From d41d64219a8783b48f74530f6a36f3ea9b84d1b0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:52:17 -0500 Subject: [PATCH 01/54] ws-game: archive/pak (Quake PACK / SiN SPAK read + write); containers/Archive: slice() lazy loader and collect() for simple archive writers (additive) --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 +++ src/Formats/archive/pak/init.luau | 135 ++++++++++++++++++++++++++++ src/Formats/containers/Archive.luau | 31 +++++++ tests/archive/pak.luau | 87 ++++++++++++++++++ tools/fixtures/pak.py | 63 +++++++++++++ 6 files changed, 329 insertions(+) create mode 100644 src/Formats/archive/pak/init.luau create mode 100644 tests/archive/pak.luau create mode 100644 tools/fixtures/pak.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..2c0a5a1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -53,6 +53,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..5000567 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -590,6 +590,18 @@ local list: { Entry } = { return require("@formats/archive/gzip") end, }, + { + name = "pak", + category = "archive", + path = "archive/pak", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, + load = function() + return require("@formats/archive/pak") + end, + }, { name = "tar", category = "archive", diff --git a/src/Formats/archive/pak/init.luau b/src/Formats/archive/pak/init.luau new file mode 100644 index 0000000..cd48140 --- /dev/null +++ b/src/Formats/archive/pak/init.luau @@ -0,0 +1,135 @@ +--!strict +-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the +-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored +-- bytes) and written from any Archive value. Written from the format description in the Quake source release +-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. +-- Not supported: Daikatana's compressed PAK entries. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Pak = { + name = "pak", + category = "archive", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake" + +-- ------------------------------------------------------------------------------------------------ constants +local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Pak.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Pak.encode(archive, opts) +end + +function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local magic = r:string(4) + local dirOfs, dirLen = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil + if not variant then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local nameLen = VARIANTS[variant].nameLen + local entrySize = nameLen + 8 + local size = r.limit - r.base + if dirOfs + dirLen > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) + end + if dirLen % entrySize ~= 0 then + return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) + end + local count = dirLen // entrySize + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + local a = Archive.new("pak", encode) + local d = r:sub(dirOfs, dirLen) + for i = 0, count - 1 do + local name = d:fixed(nameLen) + local at, n = d:u32le(), d:u32le() + if d.err then + return nil, d.err + end + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + end + a.meta.source = { format = "pak", variant = variant, entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake" + local v = VARIANTS[variant] + if not v then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = string.gsub(it.entry.name, "\\", "/") + if #name >= v.nameLen then + return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(v.magic) + w:u32le(0) + w:u32le(0) + local offsets: { number } = {} + for i, f in files do + offsets[i] = w:tell() + w:bytes(f.data) + end + local dirOfs = w:tell() + for i, f in files do + w:string(f.name) + w:fill(0, v.nameLen - #f.name) + w:u32le(offsets[i]) + w:u32le(buffer.len(f.data)) + end + w:setU32le(4, dirOfs) + w:setU32le(8, w:tell() - dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() +function Pak.new(variant: ("quake" | "sin")?): any + local a = Archive.new("pak", encode) + a.meta.source = { format = "pak", variant = variant or "quake" } + return a +end + +return Pak diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau index ef9a63d..53817b3 100644 --- a/src/Formats/containers/Archive.luau +++ b/src/Formats/containers/Archive.luau @@ -152,6 +152,37 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> return out end +-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) +function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, buf, at, n) + return out, nil + end +end + +-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read +-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) +function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out: { { entry: Types.ArchiveEntry, data: buffer } } = {} + for _, it in items do + local b: buffer = buffer.create(0) + if not it.entry.dir then + local d, err = it.read() + if not d then + return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed") + end + b = d + end + table.insert(out, { entry = it.entry, data = b }) + end + return out, nil +end + -- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension -- (".tgz" -> ".tar"), else "data" function Archive.streamName(opts: any?, exts: { string }): string diff --git a/tests/archive/pak.luau b/tests/archive/pak.luau new file mode 100644 index 0000000..6e03040 --- /dev/null +++ b/tests/archive/pak.luau @@ -0,0 +1,87 @@ +-- archive/pak tests: Quake ("PACK") and SiN ("SPAK") archives written by tools/fixtures/pak.py list the entries an +-- independent Python reader sees (names, sizes, data CRCs); our writer produces the same bytes as the Python writer +-- for the same files and round-trips; conversion from a tar; errors; the fuzz pass. Fixtures: tools/fixtures/pak.py. +local T = require("@tests/T") +local F = require("@formats") +local Pak = require("@formats/archive/pak") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/pak") + +local t = T.suite("pak") +t:eq(Pak.name, "pak", "name") +t:check(Pak.caps.decode and Pak.caps.encode, "caps") + +for _, c in Fx do + local a, err = Pak.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, #c.entries, c.name .. ": entry count") + for i, w in c.entries do + t:eq(list[i].name, w.name, c.name .. ": name " .. i) + t:eq(list[i].size, w.size, c.name .. ": size " .. w.name) + t:eq(Crc32.of((a:read(w.name))), w.crc, c.name .. ": data " .. w.name) + end + t:eq(a.meta.source.variant, c.variant, c.name .. ": variant") + if #c.data > 12 then + t:eq(F.detect(c.data), "pak", c.name .. ": F.detect") + end + -- the writer: same layout as the Python writer + local n = Pak.new(c.variant) + for _, f in c.files do + n:add(f.name, f.data) + end + local out = n:write() :: buffer + if c.layoutDefault then + t:check(buffer.tostring(out) == c.data, c.name .. ": bytes identical to the Python writer") + end + local back = Pak.decode(Bytes.reader(out)) + t:eq(#back:list(), #c.files, c.name .. ": round trip count") + -- rewriting a decoded archive keeps its variant + local again = F.save(a) :: buffer + t:eq(buffer.readstring(again, 0, 4), if c.variant == "sin" then "SPAK" else "PACK", c.name .. ": F.save keeps the variant") +end + +-- a sub-range reader, conversion from another archive, errors +do + local c = Fx[1] + local big = buffer.create(#c.data + 7) + buffer.writestring(big, 7, c.data) + local a = Pak.decode(Bytes.reader(big, 7, #c.data)) + t:check(a and Crc32.of((a:read(c.entries[2].name))) == c.entries[2].crc, "decode from a sub-range") + local tar = F.format("tar").new() + tar:add("dir/", "", { dir = true }) + tar:add("dir/x.txt", "x") + local p = F.load(F.save(tar, nil, { format = "pak" }) :: buffer) + t:check(p.format == "pak" and #p:list() == 1 and buffer.tostring(p:read("dir/x.txt")) == "x", "tar -> pak (directories dropped)") + local _, e1 = Pak.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 10)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, 8, 65) + local _, e2 = Pak.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.CORRUPT, "directory size: " .. tostring(e2)) + local long = Pak.new() + long:add(string.rep("n", 56), "x") + local _, e3 = long:write() + t:check(e3 and e3.code == Err.ARG, "a 56-byte name does not fit") + local _, e4 = Pak.encode({ kind = "image" }) + t:check(e4 and e4.code == Err.ARG, "encode a non-archive") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local a = Pak.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 40 }) + +t:done() diff --git a/tools/fixtures/pak.py b/tools/fixtures/pak.py new file mode 100644 index 0000000..dca7da8 --- /dev/null +++ b/tools/fixtures/pak.py @@ -0,0 +1,63 @@ +# Quake PAK fixtures (tools/fixtures.py): PAK files written here from the Quake source's dpackheader_t / dpackfile_t +# layout (header, file data in order, directory at the end: the layout id's qpak and most tools write), in the Quake +# ("PACK", 56-byte names) and SiN ("SPAK", 120-byte names) variants, plus one with the directory first and padding +# between files; with the expected entries read back by an independent Python reader here. +# tests/gen/pak.luau { { name, variant, data, entries = { { name, size, crc } }, files = { { name, data } } } } +import struct, zlib + +VARIANTS = {"quake": (b"PACK", 56), "sin": (b"SPAK", 120)} + + +def write(files, variant="quake", dir_first=False, pad=0): + magic, nl = VARIANTS[variant] + dirlen = len(files) * (nl + 8) + out = bytearray(magic + b"\0" * 8) + if dir_first: + dirofs = 12 + out += b"\0" * dirlen + offs = [] + for name, data in files: + out += b"\xee" * pad + offs.append(len(out)) + out += data + if not dir_first: + dirofs = len(out) + out += b"\0" * dirlen + for i, (name, data) in enumerate(files): + struct.pack_into("<%dsII" % nl, out, dirofs + i * (nl + 8), name.encode(), offs[i], len(data)) + struct.pack_into(" Date: Sat, 31 Oct 2026 13:54:43 -0500 Subject: [PATCH 02/54] ws-game: codecs/model/Rig (morph targets + weights animations, skeletons + skins, influences, joint TRS animations for the game model formats); codecs/image/Pixels.palette (RGB / BGR triples -> u32 palette; additive) --- docs/FORMATS.md | 1 + src/Formats/codecs/image/Pixels.luau | 21 +++ src/Formats/codecs/model/Rig.luau | 223 +++++++++++++++++++++++++++ tests/codecs/rig.luau | 93 +++++++++++ 4 files changed, 338 insertions(+) create mode 100644 src/Formats/codecs/model/Rig.luau create mode 100644 tests/codecs/rig.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2c0a5a1..91a5232 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -127,6 +127,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/codecs/image/Pixels.luau b/src/Formats/codecs/image/Pixels.luau index 49cd14f..d8ae224 100644 --- a/src/Formats/codecs/image/Pixels.luau +++ b/src/Formats/codecs/image/Pixels.luau @@ -13,6 +13,27 @@ local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lsh local Pixels = {} +-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], +-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, +-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). +function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer + local pal = buffer.create(1024) + local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 + for i = 0, 255 do + local v = 0xFF000000 + if i < m then + local o = base + i * 3 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + if bgr then + r, b = b, r + end + v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) + end + writeu32(pal, i * 4, v) + end + return pal +end + -- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer) diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau new file mode 100644 index 0000000..53bf256 --- /dev/null +++ b/src/Formats/codecs/model/Rig.luau @@ -0,0 +1,223 @@ +--!strict +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each +-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies +-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and +-- keyframed joint TRS tracks as animation channels. New in formats-luau. +-- +-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base +-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") +-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } +-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } +-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } +-- +-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") + +local Rig = {} + +local Scene = Types.Scene +local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 + +export type Joint = { + name: string?, + parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) + translation: { number }, + rotation: { number }, -- quaternion x, y, z, w + scale: { number }?, +} +export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) +export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time + +-- ------------------------------------------------------------------------------------------------ morph targets +-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL +-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as +-- many f32 x3 as the base; shorter ones are skipped (false is returned). +function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean + local pos = prim.attributes.POSITION + if not pos or pos.type ~= "f32" or pos.components ~= 3 then + return false + end + local nrm = prim.attributes.NORMAL + local n = pos.count * 3 + local targets: { { [string]: Types.Accessor } } = {} + local ok = true + for k, f in frames do + if buffer.len(f) < n * 4 then + ok = false + break + end + local t: { [string]: Types.Accessor } = {} + local d = buffer.create(n * 4) + local base = pos.data + for i = 0, n - 1 do + writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) + end + t.POSITION = Scene.accessor(d, "f32", 3, pos.count) + local fn = normals and normals[k] + if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then + local dn = buffer.create(n * 4) + for i = 0, n - 1 do + writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) + end + t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) + end + targets[k] = t + end + if ok then + prim.targets = targets + end + return ok +end + +-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on +-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR +-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. +function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) + for _, rg in ranges do + local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) + if last >= first then + local keys = last - first + 1 + local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 + local times = buffer.create(keys * 4) + local weights = buffer.create(keys * targets * 4) + for k = 0, keys - 1 do + writef32(times, k * 4, k / fps) + writef32(weights, (k * targets + first - 1 + k) * 4, 1) + end + table.insert(scene.animations, { + name = rg.name, + channels = { + { + node = node, + path = "weights" :: any, + input = Scene.accessor(times, "f32", 1, keys), + output = Scene.accessor(weights, "f32", 1, keys * targets), + interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, + }, + }, + }) + end + end +end + +-- ------------------------------------------------------------------------------------------------ skeletons +local function trs(j: Joint): { number } + return Mat4.compose(j.translation, j.rotation, j.scale) +end + +-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): one node per joint (TRS relative to its +-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse +-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's +-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. +function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number) + local n = #joints + local world: { { number } } = {} + local nodes: { number } = {} + for i, j in joints do + local p = if j.parent >= 1 and j.parent < i then j.parent else 0 + local m = trs(j) + local lt, lr, ls = j.translation, j.rotation, j.scale + if space == "world" then + world[i] = m + if p > 0 then + local inv = Mat4.inverse(world[p]) + if inv then + local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) + lt, lr, ls = t, r, s + end + end + else + world[i] = if p > 0 then Mat4.mul(world[p], m) else m + end + local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } + table.insert(scene.nodes, node) + local idx = #scene.nodes + nodes[i] = idx + if p > 0 then + table.insert(scene.nodes[nodes[p]].children, idx) + elseif root and scene.nodes[root] then + table.insert(scene.nodes[root].children, idx) + else + table.insert(scene.roots, idx) + end + end + local ibm = buffer.create(n * 64) + for i = 1, n do + local inv = Mat4.inverseFull(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) + return nodes, #scene.skins +end + +-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with +-- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1. +function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) + local n = #lists + local jb, wb = buffer.create(n * 8), buffer.create(n * 16) + for v, l in lists do + local pairs_: { { number } } = {} + for k = 1, #l - 1, 2 do + if l[k + 1] > 0 then + table.insert(pairs_, { l[k], l[k + 1] }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #pairs_) do + sum += pairs_[k][2] + end + for k = 1, math.min(4, #pairs_) do + writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) + writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) + end + end + return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) +end + +-- ------------------------------------------------------------------------------------------------ animations +local function floats(t: { number }, count: number, comps: number): Types.Accessor? + if #t < count * comps then + return nil + end + local b = buffer.create(count * comps * 4) + for i = 1, count * comps do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, count) +end + +-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into +-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks +-- with too few keys are skipped. Default interpolation "LINEAR". +function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number + local count = #times + local input = floats(times, count, 1) + local channels: { Types.Channel } = {} + local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" + if input then + for j, tr in tracks do + local node = nodes[j] + if node then + for _, path in { "translation", "rotation", "scale" } do + local keys = (tr :: any)[path] + local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) + if acc then + table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) + end + end + end + end + end + table.insert(scene.animations, { name = name, channels = channels }) + return #scene.animations +end + +return Rig diff --git a/tests/codecs/rig.luau b/tests/codecs/rig.luau new file mode 100644 index 0000000..6accbd5 --- /dev/null +++ b/tests/codecs/rig.luau @@ -0,0 +1,93 @@ +-- codecs/model/Rig tests: morph targets and weights animations from frames, skeletons in local and world space +-- (node TRS, inverse bind matrices against Mat4), influences (top four, normalised), joint TRS animations; and +-- Pixels.palette. +local T = require("@tests/T") +local Rig = require("@formats/codecs/model/Rig") +local Mat4 = require("@formats/codecs/model/Mat4") +local Pixels = require("@formats/codecs/image/Pixels") +local Types = require("@formats/Types") + +local t = T.suite("codecs/rig") +local Scene = Types.Scene + +local function f32s(list: { number }): buffer + local b = buffer.create(#list * 4) + for i, v in list do + buffer.writef32(b, (i - 1) * 4, v) + end + return b +end +local function near(a: number, b: number): boolean + return math.abs(a - b) < 1e-5 +end + +-- morph +do + local base = { 0, 0, 0, 1, 0, 0 } + local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(f32s(base), "f32", 3, 2) }, mode = "points" } + local frames = { f32s(base), f32s({ 0, 1, 0, 1, 2, 0 }), f32s({ 0, 0, 3, 1, 0, 3 }) } + t:check(Rig.morph(prim, frames), "morph") + local tg = prim.targets :: any + t:eq(#tg, 3, "one target per frame") + t:eq(buffer.readf32(tg[2].POSITION.data, 4), 1, "delta y") + t:eq(buffer.readf32(tg[3].POSITION.data, 20), 3, "delta z") + t:check(not Rig.morph(prim, { buffer.create(4) }), "short frame refused") + local s = Scene.new() + s.nodes[1] = { children = {}, mesh = 1 } + Rig.morphAnimation(s, 1, 3, { { name = "a", first = 2, last = 3, fps = 5 }, { name = "none", first = 9, last = 12 } }) + t:eq(#s.animations, 1, "out-of-range range skipped") + local ch = s.animations[1].channels[1] + t:eq(ch.path, "weights", "weights channel") + t:eq(ch.input.count, 2, "two keys") + t:check(near(buffer.readf32(ch.input.data, 4), 0.2), "fps") + t:eq(buffer.readf32(ch.output.data, 1 * 4), 1, "key 1 -> target 2") + t:eq(buffer.readf32(ch.output.data, (3 + 2) * 4), 1, "key 2 -> target 3") +end + +-- skeleton +do + local q = Mat4.axisAngle(0, 0, 1, 90) + local joints = { + { name = "root", parent = 0, translation = { 1, 0, 0 }, rotation = q }, + { name = "child", parent = 1, translation = { 0, 2, 0 }, rotation = { 0, 0, 0, 1 } }, + } + local s = Scene.new() + local nodes, skin = Rig.skeleton(s, joints, "local") + t:eq(#nodes, 2, "two joint nodes") + t:eq(s.roots[1], nodes[1], "root") + t:eq(s.nodes[nodes[1]].children[1], nodes[2], "parenting") + local ibm = s.skins[skin].inverseBindMatrices :: Types.Accessor + -- child world = T(1,0,0) R90 T(0,2,0): its origin is at (-1, 0, 0); the inverse maps it back to 0 + local inv = {} + for k = 1, 16 do + inv[k] = buffer.readf32(ibm.data, (16 + k - 1) * 4) + end + local x, y, z = Mat4.point(inv, -1, 0, 0) + t:check(near(x, 0) and near(y, 0) and near(z, 0), "inverse bind matrix") + -- the same joints given in world space give the same local TRS + local w = Scene.new() + local wn = Rig.skeleton(w, { + joints[1], + { name = "child", parent = 1, translation = { -1, 0, 0 }, rotation = q }, + }, "world") + local c = w.nodes[wn[2]] + t:check(near(c.translation[1], 0) and near(c.translation[2], 2) and near(c.rotation[4], 1), "world -> local") + local j, wt = Rig.influences({ { 0, 1 }, { 1, 0.2, 2, 0.6, 3, 0.1, 4, 0.05, 5, 0.05 } }) + t:eq(buffer.readu16(j.data, 8), 2, "largest weight first") + t:check(near(buffer.readf32(wt.data, 16) + buffer.readf32(wt.data, 20) + buffer.readf32(wt.data, 24) + buffer.readf32(wt.data, 28), 1), "normalised") + t:eq(buffer.readf32(wt.data, 0), 1, "single influence") + local ai = Rig.animation(s, "wave", nodes, { 0, 0.5 }, { [2] = { rotation = { 0, 0, 0, 1, 0, 0, 1, 0 }, translation = { 0 } } }) + t:eq(#s.animations[ai].channels, 1, "short track skipped, rotation kept") + t:eq(s.animations[ai].channels[1].node, nodes[2], "channel node") +end + +-- palette +do + local pal = Pixels.palette(buffer.fromstring("\1\2\3\4\5\6"), 0, 2) + t:eq(buffer.readu32(pal, 4), 0xFF060504, "rgb triples") + t:eq(buffer.readu32(pal, 8), 0xFF000000, "missing entries black") + t:eq(buffer.readu32(Pixels.palette(buffer.fromstring("\1\2\3"), 0, 1, true), 0), 0xFF010203, "bgr") + t:eq(buffer.readu32(Pixels.palette(buffer.create(3), -5, 1), 0), 0xFF000000, "bad base") +end + +t:done() From 840f0b12bb3040bd53fa8d2cc3808d47058a6ad6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:56:27 -0500 Subject: [PATCH 03/54] ws-video2: codecs/video/Dsp (jrevdct IDCT bit-exact with ffmpeg -idct int, shared MC); Mpeg1 uses it MPEG-1 decode is now bit-exact with ffmpeg -idct int (was ~0.6 MAE). ~5% slower on luau (1695 vs 1790 fps at 320x240). The IJG jrevdct.c is IJG-licensed (ffmpeg LICENSE.md), credited in licenses/NOTICE.md. --- licenses/NOTICE.md | 1 + src/Formats/codecs/video/Dsp.luau | 693 ++++++++++++++++++++ src/Formats/codecs/video/Mpeg1/Decoder.luau | 204 +----- 3 files changed, 699 insertions(+), 199 deletions(-) create mode 100644 src/Formats/codecs/video/Dsp.luau diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..76a1a69 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -37,6 +37,7 @@ | `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | +| `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau new file mode 100644 index 0000000..f449f53 --- /dev/null +++ b/src/Formats/codecs/video/Dsp.luau @@ -0,0 +1,693 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. +-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added +-- into 8-bit planes, constant (DC-only) blocks, -- half-pel motion compensation four samples at a time. Native, never throws (the caller keeps offsets in range). +-- +-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg +-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then +-- columns, with every sparse-input special case of the original kept, because several of them use merged constants +-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that +-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order +-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for +-- coefficients in the MPEG range), and the put / add clamping fused into the last pass. +-- +-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it +-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) +-- Dsp.mc(src, dst, stride, sOff, dOff, size, hx, hy, avg) -- half-pel prediction, size 8 / 16 (multiple of 4) +local Dsp = {} + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local bxor = bit32.bxor +local rshift = bit32.rshift + +-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range +-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, plus a prediction of up to 255 +local COFF = 40000 +local CLAMP = buffer.create(2 * COFF + 256) +for i = 0, 2 * COFF + 255 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end +Dsp.CLAMP = CLAMP +Dsp.COFF = COFF + +-- ------------------------------------------------------------------------------------------------ IDCT +function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) + local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 + local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 + local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0 + -- pass 1: rows, scaled up by 2^PASS1_BITS + for r = 0, 224, 32 do + local d0 = readi32(blk, r) + local d1 = readi32(blk, r + 4) + local d2 = readi32(blk, r + 8) + local d3 = readi32(blk, r + 12) + local d4 = readi32(blk, r + 16) + local d5 = readi32(blk, r + 20) + local d6 = readi32(blk, r + 24) + local d7 = readi32(blk, r + 28) + if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then + if d0 ~= 0 then + local v = d0 * 4 + writei32(blk, r, v) + writei32(blk, r + 4, v) + writei32(blk, r + 8, v) + writei32(blk, r + 12, v) + writei32(blk, r + 16, v) + writei32(blk, r + 20, v) + writei32(blk, r + 24, v) + writei32(blk, r + 28, v) + end + else + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z4 = d5 + d1 + z5 = (d7 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, r, (tmp10 + tmp3 + 1024) // 2048) + writei32(blk, r + 28, (tmp10 - tmp3 + 1024) // 2048) + writei32(blk, r + 4, (tmp11 + tmp2 + 1024) // 2048) + writei32(blk, r + 24, (tmp11 - tmp2 + 1024) // 2048) + writei32(blk, r + 8, (tmp12 + tmp1 + 1024) // 2048) + writei32(blk, r + 20, (tmp12 - tmp1 + 1024) // 2048) + writei32(blk, r + 12, (tmp13 + tmp0 + 1024) // 2048) + writei32(blk, r + 16, (tmp13 - tmp0 + 1024) // 2048) + end + end + -- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3) + for c = 0, 28, 4 do + local d0 = readi32(blk, c) + local d1 = readi32(blk, c + 32) + local d2 = readi32(blk, c + 64) + local d3 = readi32(blk, c + 96) + local d4 = readi32(blk, c + 128) + local d5 = readi32(blk, c + 160) + local d6 = readi32(blk, c + 192) + local d7 = readi32(blk, c + 224) + if d6 ~= 0 then + if d2 ~= 0 then + z1 = (d2 + d6) * 4433 + tmp2 = z1 + (-d6) * 15137 + tmp3 = z1 + (d2) * 6270 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp2 = (-d6) * 10703 + tmp3 = (d6) * 4433 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + end + else + if d2 ~= 0 then + tmp2 = (d2) * 4433 + tmp3 = (d2) * 10703 + tmp0 = (d0 + d4) * 8192 + tmp1 = (d0 - d4) * 8192 + tmp10 = tmp0 + tmp3 + tmp13 = tmp0 - tmp3 + tmp11 = tmp1 + tmp2 + tmp12 = tmp1 - tmp2 + else + tmp13 = (d0 + d4) * 8192 + tmp10 = tmp13 + tmp12 = (d0 - d4) * 8192 + tmp11 = tmp12 + end + end + if d7 ~= 0 then + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z2 = d5 + d3 + z3 = d7 + d3 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z3 = d7 + d3 + z5 = (z3 + d5) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + z1 = (-d7) * 7373 + z2 = (-z2) * 20995 + z3 = (-z3) * 16069 + z4 = (-d5) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 = z1 + z4 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + z4 = d5 + d1 + z5 = (z3 + z4) * 9633 + tmp0 = (d7) * 2446 + tmp1 = (d5) * 16819 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d5) * 20995 + z3 = (-d7) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 += z2 + z4 + tmp2 = z2 + z3 + tmp3 += z1 + z4 + else + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + z3 = (-d7) * 16069 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (-d5) * 3196 + z5 = (d5 + d7) * 9633 + z3 += z5 + z4 += z5 + tmp0 += z3 + tmp1 += z4 + tmp2 = z2 + z3 + tmp3 = z1 + z4 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z1 = d7 + d1 + z3 = d7 + d3 + z5 = (z3 + d1) * 9633 + tmp0 = (d7) * 2446 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-z1) * 7373 + z2 = (-d3) * 20995 + z3 = (-z3) * 16069 + z4 = (-d1) * 3196 + z3 += z5 + z4 += z5 + tmp0 += z1 + z3 + tmp1 = z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z3 = d7 + d3 + tmp0 = (-d7) * 4926 + z1 = (-d7) * 7373 + tmp2 = (d3) * 4176 + z2 = (-d3) * 20995 + z5 = (z3) * 9633 + z3 = (-z3) * 6436 + tmp0 += z3 + tmp1 = z2 + z5 + tmp2 += z3 + tmp3 = z1 + z5 + end + else + if d1 ~= 0 then + z1 = d7 + d1 + z5 = (z1) * 9633 + z1 = (z1) * 2260 + z3 = (-d7) * 16069 + tmp0 = (-d7) * 13623 + z4 = (-d1) * 3196 + tmp3 = (d1) * 9102 + tmp0 += z1 + tmp1 = z4 + z5 + tmp2 = z3 + z5 + tmp3 += z1 + else + tmp0 = (-d7) * 11363 + tmp1 = (d7) * 9633 + tmp2 = (-d7) * 6436 + tmp3 = (d7) * 2260 + end + end + end + else + if d5 ~= 0 then + if d3 ~= 0 then + if d1 ~= 0 then + z2 = d5 + d3 + z4 = d5 + d1 + z5 = (d3 + z4) * 9633 + tmp1 = (d5) * 16819 + tmp2 = (d3) * 25172 + tmp3 = (d1) * 12299 + z1 = (-d1) * 7373 + z2 = (-z2) * 20995 + z3 = (-d3) * 16069 + z4 = (-z4) * 3196 + z3 += z5 + z4 += z5 + tmp0 = z1 + z3 + tmp1 += z2 + z4 + tmp2 += z2 + z3 + tmp3 += z1 + z4 + else + z2 = d5 + d3 + z5 = (z2) * 9633 + tmp1 = (d5) * 13623 + z4 = (-d5) * 3196 + z2 = (-z2) * 11363 + tmp2 = (d3) * 9102 + z3 = (-d3) * 16069 + tmp0 = z3 + z5 + tmp1 += z2 + tmp2 += z2 + tmp3 = z4 + z5 + end + else + if d1 ~= 0 then + z4 = d5 + d1 + z5 = (z4) * 9633 + z1 = (-d1) * 7373 + tmp3 = (d1) * 4926 + tmp1 = (-d5) * 4176 + z2 = (-d5) * 20995 + z4 = (z4) * 6436 + tmp0 = z1 + z5 + tmp1 += z4 + tmp2 = z2 + z5 + tmp3 += z4 + else + tmp0 = (d5) * 9633 + tmp1 = (d5) * 2260 + tmp2 = (-d5) * 11363 + tmp3 = (d5) * 6436 + end + end + else + if d3 ~= 0 then + if d1 ~= 0 then + z5 = d1 + d3 + tmp3 = (d1) * 1730 + tmp2 = (-d3) * 11893 + z1 = (d1) * 8697 + z2 = (-d3) * 17799 + z4 = (z5) * 6436 + z5 = (z5) * 9633 + tmp0 = z1 - z4 + tmp1 = z2 + z4 + tmp2 += z5 + tmp3 += z5 + else + tmp0 = (-d3) * 6436 + tmp1 = (-d3) * 11363 + tmp2 = (-d3) * 2260 + tmp3 = (d3) * 9633 + end + else + if d1 ~= 0 then + tmp0 = (d1) * 2260 + tmp1 = (d1) * 6436 + tmp2 = (d1) * 9633 + tmp3 = (d1) * 11363 + else + tmp3 = 0 + tmp0 = tmp3 + tmp1 = tmp3 + tmp2 = tmp3 + end + end + end + end + writei32(blk, c, (tmp10 + tmp3 + 131072) // 262144) + writei32(blk, c + 224, (tmp10 - tmp3 + 131072) // 262144) + writei32(blk, c + 32, (tmp11 + tmp2 + 131072) // 262144) + writei32(blk, c + 192, (tmp11 - tmp2 + 131072) // 262144) + writei32(blk, c + 64, (tmp12 + tmp1 + 131072) // 262144) + writei32(blk, c + 160, (tmp12 - tmp1 + 131072) // 262144) + writei32(blk, c + 96, (tmp13 + tmp0 + 131072) // 262144) + writei32(blk, c + 128, (tmp13 - tmp0 + 131072) // 262144) + end + -- put / add, clamped + for r = 0, 224, 32 do + local p0 = readi32(blk, r) + COFF + local p1 = readi32(blk, r + 4) + COFF + local p2 = readi32(blk, r + 8) + COFF + local p3 = readi32(blk, r + 12) + COFF + local p4 = readi32(blk, r + 16) + COFF + local p5 = readi32(blk, r + 20) + COFF + local p6 = readi32(blk, r + 24) + COFF + local p7 = readi32(blk, r + 28) + COFF + if add then + p0 += readu8(dst, off) + p1 += readu8(dst, off + 1) + p2 += readu8(dst, off + 2) + p3 += readu8(dst, off + 3) + p4 += readu8(dst, off + 4) + p5 += readu8(dst, off + 5) + p6 += readu8(dst, off + 6) + p7 += readu8(dst, off + 7) + end + writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216) + writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216) + off += stride + end +end + +-- ------------------------------------------------------------------------------------------------ blocks +-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT +-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere) +function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) + if not add then + local c = readu8(CLAMP, v + COFF) * 0x01010101 + for _ = 1, 8 do + writeu32(dst, off, c) + writeu32(dst, off + 4, c) + off += stride + end + else + for _ = 1, 8 do + for i = off, off + 7 do + writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) + end + off += stride + end + end +end + +-- ------------------------------------------------------------------------------------------------ motion +-- Motion-compensated prediction of a size x size block (size 8 or 16; 4 for H.263 chroma is fine too: any multiple +-- of 4) from src at sOff to dst at dOff, both with stride (twice the plane width for field prediction), half-pel +-- flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what dst holds (the second +-- prediction of a bidirectional block, rounding up). Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) +-- >> 1; the 4-tap average splits each byte into its low 2 bits and high 6 bits so no lane overflows. +function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) + for _ = 1, size do + for i = 0, size - 4, 4 do + local p + if hx == 0 then + if hy == 0 then + p = readu32(src, sOff + i) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + end + elseif hy == 0 then + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) + else + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) + local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) + local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 + local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = h + band(rshift(l, 2), 0x0F0F0F0F) + end + if avg then + local q = readu32(dst, dOff + i) + p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) + end + writeu32(dst, dOff + i, p) + end + sOff += stride + dOff += stride + end +end + +return Dsp diff --git a/src/Formats/codecs/video/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau index 5fcdb1f..0431576 100644 --- a/src/Formats/codecs/video/Mpeg1/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg1/Decoder.luau @@ -25,6 +25,7 @@ -- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. local V = require("@formats/codecs/video/Mpeg1/Vlc") local T = require("@formats/codecs/video/Mpeg1/Tables") +local Dsp = require("@formats/codecs/video/Dsp") local readu8 = buffer.readu8 local writeu8 = buffer.writeu8 @@ -82,205 +83,10 @@ local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } --- Integer IDCT (LL&M factorisation as in the IJG "islow" IDCT: CONST_BITS 13, PASS1_BITS 2) of the 64 i32 --- coefficients in blk (natural order), written to dst (put) or added to it (add), clamped to 0..255. -local function idct(blk: buffer, ws: buffer, dst: buffer, off: number, stride: number, add: boolean) - -- pass 1: columns, into ws scaled by 4 - for c = 0, 28, 4 do - local d0 = readi32(blk, c) - local d1 = readi32(blk, c + 32) - local d2 = readi32(blk, c + 64) - local d3 = readi32(blk, c + 96) - local d4 = readi32(blk, c + 128) - local d5 = readi32(blk, c + 160) - local d6 = readi32(blk, c + 192) - local d7 = readi32(blk, c + 224) - if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then - local dc = d0 * 4 - writei32(ws, c, dc) - writei32(ws, c + 32, dc) - writei32(ws, c + 64, dc) - writei32(ws, c + 96, dc) - writei32(ws, c + 128, dc) - writei32(ws, c + 160, dc) - writei32(ws, c + 192, dc) - writei32(ws, c + 224, dc) - else - -- even part - local z1 = (d2 + d6) * 4433 - local t2 = z1 - d6 * 15137 - local t3 = z1 + d2 * 6270 - local t0 = (d0 + d4) * 8192 - local t1 = (d0 - d4) * 8192 - local t10 = t0 + t3 - local t13 = t0 - t3 - local t11 = t1 + t2 - local t12 = t1 - t2 - -- odd part - local o0, o1, o2, o3 = d7, d5, d3, d1 - local y1 = o0 + o3 - local y2 = o1 + o2 - local y3 = o0 + o2 - local y4 = o1 + o3 - local z5 = (y3 + y4) * 9633 - o0 *= 2446 - o1 *= 16819 - o2 *= 25172 - o3 *= 12299 - y1 *= -7373 - y2 *= -20995 - y3 = y3 * -16069 + z5 - y4 = y4 * -3196 + z5 - o0 += y1 + y3 - o1 += y2 + y4 - o2 += y2 + y3 - o3 += y1 + y4 - writei32(ws, c, (t10 + o3 + 1024) // 2048) - writei32(ws, c + 224, (t10 - o3 + 1024) // 2048) - writei32(ws, c + 32, (t11 + o2 + 1024) // 2048) - writei32(ws, c + 192, (t11 - o2 + 1024) // 2048) - writei32(ws, c + 64, (t12 + o1 + 1024) // 2048) - writei32(ws, c + 160, (t12 - o1 + 1024) // 2048) - writei32(ws, c + 96, (t13 + o0 + 1024) // 2048) - writei32(ws, c + 128, (t13 - o0 + 1024) // 2048) - end - end - -- pass 2: rows, descaled by 2^18 (13 + 2 + 3), into the picture - for r = 0, 224, 32 do - local d0 = readi32(ws, r) - local d1 = readi32(ws, r + 4) - local d2 = readi32(ws, r + 8) - local d3 = readi32(ws, r + 12) - local d4 = readi32(ws, r + 16) - local d5 = readi32(ws, r + 20) - local d6 = readi32(ws, r + 24) - local d7 = readi32(ws, r + 28) - local p0, p1, p2, p3, p4, p5, p6, p7 - if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then - local v = (d0 + 16) // 32 - p0, p1, p2, p3, p4, p5, p6, p7 = v, v, v, v, v, v, v, v - else - local z1 = (d2 + d6) * 4433 - local t2 = z1 - d6 * 15137 - local t3 = z1 + d2 * 6270 - local t0 = (d0 + d4) * 8192 - local t1 = (d0 - d4) * 8192 - local t10 = t0 + t3 + 131072 - local t13 = t0 - t3 + 131072 - local t11 = t1 + t2 + 131072 - local t12 = t1 - t2 + 131072 - local o0, o1, o2, o3 = d7, d5, d3, d1 - local y1 = o0 + o3 - local y2 = o1 + o2 - local y3 = o0 + o2 - local y4 = o1 + o3 - local z5 = (y3 + y4) * 9633 - o0 *= 2446 - o1 *= 16819 - o2 *= 25172 - o3 *= 12299 - y1 *= -7373 - y2 *= -20995 - y3 = y3 * -16069 + z5 - y4 = y4 * -3196 + z5 - o0 += y1 + y3 - o1 += y2 + y4 - o2 += y2 + y3 - o3 += y1 + y4 - p0 = (t10 + o3) // 262144 - p7 = (t10 - o3) // 262144 - p1 = (t11 + o2) // 262144 - p6 = (t11 - o2) // 262144 - p2 = (t12 + o1) // 262144 - p5 = (t12 - o1) // 262144 - p3 = (t13 + o0) // 262144 - p4 = (t13 - o0) // 262144 - end - if add then - p0 += readu8(dst, off) - p1 += readu8(dst, off + 1) - p2 += readu8(dst, off + 2) - p3 += readu8(dst, off + 3) - p4 += readu8(dst, off + 4) - p5 += readu8(dst, off + 5) - p6 += readu8(dst, off + 6) - p7 += readu8(dst, off + 7) - end - writeu32( - dst, - off, - readu8(CLAMP, p0 + COFF) - + readu8(CLAMP, p1 + COFF) * 256 - + readu8(CLAMP, p2 + COFF) * 65536 - + readu8(CLAMP, p3 + COFF) * 16777216 - ) - writeu32( - dst, - off + 4, - readu8(CLAMP, p4 + COFF) - + readu8(CLAMP, p5 + COFF) * 256 - + readu8(CLAMP, p6 + COFF) * 65536 - + readu8(CLAMP, p7 + COFF) * 16777216 - ) - off += stride - end -end +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc D.idct = idct - --- a constant 8x8 block (DC only): put or add v -local function fillBlock(dst: buffer, off: number, stride: number, v: number, add: boolean) - if not add then - local c = readu8(CLAMP, v + COFF) * 0x01010101 - for _ = 1, 8 do - writeu32(dst, off, c) - writeu32(dst, off + 4, c) - off += stride - end - else - for _ = 1, 8 do - for i = off, off + 7 do - writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF)) - end - off += stride - end - end -end - --- Motion-compensated prediction of a size x size block (16 luma, 8 chroma) from src at sOff to dst at dOff with --- half-pel flags hx / hy; avg averages into what dst holds (the second prediction of a B macroblock). Four bytes at --- a time: avg(a, b) rounding up = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its --- low 2 bits and high 6 bits so no lane overflows. -local function mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) - for _ = 1, size do - for i = 0, size - 4, 4 do - local p - if hx == 0 then - if hy == 0 then - p = readu32(src, sOff + i) - else - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) - p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) - end - elseif hy == 0 then - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) - p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) - else - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) - local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) - local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 - local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) - p = h + band(rshift(l, 2), 0x0F0F0F0F) - end - if avg then - local q = readu32(dst, dOff + i) - p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1) - end - writeu32(dst, dOff + i, p) - end - sOff += stride - dOff += stride - end -end D.mc = mc -- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path @@ -775,7 +581,7 @@ function D.new(maxPixels: number?): Core fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) writei32(blk, 0, 0) else - idct(blk, ws, dst, off, stride, not intra) + idct(blk, dst, off, stride, not intra) buffer.fill(blk, 0, 0, 256) end return true From cf737746d4d50a58b484b5aec9cfdecede9b443b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:56:33 -0500 Subject: [PATCH 04/54] ws-video2: Dsp header --- docs/FORMATS.md | 1 + src/Formats/codecs/video/Dsp.luau | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..f36b9a6 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -132,6 +132,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** + - codecs/video/Dsp: block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau index f449f53..6bdc215 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -3,7 +3,8 @@ --!optimize 2 -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. -- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added --- into 8-bit planes, constant (DC-only) blocks, -- half-pel motion compensation four samples at a time. Native, never throws (the caller keeps offsets in range). +-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never +-- throws (the caller keeps offsets in range). -- -- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg -- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then From 07dc6f7e84e0b9e095a2c7829e10fb4a73e13d34 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:00:57 -0500 Subject: [PATCH 05/54] ws-3d3-d: model/b3d (Blitz3D read: brushes, textures, node tree, skins, keyframe animation; LH -> RH) --- docs/FORMATS.md | 1 + docs/guide/scene.md | 16 +- src/Formats/Registry.luau | 12 + src/Formats/model/b3d/Read.luau | 576 ++++++++++++++++++++++++++++++++ src/Formats/model/b3d/init.luau | 68 ++++ tests/model/b3d.luau | 230 +++++++++++++ tools/fixtures/b3d.py | 204 +++++++++++ 7 files changed, 1106 insertions(+), 1 deletion(-) create mode 100644 src/Formats/model/b3d/Read.luau create mode 100644 src/Formats/model/b3d/init.luau create mode 100644 tests/model/b3d.luau create mode 100644 tools/fixtures/b3d.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..4049798 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -35,6 +35,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | +| model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..f8fb42d 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, B3D, LDraw) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -378,6 +378,19 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves assert(F.load(vox).voxels[1].size[1] == 4) ``` +## Blitz3D (B3D) + +`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; +each `MESH` becomes one mesh whose primitives (one per `TRIS` chunk) share the vertex accessors; brushes become +materials (colour, alpha, shininess, the first texture as `baseColorTexture` with its position / scale / rotation as +`transform`, the full brush in `extras.b3d`); `BONE` weights become a skin (the 4 strongest weights per vertex) and +`KEYS` + `ANIM` one animation sampled at `frame / fps`. Texture files come through `files` / `resolve` like any other +model's (by the stored path, then by its base name: B3D files often store absolute Windows paths). + +Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding and rotations to match), so the scene +is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records +the origin, `meta.source.fps` / `frames` the `ANIM` chunk. + ## Formats | Format | Read | Write | Notes | @@ -392,6 +405,7 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..7d0229a 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -374,6 +374,18 @@ local list: { Entry } = { return require("@formats/model/3mf") end, }, + { + name = "b3d", + category = "model", + path = "model/b3d", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, + load = function() + return require("@formats/model/b3d") + end, + }, { name = "dae", category = "model", diff --git a/src/Formats/model/b3d/Read.luau b/src/Formats/model/b3d/Read.luau new file mode 100644 index 0000000..1bfda92 --- /dev/null +++ b/src/Formats/model/b3d/Read.luau @@ -0,0 +1,576 @@ +--!strict +-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are +-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes +-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") +local Mat4 = require("@formats/codecs/model/Mat4") + +local Read = {} + +export type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, + maxDepth: number?, +} + +local LAYOUT: Chunks.Layout = { maxChunks = 1000000 } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } } +type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number } +type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } } +type Bone = { node: number, target: MeshRec?, list: { number } } +type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } } + +-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated +-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored +local function vec(r: Bytes.Reader): { number } + local x, y, z = r:f32le(), r:f32le(), r:f32le() + return { x, y, -z } +end +local function quat(r: Bytes.Reader): { number } + local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le() + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 or l ~= l then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, -z / l, w / l } +end + +local function fetcher(opts: Options?): (string) -> buffer? + local files = opts and opts.files + local resolve = opts and opts.resolve + return function(uri: string): buffer? + local v: any = if type(files) == "table" then files[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- scene(r, opts) -> Scene | nil, message, kind +function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?) + local buf = src.buf + local maxVertices = opts and opts.maxVertices or 2 ^ 24 + local maxDepth = opts and opts.maxDepth or 256 + local fetch = fetcher(opts) + local top = Chunks.walk(buf, src.base, src.limit, LAYOUT) + local head = top[1] + if not head or head.id ~= "BB3D" then + return nil, "not a BB3D file", nil + end + if head.truncated then + return nil, "truncated", "truncated" + end + local hr = Bytes.reader(buf, head.offset, head.size) + local version = hr:i32le() + if hr.err then + return nil, "truncated", "truncated" + end + + local scene = Types.Scene.new() + local texs: { TexInfo } = {} + local brushes: { Brush } = {} + local materialOf: { [number]: number } = {} -- brush index (0-based) -> material + local meshes: { MeshRec } = {} + local bones: { Bone } = {} + local nodeKeys: { [number]: Keys } = {} + local anim: { frames: number, fps: number, flags: number }? = nil + local lastMesh: MeshRec? = nil + local totalVertices = 0 + local failure: string?, failKind: string? = nil, nil + + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + local function body(c: Chunks.Chunk): Bytes.Reader + if c.truncated then + fail("truncated " .. c.id .. " chunk", "truncated") + end + return Bytes.reader(buf, c.offset, c.avail) + end + + local function readTexs(r: Bytes.Reader) + while r.pos < r.limit and not r.err do + local file = r:cstring() + local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 } + if r.err then + return fail("truncated TEXS entry", "truncated") + end + local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] } + local data = fetch(file) + if not data then + local base = string.match(file, "([^/\\]+)$") + if base and base ~= file then + data = fetch(base) + end + end + tex.data = data + if bit32.band(t.flags, 48) ~= 0 then + tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" } + end + tex.extras = { b3d = { flags = t.flags, blend = t.blend } } + table.insert(scene.textures, tex) + t.index = #scene.textures + table.insert(texs, t) + end + end + + local function readBrus(r: Bytes.Reader) + local n = r:i32le() + if r.err or n < 0 or n > 8 then + return fail("bad BRUS texture count") + end + while r.pos < r.limit and not r.err do + local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} } + for i = 1, n do + b.textures[i] = r:i32le() + end + if r.err then + return fail("truncated BRUS entry", "truncated") + end + table.insert(brushes, b) + end + end + + -- the material of brush id (0-based) | nil for -1 / out of range + local function material(id: number): number? + if id < 0 or id >= #brushes then + return nil + end + local have = materialOf[id] + if have then + return have + end + local b = brushes[id + 1] + local m = Types.Scene.material(b.name ~= "" and b.name or nil) + local c = b.color + local function clamp01(v: number): number + return if v ~= v then 1 else math.clamp(v, 0, 1) + end + m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) } + m.metallic = 0 + m.roughness = 1 - 0.8 * clamp01(b.shininess) + m.doubleSided = bit32.band(b.fx, 16) ~= 0 + if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then + m.alphaMode = "blend" + end + if bit32.band(b.fx, 1) ~= 0 then + m.extensions = { KHR_materials_unlit = {} } + end + local extraTex: { number } = {} + for i, tid in b.textures do + local t = texs[tid + 1] + if tid >= 0 and t then + if not m.baseColorTexture then + local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil } + local o, s, rot = t.offset, t.scale, t.rotation + if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot } + end + m.baseColorTexture = ref + if bit32.band(t.flags, 4) ~= 0 then + m.alphaMode = "mask" + elseif bit32.band(t.flags, 2) ~= 0 then + m.alphaMode = "blend" + end + else + extraTex[i] = t.index + end + end + end + m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } } + table.insert(scene.materials, m) + materialOf[id] = #scene.materials + return #scene.materials + end + + local function readMesh(r: Bytes.Reader, nodeIndex: number): number? + local master = r:i32le() + if r.err then + fail("truncated MESH", "truncated") + return nil + end + local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT) + local attrs: { [string]: Types.Accessor }? = nil + local count = 0 + local mesh: Types.Mesh = { primitives = {} } + local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} } + for _, c in list do + local cr = body(c) + if c.id == "VRTS" and not attrs then + local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le() + if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then + fail("bad VRTS header") + return nil + end + local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0 + local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4 + local n = (cr.limit - cr.pos) // stride + totalVertices += n + if totalVertices > maxVertices then + fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit") + return nil + end + local pos = buffer.create(n * 12) + local nrm = if hasN then buffer.create(n * 12) else nil + local col = if hasC then buffer.create(n * 16) else nil + local uvs: { buffer } = {} + for s = 1, sets do + uvs[s] = buffer.create(n * 8) + end + local readf32, writef32 = buffer.readf32, buffer.writef32 + local p = cr.pos + for i = 0, n - 1 do + writef32(pos, i * 12, readf32(buf, p)) + writef32(pos, i * 12 + 4, readf32(buf, p + 4)) + writef32(pos, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + if nrm then + writef32(nrm, i * 12, readf32(buf, p)) + writef32(nrm, i * 12 + 4, readf32(buf, p + 4)) + writef32(nrm, i * 12 + 8, -readf32(buf, p + 8)) + p += 12 + end + if col then + for k = 0, 3 do + writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4)) + end + p += 16 + end + for s = 1, sets do + if size >= 1 then + writef32(uvs[s], i * 8, readf32(buf, p)) + end + if size >= 2 then + writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4)) + end + p += size * 4 + end + end + local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) } + if nrm then + a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n) + end + if col then + a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n) + end + if size > 0 then + for s = 1, sets do + a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n) + end + end + attrs, count = a, n + mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } } + elseif c.id == "TRIS" then + local brush = cr:i32le() + if cr.err then + fail("truncated TRIS", "truncated") + return nil + end + if not attrs then + fail("TRIS before VRTS") + return nil + end + local nt = (cr.limit - cr.pos) // 12 + local idx = buffer.create(nt * 12) + local readu32, writeu32 = buffer.readu32, buffer.writeu32 + local p = cr.pos + for i = 0, nt - 1 do + local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8) + if a >= count or b >= count or cc >= count then + fail(string.format("triangle %d: vertex index out of range", i)) + return nil + end + -- mirrored z: reverse the winding to keep the faces front-facing + writeu32(idx, i * 12, a) + writeu32(idx, i * 12 + 4, cc) + writeu32(idx, i * 12 + 8, b) + p += 12 + end + local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" } + prim.material = material(if brush == -1 then master else brush) + table.insert(mesh.primitives, prim) + end + end + if not attrs then + return nil -- a mesh without vertices: the node stays a pivot + end + if #mesh.primitives == 0 then + table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" }) + end + table.insert(scene.meshes, mesh) + rec.mesh, rec.count = #scene.meshes, count + table.insert(meshes, rec) + lastMesh = rec + return #scene.meshes + end + + local function readBone(r: Bytes.Reader, nodeIndex: number) + local b: Bone = { node = nodeIndex, target = lastMesh, list = {} } + table.insert(bones, b) + local list = b.list + while r.pos + 8 <= r.limit do + local v, w = r:i32le(), r:f32le() + table.insert(list, v) + table.insert(list, w) + end + end + + local function readKeys(r: Bytes.Reader, nodeIndex: number) + local flags = r:i32le() + local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0) + local k = nodeKeys[nodeIndex] + if not k then + k = { t = {}, s = {}, r = {} } + nodeKeys[nodeIndex] = k + end + while not r.err and r.pos + per <= r.limit do + local frame = r:i32le() + if bit32.band(flags, 1) ~= 0 then + k.t[frame] = vec(r) + end + if bit32.band(flags, 2) ~= 0 then + local x, y, z = r:f32le(), r:f32le(), r:f32le() + k.s[frame] = { x, y, z } + end + if bit32.band(flags, 4) ~= 0 then + k.r[frame] = quat(r) + end + end + end + + local function readNode(c: Chunks.Chunk, depth: number): number? + if depth > maxDepth then + fail("limit: nodes nested deeper than " .. maxDepth, "limit") + return nil + end + local r = body(c) + local name = r:cstring() + local t = vec(r) + local sx, sy, sz = r:f32le(), r:f32le(), r:f32le() + local q = quat(r) + if r.err then + fail("truncated NODE", "truncated") + return nil + end + local node: Types.Node = { name = name, children = {} } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then + node.rotation = q + end + if sx ~= 1 or sy ~= 1 or sz ~= 1 then + node.scale = { sx, sy, sz } + end + table.insert(scene.nodes, node) + local index = #scene.nodes + for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do + if failure then + break + end + local id = sub.id + if id == "NODE" then + local child = readNode(sub, depth + 1) + if child then + table.insert(node.children, child) + end + elseif id == "MESH" and not node.mesh then + node.mesh = readMesh(body(sub), index) + elseif id == "BONE" then + readBone(body(sub), index) + elseif id == "KEYS" then + readKeys(body(sub), index) + elseif id == "ANIM" then + local ar = body(sub) + local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le() + if not ar.err and not anim then + anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 } + end + end + end + return index + end + + for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do + if failure then + break + end + if c.id == "TEXS" then + readTexs(body(c)) + elseif c.id == "BRUS" then + readBrus(body(c)) + elseif c.id == "NODE" then + local n = readNode(c, 1) + if n then + table.insert(scene.roots, n) + end + end + end + if failure then + return nil, failure, failKind + end + if #scene.nodes == 0 then + return nil, "no NODE chunk", nil + end + + -- ------------------------------------------------------------------------------------------ skins + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, ch in n.children do + parent[ch] = i + end + end + local worldCache: { [number]: { number } } = {} + local function world(i: number): { number } + local w = worldCache[i] + if not w then + local n = scene.nodes[i] + local l = Mat4.compose(n.translation, n.rotation, n.scale) + w = if parent[i] then Mat4.mul(world(parent[i]), l) else l + worldCache[i] = w + end + return w + end + local bonesOf: { [MeshRec]: { Bone } } = {} + for _, b in bones do + local m = b.target + if m then + local l = bonesOf[m] or {} + bonesOf[m] = l + table.insert(l, b) + end + end + for _, rec in meshes do + local list = bonesOf[rec] + if list then + local nv = rec.count + local inf: { { number } } = {} + local joints: { number } = {} + for j, b in list do + joints[j] = b.node + local l = b.list + for k = 1, #l, 2 do + local v, w = l[k], l[k + 1] + if v >= 0 and v < nv and w > 0 and w == w then + local e = inf[v + 1] + if not e then + e = {} + inf[v + 1] = e + end + table.insert(e, j - 1) + table.insert(e, w) + end + end + end + local self: number? = nil -- the mesh node as a joint, for vertices no bone moves + local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16) + for v = 0, nv - 1 do + local e = inf[v + 1] + if not e then + if not self then + table.insert(joints, rec.node) + self = #joints - 1 + end + buffer.writeu16(jb, v * 8, self :: number) + buffer.writef32(wb, v * 16, 1) + else + -- the 4 strongest, normalised + local order = {} + for k = 1, #e, 2 do + table.insert(order, k) + end + table.sort(order, function(a: number, b: number): boolean + return e[a + 1] > e[b + 1] + end) + local sum = 0 + for k = 1, math.min(4, #order) do + sum += e[order[k] + 1] + end + for k = 1, math.min(4, #order) do + buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]]) + buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum) + end + end + end + local meshWorld = world(rec.node) + local ibm = buffer.create(#joints * 64) + for j, ni in joints do + local inv = Mat4.inverse(world(ni)) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local ia = Types.Scene.accessor(ibm, "f32", 16, #joints) + ia.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia }) + scene.nodes[rec.node].skin = #scene.skins + local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv) + for _, prim in scene.meshes[rec.mesh].primitives do + prim.attributes.JOINTS_0 = J + prim.attributes.WEIGHTS_0 = W + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + local fps = if anim then anim.fps else 60 + local channels: { Types.Channel } = {} + for ni = 1, #scene.nodes do + local k = nodeKeys[ni] + if k then + for _, path in { "translation", "rotation", "scale" } do + local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s + local frames = {} + for f in map do + table.insert(frames, f) + end + if #frames > 0 then + table.sort(frames) + local nc = if path == "rotation" then 4 else 3 + local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4) + for i, f in frames do + buffer.writef32(input, (i - 1) * 4, f / fps) + local v = map[f] + for c = 1, nc do + buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c]) + end + end + table.insert(channels, { + node = ni, + path = path :: any, + input = Types.Scene.accessor(input, "f32", 1, #frames), + output = Types.Scene.accessor(output, "f32", nc, #frames), + interpolation = "LINEAR" :: "LINEAR", + }) + end + end + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "b3d", channels = channels }) + end + + scene.meta.up = "y" + scene.meta.source = { + format = "b3d", + version = version, + brushes = #brushes, + frames = if anim then anim.frames else nil, + fps = if anim then anim.fps else nil, + handedness = "left", -- converted: z mirrored, winding reversed + } + return scene, nil, nil +end + +return Read diff --git a/src/Formats/model/b3d/init.luau b/src/Formats/model/b3d/init.luau new file mode 100644 index 0000000..14668d9 --- /dev/null +++ b/src/Formats/model/b3d/init.luau @@ -0,0 +1,68 @@ +--!strict +-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description +-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer. +-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler, +-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes -> +-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is +-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree +-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) / +-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the +-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights +-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the +-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps, +-- default 60) -> one animation of LINEAR channels at frame / fps seconds. +-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding +-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their +-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }. +-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the +-- extras; texture coordinate sets of 3 / 4 components keep their first two. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/b3d/Read") + +-- ------------------------------------------------------------------------------------------------ contract +local B3d = { + name = "b3d", + category = "model", + extensions = { "b3d" }, + mime = { "model/x-b3d" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" }, + caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the files by name + maxVertices: number?, -- default 2^24 + maxDepth: number?, -- node nesting (default 256) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function B3d.sniff(r: Bytes.Reader): number + if r:peek(4) == "BB3D" then + return if r:peek(4, 8) ~= "" then 1 else 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r:peek(4) ~= "BB3D" then + return nil, Err.new(Err.CORRUPT, "no BB3D chunk") + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +return B3d diff --git a/tests/model/b3d.luau b/tests/model/b3d.luau new file mode 100644 index 0000000..66a6c28 --- /dev/null +++ b/tests/model/b3d.luau @@ -0,0 +1,230 @@ +-- model/b3d tests: assimp's Blitz3D models (WusonBlitz, dwarf2, turtle1) and generated files (textures, brushes, +-- vertex colours, two UV sets, nested rotated / scaled / mirrored nodes, pivots, master brushes, bones, keys + ANIM) +-- against assimp (meshes, faces, materials, animations, channels, bones; world bounds, triangle area and signed +-- volume from its PreTransformVertices export: the left- to right-handed conversion and the winding) and the counts +-- the generator wrote; the skin's bind pose; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/b3d.py. +local T = require("@tests/T") +local B3d = require("@formats/model/b3d") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/b3d_cases") + +local t = T.suite("b3d") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return B3d.decode(Bytes.reader(b), opts) +end + +t:eq(B3d.name, "b3d", "name") +t:eq(B3d.category, "model", "category") +t:check(B3d.caps.decode and not B3d.caps.encode, "caps") +t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BB3D\0\0\0\0\1\0\0\0"))), 1, "sniff") +t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BX3D\0\0\0\0\1\0\0\0"))), 0, "sniff other") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- world triangles of the merged scene: area and signed volume +local function measure(prim: any): (number, number) + local get = assert(Types.Scene.reader(prim.attributes.POSITION)) + local idx = prim.indices and Types.Scene.reader(prim.indices) + local n = if idx then prim.indices.count else prim.attributes.POSITION.count + local area, vol = 0, 0 + for k = 0, n // 3 - 1 do + local i0, i1, i2 = 3 * k, 3 * k + 1, 3 * k + 2 + if idx then + i0, i1, i2 = idx(i0, 0), idx(i1, 0), idx(i2, 0) + end + local ax, ay, az = get(i0, 0), get(i0, 1), get(i0, 2) + local bx, by, bz = get(i1, 0), get(i1, 1), get(i1, 2) + local cx, cy, cz = get(i2, 0), get(i2, 1), get(i2, 2) + local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az + local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + area += math.sqrt(x * x + y * y + z * z) / 2 + vol += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6 + end + return area, vol +end + +-- assimp's bone count: per primitive, the joints that weight one of its vertices (not the mesh node's own joint) +local function boneCount(scene: any): number + local n = 0 + for ni, node in scene.nodes do + if node.mesh and node.skin then + local skin = scene.skins[node.skin] + for _, p in scene.meshes[node.mesh].primitives do + local J, W = Types.Scene.reader(p.attributes.JOINTS_0), Types.Scene.reader(p.attributes.WEIGHTS_0) + local idx = assert(Types.Scene.reader(p.indices)) + local seen = {} + for i = 0, p.indices.count - 1 do + local v = idx(i, 0) + for k = 0, 3 do + local j = (J :: any)(v, k) + if (W :: any)(v, k) > 0 and skin.joints[j + 1] ~= ni and not seen[j] then + seen[j] = true + n += 1 + end + end + end + end + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ cases +local samples = {} +for _, c in Cases do + local scene, err = decode(c.data, { files = c.files }) + local a = c.assimp + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if scene and not a.failed then + local prims, faces = 0, 0 + for _, pl in Types.Scene.flatten(scene) do + prims += 1 + faces += pl.primitive.indices.count // 3 + end + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(math.max(1, scene.meta.source.brushes), a.materials, c.name .. ": materials (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + local animated = {} + local nAnimated = 0 + for _, anim in scene.animations do + for _, ch in anim.channels do + if not animated[ch.node] then + animated[ch.node] = true + nAnimated += 1 + end + end + end + if a.animations > 0 then + t:eq(nAnimated, a.animation_channels, c.name .. ": animated nodes (assimp)") + end + t:eq(boneCount(scene), a.bones, c.name .. ": bones (assimp)") + local merged = assert(MeshOps.merge(scene)) + local lo, hi = MeshOps.bounds(merged) + local ok = lo ~= nil + for k = 1, 3 do + ok = ok and near((lo :: any)[k], a.min[k], 1e-4) and near((hi :: any)[k], a.max[k], 1e-4) + end + t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " "))) + local area, vol = measure(merged) + t:check(near(area, a.area, 1e-4), string.format("%s: area %.6g (assimp %.6g)", c.name, area, a.area)) + -- (a mirrored node: glTF turns its faces back, assimp's PreTransformVertices does not; skip the volume there) + if not (c.want and c.want.mirrored) then + t:check(near(vol, a.volume, 1e-3), string.format("%s: signed volume %.6g (assimp %.6g)", c.name, vol, a.volume)) + end + -- textures resolved through files + for _, tex in scene.textures do + local base = string.match(tex.uri, "([^/\\]+)$") + t:check((tex.data ~= nil) == (c.files[base] ~= nil), c.name .. ": texture data " .. tostring(tex.uri)) + end + local w = c.want + if w then + local nv, nt = 0, 0 + for _, m in scene.meshes do + nv += m.primitives[1].attributes.POSITION.count + for _, p in m.primitives do + nt += p.indices.count // 3 + end + end + t:eq(nv, w.vertices, c.name .. ": vertices") + t:eq(nt, w.triangles, c.name .. ": triangles") + t:eq(#scene.textures, w.textures, c.name .. ": textures") + t:eq(#scene.materials, w.materials, c.name .. ": materials") + t:eq(#scene.nodes, w.nodes, c.name .. ": nodes") + local attrs = scene.meshes[1].primitives[1].attributes + t:eq(attrs.COLOR_0 ~= nil, w.colors, c.name .. ": COLOR_0") + local sets = 0 + while attrs["TEXCOORD_" .. sets] do + sets += 1 + end + t:eq(sets, w.uvSets, c.name .. ": uv sets") + if w.joints then + t:eq(#scene.skins, 1, c.name .. ": one skin") + t:eq(#scene.skins[1].joints, w.joints, c.name .. ": joints") + t:eq(#scene.animations[1].channels, w.channels, c.name .. ": channels") + t:eq(scene.meta.source.fps, w.fps, c.name .. ": fps") + t:eq(scene.meta.source.frames, w.frames, c.name .. ": frames") + end + end + if c.name == "gen/textured" then + local m1, m2 = scene.materials[1], scene.materials[2] + t:check(m1.name == "red" and m1.baseColorTexture and m1.baseColorTexture.texture == 1, "textured: brush texture") + local tr = m1.baseColorTexture and m1.baseColorTexture.transform + t:check(tr and tr.offset[1] == 0.25 and tr.scale[2] == 3 and tr.rotation == 0.5, "textured: texture transform") + t:check(m1.extras.b3d.textures[2] == 2, "textured: second brush texture in extras") + t:check(m2.name == "glass" and m2.alphaMode == "blend" and m2.doubleSided and m2.extensions.KHR_materials_unlit, "textured: alpha, FX") + t:check(m2.baseColorTexture and m2.baseColorTexture.texCoord == 1, "textured: second UV set flag") + t:check(scene.textures[2].sampler and scene.textures[2].sampler.wrapS == "clamp", "textured: clamp") + end + -- the bind pose: skinning the vertices with the inverse bind matrices gives the static placement + for ni, node in scene.nodes do + if node.skin then + local skin = scene.skins[node.skin] + local worlds = {} + for _, pl in Types.Scene.flatten(scene) do + worlds[pl.node] = pl.matrix + end + local ibm = assert(Types.Scene.reader(skin.inverseBindMatrices)) + local function world(i: number): { number } + local parent + for pi, n in scene.nodes do + if table.find(n.children, i) then + parent = pi + end + end + local l = Types.Scene.nodeMatrix(scene.nodes[i]) + return if parent then Types.Scene.mul(world(parent), l) else l + end + local maxErr = 0 + local meshWorld = world(ni) + for j, jn in skin.joints do + local m = {} + for k = 1, 16 do + m[k] = ibm(j - 1, k - 1) + end + local jm = Types.Scene.mul(world(jn), m) + for k = 1, 16 do + maxErr = math.max(maxErr, math.abs(jm[k] - meshWorld[k])) + end + end + t:check(maxErr < 1e-3, c.name .. ": joint * inverse bind = the mesh's world matrix (" .. maxErr .. ")") + end + end + end + if #c.data < 100000 then + table.insert(samples, c.data) + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e = decode("BB3D\4\0\0\0\1\0\0\0") + t:check(e and e.code == Err.CORRUPT, "no NODE: CORRUPT") + _, e = decode("BB3D\100\0\0\0\1\0\0\0") + t:check(e and e.code == Err.TRUNCATED, "short BB3D: TRUNCATED") + _, e = decode("RIFF\0\0\0\0") + t:check(e and e.code == Err.CORRUPT, "not B3D: CORRUPT") + local s = Cases[#Cases].data + local _, e2 = decode(string.sub(s, 1, #s - 7)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated file: TRUNCATED (" .. tostring(e2) .. ")") + local _, e3 = decode(s, { maxVertices = 4 }) + t:check(e3 and e3.code == Err.LIMIT, "maxVertices: LIMIT") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +t:fuzz("decode", function(b: buffer) + local s = B3d.decode(Bytes.reader(b)) + if s then + MeshOps.merge(s) + end + return s +end, samples, { mutations = 16, keepHeader = 4 }) + +t:done() diff --git a/tools/fixtures/b3d.py b/tools/fixtures/b3d.py new file mode 100644 index 0000000..84cdca9 --- /dev/null +++ b/tools/fixtures/b3d.py @@ -0,0 +1,204 @@ +# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs +# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures +# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes, +# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r` +# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds, +# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote. +# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} } +import importlib.util, math, os, re, struct, subprocess + +INPUTS = ["tools/fixtures/_model_ref.py"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_src(): + out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +# ---------------------------------------------------------------------------------------------------- B3D writer +def chunk(tag, *parts): + body = b"".join(parts) + return tag.encode() + struct.pack("> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0) + for s in range(sets): + v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)]) + verts.append(v) + # Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling) + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] + tris = [] + for a, b, c, d in quads: + tris += [(a, b, c), (a, c, d)] + tchunks = [] + for k, br in enumerate(brushes): + mine = [t for j, t in enumerate(tris) if j % len(brushes) == k] + tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine))) + return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12 + + +def textured(): + texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5), + cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0)) + brus = chunk("BRUS", i32(2), + cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1), + cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1)) + m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1)) + m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1) + child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2) + root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child) + data = chunk("BB3D", i32(1), texs, brus, root) + return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2} + + +def pivots(): + m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,)) + m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,)) + a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1) + b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2) + pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b) + data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot)) + return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True} + + +def skinned(): + # a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones + verts, tris = [], [] + for ring in range(3): + for k in range(4): + a = math.radians(90 * k) + verts.append(f32(math.cos(a), ring * 2.0, math.sin(a))) + for ring in range(2): + for k in range(4): + a, b = ring * 4 + k, ring * 4 + (k + 1) % 4 + tris += [(a, b + 4, b), (a, a + 4, b + 4)] + mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris))) + w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8)) + w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12)) + keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)]) + keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)]) + bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2) + bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2) + root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25))) + data = chunk("BB3D", i32(1), root) + return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3, + "joints": 2, "channels": 3, "fps": 25.0, "frames": 10} + + +# ---------------------------------------------------------------------------------------------------- references +def info(ctx, path): + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {"failed": True} + out = {} + for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1 + return out + + +def ptv(ctx, path, tmp): + # world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume + out = os.path.join(tmp, "ptv.obj") + ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"]) + vs, area, vol = [], 0.0, 0.0 + lo, hi = [1e30] * 3, [-1e30] * 3 + with open(out) as f: + for line in f: + p = line.split() + if not p: + continue + if p[0] == "v": + v = [float(x) for x in p[1:4]] + vs.append(v) + lo = [min(a, b) for a, b in zip(lo, v)] + hi = [max(a, b) for a, b in zip(hi, v)] + elif p[0] == "f": + idx = [int(x.split("/")[0]) for x in p[1:]] + idx = [i - 1 if i > 0 else len(vs) + i for i in idx] + for k in range(1, len(idx) - 1): + a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]] + e1 = [b[j] - a[j] for j in range(3)] + e2 = [c[j] - a[j] for j in range(3)] + cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]] + area += math.sqrt(sum(x * x for x in cr)) / 2 + vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6 + os.remove(out) + return {"min": lo, "max": hi, "area": area, "volume": vol} + + +def generate(ctx): + M = ref_module(ctx) + tmp = M.tempdir() + cases = [] + src = assimp_src() + for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"): + p = os.path.join(src, "test", rel) + if not os.path.exists(p): + continue + d = os.path.dirname(p) + files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) + if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000} + cases.append({"name": "assimp/" + rel, "path": p, "files": files}) + for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)): + data, want = fn() + p = os.path.join(tmp, name + ".b3d") + with open(p, "wb") as f: + f.write(data) + files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {} + cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want}) + for c in cases: + a = info(ctx, c["path"]) + if not a.get("failed"): + a.update(ptv(ctx, c["path"], tmp)) + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("b3d_cases", cases) + + +# a 1x1 PNG (texture data for the generated files) +M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000" + "1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082") From 7b4bf1ee4345365560598c0c67df86cb4595a383 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:02:01 -0500 Subject: [PATCH 06/54] containers: video track palettes and depths for the legacy codecs Small backward-compatible additions so palettised codecs find their colour table on the Track: - containers/Avi: Avi.bitmapInfo(strf) (BITMAPINFOHEADER facts + palette as 256 RGBA u32); video/avi sets track.palette for 1..8-bit streams. - containers/IsoBmff/QtPalette (new): QuickTime sample description depth + colour table (stsd table, Mac default tables, grey ramps); IsoBmff Demux sets track.bitsPerPixel / track.palette, video/mp4 copies them. - video/mkv: V_MS/VFW/FOURCC (BITMAPINFOHEADER) and V_QUICKTIME (sample description) CodecPrivate map to the FourCC's codec with depth / palette. --- src/Formats/Registry.luau | 2 +- src/Formats/containers/Avi/init.luau | 47 ++++++++ src/Formats/containers/IsoBmff/Demux.luau | 14 +++ src/Formats/containers/IsoBmff/QtPalette.luau | 113 ++++++++++++++++++ src/Formats/video/avi/init.luau | 4 + src/Formats/video/mkv/Parse.luau | 38 ++++++ src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 + 8 files changed, 220 insertions(+), 2 deletions(-) create mode 100644 src/Formats/containers/IsoBmff/QtPalette.luau diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..288846f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -308,7 +308,7 @@ local list: { Entry } = { path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau index 081e9b9..9d89f18 100644 --- a/src/Formats/containers/Avi/init.luau +++ b/src/Formats/containers/Avi/init.luau @@ -9,6 +9,7 @@ -- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf -- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute -- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- local bi = Avi.bitmapInfo(strf) -- a BITMAPINFOHEADER: size, depth, FourCC, palette (also Matroska VFW) -- -- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). local Err = require("@formats/core/Err") @@ -520,4 +521,50 @@ function Avi.write(opts: WOptions, chunks: { { any } }): buffer return w:finish() end +-- ------------------------------------------------------------------------------------------------ BITMAPINFO +export type BitmapInfo = { + width: number, + height: number, -- signed: > 0 = bottom-up rows + bits: number, -- biBitCount + compression: string, -- biCompression as a FourCC ("\0\0\0\0" = BI_RGB) + palette: buffer?, -- bits <= 8: 256 u32 entries, bytes R, G, B, 0xFF (codecs/image/Pixels layout); unused ones 0 + extra: buffer?, -- the bytes after the 40-byte header (palette included), nil when none +} + +-- bitmapInfo(f) -> the BITMAPINFOHEADER facts of an AVI video strf (or a Matroska V_MS/VFW/FOURCC CodecPrivate) | +-- nil when shorter than 40 bytes. The palette is the last (2^bits) * 4 bytes after the header (B, G, R, x entries; +-- a trailing "BottomUp" tag is skipped), as the VfW codecs store it. +function Avi.bitmapInfo(f: buffer): BitmapInfo? + local n = buffer.len(f) + if n < 40 then + return nil + end + local bits = readu16(f, 14) + local info: BitmapInfo = { + width = buffer.readi32(f, 4), + height = buffer.readi32(f, 8), + bits = bits, + compression = readstring(f, 16, 4), + } + if n > 40 then + local e = buffer.create(n - 40) + buffer.copy(e, 0, f, 40) + info.extra = e + if bits >= 1 and bits <= 8 then + local count = math.min(2 ^ bits, (n - 40) // 4) + local at = n - count * 4 + if at - 40 >= 9 and readstring(f, n - 9, 9) == "BottomUp\0" then + at -= 9 + end + local pal = buffer.create(1024) + for i = 0, count - 1 do + local o = at + i * 4 + buffer.writeu32(pal, i * 4, readu8(f, o + 2) + readu8(f, o + 1) * 256 + readu8(f, o) * 65536 + 0xFF000000) + end + info.palette = pal + end + end + return info +end + return Avi diff --git a/src/Formats/containers/IsoBmff/Demux.luau b/src/Formats/containers/IsoBmff/Demux.luau index 7f8689d..d44c566 100644 --- a/src/Formats/containers/IsoBmff/Demux.luau +++ b/src/Formats/containers/IsoBmff/Demux.luau @@ -8,9 +8,14 @@ local Err = require("@formats/core/Err") local Bytes = require("@formats/core/Bytes") local Box = require("@formats/containers/IsoBmff/Box") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local readstring = buffer.readstring +local function readu16be(b: buffer, o: number): number + return buffer.readu8(b, o) * 256 + buffer.readu8(b, o + 1) +end + local Demux = {} export type Edit = { duration: number, mediaTime: number, rate: number } -- duration in movie ticks, mediaTime in media ticks (-1 = empty) @@ -33,6 +38,8 @@ export type Track = { channels: number?, bitsPerSample: number?, config: buffer?, -- codec configuration (AudioSpecificConfig, ALAC cookie, dOps, avcC, ...) + bitsPerPixel: number?, -- video: the sample description's depth (24, 32, 40 = 8-bit grey, ...) + palette: buffer?, -- video, 1..8-bit depths: 256 u32 entries (bytes R, G, B, 0xFF) objectType: number?, -- esds objectTypeIndication pcm: { bits: number, float: boolean, little: boolean }?, entryBoxes: { Box.Box }, -- the sample entry's child boxes (esds, btrt, colr, pasp, ...) @@ -194,6 +201,13 @@ local function sampleEntry(b: buffer, e: Box.Box, handler: string, t: Track) t.height = r:u16be() r:skip(4 + 4 + 4 + 2 + 32 + 2 + 2) childStart = r.pos + -- QuickTime depth and colour table (palettised codecs: QuickTime RLE / SMC, Cinepak, ...) + local depth, pal = QtPalette.read(b, e.start, e.stop, if typ == "cvid" then "cinepak" else typ) + t.bitsPerPixel = depth + t.palette = pal + if pal and not r.err and readu16be(b, childStart - 2) == 0 and childStart + 8 <= e.stop then + childStart = math.min(e.stop, childStart + 8 + (readu16be(b, childStart + 6) + 1) * 8) + end else childStart = r.pos end diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau new file mode 100644 index 0000000..2034dc3 --- /dev/null +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -0,0 +1,113 @@ +--!strict +-- containers/IsoBmff/QtPalette: the depth and colour table of a QuickTime video sample description (Apple QuickTime +-- File Format, "Video sample description": depth at byte 82, color table ID at 84, then the table when the ID is 0). +-- Used by the MOV demuxer and by Matroska's V_QUICKTIME tracks (whose CodecPrivate is the same description). Depths 1, +-- 2, 4 and 8 are palettised: the colour table from the description, the Macintosh default table (ID -1), or a grey +-- ramp (depths 33..40: the 0x20 bit marks grey). Written from the QuickTime documentation; the default tables are the +-- Macintosh system palettes (white first, a 6x6x6 cube, then red / green / blue / grey ramps). +-- +-- local depth, palette = QtPalette.read(buf, entryStart, entryStop, codec) +-- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil +-- +-- Never throws. +local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 + +local QtPalette = {} + +local function rgb(r: number, g: number, b: number): number + return r + g * 256 + b * 65536 + 0xFF000000 +end + +-- the Macintosh default colour tables: 2 / 4 / 16 entries (System 7 control panel), 256 (the system palette) +local SMALL: { [number]: { number } } = { + [1] = { 0xFFFFFF, 0x000000 }, + [2] = { 0xFFFFFF, 0xACACAC, 0x555555, 0x000000 }, + [4] = { + 0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5, 0x0000D4, 0x02ABEA, + 0x1FB714, 0x006411, 0x562C05, 0x90713A, 0xC0C0C0, 0x808080, 0x404040, 0x000000, + }, +} + +local function defaultTable(bits: number): buffer + local pal = buffer.create(1024) + local small = SMALL[bits] + if small then + for i, c in small do + writeu32(pal, (i - 1) * 4, rgb(c // 65536, (c // 256) % 256, c % 256)) + end + return pal + end + local i = 0 + for r = 5, 0, -1 do + for g = 5, 0, -1 do + for b = 5, 0, -1 do + if i < 215 then + writeu32(pal, i * 4, rgb(r * 51, g * 51, b * 51)) + end + i += 1 + end + end + end + -- ramps without the cube's multiples of 0x33: red, green, blue, grey; then black + local RAMP = { 0xEE, 0xDD, 0xBB, 0xAA, 0x88, 0x77, 0x55, 0x44, 0x22, 0x11 } + i = 215 + for ch = 0, 3 do + for _, v in RAMP do + local r = if ch == 0 or ch == 3 then v else 0 + local g = if ch == 1 or ch == 3 then v else 0 + local b = if ch == 2 or ch == 3 then v else 0 + writeu32(pal, i * 4, rgb(r, g, b)) + i += 1 + end + end + writeu32(pal, 255 * 4, rgb(0, 0, 0)) + return pal +end + +-- read(buf, start, stop, codec?) -> depth, palette | nil: start = the offset of the sample description (its size +-- field), stop = its end. Cinepak's grey flag selects its own grey mode, so no grey palette is made for it. +function QtPalette.read(b: buffer, start: number, stop: number, codec: string?): (number?, buffer?) + if start + 86 > stop or stop > buffer.len(b) then + return nil, nil + end + local raw = readu16(b, start + 82) + local id = readu16(b, start + 84) + local bits = raw % 32 + local grey = raw >= 32 and (raw // 32) % 2 == 1 + if bits ~= 1 and bits ~= 2 and bits ~= 4 and bits ~= 8 then + return raw, nil + end + if grey and codec == "cinepak" then + return raw, nil + end + if grey and bits > 1 and id ~= 0 then + local pal = buffer.create(1024) + local count = 2 ^ bits + local step = 256 // (count - 1) + local v = 255 + for i = 0, count - 1 do + writeu32(pal, i * 4, rgb(v, v, v)) + v = math.max(0, v - step) + end + return bits, pal + elseif id ~= 0 then + return bits, defaultTable(bits) + end + local pal = buffer.create(1024) + if start + 94 <= stop then + local first = readu32(b, start + 86) + local last = readu16(b, start + 92) + if first <= 255 and last <= 255 then + for i = first, last do + local o = start + 94 + (i - first) * 8 + if o + 8 > stop then + break + end + writeu32(pal, i * 4, rgb(readu8(b, o + 2), readu8(b, o + 4), readu8(b, o + 6))) + end + end + end + return bits, pal +end + +return QtPalette diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..3c5d919 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -110,6 +110,10 @@ local function videoTrack(s: Avi.Stream, id: number): Types.Track t.pixelFormat = "yuv420p" end end + local bi = Avi.bitmapInfo(f) + if bi and bi.palette then + t.palette = bi.palette -- 1..8-bit codecs (Microsoft Video 1, Cinepak, QuickTime RLE / SMC in AVI, ...) + end local size = buffer.readu32(f, 0) if size > 40 and buffer.len(f) > 40 then local c = buffer.create(buffer.len(f) - 40) diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index fd07900..252a004 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -9,6 +9,8 @@ local Types = require("@formats/Types") local Ebml = require("@formats/containers/Ebml") local Demux = require("@formats/containers/Demux") local Video = require("@formats/codecs/video/Video") +local Avi = require("@formats/containers/Avi") +local QtPalette = require("@formats/containers/IsoBmff/QtPalette") local Deflate = require("@formats/codecs/compress/Deflate") local Parse = {} @@ -152,6 +154,39 @@ local function codecFor(id: string, kind: string, bits: number?): string end Parse.codecFor = codecFor +-- V_MS/VFW/FOURCC (CodecPrivate = a BITMAPINFOHEADER) and V_QUICKTIME (CodecPrivate = a QuickTime sample +-- description, sometimes without its size field): the codec from the FourCC, the depth and palette, the extradata +local function vfwOrQuickTime(t: any, codecId: string, priv: buffer) + local n = buffer.len(priv) + if codecId == "V_MS/VFW/FOURCC" then + local bi = Avi.bitmapInfo(priv) + if bi then + t.codec = Video.fromFourcc(bi.compression) or t.codec + t.codecTag = bi.compression + t.bitsPerPixel = bi.bits + t.palette = bi.palette + t.config = bi.extra + end + elseif codecId == "V_QUICKTIME" and n >= 21 then + local desc = priv + if Video.fromFourcc(buffer.readstring(priv, 0, 4)) then + desc = buffer.create(n + 4) + local size = n + 4 + buffer.writeu8(desc, 0, size // 16777216 % 256) + buffer.writeu8(desc, 1, size // 65536 % 256) + buffer.writeu8(desc, 2, size // 256 % 256) + buffer.writeu8(desc, 3, size % 256) + buffer.copy(desc, 4, priv, 0, n) + end + local fcc = buffer.readstring(desc, 4, 4) + t.codec = Video.fromFourcc(fcc) or t.codec + t.codecTag = fcc + local depth, pal = QtPalette.read(desc, 0, buffer.len(desc), t.codec) + t.bitsPerPixel = depth + t.palette = pal + end +end + type TrackInfo = Types.Track & { strip: buffer?, lacing: boolean?, defaultDurationNs: number? } local function parseVideo(buf: buffer, off: number, len: number, t: any) @@ -278,6 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) + if t.kind == "video" and t.config then + vfwOrQuickTime(t, codecId, t.config) + end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 t.channels = t.channels or 1 diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 1a94272..b8a22a5 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -27,7 +27,7 @@ local Mkv = { category = "video", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "containers/Avi", "containers/IsoBmff/QtPalette", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, } diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 0dcf3e8..f4d8217 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -133,6 +133,8 @@ function Mp4.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) bitsPerSample = it.bitsPerSample, config = it.config, default = true, + bitsPerPixel = it.bitsPerPixel, + palette = it.palette, } if it.kind == "video" then if not Video.entry(t.codec) then From 1aaf8fce68584b70532cb448014bec0afd697146 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:03:52 -0500 Subject: [PATCH 07/54] ws-3d3-b: model/lwo (LightWave LWO2 / LWOB / Modo LXOB read: layers with pivots and parents, polygons, VMAP / VMAD uv / colour / normal / weight / morph maps, surfaces and image blocks); 54 assimp test models match assimp's counts, materials and world bounds --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/lwo/Build.luau | 467 ++++++++++++++++++++++++++ src/Formats/model/lwo/Parse.luau | 551 +++++++++++++++++++++++++++++++ src/Formats/model/lwo/init.luau | 86 +++++ tests/model/lwo.luau | 315 ++++++++++++++++++ tools/fixtures/lwo.py | 41 +++ 7 files changed, 1473 insertions(+) create mode 100644 src/Formats/model/lwo/Build.luau create mode 100644 src/Formats/model/lwo/Parse.luau create mode 100644 src/Formats/model/lwo/init.luau create mode 100644 tests/model/lwo.luau create mode 100644 tools/fixtures/lwo.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..4ee62bf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..79dc5d6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "lwo", + category = "model", + path = "model/lwo", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, + load = function() + return require("@formats/model/lwo") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/model/lwo/Build.luau b/src/Formats/model/lwo/Build.luau new file mode 100644 index 0000000..0d62bbd --- /dev/null +++ b/src/Formats/model/lwo/Build.luau @@ -0,0 +1,467 @@ +--!strict +-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z +-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's +-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its +-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), +-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, +-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. +-- Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Parse = require("@formats/model/lwo/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } + +-- ------------------------------------------------------------------------------------------------ materials +local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number + local hit = cache[path] + if hit then + return hit + end + local norm = string.gsub(path, "\\", "/") + local base = string.match(norm, "([^/:]+)$") or norm + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } }) + cache[path] = #scene.textures + return #scene.textures +end + +local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material + local mat = Scene.material(surf.name) + local v = surf.values + local c = surf.color + local tran = math.clamp(v.TRAN or 0, 0, 1) + mat.baseColor = { c[1], c[2], c[3], 1 - tran } + if tran > 0 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + local gloss = v.GLOS + mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1 + local lumi = v.LUMI or 0 + if lumi > 0 then + mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi } + end + mat.doubleSided = surf.side == 3 + local maps = {} + local blocks = table.clone(surf.blocks) + table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean + return a.ordinal < b.ordinal + end) + for _, blk in blocks do + local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil + local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap } + if path and (blk.kind == "IMAP" or blk.kind == "TEX") then + local ti = textureIndex(scene, cache, path) + entry.texture = ti + if blk.enabled then + local ref: Types.TextureRef = { texture = ti } + if blk.uvmap and uvSets[blk.uvmap] then + ref.texCoord = uvSets[blk.uvmap] + end + if blk.channel == "COLR" and not mat.baseColorTexture then + mat.baseColorTexture = ref + elseif blk.channel == "LUMI" and not mat.emissiveTexture then + mat.emissiveTexture = ref + if lumi <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + end + table.insert(maps, entry) + end + local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source } + for k, x in v do + extras[string.lower(k)] = x + end + if surf.vcol then + extras.vcol = surf.vcol.name + end + mat.extras = { lwo = extras } + return mat +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group } + local groups: { Group } = {} + local byKey: { [string]: Group } = {} + for i, poly in layer.polys do + local kind = poly.kind + local n = #poly.corners + if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then + local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch" + local mi = surfaceOf(poly.surf) + local key = mi .. class + local g = byKey[key] + if not g then + g = { material = mi, class = class, polys = {} } + byKey[key] = g + table.insert(groups, g) + end + table.insert(g.polys, i - 1) + end + end + local rank = { poly = 1, patch = 2, line = 3, point = 4 } + table.sort(groups, function(a: Group, b: Group): boolean + if a.material ~= b.material then + return a.material < b.material + end + return rank[a.class] < rank[b.class] + end) + return groups +end + +-- the corners of a face in output order (winding reversed for the handedness change, first corner kept) +local function ordered(corners: { number }): { number } + local n = #corners + local out = table.create(n) + out[1] = corners[1] + for k = 2, n do + out[k] = corners[n - k + 2] + end + return out +end + +type Attr = { map: Parse.Map, name: string, comps: number } + +local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive + local pts, pivot = layer.pts, layer.pivot + local vertOf: { [number]: number } = {} + local srcPoint: { number } = {} -- vertex (1-based) -> point + local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local indices: { number } = {} + local faces: { number } = {} + local madMaps: { Parse.Map } = {} + for _, a in attrs do + if next(a.map.mad) then + table.insert(madMaps, a.map) + end + end + for _, m in morphs do + if next(m.mad) then + table.insert(madMaps, m) + end + end + local function vertex(f: number, p: number): number + local own = false + for _, m in madMaps do + local row = m.mad[f] + if row and row[p] then + own = true + break + end + end + if not own then + local v = vertOf[p] + if v then + return v + end + end + table.insert(srcPoint, p) + table.insert(srcPoly, if own then f else -1) + local v = #srcPoint - 1 + if not own then + vertOf[p] = v + end + return v + end + for _, f in g.polys do + local corners = ordered(layer.polys[f + 1].corners) + local n = #corners + local vs = table.create(n) + for k = 1, n do + vs[k] = vertex(f, corners[k]) + end + if g.class == "poly" or g.class == "patch" then + if triangulate then + for k = 2, n - 1 do + table.insert(indices, vs[1]) + table.insert(indices, vs[k]) + table.insert(indices, vs[k + 1]) + end + else + table.insert(faces, n) + table.move(vs, 1, n, #indices + 1, indices) + end + else + table.move(vs, 1, n, #indices + 1, indices) + end + end + local nv = #srcPoint + local pos = buffer.create(nv * 12) + for v = 1, nv do + local p = srcPoint[v] * 3 + local o = (v - 1) * 12 + writef32(pos, o, pts[p + 1] - pivot[1]) + writef32(pos, o + 4, pts[p + 2] - pivot[2]) + writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) + end + local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } + -- the value of map m for vertex v (1-based), or nil + local function value(m: Parse.Map, v: number): ({ number }?, number?) + local f = srcPoly[v] + if f >= 0 then + local row = m.mad[f] + local hit = row and row[srcPoint[v]] + if hit then + return hit, nil + end + end + local p = srcPoint[v] + if m.has[p] then + return nil, p * m.dims + end + return nil, nil + end + local names: { [string]: string } = {} + for _, a in attrs do + local m, comps = a.map, a.comps + local data = buffer.create(nv * comps * 4) + for v = 1, nv do + local o = (v - 1) * comps * 4 + local direct, at = value(m, v) + local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {} + if m.kind == "uv" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, 1 - (x[2] or 0)) + elseif m.kind == "color" then + writef32(data, o, x[1] or 1) + writef32(data, o + 4, x[2] or 1) + writef32(data, o + 8, x[3] or 1) + writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1) + elseif m.kind == "normal" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, x[2] or 0) + writef32(data, o + 8, -(x[3] or 0)) + else + writef32(data, o, x[1] or 0) + end + end + attributes[a.name] = Scene.accessor(data, "f32", comps, nv) + names[a.name] = m.name + end + local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } + if #morphs > 0 then + local targets = {} + local targetNames = {} + for _, m in morphs do + local d = buffer.create(nv * 12) + for v = 1, nv do + local direct, at = value(m, v) + local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil + if x then + local p = srcPoint[v] * 3 + local dx, dy, dz = x[1], x[2], x[3] + if m.kind == "spot" then + dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3] + end + writef32(d, (v - 1) * 12, dx) + writef32(d, (v - 1) * 12 + 4, dy) + writef32(d, (v - 1) * 12 + 8, -dz) + end + end + table.insert(targets, { POSITION = Scene.accessor(d, "f32", 3, nv) }) + table.insert(targetNames, m.name) + end + prim.targets = targets + names._targets = table.concat(targetNames, "\n") + end + local ib = buffer.create(#indices * 4) + for k, x in indices do + writeu32(ib, (k - 1) * 4, x) + end + prim.indices = Scene.accessor(ib, "u32", 1, #indices) + if g.class == "line" then + prim.mode = "lines" + elseif g.class == "point" then + prim.mode = "points" + elseif not triangulate then + prim.mode = "polygons" + local fb = buffer.create(#faces * 4) + for k, x in faces do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #faces) + end + prim.material = g.material + local extras: { [string]: any } = { maps = names } + if g.class == "patch" then + extras.subdivision = true + end + prim.extras = { lwo = extras } + return prim +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } + -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + local uvSets: { [string]: number } = {} + local nuv = 0 + for _, layer in m.layers do + for _, map in layer.maps do + if map.kind == "uv" and uvSets[map.name] == nil then + uvSets[map.name] = nuv + nuv += 1 + end + end + end + -- materials: one per surface, then one per tag without a surface, then a default one + local texCache: { [string]: number } = {} + local bySurfName: { [string]: number } = {} + for i, surf in m.surfaces do + scene.materials[i] = material(scene, m, surf, uvSets, texCache) + if bySurfName[surf.name] == nil then + bySurfName[surf.name] = i + end + local low = string.lower(surf.name) + if bySurfName[low] == nil then + bySurfName[low] = i + end + end + local tagMat: { [number]: number } = {} + local default: number? = nil + local function surfaceOf(tag: number?): number + if tag ~= nil then + local hit = tagMat[tag] + if hit then + return hit + end + local name = m.tags[tag + 1] + if name then + local mi = bySurfName[name] or bySurfName[string.lower(name)] + if not mi then + table.insert(scene.materials, Scene.material(name)) + mi = #scene.materials + bySurfName[name] = mi + end + tagMat[tag] = mi + return mi + end + end + if not default then + local mat = Scene.material("Default") + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + mat.metallic = 0 + table.insert(scene.materials, mat) + default = #scene.materials + end + return default :: number + end + -- nodes and meshes + local nodeOf: { [number]: number } = {} + local layerOfNode: { Parse.Layer } = {} + for _, layer in m.layers do + local hasGeometry = #layer.polys > 0 + if not (layer.implicit and not hasGeometry) then + local node: Types.Node = { name = layer.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + layerOfNode[ni] = layer + if nodeOf[layer.index] == nil then + nodeOf[layer.index] = ni + end + node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } } + local groups = groupLayer(layer, surfaceOf) + if #groups > 0 then + local attrs: { Attr } = {} + local morphs: { Parse.Map } = {} + local hasUv = {} + local maxUv = -1 + for _, map in layer.maps do + if map.kind == "uv" then + hasUv[uvSets[map.name]] = map + maxUv = math.max(maxUv, uvSets[map.name]) + elseif map.kind == "morph" or map.kind == "spot" then + table.insert(morphs, map) + end + end + local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} } + for k = 0, maxUv do + table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 }) + end + local nw, nc, hasNormal = 0, 0, false + for _, map in layer.maps do + if map.kind == "normal" and not hasNormal then + hasNormal = true + table.insert(attrs, { map = map, name = "NORMAL", comps = 3 }) + elseif map.kind == "weight" then + table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 }) + nw += 1 + end + end + local prims = {} + for _, g in groups do + local mat = scene.materials[g.material] + local vcol = mat and mat.extras and mat.extras.lwo and mat.extras.lwo.vcol + local pa = table.clone(attrs) + nc = 0 + for _, map in layer.maps do + if map.kind == "color" then + if map.name == vcol then + table.insert(pa, { map = map, name = "COLOR_0", comps = 4 }) + else + table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 }) + nc += 1 + end + end + end + table.insert(prims, primitive(layer, g, pa, morphs, triangulate)) + end + local mesh: Types.Mesh = { name = layer.name, primitives = prims } + if #morphs > 0 then + mesh.weights = table.create(#morphs, 0) + local tn = {} + for _, mp in morphs do + table.insert(tn, mp.name) + end + mesh.extras = { targetNames = tn } + end + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + end + end + -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + local parentOf: { [number]: number } = {} + for ni, layer in layerOfNode do + local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil + if pi and pi ~= ni then + local up, steps = pi, 0 + while up and up ~= ni and steps <= #scene.nodes do + up = parentOf[up] + steps += 1 + end + if up ~= ni then + parentOf[ni] = pi + end + end + end + for ni = 1, #scene.nodes do + local layer = layerOfNode[ni] + local pi = parentOf[ni] + local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 } + local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + scene.nodes[ni].translation = t + end + if pi then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + return scene, nil +end + +return Build diff --git a/src/Formats/model/lwo/Parse.luau b/src/Formats/model/lwo/Parse.luau new file mode 100644 index 0000000..21d985c --- /dev/null +++ b/src/Formats/model/lwo/Parse.luau @@ -0,0 +1,551 @@ +--!strict +-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build +-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave +-- 5.x), checked against what assimp's LWO importer reads (no code taken). +-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are +-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS +-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo +-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural +-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). +-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, +-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. +-- Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Bytes = require("@formats/core/Bytes") +local Chunks = require("@formats/containers/Chunks") + +local Parse = {} + +export type Map = { + kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" + name: string, + dims: number, + vals: { number }, -- per point: vals[point * dims + c + 1] + has: { [number]: boolean }, + mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values +} +export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +export type Layer = { + index: number, + name: string?, + parent: number?, + pivot: { number }, + pts: { number }, -- x, y, z flat + polys: { Poly }, + maps: { Map }, + implicit: boolean?, -- the layer before any LAYR +} +export type Block = { + kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB) + ordinal: string, + channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP + enabled: boolean, + opacity: number, + projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV + axis: number?, + clip: number?, + file: string?, -- LWOB: the TIMG path + uvmap: string?, + wrap: { number }?, + negative: boolean?, +} +export type Surface = { + name: string, + values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + color: { number }, + side: number, + vcol: { name: string, kind: string, intensity: number }?, + blocks: { Block }, + source: string?, +} +export type Model = { + version: string, -- "LWO2" | "LWOB" | "LXOB" + tags: { string }, + layers: { Layer }, + surfaces: { Surface }, + clips: { [number]: string }, -- clip index -> path + skipped: { [string]: number }, + corners: number, +} + +local MAP_KINDS: { [string]: string } = { + TXUV = "uv", + RGB = "color", + RGBA = "color", + WGHT = "weight", + MNVW = "weight", + NORM = "normal", + MORF = "morph", + SPOT = "spot", +} + +-- ------------------------------------------------------------------------------------------------ primitives +-- S0: a NUL-terminated string padded to an even length +local function s0(r: Bytes.Reader): string + local start = r.pos + local s = r:cstring() + if (r.pos - start) % 2 == 1 and r.pos < r.limit then + r.pos += 1 + end + return s +end + +-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +local function vx(r: Bytes.Reader): number + if r:peekU8() == 0xFF then + return r:u32be() - 0xFF000000 + end + return r:u16be() +end + +local function id4(r: Bytes.Reader): string + local s = r:string(4) + return (string.gsub(s, " +$", "")) +end + +-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) + while p + 6 <= e do + local id = buffer.readstring(buf, p, 4) + local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5) + local body = p + 6 + local avail = math.min(n, e - body) + f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail)) + p = body + n + (n % 2) + end +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function newLayer(index: number): Layer + return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} } +end + +local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? + local n = r:remaining() // 12 + if #layer.pts // 3 + n > limit then + return "limit: more than " .. limit .. " points" + end + local pts = layer.pts + local k = #pts + for _ = 1, n * 3 do + k += 1 + pts[k] = r:f32be() + end + return nil +end + +-- POLS (LWO2): returns nil or an error +local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 2 do + local n = bit32.band(r:u16be(), 0x3FF) + local corners = table.create(n) + for i = 1, n do + local p = vx(r) + ptBase + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + if r.err then + return "truncated polygon list" + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + table.insert(polys, { kind = kind, surf = nil, corners = corners }) + end + return nil +end + +-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count) +local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 4 do + local n = r:u16be() + local corners = table.create(n) + for i = 1, n do + local p = r:u16be() + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + local surf = r:i16be() + if r.err then + return "truncated polygon list" + end + if surf < 0 then + surf = -surf + r:u16be() -- the detail polygon count: they follow as ordinary records + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + if n > 0 then + table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners }) + end + end + return nil +end + +local function findMap(layer: Layer, kind: string, name: string, dims: number): Map + for _, m in layer.maps do + if m.kind == kind and m.name == name then + return m + end + end + local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} } + table.insert(layer.maps, m) + return m +end + +local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number }) + local typ = id4(r) + local dims = r:u16be() + local name = s0(r) + local kind = MAP_KINDS[typ] + if r.err or not kind then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3 + if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local m = findMap(layer, kind, name, want) + local npts = #layer.pts // 3 + local npolys = #layer.polys + local vals, has, mad = m.vals, m.has, m.mad + while r:remaining() >= 2 do + local p = vx(r) + ptBase + local f = if perPoly then vx(r) + polyBase else -1 + local v = table.create(want, 1) + for c = 1, dims do + local x = r:f32be() + if c <= want then + v[c] = x + end + end + if r.err then + break + end + if p < npts then + if perPoly then + if f < npolys then + local row = mad[f] + if not row then + row = {} + mad[f] = row + end + row[p] = v + end + else + has[p] = true + for c = 1, want do + vals[p * want + c] = v[c] + end + end + end + end +end + +local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number) + local typ = id4(r) + if typ ~= "SURF" and typ ~= "MATR" then + return + end + local polys = layer.polys + while r:remaining() >= 4 do + local f = vx(r) + polyBase + local tag = r:u16be() + if r.err then + break + end + local poly = polys[f + 1] + if poly then + poly.surf = tag + end + end +end + +-- ------------------------------------------------------------------------------------------------ surfaces +local function newSurface(name: string): Surface + return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil } +end + +local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } + +local function readBlock(r: Bytes.Reader, surf: Surface) + -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + if r:remaining() < 6 then + return + end + local kind = id4(r) + local hn = r:u16be() + local hend = math.min(r.pos + hn, r.limit) + local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 } + local hr = Bytes.reader(r.buf, r.pos, hend - r.pos) + blk.ordinal = s0(hr) + subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader) + if id == "CHAN" then + blk.channel = id4(sr) + elseif id == "ENAB" then + blk.enabled = sr:u16be() ~= 0 + elseif id == "OPAC" then + sr:u16be() + blk.opacity = sr:f32be() + elseif id == "NEGA" then + blk.negative = sr:u16be() ~= 0 + elseif id == "AXIS" then + blk.axis = sr:u16be() + end + end) + subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader) + if id == "PROJ" then + blk.projection = sr:u16be() + elseif id == "AXIS" then + blk.axis = sr:u16be() + elseif id == "IMAG" then + blk.clip = vx(sr) + elseif id == "VMAP" then + blk.uvmap = s0(sr) + elseif id == "WRAP" then + blk.wrap = { sr:u16be(), sr:u16be() } + end + end) + table.insert(surf.blocks, blk) +end + +local function readSurface(r: Bytes.Reader, surfaces: { Surface }) + local name = s0(r) + local source = s0(r) + local surf = newSurface(name) + if source ~= "" then + for _, s in surfaces do + if s.name == source then + surf.values = table.clone(s.values) + surf.color = table.clone(s.color) + surf.side = s.side + surf.vcol = s.vcol + surf.blocks = table.clone(s.blocks) + break + end + end + surf.source = source + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:f32be(), sr:f32be(), sr:f32be() } + if not sr.err then + surf.color = c + end + elseif SURF_VALUES[id] then + local v = sr:f32be() + if not sr.err then + surf.values[id] = v + end + elseif id == "SIDE" then + surf.side = sr:u16be() + elseif id == "VCOL" then + local intensity = sr:f32be() + vx(sr) + local kind = id4(sr) + local vname = s0(sr) + if not sr.err then + surf.vcol = { name = vname, kind = kind, intensity = intensity } + end + elseif id == "BLOK" then + readBlock(sr, surf) + end + end) + table.insert(surfaces, surf) +end + +-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks +local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" } +local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" } +local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" } +local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 } + +local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface }) + local surf = newSurface(s0(r)) + local tex: Block? = nil + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 } + if not sr.err then + surf.color = c + end + elseif B_VALUES[id] then + local v = sr:u16be() + if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then + surf.values[B_VALUES[id]] = v / 256 + end + elseif B_FLOATS[id] then + local v = sr:f32be() + if not sr.err then + surf.values[B_FLOATS[id]] = v + surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one + end + elseif id == "GLOS" then + local v = sr:u16be() + if not sr.err then + -- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness + surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1) + end + elseif id == "SMAN" then + surf.values.SMAN = sr:f32be() + elseif id == "FLAG" then + local fl = sr:u16be() + if bit32.band(fl, 0x100) ~= 0 then + surf.side = 3 + end + elseif B_TEX[id] then + local desc = sr:cstring() + local proj: number? = nil + for word, v in B_PROJ do + if string.find(desc, word, 1, true) then + proj = v + end + end + local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj } + table.insert(surf.blocks, blk) + tex = blk + elseif id == "TIMG" and tex then + local path = sr:cstring() + if path ~= "" and path ~= "(none)" then + tex.file = path + end + elseif id == "TFLG" and tex then + local fl = sr:u16be() + tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2 + tex.negative = bit32.band(fl, 16) ~= 0 + elseif id == "TVAL" and tex then + tex.opacity = sr:u16be() / 256 + end + end) + for k in surf.values do + if string.sub(k, -1) == "!" then + surf.values[k] = nil + end + end + table.insert(surfaces, surf) +end + +local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number }) + local index = r:u32be() + if r.err then + return + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "STIL" then + clips[index] = s0(sr) + elseif id == "ISEQ" then + local digits = sr:u8() + sr:u8() + local offset = sr:i16be() + sr:u16be() + local start = sr:i16be() + sr:u16be() + local prefix = s0(sr) + local suffix = s0(sr) + if not sr.err then + clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix + end + elseif id == "XREF" then + refs[index] = sr:u32be() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ the file +-- parse(buf, from, limit, opts) -> Model | nil, message +function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) + local version = buffer.readstring(buf, from + 8, 4) + local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) + local e = math.min(limit, from + 8 + declared) + local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 } + local layer = newLayer(0) + layer.implicit = true + table.insert(model.layers, layer) + local ptBase, polyBase = 0, 0 + local budget = { maxCorners } + local refs: { [number]: number } = {} + local lwob = version == "LWOB" + local list = Chunks.walk(buf, from + 12, e, Chunks.IFF) + for _, c in list do + local id = c.id + local r = Bytes.reader(buf, c.offset, c.avail) + local err: string? = nil + if id == "TAGS" or id == "SRFS" then + while r:remaining() > 0 do + table.insert(model.tags, s0(r)) + end + elseif id == "LAYR" and not lwob then + local index = r:u16be() + r:u16be() -- flags (hidden) + local px, py, pz = r:f32be(), r:f32be(), r:f32be() + local name = s0(r) + local parent: number? = if r:remaining() >= 2 then r:u16be() else nil + if r.err then + return nil, "truncated LAYR chunk" + end + if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then + table.remove(model.layers, #model.layers) + end + layer = newLayer(index) + layer.name = name + layer.parent = if parent == 0xFFFF then nil else parent + layer.pivot = { px, py, pz } + table.insert(model.layers, layer) + ptBase, polyBase = 0, 0 + elseif id == "PNTS" then + ptBase = #layer.pts // 3 + err = readPoints(r, layer, maxCorners) + elseif id == "POLS" then + polyBase = #layer.polys + if lwob then + err = readPolysB(r, layer, budget) + else + local kind = id4(r) + if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then + err = readPolys(r, layer, kind, ptBase, budget) + else + -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + local before = #layer.polys + err = readPolys(r, layer, kind, ptBase, budget) + model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before + end + end + elseif id == "VMAP" or id == "VMAD" then + readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped) + elseif id == "PTAG" then + readPtag(r, layer, polyBase) + elseif id == "SURF" then + if lwob then + readSurfaceB(r, model.surfaces) + else + readSurface(r, model.surfaces) + end + elseif id == "CLIP" then + readClip(r, model.clips, refs) + end + if err then + return nil, err + end + end + for index, target in refs do + if model.clips[index] == nil and model.clips[target] then + model.clips[index] = model.clips[target] + end + end + model.corners = maxCorners - budget[1] + return model, nil +end + +return Parse diff --git a/src/Formats/model/lwo/init.luau b/src/Formats/model/lwo/init.luau new file mode 100644 index 0000000..4b77577 --- /dev/null +++ b/src/Formats/model/lwo/init.luau @@ -0,0 +1,86 @@ +--!strict +-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from +-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. +-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / +-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and +-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: +-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the +-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has +-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces +-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> +-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, +-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: +-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding +-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. +-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / +-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/model/lwo/Parse") +local Build = require("@formats/model/lwo/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Lwo = { + name = "lwo", + category = "model", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more points / polygon corners (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ constants +local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lwo.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local v = r:peek(4, 8) + return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 12 then + return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base) + end + if r:peek(4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base) + end + local v = r:peek(4, 8) + if v == "LWO3" then + return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8) + end + if not VERSIONS[v] then + return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8) + end + local maxCorners = opts and opts.maxVertices or 2 ^ 25 + local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model)) + end + if not model then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, model, opts) + if not ok2 then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + return scene, nil +end + +return Lwo diff --git a/tests/model/lwo.luau b/tests/model/lwo.luau new file mode 100644 index 0000000..36f202b --- /dev/null +++ b/tests/model/lwo.luau @@ -0,0 +1,315 @@ +-- model/lwo tests: assimp's LightWave test models (LWO2, LWOB, Modo LXOB) against assimp (meshes per layer and +-- surface, polygons, corners, materials, world bounds); layer hierarchy and pivots, UV / colour / normal maps, +-- surfaces and image blocks; a hand-built LWO2 (VMAD splits, MORF / SPOT targets, weight maps, lines, points, skipped +-- curves, PTCH flag, derived surface, XREF clip); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/lwo.py. +local T = require("@tests/T") +local Lwo = require("@formats/model/lwo") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/lwo_cases") + +local t = T.suite("lwo") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Lwo.decode(Bytes.reader(b), opts) +end + +t:eq(Lwo.name, "lwo", "name") +t:eq(Lwo.category, "model", "category") +t:check(Lwo.caps.decode and not Lwo.caps.encode, "caps") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- assimp's counts: one mesh per (layer, surface), polygons, corners +local function counts(scene: any): (number, number, number) + local meshes, faces, corners = 0, 0, 0 + for _, m in scene.meshes do + local mats = {} + for _, p in m.primitives do + if not mats[p.material] then + mats[p.material] = true + meshes += 1 + end + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + corners += n + faces += if p.mode == "polygons" then p.faces.count elseif p.mode == "lines" then n // 2 elseif p.mode == "points" then n else n // 3 + end + end + return meshes, faces, corners +end + +local function find(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ assimp +local checked, scenes = 0, {} +for i, c in Cases do + local a = c.assimp + local scene, err = decode(c.data, { triangulate = false }) + if a.failed then + t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if scene then + scenes[i] = scene + local meshes, faces, corners = counts(scene) + -- LXOB / LWOB files: assimp's material and surface handling differs (MATR tags, flattened detail polygons) + t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": polygons (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local ok = lo ~= nil + for k = 1, 3 do + ok = ok and near(lo[k], a.min[k], 1e-4) and near(hi[k], a.max[k], 1e-4) + end + t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-")) + end + -- triangulated: the same corners as triangles + local tri = decode(c.data) + t:check(tri and tri.meshes[1] and tri.meshes[1].primitives[1].mode ~= "polygons", c.name .. ": triangulated by default") + checked += 1 + end + end +end +t:note("%d files checked against assimp", checked) + +-- ------------------------------------------------------------------------------------------------ details +do + local c = find("models/LWO2/hierarchy.lwo") + local s = decode(c.data) + local byName = {} + for i, n in s.nodes do + byName[n.name] = i + end + local root, child0, grand = byName.RootOfHierarchy, byName.ChildOfRoot0, byName.GrandChildOfRoot0 + t:check(root and child0 and grand and byName.ChildOfRoot1, "hierarchy: layer names") + t:check(table.find(s.roots, root) ~= nil and #s.roots == 1, "hierarchy: one root layer") + t:check(table.find(s.nodes[root].children, child0) ~= nil, "hierarchy: ChildOfRoot0 under RootOfHierarchy") + t:check(table.find(s.nodes[child0].children, grand) ~= nil, "hierarchy: GrandChildOfRoot0 under ChildOfRoot0") + local p = s.nodes[child0].extras.lwo.pivot + t:check(p and #p == 3, "hierarchy: pivot kept in extras") + -- weight maps -> _WEIGHT_n (no skeleton in LWO) + local prim = s.meshes[s.nodes[root].mesh].primitives[1] + t:check(prim.attributes._WEIGHT_0 and prim.attributes._WEIGHT_1, "hierarchy: weight maps as _WEIGHT_n") + t:check(prim.extras.lwo.maps._WEIGHT_0 ~= nil, "hierarchy: weight map names") +end +do + local c = find("models/LWO2/boxuv.lwo") + local s = decode(c.data) + local mat = s.materials[1] + t:check(mat.baseColorTexture, "boxuv: COLR image block -> baseColorTexture") + local tex = s.textures[mat.baseColorTexture.texture] + t:eq(tex.uri, "boxuv.png", "boxuv: texture uri") + t:eq(tex.mime, "image/png", "boxuv: texture mime") + local prim = s.meshes[1].primitives[1] + local uv = prim.attributes.TEXCOORD_0 + t:check(uv and uv.count == prim.attributes.POSITION.count, "boxuv: TEXCOORD_0") + local inRange = true + local get = assert(Types.Scene.reader(uv)) + for i = 0, uv.count - 1 do + local u, v = get(i, 0), get(i, 1) + inRange = inRange and u >= -1e-6 and u <= 1 + 1e-6 and v >= -1e-6 and v <= 1 + 1e-6 + end + t:check(inRange, "boxuv: uvs in 0..1") +end +do + local c = find("models/LWO2/box_2vc_1unused.lwo") + local s = decode(c.data) + local any = false + for _, p in s.meshes[1].primitives do + any = any or (p.attributes.COLOR_0 ~= nil or p.attributes._COLOR_0 ~= nil) + end + t:check(any, "box_2vc: colour maps") + local mat = s.materials[1] + t:check(mat.extras.lwo.vcol ~= nil, "box_2vc: surface VCOL map name") +end +do + local c = find("models/LWO2/ModoExport_vertNormals.lwo") + local s = decode(c.data) + local prim = s.meshes[1].primitives[1] + t:check(prim.attributes.NORMAL, "Modo NORM map -> NORMAL") + local get = assert(Types.Scene.reader(prim.attributes.NORMAL)) + local len = math.sqrt(get(0, 0) ^ 2 + get(0, 1) ^ 2 + get(0, 2) ^ 2) + t:check(near(len, 1, 1e-3), "Modo normals are unit length") +end +do + local c = find("models/LWO2/Subdivision.lwo") + local s = decode(c.data) + t:check(s.meshes[1].primitives[1].extras.lwo.subdivision == true, "PTCH cage flagged") + local lx = find("models/LXOB_Modo/sphereWithVertMap.lxo") + local sx = decode(lx.data) + t:eq(sx.meta.source.version, "LXOB", "LXOB version") + t:check(sx.meshes[1].primitives[1].attributes.NORMAL, "LXOB normals") + local lb = find("models/LWOB/sphere_with_mat_gloss_10pc.lwo") + local sb = decode(lb.data) + t:eq(sb.meta.source.version, "LWOB", "LWOB version") + t:check(sb.materials[1].extras.lwo.glos ~= nil, "LWOB glossiness") +end + +-- ------------------------------------------------------------------------------------------------ hand-built LWO2 +local function be16(n: number): string + return string.char(bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255)) +end +local function be32(n: number): string + return be16(bit32.rshift(n, 16)) .. be16(bit32.band(n, 0xFFFF)) +end +local function f4(x: number): string + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return be32(buffer.readu32(b, 0)) +end +local function s0(s: string): string + s ..= "\0" + return if #s % 2 == 1 then s .. "\0" else s +end +local function chunk(id: string, body: string): string + return id .. be32(#body) .. body .. (if #body % 2 == 1 then "\0" else "") +end +local function sub(id: string, body: string): string + return id .. be16(#body) .. body .. (if #body % 2 == 1 then "\0" else "") +end +local function form(body: string): string + return "FORM" .. be32(#body + 4) .. "LWO2" .. body +end + +local function quadFile(): string + local pts = "" + for _, p in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 0 } } do + pts ..= f4(p[1]) .. f4(p[2]) .. f4(p[3]) + end + local pols = "FACE" .. be16(4) .. be16(0) .. be16(1) .. be16(2) .. be16(3) -- 0: quad + .. be16(2) .. be16(4) .. be16(5) -- 1: a line + .. be16(1) .. be16(5) -- 2: a point + local curv = "CURV" .. be16(2) .. be16(0) .. be16(4) -- 3: skipped + local ptch = "PTCH" .. be16(3) .. be16(0) .. be16(1) .. be16(2) -- 4: a patch + local uv = "TXUV" .. be16(2) .. s0("UV") + for i, v in { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } } do + uv ..= be16(i - 1) .. f4(v[1]) .. f4(v[2]) + end + local vmad = "TXUV" .. be16(2) .. s0("UV") .. be16(0) .. be16(0) .. f4(0.5) .. f4(0.25) -- point 0 in polygon 0 + local morf = "MORF" .. be16(3) .. s0("up") .. be16(2) .. f4(0) .. f4(0) .. f4(1) + local spot = "SPOT" .. be16(3) .. s0("moved") .. be16(1) .. f4(1) .. f4(2) .. f4(0) + local wght = "WGHT" .. be16(1) .. s0("bone") .. be16(3) .. f4(0.75) + local tags = s0("Base") .. s0("Child") + local base = s0("Base") .. s0("") .. sub("COLR", f4(1) .. f4(0) .. f4(0) .. be16(0)) .. sub("TRAN", f4(0.25) .. be16(0)) .. sub("SIDE", be16(3)) + local blok = sub("IMAP", s0("\128") .. sub("CHAN", "COLR") .. sub("ENAB", be16(1))) .. sub("PROJ", be16(5)) .. sub("IMAG", be16(2)) .. sub("VMAP", s0("UV")) + local child = s0("Child") .. s0("Base") .. sub("LUMI", f4(0.5) .. be16(0)) .. sub("BLOK", blok) + local ptag = "SURF" .. be16(0) .. be16(0) .. be16(1) .. be16(1) .. be16(2) .. be16(1) + local ptag2 = "SURF" .. be16(0) .. be16(1) + return form(chunk("TAGS", tags) .. chunk("LAYR", be16(0) .. be16(0) .. f4(0.5) .. f4(0) .. f4(0) .. s0("Main")) .. chunk("PNTS", pts) + .. chunk("VMAP", uv) .. chunk("VMAP", morf) .. chunk("VMAP", spot) .. chunk("VMAP", wght) + .. chunk("POLS", pols) .. chunk("PTAG", ptag) .. chunk("VMAD", vmad) .. chunk("POLS", curv) .. chunk("POLS", ptch) .. chunk("PTAG", ptag2) + .. chunk("CLIP", be32(1) .. sub("STIL", s0("C:\\images\\Wood.PNG"))) .. chunk("CLIP", be32(2) .. sub("XREF", be32(1) .. s0("ref"))) + .. chunk("SURF", base) .. chunk("SURF", child) + .. chunk("LAYR", be16(1) .. be16(0) .. f4(0.5) .. f4(1) .. f4(2) .. s0("Sub") .. be16(0))) +end + +do + local data = quadFile() + local s, err = decode(data, { triangulate = false }) + t:check(s, "hand-built: decode " .. tostring(err)) + t:eq(#s.nodes, 2, "hand-built: two layers") + local main, subl = s.nodes[1], s.nodes[2] + t:eq(main.name, "Main", "hand-built: layer name") + t:check(table.find(main.children, 2) ~= nil and #s.roots == 1, "hand-built: Sub is a child of Main") + t:check(main.translation and main.translation[1] == 0.5, "hand-built: Main pivot translation") + t:check(subl.translation and subl.translation[2] == 1 and subl.translation[3] == -2, "hand-built: Sub pivot relative to Main, z negated") + t:eq(s.meta.source.skipped.CURV, 1, "hand-built: curve skipped and counted") + local mesh = s.meshes[main.mesh] + local modes = {} + for _, p in mesh.primitives do + modes[#modes + 1] = p.mode .. "/" .. p.material .. (if p.extras.lwo.subdivision then "/patch" else "") + end + t:eq(table.concat(modes, " "), "polygons/1 polygons/2/patch lines/2 points/2", "hand-built: primitives by surface and kind") + local quad = mesh.primitives[1] + t:eq(quad.attributes.POSITION.count, 4, "hand-built: quad vertices") + -- winding reversed, positions relative to the pivot, z negated + local idx = {} + for k = 0, 3 do + idx[k + 1] = buffer.readu32(quad.indices.data, k * 4) + end + local P = assert(Types.Scene.reader(quad.attributes.POSITION)) + local UV = assert(Types.Scene.reader(quad.attributes.TEXCOORD_0)) + t:eq(P(idx[1], 0), -0.5, "hand-built: x relative to the pivot") + t:eq(P(idx[2], 0), -0.5, "hand-built: winding reversed (second corner is point 3)") + t:eq(P(idx[2], 1), 1, "hand-built: second corner y") + t:eq(UV(idx[1], 0), 0.5, "hand-built: VMAD u") + t:eq(UV(idx[1], 1), 0.75, "hand-built: VMAD v flipped") + t:eq(UV(idx[3], 1), 0, "hand-built: VMAP v flipped (point 2: 1 -> 0)") + t:check(quad.targets and #quad.targets == 2, "hand-built: MORF + SPOT targets") + local T1 = assert(Types.Scene.reader(quad.targets[1].POSITION)) + local T2 = assert(Types.Scene.reader(quad.targets[2].POSITION)) + t:eq(T1(idx[3], 2), -1, "hand-built: MORF delta (z negated)") + t:eq(T2(idx[4], 1), 2, "hand-built: SPOT -> delta (point 1: y 0 -> 2)") + t:eq(mesh.weights and #mesh.weights, 2, "hand-built: mesh weights") + t:eq(mesh.extras.targetNames[2], "moved", "hand-built: target names") + local W = assert(Types.Scene.reader(quad.attributes._WEIGHT_0)) + t:eq(W(idx[2], 0), 0.75, "hand-built: weight map value (point 3)") + local base, child = s.materials[1], s.materials[2] + t:eq(base.baseColor[1], 1, "hand-built: COLR") + t:check(near(base.baseColor[4], 0.75, 1e-6) and base.alphaMode == "blend", "hand-built: TRAN -> alpha") + t:check(base.doubleSided, "hand-built: SIDE 3") + t:check(child.doubleSided and child.baseColor[1] == 1, "hand-built: derived surface copies its source") + t:check(near(child.emissive[1], 0.5, 1e-6), "hand-built: LUMI -> emissive") + t:check(child.baseColorTexture and child.baseColorTexture.texCoord == 0, "hand-built: image block via XREF clip") + t:eq(s.textures[1].uri, "Wood.PNG", "hand-built: texture uri is the file name") + t:eq(s.textures[1].extras.lwo.path, "C:\\images\\Wood.PNG", "hand-built: full path in extras") + local tri = decode(data) + t:eq(tri.meshes[1].primitives[1].indices.count, 6, "hand-built: quad fan-triangulated") + -- triangulated quads keep the right facing: +z after the conversion (LightWave clockwise from -z) + local tp = tri.meshes[1].primitives[1] + local TP = assert(Types.Scene.reader(tp.attributes.POSITION)) + local a, b, c = buffer.readu32(tp.indices.data, 0), buffer.readu32(tp.indices.data, 4), buffer.readu32(tp.indices.data, 8) + local ux, uy = TP(b, 0) - TP(a, 0), TP(b, 1) - TP(a, 1) + local vx, vy = TP(c, 0) - TP(a, 0), TP(c, 1) - TP(a, 1) + t:check(ux * vy - uy * vx < 0, "hand-built: facing kept (LightWave +z normal -> glTF -z)") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("FORM\0\0\0\4LWO3") + t:check(e1 and e1.code == Err.UNSUPPORTED, "LWO3: " .. tostring(e1)) + local _, e2 = decode("FORM\0\0\0\4ILBM") + t:check(e2 and e2.code == Err.CORRUPT, "not LWO: " .. tostring(e2)) + local _, e3 = decode("FORM") + t:check(e3 and e3.code == Err.TRUNCATED, "short: " .. tostring(e3)) + local _, e4 = decode(quadFile(), { maxVertices = 3 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local bad = form(chunk("PNTS", f4(0) .. f4(0) .. f4(0)) .. chunk("POLS", "FACE" .. be16(3) .. be16(0) .. be16(1) .. be16(2))) + local _, e5 = decode(bad) + t:check(e5 and e5.code == Err.CORRUPT, "point index out of range: " .. tostring(e5)) + t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring(quadFile()))), 1, "sniff") + t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { quadFile() } + for _, c in Cases do + if #c.data < 30000 and #samples < 16 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Lwo.decode(Bytes.reader(b), { triangulate = false }) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 12 }) +end + +t:done() diff --git a/tools/fixtures/lwo.py b/tools/fixtures/lwo.py new file mode 100644 index 0000000..420bd15 --- /dev/null +++ b/tools/fixtures/lwo.py @@ -0,0 +1,41 @@ +# LightWave object fixtures (tools/fixtures.py): assimp's LWO test models (LWO2, LWOB, Modo LXOB; models and +# models-nonbsd, read from the nixpkgs assimp source, never committed) with assimp's view of them (`assimp info -r`: +# meshes, polygons, corners, materials, nodes; world bounds from assimp's PreTransformVertices export). +# tests/gen/lwo_cases.luau { name, data, assimp = { meshes, faces, vertices, materials, nodes, min, max } } +import importlib.util, os + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +INPUTS = ["src/Formats/model/lwo", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def generate(ctx): + M = module(ctx, "_model_ref") + fbx = module(ctx, "fbx") # assimp_src, ptv_bounds + tmp = M.tempdir() + src = fbx.assimp_src(ctx) + cases = [] + for sub in ("models/LWO", "models-nonbsd/LWO"): + d0 = os.path.join(src, "test", sub) + for root, _, files in sorted(os.walk(d0)): + for f in sorted(files): + if f.lower().endswith((".lwo", ".lxo")): + p = os.path.join(root, f) + cases.append({"name": sub.split("/")[0] + "/" + os.path.relpath(p, d0), "path": p}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + for c, a in zip(cases, infos): + a.pop("min", None) + a.pop("max", None) + a.pop("perMesh", None) + if not a.get("failed"): + a.update(fbx.ptv_bounds(ctx, c["path"], tmp)) + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("lwo_cases", cases) From 4c74171631c6225d3b4eb7168432c9a11d877746 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:04:40 -0500 Subject: [PATCH 08/54] ws-3d3: model/pmx: MikuMikuDance PMX 2.0 / 2.1 and PMD 1.0 reader (weights, materials, bones + skin, vertex morphs -> targets, other morphs / physics in extras); tests against assimp and synthetic models --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/pmx/Build.luau | 307 +++++++++++++++++++++++ src/Formats/model/pmx/Pmd.luau | 339 +++++++++++++++++++++++++ src/Formats/model/pmx/Read.luau | 411 +++++++++++++++++++++++++++++++ src/Formats/model/pmx/init.luau | 77 ++++++ tests/model/pmx.luau | 263 ++++++++++++++++++++ tools/fixtures/_pmx_writer.py | 265 ++++++++++++++++++++ tools/fixtures/pmx.py | 77 ++++++ 9 files changed, 1752 insertions(+) create mode 100644 src/Formats/model/pmx/Build.luau create mode 100644 src/Formats/model/pmx/Pmd.luau create mode 100644 src/Formats/model/pmx/Read.luau create mode 100644 src/Formats/model/pmx/init.luau create mode 100644 tests/model/pmx.luau create mode 100644 tools/fixtures/_pmx_writer.py create mode 100644 tools/fixtures/pmx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..f3846c1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,6 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | pmx | .pmx .pmd | yes | - | materials: true, skins: true, morphTargets: true, pmd: true | `tests/model/pmx.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..a414daf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -446,6 +446,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "pmx", + category = "model", + path = "model/pmx", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, + load = function() + return require("@formats/model/pmx") + end, + }, { name = "stl", category = "model", diff --git a/src/Formats/model/pmx/Build.luau b/src/Formats/model/pmx/Build.luau new file mode 100644 index 0000000..213cfd9 --- /dev/null +++ b/src/Formats/model/pmx/Build.luau @@ -0,0 +1,307 @@ +--!strict +-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up, +-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed +-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with +-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as +-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex +-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative +-- translation each) and one skin with translation-only inverse bind matrices. +local Types = require("@formats/Types") + +local Build = {} + +local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32 +local S = Types.Scene + +local SPHERE = { [0] = "off", "multiply", "add", "subtexture" } +local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve +local function fetcher(opts: any): (string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + local slash = string.gsub(uri, "\\", "/") + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, slash) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +local function lh(v: { number }?): { number }? + return if v then { v[1], v[2], -v[3] } else nil +end + +-- the scene index of a file texture index (0-based, -1 = none) +local function texIndex(m: any, i: number?): number? + return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil +end + +local function material(m: any, mat: any): Types.Material + local out = S.material(mat.name) + local d = mat.diffuse + out.baseColor = { d[1], d[2], d[3], d[4] } + out.metallic = 0 + out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1) + out.doubleSided = bit32.btest(mat.flags, 0x01) + if d[4] < 1 then + out.alphaMode = "blend" + end + local t = texIndex(m, mat.texture) + if t then + out.baseColorTexture = { texture = t } + end + local x: { [string]: any } = { + nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient, + flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize, + sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode, + toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count, + } + if mat.toonShared then + x.toonShared = mat.toonShared + x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1) + end + out.extras = { pmx = x } + return out +end + +-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root +local function parents(bones: { any }): { number } + local nb = #bones + local par = table.create(nb, 0) + for i, b in bones do + local p = b.parent + if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then + par[i] = p + 1 + end + end + for i = 1, nb do + local seen, j, steps = {}, i, 0 + while par[j] ~= 0 and steps <= nb do + seen[j] = true + j = par[j] + steps += 1 + if seen[j] then + par[i] = 0 + break + end + end + end + return par +end + +-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered +local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive + local map: { [number]: number } = {} + local verts: { number } = {} + local ind = S.accessor(nil, "u32", 1, n) + for t = 0, n // 3 - 1 do + -- reversed winding: a, c, b + for c = 0, 2 do + local src = readu32(m.indices, (first + t * 3 + c) * 4) + local v = map[src] + if not v then + v = #verts + verts[v + 1] = src + map[src] = v + end + buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v) + end + end + local nv = #verts + local nb = #m.bones + local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv) + local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv) + local edge = S.accessor(nil, "f32", 1, nv) + local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge } + if nb > 0 then + attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we + end + local uvas = {} + for a = 1, #m.uva do + uvas[a] = S.accessor(nil, "f32", 4, nv) + attrs["_UVA" .. a] = uvas[a] + end + local sd: { Types.Accessor }? = nil + local deform: Types.Accessor? = nil + if sdef then + sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) } + attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3] + deform = S.accessor(nil, "u8", 1, nv) + attrs._DEFORM = deform + end + for v = 0, nv - 1 do + local src = verts[v + 1] + for c = 0, 2 do + local sgn = if c == 2 then -1 else 1 + writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4)) + writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4)) + end + buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8) + buffer.copy(edge.data, v * 4, m.edge, src * 4, 4) + for a, acc in uvas do + buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16) + end + -- weights: invalid bones get weight 0, the rest is normalized + local sum = 0 + local js, ws = table.create(4, 0), table.create(4, 0) + for c = 0, 3 do + local j = readi32(m.joints, src * 16 + c * 4) + local w = readf32(m.weights, src * 16 + c * 4) + if j >= 0 and j < nb and w > 0 and w == w then + js[c + 1], ws[c + 1] = j, w + sum += w + end + end + for c = 0, 3 do + buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1]) + writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0)) + end + if sd and deform then + buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src)) + if m.sdef then + for q = 0, 2 do + for c = 0, 2 do + local x = readf32(m.sdef, src * 36 + q * 12 + c * 4) + writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + end + end + local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" } + if #morphs > 0 then + local targets: { { [string]: Types.Accessor } } = {} + for k, mo in morphs do + local d = S.accessor(nil, "f32", 3, nv) + for o, src in mo.vertices do + local v = map[src] + if v then + for c = 0, 2 do + local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4) + writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x) + end + end + end + targets[k] = { POSITION = d } + end + prim.targets = targets + end + return prim +end + +function Build.scene(m: any, opts: any): (any, ...any) + local scene = S.new() + scene.meta.up = "y" + local fetch = fetcher(opts) + for i, path in m.textures do + local uri = string.gsub(path, "\\", "/") + local tex: Types.Texture = { name = path, uri = uri } + local data = fetch(path) + if data then + tex.data = data + end + local ext = string.match(uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + scene.textures[i] = tex + end + for i, mat in m.materials do + scene.materials[i] = material(m, mat) + end + + -- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs) + local vmorphs, names, others = {}, {}, {} + local wantMorphs = not (opts and opts.morphs == false) + for _, mo in m.morphs do + if mo.type == 1 and wantMorphs then + table.insert(vmorphs, mo) + table.insert(names, mo.name) + elseif mo.type ~= 1 then + table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets }) + end + end + local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28 + if #vmorphs * m.vertexCount * 12 > maxBytes then + return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit" + end + local sdef = false + for v = 0, m.vertexCount - 1 do + local k = buffer.readu8(m.deform, v) + if k == 3 or k == 4 then + sdef = true + break + end + end + local mesh: Types.Mesh = { name = m.name, primitives = {} } + local first = 0 + for i, mat in m.materials do + local n = mat.count + if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then + return nil, string.format("material %d: %s face indices past the face list", i, tostring(n)) + end + local prim = primitive(m, first, n, vmorphs, sdef) + prim.material = i + table.insert(mesh.primitives, prim) + first += n + end + if first < m.indexCount then + -- faces no material covers + table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef)) + end + mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil } + if #vmorphs > 0 then + mesh.weights = table.create(#vmorphs, 0) + end + scene.meshes[1] = mesh + + -- nodes: 1 = the model, 2 = the mesh, then one per bone + scene.nodes[1] = { name = m.name, children = { 2 } } + scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 } + scene.roots[1] = 1 + local bones = m.bones + local nb = #bones + if nb > 0 then + local par = parents(bones) + local world: { { number } } = {} + for i, b in bones do + world[i] = lh(b.pos) or { 0, 0, 0 } + end + local ibm = S.accessor(nil, "f32", 16, nb) + ibm.matrix = true + local joints: { number } = {} + for i, b in bones do + local w, p = world[i], par[i] + local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] } + local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos } + x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik + scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } } + joints[i] = 2 + i + for c = 0, 15 do + local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0 + writef32(ibm.data, ((i - 1) * 16 + c) * 4, val) + end + end + for i = 1, nb do + local p = par[i] + table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i) + end + scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm } + scene.nodes[2].skin = 1 + end + scene.meta.source = { + format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment, + commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList, + softBodies = m.softBodies, toonTextures = m.toonTextures, + } + return scene +end + +return Build diff --git a/src/Formats/model/pmx/Pmd.luau b/src/Formats/model/pmx/Pmd.luau new file mode 100644 index 0000000..affdd3a --- /dev/null +++ b/src/Formats/model/pmx/Pmd.luau @@ -0,0 +1,339 @@ +--!strict +-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as +-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community +-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces, +-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to +-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in +-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in +-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") + +local Pmd = {} + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +local function ascii(s: string): boolean + return not string.find(s, "[\128-\255]") +end + +local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any) + if n * size > r.limit - r.pos then + return false, string.format("%d %s do not fit in the file", n, what) + end + return true +end + +function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("Pmd") then + return nil, "not a PMD file" + end + local version = r:f32le() + if version ~= 1 then + return nil, "unsupported: PMD version " .. tostring(version), "unsupported" + end + local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil } + m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256) + local buf = r.buf + + -- vertices: 38 bytes each + local nv = r:u32le() + if r.err then + return nil, "truncated", "truncated" + end + local ok, e = counted(r, nv, 38, "vertices") + if not ok then + return nil, e, "truncated" + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4) + for v = 0, nv - 1 do + local p = r.pos + v * 38 + buffer.copy(pos, v * 12, buf, p, 12) + buffer.copy(nrm, v * 12, buf, p + 12, 12) + buffer.copy(uv, v * 8, buf, p + 24, 8) + local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34) + local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100 + local single = b0 == b1 or w == 1 + buffer.writeu8(deform, v, if single then 0 else 1) + buffer.writei32(joints, v * 16, b0) + buffer.writei32(joints, v * 16 + 4, if single then -1 else b1) + buffer.writei32(joints, v * 16 + 8, -1) + buffer.writei32(joints, v * 16 + 12, -1) + buffer.writef32(weights, v * 16, if single then 1 else w) + buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w) + buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1) + end + r.pos += nv * 38 + m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge + + -- faces: u16 indices + local ni = r:u32le() + ok, e = counted(r, ni, 2, "face indices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + for i = 0, ni - 1 do + local x = buffer.readu16(buf, r.pos + i * 2) + if x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv) + end + buffer.writeu32(ind, i * 4, x) + end + r.pos += ni * 2 + m.indexCount, m.indices = ni, ind + + -- materials: 70 bytes each; texture names collected into the texture list + local nm = r:u32le() + ok, e = counted(r, nm, 70, "materials") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.textures = {} + local texIndex: { [string]: number } = {} + local function tex(name: string): number + if name == "" then + return -1 + end + local i = texIndex[name] + if not i then + table.insert(m.textures, name) + i = #m.textures - 1 + texIndex[name] = i + end + return i + end + m.materials = table.create(nm) + local toonIdx = {} + for i = 1, nm do + local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) } + local d = vec(r, 4) + mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3) + local toon, edgeFlag = r:u8(), r:u8() + mat.count = r:u32le() + local file = r:fixed(20) + mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0) + mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, "" + mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0 + for part in string.gmatch(file, "[^*]+") do + local ext = string.lower(string.match(part, "%.(%w+)$") or "") + if ext == "sph" or ext == "spa" then + mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2 + else + mat.texture = tex(part) + end + end + toonIdx[i] = toon + m.materials[i] = mat + end + + -- bones: 39 bytes each + local nb = r:u16le() + ok, e = counted(r, nb, 39, "bones") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { nameSjis = r:fixed(20) } + local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le() + b.pos = vec(r, 3) + b.parent = if parent == 0xFFFF then -1 else parent + b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 } + b.layer, b.pmdType, b.ikParent = 0, kind, ikParent + -- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled + b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10 + m.bones[i] = b + end + + -- IK chains + local nik = r:u16le() + for _ = 1, nik do + local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le() + local links = table.create(len) + for l = 1, len do + links[l] = { bone = r:u16le() } + end + if r.err then + return nil, "truncated", "truncated" + end + local b = m.bones[bone + 1] + if b then + b.flags = bit32.bor(b.flags, 0x20) + -- PMD's limit is in units of 4 radians (PMX stores radians) + b.ik = { target = target, loops = loops, limit = limit * 4, links = links } + end + end + + -- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it + local ns = r:u16le() + if r.err then + return nil, "truncated", "truncated" + end + m.morphs = {} + local base: { number } = {} + for s = 1, ns do + local name = r:fixed(20) + local n, panel = r:u32le(), r:u8() + ok, e = counted(r, n, 16, "skin vertices") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + if s == 1 and panel == 0 then + for o = 1, n do + base[o] = r:u32le() + r:skip(12) + end + else + local vi, deltas = table.create(n), buffer.create(n * 12) + for o = 1, n do + local k = r:u32le() + local v = base[k + 1] + if not v or v >= nv then + return nil, string.format("skin %d: base vertex %d out of range", s - 1, k) + end + vi[o] = v + buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12) + r:skip(12) + end + table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas }) + end + end + + -- display lists (skin list, bone group names, bone groups) + local nsd = r:u8() + r:skip(nsd * 2) + local ng = r:u8() + local groups: { { [string]: any } } = {} + for g = 1, ng do + groups[g] = { nameSjis = r:fixed(50), special = false, items = {} } + end + local nbd = r:u32le() + ok, e = counted(r, nbd, 3, "bone display entries") + if r.err or not ok then + return nil, e or "truncated", "truncated" + end + for _ = 1, nbd do + local bone, g = r:u16le(), r:u8() + local grp = groups[g] + if grp then + table.insert(grp.items, { bone = bone }) + end + end + m.frames = groups + + -- optional: English names, toon textures, physics + local function name(t: { [string]: any }, en: string?) + local raw = t.nameSjis or "" + t.nameEn = en + t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw + if ascii(raw) then + t.nameSjis = nil + end + end + local en: any = {} + if r.limit - r.pos >= 1 and r:u8() == 1 then + en.name, en.comment = r:fixed(20), r:fixed(256) + en.bones = table.create(nb) + for i = 1, nb do + en.bones[i] = r:fixed(20) + end + en.morphs = {} + for i = 1, #m.morphs do + en.morphs[i] = r:fixed(20) + end + en.groups = {} + for i = 1, ng do + en.groups[i] = r:fixed(50) + end + end + local model = { nameSjis = m.nameSjis } + name(model, en.name) + m.name, m.nameEn = model.name, en.name + m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment + if ascii(m.nameSjis) then + m.nameSjis = nil + end + for i, b in m.bones do + name(b, en.bones and en.bones[i]) + end + for i, mo in m.morphs do + name(mo, en.morphs and en.morphs[i]) + end + for i, g in groups do + name(g, en.groups and en.groups[i]) + end + local toons: { string } = {} + for i = 1, 10 do + toons[i] = string.format("toon%02d.bmp", i) + end + if r.limit - r.pos >= 1000 then + for i = 1, 10 do + toons[i] = r:fixed(100) + end + end + m.toonTextures = toons + for i, mat in m.materials do + local t = toonIdx[i] + if t < 10 then + if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then + mat.toonShared = t + else + mat.toon = tex(toons[t + 1]) + end + else + mat.toon = -1 + end + end + m.rigidBodies, m.jointsList = {}, {} + if r.limit - r.pos >= 4 then + local nr = r:u32le() + ok, e = counted(r, nr, 83, "rigid bodies") + if not ok then + return nil, e, "truncated" + end + for i = 1, nr do + local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + if b.bone == 0xFFFF then + b.bone = -1 + end + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj = r:u32le() + ok, e = counted(r, nj, 124, "joints") + if not ok then + return nil, e, "truncated" + end + for i = 1, nj do + local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Pmd diff --git a/src/Formats/model/pmx/Read.luau b/src/Formats/model/pmx/Read.luau new file mode 100644 index 0000000..cd7f90d --- /dev/null +++ b/src/Formats/model/pmx/Read.luau @@ -0,0 +1,411 @@ +--!strict +-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that +-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor. +-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices +-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes, +-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies, +-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices). +-- Never throws: returns nil, message[, kind]. +local Bytes = require("@formats/core/Bytes") +local Text = require("@formats/codecs/text/Text") + +local Read = {} + +export type Model = { [string]: any } + +local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32 + +-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none) +local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number + if size == 1 then + return if vertex then function() return r:u8() end else function() return r:i8() end + elseif size == 2 then + return if vertex then function() return r:u16le() end else function() return r:i16le() end + end + return function() return r:i32le() end +end + +local function vec(r: Bytes.Reader, n: number): { number } + local v: { number } = {} + for i = 1, n do + v[i] = r:f32le() + end + return v +end + +-- a count field: i32 >= 0 and at most remaining / minSize records +local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any) + local n = r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + if n < 0 then + return nil, "negative " .. what .. " count" + end + if n * minSize > r.limit - r.pos then + return nil, string.format("%d %s do not fit in the file", n, what), "truncated" + end + return n +end + +function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any) + if not r:match("PMX ") then + return nil, "not a PMX file" + end + local version = r:f32le() + local nglobals = r:u8() + if r.err then + return nil, "truncated", "truncated" + end + if version < 1.95 or version > 2.15 then + return nil, "unsupported: PMX version " .. tostring(version), "unsupported" + end + version = if version > 2.05 then 2.1 else 2.0 + if nglobals < 8 then + return nil, "only " .. nglobals .. " header globals" + end + local g: { number } = {} + for i = 1, nglobals do + g[i] = r:u8() + end + local utf8 = g[1] == 1 + if g[1] > 1 then + return nil, "unknown text encoding " .. g[1] + end + local uva = g[2] + if uva > 4 then + return nil, uva .. " additional UVs (at most 4)" + end + for i = 3, 8 do + if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then + return nil, "bad index size " .. g[i] + end + end + local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8] + local buf = r.buf + local function text(): string + local n = r:i32le() + if r.err or n < 0 or n > r.limit - r.pos then + r:need(r.limit - r.pos + 1) + return "" + end + local p = r.pos + r.pos += n + if utf8 then + return buffer.readstring(buf, p, n) + end + return Text.utf16(buf, p, n) + end + local vidx = indexReader(r, vsize, true) + local tidx = indexReader(r, tsize, false) + local midx = indexReader(r, msize, false) + local bidx = indexReader(r, bsize, false) + local moidx = indexReader(r, morsize, false) + local ridx = indexReader(r, rsize, false) + local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } } + m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text() + if r.err then + return nil, "truncated", "truncated" + end + + -- vertices: position, normal, uv, additional uvs, deform, edge scale + local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices") + if not nv then + return nil, e, k + end + local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24 + if nv > maxV then + return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit" + end + local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8) + local uvas = {} + for a = 1, uva do + uvas[a] = buffer.create(nv * 16) + end + local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16) + local edge = buffer.create(nv * 4) + local sdef: buffer? = nil + local writef32, writei32 = buffer.writef32, buffer.writei32 + for v = 0, nv - 1 do + if not r:need(32 + uva * 16 + 1) then + return nil, "truncated", "truncated" + end + local p = r.pos + for c = 0, 2 do + writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4)) + writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4)) + end + writef32(uv, v * 8, buffer.readf32(buf, p + 24)) + writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28)) + p += 32 + for a = 1, uva do + buffer.copy(uvas[a], v * 16, buf, p, 16) + p += 16 + end + local kind = readu8(buf, p) + r.pos = p + 1 + buffer.writeu8(deform, v, kind) + local o = v * 16 + if kind == 0 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, -1) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + writef32(weights, o, 1) + elseif kind == 1 or kind == 3 then + writei32(joints, o, bidx()) + writei32(joints, o + 4, bidx()) + writei32(joints, o + 8, -1) + writei32(joints, o + 12, -1) + local w = r:f32le() + writef32(weights, o, w) + writef32(weights, o + 4, 1 - w) + if kind == 3 then + local sd = sdef or buffer.create(nv * 36) + sdef = sd + for c = 0, 8 do + writef32(sd, v * 36 + c * 4, r:f32le()) + end + end + elseif kind == 2 or kind == 4 then + for c = 0, 3 do + writei32(joints, o + c * 4, bidx()) + end + for c = 0, 3 do + writef32(weights, o + c * 4, r:f32le()) + end + else + return nil, "unknown vertex deform type " .. kind + end + writef32(edge, v * 4, r:f32le()) + if r.err then + return nil, "truncated", "truncated" + end + end + m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas + m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge + + -- faces: vertex index triples + local ni + ni, e, k = count(r, vsize, "face indices") + if not ni then + return nil, e, k + end + if ni % 3 ~= 0 then + return nil, ni .. " face indices (not triangles)" + end + local ind = buffer.create(ni * 4) + local p = r.pos + for i = 0, ni - 1 do + local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4) + if x < 0 or x >= nv then + return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil + end + buffer.writeu32(ind, i * 4, x) + end + r.pos = p + ni * vsize + m.indexCount, m.indices = ni, ind + + -- textures + local nt + nt, e, k = count(r, 4, "textures") + if not nt then + return nil, e, k + end + m.textures = table.create(nt) + for i = 1, nt do + m.textures[i] = text() + end + + -- materials + local nm + nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials") + if not nm then + return nil, e, k + end + m.materials = table.create(nm) + for i = 1, nm do + local mat: { [string]: any } = { name = text(), nameEn = text() } + mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + mat.flags = r:u8() + mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le() + mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8() + if r:u8() == 1 then + mat.toonShared = r:u8() + else + mat.toon = tidx() + end + mat.memo, mat.count = text(), r:i32le() + if r.err then + return nil, "truncated", "truncated" + end + m.materials[i] = mat + end + + -- bones + local nb + nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones") + if not nb then + return nil, e, k + end + m.bones = table.create(nb) + for i = 1, nb do + local b: { [string]: any } = { name = text(), nameEn = text() } + b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le() + local fl = r:u16le() + b.flags = fl + b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3) + if bit32.btest(fl, 0x300) then + b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) } + end + if bit32.btest(fl, 0x400) then + b.axis = vec(r, 3) + end + if bit32.btest(fl, 0x800) then + b.localX, b.localZ = vec(r, 3), vec(r, 3) + end + if bit32.btest(fl, 0x2000) then + b.externalKey = r:i32le() + end + if bit32.btest(fl, 0x20) then + local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() } + local nl + nl, e, k = count(r, bsize + 1, "IK links") + if not nl then + return nil, e, k + end + ik.links = table.create(nl) + for l = 1, nl do + local link: { [string]: any } = { bone = bidx() } + if r:u8() == 1 then + link.min, link.max = vec(r, 3), vec(r, 3) + end + ik.links[l] = link + end + b.ik = ik + end + if r.err then + return nil, "truncated", "truncated" + end + m.bones[i] = b + end + + -- morphs + local nmo + nmo, e, k = count(r, 8 + 2 + 4, "morphs") + if not nmo then + return nil, e, k + end + local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 } + m.morphs = table.create(nmo) + for i = 1, nmo do + local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() } + local t = mo.type + local size = SIZE[t] + if not size then + return nil, "unknown morph type " .. t + end + local no + no, e, k = count(r, size, "morph offsets") + if not no then + return nil, e, k + end + if t == 1 then + -- vertex morphs: packed (index list + deltas), they become morph targets + local vi, d = table.create(no), buffer.create(no * 12) + for o = 1, no do + local x = vidx() + vi[o] = x + for c = 0, 2 do + writef32(d, ((o - 1) * 3 + c) * 4, r:f32le()) + end + end + mo.vertices, mo.deltas = vi, d + else + local offs = table.create(no) + for o = 1, no do + local off: { [string]: any } + if t == 0 or t == 9 then + off = { morph = moidx(), weight = r:f32le() } + elseif t == 2 then + off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) } + elseif t <= 7 then + off = { vertex = vidx(), value = vec(r, 4) } + elseif t == 8 then + off = { material = midx(), operation = r:u8() } + off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3) + off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4) + else + off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) } + end + offs[o] = off + end + mo.offsets = offs + end + if r.err then + return nil, "truncated", "truncated" + end + m.morphs[i] = mo + end + + -- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs) + m.frames, m.rigidBodies, m.jointsList = {}, {}, {} + if r.limit - r.pos >= 4 then + local nf + nf, e, k = count(r, 8 + 1 + 4, "display frames") + if not nf then + return nil, e, k + end + for i = 1, nf do + local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 } + local nitem + nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items") + if not nitem then + return nil, e, k + end + f.items = table.create(nitem) + for q = 1, nitem do + local kind = r:u8() + f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() } + end + m.frames[i] = f + end + end + if r.limit - r.pos >= 4 then + local nr + nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies") + if not nr then + return nil, e, k + end + for i = 1, nr do + local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() } + b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3) + b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le() + b.mode = r:u8() + m.rigidBodies[i] = b + end + end + if r.limit - r.pos >= 4 then + local nj + nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints") + if not nj then + return nil, e, k + end + for i = 1, nj do + local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() } + j.position, j.rotation = vec(r, 3), vec(r, 3) + j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3) + j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3) + m.jointsList[i] = j + end + end + if version >= 2.1 and r.limit - r.pos >= 4 then + m.softBodies = r:i32le() + end + if r.err then + return nil, "truncated", "truncated" + end + return m +end + +return Read diff --git a/src/Formats/model/pmx/init.luau b/src/Formats/model/pmx/init.luau new file mode 100644 index 0000000..5a671b1 --- /dev/null +++ b/src/Formats/model/pmx/init.luau @@ -0,0 +1,77 @@ +--!strict +-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD +-- format, as documented by the MMD community). New code, no third-party code. +-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 / +-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 / +-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one +-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor, +-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon +-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin; +-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames), +-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras +-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the +-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm). +-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/pmx/Read") +local Pmd = require("@formats/model/pmx/Pmd") +local Build = require("@formats/model/pmx/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Pmx = { + name = "pmx", + category = "model", + extensions = { "pmx", "pmd" }, + mime = { "model/x-pmx", "model/x-pmd" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" }, + caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name) + resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths) + morphs: boolean?, -- vertex morphs as morph targets (default true) + maxVertices: number?, -- default 2^24 + maxBytes: number?, -- morph target bytes (default 2^28) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Pmx.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 4) == "PMX " then + return 1 + end + if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local pmd = r:peek(3) == "Pmd" + local m: any, msg: string?, kind: string? + if pmd then + m, msg, kind = Pmd.parse(r, opts) + else + m, msg, kind = Read.parse(r, opts) + end + if not m then + return nil, Err.from(msg, r.pos - r.base, kind) + end + local scene, berr, bkind = Build.scene(m, opts) + if not scene then + return nil, Err.from(berr, nil, bkind) + end + if pmd and scene.meta.source then + scene.meta.source.pmd = true + end + return scene, nil +end + +return Pmx diff --git a/tests/model/pmx.luau b/tests/model/pmx.luau new file mode 100644 index 0000000..e685dcf --- /dev/null +++ b/tests/model/pmx.luau @@ -0,0 +1,263 @@ +-- model/pmx tests: assimp's MMD model (Alicia_blade.pmx) and synthetic PMX 2.0 / 2.1 models (UTF-16 / UTF-8, index +-- sizes 1 / 2 / 4, additional UVs, BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF, every morph type, IK / inherit / axis bones, +-- display frames, rigid bodies, joints) against assimp (meshes, faces per mesh, materials, bones, world bounds) and the +-- generator's facts (vertices, weights, bones, morphs, textures); the same models as PMD against their PMX decode; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pmx.py. +local T = require("@tests/T") +local F = require("@formats") +local Pmx = require("@formats/model/pmx") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/pmx_cases") +local Pmds = require("@tests/gen/pmx_pmd") + +local t = T.suite("pmx") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Pmx.decode(Bytes.reader(b), opts) +end + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +t:eq(Pmx.name, "pmx", "name") +t:eq(Pmx.category, "model", "category") +t:check(Pmx.caps.decode and not Pmx.caps.encode, "contract") + +local function faces(scene: any): (number, { number }) + local n, per = 0, {} + for i, p in scene.meshes[1].primitives do + per[i] = p.indices.count // 3 + n += per[i] + end + return n, per +end + +local function bounds(scene: any): ({ number }, { number }) + return MeshOps.bounds(MeshOps.merge(scene)) +end + +-- a file vertex in the decoded primitives: position (z negated) and uv +local function findVertex(scene: any, pos: { number }, uv: { number }): (any, number?) + for _, p in scene.meshes[1].primitives do + local P, U = p.attributes.POSITION, p.attributes.TEXCOORD_0 + for v = 0, P.count - 1 do + local x, y, z = buffer.readf32(P.data, v * 12), buffer.readf32(P.data, v * 12 + 4), buffer.readf32(P.data, v * 12 + 8) + if near(x, pos[1], 1e-6) and near(y, pos[2], 1e-6) and near(z, -pos[3], 1e-6) and near(buffer.readf32(U.data, v * 8), uv[1], 1e-6) and near(buffer.readf32(U.data, v * 8 + 4), uv[2], 1e-6) then + return p, v + end + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +local checked = { assimp = 0, expect = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i] = scene + local a = c.assimp + local nf, per = faces(scene) + if not a.skip then + t:eq(#scene.meshes[1].primitives, a.meshes, c.name .. ": meshes (assimp)") + t:eq(nf, a.faces, c.name .. ": faces (assimp)") + t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)") + local ok = true + for k, pm in a.perMesh do + ok = ok and per[k] == pm.faces + end + t:check(ok, c.name .. ": faces per material (assimp)") + t:eq(#scene.skins[1].joints * #scene.meshes[1].primitives, a.bones, c.name .. ": bones x meshes (assimp)") + if a.min then + local lo, hi = bounds(scene) + local okb = true + for k = 1, 3 do + okb = okb and near(lo[k], a.min[k], 1e-5) and near(hi[k], a.max[k], 1e-5) + end + t:check(okb, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo, " "), table.concat(hi, " "))) + end + checked.assimp += 1 + end + local x = c.expect + if x then + local src = scene.meta.source + t:eq(src.version, x.version, c.name .. ": version") + t:eq(src.name, x.name, c.name .. ": model name") + t:eq(#scene.skins[1].joints, x.bones, c.name .. ": bones") + t:eq(#scene.nodes, 2 + x.bones, c.name .. ": nodes") + t:eq(#scene.textures, x.textures, c.name .. ": textures") + t:eq(#src.rigidBodies, x.rigid, c.name .. ": rigid bodies") + t:eq(#src.joints, x.joints, c.name .. ": joints") + t:eq(#src.displayFrames, x.frames, c.name .. ": display frames") + local mesh = scene.meshes[1] + local vertexMorphs = x.morphTypes["1"] or 0 + t:eq(#(mesh.extras.targetNames or {}), vertexMorphs, c.name .. ": vertex morphs -> targets") + t:eq(#mesh.primitives[1].targets, vertexMorphs, c.name .. ": targets per primitive") + t:eq(#((mesh.extras.pmx or {}).morphs or {}), x.morphs - vertexMorphs, c.name .. ": other morphs in extras") + t:check(x.uva == 0 or mesh.primitives[1].attributes["_UVA" .. x.uva] ~= nil, c.name .. ": additional UVs") + -- unique vertices: a material boundary can split a ring, so at least the file's count + local nv = 0 + for _, p in mesh.primitives do + nv += p.attributes.POSITION.count + end + t:check(nv >= x.vertices and nv <= x.vertices * 2, c.name .. ": vertices " .. nv .. " / " .. x.vertices) + for _, s in x.samples do + local p, v = findVertex(scene, s.pos, s.uv) + t:check(p ~= nil, c.name .. ": vertex " .. s.index .. " found") + if p and v then + local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0 + local want: { [number]: number } = {} + local sum = 0 + local ws = if s.deform == 1 or s.deform == 3 then { s.weights[1], 1 - s.weights[1] } elseif s.deform == 0 then { 1 } else s.weights + for k, b in s.bones do + if b >= 0 and ws[k] and ws[k] > 0 then + want[b] = (want[b] or 0) + ws[k] + sum += ws[k] + end + end + local got: { [number]: number } = {} + for k = 0, 3 do + local w = buffer.readf32(W.data, (v * 4 + k) * 4) + if w > 0 then + local j = buffer.readu16(J.data, (v * 4 + k) * 2) + got[j] = (got[j] or 0) + w + end + end + local ok = true + for b, w in want do + ok = ok and got[b] ~= nil and near(got[b], w / sum, 1e-5) + end + t:check(ok, c.name .. ": vertex " .. s.index .. " weights (deform " .. s.deform .. ")") + if s.deform == 3 then + t:check(p.attributes._SDEF_C ~= nil and buffer.readu8(p.attributes._DEFORM.data, v) == 3, c.name .. ": SDEF attributes") + end + end + end + -- the texture named tex\body.png came from files["tex/body.png"] + t:check(scene.textures[1].uri == "tex/body.png" and scene.textures[1].data ~= nil and scene.textures[1].mime == "image/png", c.name .. ": texture data") + local m1 = scene.materials[1] + t:check(m1.baseColorTexture and m1.baseColorTexture.texture == 1 and m1.doubleSided, c.name .. ": material 1 texture, no-cull") + t:check(m1.extras.pmx.sphereTexture == 2 and m1.extras.pmx.sphereMode == "multiply" and m1.extras.pmx.toonShared == 3, c.name .. ": sphere / toon") + t:check(scene.materials[2].alphaMode == "blend", c.name .. ": translucent material") + local ik = nil + for _, n in scene.nodes do + if n.extras and n.extras.pmx and n.extras.pmx.ik then + ik = n.extras.pmx.ik + end + end + t:check(ik and ik.loops == 40 and #ik.links == 2, c.name .. ": IK bone") + checked.expect += 1 + end +end +t:note("%d files: %d against assimp, %d against the generator", #Cases, checked.assimp, checked.expect) + +-- skins: every joint's inverse bind matrix undoes its world translation +do + local s = scenes[2] + if s then + local skin = s.skins[1] + local ok = true + local world = {} + -- world matrices by walking from the root + local function walk(n: number, parent: { number }) + local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(s.nodes[n])) + world[n] = w + for _, c in s.nodes[n].children do + walk(c, w) + end + end + walk(1, Types.Scene.IDENTITY) + for k, j in skin.joints do + local w = world[j] + for c = 0, 2 do + ok = ok and near(buffer.readf32(skin.inverseBindMatrices.data, ((k - 1) * 16 + 12 + c) * 4), -w[13 + c], 1e-5) + end + end + t:check(ok, "inverse bind matrices = -world bone positions") + end +end + +-- ------------------------------------------------------------------------------------------------ PMD +for _, c in Pmds do + local s, err = decode(c.data) + t:check(s, c.name .. ": decode: " .. tostring(err)) + local ref = scenes[c.pmx] + if s and ref then + t:check(s.meta.source.pmd == true and s.meta.source.format == "pmx", c.name .. ": meta.source") + local a, pa = faces(s) + local b, pb = faces(ref) + t:eq(a, b, c.name .. ": faces (= PMX)") + t:eq(#pa, #pb, c.name .. ": primitives (= PMX)") + t:eq(#s.skins[1].joints, #ref.skins[1].joints, c.name .. ": bones (= PMX)") + t:eq(#s.meshes[1].extras.targetNames, #ref.meshes[1].extras.targetNames, c.name .. ": vertex morphs (= PMX)") + local lo, hi = bounds(s) + local lo2, hi2 = bounds(ref) + local ok = true + for k = 1, 3 do + ok = ok and near(lo[k], lo2[k], 1e-6) and near(hi[k], hi2[k], 1e-6) + end + t:check(ok, c.name .. ": bounds (= PMX)") + -- the same morph deltas + local d1 = s.meshes[1].primitives[1].targets[1].POSITION + local d2 = ref.meshes[1].primitives[1].targets[1].POSITION + t:check(d1.count == d2.count and buffer.tostring(d1.data) == buffer.tostring(d2.data), c.name .. ": morph deltas (= PMX)") + t:eq(s.meshes[1].extras.targetNames[1], "up", c.name .. ": English morph names") + t:eq(s.materials[1].extras.pmx.sphereMode, "multiply", c.name .. ": texture*sphere name") + end +end + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local c = Cases[2] + t:eq(F.detect(c.data), "pmx", "F.detect pmx") + t:eq(F.detect(Pmds[1].data), "pmx", "F.detect pmd") + local s = F.load(c.data, { files = c.files }) + t:check(s and s.kind == "scene" and s.meta.up == "y", "F.load") + local _, e1 = decode(string.sub(c.data, 1, 300)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("PMX " .. "\0\0\64\64" .. string.sub(c.data, 9)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 2.0 -> 3.0: " .. tostring(e2)) + local _, e3 = decode(string.sub(c.data, 1, 11) .. "\3" .. string.sub(c.data, 13)) + t:check(e3 and e3.code == Err.CORRUPT, "index size 3: " .. tostring(e3)) + local _, e4 = decode(c.data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = decode(c.data, { maxBytes = 100 }) + t:check(e5 and e5.code == Err.LIMIT, "maxBytes (morph targets): " .. tostring(e5)) + local s2 = decode(c.data, { maxBytes = 100, morphs = false }) + t:check(s2 and s2.meshes[1].primitives[1].targets == nil, "morphs = false") + local _, e6 = decode("Pmd\0\0\0\64" .. string.rep("\0", 300)) + t:check(e6 and e6.code == Err.UNSUPPORTED, "PMD version 2: " .. tostring(e6)) + local _, e7 = decode(string.sub(Pmds[1].data, 1, 400)) + t:check(e7 and (e7.code == Err.TRUNCATED or e7.code == Err.CORRUPT), "PMD truncated: " .. tostring(e7)) +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 120000 then + table.insert(samples, c.data) + end + end + for _, c in Pmds do + table.insert(samples, c.data) + end + t:fuzz("decode", function(b: buffer) + local s = Pmx.decode(Bytes.reader(b)) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 17 }) +end + +t:done() diff --git a/tools/fixtures/_pmx_writer.py b/tools/fixtures/_pmx_writer.py new file mode 100644 index 0000000..dcace7d --- /dev/null +++ b/tools/fixtures/_pmx_writer.py @@ -0,0 +1,265 @@ +# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every +# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs, +# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis +# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes +# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code. +import math, struct + + +def f32s(*v): + return struct.pack("<%df" % len(v), *v) + + +class Pmx: + def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0): + self.version, self.utf8, self.uva = version, utf8, uva + self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes + + def text(self, s): + b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le") + return struct.pack("= 2.1: + out += struct.pack("= 2.1 else [])) + verts = [] + for r in range(rings): + y = r * 2.0 + for s in range(seg): + a = 2 * math.pi * s / seg + x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r + b0 = min(nbones - 1, r * nbones // rings) + b1 = min(nbones - 1, b0 + 1) + k = kinds[(r * seg + s) % len(kinds)] + w = rnd.random() + if k == 0: + bones, weights = [b0], [1.0] + elif k in (1, 3): + bones, weights = [b0, b1], [w] + else: + ws = [rnd.random() + 0.1 for _ in range(4)] + bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws] + verts.append({ + "pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)), + "uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)], + "deform": k, "bones": bones, "weights": weights, "edge": 1.0, + "sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)), + }) + faces = [] + for r in range(rings - 1): + for s in range(seg): + a, b = r * seg + s, r * seg + (s + 1) % seg + c, d = a + seg, b + seg + faces += [a, c, b, b, c, d] + ntri = len(faces) // 3 + counts, left = [], ntri + for k in range(nmat): + n = left if k == nmat - 1 else max(1, ntri // nmat) + counts.append(n * 3) + left -= n + mats = [] + for k in range(nmat): + mats.append({ + "name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5), + "specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3], + "edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1, + "sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k], + }) + bones = [] + for i in range(nbones): + fl = 0x1A | (1 if i < nbones - 1 else 0) + b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1, + "layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)} + if i == 1: + b["flags"] |= 0x100 + b["inherit"] = (0, 0.5) + if i == 2: + b["flags"] |= 0x400 | 0x800 + b["axis"] = (0.0, 1.0, 0.0) + b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0) + bones.append(b) + # an IK bone at the end targeting the last chain bone + bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0), + "ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}}) + morphs = [ + {"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]}, + {"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]}, + {"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]}, + {"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]}, + {"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]}, + {"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]}, + ] + if uva: + morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]}) + if version >= 2.1 and flips: # assimp 6 rejects these morph types + morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]}) + morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]}) + frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]}, + {"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}] + rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3), + "pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)] + joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}] + return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces, + "textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs, + "frames": frames, "rigid": rigid, "joints": joints} + + +def pmd(m): + """the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)""" + def name(s, n): + b = s.encode("ascii", "replace")[: n - 1] + return b + b"\0" * (n - len(b)) + out = bytearray(b"Pmd") + struct.pack("= 0 else "" + if mat["sphere"] >= 0: + tex += "*" + m["textures"][mat["sphere"]] + out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"]) + out += struct.pack(" bytes }, assimp, expect? } +# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) } +import importlib.util, os, struct, zlib + +INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def tiny_png(): + raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + W = load(ctx, "_pmx_writer") + tmp = M.tempdir() + cases, pmds = [], [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx") + if os.path.exists(src): + cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}}) + variants = [ + ("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)), + ("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)), + ("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)), + ("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)), + ] + png = tiny_png() + for fname, wopts, topts in variants: + uva = wopts["uva"] + model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts) + data = W.Pmx(**wopts).build(model) + path = os.path.join(tmp, fname) + with open(path, "wb") as f: + f.write(data) + vs = model["vertices"] + samples = [] + for i in (0, 1, 2, 3, len(vs) - 1): + v = vs[i] + samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]}) + types = {} + for mo in model["morphs"]: + types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1 + expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types, + "textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"], + "rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])} + cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect}) + if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2: + pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + for c, a in zip(cases, infos): + a.update(Fbx.assimp_extra(ctx, c["path"])) + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.ptv_bounds(ctx, c["path"], tmp)) + if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"): + a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("pmx_cases", cases) + ctx.emit("pmx_pmd", pmds) From f17a54395d5ea86ae3a0f427795703dbe6565032 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:05:10 -0500 Subject: [PATCH 09/54] ws-tex: codecs/image/Bcn (BC1-7 decode, BC1/3/4/5 encode) + codecs/image/Half Decoders ported from Pillow BcnDecode.c (CC0) with D3D11 rules (BC6H +32 rounding, float output, reserved modes, signed RGTC). Tests against Pillow and Godot 4 (bcdec) over random blocks of every BC6H / BC7 mode; encoder PSNR above Pillow's encoder. Bench lines in tools/bench.luau. --- licenses/NOTICE.md | 1 + licenses/pillow-bcn-CC0.txt | 134 ++++++ src/Formats/codecs/image/Bcn/Decode.luau | 498 +++++++++++++++++++++++ src/Formats/codecs/image/Bcn/Encode.luau | 442 ++++++++++++++++++++ src/Formats/codecs/image/Bcn/init.luau | 121 ++++++ src/Formats/codecs/image/Half.luau | 74 ++++ tests/codecs/bcn.luau | 241 +++++++++++ tools/bench.luau | 24 ++ tools/fixtures/_tex_reference.py | 107 +++++ tools/fixtures/bcn.py | 119 ++++++ 10 files changed, 1761 insertions(+) create mode 100644 licenses/pillow-bcn-CC0.txt create mode 100644 src/Formats/codecs/image/Bcn/Decode.luau create mode 100644 src/Formats/codecs/image/Bcn/Encode.luau create mode 100644 src/Formats/codecs/image/Bcn/init.luau create mode 100644 src/Formats/codecs/image/Half.luau create mode 100644 tests/codecs/bcn.luau create mode 100644 tools/fixtures/_tex_reference.py create mode 100644 tools/fixtures/bcn.py diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..1fa543c 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/pillow-bcn-CC0.txt b/licenses/pillow-bcn-CC0.txt new file mode 100644 index 0000000..e47711c --- /dev/null +++ b/licenses/pillow-bcn-CC0.txt @@ -0,0 +1,134 @@ +Pillow src/libImaging/BcnDecode.c (https://github.com/python-pillow/Pillow), file header: + +/* + * The Python Imaging Library + * + * decoder for DXTn-compressed data + * + * Format documentation: + * https://web.archive.org/web/20170802060935/http://oss.sgi.com/projects/ogl-sample/registry/EXT/texture_compression_s3tc.txt + * + * The contents of this file are in the public domain (CC0) + * Full text of the CC0 license: + * https://creativecommons.org/publicdomain/zero/1.0/ + */ + +The full CC0 1.0 text follows. + +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + + diff --git a/src/Formats/codecs/image/Bcn/Decode.luau b/src/Formats/codecs/image/Bcn/Decode.luau new file mode 100644 index 0000000..8b892d1 --- /dev/null +++ b/src/Formats/codecs/image/Bcn/Decode.luau @@ -0,0 +1,498 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Decode: the BC1..BC7 block decoders (S3TC / DXT1-5, RGTC, BPTC). Ported from Pillow's +-- src/libImaging/BcnDecode.c (CC0, licenses/pillow-bcn-CC0.txt) and changed to follow the D3D11 functional spec where +-- Pillow does not: BC6H interpolation rounds ((a * (64 - w) + b * w + 32) >> 6), BC6H keeps its float values (no 8-bit +-- clamp), BC7's reserved mode 8 and BC6H's reserved modes decode to transparent / zero, BC4 / BC5 SNORM interpolate +-- the signed values (-128 reads as -127). Each decoder writes one 4x4 block into a 64-byte (rgba8) or 256-byte +-- (rgbaf32) scratch block; the caller clips it into the image. Never throws: the caller checks the source size. +local Half = require("@formats/codecs/image/Half") + +local Decode = {} + +local readu8, readu16, readu32, writeu8, writeu32, writef32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32, buffer.writef32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ BC1 / BC2 / BC3 +local pal = buffer.create(16) -- 4 rgba8 colours + +local function c565(c: number): (number, number, number) + local r = rshift(band(c, 0xF800), 8) + local g = rshift(band(c, 0x7E0), 3) + local b = lshift(band(c, 0x1F), 3) + return bor(r, rshift(r, 5)), bor(g, rshift(g, 6)), bor(b, rshift(b, 5)) +end + +-- the BC1 colour block at p into blk (64 bytes); fourColour = BC2 / BC3 (always the 4-colour palette) +local function colour(src: buffer, p: number, blk: buffer, fourColour: boolean) + local c0, c1 = readu16(src, p), readu16(src, p + 2) + local r0, g0, b0 = c565(c0) + local r1, g1, b1 = c565(c1) + writeu32(pal, 0, r0 + g0 * 256 + b0 * 65536 + 0xFF000000) + writeu32(pal, 4, r1 + g1 * 256 + b1 * 65536 + 0xFF000000) + if c0 > c1 or fourColour then + writeu32(pal, 8, (2 * r0 + r1) // 3 + ((2 * g0 + g1) // 3) * 256 + ((2 * b0 + b1) // 3) * 65536 + 0xFF000000) + writeu32(pal, 12, (r0 + 2 * r1) // 3 + ((g0 + 2 * g1) // 3) * 256 + ((b0 + 2 * b1) // 3) * 65536 + 0xFF000000) + else + writeu32(pal, 8, (r0 + r1) // 2 + ((g0 + g1) // 2) * 256 + ((b0 + b1) // 2) * 65536 + 0xFF000000) + writeu32(pal, 12, 0) + end + local idx = readu32(src, p + 4) + for i = 0, 15 do + writeu32(blk, i * 4, readu32(pal, band(rshift(idx, i * 2), 3) * 4)) + end +end + +-- the 8 values of a BC3 alpha / BC4 block (unsigned) into vals +local vals = table.create(8, 0) +local function ramp8(a0: number, a1: number) + vals[1], vals[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + vals[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + vals[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + vals[7], vals[8] = 0, 255 + end +end + +-- signed (SNORM) ramp, values -127..127 rounded to the nearest integer, biased by 128 into 1..255 +local function ramp8s(u0: number, u1: number) + local s0: number = math.max(if u0 >= 128 then u0 - 256 else u0, -127) + local s1: number = math.max(if u1 >= 128 then u1 - 256 else u1, -127) + vals[1], vals[2] = s0 + 128, s1 + 128 + if s0 > s1 then + for i = 1, 6 do + vals[i + 2] = math.floor(((7 - i) * s0 + i * s1) / 7 + 0.5) + 128 + end + else + for i = 1, 4 do + vals[i + 2] = math.floor(((5 - i) * s0 + i * s1) / 5 + 0.5) + 128 + end + vals[7], vals[8] = 1, 255 + end +end + +-- one 8-byte BC3 alpha / BC4 block at p into byte `channel` of every blk pixel (and the next ones when spread) +local function single(src: buffer, p: number, blk: buffer, channel: number, signed: boolean, spread: boolean) + if signed then + ramp8s(readu8(src, p), readu8(src, p + 1)) + else + ramp8(readu8(src, p), readu8(src, p + 1)) + end + local lo = readu8(src, p + 2) + readu8(src, p + 3) * 256 + readu8(src, p + 4) * 65536 + local hi = readu8(src, p + 5) + readu8(src, p + 6) * 256 + readu8(src, p + 7) * 65536 + for i = 0, 15 do + local sel = if i < 8 then band(rshift(lo, i * 3), 7) else band(rshift(hi, (i - 8) * 3), 7) + local v = vals[sel + 1] + local o = i * 4 + if spread then + writeu32(blk, o, v + v * 256 + v * 65536 + 0xFF000000) + else + writeu8(blk, o + channel, v) + end + end +end + +function Decode.bc1(src: buffer, p: number, blk: buffer) + colour(src, p, blk, false) +end + +function Decode.bc2(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + for i = 0, 15 do + local a = band(rshift(readu8(src, p + rshift(i, 1)), band(i, 1) * 4), 15) + writeu8(blk, i * 4 + 3, a * 17) + end +end + +function Decode.bc3(src: buffer, p: number, blk: buffer) + colour(src, p + 8, blk, true) + single(src, p, blk, 3, false, false) +end + +function Decode.bc4(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, false, true) +end + +function Decode.bc4s(src: buffer, p: number, blk: buffer) + single(src, p, blk, 0, true, true) +end + +local function bc5(src: buffer, p: number, blk: buffer, signed: boolean) + for i = 0, 15 do + writeu32(blk, i * 4, 0xFF000000) + end + single(src, p, blk, 0, signed, false) + single(src, p + 8, blk, 1, signed, false) +end +function Decode.bc5(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, false) +end +function Decode.bc5s(src: buffer, p: number, blk: buffer) + bc5(src, p, blk, true) +end + +-- ------------------------------------------------------------------------------------------------ BPTC tables +-- partition tables (BC7 Table.P2 1 bit per pixel, Table.P3 2 bits per pixel) and the anchor indices +local SI2 = { + 0xcccc, 0x8888, 0xeeee, 0xecc8, 0xc880, 0xfeec, 0xfec8, 0xec80, 0xc800, 0xffec, 0xfe80, 0xe800, 0xffe8, 0xff00, 0xfff0, 0xf000, + 0xf710, 0x008e, 0x7100, 0x08ce, 0x008c, 0x7310, 0x3100, 0x8cce, 0x088c, 0x3110, 0x6666, 0x366c, 0x17e8, 0x0ff0, 0x718e, 0x399c, + 0xaaaa, 0xf0f0, 0x5a5a, 0x33cc, 0x3c3c, 0x55aa, 0x9696, 0xa55a, 0x73ce, 0x13c8, 0x324c, 0x3bdc, 0x6996, 0xc33c, 0x9966, 0x0660, + 0x0272, 0x04e4, 0x4e40, 0x2720, 0xc936, 0x936c, 0x39c6, 0x639c, 0x9336, 0x9cc6, 0x817e, 0xe718, 0xccf0, 0x0fcc, 0x7744, 0xee22, +} +local SI3 = { + 0xaa685050, 0x6a5a5040, 0x5a5a4200, 0x5450a0a8, 0xa5a50000, 0xa0a05050, 0x5555a0a0, 0x5a5a5050, 0xaa550000, 0xaa555500, + 0xaaaa5500, 0x90909090, 0x94949494, 0xa4a4a4a4, 0xa9a59450, 0x2a0a4250, 0xa5945040, 0x0a425054, 0xa5a5a500, 0x55a0a0a0, + 0xa8a85454, 0x6a6a4040, 0xa4a45000, 0x1a1a0500, 0x0050a4a4, 0xaaa59090, 0x14696914, 0x69691400, 0xa08585a0, 0xaa821414, + 0x50a4a450, 0x6a5a0200, 0xa9a58000, 0x5090a0a8, 0xa8a09050, 0x24242424, 0x00aa5500, 0x24924924, 0x24499224, 0x50a50a50, + 0x500aa550, 0xaaaa4444, 0x66660000, 0xa5a0a5a0, 0x50a050a0, 0x69286928, 0x44aaaa44, 0x66666600, 0xaa444444, 0x54a854a8, + 0x95809580, 0x96969600, 0xa85454a8, 0x80959580, 0xaa141414, 0x96960000, 0xaaaa1414, 0xa05050a0, 0xa0a5a5a0, 0x96000000, + 0x40804080, 0xa9a8a9a8, 0xaaaaaa44, 0x2a4a5254, +} +local AI0 = { + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8, 2, 2, 8, 8, 2, 2, + 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2, 2, 15, 15, 15, 15, 15, 2, 2, 15, +} +local AI1 = { + 3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5, 15, 15, + 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5, 10, 8, 13, 15, 12, 3, 3, +} +local AI2 = { + 15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6, 10, 15, 15, 10, 8, + 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8, +} +local W2 = { [0] = 0, 21, 43, 64 } +local W3 = { [0] = 0, 9, 18, 27, 37, 46, 55, 64 } +local W4 = { [0] = 0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64 } +local WEIGHTS = { [2] = W2, [3] = W3, [4] = W4 } +Decode.SI2, Decode.SI3, Decode.AI0, Decode.AI1, Decode.AI2, Decode.WEIGHTS = SI2, SI3, AI0, AI1, AI2, WEIGHTS + +local function subset(ns: number, part: number, i: number): number + if ns == 2 then + return band(rshift(SI2[part + 1], i), 1) + elseif ns == 3 then + return band(rshift(SI3[part + 1], 2 * i), 3) + end + return 0 +end + +-- the 128-bit block as four u32 words: bits(at, n) for n <= 16 +local w0, w1, w2, w3 = 0, 0, 0, 0 +local function load(src: buffer, p: number) + w0, w1, w2, w3 = readu32(src, p), readu32(src, p + 4), readu32(src, p + 8), readu32(src, p + 12) +end +local function word(i: number): number + return if i == 0 then w0 elseif i == 1 then w1 elseif i == 2 then w2 else w3 +end +local function bits(at: number, n: number): number + if n == 0 then + return 0 + end + local wi, sh = rshift(at, 5), band(at, 31) + local v = rshift(word(wi), sh) + if sh + n > 32 and wi < 3 then + v = bor(v, lshift(word(wi + 1), 32 - sh)) + end + return band(v, lshift(1, n) - 1) +end + +-- ------------------------------------------------------------------------------------------------ BC7 +-- ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 +local MODES7 = { + { 3, 4, 0, 0, 4, 0, 1, 0, 3, 0 }, + { 2, 6, 0, 0, 6, 0, 0, 1, 3, 0 }, + { 3, 6, 0, 0, 5, 0, 0, 0, 2, 0 }, + { 2, 6, 0, 0, 7, 0, 1, 0, 2, 0 }, + { 1, 0, 2, 1, 5, 6, 0, 0, 2, 3 }, + { 1, 0, 2, 0, 7, 8, 0, 0, 2, 2 }, + { 1, 0, 0, 0, 7, 7, 1, 0, 4, 0 }, + { 2, 6, 0, 0, 5, 5, 1, 0, 2, 0 }, +} +local er, eg, eb, ea = table.create(6, 0), table.create(6, 0), table.create(6, 0), table.create(6, 0) + +local function expand(v: number, n: number): number + v = band(lshift(v, 8 - n), 255) + return bor(v, rshift(v, n)) +end + +function Decode.bc7(src: buffer, p: number, blk: buffer) + local m0 = readu8(src, p) + if m0 == 0 then + buffer.fill(blk, 0, 0, 64) + return + end + load(src, p) + local mode = 0 + while band(m0, lshift(1, mode)) == 0 do + mode += 1 + end + local info = MODES7[mode + 1] + local ns, pb, rb, isb, cb, ab, epb, spb, ib, ib2 = info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10] + local bit = mode + 1 + local part = bits(bit, pb) + bit += pb + local rot = bits(bit, rb) + bit += rb + local sel = bits(bit, isb) + bit += isb + local nep = ns * 2 + for i = 1, nep do + er[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eg[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + eb[i] = bits(bit, cb) + bit += cb + end + for i = 1, nep do + if ab > 0 then + ea[i] = bits(bit, ab) + bit += ab + else + ea[i] = 255 + end + end + if epb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep do + local v = bits(bit, 1) + bit += 1 + er[i], eg[i], eb[i] = er[i] * 2 + v, eg[i] * 2 + v, eb[i] * 2 + v + if ab > 0 then + ea[i] = ea[i] * 2 + v + end + end + end + if spb == 1 then + cb += 1 + if ab > 0 then + ab += 1 + end + for i = 1, nep, 2 do + local v = bits(bit, 1) + bit += 1 + for j = i, i + 1 do + er[j], eg[j], eb[j] = er[j] * 2 + v, eg[j] * 2 + v, eb[j] * 2 + v + if ab > 0 then + ea[j] = ea[j] * 2 + v + end + end + end + end + for i = 1, nep do + er[i], eg[i], eb[i] = expand(er[i], cb), expand(eg[i], cb), expand(eb[i], cb) + if ab > 0 then + ea[i] = expand(ea[i], ab) + end + end + local cw = WEIGHTS[ib] + local aw = if ab > 0 and ib2 > 0 then WEIGHTS[ib2] else cw + local cbit = bit + local abit = cbit + 16 * ib - ns + local a1 = if ns == 2 then AI0[part + 1] elseif ns == 3 then AI1[part + 1] else -1 + local a2 = if ns == 3 then AI2[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 2 + 1 + local n = ib + if i == 0 or i == a1 or i == a2 then + n -= 1 + end + local i0 = bits(cbit, n) + cbit += n + local wc, wa + if ab > 0 and ib2 > 0 then + local n2 = if i == 0 then ib2 - 1 else ib2 + local i1 = bits(abit, n2) + abit += n2 + if sel == 1 then + wc, wa = aw[i1], cw[i0] + else + wc, wa = cw[i0], aw[i1] + end + else + wc, wa = cw[i0], cw[i0] + end + local tc, ta = 64 - wc, 64 - wa + local r = rshift(tc * er[s] + wc * er[s + 1] + 32, 6) + local g = rshift(tc * eg[s] + wc * eg[s + 1] + 32, 6) + local b = rshift(tc * eb[s] + wc * eb[s + 1] + 32, 6) + local a = rshift(ta * ea[s] + wa * ea[s + 1] + 32, 6) + if rot == 1 then + r, a = a, r + elseif rot == 2 then + g, a = a, g + elseif rot == 3 then + b, a = a, b + end + writeu32(blk, i * 4, r + g * 256 + b * 65536 + a * 16777216) + end +end + +-- ------------------------------------------------------------------------------------------------ BC6H +-- ns, transformed, pb, epb, rb, gb, bb +local MODES6 = { + { 2, 1, 5, 10, 5, 5, 5 }, + { 2, 1, 5, 7, 6, 6, 6 }, + { 2, 1, 5, 11, 5, 4, 4 }, + { 2, 1, 5, 11, 4, 5, 4 }, + { 2, 1, 5, 11, 4, 4, 5 }, + { 2, 1, 5, 9, 5, 5, 5 }, + { 2, 1, 5, 8, 6, 5, 5 }, + { 2, 1, 5, 8, 5, 6, 5 }, + { 2, 1, 5, 8, 5, 5, 6 }, + { 2, 0, 5, 6, 6, 6, 6 }, + { 1, 0, 0, 10, 10, 10, 10 }, + { 1, 1, 0, 11, 9, 9, 9 }, + { 1, 1, 0, 12, 8, 8, 8 }, + { 1, 1, 0, 16, 4, 4, 4 }, +} +-- Table.F: for each endpoint bit in stream order, endpoint * 16 + bit (endpoints r0 g0 b0 r1 g1 b1 r2 ... b3) +local PACK6 = { + { 116, 132, 180, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 117, 164, 165, 0, 1, 2, 3, 4, 5, 6, 176, 177, 132, 16, 17, 18, 19, 20, 21, 22, 133, 178, 116, 32, 33, 34, 35, 36, 37, 38, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 10, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 26, 160, 161, 162, 163, 80, 81, 82, 83, 42, 177, 128, 129, 130, 131, 96, 97, 98, 99, 176, 178, 144, 145, 146, 147, 116, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 10, 132, 112, 113, 114, 115, 64, 65, 66, 67, 26, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 42, 128, 129, 130, 131, 96, 97, 98, 99, 177, 178, 144, 145, 146, 147, 180, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 132, 16, 17, 18, 19, 20, 21, 22, 23, 24, 116, 32, 33, 34, 35, 36, 37, 38, 39, 40, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 164, 132, 16, 17, 18, 19, 20, 21, 22, 23, 178, 116, 32, 33, 34, 35, 36, 37, 38, 39, 179, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 176, 132, 16, 17, 18, 19, 20, 21, 22, 23, 117, 116, 32, 33, 34, 35, 36, 37, 38, 39, 165, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 177, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 177, 132, 16, 17, 18, 19, 20, 21, 22, 23, 133, 116, 32, 33, 34, 35, 36, 37, 38, 39, 181, 180, 48, 49, 50, 51, 52, 164, 112, 113, 114, 115, 64, 65, 66, 67, 68, 176, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 178, 144, 145, 146, 147, 148, 179 }, + { 0, 1, 2, 3, 4, 5, 164, 176, 177, 132, 16, 17, 18, 19, 20, 21, 117, 133, 178, 116, 32, 33, 34, 35, 36, 37, 165, 179, 181, 180, 48, 49, 50, 51, 52, 53, 112, 113, 114, 115, 64, 65, 66, 67, 68, 69, 160, 161, 162, 163, 80, 81, 82, 83, 84, 85, 128, 129, 130, 131, 96, 97, 98, 99, 100, 101, 144, 145, 146, 147, 148, 149 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 56, 10, 64, 65, 66, 67, 68, 69, 70, 71, 72, 26, 80, 81, 82, 83, 84, 85, 86, 87, 88, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 52, 53, 54, 55, 11, 10, 64, 65, 66, 67, 68, 69, 70, 71, 27, 26, 80, 81, 82, 83, 84, 85, 86, 87, 43, 42 }, + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 15, 14, 13, 12, 11, 10, 64, 65, 66, 67, 31, 30, 29, 28, 27, 26, 80, 81, 82, 83, 47, 46, 45, 44, 43, 42 }, +} +local ep = table.create(12, 0) +local uq = table.create(12, 0) + +local function signExtend(v: number, n: number): number + v = band(v, lshift(1, n) - 1) + return if v >= lshift(1, n - 1) then v - lshift(1, n) else v +end + +local function unquantize(x: number, n: number, signed: boolean): number + if not signed then + if n >= 15 or x == 0 then + return x + elseif x == lshift(1, n) - 1 then + return 0xFFFF + end + return rshift(x * 32768 + 0x4000, n - 1) + end + if n >= 16 then + return x + end + local neg = x < 0 + if neg then + x = -x + end + if x ~= 0 then + if x >= lshift(1, n - 1) - 1 then + x = 0x7FFF + else + x = rshift(x * 32768 + 0x4000, n - 1) + end + end + return if neg then -x else x +end + +local function finish(v: number, signed: boolean): number + if signed then + if v < 0 then + return -HALF[(-v * 31) // 32] + end + return HALF[(v * 31) // 32] + end + return HALF[(v * 31) // 64] +end + +-- one BC6H block into blk as rgbaf32 (256 bytes, alpha 1) +function Decode.bc6h(src: buffer, p: number, blk: buffer, signed: boolean) + load(src, p) + local m = band(w0, 31) + local mode, bit, epbits, ib + local low = band(m, 3) + if low < 2 then + mode, bit, epbits, ib = low, 2, 75, 3 + elseif low == 2 then + mode, bit, epbits, ib = 2 + rshift(m, 2), 5, 72, 3 + else + mode, bit, epbits, ib = 10 + rshift(m, 2), 5, 60, 4 + end + if mode >= 14 then + for i = 0, 15 do + local o = i * 16 + writef32(blk, o, 0) + writef32(blk, o + 4, 0) + writef32(blk, o + 8, 0) + writef32(blk, o + 12, 1) + end + return + end + local info = MODES6[mode + 1] + local ns, tr, pb, epb, rbits, gbits, bbits = info[1], info[2], info[3], info[4], info[5], info[6], info[7] + local nep = if ns == 2 then 12 else 6 + for i = 1, 12 do + ep[i] = 0 + end + local pack = PACK6[mode + 1] + for i = 1, epbits do + local d = pack[i] + local e = rshift(d, 4) + 1 + ep[e] = bor(ep[e], lshift(bits(bit + i - 1, 1), band(d, 15))) + end + bit += epbits + local part = bits(bit, pb) + bit += pb + local mask = lshift(1, epb) - 1 + if signed then + ep[1], ep[2], ep[3] = signExtend(ep[1], epb), signExtend(ep[2], epb), signExtend(ep[3], epb) + end + if signed or tr == 1 then + for i = 4, nep, 3 do + ep[i], ep[i + 1], ep[i + 2] = signExtend(ep[i], rbits), signExtend(ep[i + 1], gbits), signExtend(ep[i + 2], bbits) + end + end + if tr == 1 then + for i = 4, nep, 3 do + for c = 0, 2 do + local v = band(ep[i + c] + ep[1 + c], mask) + ep[i + c] = if signed then signExtend(v, epb) else v + end + end + end + for i = 1, nep do + uq[i] = unquantize(ep[i], epb, signed) + end + local w = WEIGHTS[ib] + local a1 = if ns == 2 then AI0[part + 1] else -1 + for i = 0, 15 do + local s = subset(ns, part, i) * 6 + 1 + local n = if i == 0 or i == a1 then ib - 1 else ib + local wt = w[bits(bit, n)] + bit += n + local t = 64 - wt + local o = i * 16 + -- floor((a * t + b * w + 32) / 64): the products may be negative (signed) - // floors like >> would + writef32(blk, o, finish((uq[s] * t + uq[s + 3] * wt + 32) // 64, signed)) + writef32(blk, o + 4, finish((uq[s + 1] * t + uq[s + 4] * wt + 32) // 64, signed)) + writef32(blk, o + 8, finish((uq[s + 2] * t + uq[s + 5] * wt + 32) // 64, signed)) + writef32(blk, o + 12, 1) + end +end + +return Decode diff --git a/src/Formats/codecs/image/Bcn/Encode.luau b/src/Formats/codecs/image/Bcn/Encode.luau new file mode 100644 index 0000000..2aea052 --- /dev/null +++ b/src/Formats/codecs/image/Bcn/Encode.luau @@ -0,0 +1,442 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn/Encode: BC1 / BC3 / BC4 / BC5 block encoders (new in formats-luau; the approach follows stb_dxt by +-- Fabian Giesen / Sean Barrett, public domain: the principal axis of the block's colours by power iteration, the +-- extreme pixels along it as endpoints, then least-squares refinement of the endpoints for the chosen indices, keeping +-- the best; single-colour blocks use exact endpoint tables). Indices are chosen against the palette exactly as +-- Bcn/Decode rebuilds it. BC4 / BC5 channels try both the 8-value and the 6-value (+ 0 / 255) ramps. Never throws. +local Encode = {} + +local readu8, writeu8, writeu16, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +local function exp5(v: number): number + return bor(lshift(v, 3), rshift(v, 2)) +end +local function exp6(v: number): number + return bor(lshift(v, 2), rshift(v, 4)) +end + +-- ------------------------------------------------------------------------------------------------ single colours +-- OM[k][v + 1] = e0 * 256 + e1 (quantized) whose colour-2 value (4-colour: (2 e0 + e1) // 3; 3-colour: (e0 + e1) +-- // 2) is closest to v; k = 1 / 2 for 5-bit (4 / 3 colour), 3 / 4 for 6-bit +local OM: { { number } }? = nil +local function singleTables(): { { number } } + local om = OM + if om then + return om + end + local t: { { number } } = {} + for k = 1, 4 do + local bitsN = if k <= 2 then 5 else 6 + local maxq = lshift(1, bitsN) - 1 + local exp: (number) -> number = if bitsN == 5 then exp5 else exp6 + local best = table.create(256, 1e9) + local pick = table.create(256, 0) + for a = 0, maxq do + local ea = exp(a) + for b = 0, maxq do + local eb = exp(b) + local v: number = if k % 2 == 1 then (2 * ea + eb) // 3 else (ea + eb) // 2 + -- prefer endpoints close to each other (less error if the colour shifts) + local e = math.abs(ea - eb) * 0.01 + for target = math.max(0, v - 8), math.min(255, v + 8) do + local err = (target - v) ^ 2 + e + if err < best[target + 1] then + best[target + 1] = err + pick[target + 1] = a * 256 + b + end + end + end + end + t[k] = pick + end + OM = t + return t +end + +-- ------------------------------------------------------------------------------------------------ BC1 colour +local R, G, B, A = table.create(16, 0), table.create(16, 0), table.create(16, 0), table.create(16, 0) +local USE = table.create(16, true) +local PR, PG, PB = table.create(4, 0), table.create(4, 0), table.create(4, 0) +local IDX = table.create(16, 0) +local BEST = table.create(16, 0) + +local function palette(c0: number, c1: number, four: boolean) + local r0, g0, b0 = exp5(rshift(c0, 11)), exp6(band(rshift(c0, 5), 63)), exp5(band(c0, 31)) + local r1, g1, b1 = exp5(rshift(c1, 11)), exp6(band(rshift(c1, 5), 63)), exp5(band(c1, 31)) + PR[1], PG[1], PB[1] = r0, g0, b0 + PR[2], PG[2], PB[2] = r1, g1, b1 + if four then + PR[3], PG[3], PB[3] = (2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3 + PR[4], PG[4], PB[4] = (r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3 + else + PR[3], PG[3], PB[3] = (r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2 + PR[4], PG[4], PB[4] = 0, 0, 0 + end +end + +-- indices for the palette into IDX (0-based); returns the squared error of the used pixels +local function assign(four: boolean): number + local n = if four then 4 else 3 + local total = 0 + for i = 1, 16 do + if USE[i] then + local r, g, b = R[i], G[i], B[i] + local bi, be = 0, math.huge + for k = 1, n do + local dr, dg, db = r - PR[k], g - PG[k], b - PB[k] + local e = dr * dr + dg * dg + db * db + if e < be then + be, bi = e, k - 1 + end + end + IDX[i] = bi + total += be + else + IDX[i] = 3 + end + end + return total +end + +local function q565(r: number, g: number, b: number): number + local qr = math.clamp(math.floor(r * 31 / 255 + 0.5), 0, 31) + local qg = math.clamp(math.floor(g * 63 / 255 + 0.5), 0, 63) + local qb = math.clamp(math.floor(b * 31 / 255 + 0.5), 0, 31) + return qr * 2048 + qg * 32 + qb +end + +-- the endpoint weights of index k (the e0 share) +local W4 = { 1, 0, 2 / 3, 1 / 3 } +local W3 = { 1, 0, 0.5, 0 } + +-- least squares endpoints for the current IDX: c0, c1 or nil when degenerate +local function refine(four: boolean): (number?, number?) + local W = if four then W4 else W3 + local aa, bb, ab = 0, 0, 0 + local ar, ag, ab_, br, bg, bb_ = 0, 0, 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + local w = W[IDX[i] + 1] + local v = 1 - w + aa += w * w + bb += v * v + ab += w * v + ar += w * R[i] + ag += w * G[i] + ab_ += w * B[i] + br += v * R[i] + bg += v * G[i] + bb_ += v * B[i] + end + end + local det = aa * bb - ab * ab + if math.abs(det) < 1e-9 then + return nil, nil + end + local f = 1 / det + local r0, g0, b0 = (ar * bb - br * ab) * f, (ag * bb - bg * ab) * f, (ab_ * bb - bb_ * ab) * f + local r1, g1, b1 = (br * aa - ar * ab) * f, (bg * aa - ag * ab) * f, (bb_ * aa - ab_ * ab) * f + return q565(r0, g0, b0), q565(r1, g1, b1) +end + +-- encodes R / G / B (USE marks the pixels that count) as a BC1 colour block at out[o]; four = 4-colour mode +-- (opaque), else the 3-colour mode with index 3 for the unused (transparent) pixels +local function colourBlock(out: buffer, o: number, four: boolean) + local n, mr, mg, mb = 0, 0, 0, 0 + for i = 1, 16 do + if USE[i] then + n += 1 + mr += R[i] + mg += G[i] + mb += B[i] + end + end + if n == 0 then + writeu16(out, o, 0) + writeu16(out, o + 2, 0) + writeu32(out, o + 4, 0xFFFFFFFF) + return + end + mr, mg, mb = mr / n, mg / n, mb / n + local crr, cgg, cbb, crg, crb, cgb = 0, 0, 0, 0, 0, 0 + local same = true + local fr, fg, fb = -1, -1, -1 + for i = 1, 16 do + if USE[i] then + if fr < 0 then + fr, fg, fb = R[i], G[i], B[i] + elseif R[i] ~= fr or G[i] ~= fg or B[i] ~= fb then + same = false + end + local dr, dg, db = R[i] - mr, G[i] - mg, B[i] - mb + crr += dr * dr + cgg += dg * dg + cbb += db * db + crg += dr * dg + crb += dr * db + cgb += dg * db + end + end + local c0, c1 + if same then + local t = singleTables() + local k = if four then 0 else 1 + local pr, pg, pb = t[1 + k][fr + 1], t[3 + k][fg + 1], t[1 + k][fb + 1] + c0 = rshift(pr, 8) * 2048 + rshift(pg, 8) * 32 + rshift(pb, 8) + c1 = band(pr, 255) * 2048 + band(pg, 255) * 32 + band(pb, 255) + local i2 = 2 + if c0 == c1 then + i2 = 0 + end + -- index 2 everywhere (or 0 for an exact endpoint); order fixed below + for i = 1, 16 do + IDX[i] = if USE[i] then i2 else 3 + end + else + -- principal axis + local vr, vg, vb = 1, 1, 1 + for _ = 1, 8 do + local nr = crr * vr + crg * vg + crb * vb + local ng = crg * vr + cgg * vg + cgb * vb + local nb = crb * vr + cgb * vg + cbb * vb + local m = math.max(math.abs(nr), math.abs(ng), math.abs(nb)) + if m < 1e-9 then + break + end + vr, vg, vb = nr / m, ng / m, nb / m + end + local lo, hi, li, hi_ = math.huge, -math.huge, 1, 1 + for i = 1, 16 do + if USE[i] then + local d = R[i] * vr + G[i] * vg + B[i] * vb + if d < lo then + lo, li = d, i + end + if d > hi then + hi, hi_ = d, i + end + end + end + c0 = q565(R[hi_], G[hi_], B[hi_]) + c1 = q565(R[li], G[li], B[li]) + palette(c0, c1, four) + local err = assign(four) + for i = 1, 16 do + BEST[i] = IDX[i] + end + for _ = 1, 2 do + local n0, n1 = refine(four) + if not n0 or not n1 then + break + end + palette(n0, n1, four) + local e2 = assign(four) + if e2 < err then + err, c0, c1 = e2, n0, n1 + for i = 1, 16 do + BEST[i] = IDX[i] + end + else + break + end + end + for i = 1, 16 do + IDX[i] = BEST[i] + end + end + -- the mode is set by the endpoint order: 4-colour c0 > c1, 3-colour c0 <= c1 + if four then + if c0 < c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 elseif v == 2 then 3 else 2 + end + elseif c0 == c1 then + for i = 1, 16 do + IDX[i] = 0 + end + end + elseif c0 > c1 then + c0, c1 = c1, c0 + for i = 1, 16 do + local v = IDX[i] + IDX[i] = if v == 0 then 1 elseif v == 1 then 0 else v + end + end + writeu16(out, o, c0) + writeu16(out, o + 2, c1) + local bitsv = 0 + for i = 16, 1, -1 do + bitsv = bitsv * 4 + IDX[i] + end + writeu32(out, o + 4, bitsv) +end + +-- ------------------------------------------------------------------------------------------------ BC4 channel +local V = table.create(16, 0) +local RAMP = table.create(8, 0) +local SEL = table.create(16, 0) +local SELB = table.create(16, 0) + +local function ramp(a0: number, a1: number) + RAMP[1], RAMP[2] = a0, a1 + if a0 > a1 then + for i = 1, 6 do + RAMP[i + 2] = ((7 - i) * a0 + i * a1) // 7 + end + else + for i = 1, 4 do + RAMP[i + 2] = ((5 - i) * a0 + i * a1) // 5 + end + RAMP[7], RAMP[8] = 0, 255 + end +end + +local function pick(): number + local total = 0 + for i = 1, 16 do + local v = V[i] + local bi, be = 0, math.huge + for k = 1, 8 do + local d = v - RAMP[k] + local e = d * d + if e < be then + be, bi = e, k - 1 + end + end + SEL[i] = bi + total += be + end + return total +end + +-- encodes V[1..16] (0..255) as an 8-byte BC4 block at out[o] +local function channelBlock(out: buffer, o: number) + local lo, hi = 255, 0 + local lo2, hi2 = 255, 0 + for i = 1, 16 do + local v = V[i] + lo, hi = math.min(lo, v), math.max(hi, v) + if v > 0 and v < 255 then + lo2, hi2 = math.min(lo2, v), math.max(hi2, v) + end + end + local a0, a1 + if lo == hi then + a0, a1 = lo, lo + ramp(a0, a1) + pick() + else + -- 8-value ramp, then a few nudged endpoints + local bestErr, b0, b1 = math.huge, hi, lo + for d0 = 0, 2 do + for d1 = 0, 2 do + local x0, x1 = hi - d0, lo + d1 + if x0 > x1 then + ramp(x0, x1) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, x0, x1 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + end + end + end + -- 6-value ramp with the 0 / 255 extremes + if lo2 > hi2 then + lo2, hi2 = lo, lo + end + ramp(lo2, hi2) + local e = pick() + if e < bestErr then + bestErr, b0, b1 = e, lo2, hi2 + for i = 1, 16 do + SELB[i] = SEL[i] + end + end + a0, a1 = b0, b1 + for i = 1, 16 do + SEL[i] = SELB[i] + end + end + writeu8(out, o, a0) + writeu8(out, o + 1, a1) + local lo24, hi24 = 0, 0 + for i = 8, 1, -1 do + lo24 = lo24 * 8 + SEL[i] + hi24 = hi24 * 8 + SEL[i + 8] + end + writeu8(out, o + 2, band(lo24, 255)) + writeu8(out, o + 3, band(rshift(lo24, 8), 255)) + writeu8(out, o + 4, rshift(lo24, 16)) + writeu8(out, o + 5, band(hi24, 255)) + writeu8(out, o + 6, band(rshift(hi24, 8), 255)) + writeu8(out, o + 7, rshift(hi24, 16)) +end + +-- ------------------------------------------------------------------------------------------------ whole images +-- the 4x4 block at bx, by of an rgba8 image into R / G / B / A (edge pixels repeat) +local function gather(px: buffer, w: number, h: number, bx: number, by: number) + for y = 0, 3 do + local sy = math.min(by * 4 + y, h - 1) + for x = 0, 3 do + local sx = math.min(bx * 4 + x, w - 1) + local s = (sy * w + sx) * 4 + local i = y * 4 + x + 1 + R[i], G[i], B[i], A[i] = readu8(px, s), readu8(px, s + 1), readu8(px, s + 2), readu8(px, s + 3) + end + end +end + +-- encode(kind, rgba8 pixels, w, h, alphaThreshold) -> the block data (kind = bc1 / bc3 / bc4 / bc5) +function Encode.run(kind: string, px: buffer, w: number, h: number, threshold: number): buffer + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local bytes = if kind == "bc1" or kind == "bc4" then 8 else 16 + local out = buffer.create(bw * bh * bytes) + local o = 0 + for by = 0, bh - 1 do + for bx = 0, bw - 1 do + gather(px, w, h, bx, by) + if kind == "bc1" then + local any = false + for i = 1, 16 do + local u = A[i] >= threshold + USE[i] = u + any = any or not u + end + colourBlock(out, o, not any) + elseif kind == "bc3" then + for i = 1, 16 do + USE[i] = true + V[i] = A[i] + end + channelBlock(out, o) + colourBlock(out, o + 8, true) + elseif kind == "bc4" then + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + else + for i = 1, 16 do + V[i] = R[i] + end + channelBlock(out, o) + for i = 1, 16 do + V[i] = G[i] + end + channelBlock(out, o + 8) + end + o += bytes + end + end + return out +end + +return Encode diff --git a/src/Formats/codecs/image/Bcn/init.luau b/src/Formats/codecs/image/Bcn/init.luau new file mode 100644 index 0000000..c0bd23b --- /dev/null +++ b/src/Formats/codecs/image/Bcn/init.luau @@ -0,0 +1,121 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): +-- decode of BC1 (DXT1, with the 3-colour + transparent mode), BC2 (DXT3), BC3 (DXT5), BC4 / BC5 (RGTC / ATI1 / ATI2, +-- UNORM and SNORM), BC6H (UF16 / SF16, to rgbaf32) and BC7 (all 8 modes); encode of BC1 / BC3 / BC4 / BC5 (UNORM). +-- Decoders ported from Pillow's BcnDecode.c (CC0) with the D3D11 rules; encoders new (stb_dxt-style). Never throws. +-- +-- local px, err = Bcn.decode("bc7", buf, offset, w, h) -- rgba8 pixels (rgbaf32 for bc6h / bc6hs) +-- local blocks = Bcn.encode("bc1", rgba8Pixels, w, h) -- the block data (row-major blocks) +-- Bcn.size("bc3", w, h) -- bytes of a w x h image (whole 4x4 blocks) +-- +-- Channels: BC4 decodes to grey (r = g = b, opaque), BC5 to red + green (blue 0, opaque); SNORM values are biased by +-- 128 into rgba8 (-127 -> 1, 0 -> 128, 127 -> 255). BC1 / BC3 / BC5 encode reads R / G (BC4: R), BC1 alpha below +-- opts.alphaThreshold (default 128) selects the transparent 3-colour mode. +local Decode = require("@formats/codecs/image/Bcn/Decode") +local Encode = require("@formats/codecs/image/Bcn/Encode") + +local Bcn = {} + +-- kind -> bytes per 4x4 block +Bcn.BLOCK = table.freeze({ bc1 = 8, bc2 = 16, bc3 = 16, bc4 = 8, bc4s = 8, bc5 = 16, bc5s = 16, bc6h = 16, bc6hs = 16, bc7 = 16 }) :: { [string]: number } +-- kinds that decode to rgbaf32 +Bcn.FLOAT = table.freeze({ bc6h = true, bc6hs = true }) :: { [string]: boolean } + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local BLOCKS: { [string]: (buffer, number, buffer) -> () } = { + bc1 = Decode.bc1, + bc2 = Decode.bc2, + bc3 = Decode.bc3, + bc4 = Decode.bc4, + bc4s = Decode.bc4s, + bc5 = Decode.bc5, + bc5s = Decode.bc5s, + bc7 = Decode.bc7, + bc6h = function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, false) + end, + bc6hs = function(src: buffer, p: number, blk: buffer) + Decode.bc6h(src, p, blk, true) + end, +} + +-- size(kind, w, h) -> bytes of the block data (nil for an unknown kind) +function Bcn.size(kind: string, w: number, h: number): number? + local b = Bcn.BLOCK[kind] + if not b then + return nil + end + return ((w + 3) // 4) * ((h + 3) // 4) * b +end + +-- decode(kind, src, offset, w, h, out?, outOffset?) -> pixels (rgba8, or rgbaf32 for BC6H) | nil, message. +-- out (optional) receives the pixels at outOffset (default 0) instead of a new buffer. +function Bcn.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?): (buffer?, string?) + local fn = BLOCKS[kind] + if not fn then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Bcn.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local float = Bcn.FLOAT[kind] == true + local bpp = if float then 16 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local bytes = Bcn.BLOCK[kind] + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + fn(src, p, blk) + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + if cols == 4 and not float then + for y = 0, rows - 1 do + local d, s = base + y * rowBytes, y * 16 + writeu32(dst, d, readu32(blk, s)) + writeu32(dst, d + 4, readu32(blk, s + 4)) + writeu32(dst, d + 8, readu32(blk, s + 8)) + writeu32(dst, d + 12, readu32(blk, s + 12)) + end + else + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + end + return dst, nil +end + +export type EncodeOptions = { + alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128; 0 = always opaque) +} + +-- encode(kind, pixels, w, h, opts?) -> block data | nil, message. pixels: rgba8, w x h; kind = bc1 / bc3 / bc4 / bc5. +function Bcn.encode(kind: string, px: buffer, w: number, h: number, opts: EncodeOptions?): (buffer?, string?) + if kind ~= "bc1" and kind ~= "bc3" and kind ~= "bc4" and kind ~= "bc5" then + return nil, "unsupported: no encoder for " .. tostring(kind) + end + if type(w) ~= "number" or type(h) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or buffer.len(px) < w * h * 4 then + return nil, "needs w x h rgba8 pixels" + end + local t = opts and opts.alphaThreshold or 128 + return Encode.run(kind, px, w, h, t), nil +end + +return Bcn diff --git a/src/Formats/codecs/image/Half.luau b/src/Formats/codecs/image/Half.luau new file mode 100644 index 0000000..f32e49a --- /dev/null +++ b/src/Formats/codecs/image/Half.luau @@ -0,0 +1,74 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, +-- OpenEXR HALF channels). New in formats-luau. Never throws. +-- +-- local f = Half.TABLE[h] -- the number of every half bit pattern 0..65535 (a 65536-entry table) +-- local f = Half.toFloat(h) -- the same, computed +-- local h = Half.fromFloat(f) -- round to nearest even; overflow -> infinity, NaN -> a quiet NaN +local Half = {} + +local band, bor, rshift, lshift = bit32.band, bit32.bor, bit32.rshift, bit32.lshift + +-- toFloat(h) -> number (h a 16-bit pattern) +local function toFloat(h: number): number + local s = if h >= 32768 then -1 else 1 + local e = band(rshift(h, 10), 31) + local m = band(h, 1023) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 / 0 + end + return s * (1024 + m) * 2 ^ (e - 25) +end +Half.toFloat = toFloat + +local TABLE: { [number]: number } = table.create(65536, 0) +for h = 0, 65535 do + TABLE[h] = toFloat(h) +end +Half.TABLE = TABLE + +local scratch = buffer.create(4) + +-- fromFloat(f) -> the nearest half bit pattern (ties to even) +function Half.fromFloat(f: number): number + if f ~= f then + return 0x7E00 + end + buffer.writef32(scratch, 0, f) + local x = buffer.readu32(scratch, 0) + local sign = band(rshift(x, 16), 0x8000) + local e = band(rshift(x, 23), 0xFF) + local m = band(x, 0x7FFFFF) + if e == 255 then + return bor(sign, 0x7C00) + end + local ne = e - 112 + if ne >= 31 then + return bor(sign, 0x7C00) + elseif ne <= 0 then + if ne < -10 then + return sign + end + m = bor(m, 0x800000) + local shift = 14 - ne + local hm = rshift(m, shift) + local rem = band(m, lshift(1, shift) - 1) + local halfway = lshift(1, shift - 1) + if rem > halfway or (rem == halfway and band(hm, 1) == 1) then + hm += 1 + end + return sign + hm + end + local hm = rshift(m, 13) + local rem = band(m, 0x1FFF) + if rem > 0x1000 or (rem == 0x1000 and band(hm, 1) == 1) then + hm += 1 -- a carry out of the mantissa bumps the exponent (up to infinity), as it should + end + return sign + ne * 1024 + hm +end + +return Half diff --git a/tests/codecs/bcn.luau b/tests/codecs/bcn.luau new file mode 100644 index 0000000..15a1dc6 --- /dev/null +++ b/tests/codecs/bcn.luau @@ -0,0 +1,241 @@ +-- codecs/image/Bcn tests: random BC1..BC7 blocks (every BC7 and BC6H mode, the BC1 3-colour mode, odd sizes) against +-- Pillow's and Godot's (bcdec) decodes; BC6H floats against Godot; the encoders (BC1 / BC3 / BC4 / BC5) within reach +-- of Pillow's encoder PSNR, exact on flat blocks; argument errors; the fuzz no-throw pass. Fixtures: tools/fixtures/bcn.py. +local T = require("@tests/T") +local Bcn = require("@formats/codecs/image/Bcn") +local Half = require("@formats/codecs/image/Half") +local Fx = require("@tests/gen/bcn") + +local t = T.suite("bcn") + +-- the largest per-byte difference between two rgba8 buffers (channels: which of r, g, b, a count) +local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number) + local worst, at = 0, -1 + for i = 0, n - 1 do + for _, c in channels do + local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c)) + if d > worst then + worst, at = d, i + end + end + end + return worst, at +end + +local RGBA, RGB, RG, R = { 0, 1, 2, 3 }, { 0, 1, 2 }, { 0, 1 }, { 0 } +-- which channels each reference defines, and the allowed difference to it +local PILLOW: { [string]: { any } } = { + bc1 = { RGBA, 0 }, + bc2 = { RGBA, 0 }, + bc3 = { RGBA, 0 }, + bc4 = { RGB, 0 }, + bc5 = { RG, 0 }, + bc5s = { RG, 1 }, -- Pillow interpolates the biased unsigned values with truncation + bc7 = { RGBA, 0 }, +} + +local stats = { pillow = 0, godot = 0 } +for _, c in Fx.cases do + local src = buffer.fromstring(c.data) + local px, err = Bcn.decode(c.kind, src, 0, c.w, c.h) + t:check(px, c.name .. ": " .. tostring(err)) + local n = c.w * c.h + if Bcn.FLOAT[c.kind] then + t:eq(buffer.len(px), n * 16, c.name .. ": rgbaf32 size") + -- Godot (bcdec) floats: exact half values + local g = buffer.fromstring(c.godot) + local worst = 0 + for i = 0, n - 1 do + for ch = 0, 2 do + local a, b = buffer.readf32(px, i * 16 + ch * 4), buffer.readf32(g, i * 16 + ch * 4) + local d = math.abs(a - b) / math.max(math.abs(b), 1e-3) + worst = math.max(worst, d) + end + end + t:check(worst < 1e-3, string.format("%s: relative error %g against Godot", c.name, worst)) + stats.godot += 1 + -- Pillow: 8-bit truncation of the clamped float (and no rounding term in its interpolation): within 1. Its + -- signed BC6H differs from bcdec and the spec (negative endpoints), so only BC6H UF16 is compared. + local p = buffer.fromstring(c.pillow) + local w2 = 0 + for i = 0, n - 1 do + for ch = 0, 2 do + local v = math.clamp(buffer.readf32(px, i * 16 + ch * 4), 0, 1) + w2 = math.max(w2, math.abs(math.floor(v * 255) - buffer.readu8(p, i * 4 + ch))) + end + end + if c.kind == "bc6h" then + t:check(w2 <= 1, string.format("%s: %d off Pillow", c.name, w2)) + stats.pillow += 1 + end + else + t:eq(buffer.len(px), n * 4, c.name .. ": rgba8 size") + local ref = PILLOW[c.kind] + local d, at = maxDiff(px, buffer.fromstring(c.pillow), n, ref[1]) + t:check(d <= ref[2], string.format("%s: %d off Pillow at pixel %d", c.name, d, at)) + stats.pillow += 1 + if c.godot then + local chans = if c.kind == "bc4" then R elseif c.kind == "bc5" then RG else RGBA + local dg, atg = maxDiff(px, buffer.fromstring(c.godot), n, chans) + -- bcdec rounds some interpolated values where Pillow truncates: within 1 + t:check(dg <= 1, string.format("%s: %d off Godot at pixel %d", c.name, dg, atg)) + stats.godot += 1 + end + end + -- into a bigger buffer at an offset, from an offset + local big = buffer.create(buffer.len(src) + 5) + buffer.copy(big, 5, src) + local bpp = if Bcn.FLOAT[c.kind] then 16 else 4 + local out = buffer.create(n * bpp + 8) + local px2 = Bcn.decode(c.kind, big, 5, c.w, c.h, out, 8) + t:check(px2 == out and buffer.readstring(out, 8, n * bpp) == buffer.readstring(px, 0, n * bpp), c.name .. ": offsets") +end +t:note("%d block images decoded: %d Pillow, %d Godot comparisons", #Fx.cases, stats.pillow, stats.godot) + +-- BC4 SNORM = the red channel of BC5 SNORM +do + for _, c in Fx.cases do + if c.kind == "bc5s" then + local src = buffer.fromstring(c.data) + local nb = buffer.len(src) // 16 + local b4 = buffer.create(nb * 8) + for i = 0, nb - 1 do + buffer.copy(b4, i * 8, src, i * 16, 8) + end + local p4 = Bcn.decode("bc4s", b4, 0, c.w, c.h) :: buffer + local p5 = Bcn.decode("bc5s", src, 0, c.w, c.h) :: buffer + local ok = true + for i = 0, c.w * c.h - 1 do + ok = ok and buffer.readu8(p4, i * 4) == buffer.readu8(p5, i * 4) and buffer.readu8(p4, i * 4 + 1) == buffer.readu8(p5, i * 4) + end + t:check(ok, c.name .. ": bc4s = bc5s red") + end + end +end + +-- encoders +local function psnr(a: buffer, b: buffer, n: number, channels: { number }): number + local se = 0 + for i = 0, n - 1 do + for _, c in channels do + local d = buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c) + se += d * d + end + end + return if se == 0 then 99 else 10 * math.log10(255 * 255 * n * #channels / se) +end + +for _, e in Fx.enc do + local px = buffer.fromstring(e.rgba) + local n = e.w * e.h + for _, k in { { "bc1", RGB }, { "bc3", RGBA }, { "bc5", RG }, { "bc4", R } } do + local kind, ch = k[1], k[2] + local blocks, err = Bcn.encode(kind, px, e.w, e.h) + t:check(blocks, kind .. " encode: " .. tostring(err)) + t:eq(buffer.len(blocks), Bcn.size(kind, e.w, e.h), e.name .. " " .. kind .. ": size") + local back = Bcn.decode(kind, blocks, 0, e.w, e.h) :: buffer + local p = psnr(px, back, n, ch) + local base = e.psnr[kind] + if base then + t:check(p >= base - 0.5, string.format("%s %s: PSNR %.2f dB, Pillow %.2f dB", e.name, kind, p, base)) + t:note("%s %s: %.2f dB (Pillow %.2f dB)", e.name, kind, p, base) + else + t:check(p >= 35, string.format("%s %s: PSNR %.2f dB", e.name, kind, p)) + end + if kind == "bc1" then + -- the transparent pixels survive (3-colour mode) + local bad = 0 + for i = 0, n - 1 do + local a = buffer.readu8(px, i * 4 + 3) + if (a >= 128) ~= (buffer.readu8(back, i * 4 + 3) == 255) then + bad += 1 + end + end + t:eq(bad, 0, e.name .. " bc1: alpha mask") + end + end +end + +-- flat colours are exact through the single-colour tables (BC1 4-colour and 3-colour, BC4) +do + local rand = T.rng(3) + local worst = 0 + for _ = 1, 200 do + local r, g, b = rand(256), rand(256), rand(256) + local px = buffer.create(64) + for i = 0, 15 do + buffer.writeu32(px, i * 4, r + g * 256 + b * 65536 + (if i == 5 then 0 else 255) * 16777216) + end + for _, opaque in { true, false } do + if opaque then + buffer.writeu8(px, 23, 255) + else + buffer.writeu8(px, 23, 0) + end + local back = Bcn.decode("bc1", Bcn.encode("bc1", px, 4, 4) :: buffer, 0, 4, 4) :: buffer + for i = 0, 15 do + if opaque or i ~= 5 then + for c = 0, 2 do + worst = math.max(worst, math.abs(buffer.readu8(back, i * 4 + c) - buffer.readu8(px, i * 4 + c))) + end + end + end + end + end + -- 5 / 6-bit endpoints reach every 8-bit value within 1 (4-colour) / 2 (3-colour midpoints) + t:check(worst <= 2, "flat bc1 colours within " .. worst) + local px = buffer.create(64) + for v = 0, 255, 5 do + for i = 0, 15 do + buffer.writeu32(px, i * 4, v + 0xFF000000) + end + local back = Bcn.decode("bc4", Bcn.encode("bc4", px, 4, 4) :: buffer, 0, 4, 4) :: buffer + t:eq(buffer.readu8(back, 0), v, "flat bc4 " .. v) + end +end + +-- Half +do + t:eq(Half.fromFloat(1), 0x3C00, "half 1") + t:eq(Half.fromFloat(-2), 0xC000, "half -2") + t:eq(Half.fromFloat(65504), 0x7BFF, "half max") + t:eq(Half.fromFloat(1e6), 0x7C00, "half overflow") + t:eq(Half.fromFloat(2 ^ -24), 1, "half smallest subnormal") + t:eq(Half.fromFloat(0 / 0), 0x7E00, "half NaN") + local ok = true + for h = 0, 65535 do + local f = Half.TABLE[h] + if f == f and Half.fromFloat(f) ~= h and not (h == 0x8000) then + ok = false + end + end + t:check(ok, "half round trip of every pattern") +end + +-- errors +do + local _, e1 = Bcn.decode("bc9", buffer.create(8), 0, 4, 4) + t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind") + local _, e2 = Bcn.decode("bc1", buffer.create(7), 0, 4, 4) + t:check(e2 and string.find(e2, "truncated") ~= nil, "short data") + local _, e3 = Bcn.encode("bc7", buffer.create(64), 4, 4) + t:check(e3 ~= nil, "no bc7 encoder") + local _, e4 = Bcn.encode("bc1", buffer.create(10), 4, 4) + t:check(e4 ~= nil, "short pixels") +end + +-- fuzz: random block data of every kind and size +local samples = {} +for _, c in Fx.cases do + table.insert(samples, buffer.fromstring(c.data)) +end +for _, kind in { "bc1", "bc2", "bc3", "bc4", "bc4s", "bc5", "bc5s", "bc6h", "bc6hs", "bc7" } do + t:fuzz("decode " .. kind, function(b: buffer) + local n = buffer.len(b) // Bcn.BLOCK[kind] + if n < 1 then + return Bcn.decode(kind, b, 0, 4, 4) + end + return Bcn.decode(kind, b, 0, 4 * n - 1, 3) + end, samples, { mutations = 2 }) +end +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..5486408 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,27 @@ do jitTune(false) end end +do + -- textures (ws-tex): codecs/image/Bcn on a 256 x 256 image (tools/fixtures/bcn.py); MB/s of rgba8 output (decode) + -- or input (encode); BC6H of rgbaf32 output + local Bcn = require("@formats/codecs/image/Bcn") + local BB = require("@tests/gen/bcn_bench") + local w, h = BB.w, BB.h + local px = buffer.fromstring(BB.rgba) + for _, kind in { "bc1", "bc3", "bc5" } do + local blocks = Bcn.encode(kind, px, w, h) :: buffer + bench("bcn decode " .. kind .. " 256x256", 5, w * h * 4, function() + Bcn.decode(kind, blocks, 0, w, h) + end) + bench("bcn encode " .. kind .. " 256x256", 2, w * h * 4, function() + Bcn.encode(kind, px, w, h) + end) + end + local b7, b6 = buffer.fromstring(BB.bc7), buffer.fromstring(BB.bc6h) + bench("bcn decode bc7 256x256", 5, w * h * 4, function() + Bcn.decode("bc7", b7, 0, w, h) + end) + bench("bcn decode bc6h 256x256", 5, w * h * 16, function() + Bcn.decode("bc6h", b6, 0, w, h) + end) +end diff --git a/tools/fixtures/_tex_reference.py b/tools/fixtures/_tex_reference.py new file mode 100644 index 0000000..af25edf --- /dev/null +++ b/tools/fixtures/_tex_reference.py @@ -0,0 +1,107 @@ +# Shared by the texture fixture generators (bcn.py, etc.py, dds.py, ktx.py): reference block decoders through nix. +# godot(ctx, jobs) Godot 4's Image.decompress (bcdec for BC1-7, etcpak for ETC1 / ETC2 / EAC): each job is +# (raw block bytes, w, h, godot format number, float) -> rgba8 bytes, or rgbaf32 little-endian +# bytes when float is true +# pillow(ctx, jobs) Pillow's DDS reader (BcnDecode.c): each job is (dds bytes) -> (mode, raw bytes) +# dds_dx10(w, h, dxgi, data) / dds_fourcc(w, h, fourcc, data): minimal DDS files around block data +import os, shutil, struct, tempfile + +# Godot Image.Format numbers (checked against Godot 4.7) +GODOT = {"bc1": 17, "bc2": 18, "bc3": 19, "bc4": 20, "bc5": 21, "bc7": 22, "bc6hs": 23, "bc6h": 24, "etc1": 25, + "eac_r11": 26, "eac_r11s": 27, "eac_rg11": 28, "eac_rg11s": 29, "etc2_rgb": 30, "etc2_rgba": 31, + "etc2_rgba1": 32} + +GD_SCRIPT = r'''extends SceneTree +func _init(): + var dir = OS.get_cmdline_user_args()[0] + var lines = FileAccess.get_file_as_string(dir + "/jobs.txt").split("\n", false) + for line in lines: + var a = line.split(" ") + var data = FileAccess.get_file_as_bytes(dir + "/" + a[0]) + var img = Image.create_from_data(int(a[1]), int(a[2]), false, int(a[3]), data) + img.decompress() + if a[4] == "1": + img.convert(Image.FORMAT_RGBAF) + else: + img.convert(Image.FORMAT_RGBA8) + var f = FileAccess.open(dir + "/" + a[0] + ".out", FileAccess.WRITE) + f.store_buffer(img.get_data()) + f.close() + quit() +''' + + +def godot(ctx, jobs): + work = tempfile.mkdtemp(prefix="formats-godot-") + try: + lines = [] + for i, (data, w, h, fmt, flt) in enumerate(jobs): + with open(os.path.join(work, "j%d" % i), "wb") as f: + f.write(data) + lines.append("j%d %d %d %d %d" % (i, w, h, fmt, 1 if flt else 0)) + with open(os.path.join(work, "jobs.txt"), "w") as f: + f.write("\n".join(lines) + "\n") + with open(os.path.join(work, "run.gd"), "w") as f: + f.write(GD_SCRIPT) + ctx.nix("godot", ["godot", "--headless", "--script", os.path.join(work, "run.gd"), "--", work]) + out = [] + for i in range(len(jobs)): + with open(os.path.join(work, "j%d.out" % i), "rb") as f: + out.append(f.read()) + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + +def pillow(ctx, files): + """files: list of bytes (any format Pillow reads) -> list of (mode, w, h, raw bytes)""" + work = tempfile.mkdtemp(prefix="formats-pillow-") + try: + for i, data in enumerate(files): + with open(os.path.join(work, "f%d" % i), "wb") as f: + f.write(data) + code = ("import os\nfrom PIL import Image\nw=%r\nfor i in range(%d):\n" + " im=Image.open(os.path.join(w,'f%%d'%%i)); im.load()\n" + " open(os.path.join(w,'f%%d.out'%%i),'wb').write(im.tobytes())\n" + " open(os.path.join(w,'f%%d.mode'%%i),'w').write('%%s %%d %%d'%%(im.mode,im.width,im.height))\n") % (work, len(files)) + ctx.python(["pillow"], code) + out = [] + for i in range(len(files)): + mode, w, h = open(os.path.join(work, "f%d.mode" % i)).read().split() + out.append((mode, int(w), int(h), open(os.path.join(work, "f%d.out" % i), "rb").read())) + return out + finally: + shutil.rmtree(work, ignore_errors=True) + + +def dds_header(w, h, pf, caps=0x1000, mips=0, flags=0x1007, pitch=0, depth=0, caps2=0): + if mips: + flags |= 0x20000 + return (b"DDS " + struct.pack("<7I", 124, flags, h, w, pitch, depth, mips) + b"\0" * 44 + pf + + struct.pack("<4I", caps, caps2, 0, 0) + b"\0" * 4) + + +def dds_dx10(w, h, dxgi, data, array=1, misc=0, mips=0, caps2=0): + pf = struct.pack("<2I", 32, 4) + b"DX10" + b"\0" * 20 + return dds_header(w, h, pf, mips=mips, caps2=caps2) + struct.pack("<5I", dxgi, 3, misc, array, 0) + data + + +def dds_fourcc(w, h, fourcc, data, mips=0, caps2=0): + pf = struct.pack("<2I", 32, 4) + fourcc + b"\0" * 20 + return dds_header(w, h, pf, mips=mips, caps2=caps2) + data + + +def rgba_from(mode, raw): + """Pillow raw bytes of mode L / RGB / RGBA -> rgba8 bytes""" + if mode == "RGBA": + return raw + out = bytearray() + if mode == "L": + for v in raw: + out += bytes((v, v, v, 255)) + elif mode == "RGB": + for i in range(0, len(raw), 3): + out += raw[i:i + 3] + b"\xff" + else: + raise ValueError(mode) + return bytes(out) diff --git a/tools/fixtures/bcn.py b/tools/fixtures/bcn.py new file mode 100644 index 0000000..aeb90b8 --- /dev/null +++ b/tools/fixtures/bcn.py @@ -0,0 +1,119 @@ +# BCn fixtures (tools/fixtures.py): random BC1..BC7 blocks (every BC7 mode and BC6H mode forced in turn, the BC1 +# 3-colour mode, odd image sizes) decoded by two references: Pillow's DDS reader and Godot 4 (bcdec); plus encoder +# baselines: test images and the PSNR Pillow's own BC1 / BC3 / BC5 encoder reaches on them. +# tests/gen/bcn.luau { cases = { { name, kind, w, h, data, pillow?, godot?, tol } }, enc = { { name, w, h, +# rgba, psnr = { bc1, bc3, bc5 } } } } (pillow / godot: rgba8 bytes, or rgbaf32 for BC6H) +# tests/gen/bcn_bench.luau a 256 x 256 image and random BC1 / BC6H / BC7 blocks for tools/bench.luau +import importlib.util, math, os, random, struct + +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +DXGI = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc5s": 84, "bc6h": 95, "bc6hs": 96, "bc7": 98} +BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc5s": 16, "bc6h": 16, "bc6hs": 16, "bc7": 16} +BC6_HEADERS = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30, 3, 7, 11, 15, 19, 23, 27, 31] + + +def blocks(rng, kind, n, mode=None): + out = bytearray() + for _ in range(n): + b = bytearray(rng.getrandbits(8) for _ in range(BLOCK[kind])) + if kind == "bc7" and mode is not None: + b[0] = (b[0] & ~((2 << mode) - 1) & 0xFF) | (1 << mode) + elif kind.startswith("bc6h") and mode is not None: + bitsn = 2 if mode < 2 else 5 + b[0] = (b[0] & ~((1 << bitsn) - 1) & 0xFF) | mode + out += b + return bytes(out) + + +def test_image(w, h, rng, alpha): + px = bytearray() + for y in range(h): + for x in range(w): + r = int(128 + 100 * math.sin(x / 7.0) * math.cos(y / 11.0)) + g = int(255 * x / (w - 1)) + b = int(255 * y / (h - 1)) if (x // 16 + y // 16) % 2 else 40 + n = rng.randrange(-12, 13) + r, g, b = [max(0, min(255, v + n)) for v in (r, g, b)] + a = 255 + if alpha: + a = 0 if (x - w / 2) ** 2 + (y - h / 2) ** 2 < (w / 4) ** 2 else 255 + px += bytes((r, g, b, a)) + return bytes(px) + + +def psnr(a, b, channels): + se, n = 0, 0 + for i in range(0, len(a), 4): + for c in channels: + d = a[i + c] - b[i + c] + se += d * d + n += 1 + return 99.0 if se == 0 else 10 * math.log10(255 * 255 * n / se) + + +def generate(ctx): + rng = random.Random(7) + cases = [] + + def add(name, kind, w, h, data): + cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data}) + + for kind in ("bc1", "bc2", "bc3", "bc4", "bc5", "bc5s"): + add(kind + " 32x32", kind, 32, 32, blocks(rng, kind, 64)) + add(kind + " 13x7", kind, 13, 7, blocks(rng, kind, 8)) + for m in range(8): + add("bc7 mode %d" % m, "bc7", 32, 16, blocks(rng, "bc7", 32, m)) + add("bc7 15x9", "bc7", 15, 9, blocks(rng, "bc7", 12)) + for kind in ("bc6h", "bc6hs"): + for m in BC6_HEADERS: + add("%s mode %d" % (kind, m), kind, 16, 16, blocks(rng, kind, 16, m)) + # Pillow (BC1..BC5, BC5S, BC7, BC6H as clamped 8-bit) + files = [R.dds_dx10(c["w"], c["h"], DXGI[c["kind"]], c["data"]) for c in cases] + for c, (mode, w, h, raw) in zip(cases, R.pillow(ctx, files)): + c["pillow"] = R.rgba_from(mode, raw) + # Godot (bcdec): everything but the signed BC5 (no Godot format); BC6H as floats + gj, gi = [], [] + for i, c in enumerate(cases): + if c["kind"] in R.GODOT: + gj.append((c["data"], c["w"], c["h"], R.GODOT[c["kind"]], c["kind"].startswith("bc6h"))) + gi.append(i) + for i, out in zip(gi, R.godot(ctx, gj)): + cases[i]["godot"] = out + + # encoder baselines: Pillow's encoder on the same images, decoded by Pillow + enc = [] + for name, w, h, alpha in (("photo 64x64", 64, 64, False), ("alpha 64x48", 64, 48, True), ("odd 37x21", 37, 21, False)): + px = test_image(w, h, rng, alpha) + e = {"name": name, "w": w, "h": h, "rgba": px, "psnr": {}} + enc.append(e) + import tempfile, shutil + work = tempfile.mkdtemp(prefix="formats-bcn-") + try: + for i, e in enumerate(enc): + open(os.path.join(work, "src%d" % i), "wb").write(e["rgba"]) + code = ("import os\nfrom PIL import Image\nw=%r\n" + "for i, (W, H) in enumerate(%r):\n" + " im=Image.frombytes('RGBA',(W,H),open(os.path.join(w,'src%%d'%%i),'rb').read())\n" + " for pf in ('DXT1','DXT5','BC5'):\n" + " p=os.path.join(w,'e%%d_%%s.dds'%%(i,pf))\n" + " (im if pf!='BC5' else im.convert('RGB')).save(p,pixel_format=pf)\n" + " back=Image.open(p).convert('RGBA')\n" + " open(p+'.rgba','wb').write(back.tobytes())\n") % (work, [(e["w"], e["h"]) for e in enc]) + ctx.python(["pillow"], code) + for i, e in enumerate(enc): + for pf, kind, ch in (("DXT1", "bc1", (0, 1, 2)), ("DXT5", "bc3", (0, 1, 2, 3)), ("BC5", "bc5", (0, 1))): + back = open(os.path.join(work, "e%d_%s.dds.rgba" % (i, pf)), "rb").read() + e["psnr"][kind] = psnr(e["rgba"], back, ch) + finally: + shutil.rmtree(work, ignore_errors=True) + ctx.emit("bcn", {"cases": cases, "enc": enc}) + + # bench: a 512 x 512 image, and random BC7 blocks of every mode + w = h = 256 + px = test_image(w, h, rng, True) + bench = {"w": w, "h": h, "rgba": px, "bc7": blocks(rng, "bc7", (w // 4) * (h // 4)), + "bc1": blocks(rng, "bc1", (w // 4) * (h // 4)), "bc6h": blocks(rng, "bc6h", (w // 4) * (h // 4), 3)} + ctx.emit("bcn_bench", bench) From 27518c55c53ea1486bf810c9fbfda3eb4b7971d6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:05:28 -0500 Subject: [PATCH 10/54] ws-3d3-b: model/lwo: typed tables (no new type diagnostic) --- src/Formats/model/lwo/Build.luau | 16 +++++++++------- src/Formats/model/lwo/Parse.luau | 6 +++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Formats/model/lwo/Build.luau b/src/Formats/model/lwo/Build.luau index 0d62bbd..6a5ccb1 100644 --- a/src/Formats/model/lwo/Build.luau +++ b/src/Formats/model/lwo/Build.luau @@ -108,7 +108,7 @@ local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { table.insert(g.polys, i - 1) end end - local rank = { poly = 1, patch = 2, line = 3, point = 4 } + local rank: { [string]: number } = { poly = 1, patch = 2, line = 3, point = 4 } table.sort(groups, function(a: Group, b: Group): boolean if a.material ~= b.material then return a.material < b.material @@ -121,7 +121,7 @@ end -- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners: { number }): { number } local n = #corners - local out = table.create(n) + local out = table.create(n) :: { number } out[1] = corners[1] for k = 2, n do out[k] = corners[n - k + 2] @@ -175,7 +175,7 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: for _, f in g.polys do local corners = ordered(layer.polys[f + 1].corners) local n = #corners - local vs = table.create(n) + local vs = table.create(n) :: { number } for k = 1, n do vs[k] = vertex(f, corners[k]) end @@ -249,8 +249,8 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: end local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } if #morphs > 0 then - local targets = {} - local targetNames = {} + local targets: { { [string]: Types.Accessor } } = {} + local targetNames: { string } = {} for _, m in morphs do local d = buffer.create(nv * 12) for v = 1, nv do @@ -267,7 +267,8 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: writef32(d, (v - 1) * 12 + 8, -dz) end end - table.insert(targets, { POSITION = Scene.accessor(d, "f32", 3, nv) }) + local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) } + table.insert(targets, tgt) table.insert(targetNames, m.name) end prim.targets = targets @@ -403,7 +404,8 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S local prims = {} for _, g in groups do local mat = scene.materials[g.material] - local vcol = mat and mat.extras and mat.extras.lwo and mat.extras.lwo.vcol + local ex: any = mat and mat.extras + local vcol = ex and ex.lwo and ex.lwo.vcol local pa = table.clone(attrs) nc = 0 for _, map in layer.maps do diff --git a/src/Formats/model/lwo/Parse.luau b/src/Formats/model/lwo/Parse.luau index 21d985c..80d8520 100644 --- a/src/Formats/model/lwo/Parse.luau +++ b/src/Formats/model/lwo/Parse.luau @@ -139,7 +139,7 @@ local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: nu local npts = #layer.pts // 3 while r:remaining() >= 2 do local n = bit32.band(r:u16be(), 0x3FF) - local corners = table.create(n) + local corners = table.create(n) :: { number } for i = 1, n do local p = vx(r) + ptBase if p >= npts and not r.err then @@ -165,7 +165,7 @@ local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): st local npts = #layer.pts // 3 while r:remaining() >= 4 do local n = r:u16be() - local corners = table.create(n) + local corners = table.create(n) :: { number } for i = 1, n do local p = r:u16be() if p >= npts and not r.err then @@ -224,7 +224,7 @@ local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: while r:remaining() >= 2 do local p = vx(r) + ptBase local f = if perPoly then vx(r) + polyBase else -1 - local v = table.create(want, 1) + local v = table.create(want, 1) :: { number } for c = 1, dims do local x = r:f32be() if c <= want then From be643a66c8fee48c47858adccb6207c144560c48 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:09:27 -0500 Subject: [PATCH 11/54] ws-tex: codecs/image/Etc (ETC1, ETC2 RGB/RGBA/RGB A1, EAC R11/RG11 decode) Written from the Khronos Data Format Spec 1.3. Exact against Godot 4 (etcpak) for ETC1 / ETC2 in every mode, EAC unsigned within 1 (8-bit rounding); RGB A1 checked as punch-through rules over Godot's ETC2 RGB decode; signed EAC against the spec rule in the fixture generator. --- docs/FORMATS.md | 3 + src/Formats/codecs/image/Etc.luau | 315 ++++++++++++++++++++++++++++++ tests/codecs/etc.luau | 129 ++++++++++++ tools/fixtures/etc.py | 128 ++++++++++++ 4 files changed, 575 insertions(+) create mode 100644 src/Formats/codecs/image/Etc.luau create mode 100644 tests/codecs/etc.luau create mode 100644 tools/fixtures/etc.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..7b021d0 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -114,8 +114,11 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/font/Cff: Compact Font Format (Adobe TN #5176) and Type 2 charstrings (TN #5177): the outlines of OpenType fonts - codecs/font/TrueType: the sfnt font container (TrueType .ttf, OpenType .otf with CFF outlines, collections .ttc) parsed - **image** + - codecs/image/Bcn: the BCn block-compressed texture codecs, shared by the texture formats (DDS, KTX, VTF, BLP, ...): - codecs/image/Blend: layer compositing on rgba8 buffers (straight alpha): source-over with the separable and non-separable - codecs/image/Dct: the 8x8 DCTs JPEG, Motion-JPEG and MPEG-1 share (native; never throws). + - codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar + - codecs/image/Half: IEEE 754 binary16 ("half") <-> number, for the float texel formats (DDS / KTX R16F..., BC6H, - codecs/image/Jpeg: the JPEG codec (ITU T.81) on byte ranges: image/jpeg is a thin format over it, and the Motion-JPEG - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, - codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette diff --git a/src/Formats/codecs/image/Etc.luau b/src/Formats/codecs/image/Etc.luau new file mode 100644 index 0000000..4c8720f --- /dev/null +++ b/src/Formats/codecs/image/Etc.luau @@ -0,0 +1,315 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Etc: the Ericsson / Khronos block texture codecs, decode only: ETC1, ETC2 RGB (with the T, H and planar +-- modes), ETC2 RGBA (an EAC alpha block + ETC2 colour), ETC2 RGB A1 (punch-through alpha) and EAC R11 / RG11 +-- (unsigned and signed). Written from the Khronos Data Format Specification 1.3, section 21 (ETC1 / ETC2 / EAC); new +-- in formats-luau. Shared by the texture formats (KTX, PVR, ...). Never throws: the caller gets a message instead. +-- +-- local px, err = Etc.decode("etc2_rgba", buf, offset, w, h) -- rgba8 pixels +-- local px16 = Etc.decode("eac_rg11", buf, offset, w, h, nil, 0, true) -- rgba16 (EAC keeps its 11 bits) +-- Etc.size("etc1", w, h) -- bytes of the block data +-- +-- Kinds: etc1, etc2_rgb, etc2_rgba, etc2_rgba1, eac_r11, eac_r11s, eac_rg11, eac_rg11s. R11 decodes to grey (r = g = b), +-- RG11 to red + green (blue 0); signed values are biased (-1 -> 1, 0 -> 128, +1 -> 255; rgba16: 0 / 32768 / 65535). +local Etc = {} + +Etc.BLOCK = table.freeze({ etc1 = 8, etc2_rgb = 8, etc2_rgba = 16, etc2_rgba1 = 8, eac_r11 = 8, eac_r11s = 8, eac_rg11 = 16, eac_rg11s = 16 }) :: { [string]: number } + +local readu8, readu32, writeu8, writeu16, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu16, buffer.writeu32 +local band, rshift, byteswap = bit32.band, bit32.rshift, bit32.byteswap + +-- ------------------------------------------------------------------------------------------------ tables +local MOD = { -- the ETC1 intensity modifiers per table: index (msb * 2 + lsb) -> a, b, -a, -b + { 2, 8, -2, -8 }, + { 5, 17, -5, -17 }, + { 9, 29, -9, -29 }, + { 13, 42, -13, -42 }, + { 18, 60, -18, -60 }, + { 24, 80, -24, -80 }, + { 33, 106, -33, -106 }, + { 47, 183, -47, -183 }, +} +local DIST = { 3, 6, 11, 16, 23, 32, 41, 64 } -- T / H mode distances +local EAC = { + { -3, -6, -9, -15, 2, 5, 8, 14 }, + { -3, -7, -10, -13, 2, 6, 9, 12 }, + { -2, -5, -8, -13, 1, 4, 7, 12 }, + { -2, -4, -6, -13, 1, 3, 5, 12 }, + { -3, -6, -8, -12, 2, 5, 7, 11 }, + { -3, -7, -9, -11, 2, 6, 8, 10 }, + { -4, -7, -8, -11, 3, 6, 7, 10 }, + { -3, -5, -8, -11, 2, 4, 7, 10 }, + { -2, -6, -8, -10, 1, 5, 7, 9 }, + { -2, -5, -8, -10, 1, 4, 7, 9 }, + { -2, -4, -8, -10, 1, 3, 7, 9 }, + { -2, -5, -7, -10, 1, 4, 6, 9 }, + { -3, -4, -7, -10, 2, 3, 6, 9 }, + { -1, -2, -3, -10, 0, 1, 2, 9 }, + { -4, -6, -8, -9, 3, 5, 7, 8 }, + { -3, -5, -7, -9, 2, 4, 6, 8 }, +} + +local function clamp8(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end +local function rgb(r: number, g: number, b: number): number + return clamp8(r) + clamp8(g) * 256 + clamp8(b) * 65536 + 0xFF000000 +end + +-- ------------------------------------------------------------------------------------------------ colour blocks +-- blk: 16 u32 rgba8 pixels in raster order (y * 4 + x) +local P = table.create(4, 0) -- T / H paint colours (rgba8 u32) + +local function be32(src: buffer, p: number): number + return byteswap(readu32(src, p)) +end + +-- the 2-bit pixel index of pixel i (column-major: i = x * 4 + y) +local function pix(lo: number, i: number): number + return band(rshift(lo, i + 15), 2) + band(rshift(lo, i), 1) +end + +-- ETC1 / ETC2 colour block at p into blk. etc2: T / H / planar modes; punch: the RGB A1 variant (bit 33 = opaque). +local function colour(src: buffer, p: number, blk: buffer, etc2: boolean, punch: boolean) + local hi, lo = be32(src, p), be32(src, p + 4) + local diffBit = band(rshift(hi, 1), 1) + local flip = band(hi, 1) + local opaque = not punch or diffBit == 1 + local r1, g1, b1, r2, g2, b2 + if not punch and diffBit == 0 then + r1, r2 = band(rshift(hi, 28), 15) * 17, band(rshift(hi, 24), 15) * 17 + g1, g2 = band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + b1, b2 = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17 + else + local R, G, B = band(rshift(hi, 27), 31), band(rshift(hi, 19), 31), band(rshift(hi, 11), 31) + local dR, dG, dB = band(rshift(hi, 24), 7), band(rshift(hi, 16), 7), band(rshift(hi, 8), 7) + if dR >= 4 then + dR -= 8 + end + if dG >= 4 then + dG -= 8 + end + if dB >= 4 then + dB -= 8 + end + local R2, G2, B2 = R + dR, G + dG, B + dB + if etc2 and (R2 < 0 or R2 > 31) then + -- T mode + local ra = band(rshift(hi, 27), 3) * 4 + band(rshift(hi, 24), 3) + local c1r, c1g, c1b = ra * 17, band(rshift(hi, 20), 15) * 17, band(rshift(hi, 16), 15) * 17 + local c2r, c2g, c2b = band(rshift(hi, 12), 15) * 17, band(rshift(hi, 8), 15) * 17, band(rshift(hi, 4), 15) * 17 + local d = DIST[band(rshift(hi, 2), 3) * 2 + band(hi, 1) + 1] + P[1] = rgb(c1r, c1g, c1b) + P[2] = rgb(c2r + d, c2g + d, c2b + d) + P[3] = rgb(c2r, c2g, c2b) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (G2 < 0 or G2 > 31) then + -- H mode + local q1r = band(rshift(hi, 27), 15) + local q1g = band(rshift(hi, 24), 7) * 2 + band(rshift(hi, 20), 1) + local q1b = band(rshift(hi, 19), 1) * 8 + band(rshift(hi, 15), 7) + local q2r, q2g, q2b = band(rshift(hi, 11), 15), band(rshift(hi, 7), 15), band(rshift(hi, 3), 15) + local order = if q1r * 256 + q1g * 16 + q1b >= q2r * 256 + q2g * 16 + q2b then 1 else 0 + local d = DIST[band(rshift(hi, 2), 1) * 4 + band(hi, 1) * 2 + order + 1] + local c1r, c1g, c1b, c2r, c2g, c2b = q1r * 17, q1g * 17, q1b * 17, q2r * 17, q2g * 17, q2b * 17 + P[1] = rgb(c1r + d, c1g + d, c1b + d) + P[2] = rgb(c1r - d, c1g - d, c1b - d) + P[3] = rgb(c2r + d, c2g + d, c2b + d) + P[4] = rgb(c2r - d, c2g - d, c2b - d) + elseif etc2 and (B2 < 0 or B2 > 31) then + -- planar (always opaque) + local ro = band(rshift(hi, 25), 63) + local go = band(rshift(hi, 24), 1) * 64 + band(rshift(hi, 17), 63) + local bo = band(rshift(hi, 16), 1) * 32 + band(rshift(hi, 11), 3) * 8 + band(rshift(hi, 7), 7) + local rh = band(rshift(hi, 2), 31) * 2 + band(hi, 1) + local gh, bh = band(rshift(lo, 25), 127), band(rshift(lo, 19), 63) + local rv, gv, bv = band(rshift(lo, 13), 63), band(rshift(lo, 6), 127), band(lo, 63) + ro, rh, rv = ro * 4 + rshift(ro, 4), rh * 4 + rshift(rh, 4), rv * 4 + rshift(rv, 4) + go, gh, gv = go * 2 + rshift(go, 6), gh * 2 + rshift(gh, 6), gv * 2 + rshift(gv, 6) + bo, bh, bv = bo * 4 + rshift(bo, 4), bh * 4 + rshift(bh, 4), bv * 4 + rshift(bv, 4) + for y = 0, 3 do + for x = 0, 3 do + local r = (x * (rh - ro) + y * (rv - ro) + 4 * ro + 2) // 4 + local g = (x * (gh - go) + y * (gv - go) + 4 * go + 2) // 4 + local b = (x * (bh - bo) + y * (bv - bo) + 4 * bo + 2) // 4 + writeu32(blk, (y * 4 + x) * 4, rgb(r, g, b)) + end + end + return + else + r1, g1, b1 = R * 8 + rshift(R, 2), G * 8 + rshift(G, 2), B * 8 + rshift(B, 2) + r2, g2, b2 = R2 * 8 + rshift(R2, 2), G2 * 8 + rshift(G2, 2), B2 * 8 + rshift(B2, 2) + end + if not r1 then + -- T / H: the paint colours by index + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local idx = pix(lo, i) + local c = if not opaque and idx == 2 then 0 else P[idx + 1] + writeu32(blk, (y * 4 + x) * 4, c) + end + return + end + end + local t1, t2 = MOD[band(rshift(hi, 5), 7) + 1], MOD[band(rshift(hi, 2), 7) + 1] + for i = 0, 15 do + local x, y = rshift(i, 2), band(i, 3) + local second = if flip == 0 then x >= 2 else y >= 2 + local idx = pix(lo, i) + local c + if not opaque and idx == 2 then + c = 0 + else + local m = if second then t2[idx + 1] else t1[idx + 1] + if not opaque and idx == 0 then + m = 0 + end + if second then + c = rgb((r2 :: number) + m, (g2 :: number) + m, (b2 :: number) + m) + else + c = rgb((r1 :: number) + m, (g1 :: number) + m, (b1 :: number) + m) + end + end + writeu32(blk, (y * 4 + x) * 4, c) + end +end + +-- ------------------------------------------------------------------------------------------------ EAC +local VALS = table.create(16, 0) + +-- the 16 values of the EAC block at p into VALS (raster order): mode "alpha" (8-bit), "u11" / "s11" (11-bit) +local function eac(src: buffer, p: number, mode: string) + local base = readu8(src, p) + local b1 = readu8(src, p + 1) + local mult, tab = rshift(b1, 4), EAC[band(b1, 15) + 1] + -- 48 index bits, pixel 0 (column-major) first: bytes 2..7 big-endian, as 24 + 24 bits + local hiIdx = readu8(src, p + 2) * 65536 + readu8(src, p + 3) * 256 + readu8(src, p + 4) + local loIdx = readu8(src, p + 5) * 65536 + readu8(src, p + 6) * 256 + readu8(src, p + 7) + if mode == "s11" then + if base >= 128 then + base -= 256 + end + if base == -128 then + base = -127 + end + end + for i = 0, 15 do + local idx = if i < 8 then band(rshift(hiIdx, 21 - i * 3), 7) else band(rshift(loIdx, 21 - (i - 8) * 3), 7) + local m = tab[idx + 1] + local v + if mode == "alpha" then + v = clamp8(base + m * mult) + elseif mode == "u11" then + v = if mult == 0 then base * 8 + 4 + m else base * 8 + 4 + m * mult * 8 + v = if v < 0 then 0 elseif v > 2047 then 2047 else v + else + v = if mult == 0 then base * 8 + m else base * 8 + m * mult * 8 + v = if v < -1023 then -1023 elseif v > 1023 then 1023 else v + end + VALS[band(i, 3) * 4 + rshift(i, 2) + 1] = v + end +end + +-- 11-bit values -> 8 / 16 bits +local function to8(v: number, signed: boolean): number + if signed then + return math.floor(v * 127 / 1023 + 0.5) + 128 + end + return math.floor(v * 255 / 2047 + 0.5) +end +local function to16(v: number, signed: boolean): number + if signed then + return math.floor((v + 1023) * 65535 / 2046 + 0.5) + end + return v * 32 + rshift(v, 6) +end + +-- ------------------------------------------------------------------------------------------------ decode +-- size(kind, w, h) -> bytes of the block data | nil for an unknown kind +function Etc.size(kind: string, w: number, h: number): number? + local b = Etc.BLOCK[kind] + return if b then ((w + 3) // 4) * ((h + 3) // 4) * b else nil +end + +-- decode(kind, src, offset, w, h, out?, outOffset?, wide?) -> pixels | nil, message. rgba8, or rgba16 for the EAC +-- kinds when wide is true. +function Etc.decode(kind: string, src: buffer, offset: number, w: number, h: number, out: buffer?, outOffset: number?, wide: boolean?): (buffer?, string?) + local bytes = Etc.BLOCK[kind] + if not bytes then + return nil, "unsupported: unknown block format " .. tostring(kind) + end + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, "bad image size" + end + local need = Etc.size(kind, w, h) :: number + if offset < 0 or offset + need > buffer.len(src) then + return nil, "truncated: block data runs past the end" + end + local isEac = string.sub(kind, 1, 3) == "eac" + local w16 = isEac and wide == true + local bpp = if w16 then 8 else 4 + local oo = outOffset or 0 + local dst = out or buffer.create(w * h * bpp) + if oo + w * h * bpp > buffer.len(dst) then + return nil, "output buffer too small" + end + local signed = kind == "eac_r11s" or kind == "eac_rg11s" + local two = kind == "eac_rg11" or kind == "eac_rg11s" + local mode11 = if signed then "s11" else "u11" + local etc2 = kind ~= "etc1" + local punch = kind == "etc2_rgba1" + local blk = buffer.create(16 * bpp) + local bw, bh = (w + 3) // 4, (h + 3) // 4 + local p = offset + local rowBytes = w * bpp + for by = 0, bh - 1 do + local rows = math.min(4, h - by * 4) + for bx = 0, bw - 1 do + if isEac then + eac(src, p, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + local q = to16(v, signed) + writeu16(blk, i * 8, q) + writeu16(blk, i * 8 + 2, if two then 0 else q) + writeu16(blk, i * 8 + 4, if two then 0 else q) + writeu16(blk, i * 8 + 6, 65535) + else + local q = to8(v, signed) + writeu32(blk, i * 4, if two then q + 0xFF000000 else q + q * 256 + q * 65536 + 0xFF000000) + end + end + if two then + eac(src, p + 8, mode11) + for i = 0, 15 do + local v = VALS[i + 1] + if w16 then + writeu16(blk, i * 8 + 2, to16(v, signed)) + else + writeu8(blk, i * 4 + 1, to8(v, signed)) + end + end + end + elseif kind == "etc2_rgba" then + colour(src, p + 8, blk, true, false) + eac(src, p, "alpha") + for i = 0, 15 do + writeu8(blk, i * 4 + 3, VALS[i + 1]) + end + else + colour(src, p, blk, etc2, punch) + end + p += bytes + local cols = math.min(4, w - bx * 4) + local base = oo + (by * 4) * rowBytes + bx * 4 * bpp + for y = 0, rows - 1 do + buffer.copy(dst, base + y * rowBytes, blk, y * 4 * bpp, cols * bpp) + end + end + end + return dst, nil +end + +return Etc diff --git a/tests/codecs/etc.luau b/tests/codecs/etc.luau new file mode 100644 index 0000000..6d5da15 --- /dev/null +++ b/tests/codecs/etc.luau @@ -0,0 +1,129 @@ +-- codecs/image/Etc tests: random ETC1 / ETC2 (every mode: individual, differential, T, H, planar; RGB A1 opaque and +-- transparent; RGBA with EAC alpha) and EAC R11 / RG11 (unsigned, signed, multiplier 0) blocks against Godot 4's +-- decode (etcpak); odd sizes; the 16-bit EAC output; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/etc.py. +local T = require("@tests/T") +local Etc = require("@formats/codecs/image/Etc") +local Fx = require("@tests/gen/etc") + +local t = T.suite("etc") + +local function maxDiff(a: buffer, b: buffer, n: number, channels: { number }): (number, number) + local worst, at = 0, -1 + for i = 0, n - 1 do + for _, c in channels do + local d = math.abs(buffer.readu8(a, i * 4 + c) - buffer.readu8(b, i * 4 + c)) + if d > worst then + worst, at = d, i + end + end + end + return worst, at +end + +local worstEac = 0 +for _, c in Fx do + local src = buffer.fromstring(c.data) + local px, err = Etc.decode(c.kind, src, 0, c.w, c.h) + t:check(px, c.name .. ": " .. tostring(err)) + local n = c.w * c.h + t:eq(buffer.len(px), n * 4, c.name .. ": size") + local eacKind = string.sub(c.kind, 1, 3) == "eac" + if c.spec then + -- signed EAC against the spec rule (values -1023..1023), biased into 8 bits + local two = c.kind == "eac_rg11s" + local bad = 0 + for i = 0, n - 1 do + for ch = 0, if two then 1 else 0 do + local want = math.floor(c.spec[i * 2 + ch + 1] * 127 / 1023 + 0.5) + 128 + if buffer.readu8(px, i * 4 + ch) ~= want then + bad += 1 + end + end + end + t:eq(bad, 0, c.name .. ": against the spec values") + elseif c.kind == "etc2_rgba1" then + -- Godot decoded the blocks as ETC2 RGB: opaque blocks match it; transparent ones have index 2 transparent + -- black and indexes 1 / 3 unchanged (index 0 drops its modifier in the differential mode); planar is opaque + local g = buffer.fromstring(c.godot) + local bw = (c.w + 3) // 4 + local bad = 0 + for y = 0, c.h - 1 do + for x = 0, c.w - 1 do + local bo = ((y // 4) * bw + x // 4) * 8 + local hi = bit32.byteswap(buffer.readu32(src, bo)) + local lo = bit32.byteswap(buffer.readu32(src, bo + 4)) + local i = (x % 4) * 4 + y % 4 + local idx = bit32.band(bit32.rshift(lo, i + 15), 2) + bit32.band(bit32.rshift(lo, i), 1) + local opaque = bit32.band(hi, 2) ~= 0 + local function ch(v: number, at: number): number + v = bit32.band(bit32.rshift(hi, at), 31) + (function(d: number): number + return if d >= 4 then d - 8 else d + end)(bit32.band(bit32.rshift(hi, at - 3), 7)) + return v + end + local r2, g2, b2 = ch(0, 27), ch(0, 19), ch(0, 11) + local planar = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and (b2 < 0 or b2 > 31) + local diff = r2 >= 0 and r2 <= 31 and g2 >= 0 and g2 <= 31 and b2 >= 0 and b2 <= 31 + local o = (y * c.w + x) * 4 + local mine, ref = buffer.readu32(px, o), buffer.readu32(g, o) + if opaque or planar then + bad += if mine == ref then 0 else 1 + elseif idx == 2 then + bad += if mine == 0 then 0 else 1 + elseif idx ~= 0 or not diff then + bad += if mine == ref then 0 else 1 + end + end + end + t:eq(bad, 0, c.name .. ": punch-through rules over Godot's ETC2 RGB decode") + else + local g = buffer.fromstring(c.godot) + local chans = if c.kind == "eac_r11" then { 0 } elseif eacKind then { 0, 1 } else { 0, 1, 2, 3 } + local d, at = maxDiff(px, g, n, chans) + if eacKind then + -- Godot keeps EAC as 16-bit / half floats and converts to 8 bits with its own rounding + worstEac = math.max(worstEac, d) + t:check(d <= 1, string.format("%s: %d off Godot at pixel %d", c.name, d, at)) + else + t:check(d == 0, string.format("%s: %d off Godot at pixel %d", c.name, d, at)) + end + end + -- 16-bit EAC agrees with the 8-bit output + if eacKind then + local p16 = Etc.decode(c.kind, src, 0, c.w, c.h, nil, 0, true) :: buffer + t:eq(buffer.len(p16), n * 8, c.name .. ": rgba16 size") + local ok = true + for i = 0, n - 1 do + local v16 = buffer.readu16(p16, i * 8) + ok = ok and math.abs(math.floor(v16 / 257 + 0.5) - buffer.readu8(px, i * 4)) <= 1 + end + t:check(ok, c.name .. ": rgba16 ~ rgba8") + end + -- from / into offsets + local big = buffer.create(buffer.len(src) + 3) + buffer.copy(big, 3, src) + local out = buffer.create(n * 4 + 4) + Etc.decode(c.kind, big, 3, c.w, c.h, out, 4) + t:check(buffer.readstring(out, 4, n * 4) == buffer.tostring(px), c.name .. ": offsets") +end +t:note("%d block images match Godot (EAC within %d)", #Fx, worstEac) + +do + local _, e1 = Etc.decode("etc3", buffer.create(8), 0, 4, 4) + t:check(e1 and string.find(e1, "unsupported") ~= nil, "unknown kind") + local _, e2 = Etc.decode("etc2_rgba", buffer.create(8), 0, 4, 4) + t:check(e2 and string.find(e2, "truncated") ~= nil, "short data") + t:eq(Etc.size("etc2_rgba", 5, 5), 64, "size") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, buffer.fromstring(c.data)) +end +for kind in Etc.BLOCK do + t:fuzz("decode " .. kind, function(b: buffer) + local n = buffer.len(b) // Etc.BLOCK[kind] + return Etc.decode(kind, b, 0, math.max(1, 4 * n - 2), 4) + end, samples, { mutations = 2 }) +end +t:done() diff --git a/tools/fixtures/etc.py b/tools/fixtures/etc.py new file mode 100644 index 0000000..64657d1 --- /dev/null +++ b/tools/fixtures/etc.py @@ -0,0 +1,128 @@ +# ETC fixtures (tools/fixtures.py): random ETC1 / ETC2 / EAC blocks, sorted by mode so that every ETC2 mode +# (individual, differential, T, H, planar; punch-through opaque and transparent) and every EAC multiplier case is +# covered, decoded by Godot 4 (etcpak's decoder, through Image.decompress). +# tests/gen/etc.luau { { name, kind, w, h, data, godot (rgba8 bytes) } } +import importlib.util, os, random + +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + + +def mode(b, punch): + """the ETC2 mode of an 8-byte colour block""" + hi = int.from_bytes(b[:4], "big") + if not punch and not (hi >> 1) & 1: + return "individual" + def s3(v): + return v - 8 if v >= 4 else v + r, g, bb = (hi >> 27) & 31, (hi >> 19) & 31, (hi >> 11) & 31 + dr, dg, db = s3((hi >> 24) & 7), s3((hi >> 16) & 7), s3((hi >> 8) & 7) + if not 0 <= r + dr <= 31: + return "T" + if not 0 <= g + dg <= 31: + return "H" + if not 0 <= bb + db <= 31: + return "planar" + return "differential" + + +def colour_blocks(rng, n, want, punch=False, opaque=None): + out = bytearray() + while len(out) < n * 8: + b = bytearray(rng.getrandbits(8) for _ in range(8)) + if opaque is not None: + b[3] = (b[3] & 0xFD) | (2 if opaque else 0) + if mode(b, punch) == want: + out += b + return bytes(out) + + +def eac_blocks(rng, n, zero_mult=False): + out = bytearray() + for _ in range(n): + b = bytearray(rng.getrandbits(8) for _ in range(8)) + if zero_mult: + b[1] &= 0x0F + out += b + return bytes(out) + + +EAC = [[-3, -6, -9, -15, 2, 5, 8, 14], [-3, -7, -10, -13, 2, 6, 9, 12], [-2, -5, -8, -13, 1, 4, 7, 12], + [-2, -4, -6, -13, 1, 3, 5, 12], [-3, -6, -8, -12, 2, 5, 7, 11], [-3, -7, -9, -11, 2, 6, 8, 10], + [-4, -7, -8, -11, 3, 6, 7, 10], [-3, -5, -8, -11, 2, 4, 7, 10], [-2, -6, -8, -10, 1, 5, 7, 9], + [-2, -5, -8, -10, 1, 4, 7, 9], [-2, -4, -8, -10, 1, 3, 7, 9], [-2, -5, -7, -10, 1, 4, 6, 9], + [-3, -4, -7, -10, 2, 3, 6, 9], [-1, -2, -3, -10, 0, 1, 2, 9], [-4, -6, -8, -9, 3, 5, 7, 8], + [-3, -5, -7, -9, 2, 4, 6, 8]] + + +def s11(c): + """signed EAC R11 / RG11 -> the 11-bit values (-1023..1023) per pixel and channel, as a flat list""" + two = c["kind"] == "eac_rg11s" + w, h, data = c["w"], c["h"], c["data"] + bw = (w + 3) // 4 + out = [0] * (w * h * 2) + step = 16 if two else 8 + for bi in range(len(data) // step): + bx, by = bi % bw, bi // bw + for ch in range(2 if two else 1): + b = data[bi * step + ch * 8: bi * step + ch * 8 + 8] + base = b[0] - 256 if b[0] >= 128 else b[0] + base = max(base, -127) + mult, tab = b[1] >> 4, EAC[b[1] & 15] + bits = int.from_bytes(b[2:], "big") + for i in range(16): + m = tab[(bits >> (45 - 3 * i)) & 7] + v = base * 8 + (m * mult * 8 if mult else m) + v = max(-1023, min(1023, v)) + x, y = bx * 4 + i // 4, by * 4 + i % 4 + if x < w and y < h: + out[(y * w + x) * 2 + ch] = v + return out + + +def generate(ctx): + rng = random.Random(11) + cases = [] + + def add(name, kind, w, h, data): + cases.append({"name": name, "kind": kind, "w": w, "h": h, "data": data}) + + add("etc1 individual", "etc1", 16, 16, colour_blocks(rng, 16, "individual")) + add("etc1 differential", "etc1", 16, 16, colour_blocks(rng, 16, "differential")) + add("etc1 random 13x6", "etc1", 13, 6, bytes(rng.getrandbits(8) for _ in range(8 * 8))) + for m in ("individual", "differential", "T", "H", "planar"): + add("etc2_rgb " + m, "etc2_rgb", 16, 16, colour_blocks(rng, 16, m)) + for m in ("differential", "T", "H", "planar"): + for op in (True, False): + add("etc2_rgba1 %s %s" % (m, "opaque" if op else "transparent"), "etc2_rgba1", 16, 16, + colour_blocks(rng, 16, m, True, op)) + for m in ("individual", "differential", "T", "H", "planar"): + rgba = bytearray() + col = colour_blocks(rng, 16, m) + alpha = eac_blocks(rng, 16, m == "planar") + for i in range(16): + rgba += alpha[i * 8:i * 8 + 8] + col[i * 8:i * 8 + 8] + add("etc2_rgba " + m, "etc2_rgba", 16, 16, bytes(rgba)) + for kind in ("eac_r11", "eac_r11s"): + add(kind, kind, 16, 16, eac_blocks(rng, 16)) + add(kind + " multiplier 0", kind, 8, 8, eac_blocks(rng, 4, True)) + for kind in ("eac_rg11", "eac_rg11s"): + add(kind, kind, 16, 12, eac_blocks(rng, 24)) + add("etc2_rgb 10x5", "etc2_rgb", 10, 5, bytes(rng.getrandbits(8) for _ in range(6 * 8))) + # Godot cannot decode RGB A1 or the signed EAC kinds: A1 blocks go through it as ETC2 RGB (the test checks the + # punch-through rules on top; the opaque bit is set for Godot, else ETC2 RGB reads the individual mode), signed EAC is checked against s11() below (the KDFS 1.3 rule, written here) + jobs, idx = [], [] + for i, c in enumerate(cases): + k = "etc2_rgb" if c["kind"] == "etc2_rgba1" else c["kind"] + if k in ("eac_r11s", "eac_rg11s"): + c["spec"] = s11(c) + else: + data = c["data"] + if c["kind"] == "etc2_rgba1": # with the opaque bit set: ETC2 RGB's differential / T / H / planar + data = bytes(v | 2 if i % 8 == 3 else v for i, v in enumerate(data)) + jobs.append((data, c["w"], c["h"], R.GODOT[k], False)) + idx.append(i) + for i, out in zip(idx, R.godot(ctx, jobs)): + cases[i]["godot"] = out + ctx.emit("etc", cases) From 9a6ddd5c162266194bce57e3a118df39fb810cf0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:14:50 -0500 Subject: [PATCH 12/54] ws-3d3: codecs/model/Draco: Draco decoder (port of Google Draco 1.5.7, Apache-2.0) Meshes (sequential; Edgebreaker standard / predictive / valence, topology splits, attribute seams) and sequential point clouds, bitstreams 1.0 - 2.2; generic / integer / quantization / octahedral normal attribute decoders; difference, parallelogram, multi and constrained multi-parallelogram, tex coords (deprecated and portable, exact int64 arithmetic) and geometric normal predictions; metadata. Byte-exact against libdraco on 196 files (Draco test data 0.9 - 2.2 and draco_encoder outputs at every level / quantization). kd-tree point clouds: UNSUPPORTED for now. --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/draco-LICENSE.txt | 252 ++++ .../codecs/model/Draco/Attributes.luau | 473 +++++++ .../codecs/model/Draco/Connectivity.luau | 1204 +++++++++++++++++ src/Formats/codecs/model/Draco/Int64.luau | 156 +++ src/Formats/codecs/model/Draco/Predict.luau | 977 +++++++++++++ src/Formats/codecs/model/Draco/Reader.luau | 480 +++++++ src/Formats/codecs/model/Draco/init.luau | 354 +++++ tests/codecs/draco.luau | 80 ++ tools/fixtures/_draco_dump.cc | 44 + tools/fixtures/draco.py | 137 ++ 12 files changed, 4159 insertions(+) create mode 100644 licenses/draco-LICENSE.txt create mode 100644 src/Formats/codecs/model/Draco/Attributes.luau create mode 100644 src/Formats/codecs/model/Draco/Connectivity.luau create mode 100644 src/Formats/codecs/model/Draco/Int64.luau create mode 100644 src/Formats/codecs/model/Draco/Predict.luau create mode 100644 src/Formats/codecs/model/Draco/Reader.luau create mode 100644 src/Formats/codecs/model/Draco/init.luau create mode 100644 tests/codecs/draco.luau create mode 100644 tools/fixtures/_draco_dump.cc create mode 100644 tools/fixtures/draco.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..05b81c3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -124,6 +124,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or - **model** + - codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - **text** diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..346af59 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -37,6 +37,7 @@ | `src/Formats/codecs/Vp8/` inter frames (Decode: inter headers / modes / motion vectors / references, Predict, the inter tables in Tables) | Luau translations of libvpx 1.17 (WebM Project): vp8/decoder/decodeframe.c, decodemv.c, onyxd_if.c; vp8/common/findnearmv.c, reconinter.c, filter.c, vp8_loopfilter.c, entropymode.c, entropymv.c, modecont.c | BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | +| `src/Formats/codecs/model/Draco/` | Luau port of the Draco 1.5.7 decoder (Google): compression/{decode, mesh, attributes, entropy, bit_coders, point_cloud}, mesh/corner_table, mesh/mesh_attribute_corner_table, core/{decoder_buffer, varint_decoding, math_utils}, attributes/attribute_{quantization,octahedron}_transform | Apache-2.0: [draco-LICENSE.txt](draco-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this diff --git a/licenses/draco-LICENSE.txt b/licenses/draco-LICENSE.txt new file mode 100644 index 0000000..3010954 --- /dev/null +++ b/licenses/draco-LICENSE.txt @@ -0,0 +1,252 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-------------------------------------------------------------------------------- +Files: docs/assets/js/ASCIIMathML.js + +Copyright (c) 2014 Peter Jipsen and other ASCIIMathML.js contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +-------------------------------------------------------------------------------- +Files: docs/assets/css/pygments/* + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/src/Formats/codecs/model/Draco/Attributes.luau b/src/Formats/codecs/model/Draco/Attributes.luau new file mode 100644 index 0000000..5b5b11f --- /dev/null +++ b/src/Formats/codecs/model/Draco/Attributes.luau @@ -0,0 +1,473 @@ +--!strict +-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear +-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute +-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to +-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream +-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/ +-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc; +-- Apache-2.0, licenses/draco-LICENSE.txt). +local Reader = require("@formats/codecs/model/Draco/Reader") +local Connectivity = require("@formats/codecs/model/Draco/Connectivity") +local Predict = require("@formats/codecs/model/Draco/Predict") + +local Attributes = {} + +type D = Reader.D + +-- data type ids (draco::DataType) -> byte length +local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 } +Attributes.DT_LENGTH = DT_LENGTH + +export type Attr = { + id: number, -- 0-based attribute id + type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types) + dataType: number, + comps: number, + normalized: boolean, + uniqueId: number, + seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals + map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity + numValues: number, + portable: { number }?, -- the integer (portable) values + values: { number }?, -- the final values (numbers), flat + raw: buffer?, -- generic attributes: the raw values + quant: { min: { number }, range: number, bits: number }?, + octBits: number?, + scheme: Predict.Scheme?, +} + +type Decoder = { + attrs: { Attr }, + traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?, + md: Predict.MeshData?, + points: { number }?, +} + +-- the geometry the attributes decode against +export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean } + +local function zigzag(v: number): number + if v % 2 == 1 then + return -(v // 2) - 1 + end + return v // 2 +end + +-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to +-- integers unless the scheme works in floats) +local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent? + local old = ver < 0x0200 + local vals = if old then pos.values else pos.portable + if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then + return nil + end + local map = pos.map + local trunc = old and not floats + return function(point: number): (number, number, number) + local e = if map then (map[point + 1] or 0) else point + local o = e * 3 + local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0 + if trunc then + x = if x < 0 then math.ceil(x) else math.floor(x) + y = if y < 0 then math.ceil(y) else math.floor(y) + z = if z < 0 then math.ceil(z) else math.floor(z) + end + return x, y, z + end +end + +local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?) + local comps = if a.seqType == 3 then 2 else a.comps + local n = #points + local numValues = n * comps + if n == 0 then + return false, "no values" + end + local compressed = Reader.u8(d) + if d.bad then + return false, d.bad + end + local vals: { number } + if compressed > 0 then + local s = Reader.symbols(d, numValues, comps) + if not s then + return false, d.bad or "bad values" + end + vals = s + else + local nb = Reader.u8(d) + if d.bad then + return false, d.bad + end + if nb < 1 or nb > 4 then + return false, "bad value byte count" + end + if Reader.remaining(d) < nb * numValues then + return false, "truncated values" + end + vals = table.create(numValues, 0) + local b, p = d.b, d.pos + if nb == 4 then + for i = 1, numValues do + vals[i] = buffer.readu32(b, p) + p += 4 + end + elseif nb == 1 then + for i = 1, numValues do + vals[i] = buffer.readu8(b, p) + p += 1 + end + elseif nb == 2 then + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + p += 2 + end + else + for i = 1, numValues do + vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536 + p += 3 + end + end + d.pos = p + end + if not scheme or not scheme.tr.positive then + for i = 1, numValues do + vals[i] = zigzag(vals[i]) + end + else + local i32 = Predict.i32 + for i = 1, numValues do + vals[i] = i32(vals[i]) + end + end + if scheme then + if not Predict.decodeData(scheme, d) then + return false, d.bad or "bad prediction data" + end + local ok, err = Predict.compute(scheme, vals, n, comps, points) + if not ok then + return false, err + end + end + a.portable = vals + a.numValues = n + return true, nil +end + +local function decodeQuantInfo(d: D, a: Attr): boolean + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false + end + a.quant = { min = mins, range = range, bits = bits } + return true +end + +-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors +local function storeValues(a: Attr): (boolean, string?) + local src = a.portable :: { number } + local n = a.numValues + local fround = Predict.fround + if a.seqType == 1 then + local dt = a.dataType + local out = table.create(n * a.comps, 0) + for i = 1, n * a.comps do + local v = src[i] + if dt == 1 then + v = (v + 128) % 256 - 128 + elseif dt == 2 or dt == 11 then + v %= 256 + elseif dt == 3 then + v = (v + 32768) % 65536 - 32768 + elseif dt == 4 then + v %= 65536 + elseif dt == 6 then + v %= 4294967296 + elseif dt ~= 5 then + return false, "unsupported: integer attribute of data type " .. dt + end + out[i] = v + end + a.values = out + elseif a.seqType == 2 then + local q = a.quant + if not q then + return false, "no quantization data" + end + local maxQ = 2 ^ q.bits - 1 + local delta = fround(q.range / fround(maxQ)) + local comps = a.comps + local mins = q.min + local out = table.create(n * comps, 0) + local k = 1 + for _ = 1, n do + for c = 1, comps do + out[k] = fround(fround(fround(src[k]) * delta) + mins[c]) + k += 1 + end + end + a.values = out + elseif a.seqType == 3 then + local o = Predict.octahedron(a.octBits or 0) + if not o then + return false, "bad normal quantization" + end + local out = table.create(n * 3, 0) + for i = 0, n - 1 do + local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2]) + out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z + end + a.values = out + end + return true, nil +end + +-- decodes every attribute; returns them in attribute id order +function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) + local ver = d.ver + local numDecoders = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local mesh = g.mesh + local decoders: { Decoder } = {} + for i = 0, numDecoders - 1 do + local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil } + if g.edgebreaker and mesh then + local attDataId = Reader.i8(d) + local decoderType = Reader.u8(d) + if d.bad then + return nil, d.bad + end + local ad = nil + if attDataId >= 0 then + ad = mesh.attrData[attDataId + 1] + if not ad or ad.decoderId >= 0 then + return nil, "bad attribute data id" + end + ad.decoderId = i + else + if mesh.posDecoderId >= 0 then + return nil, "two position decoders" + end + mesh.posDecoderId = i + end + local method = 0 + if ver >= 0x0102 then + method = Reader.u8(d) + if d.bad or method >= 2 then + return nil, "bad traversal method" + end + end + local ct = mesh.ct :: Connectivity.CT + local enc + if decoderType == 0 then + if ad then + enc = ad.enc + ad.used = false + else + enc = mesh.posEnc :: Connectivity.Enc + end + dec.traversal = { ct = ct, enc = enc, method = method } + else + if method ~= 0 or not ad then + return nil, "bad corner attribute decoder" + end + local cad = ad :: Connectivity.AttrData + enc = cad.enc + dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 } + end + -- prediction data: the attribute's own corner table when its seams are in use + local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct + dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } + elseif g.kdTree then + return nil, "unsupported: kd-tree point clouds" + end + decoders[i + 1] = dec + end + -- the attribute descriptors + local all: { Attr } = {} + for _, dec in decoders do + local n = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if n == 0 or n > 5 * Reader.remaining(d) then + return nil, "bad attribute count" + end + for _ = 1, n do + local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + if d.bad then + return nil, d.bad + end + if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then + return nil, "bad attribute descriptor" + end + local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d) + local a: Attr = { + id = #all, + type = attType, + dataType = dataType, + comps = comps, + normalized = normalized > 0, + uniqueId = uniqueId, + seqType = 0, + map = nil, + numValues = 0, + } + table.insert(all, a) + table.insert(dec.attrs, a) + end + for _, a in dec.attrs do + local t = Reader.u8(d) + if d.bad then + return nil, d.bad + end + if t > 3 then + return nil, "unknown attribute decoder " .. t + end + if (t == 2 or t == 3) and a.dataType ~= 9 then + return nil, "quantized attribute is not f32" + end + if t == 3 and a.comps ~= 3 then + return nil, "normal attribute without 3 components" + end + a.seqType = t + end + end + if d.bad then + return nil, d.bad + end + local function named(t: number): Attr? + for _, a in all do + if a.type == t then + return a + end + end + return nil + end + -- decode + for _, dec in decoders do + local points: { number } + local trav = dec.traversal + if trav then + local faces = (mesh :: Connectivity.Mesh).faces + local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method) + if not p then + return nil, "bad attribute traversal" + end + points = p + local numPoints = (mesh :: Connectivity.Mesh).numPoints + for _, a in dec.attrs do + local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints) + if not m then + return nil, "bad attribute mapping" + end + a.map = m + end + else + points = table.create(g.numPoints, 0) + for i = 1, g.numPoints do + points[i] = i - 1 + end + end + dec.points = points + -- portable values + for _, a in dec.attrs do + if a.seqType == 0 then + local stride = DT_LENGTH[a.dataType] * a.comps + local size = #points * stride + if Reader.remaining(d) < size then + return nil, "truncated attribute values" + end + local raw = buffer.create(size) + buffer.copy(raw, 0, d.b, d.pos, size) + d.pos += size + a.raw = raw + a.numValues = #points + continue + end + local psm = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if psm < -2 or psm >= 7 then + return nil, "bad prediction scheme" + end + local scheme: Predict.Scheme? = nil + if psm ~= -2 then + local ptt = Reader.i8(d) + if d.bad then + return nil, d.bad + end + if ptt < -1 or ptt >= 4 then + return nil, "bad prediction transform" + end + if a.seqType == 3 then + if ptt == 2 or ptt == 3 then + scheme = Predict.new(psm, Predict.transform(ptt), dec.md) + end + elseif ptt == 1 then + scheme = Predict.new(psm, Predict.transform(1), dec.md) + end + end + if scheme and Predict.needsParent(scheme) then + local pos = named(0) + local getter = pos and parentGetter(ver, pos, scheme.method == 3) + if not getter then + return nil, "prediction needs the decoded positions" + end + scheme.parent = getter + end + if ver < 0x0200 then + if a.seqType == 2 and not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + local ok, err = decodeIntegerValues(d, a, points, scheme) + if not ok then + return nil, err + end + a.scheme = scheme + if ver < 0x0200 then + local ok2, err2 = storeValues(a) + if not ok2 then + return nil, err2 + end + end + end + -- data needed by the transforms + if ver >= 0x0200 then + for _, a in dec.attrs do + if a.seqType == 2 then + if not decodeQuantInfo(d, a) then + return nil, d.bad or "bad quantization data" + end + elseif a.seqType == 3 then + a.octBits = Reader.u8(d) + end + end + if d.bad then + return nil, d.bad + end + for _, a in dec.attrs do + if a.seqType ~= 0 then + local ok, err = storeValues(a) + if not ok then + return nil, err + end + end + end + end + end + return all, nil +end + +return Attributes diff --git a/src/Formats/codecs/model/Draco/Connectivity.luau b/src/Formats/codecs/model/Draco/Connectivity.luau new file mode 100644 index 0000000..9564ef2 --- /dev/null +++ b/src/Formats/codecs/model/Draco/Connectivity.luau @@ -0,0 +1,1204 @@ +--!strict +-- codecs/model/Draco/Connectivity: Draco mesh connectivity. The sequential decoder (raw or rANS delta-coded indices) +-- and the Edgebreaker decoder (standard, predictive and valence traversals, topology splits, start faces, attribute +-- seams), the corner tables they build (the mesh's and one per attribute seam set), and the traversal sequencers +-- (depth first and max prediction degree) that order attribute values. Ported from Google's Draco 1.5.7 +-- (compression/mesh/mesh_sequential_decoder.cc, mesh_edgebreaker_decoder_impl.cc, mesh_edgebreaker_traversal_*, +-- mesh/corner_table, mesh/mesh_attribute_corner_table, compression/mesh/traverser/*; Apache-2.0, +-- licenses/draco-LICENSE.txt). Corners, vertices and faces are 0-based values stored at [i + 1]; -1 is invalid. +local Reader = require("@formats/codecs/model/Draco/Reader") + +local Connectivity = {} + +type D = Reader.D + +-- a corner table: corner -> vertex, corner -> opposite corner, vertex -> left-most corner +export type CT = { c2v: { number }, opp: { number }, lmc: { number }, nv: number, nf: number } +-- encoding data of one attribute connectivity: vertex -> value index, value index -> corner +export type Enc = { v2e: { number }, e2c: { number }, numValues: number } +export type AttrData = { decoderId: number, used: boolean, seams: { number }, ct: CT?, enc: Enc } +export type Mesh = { + faces: { number }, -- corner -> point + numFaces: number, + numPoints: number, + ct: CT?, -- Edgebreaker only + attrData: { AttrData }, + posEnc: Enc?, + posDecoderId: number, +} + +local TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E = 0, 1, 3, 5, 7 +local SYMBOL_TO_TOPOLOGY = { [0] = TOPOLOGY_C, TOPOLOGY_S, TOPOLOGY_L, TOPOLOGY_R, TOPOLOGY_E } + +local function nextC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 2 then c - 2 else c + 1 +end +local function prevC(c: number): number + if c < 0 then + return -1 + end + return if c % 3 == 0 then c + 2 else c - 1 +end +Connectivity.next = nextC +Connectivity.prev = prevC + +local function newEnc(nv: number): Enc + return { v2e = table.create(nv, 0), e2c = {}, numValues = 0 } +end + +-- ------------------------------------------------------------------------------------------------ sequential +function Connectivity.sequential(d: D): (Mesh?, string?) + local numFaces, numPoints + if d.ver < 0x0202 then + numFaces, numPoints = Reader.u32(d), Reader.u32(d) + else + numFaces, numPoints = Reader.varint(d), Reader.varint(d) + end + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 or numFaces > Reader.remaining(d) // 3 then + return nil, "too many faces" + end + local method = Reader.u8(d) + local n = numFaces * 3 + local faces = table.create(n, 0) + if method == 0 then + local sym = Reader.symbols(d, n, 1) + if not sym then + return nil, d.bad or "bad indices" + end + local last = 0 + for i = 1, n do + local e = sym[i] + local diff = e // 2 + if e % 2 == 1 then + if diff > last then + return nil, "bad index delta" + end + diff = -diff + elseif diff > 0x7fffffff - last then + return nil, "bad index delta" + end + last += diff + faces[i] = last + end + else + local b = d.b + if numPoints < 256 then + if d.pos + n > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu8(b, d.pos + i - 1) + end + d.pos += n + elseif numPoints < 65536 then + if d.pos + n * 2 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu16(b, d.pos + (i - 1) * 2) + end + d.pos += n * 2 + elseif numPoints < 2 ^ 21 and d.ver >= 0x0202 then + for i = 1, n do + faces[i] = Reader.varint(d) + end + else + if d.pos + n * 4 > d.limit then + return nil, "truncated indices" + end + for i = 1, n do + faces[i] = buffer.readu32(b, d.pos + (i - 1) * 4) + end + d.pos += n * 4 + end + end + if d.bad then + return nil, d.bad + end + return { faces = faces, numFaces = numFaces, numPoints = numPoints, ct = nil, attrData = {}, posEnc = nil, posDecoderId = -1 }, nil +end + +-- ------------------------------------------------------------------------------------------------ edgebreaker +-- the traversal decoders: symbols, start face configurations, attribute seam bits +type Trav = { + decodeSymbol: () -> number, + newActiveCorner: (corner: number) -> (), + mergeVertices: (dest: number, src: number) -> (), + startFace: () -> boolean, + seam: (i: number) -> boolean, +} + +-- MeshEdgebreakerTraversalDecoder::Start (the standard parts): symbols (bits), start faces, seam decoders. +-- Returns the decoder state and the buffer after them. +local function standardStart(buf: D, numAttributeData: number, withSymbols: boolean): (any?, D) + local st: any = {} + if withSymbols then + local sym = Reader.copy(buf) + local size = Reader.startBits(sym, true) + if sym.bad then + buf.bad = sym.bad + return nil, buf + end + buf = Reader.copy(sym) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "traversal symbols past the end") + return nil, buf + end + buf.pos += size + st.sym = sym + end + if buf.ver < 0x0202 then + local sf = Reader.copy(buf) + local size = Reader.startBits(sf, true) + if sf.bad then + buf.bad = sf.bad + return nil, buf + end + buf = Reader.copy(sf) + buf.bitMode = false + if size > Reader.remaining(buf) then + Reader.fail(buf, "start faces past the end") + return nil, buf + end + buf.pos += size + st.startBuf = sf + else + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.startDec = bd + end + st.seams = {} + for i = 1, numAttributeData do + local bd = Reader.bitDecoder(buf) + if not bd then + return nil, buf + end + st.seams[i] = bd + end + return st, buf +end + +local function standardSymbol(sym: D): number + local s = Reader.bits(sym, 1) + if s == TOPOLOGY_C then + return s + end + return s + Reader.bits(sym, 2) * 2 +end + +-- builds the traversal decoder for `kind` (0 standard, 1 predictive, 2 valence); returns it and the buffer after its data +local function makeTraversal(kind: number, buf: D, numAttributeData: number, numVertices: number, numFaces: number, ct: CT): (Trav?, D) + local ver = buf.ver + local st, out = standardStart(buf, numAttributeData, kind ~= 2 or ver < 0x0202) + if not st then + return nil, out + end + local function startFace(): boolean + if st.startBuf then + return Reader.bits(st.startBuf, 1) == 1 + end + return Reader.bit(st.startDec) + end + local function seam(i: number): boolean + return Reader.bit(st.seams[i + 1]) + end + local valences = table.create(numVertices, 0) + local c2v = ct.c2v + local function vtx(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function addValence(v: number, k: number) + if v >= 0 and v < numVertices then + valences[v + 1] += k + end + end + local function mergeVertices(dest: number, src: number) + if dest >= 0 and dest < numVertices and src >= 0 and src < numVertices then + valences[dest + 1] += valences[src + 1] + end + end + local lastSymbol = -1 + local function updateValences(corner: number) + local nx, pv = nextC(corner), prevC(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_S then + addValence(vtx(nx), 1) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_R then + addValence(vtx(corner), 1) + addValence(vtx(nx), 1) + addValence(vtx(pv), 2) + elseif lastSymbol == TOPOLOGY_L then + addValence(vtx(corner), 1) + addValence(vtx(nx), 2) + addValence(vtx(pv), 1) + elseif lastSymbol == TOPOLOGY_E then + addValence(vtx(corner), 2) + addValence(vtx(nx), 2) + addValence(vtx(pv), 2) + end + end + + if kind == 0 then + local sym = st.sym + return { + decodeSymbol = function(): number + return standardSymbol(sym) + end, + newActiveCorner = function(_c: number) end, + mergeVertices = function(_a: number, _b: number) end, + startFace = startFace, + seam = seam, + }, out + elseif kind == 1 then + -- predictive (deprecated): a bit says whether the predicted symbol (from the pivot's valence) is right + local n = Reader.i32(out) + if out.bad or n < 0 or n >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local pred = Reader.bitDecoder(out) + if not pred then + return nil, out + end + local sym = st.sym + local predicted = -1 + return { + decodeSymbol = function(): number + if predicted ~= -1 and Reader.bit(pred) then + lastSymbol = predicted + return predicted + end + lastSymbol = standardSymbol(sym) + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + if lastSymbol == TOPOLOGY_C or lastSymbol == TOPOLOGY_R then + local pivot = vtx(nextC(corner)) + local val = if pivot >= 0 and pivot < numVertices then valences[pivot + 1] else 0 + predicted = if val < 6 then TOPOLOGY_R else TOPOLOGY_C + else + predicted = -1 + end + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out + end + -- valence: per-context symbol streams chosen by the valence of the next vertex + local minValence, maxValence = 2, 7 + if ver < 0x0202 then + local nSplit = Reader.count(out, 0x0200) + if out.bad or nSplit >= numVertices then + Reader.fail(out, "bad split symbol count") + return nil, out + end + local mode = Reader.i8(out) + if out.bad or mode ~= 0 then + Reader.fail(out, "unsupported valence mode") + return nil, out + end + end + local contexts: { { number } } = {} + local counters: { number } = {} + for i = 1, maxValence - minValence + 1 do + local n = Reader.varint(out) + if out.bad then + return nil, out + end + if n > numFaces then + Reader.fail(out, "too many context symbols") + return nil, out + end + counters[i] = n + contexts[i] = {} + if n > 0 then + -- C++ ignores a failure here (the symbols stay zero) + local save = out.bad + local syms = Reader.symbols(out, n, 1) + if syms then + contexts[i] = syms + else + out.bad = save + end + end + end + local active = -1 + local sym = st.sym + return { + decodeSymbol = function(): number + if active ~= -1 then + local k = counters[active + 1] - 1 + counters[active + 1] = k + if k < 0 then + return -1 + end + local id = contexts[active + 1][k + 1] or 0 + if id > 4 then + return -1 + end + lastSymbol = SYMBOL_TO_TOPOLOGY[id] + elseif ver < 0x0202 then + lastSymbol = standardSymbol(sym) + else + lastSymbol = TOPOLOGY_E + end + return lastSymbol + end, + newActiveCorner = function(corner: number) + updateValences(corner) + local v = vtx(nextC(corner)) + local val = if v >= 0 and v < numVertices then valences[v + 1] else 0 + if val < minValence then + val = minValence + elseif val > maxValence then + val = maxValence + end + active = val - minValence + end, + mergeVertices = mergeVertices, + startFace = startFace, + seam = seam, + }, out +end + +-- hole and topology split events; returns the split stack (source / split symbol ids, edges) or nil +local function splitEvents(eb: D, numFaces: number): { any }? + local ver = eb.ver + local n = Reader.count(eb, 0x0200) + if eb.bad then + return nil + end + local splits = {} + if n > 0 then + if n > numFaces then + Reader.fail(eb, "too many topology splits") + return nil + end + if ver < 0x0102 then + for i = 1, n do + local split = Reader.u32(eb) + local source = Reader.u32(eb) + local edge = Reader.u8(eb) % 2 + splits[i] = { source = source, split = split, edge = edge } + end + else + local last = 0 + for i = 1, n do + local source = Reader.varint(eb) + last + local delta = Reader.varint(eb) + if eb.bad then + return nil + end + if delta > source then + Reader.fail(eb, "bad topology split") + return nil + end + splits[i] = { source = source, split = source - delta, edge = 0 } + last = source + end + Reader.startBits(eb, false) + for i = 1, n do + local e = Reader.bits(eb, if ver < 0x0202 then 2 else 1) + splits[i].edge = e % 2 + end + Reader.endBits(eb) + end + end + -- hole events (before 2.1): read and ignored + local holes = 0 + if ver < 0x0200 then + holes = Reader.u32(eb) + elseif ver < 0x0201 then + holes = Reader.varint(eb) + end + if eb.bad then + return nil + end + if holes > Reader.remaining(eb) then + Reader.fail(eb, "too many hole events") + return nil + end + for _ = 1, holes do + if ver < 0x0102 then + Reader.i32(eb) + else + Reader.varint(eb) + end + end + if eb.bad then + return nil + end + return splits +end + +-- MeshAttributeCornerTable from the seam corners (InitEmpty, AddSeamEdge, RecomputeVertices) +local function attributeTable(ct: CT, seams: { number }): CT? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nc = ct.nf * 3 + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local edgeSeam: { [number]: boolean } = {} + local vertSeam: { [number]: boolean } = {} + for _, c in seams do + edgeSeam[c] = true + vertSeam[V(nextC(c))] = true + vertSeam[V(prevC(c))] = true + local o = if c < 0 then -1 else (opp[c + 1] or -1) + if o ~= -1 then + edgeSeam[o] = true + vertSeam[V(nextC(o))] = true + vertSeam[V(prevC(o))] = true + end + end + local aopp = table.create(nc, -1) + for c = 0, nc - 1 do + aopp[c + 1] = if edgeSeam[c] then -1 else (opp[c + 1] or -1) + end + local ac2v = table.create(nc, -1) + local almc: { number } = {} + local num = 0 + local function swingLeftA(c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else aopp[n + 1] + return nextC(o) + end + local function swingRight(c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (opp[p + 1] or -1) + return prevC(o) + end + for v = 0, ct.nv - 1 do + local c = lmc[v + 1] or -1 + if c ~= -1 then + local id = num + num += 1 + local first = c + if vertSeam[v] then + local act = swingLeftA(first) + while act ~= -1 do + first = act + act = swingLeftA(act) + if act == c then + return nil + end + end + end + ac2v[first + 1] = id + table.insert(almc, first) + local act = swingRight(first) + local guard = 0 + while act ~= -1 and act ~= first do + if edgeSeam[nextC(act)] then + id = num + num += 1 + table.insert(almc, act) + end + ac2v[act + 1] = id + act = swingRight(act) + guard += 1 + if guard > nc then + return nil + end + end + end + end + return { c2v = ac2v, opp = aopp, lmc = almc, nv = num, nf = ct.nf, vertSeam = vertSeam } :: any +end + +-- MeshEdgebreakerDecoderImpl::DecodeConnectivity (+ the traversal start, seams, AssignPointsToCorners) +function Connectivity.edgebreaker(d: D, traversalKind: number): (Mesh?, string?) + local ver = d.ver + if ver < 0x0202 then + Reader.count(d, 0x0200) -- num_new_vertices (unused) + end + local numEncodedVertices = Reader.count(d, 0x0200) + local numFaces = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces > 0xffffffff // 3 then + return nil, "too many faces" + end + if numEncodedVertices > numFaces * 3 then + return nil, "more vertices than corners" + end + local minEdges = (3 * numFaces) // 2 + local maxEdges = numEncodedVertices * (numEncodedVertices - 1) / 2 + if numEncodedVertices == 0 then + maxEdges = 0 + end + if maxEdges < minEdges then + return nil, "too few vertices for the faces" + end + local numAttributeData = Reader.u8(d) + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numFaces < numSymbols or numFaces > numSymbols + numSymbols // 3 then + return nil, "bad symbol count" + end + local numSplitSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if numSplitSymbols > numSymbols then + return nil, "bad split symbol count" + end + local maxVertices = numEncodedVertices + numSplitSymbols + + -- the corner table (filled lazily: nil = invalid) + local c2v: { number } = {} + local opp: { number } = {} + local lmc: { number } = {} + local nv = 0 + local ct: CT = { c2v = c2v, opp = opp, lmc = lmc, nv = 0, nf = numFaces } + local notHole: { [number]: boolean } = {} + + local splits: { any }? + local splitBytes = 0 + if ver < 0x0202 then + local size = Reader.count(d, 0x0200) + if d.bad then + return nil, d.bad + end + if size == 0 or size > Reader.remaining(d) then + return nil, "bad connectivity size" + end + local eb = Reader.new(d.b, d.pos + size, d.limit, ver) + splits = splitEvents(eb, numFaces) + if not splits then + return nil, eb.bad or "bad split events" + end + splitBytes = eb.pos - (d.pos + size) + else + splits = splitEvents(d, numFaces) + if not splits then + return nil, d.bad or "bad split events" + end + end + local splitData = splits :: { any } + + local trav, after = makeTraversal(traversalKind, Reader.copy(d), numAttributeData, maxVertices, numFaces, ct) + if not trav then + return nil, after.bad or "bad traversal data" + end + + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function setOpp(a: number, b: number) + if a >= 0 then + opp[a + 1] = b + end + if b >= 0 then + opp[b + 1] = a + end + end + local function setLmc(v: number, c: number) + if v >= 0 then + lmc[v + 1] = c + end + end + local function LMC(v: number): number + return if v < 0 then -1 else (lmc[v + 1] or -1) + end + local function addVertex(): number + nv += 1 + lmc[nv] = -1 + return nv - 1 + end + local function swingLeft(c: number): number + return nextC(O(nextC(c))) + end + local function swingRight(c: number): number + return prevC(O(prevC(c))) + end + + -- the symbols + local stack: { number } = {} + local sp = 0 + local splitActive: { [number]: number } = {} + local invalidVerts: { number } = {} + local removeInvalid = numAttributeData == 0 + local nf = 0 + for symbolId = 0, numSymbols - 1 do + local face = nf + nf += 1 + local checkSplit = false + local symbol = trav.decodeSymbol() + local corner = 3 * face + if symbol == TOPOLOGY_C then + if sp == 0 then + return nil, "bad traversal (C)" + end + local a = stack[sp] + local vx = V(nextC(a)) + local b = nextC(LMC(vx)) + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (C)" + end + setOpp(a, corner + 1) + setOpp(b, corner + 2) + local vap, vbn = V(prevC(a)), V(nextC(b)) + if vx == vap or vx == vbn then + return nil, "bad traversal (C)" + end + c2v[corner + 1] = vx + c2v[corner + 2] = vbn + c2v[corner + 3] = vap + setLmc(vap, corner + 2) + notHole[vx] = true + stack[sp] = corner + elseif symbol == TOPOLOGY_R or symbol == TOPOLOGY_L then + if sp == 0 then + return nil, "bad traversal (R / L)" + end + local a = stack[sp] + if O(a) ~= -1 then + return nil, "bad traversal (R / L)" + end + local oc, cl, cr + if symbol == TOPOLOGY_R then + oc, cl, cr = corner + 2, corner + 1, corner + else + oc, cl, cr = corner + 1, corner, corner + 2 + end + setOpp(oc, a) + local nvx = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + c2v[oc + 1] = nvx + setLmc(nvx, oc) + local vr = V(prevC(a)) + c2v[cr + 1] = vr + setLmc(vr, cr) + c2v[cl + 1] = V(nextC(a)) + stack[sp] = corner + checkSplit = true + elseif symbol == TOPOLOGY_S then + if sp == 0 then + return nil, "bad traversal (S)" + end + local b = stack[sp] + stack[sp] = nil + sp -= 1 + local pushed = splitActive[symbolId] + if pushed then + sp += 1 + stack[sp] = pushed + end + if sp == 0 then + return nil, "bad traversal (S)" + end + local a = stack[sp] + if a == b or O(a) ~= -1 or O(b) ~= -1 then + return nil, "bad traversal (S)" + end + setOpp(a, corner + 2) + setOpp(b, corner + 1) + local vp = V(prevC(a)) + c2v[corner + 1] = vp + c2v[corner + 2] = V(nextC(a)) + local vbp = V(prevC(b)) + c2v[corner + 3] = vbp + setLmc(vbp, corner + 2) + local cn = nextC(b) + local vn = V(cn) + trav.mergeVertices(vp, vn) + setLmc(vp, LMC(vn)) + local first = cn + while cn ~= -1 do + c2v[cn + 1] = vp + cn = swingLeft(cn) + if cn == first then + return nil, "bad traversal (S loop)" + end + end + setLmc(vn, -1) + if removeInvalid then + table.insert(invalidVerts, vn) + end + stack[sp] = corner + elseif symbol == TOPOLOGY_E then + local v0 = addVertex() + c2v[corner + 1] = v0 + c2v[corner + 2] = addVertex() + c2v[corner + 3] = addVertex() + if nv > maxVertices then + return nil, "too many vertices" + end + setLmc(v0, corner) + setLmc(v0 + 1, corner + 1) + setLmc(v0 + 2, corner + 2) + sp += 1 + stack[sp] = corner + checkSplit = true + else + return nil, "bad traversal symbol" + end + ct.nv = nv + trav.newActiveCorner(stack[sp]) + if checkSplit then + local encId = numSymbols - symbolId - 1 + while true do + local top = splitData[#splitData] + if not top then + break + end + if top.source > encId then + return nil, "bad split symbol id" + end + if top.source ~= encId then + break + end + splitData[#splitData] = nil + local act = stack[sp] + local newActive = if top.edge == 1 then nextC(act) else prevC(act) + splitActive[numSymbols - top.split - 1] = newActive + end + end + end + if nv > maxVertices then + return nil, "too many vertices" + end + + -- start faces: interior faces that close the remaining holes + local initFaces = {} + while sp > 0 do + local corner = stack[sp] + stack[sp] = nil + sp -= 1 + if trav.startFace() then + if nf >= numFaces then + return nil, "too many faces" + end + local vn = V(nextC(corner)) + local b = nextC(LMC(vn)) + local vx = V(nextC(b)) + local c = nextC(LMC(vx)) + if corner == b or corner == c or b == c or O(corner) ~= -1 or O(b) ~= -1 or O(c) ~= -1 then + return nil, "bad start face" + end + local vp = V(nextC(c)) + local nc = 3 * nf + nf += 1 + setOpp(nc, corner) + setOpp(nc + 1, b) + setOpp(nc + 2, c) + c2v[nc + 1] = vx + c2v[nc + 2] = vp + c2v[nc + 3] = vn + for k = 0, 2 do + notHole[V(nc + k)] = true + end + table.insert(initFaces, nc) + end + end + if nf ~= numFaces then + return nil, "face count mismatch" + end + + -- compact the vertices removed by S symbols (no attribute data only) + local numVertices = nv + for _, inv in invalidVerts do + local src = numVertices - 1 + while src >= 0 and LMC(src) == -1 do + numVertices -= 1 + src = numVertices - 1 + end + if src >= inv then + -- every corner of src (VertexCornersIterator: left, then right) + local start = LMC(src) + local corners = {} + local cc = start + local left = true + local guard = 0 + while cc ~= -1 do + table.insert(corners, cc) + guard += 1 + if guard > numFaces * 3 + 3 then + return nil, "bad vertex fan" + end + if left then + cc = swingLeft(cc) + if cc == -1 then + cc = swingRight(start) + left = false + elseif cc == start then + cc = -1 + end + else + cc = swingRight(cc) + end + end + for _, cid in corners do + if V(cid) ~= src then + return nil, "bad vertex fan" + end + c2v[cid + 1] = inv + end + setLmc(inv, LMC(src)) + setLmc(src, -1) + notHole[inv] = notHole[src] + notHole[src] = true + numVertices -= 1 + end + end + + -- continue after the traversal data (and the split events before 2.2) + d.pos = after.pos + d.bad = after.bad + if ver < 0x0202 then + d.pos += splitBytes + end + + -- attribute seams + local attrData: { AttrData } = {} + for i = 1, numAttributeData do + attrData[i] = { decoderId = -1, used = true, seams = {}, ct = nil, enc = newEnc(0) } + end + if numAttributeData > 0 then + for f = 0, numFaces - 1 do + local base = 3 * f + for k = 0, 2 do + local c = if k == 0 then base elseif k == 1 then base + 1 else base + 2 + local o = O(c) + if o == -1 then + for i = 1, numAttributeData do + table.insert(attrData[i].seams, c) + end + elseif ver < 0x0201 or o // 3 >= f then + for i = 1, numAttributeData do + if trav.seam(i - 1) then + table.insert(attrData[i].seams, c) + end + end + end + end + end + end + ct.nv = nv + for i = 1, numAttributeData do + local act = attributeTable(ct, attrData[i].seams) + if not act then + return nil, "bad attribute seams" + end + attrData[i].ct = act + attrData[i].enc = newEnc(math.max(act.nv, nv)) + end + local posEnc = newEnc(nv) + + -- AssignPointsToCorners + local faces = table.create(numFaces * 3, 0) + local numPoints + if numAttributeData == 0 then + for c = 0, numFaces * 3 - 1 do + faces[c + 1] = V(c) + end + numPoints = numVertices + else + numPoints = 0 + for v = 0, nv - 1 do + local c = LMC(v) + if c ~= -1 then + local first = c + if notHole[v] then + for i = 1, numAttributeData do + local act = attrData[i].ct :: any + if act.vertSeam[V(c)] then + local vid = act.c2v[c + 1] + local a = swingRight(c) + local found = false + while a ~= c do + if a == -1 then + return nil, "bad seam fan" + end + if act.c2v[a + 1] ~= vid then + first = a + found = true + break + end + a = swingRight(a) + end + if found then + break + end + end + end + end + c = first + faces[c + 1] = numPoints + numPoints += 1 + local pc = c + c = swingRight(c) + local guard = 0 + while c ~= -1 and c ~= first do + local seam = false + for i = 1, numAttributeData do + local ac2v = (attrData[i].ct :: CT).c2v + if ac2v[c + 1] ~= ac2v[pc + 1] then + seam = true + break + end + end + if seam then + faces[c + 1] = numPoints + numPoints += 1 + else + faces[c + 1] = faces[pc + 1] + end + pc = c + c = swingRight(c) + guard += 1 + if guard > numFaces * 3 then + return nil, "bad vertex fan" + end + end + end + end + end + for k = 1, nv do + if not lmc[k] then + lmc[k] = -1 + end + end + return { + faces = faces, + numFaces = numFaces, + numPoints = numPoints, + ct = ct, + attrData = attrData, + posEnc = posEnc, + posDecoderId = -1, + }, nil +end + +-- ------------------------------------------------------------------------------------------------ traversal +-- MeshTraversalSequencer::GenerateSequence: the point ids in value order; fills enc (v2e, e2c, numValues). +-- method 0 = depth first, 1 = max prediction degree. +function Connectivity.traverse(ct: CT, faces: { number }, enc: Enc, method: number): { number }? + local c2v, opp, lmc = ct.c2v, ct.opp, ct.lmc + local nf, nvt = ct.nf, ct.nv + local faceVisited = table.create(nf, false) + local vertVisited = table.create(nvt, false) + local points: { number } = {} + local v2e, e2c = enc.v2e, enc.e2c + local function V(c: number): number + return if c < 0 then -1 else (c2v[c + 1] or -1) + end + local function O(c: number): number + return if c < 0 then -1 else (opp[c + 1] or -1) + end + local function faceSeen(c: number): boolean + if c < 0 then + return true + end + return faceVisited[c // 3 + 1] == true + end + local function visit(v: number, c: number): boolean + if v < 0 or v >= nvt then + return false + end + vertVisited[v + 1] = true + table.insert(points, faces[c + 1]) + table.insert(e2c, c) + v2e[v + 1] = enc.numValues + enc.numValues += 1 + return true + end + local function onBoundary(v: number): boolean + local c = if v < 0 then -1 else (lmc[v + 1] or -1) + return nextC(O(nextC(c))) == -1 + end + if method == 0 then + local stack: { number } = {} + for f = 0, nf - 1 do + local start = 3 * f + if not faceSeen(start) then + stack[1] = start + for k = #stack, 2, -1 do + stack[k] = nil + end + local nx, pv = V(nextC(start)), V(prevC(start)) + if nx == -1 or pv == -1 then + return nil + end + if not vertVisited[nx + 1] and not visit(nx, nextC(start)) then + return nil + end + if not vertVisited[pv + 1] and not visit(pv, prevC(start)) then + return nil + end + while #stack > 0 do + local c = stack[#stack] + if c == -1 or faceSeen(c) then + stack[#stack] = nil + continue + end + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v == -1 then + return nil + end + if not vertVisited[v + 1] then + local boundary = onBoundary(v) + if not visit(v, c) then + return nil + end + if not boundary then + c = O(nextC(c)) + if c == -1 then + -- C++ would index face -1 here; treat as done + stack[#stack] = nil + break + end + continue + end + end + local rc, lc = O(nextC(c)), O(prevC(c)) + if faceSeen(rc) then + if faceSeen(lc) then + stack[#stack] = nil + break + end + c = lc + elseif faceSeen(lc) then + c = rc + else + stack[#stack] = lc + table.insert(stack, rc) + break + end + end + end + end + end + return points + end + -- max prediction degree + if nvt == 0 then + return points + end + local degree = table.create(nvt, 0) + local stacks: { { number } } = { {}, {}, {} } + local best = 0 + local function priority(c: number): number + local v = V(c) + if v < 0 or v >= nvt then + return 0 + end + local p = 0 + if not vertVisited[v + 1] then + degree[v + 1] += 1 + p = if degree[v + 1] > 1 then 1 else 2 + end + return p + end + for f = 0, nf - 1 do + local start = 3 * f + table.insert(stacks[1], start) + best = 0 + local nx, pv, tip = V(nextC(start)), V(prevC(start)), V(start) + for _, pair in { { nx, nextC(start) }, { pv, prevC(start) }, { tip, start } } do + local v = pair[1] + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, pair[2]) + end + end + while true do + local c = -1 + for i = best, 2 do + local s = stacks[i + 1] + if #s > 0 then + c = s[#s] + s[#s] = nil + best = i + break + end + end + if c == -1 then + break + end + if not faceSeen(c) then + while true do + faceVisited[c // 3 + 1] = true + local v = V(c) + if v < 0 or v >= nvt then + return nil + end + if not vertVisited[v + 1] then + visit(v, c) + end + local rc, lc = O(nextC(c)), O(prevC(c)) + local rSeen, lSeen = faceSeen(rc), faceSeen(lc) + if not lSeen then + local p = priority(lc) + if rSeen and p <= best then + c = lc + continue + end + table.insert(stacks[p + 1], lc) + if p < best then + best = p + end + end + if not rSeen then + local p = priority(rc) + if p <= best then + c = rc + continue + end + table.insert(stacks[p + 1], rc) + if p < best then + best = p + end + end + break + end + end + end + end + return points +end + +-- MeshTraversalSequencer::UpdatePointToAttributeIndexMapping: point -> value index (1-based table of 0-based values) +function Connectivity.mapping(ct: CT, faces: { number }, enc: Enc, numPoints: number): { number }? + local map = table.create(numPoints, 0) + local c2v, v2e = ct.c2v, enc.v2e + for c = 0, ct.nf * 3 - 1 do + local p = faces[c + 1] + local v = c2v[c + 1] or -1 + if v == -1 then + return nil + end + local e = v2e[v + 1] or 0 + if p >= numPoints or e >= numPoints then + return nil + end + map[p + 1] = e + end + return map +end + +return Connectivity diff --git a/src/Formats/codecs/model/Draco/Int64.luau b/src/Formats/codecs/model/Draco/Int64.luau new file mode 100644 index 0000000..4365b8b --- /dev/null +++ b/src/Formats/codecs/model/Draco/Int64.luau @@ -0,0 +1,156 @@ +--!strict +-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 / +-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both +-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed. +local Int64 = {} + +local P32 = 4294967296 +local P31 = 2147483648 + +function Int64.from(n: number): (number, number) + if n >= 0 then + return (n // P32) % P32, n % P32 + end + local h, l = Int64.from(-n) + return Int64.neg(h, l) +end + +function Int64.neg(h: number, l: number): (number, number) + if l == 0 then + return (P32 - h) % P32, 0 + end + return P32 - 1 - h, P32 - l +end + +function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number) + local l = al + bl + local c = 0 + if l >= P32 then + l -= P32 + c = 1 + end + return (ah + bh + c) % P32, l +end + +function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number) + local nh, nl = Int64.neg(bh, bl) + return Int64.add(ah, al, nh, nl) +end + +-- the product mod 2^64 (the same bits for signed and unsigned operands) +function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number) + local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536 + local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536 + local c0 = a0 * b0 + local c1 = a1 * b0 + a0 * b1 + local c2 = a2 * b0 + a1 * b1 + a0 * b2 + local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3 + local lo = c0 + (c1 % 65536) * 65536 + local carry = lo // P32 + lo %= P32 + local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32 + return hi, lo +end + +function Int64.isNeg(h: number): boolean + return h >= P31 +end + +-- the signed value as a number (exact below 2^53 in magnitude) +function Int64.signed(h: number, l: number): number + if h >= P31 then + return (h - P32) * P32 + l + end + return h * P32 + l +end + +-- the unsigned value as a number (rounded past 2^53) +function Int64.unsigned(h: number, l: number): number + return h * P32 + l +end + +-- unsigned compare: -1, 0, 1 +function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number + if ah ~= bh then + return if ah < bh then -1 else 1 + end + if al ~= bl then + return if al < bl then -1 else 1 + end + return 0 +end + +-- signed compare: -1, 0, 1 +function Int64.cmp(ah: number, al: number, bh: number, bl: number): number + local sa = if ah >= P31 then ah - P32 else ah + local sb = if bh >= P31 then bh - P32 else bh + if sa ~= sb then + return if sa < sb then -1 else 1 + end + return Int64.ucmp(0, al, 0, bl) +end + +-- unsigned division (b ~= 0): quotient, remainder +function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number) + if ah == 0 and bh == 0 then + return 0, al // bl, 0, al % bl + end + local qh, ql, rh, rl = 0, 0, 0, 0 + for i = 63, 0, -1 do + -- r = r * 2 + bit i of a + local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2 + local over = rh >= P31 + rh = (rh * 2 + rl // P31) % P32 + rl = (rl * 2) % P32 + bit + if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then + rh, rl = Int64.sub(rh, rl, bh, bl) + if i >= 32 then + qh += 2 ^ (i - 32) + else + ql += 2 ^ i + end + end + end + return qh, ql, rh, rl +end + +-- signed division truncating toward zero (b ~= 0) +function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number) + local na, nb = ah >= P31, bh >= P31 + if na then + ah, al = Int64.neg(ah, al) + end + if nb then + bh, bl = Int64.neg(bh, bl) + end + local qh, ql = Int64.udivmod(ah, al, bh, bl) + if na ~= nb then + return Int64.neg(qh, ql) + end + return qh, ql +end + +-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included) +function Int64.isqrt(h: number, l: number): (number, number) + if h == 0 and l == 0 then + return 0, 0 + end + local acth, actl = h, l + local sh, sl = 0, 1 + while Int64.ucmp(acth, actl, 0, 2) >= 0 do + sh, sl = Int64.add(sh, sl, sh, sl) + acth, actl = Int64.udivmod(acth, actl, 0, 4) + end + repeat + local qh, ql = Int64.udivmod(h, l, sh, sl) + local th, tl = Int64.add(sh, sl, qh, ql) + sh, sl = Int64.udivmod(th, tl, 0, 2) + if sh == 0 and sl == 0 then + return 0, 0 + end + local pph, ppl = Int64.mul(sh, sl, sh, sl) + until Int64.ucmp(pph, ppl, h, l) <= 0 + return sh, sl +end + +return Int64 diff --git a/src/Formats/codecs/model/Draco/Predict.luau b/src/Formats/codecs/model/Draco/Predict.luau new file mode 100644 index 0000000..61098a8 --- /dev/null +++ b/src/Formats/codecs/model/Draco/Predict.luau @@ -0,0 +1,977 @@ +--!strict +-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference +-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and +-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron. +-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53; +-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7 +-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0, +-- licenses/draco-LICENSE.txt). +local Reader = require("@formats/codecs/model/Draco/Reader") +local Connectivity = require("@formats/codecs/model/Draco/Connectivity") +local Int64 = require("@formats/codecs/model/Draco/Int64") + +local Predict = {} + +type D = Reader.D +type CT = Connectivity.CT + +local nextC, prevC = Connectivity.next, Connectivity.prev + +local F32 = buffer.create(4) +local function fround(x: number): number + buffer.writef32(F32, 0, x) + return buffer.readf32(F32, 0) +end +Predict.fround = fround + +local function i32(x: number): number + return (x + 2147483648) % 4294967296 - 2147483648 +end +Predict.i32 = i32 + +local function tdiv(a: number, b: number): number + local q = a / b + return if q < 0 then math.ceil(q) else math.floor(q) +end + +-- static_cast of a float with the decoder's NaN / range guard (INT_MIN) +local function truncInt(x: number): number + if x ~= x or x > 2147483647 or x < -2147483648 then + return -2147483648 + end + return tdiv(x, 1) +end + +-- exact a * b = p + e (Dekker), for integers below 2^53 +local SPLIT = 134217729 +local function twoProd(a: number, b: number): (number, number) + local p = a * b + local t = SPLIT * a + local ah = t - (t - a) + local al = a - ah + t = SPLIT * b + local bh = t - (t - b) + local bl = b - bh + return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl +end + +-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0) +local function mulDiv(a: number, b: number, c: number): number + local neg = (a < 0) ~= (b < 0) + a, b = math.abs(a), math.abs(b) + local p = a * b + local q + if p < 9007199254740992 then + q = p // c + else + q = math.floor(p / c) + local ph, pl = twoProd(a, b) + local qh, ql = twoProd(q, c) + local r = (ph - qh) + (pl - ql) + while r < 0 do + q -= 1 + r += c + end + while r >= c do + q += 1 + r -= c + end + end + return if neg then -q else q +end + +-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53 +local function isqrtProd(a: number, b: number): number + if a == 0 or b == 0 then + return 0 + end + local s = math.floor(math.sqrt(a) * math.sqrt(b)) + local ph, pl = twoProd(a, b) + local function le(x: number): boolean -- x * x <= a * b + local xh, xl = twoProd(x, x) + if xh ~= ph then + return xh < ph + end + return xl <= pl + end + while s > 0 and not le(s) do + s -= 1 + end + while le(s + 1) do + s += 1 + end + return s +end + +-- ------------------------------------------------------------------------------------------------ octahedron toolbox +export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number } + +function Predict.octahedron(bits: number): Oct? + if bits < 2 or bits > 30 then + return nil + end + local maxQ = 2 ^ bits - 1 + local maxV = maxQ - 1 + return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) } +end + +local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number) + local maxV, center = o.maxV, o.center + if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then + return maxV, maxV + elseif s == 0 and t > center then + t = center - (t - center) + elseif s == maxV and t < center then + t = center + (center - t) + elseif t == maxV and s < center then + s = center + (center - s) + elseif t == 0 and s > center then + s = center - (s - center) + end + return s, t +end + +local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number) + local s, t + local center, maxV = o.center, o.maxV + if x >= 0 then + s, t = y + center, z + center + else + s = if y < 0 then math.abs(z) else maxV - math.abs(z) + t = if z < 0 then math.abs(y) else maxV - math.abs(y) + end + return canonicalizeCoords(o, s, t) +end + +local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number) + local sum = math.abs(x) + math.abs(y) + math.abs(z) + local center = o.center + if sum == 0 then + return center, y, z + end + x = mulDiv(x, center, sum) + y = mulDiv(y, center, sum) + if z >= 0 then + z = center - math.abs(x) - math.abs(y) + else + z = -(center - math.abs(x) - math.abs(y)) + end + return x, y, z +end + +local function invertDiamond(o: Oct, s: number, t: number): (number, number) + local signS, signT + if s >= 0 and t >= 0 then + signS, signT = 1, 1 + elseif s <= 0 and t <= 0 then + signS, signT = -1, -1 + else + signS = if s > 0 then 1 else -1 + signT = if t > 0 then 1 else -1 + end + local cs, ctv = signS * o.center, signT * o.center + local us, ut = s + s - cs, t + t - ctv + if signS * signT >= 0 then + us, ut = -ut, -us + else + us, ut = ut, us + end + return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2) +end + +local function modMax(o: Oct, x: number): number + if x > o.center then + return x - o.maxQ + elseif x < -o.center then + return x + o.maxQ + end + return x +end + +-- quantized octahedral (s, t) -> unit vector, in f32 like the C++ +function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number) + local y = fround(fround(fround(s) * o.scale) - 1) + local z = fround(fround(fround(t) * o.scale) - 1) + local x = fround(fround(1 - math.abs(y)) - math.abs(z)) + local xo = -x + if xo < 0 then + xo = 0 + end + y = fround(if y < 0 then y + xo else y - xo) + z = fround(if z < 0 then z + xo else z - xo) + local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z)) + if n2 < 1e-6 then + return 0, 0, 0 + end + local dd = fround(1 / fround(math.sqrt(n2))) + return fround(x * dd), fround(y * dd), fround(z * dd) +end + +-- ------------------------------------------------------------------------------------------------ transforms +-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values +export type Transform = { + kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized + positive: boolean, -- corrections are stored without the zig-zag sign mapping + min: number, + max: number, + maxDif: number, + oct: Oct?, +} + +function Predict.transform(kind: number): Transform + return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil } +end + +function Predict.decodeTransform(tr: Transform, d: D): boolean + if tr.kind == 1 then + local mn, mx = Reader.i32(d), Reader.i32(d) + if d.bad or mn > mx then + return false + end + local dif = mx - mn + if dif >= 2147483647 then + return false + end + tr.min, tr.max, tr.maxDif = mn, mx, dif + 1 + return true + end + local maxQ = Reader.i32(d) + if tr.kind == 3 or d.ver < 0x0202 then + Reader.i32(d) -- center value (unused) + end + if d.bad or maxQ <= 0 or maxQ % 2 == 0 then + return false + end + local bits = 0 + while 2 ^ bits <= maxQ do + bits += 1 + end + local o = Predict.octahedron(bits) + if not o then + return false + end + tr.oct = o + return true +end + +-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..] +local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number) + if tr.kind == 1 then + local mn, mx, dif = tr.min, tr.max, tr.maxDif + for c = 1, comps do + local p = pred[c] + if p > mx then + p = mx + elseif p < mn then + p = mn + end + local v = i32(p + data[off + c]) + if v > mx then + v -= dif + elseif v < mn then + v += dif + end + data[off + c] = v + end + return + end + local o = tr.oct :: Oct + local center = o.center + local ps, pt = pred[1] - center, pred[2] - center + local cs, ct = data[off + 1], data[off + 2] + local inDiamond = math.abs(ps) + math.abs(pt) <= center + if not inDiamond then + ps, pt = invertDiamond(o, ps, pt) + end + local os_: number, ot: number = 0, 0 + if tr.kind == 2 then + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + else + local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0) + local rot = 0 + if ps == 0 then + rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1 + elseif ps > 0 then + rot = if pt >= 0 then 2 else 1 + else + rot = if pt <= 0 then 0 else 3 + end + local function rotate(x: number, y: number, r: number): (number, number) + if r == 1 then + return y, -x + elseif r == 2 then + return -x, -y + elseif r == 3 then + return -y, x + end + return x, y + end + if not bottomLeft then + ps, pt = rotate(ps, pt, rot) + end + os_ = modMax(o, i32(ps + cs)) + ot = modMax(o, i32(pt + ct)) + if not bottomLeft then + os_, ot = rotate(os_, ot, (4 - rot) % 4) + end + end + if not inDiamond then + os_, ot = invertDiamond(o, os_, ot) + end + data[off + 1] = os_ + center + data[off + 2] = ot + center +end +Predict.apply = apply + +-- ------------------------------------------------------------------------------------------------ schemes +-- the mesh data of a scheme: corner table, value -> corner, vertex -> value +export type MeshData = { ct: CT, e2c: { number }, v2e: { number } } +-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0) +export type Parent = (point: number) -> (number, number, number) + +export type Scheme = { + method: number, + tr: Transform, + md: MeshData?, + parent: Parent?, + -- per-scheme decoded data + crease: { { boolean } }?, + orient: { boolean }?, + flips: Reader.Bits?, + areaMode: boolean, + ver: number, +} + +local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6 +Predict.GEOMETRIC_NORMAL = GEONORMAL + +-- whether the scheme needs the position attribute +function Predict.needsParent(s: Scheme): boolean + return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL) +end + +-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta +function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme + local m = method + if not md then + m = DELTA + elseif tr.kind ~= 1 then + if m ~= GEONORMAL then + m = DELTA + md = nil + end + elseif m < PARALLELOGRAM or m > GEONORMAL then + m = DELTA + md = nil + end + return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 } +end + +-- DecodePredictionData +function Predict.decodeData(s: Scheme, d: D): boolean + local m = s.method + s.ver = d.ver + if m == CONSTRAINED then + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode ~= 0 then + return false + end + end + local md = s.md :: MeshData + local crease = {} + for i = 1, 4 do + local n = Reader.varint(d) + if d.bad or n > md.ct.nf * 3 then + return false + end + local flags = table.create(n, false) + if n > 0 then + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + for j = 1, n do + flags[j] = Reader.bit(bd) + end + end + crease[i] = flags + end + s.crease = crease + elseif m == TEXPORT then + local n = Reader.i32(d) + if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == TEXDEP then + local n = Reader.count(d, 0x0202) + local md = s.md :: MeshData + if d.bad or n == 0 or n > md.ct.nf * 3 then + return false + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + local orient = table.create(n, false) + local last = true + for i = 1, n do + if not Reader.bit(bd) then + last = not last + end + orient[i] = last + end + s.orient = orient + elseif m == GEONORMAL then + if not Predict.decodeTransform(s.tr, d) then + return false + end + if d.ver < 0x0202 then + local mode = Reader.u8(d) + if d.bad or mode > 1 then + return false + end + s.areaMode = mode == 1 + end + local bd = Reader.bitDecoder(d) + if not bd then + return false + end + s.flips = bd + return true + end + return Predict.decodeTransform(s.tr, d) +end + +local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean + local ct = md.ct + local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1) + if oci == -1 then + return false + end + local c2v, v2e = ct.c2v, md.v2e + local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1 + if vo < 0 or vn < 0 or vp < 0 then + return false + end + local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0 + if eo < p and en < p and ep < p then + for c = 1, comps do + out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c]) + end + return true + end + return false +end + +local function swingRight(ct: CT, c: number): number + local p = prevC(c) + local o = if p < 0 then -1 else (ct.opp[p + 1] or -1) + return prevC(o) +end +local function swingLeft(ct: CT, c: number): number + local n = nextC(c) + local o = if n < 0 then -1 else (ct.opp[n + 1] or -1) + return nextC(o) +end + +-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor +-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate +-- edge: predict from a neighbour); or "fail", message. +local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any) + local pnx, pny, pnz = qx - nx, qy - ny, qz - nz + local cnx, cny, cnz = tx - nx, ty - ny, tz - nz + local pnu, pnv = pu - nu, pv - nv + local B = 67108864 -- 2^26: below it every product and sum stays exact in a double + local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B + if small then + local pn2 = pnx * pnx + pny * pny + pnz * pnz + local dot = pnx * cnx + pny * cny + pnz * cnz + if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then + if pn2 == 0 then + return "fallback" + end + local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv + local dx = tx - (nx + tdiv(dot * pnx, pn2)) + local dy = ty - (ny + tdiv(dot * pny, pn2)) + local dz = tz - (nz + tdiv(dot * pnz, pn2)) + local cx2 = dx * dx + dy * dy + dz * dz + if cx2 < B then + local norm = isqrtProd(cx2, pn2) + local cxu, cxv = pnv * norm, -pnu * norm + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + if o then + return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2)) + end + return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2)) + end + end + end + -- the general case: int64 + local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div + local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number) + local xh, xl = from(ax) + local yh, yl = from(ay) + local zh, zl = from(az) + local uh, ul = from(bx) + local vh, vl = from(by) + local wh, wl = from(bz) + local h1, l1 = mul(xh, xl, uh, ul) + local h2, l2 = mul(yh, yl, vh, vl) + local h3, l3 = mul(zh, zl, wh, wl) + h1, l1 = add(h1, l1, h2, l2) + return add(h1, l1, h3, l3) + end + local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz) + if p2h == 0 and p2l == 0 then + return "fallback" + end + local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz) + local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX + local function absmax(...: number): (number, number) + local m = 0 + for _, x in { ... } do + m = math.max(m, math.abs(x)) + end + return from(m) + end + local function absI(h: number, l: number): (number, number) + if Int64.isNeg(h) then + return Int64.neg(h, l) + end + return h, l + end + -- the overflow guards (unsigned divisions as in the C++) + local nmh, nml = absmax(nu, nv) + local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l) + if Int64.ucmp(nmh, nml, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local adh, adl = absI(dh, dl) + local pmh, pml = absmax(pnu, pnv) + lh, ll = Int64.div(MAXH, MAXL, pmh, pml) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + local nuh, nul = from(nu) + local nvh, nvl = from(nv) + local puh, pul = from(pnu) + local pvh, pvl = from(pnv) + local xuh, xul + do + local ah, al = mul(nuh, nul, p2h, p2l) + local bh, bl = mul(dh, dl, puh, pul) + xuh, xul = add(ah, al, bh, bl) + end + local xvh, xvl + do + local ah, al = mul(nvh, nvl, p2h, p2l) + local bh, bl = mul(dh, dl, pvh, pvl) + xvh, xvl = add(ah, al, bh, bl) + end + local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz)) + local pah, pal = from(pam) + lh, ll = Int64.div(MAXH, MAXL, pah, pal) + if Int64.cmp(adh, adl, lh, ll) > 0 then + return "fail", "prediction: tex coord overflow" + end + -- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos + local function proj(n: number, pc: number, t: number): (number, number) + local ph, pl = from(pc) + local mh, ml = mul(dh, dl, ph, pl) + local qh, ql = div(mh, ml, p2h, p2l) + local nh, nl = from(n) + local xh, xl = add(nh, nl, qh, ql) + local th, tl = from(t) + return sub(th, tl, xh, xl) + end + local ax, axl = proj(nx, pnx, tx) + local ay, ayl = proj(ny, pny, ty) + local az, azl = proj(nz, pnz, tz) + local c2h, c2l = mul(ax, axl, ax, axl) + do + local h, l = mul(ay, ayl, ay, ayl) + c2h, c2l = add(c2h, c2l, h, l) + h, l = mul(az, azl, az, azl) + c2h, c2l = add(c2h, c2l, h, l) + end + local prh, prl = mul(c2h, c2l, p2h, p2l) + local sh, sl = Int64.isqrt(prh, prl) + -- cx_uv = (pn_uv.v, -pn_uv.u) * norm + local cuh, cul = mul(pvh, pvl, sh, sl) + local nh, nl = Int64.neg(puh, pul) + local cvh, cvl = mul(nh, nl, sh, sl) + local o = pop() + if o == nil then + return "fail", "prediction: orientations run out" + end + local uh, ul, vh, vl + if o then + uh, ul = add(xuh, xul, cuh, cul) + vh, vl = add(xvh, xvl, cvh, cvl) + else + uh, ul = sub(xuh, xul, cuh, cul) + vh, vl = sub(xvh, xvl, cvh, cvl) + end + uh, ul = div(uh, ul, p2h, p2l) + vh, vl = div(vh, vl, p2h, p2l) + -- static_cast: the low 32 bits + return "ok", i32(ul), i32(vl) +end + +-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map +function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?) + local tr = s.tr + local m = s.method + local pred = table.create(math.max(comps, 3), 0) + if m == DELTA then + if numEntries == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + for e = 1, numEntries - 1 do + local off = e * comps + for c = 1, comps do + pred[c] = data[off - comps + c] + end + apply(tr, pred, data, off, comps) + end + return true, nil + end + local md = s.md :: MeshData + local e2c = md.e2c + local n = #e2c + if n ~= numEntries then + return false, "prediction: value count mismatch" + end + local ct = md.ct + local function previous(p: number) + local off = (p - 1) * comps + for c = 1, comps do + pred[c] = data[off + c] + end + end + if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then + if n == 0 then + return true, nil + end + apply(tr, pred, data, 0, comps) + local para = table.create(comps, 0) + local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) } + local creasePos = { 0, 0, 0, 0 } + local nc = ct.nf * 3 + for p = 1, n - 1 do + local start = e2c[p + 1] + local off = p * comps + if m == PARALLELOGRAM then + if parallelogram(md, p, start, data, comps, pred) then + apply(tr, pred, data, off, comps) + else + previous(p) + apply(tr, pred, data, off, comps) + end + elseif m == MULTI then + for c = 1, comps do + pred[c] = 0 + end + local count = 0 + local ci = start + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, para) then + for c = 1, comps do + pred[c] = i32(pred[c] + para[c]) + end + count += 1 + end + ci = swingRight(ct, ci) + if ci == start then + ci = -1 + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + if count == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], count) + end + end + apply(tr, pred, data, off, comps) + else + local count = 0 + local ci = start + local first = true + local guard = 0 + while ci ~= -1 do + if parallelogram(md, p, ci, data, comps, preds[count + 1]) then + count += 1 + if count == 4 then + break + end + end + if first then + ci = swingLeft(ct, ci) + else + ci = swingRight(ct, ci) + end + if ci == start then + break + end + if ci == -1 and first then + first = false + ci = swingRight(ct, start) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local used = 0 + if count > 0 then + for c = 1, comps do + pred[c] = 0 + end + local crease = s.crease :: { { boolean } } + for i = 1, count do + local pos = creasePos[count] + 1 + creasePos[count] = pos + local flag = crease[count][pos] + if flag == nil then + return false, "prediction: crease flags run out" + end + if not flag then + used += 1 + for c = 1, comps do + pred[c] = i32(pred[c] + preds[i][c]) + end + end + end + end + if used == 0 then + previous(p) + else + for c = 1, comps do + pred[c] = tdiv(pred[c], used) + end + end + apply(tr, pred, data, off, comps) + end + end + return true, nil + end + local parent = s.parent + if not parent then + return false, "prediction: no position attribute" + end + local c2v, v2e = ct.c2v, md.v2e + local function entryOf(c: number): number + local v = if c < 0 then -1 else (c2v[c + 1] or -1) + if v < 0 then + return math.huge + end + return v2e[v + 1] or 0 + end + local function posOf(e: number): (number, number, number) + local pt = points[e + 1] + if pt == nil then + return 0, 0, 0 + end + return parent(pt) + end + if m == TEXPORT or m == TEXDEP then + if comps ~= 2 then + return false, "prediction: tex coords need 2 components" + end + local orient = s.orient :: { boolean } + local no = #orient + for p = 0, n - 1 do + local ci = e2c[p + 1] + local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci)) + local done = false + if pe < p and ne < p then + local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2] + local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2] + if m == TEXPORT then + if pu == nu and pv == nv then + pred[1], pred[2] = pu, pv + done = true + else + local tx, ty, tz = posOf(p) + local nx, ny, nz = posOf(ne) + local qx, qy, qz = posOf(pe) + local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean? + if no == 0 then + return nil + end + local o = orient[no] + orient[no] = nil + no -= 1 + return o + end) + if status == "fail" then + return false, u :: any + elseif status == "ok" then + pred[1], pred[2] = u, v + done = true + end + end + else + local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv) + if fpu == fnu and fpv == fnv then + pred[1], pred[2] = truncInt(fpu), truncInt(fpv) + done = true + else + local tx: number, ty: number, tz: number = posOf(p) + local nx: number, ny: number, nz: number = posOf(ne) + local qx: number, qy: number, qz: number = posOf(pe) + tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz) + qx, qy, qz = fround(qx), fround(qy), fround(qz) + local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz) + local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz) + local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz)) + local sv, tv = 0, 0 + if s.ver < 0x0102 or pn2 > 0 then + local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz)) + sv = fround(dot / pn2) + local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv)) + local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez)) + tv = fround(math.sqrt(fround(e2 / pn2))) + end + local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv) + local pnus = fround(fround(pnu * sv) + fnu) + local pnut = fround(pnu * tv) + local pnvs = fround(fround(pnv * sv) + fnv) + local pnvt = fround(pnv * tv) + if no == 0 then + return false, "prediction: orientations run out" + end + local o = orient[no] + orient[no] = nil + no -= 1 + local u: number, v: number = 0, 0 + if o then + u = fround(pnus - pnvt) + v = fround(pnvs + pnut) + else + u = fround(pnus + pnvt) + v = fround(pnvs - pnut) + end + local function toInt(x: number): number + local r = math.floor(x + 0.5) + if r ~= r or r > 2147483647 or r < -2147483648 then + return -2147483648 + end + return r + end + pred[1] = toInt(u) + pred[2] = toInt(v) + done = true + end + end + end + if not done then + local off = -1 + if pe < p then + off = pe * 2 + end + if ne < p then + off = ne * 2 + elseif p > 0 then + off = (p - 1) * 2 + else + off = -1 + end + if off < 0 then + pred[1], pred[2] = 0, 0 + else + pred[1], pred[2] = data[off + 1], data[off + 2] + end + end + apply(tr, pred, data, p * 2, 2) + end + return true, nil + end + -- geometric normal + local o = tr.oct + local flips = s.flips + if not o or not flips or comps ~= 2 then + return false, "prediction: bad geometric normal setup" + end + local nc = ct.nf * 3 + for p = 0, n - 1 do + local ci = e2c[p + 1] + local cx, cy, cz = posOf(entryOf(ci)) + local sx, sy, sz = 0, 0, 0 + -- VertexCornersIterator from ci: swing left, then right from the start + local c = ci + local left = true + local guard = 0 + while c ~= -1 do + local cn, cp + if s.areaMode then + cn, cp = nextC(c), prevC(c) + else + cn, cp = nextC(ci), prevC(ci) + end + local ax, ay, az = posOf(entryOf(cn)) + local bx, by, bz = posOf(entryOf(cp)) + ax, ay, az = ax - cx, ay - cy, az - cz + bx, by, bz = bx - cx, by - cy, bz - cz + sx += ay * bz - az * by + sy += az * bx - ax * bz + sz += ax * by - ay * bx + if left then + c = swingLeft(ct, c) + if c == -1 then + c = swingRight(ct, ci) + left = false + elseif c == ci then + c = -1 + end + else + c = swingRight(ct, c) + end + guard += 1 + if guard > nc then + return false, "prediction: bad vertex fan" + end + end + local upper = 2 ^ 29 + local sum = math.abs(sx) + math.abs(sy) + math.abs(sz) + if sum > upper then + local q = sum // upper + sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q) + end + sx, sy, sz = i32(sx), i32(sy), i32(sz) + sx, sy, sz = canonicalizeVector(o, sx, sy, sz) + if Reader.bit(flips) then + sx, sy, sz = -sx, -sy, -sz + end + pred[1], pred[2] = intVectorToOct(o, sx, sy, sz) + apply(tr, pred, data, p * 2, 2) + end + return true, nil +end + +return Predict diff --git a/src/Formats/codecs/model/Draco/Reader.luau b/src/Formats/codecs/model/Draco/Reader.luau new file mode 100644 index 0000000..1fb3b5c --- /dev/null +++ b/src/Formats/codecs/model/Draco/Reader.luau @@ -0,0 +1,480 @@ +--!strict +-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and +-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit +-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h, +-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0, +-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2). +-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries. +local Reader = {} + +local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32 +local band, rshift = bit32.band, bit32.rshift + +export type D = { + b: buffer, + pos: number, -- absolute offset in b + limit: number, -- absolute end + ver: number, -- major * 256 + minor + bad: string?, + bitMode: boolean, + bitStart: number, -- absolute byte where the bit run starts + bitOff: number, -- bits consumed +} + +function Reader.new(b: buffer, pos: number, limit: number, ver: number): D + return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 } +end + +-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards) +function Reader.copy(d: D): D + return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff } +end + +function Reader.fail(d: D, msg: string): number + if not d.bad then + d.bad = msg + end + return 0 +end + +function Reader.remaining(d: D): number + return d.limit - d.pos +end + +function Reader.u8(d: D): number + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 1 + return readu8(d.b, p) +end + +function Reader.i8(d: D): number + local v = Reader.u8(d) + return if v >= 128 then v - 256 else v +end + +function Reader.u16(d: D): number + local p = d.pos + if p + 2 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 2 + return readu16(d.b, p) +end + +function Reader.u32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readu32(d.b, p) +end + +function Reader.i32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readi32(d.b, p) +end + +-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway) +function Reader.u64(d: D): number + local p = d.pos + if p + 8 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 8 + return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296 +end + +function Reader.f32(d: D): number + local p = d.pos + if p + 4 > d.limit then + return Reader.fail(d, "truncated") + end + d.pos = p + 4 + return readf32(d.b, p) +end + +-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts +function Reader.varint(d: D, wide: boolean?): number + local maxBytes = if wide then 10 else 5 + local v, mul = 0, 1 + for _ = 1, maxBytes do + local p = d.pos + if p + 1 > d.limit then + return Reader.fail(d, "truncated varint") + end + local c = readu8(d.b, p) + d.pos = p + 1 + v += band(c, 127) * mul + if c < 128 then + if not wide then + v %= 4294967296 + end + return v + end + mul *= 128 + end + return Reader.fail(d, "varint too long") +end + +-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on +function Reader.count(d: D, fixedBefore: number): number + if d.ver < fixedBefore then + return Reader.u32(d) + end + return Reader.varint(d) +end + +-- ------------------------------------------------------------------------------------------------ bit runs +-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end +-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed. +function Reader.startBits(d: D, decodeSize: boolean): number + local size = 0 + if decodeSize then + if d.ver < 0x0202 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + end + d.bitMode = true + d.bitStart = d.pos + d.bitOff = 0 + return size +end + +function Reader.bits(d: D, n: number): number + if not d.bitMode then + return Reader.fail(d, "bit decoder not active") + end + if n > 32 then + return Reader.fail(d, "bit run over 32 bits") + end + local b, start, limit = d.b, d.bitStart, d.limit + local off = d.bitOff + local v, mul = 0, 1 + for _ = 1, n do + local byte = start + rshift(off, 3) + if byte < limit then + if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then + v += mul + end + off += 1 + end + mul *= 2 + end + d.bitOff = off + return v +end + +function Reader.endBits(d: D) + d.bitMode = false + d.pos = d.bitStart + (d.bitOff + 7) // 8 +end + +-- ------------------------------------------------------------------------------------------------ rANS symbols +-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20 +local function precisionBits(bitLength: number): number + local p = (3 * bitLength) // 2 + return if p < 12 then 12 elseif p > 20 then 20 else p +end + +export type Rans = { + b: buffer, + base: number, -- absolute start of the coded bytes + off: number, -- bytes left (read backwards from base + off) + state: number, + lBase: number, + precBits: number, + lut: { number }, -- rem + 1 -> symbol + 1 + prob: { number }, + cum: { number }, + numSymbols: number, +} + +-- RAnsSymbolDecoder::Create: the probability table +local function ransCreate(d: D, precBits: number): Rans? + local numSymbols = Reader.count(d, 0x0200) + if d.bad then + return nil + end + if numSymbols // 64 > Reader.remaining(d) then + Reader.fail(d, "rans: too many symbols") + return nil + end + local prec = 2 ^ precBits + local prob = table.create(numSymbols, 0) + local i = 0 + while i < numSymbols do + local data = Reader.u8(d) + if d.bad then + return nil + end + local token = band(data, 3) + if token == 3 then + local offset = rshift(data, 2) + if i + offset >= numSymbols then + Reader.fail(d, "rans: bad zero run") + return nil + end + for j = 0, offset do + prob[i + j + 1] = 0 + end + i += offset + 1 + else + local p = rshift(data, 2) + for k = 1, token do + p += Reader.u8(d) * 2 ^ (8 * k - 2) + end + if d.bad then + return nil + end + prob[i + 1] = p + i += 1 + end + end + local lut: { number } = {} + local cum = table.create(numSymbols, 0) + if numSymbols > 0 then + lut = table.create(prec, 0) + local c, act = 0, 0 + for s = 1, numSymbols do + cum[s] = c + c += prob[s] + if c > prec then + Reader.fail(d, "rans: probabilities over the precision") + return nil + end + for j = act + 1, c do + lut[j] = s + end + act = c + end + if c ~= prec then + Reader.fail(d, "rans: probabilities do not sum to the precision") + return nil + end + end + return { + b = d.b, + base = 0, + off = 0, + state = 0, + lBase = prec * 4, + precBits = precBits, + lut = lut, + prob = prob, + cum = cum, + numSymbols = numSymbols, + } +end + +-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes +local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?) + if size < 1 then + return nil, nil + end + local x = rshift(readu8(b, base + size - 1), 6) + local off: number, state: number = 0, 0 + if x == 0 then + off = size - 1 + state = band(readu8(b, base + size - 1), 0x3F) + elseif x == 1 then + if size < 2 then + return nil, nil + end + off = size - 2 + state = band(readu16(b, base + size - 2), 0x3FFF) + elseif x == 2 then + if size < 3 then + return nil, nil + end + off = size - 3 + state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536 + else + if not allow4 or size < 4 then + return nil, nil + end + off = size - 4 + state = band(readu32(b, base + size - 4), 0x3FFFFFFF) + end + state += lBase + if state >= lBase * 256 then + return nil, nil + end + return off, state +end + +-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes +local function ransStart(d: D, r: Rans): boolean + local size + if d.ver < 0x0200 then + size = Reader.u64(d) + else + size = Reader.varint(d, true) + end + if d.bad then + return false + end + if size > Reader.remaining(d) then + Reader.fail(d, "rans: data past the end") + return false + end + local off, state = ansInit(d.b, d.pos, size, r.lBase, true) + if not off then + Reader.fail(d, "rans: bad initial state") + return false + end + r.base, r.off, r.state = d.pos, off, state :: number + d.pos += size + return true +end + +-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values) +local function ransRead(r: Rans, n: number, out: { number }, first: number) + local b, base, off, state = r.b, r.base, r.off, r.state + local lBase, bits = r.lBase, r.precBits + local mask = 2 ^ bits - 1 + local lut, prob, cum = r.lut, r.prob, r.cum + for i = first, first + n - 1 do + while state < lBase and off > 0 do + off -= 1 + state = state * 256 + readu8(b, base + off) + end + local quo, rem = rshift(state, bits), band(state, mask) + local s = lut[rem + 1] + state = quo * prob[s] + rem - cum[s] + out[i] = s - 1 + end + r.off, r.state = off, state +end + +local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean + local tag = ransCreate(d, precisionBits(5)) + if not tag or not ransStart(d, tag) then + return false + end + if n > 0 and tag.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + Reader.startBits(d, false) + local len = { 0 } + local k = 1 + local i = 0 + while i < n do + ransRead(tag, 1, len, 1) + local bitLength = len[1] + for _ = 1, comps do + if k > n then + break + end + out[k] = Reader.bits(d, bitLength) + k += 1 + end + if d.bad then + return false + end + i += comps + end + Reader.endBits(d) + return true +end + +local function decodeRaw(d: D, n: number, out: { number }): boolean + local maxBitLength = Reader.u8(d) + if d.bad then + return false + end + if maxBitLength < 1 or maxBitLength > 18 then + Reader.fail(d, "rans: bad symbol bit length") + return false + end + local r = ransCreate(d, precisionBits(maxBitLength)) + if not r then + return false + end + if n > 0 and r.numSymbols == 0 then + Reader.fail(d, "rans: no symbols") + return false + end + if not ransStart(d, r) then + return false + end + ransRead(r, n, out, 1) + return true +end + +-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set) +function Reader.symbols(d: D, n: number, comps: number): { number }? + local out = table.create(n, 0) + if n == 0 then + return out + end + local scheme = Reader.u8(d) + if d.bad then + return nil + end + local ok + if scheme == 0 then + ok = decodeTagged(d, n, math.max(comps, 1), out) + elseif scheme == 1 then + ok = decodeRaw(d, n, out) + else + Reader.fail(d, "rans: unknown symbol coding scheme") + ok = false + end + return if ok then out else nil +end + +-- ------------------------------------------------------------------------------------------------ binary rANS +export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number } + +-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes +function Reader.bitDecoder(d: D): Bits? + local p0 = Reader.u8(d) + local size = Reader.count(d, 0x0202) + if d.bad then + return nil + end + if size > Reader.remaining(d) then + Reader.fail(d, "rabs: data past the end") + return nil + end + local off, state = ansInit(d.b, d.pos, size, 4096, false) + if not off then + Reader.fail(d, "rabs: bad initial state") + return nil + end + local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 } + d.pos += size + return bd +end + +-- rabs_desc_read: one bit (true / false) +function Reader.bit(bd: Bits): boolean + local state, off = bd.state, bd.off + if state < 4096 and off > 0 then + off -= 1 + state = state * 256 + readu8(bd.b, bd.base + off) + bd.off = off + end + local quot, rem = rshift(state, 8), band(state, 255) + local p = bd.p + local xn = quot * p + if rem < p then + bd.state = xn + rem + return true + end + bd.state = state - xn - p + return false +end + +return Reader diff --git a/src/Formats/codecs/model/Draco/init.luau b/src/Formats/codecs/model/Draco/init.luau new file mode 100644 index 0000000..fd994e2 --- /dev/null +++ b/src/Formats/codecs/model/Draco/init.luau @@ -0,0 +1,354 @@ +--!strict +-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). +-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. +-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions +-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology +-- splits, attribute seams) and sequential point clouds; attribute decoders generic / integer / quantization / +-- octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, constrained +-- multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal octahedron +-- transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the dequantization). +-- Not supported: kd-tree point clouds (Err.UNSUPPORTED). +-- +-- local Draco = require("@formats/codecs/model/Draco") +-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string +-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points) +-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId, +-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) } +-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map) +-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } } +-- +-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT. +-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Reader = require("@formats/codecs/model/Draco/Reader") +local Connectivity = require("@formats/codecs/model/Draco/Connectivity") +local Attributes = require("@formats/codecs/model/Draco/Attributes") + +local Draco = {} + +local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" } +local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" } +Draco.ATTRIBUTE_NAMES = NAMES +Draco.DATA_TYPES = TYPES + +export type Attribute = { + name: string, + typeId: number, + uniqueId: number, + components: number, + type: string, + normalized: boolean, + data: buffer, +} +export type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? } +export type Geometry = { + kind: "mesh" | "points", + version: string, + method: string, + numPoints: number, + numFaces: number, + indices: buffer?, + attributes: { Attribute }, + metadata: Metadata?, +} +export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number } + +-- sniff(buf, off?) -> whether the bytes start with "DRACO" +function Draco.sniff(buf: buffer, off: number?): boolean + local o = off or 0 + return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO" +end + +local function header(d: Reader.D): (Header?, string?) + if Reader.remaining(d) < 11 then + return nil, "truncated header" + end + if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then + return nil, "not Draco data" + end + d.pos += 5 + local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d) + local flags = Reader.u16(d) + if kind > 1 then + return nil, "unsupported: geometry type " .. kind + end + return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil +end + +-- info(buf, off?, len?) -> the header +function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local d = Reader.new(buf, o, o + l, 0) + local h, err = header(d) + if not h then + return nil, Err.from(err, 0) + end + return h, nil +end + +local function metadataElement(d: Reader.D, depth: number): Metadata? + if depth > 1000 then + return nil + end + local m: Metadata = { entries = {}, children = {} } + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + for _ = 1, n do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local size = Reader.varint(d) + if d.bad or size == 0 or size > Reader.remaining(d) then + return nil + end + local v = buffer.create(size) + buffer.copy(v, 0, d.b, d.pos, size) + d.pos += size + m.entries[name] = v + end + local subs = Reader.varint(d) + if d.bad or subs > Reader.remaining(d) then + return nil + end + for _ = 1, subs do + local nameLen = Reader.u8(d) + if d.bad or Reader.remaining(d) < nameLen then + return nil + end + local name = buffer.readstring(d.b, d.pos, nameLen) + d.pos += nameLen + local child = metadataElement(d, depth + 1) + if not child then + return nil + end + m.children[name] = child + end + return m +end + +local function metadata(d: Reader.D): Metadata? + local n = Reader.varint(d) + if d.bad or n > Reader.remaining(d) then + return nil + end + local atts: { [number]: Metadata } = {} + for _ = 1, n do + local id = Reader.varint(d) + local m = metadataElement(d, 0) + if not m then + return nil + end + atts[id] = m + end + local m = metadataElement(d, 0) + if not m then + return nil + end + m.attributes = atts + return m +end + +local WRITE: { [number]: (buffer, number, number) -> () } = { + [1] = buffer.writei8, + [2] = buffer.writeu8, + [3] = buffer.writei16, + [4] = buffer.writeu16, + [5] = buffer.writei32, + [6] = buffer.writeu32, + [9] = buffer.writef32, + [11] = buffer.writeu8, +} + +-- per point output buffer of an attribute +local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?) + local size = Attributes.DT_LENGTH[a.dataType] + local comps = a.comps + local stride = size * comps + local out = buffer.create(numPoints * stride) + local map = a.map + local n = a.numValues + if a.raw then + local raw = a.raw :: buffer + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + buffer.copy(out, p * stride, raw, e * stride, stride) + end + return out, nil + end + local vals = a.values :: { number } + local w = WRITE[a.dataType] + if not w then + return nil, "unsupported: data type " .. a.dataType + end + for p = 0, numPoints - 1 do + local e = if map then map[p + 1] else p + if e >= n then + return nil, "attribute value out of range" + end + local o = p * stride + local k = e * comps + for c = 1, comps do + w(out, o, vals[k + c]) + o += size + end + end + return out, nil +end + +local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?) + local d = Reader.new(buf, o, o + l, 0) + local h, herr = header(d) + if not h then + return nil, herr, nil + end + local ver = h.major * 256 + h.minor + local maxVer = if h.kind == "points" then 0x0203 else 0x0202 + if h.major < 1 or ver > maxVer then + return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil + end + d.ver = ver + local maxPoints = (opts and opts.maxPoints) or 2 ^ 24 + local maxFaces = (opts and opts.maxFaces) or 2 ^ 24 + local meta: Metadata? = nil + if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then + meta = metadata(d) + if not meta then + return nil, d.bad or "bad metadata", nil + end + end + local mesh: Connectivity.Mesh? = nil + local numPoints = 0 + local method + if h.kind == "mesh" then + if h.method == 0 then + method = "sequential" + local m, err = Connectivity.sequential(d) + if not m then + return nil, err, nil + end + mesh = m + elseif h.method == 1 then + method = "edgebreaker" + local kind = Reader.u8(d) + if d.bad then + return nil, d.bad, nil + end + if kind > 2 then + return nil, "unknown edgebreaker traversal " .. kind, nil + end + local m, err = Connectivity.edgebreaker(d, kind) + if not m then + return nil, err, nil + end + mesh = m + else + return nil, "unsupported: mesh encoding method " .. h.method, nil + end + local m = mesh :: Connectivity.Mesh + if m.numFaces > maxFaces then + return nil, "too many faces", "limit" + end + numPoints = m.numPoints + else + if h.method == 1 then + return nil, "unsupported: kd-tree point clouds", nil + elseif h.method ~= 0 then + return nil, "unsupported: point cloud encoding method " .. h.method, nil + end + method = "sequential" + numPoints = Reader.i32(d) + if d.bad then + return nil, d.bad, nil + end + if numPoints < 0 then + return nil, "bad point count", nil + end + end + if numPoints > maxPoints then + return nil, "too many points", "limit" + end + local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = false }) + if not attrs then + return nil, aerr, nil + end + local g: Geometry = { + kind = h.kind, + version = h.major .. "." .. h.minor, + method = method, + numPoints = numPoints, + numFaces = 0, + indices = nil, + attributes = {}, + metadata = meta, + } + if mesh then + local nf = mesh.numFaces + local idx = buffer.create(nf * 12) + local faces = mesh.faces + for i = 1, nf * 3 do + local v = faces[i] + if v < 0 or v >= numPoints then + return nil, "face index out of range", nil + end + buffer.writeu32(idx, (i - 1) * 4, v) + end + g.numFaces = nf + g.indices = idx + end + for _, a in attrs do + local data, err = expand(a, numPoints) + if not data then + return nil, err, nil + end + table.insert(g.attributes, { + name = NAMES[a.type] or "GENERIC", + typeId = a.type, + uniqueId = a.uniqueId, + components = a.comps, + type = TYPES[a.dataType], + normalized = a.normalized, + data = data, + }) + end + return g, nil, nil +end + +-- decode(src, off?, len?, opts?) -> Geometry | nil, Err +function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?) + local buf, o, l, aerr = Bytes.span("draco", src, off, len) + if not buf then + return nil, aerr + end + local ok, g, msg, kind = pcall(decode, buf, o, l, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g)) + end + if not g then + return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil)) + end + return g, nil +end + +-- attribute(g, uniqueId) -> the attribute with that unique id +function Draco.attribute(g: Geometry, uniqueId: number): Attribute? + for _, a in g.attributes do + if a.uniqueId == uniqueId then + return a + end + end + return nil +end + +return Draco diff --git a/tests/codecs/draco.luau b/tests/codecs/draco.luau new file mode 100644 index 0000000..d7098a7 --- /dev/null +++ b/tests/codecs/draco.luau @@ -0,0 +1,80 @@ +-- codecs/model/Draco tests: Google's Draco test data (bitstreams 0.9 - 2.2) and files encoded by draco_encoder 1.5.7 +-- at every compression level, quantization and as point clouds, decoded and compared byte for byte (points, faces, +-- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc); kd-tree +-- point clouds report UNSUPPORTED; argument errors; the fuzz no-throw pass (which also fails on any internal error the +-- decoder's safety net caught). Fixtures: tools/fixtures/draco.py. +local T = require("@tests/T") +local Draco = require("@formats/codecs/model/Draco") +local Err = require("@formats/core/Err") +local Crc32 = require("@formats/core/Crc32") +local Cases = require("@tests/gen/draco_cases") + +local t = T.suite("draco") + +local counts = { exact = 0, unsupported = 0, rejected = 0 } +local samples = {} +for _, c in Cases do + local g, err = Draco.decode(c.data) + if c.error then + t:check(g == nil and err ~= nil, c.name .. ": libdraco rejects it, so do we") + counts.rejected += 1 + elseif not g and err and err.code == Err.UNSUPPORTED and string.find(err.message, "kd-tree", 1, true) then + counts.unsupported += 1 + else + t:check(g, c.name .. ": decode: " .. tostring(err)) + if g then + t:eq(g.numPoints, c.points, c.name .. ": points") + if c.faces then + t:eq(g.numFaces, c.faces, c.name .. ": faces") + t:eq(Crc32.of(g.indices :: buffer), c.indices, c.name .. ": indices") + end + t:eq(#g.attributes, #c.attrs, c.name .. ": attribute count") + for i, want in c.attrs do + local a = g.attributes[i] + if a then + t:eq(a.typeId, want.type, c.name .. ": attribute " .. i .. " type") + t:eq(a.type, Draco.DATA_TYPES[want.dataType], c.name .. ": attribute " .. i .. " data type") + t:eq(a.components, want.components, c.name .. ": attribute " .. i .. " components") + t:eq(a.normalized, want.normalized, c.name .. ": attribute " .. i .. " normalized") + t:eq(a.uniqueId, want.uniqueId, c.name .. ": attribute " .. i .. " unique id") + t:eq(Crc32.of(a.data), want.crc, c.name .. ": attribute " .. i .. " (" .. a.name .. ") values") + end + end + counts.exact += 1 + if #c.data < 4000 then + table.insert(samples, c.data) + end + end + end +end +t:note("%d files decoded exactly like libdraco, %d kd-tree point clouds unsupported, %d rejected by both", counts.exact, counts.unsupported, counts.rejected) + +-- the attribute lookup and the header +local first = Cases[1] +local info = Draco.info(first.data) +t:check(info and (info.kind == "mesh" or info.kind == "points"), "info") +t:check(Draco.sniff(buffer.fromstring(first.data)), "sniff") +t:check(not Draco.sniff(buffer.fromstring("DRAC")), "sniff short") + +-- errors +local _, e1 = Draco.decode(buffer.fromstring("NOTDRACO......")) +t:check(e1 and e1.code == Err.CORRUPT, "not Draco data: " .. tostring(e1)) +local _, e2 = Draco.decode(buffer.fromstring("DRACO\9\0\1\1\0\0")) +t:check(e2 and e2.code == Err.UNSUPPORTED, "future version: " .. tostring(e2)) +local _, e3 = Draco.decode(42 :: any) +t:check(e3 and e3.code == Err.ARG, "bad argument") + +-- fuzz: never throws, and the internal safety net never fires +local internal = 0 +t:fuzz("decode", function(b: buffer) + local g, err = Draco.decode(b) + if not g and err and string.find(err.message, "internal error", 1, true) then + internal += 1 + if internal <= 5 then + print(" internal error: " .. err.message) + end + end + return g +end, samples, { mutations = 12, keepHeader = 11 }) +t:eq(internal, 0, "fuzz: internal errors") +t:done() diff --git a/tools/fixtures/_draco_dump.cc b/tools/fixtures/_draco_dump.cc new file mode 100644 index 0000000..e42196c --- /dev/null +++ b/tools/fixtures/_draco_dump.cc @@ -0,0 +1,44 @@ +// Dumps a decoded Draco file: points, faces and every attribute's per-point bytes (hex), for the fixture generator. +#include "draco/compression/decode.h" +#include +#include +#include +#include +static void hex(const uint8_t* p, size_t n) { for (size_t i = 0; i < n; ++i) printf("%02x", p[i]); } +int main(int argc, char** argv) { + std::ifstream f(argv[1], std::ios::binary); + std::vector data((std::istreambuf_iterator(f)), std::istreambuf_iterator()); + draco::DecoderBuffer buf; + buf.Init(data.data(), data.size()); + auto type = draco::Decoder::GetEncodedGeometryType(&buf); + if (!type.ok()) { printf("ERROR %s\n", type.status().error_msg()); return 0; } + draco::Decoder dec; + std::unique_ptr pc; + std::unique_ptr mesh; + if (type.value() == draco::TRIANGULAR_MESH) { + auto r = dec.DecodeMeshFromBuffer(&buf); + if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; } + mesh = std::move(r).value(); + } else { + auto r = dec.DecodePointCloudFromBuffer(&buf); + if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; } + pc = std::move(r).value(); + } + const draco::PointCloud* g = mesh ? mesh.get() : pc.get(); + printf("POINTS %u\n", g->num_points()); + if (mesh) { + printf("FACES %u ", mesh->num_faces()); + for (draco::FaceIndex fi(0); fi < mesh->num_faces(); ++fi) { + const auto& face = mesh->face(fi); + for (int c = 0; c < 3; ++c) { uint32_t v = face[c].value(); hex((const uint8_t*)&v, 4); } + } + printf("\n"); + } + for (int i = 0; i < g->num_attributes(); ++i) { + const draco::PointAttribute* a = g->attribute(i); + printf("ATTR %d %d %d %d %u ", (int)a->attribute_type(), (int)a->data_type(), (int)a->num_components(), a->normalized() ? 1 : 0, a->unique_id()); + for (draco::PointIndex p(0); p < g->num_points(); ++p) hex(a->GetAddress(a->mapped_index(p)), a->byte_stride()); + printf("\n"); + } + return 0; +} diff --git a/tools/fixtures/draco.py b/tools/fixtures/draco.py new file mode 100644 index 0000000..a6999b2 --- /dev/null +++ b/tools/fixtures/draco.py @@ -0,0 +1,137 @@ +# Draco fixtures (tools/fixtures.py): every .drc file of Google's Draco test data (bitstreams 0.9 - 2.2, read from the +# nixpkgs draco source, never committed) and files made here by draco_encoder 1.5.7 (nix) from the test data meshes +# and generated ones (a UV sphere with seams, a noisy grid, a coloured PLY), at every compression level (sequential, +# Edgebreaker standard / valence; difference, parallelogram, constrained multi-parallelogram, portable tex coords and +# geometric normal predictions), several quantizations (up to 30 bits) and as point clouds. The reference values come +# from libdraco itself: tools/fixtures/_draco_dump.cc, compiled here against nixpkgs#draco, prints the decoded points, +# faces and each attribute's bytes per point. +# tests/gen/draco_cases.luau { { name, data, error? = true, points, faces, indices = crc, attrs = { { type, dataType, +# components, normalized, uniqueId, crc } } } } +import math, os, subprocess, tempfile, zlib + +INPUTS = ["tools/fixtures/_draco_dump.cc"] + + +def store_path(attr): + out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def uv_sphere(rings=12, segs=20): + # an OBJ sphere with a UV seam and poles: vertices shared by position, split by UV + v, vt, vn, f = [], [], [], [] + for r in range(rings + 1): + th = math.pi * r / rings + for s in range(segs + 1): + ph = 2 * math.pi * s / segs + x, y, z = math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph) + v.append((x, y, z)) + vn.append((x, y, z)) + vt.append((s / segs, r / rings)) + w = segs + 1 + for r in range(rings): + for s in range(segs): + a, b, c, d = r * w + s + 1, r * w + s + 2, (r + 1) * w + s + 2, (r + 1) * w + s + 1 + if r > 0: + f.append((a, b, c)) + if r < rings - 1: + f.append((a, c, d)) + out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt] + ["vn %.6f %.6f %.6f" % p for p in vn] + out += ["f %d/%d/%d %d/%d/%d %d/%d/%d" % (a, a, a, b, b, b, c, c, c) for a, b, c in f] + return "\n".join(out) + "\n" + + +def noisy_grid(rng, n=24): + # a height field with a hole and per-vertex UVs: boundaries, holes and parallelogram predictions + v, vt, f = [], [], [] + for j in range(n): + for i in range(n): + v.append((i * 0.1, rng.uniform(-0.05, 0.05), j * 0.1)) + vt.append((i / (n - 1), j / (n - 1))) + for j in range(n - 1): + for i in range(n - 1): + if 8 <= i < 12 and 8 <= j < 12: + continue + a, b, c, d = j * n + i + 1, j * n + i + 2, (j + 1) * n + i + 2, (j + 1) * n + i + 1 + f.append((a, b, c)) + f.append((a, c, d)) + out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt] + out += ["f %d/%d %d/%d %d/%d" % (a, a, b, b, c, c) for a, b, c in f] + return "\n".join(out) + "\n" + + +def colored_ply(rng, n=200): + # an ASCII point set / mesh with colours (u8) and a generic float property + pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)] + faces = [(i, i + 1, i + 2) for i in range(0, n - 2, 3)] + head = ["ply", "format ascii 1.0", "element vertex %d" % n, "property float x", "property float y", "property float z", + "property uchar red", "property uchar green", "property uchar blue", "property uchar alpha", + "element face %d" % len(faces), "property list uchar int vertex_indices", "end_header"] + body = ["%.5f %.5f %.5f %d %d %d %d" % (p[0], p[1], p[2], rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for p in pts] + body += ["3 %d %d %d" % t for t in faces] + return "\n".join(head + body) + "\n" + + +def parse_dump(txt): + out = {"attrs": []} + for line in txt.split("\n"): + parts = line.split(" ") + if parts[0] == "ERROR": + return {"error": True} + if parts[0] == "POINTS": + out["points"] = int(parts[1]) + elif parts[0] == "FACES": + out["faces"] = int(parts[1]) + out["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else "")) + elif parts[0] == "ATTR": + out["attrs"].append({"type": int(parts[1]), "dataType": int(parts[2]), "components": int(parts[3]), + "normalized": parts[4] == "1", "uniqueId": int(parts[5]), + "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))}) + return out + + +def generate(ctx): + draco = store_path("draco") + src = store_path("draco.src") + testdata = os.path.join(src, "testdata") + tmp = tempfile.mkdtemp(prefix="formats-draco-") + dump = os.path.join(tmp, "dump") + ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"), + "-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump]) + encoder = os.path.join(draco, "bin", "draco_encoder") + + files = [] # (name, path) + for f in sorted(os.listdir(testdata)): + if f.endswith(".drc"): + files.append(("testdata/" + f, os.path.join(testdata, f))) + + rng = ctx.rng(31) + gen_inputs = {"uvsphere.obj": uv_sphere(), "grid.obj": noisy_grid(rng), "colored.ply": colored_ply(rng)} + for name, text in gen_inputs.items(): + with open(os.path.join(tmp, name), "w") as fh: + fh.write(text) + inputs = [(n, os.path.join(tmp, n)) for n in gen_inputs] + [(n, os.path.join(testdata, n)) for n in + ("cube_att.obj", "test_nm.obj", "sphere.obj", "cube_quads.obj", "test_generic.ply", "Box.ply")] + variants = [("cl%d" % cl, ["-cl", str(cl)]) for cl in range(11)] + variants += [("q14", ["-qp", "14", "-qt", "12", "-qn", "10"]), ("q20", ["-qp", "20", "-qt", "16", "-qn", "14", "-qg", "12"]), + ("q30", ["-qp", "30", "-qt", "30", "-qn", "30", "-qg", "30"]), ("q30cl10", ["-cl", "10", "-qp", "24", "-qt", "24", "-qn", "24"]), + ("raw", ["-qp", "0", "-qt", "0", "-qn", "0", "-qg", "0"]), ("meta", ["--metadata"]), ("poly", ["-preserve_polygons"]), + ("pc", ["-point_cloud", "-cl", "0"]), ("pckd", ["-point_cloud"])] + for iname, ipath in inputs: + for vname, args in variants: + out = os.path.join(tmp, "%s.%s.drc" % (iname, vname)) + r = subprocess.run([encoder, "-i", ipath, "-o", out] + args, capture_output=True) + if r.returncode == 0 and os.path.exists(out): + files.append(("enc/%s.%s" % (iname, vname), out)) + # the large bunny once (Edgebreaker valence + normals) + out = os.path.join(tmp, "bunny.drc") + if subprocess.run([encoder, "-i", os.path.join(testdata, "bunny_norm.obj"), "-o", out, "-cl", "7"], capture_output=True).returncode == 0: + files.append(("enc/bunny_norm.obj.cl7", out)) + + cases = [] + for name, path in files: + ref = parse_dump(subprocess.run([dump, path], capture_output=True).stdout.decode()) + case = {"name": name, "data": open(path, "rb").read()} + case.update(ref) + cases.append(case) + ctx.emit("draco_cases", cases) From 8183f4d2d7bb50d66d72fa8ab89667b127d3a2b9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:16:35 -0500 Subject: [PATCH 13/54] ws-video2-theora: codecs/video/Theora, a Theora decoder (port of libtheora 1.2.0, BSD) Headers (identification, comment via VorbisComment, setup: loop-filter limits, quant ranges -> dequant tables, the 80 Huffman trees as collapsed lookup tables), intra / inter frames, coded SB / block flags, MB modes (8 alphabets), MVs (VLC / CLC, last / prior, 4MV with per-format chroma averages, half / quarter-pel), block qi, DCT tokens with EOB runs, DC prediction, the spec IDCT, loop filter, golden / previous refs, 4:2:0 / 4:2:2 / 4:4:4, picture-region crop, empty-packet dupes. Bit-exact with ffmpeg on every frame of 12 fixtures (tests/codecs/theora). Outside the folder: codecs/video/Video BUILTIN entry theora gets a decoder (track.config = Xiph-laced headers, as Matroska's CodecPrivate); licenses/libtheora-BSD.txt + NOTICE row. --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/libtheora-BSD.txt | 28 + src/Formats/codecs/video/Theora/Decoder.luau | 1254 ++++++++++++++++++ src/Formats/codecs/video/Theora/Header.luau | 370 ++++++ src/Formats/codecs/video/Theora/init.luau | 270 ++++ src/Formats/codecs/video/Video/init.luau | 9 +- tests/codecs/theora.luau | 285 ++++ tools/fixtures/theora.py | 195 +++ 9 files changed, 2412 insertions(+), 1 deletion(-) create mode 100644 licenses/libtheora-BSD.txt create mode 100644 src/Formats/codecs/video/Theora/Decoder.luau create mode 100644 src/Formats/codecs/video/Theora/Header.luau create mode 100644 src/Formats/codecs/video/Theora/init.luau create mode 100644 tests/codecs/theora.luau create mode 100644 tools/fixtures/theora.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..5f34e95 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -134,4 +134,5 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **video** - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from + - codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..ef688ee 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,7 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/libtheora-BSD.txt b/licenses/libtheora-BSD.txt new file mode 100644 index 0000000..c8ccce4 --- /dev/null +++ b/licenses/libtheora-BSD.txt @@ -0,0 +1,28 @@ +Copyright (C) 2002-2009 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau new file mode 100644 index 0000000..d29b8cf --- /dev/null +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -0,0 +1,1254 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A +-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, +-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: +-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode +-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel +-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients; +-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5), +-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for +-- unrestricted motion vectors, golden / previous reference frames; +-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame. +-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists, +-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default), +-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ). +-- +-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled +-- chroma) pixels of edge padding; output() turns the picture region into top-down planes. +local Header = require("@formats/codecs/video/Theora/Header") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu16 = buffer.readu16 +local readi16 = buffer.readi16 +local writei16 = buffer.writei16 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local readu32 = buffer.readu32 +local bcopy = buffer.copy +local bfill = buffer.fill +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap + +local D = {} + +-- macro block modes (libtheora's numbering) +local NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV = 0, 1, 2, 3, 4, 5, 6, 7 +-- reference frames of a fragment (refi) +local GOLD, PREV, SELF, NONE = 0, 1, 2, 3 +local FRAME_FOR_MODE = { [0] = PREV, SELF, PREV, PREV, PREV, GOLD, GOLD, PREV } + +-- the mode alphabets of schemes 1..7 (scheme 0 sends its own) +local ALPHABETS = { + { MV_LAST, MV_LAST2, INTER_MV, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, MV_LAST2, NOMV, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, MV_LAST2, NOMV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { MV_LAST, INTER_MV, NOMV, MV_LAST2, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_NOMV, GOLD_MV, FOURMV }, + { NOMV, GOLD_NOMV, MV_LAST, MV_LAST2, INTER_MV, INTRA, GOLD_MV, FOURMV }, + { NOMV, INTRA, INTER_MV, MV_LAST, MV_LAST2, GOLD_NOMV, GOLD_MV, FOURMV }, +} + +-- the macro block mode VLC (0, 10, 110, ..., 1111110, 1111111): by the next 7 bits, index * 8 + length +local MODE_VLC = table.create(128, 0) +for w = 0, 127 do + local n = 0 + while n < 7 and bit32.extract(w, 6 - n, 1) == 1 do + n += 1 + end + MODE_VLC[w + 1] = n * 8 + (if n < 7 then n + 1 else 7) +end + +-- the motion vector component VLC (Theora spec table 7.23): by the next 8 bits, (value + 32) * 16 + length +local MV_VLC = table.create(256, 0) +do + local function put(code: number, len: number, v: number) + local sh = 8 - len + for i = 0, 2 ^ sh - 1 do + MV_VLC[code * 2 ^ sh + i + 1] = (v + 32) * 16 + len + end + end + put(0, 3, 0) + put(1, 3, 1) + put(2, 3, -1) + put(6, 4, 2) + put(7, 4, -2) + put(8, 4, 3) + put(9, 4, -3) + for m = 4, 7 do + put(0x28 + (m - 4) * 2, 6, m) + put(0x29 + (m - 4) * 2, 6, -m) + end + for m = 8, 15 do + put(0x60 + (m - 8) * 2, 7, m) + put(0x61 + (m - 8) * 2, 7, -m) + end + for m = 16, 31 do + put(0xE0 + (m - 16) * 2, 8, m) + put(0xE1 + (m - 16) * 2, 8, -m) + end +end + +-- DCT tokens: extra bits per token +local TOKEN_EXTRA = { + [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +} + +-- natural index of zig-zag position (1-based by position + 1) +local ZIGZAG = Header.ZIGZAG + +-- clamp to 0..255 by lookup: CLAMP[v + COFF], v in [-COFF, COFF + 255] +local COFF = 70000 +local CLAMP = buffer.create(2 * COFF + 512) +for i = 0, 2 * COFF + 511 do + buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) +end + +local C1, C2, C3, C4, C5, C6, C7 = 64277, 60547, 54491, 46341, 36410, 25080, 12785 + +export type State = { + pf: number, + hdec: number, + vdec: number, + fw: number, + fh: number, + pw: { number }, -- plane sizes in pixels, [pli + 1] + ph: { number }, + nhf: { number }, -- plane sizes in fragments + nvf: { number }, + foff: { number }, -- first fragment id - 1 of each plane + stride: { number }, + padx: { number }, + pady: { number }, + origin: { number }, -- byte offset of pixel (0, 0) + planeSize: { number }, + nfrags: number, + nsbs: number, + sbPlane: { number }, -- [pli + 1]: the first super block (0-based) of each plane, and [4] = nsbs + sbFr: { number }, -- [sbi * 16 + quad * 4 + bi + 1]: fragment id (1-based) or 0 + sbQuadValid: { boolean }, -- [sbi * 4 + quad + 1] + nmbs: number, + mbMode: { number }, -- [mbi + 1]: -1 outside the frame + mbFr: { number }, -- [mbi * 12 + pli * 4 + bi + 1]: fragment id or 0 + mapIdx: { number }, -- the valid (pli * 4 + bi) slots of a macro block for this pixel format + -- per fragment [fi] + coded: { number }, + refi: { number }, + fmode: { number }, + mvx: { number }, + mvy: { number }, + qii: { number }, + dcv: { number }, + tis: { number }, + last: { number }, + fpos: { number }, -- byte offset of the fragment's first pixel in its plane + fpl: { number }, -- plane (0..2) + coef: buffer, -- i16 [(fi - 1) * 64 + zzi] + clist: { { number } }, -- coded fragments per plane, coded order + ncl: { number }, + act: { { number } }, + refs: { { buffer } }, -- [r][pli + 1] + gold: number, + prev: number, + shown: number, -- the reference holding the last decoded picture + dequant: buffer, + lflim: { number }, + huff: { number }, + roots: { number }, + blk: buffer, -- i32 x 64 work blocks + tmp: buffer, + res: buffer, + bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] + keyframes: number, +} + +-- new(info, setup) -> State +function D.new(info: Header.Info, setup: Header.Setup): State + local pf = info.pixelFormat + local hdec = if pf % 2 == 0 then 1 else 0 + local vdec = if pf < 2 then 1 else 0 + local fw, fh = info.frameWidth, info.frameHeight + local st: any = { + pf = pf, + hdec = hdec, + vdec = vdec, + fw = fw, + fh = fh, + pw = {}, + ph = {}, + nhf = {}, + nvf = {}, + foff = {}, + stride = {}, + padx = {}, + pady = {}, + origin = {}, + planeSize = {}, + dequant = setup.dequant, + lflim = setup.lflim, + huff = setup.huff, + roots = setup.roots, + blk = buffer.create(256), + tmp = buffer.create(256), + res = buffer.create(256), + bv = table.create(257, 0), + keyframes = 0, + } + local nfr = 0 + for pli = 0, 2 do + local hd, vd = if pli > 0 then hdec else 0, if pli > 0 then vdec else 0 + local w, h = fw // 2 ^ hd, fh // 2 ^ vd + local px, py = 16 // 2 ^ hd, 16 // 2 ^ vd + st.pw[pli + 1], st.ph[pli + 1] = w, h + st.nhf[pli + 1], st.nvf[pli + 1] = w // 8, h // 8 + st.foff[pli + 1] = nfr + nfr += (w // 8) * (h // 8) + st.padx[pli + 1], st.pady[pli + 1] = px, py + local stride = w + 2 * px + st.stride[pli + 1] = stride + st.origin[pli + 1] = py * stride + px + st.planeSize[pli + 1] = stride * (h + 2 * py) + end + st.nfrags = nfr + st.coded = table.create(nfr, 0) + st.refi = table.create(nfr, NONE) + st.fmode = table.create(nfr, 0) + st.mvx = table.create(nfr, 0) + st.mvy = table.create(nfr, 0) + st.qii = table.create(nfr, 0) + st.dcv = table.create(nfr, 0) + st.tis = table.create(nfr, 0) + st.last = table.create(nfr, 0) + st.fpos = table.create(nfr, 0) + st.fpl = table.create(nfr, 0) + st.coef = buffer.create(nfr * 128) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride, origin = st.stride[pli + 1], st.origin[pli + 1] + for fy = 0, nv - 1 do + for fx = 0, nh - 1 do + local fi = st.foff[pli + 1] + fy * nh + fx + 1 + st.fpos[fi] = origin + fy * 8 * stride + fx * 8 + st.fpl[fi] = pli + end + end + end + -- super blocks: 4x4 fragments in Hilbert order (oc_sb_create_plane_mapping) + local SB_MAP = { + { { 0, 0 }, { 0, 1 }, { 3, 2 }, { 3, 3 } }, + { { 0, 3 }, { 0, 2 }, { 3, 1 }, { 3, 0 } }, + { { 1, 0 }, { 1, 3 }, { 2, 0 }, { 2, 3 } }, + { { 1, 1 }, { 1, 2 }, { 2, 1 }, { 2, 2 } }, + } + local sbFr: { number } = {} + local sbQuadValid: { boolean } = {} + local sbPlane: { number } = {} + local sbi = 0 + for pli = 0, 2 do + sbPlane[pli + 1] = sbi + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + for y = 0, nv - 1, 4 do + for x = 0, nh - 1, 4 do + for k = 1, 16 do + sbFr[sbi * 16 + k] = 0 + end + for i = 0, math.min(4, nv - y) - 1 do + for j = 0, math.min(4, nh - x) - 1 do + local m = SB_MAP[i + 1][j + 1] + sbFr[sbi * 16 + m[1] * 4 + m[2] + 1] = st.foff[pli + 1] + (y + i) * nh + x + j + 1 + end + end + for q = 0, 3 do + -- the upper left block of each quadrant: index 0, but 2 in quadrant 3 + local tl = if q == 3 then 2 else 0 + sbQuadValid[sbi * 4 + q + 1] = sbFr[sbi * 16 + q * 4 + tl + 1] ~= 0 + end + sbi += 1 + end + end + end + sbPlane[4] = sbi + st.nsbs = sbi + st.sbFr, st.sbQuadValid, st.sbPlane = sbFr, sbQuadValid, sbPlane + -- macro blocks: 4 per luma super block (oc_mb_create_mapping) + local nsbl = sbPlane[2] + local nmbs = nsbl * 4 + local mbMode = table.create(nmbs, 0) + local mbFr = table.create(nmbs * 12, 0) + local MB_MAP = { { 0, 3 }, { 1, 2 } } + local nhl, nvl = st.nhf[1], st.nvf[1] + local nhc = st.nhf[2] + sbi = 0 + for y = 0, nvl - 1, 4 do + for x = 0, nhl - 1, 4 do + for ymb = 0, 1 do + for xmb = 0, 1 do + local mbi = sbi * 4 + MB_MAP[ymb + 1][xmb + 1] + local mbx, mby = x + xmb * 2, y + ymb * 2 + if mbx >= nhl or mby >= nvl then + mbMode[mbi + 1] = -1 + else + local o = mbi * 12 + for i = 0, 1 do + for j = 0, 1 do + mbFr[o + i * 2 + j + 1] = (mby + i) * nhl + mbx + j + 1 + end + end + for pli = 1, 2 do + local base = st.foff[pli + 1] + 1 + if pf == 0 then + mbFr[o + pli * 4 + 1] = base + (mby // 2) * nhc + mbx // 2 + elseif pf == 2 then + for i = 0, 1 do + mbFr[o + pli * 4 + i * 2 + 1] = base + (mby + i) * nhc + mbx // 2 + end + else + for k = 0, 3 do + mbFr[o + pli * 4 + k + 1] = mbFr[o + k + 1] + st.foff[pli + 1] + end + end + end + end + end + end + sbi += 1 + end + end + st.nmbs, st.mbMode, st.mbFr = nmbs, mbMode, mbFr + st.mapIdx = if pf == 0 then { 0, 1, 2, 3, 4, 8 } elseif pf == 2 then { 0, 1, 2, 3, 4, 6, 8, 10 } else { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } + st.clist = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.act = { table.create(st.nhf[1] * st.nvf[1], 0), table.create(st.nhf[2] * st.nvf[2], 0), table.create(st.nhf[3] * st.nvf[3], 0) } + st.ncl = { 0, 0, 0 } + -- three reference frames, grey until the first keyframe + st.refs = {} + for r = 1, 3 do + local planes = {} + for pli = 1, 3 do + local b = buffer.create(st.planeSize[pli]) + bfill(b, 0, 128) + planes[pli] = b + end + st.refs[r] = planes + end + st.gold, st.prev, st.shown = 1, 1, 1 + return st :: State +end + +-- ------------------------------------------------------------------------------------------------ reconstruction +-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs +local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) + local t0 = (C4 * (x0 + x4)) // 65536 + local t1 = (C4 * (x0 - x4)) // 65536 + local t2 = (C6 * x2) // 65536 - (C2 * x6) // 65536 + local t3 = (C2 * x2) // 65536 + (C6 * x6) // 65536 + local t4 = (C7 * x1) // 65536 - (C1 * x7) // 65536 + local t5 = (C3 * x5) // 65536 - (C5 * x3) // 65536 + local t6 = (C5 * x5) // 65536 + (C3 * x3) // 65536 + local t7 = (C1 * x1) // 65536 + (C7 * x7) // 65536 + local r = t4 + t5 + t5 = (C4 * (t4 - t5)) // 65536 + t4 = r + r = t7 + t6 + t6 = (C4 * (t7 - t6)) // 65536 + t7 = r + r = t0 + t3 + t3 = t0 - t3 + t0 = r + r = t1 + t2 + t2 = t1 - t2 + t1 = r + r = t6 + t5 + t5 = t6 - t5 + t6 = r + return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 +end + +-- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and +-- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. +local function idct(blk: buffer, tmp: buffer, res: buffer) + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) + local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) + local c = i * 2 + if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + writei16(tmp, c, 0) + writei16(tmp, c + 16, 0) + writei16(tmp, c + 32, 0) + writei16(tmp, c + 48, 0) + writei16(tmp, c + 64, 0) + writei16(tmp, c + 80, 0) + writei16(tmp, c + 96, 0) + writei16(tmp, c + 112, 0) + else + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + writei16(tmp, c, y0) + writei16(tmp, c + 16, y1) + writei16(tmp, c + 32, y2) + writei16(tmp, c + 48, y3) + writei16(tmp, c + 64, y4) + writei16(tmp, c + 80, y5) + writei16(tmp, c + 96, y6) + writei16(tmp, c + 112, y7) + end + end + for i = 0, 7 do + local o = i * 16 + local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) + local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) + local c = i * 4 + writei32(res, c, (y0 + 8) // 16) + writei32(res, c + 32, (y1 + 8) // 16) + writei32(res, c + 64, (y2 + 8) // 16) + writei32(res, c + 96, (y3 + 8) // 16) + writei32(res, c + 128, (y4 + 8) // 16) + writei32(res, c + 160, (y5 + 8) // 16) + writei32(res, c + 192, (y6 + 8) // 16) + writei32(res, c + 224, (y7 + 8) // 16) + end +end + +local function wrap16(v: number): number + return (v + 32768) % 65536 - 32768 +end + +-- the motion vector offsets of one component: integer part (toward zero) and the second sample's extra step (away +-- from zero) when there is a fraction. q: quarter-pel (subsampled direction) or half-pel +local function mvSplit(d: number, q: boolean): (number, number) + local div = if q then 4 else 2 + local a = if d < 0 then -((-d) // div) else d // div + local frac = d - a * div + local b = if frac > 0 then 1 elseif frac < 0 then -1 else 0 + return a, b +end + +-- reconstruct one coded fragment into dst (the SELF reference planes) +local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) + local pli = st.fpl[fi] + local mode = st.fmode[fi] + local qti = if mode == INTRA then 0 else 1 + local dq = st.dequant + local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) + local dc = st.dcv[fi] + local last = st.last[fi] + local res = st.res + local flat = false + local fv = 0 + if last == 0 then + flat = true + fv = wrap16((dc * dcq + 15) // 32) + else + local blk = st.blk + bfill(blk, 0, 0, 128) + writei16(blk, 0, wrap16(dc * dcq)) + local coef = st.coef + local co = (fi - 1) * 128 + local ao = (((qis[st.qii[fi] + 1] * 3 + pli) * 2 + qti) * 64) * 2 + for z = 1, last do + local c = readi16(coef, co + z * 2) + if c ~= 0 then + writei16(coef, co + z * 2, 0) + writei16(blk, ZIGZAG[z + 1] * 2, wrap16(c * readu16(dq, ao + z * 2))) + end + end + st.last[fi] = 0 + idct(blk, st.tmp, res) + end + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] + if ri == SELF then + if flat then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + else + for y = 0, 7 do + local d, s = pos + y * stride, y * 32 + for x = 0, 7 do + writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) + end + end + end + return + end + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local qx = pli > 0 and st.hdec == 1 + local qy = pli > 0 and st.vdec == 1 + local mx, mx2 = mvSplit(st.mvx[fi], qx) + local my, my2 = mvSplit(st.mvy[fi], qy) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + local s2 = s1 + my2 * stride + mx2 + for y = 0, 7 do + local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 + for x = 0, 7 do + local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) + end + end + else + for y = 0, 7 do + local d, a, r = pos + y * stride, s1 + y * stride, y * 32 + for x = 0, 7 do + local v = if flat then fv else readi32(res, r + x * 4) + writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ loop filter +local function filterH(b: buffer, p: number, stride: number, bv: { number }) + p -= 2 + for _ = 0, 7 do + local p0, p1, p2, p3 = readu8(b, p), readu8(b, p + 1), readu8(b, p + 2), readu8(b, p + 3) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, p + 1, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + 2, readu8(CLAMP, p2 - f + COFF)) + p += stride + end +end + +local function filterV(b: buffer, p: number, stride: number, bv: { number }) + local q0, q1, q2 = p - 2 * stride, p - stride, p + stride + for x = 0, 7 do + local p0, p1, p2, p3 = readu8(b, q0 + x), readu8(b, q1 + x), readu8(b, p + x), readu8(b, q2 + x) + local f = bv[(p0 - p3 + 3 * (p2 - p1) + 4) // 8 + 129] + writeu8(b, q1 + x, readu8(CLAMP, p1 + f + COFF)) + writeu8(b, p + x, readu8(CLAMP, p2 - f + COFF)) + end +end + +local function loopFilter(st: State, planes: { buffer }, flimit: number) + local bv = st.bv + for i = -128, 128 do + local a = math.abs(i) + local v = 0 + if a < flimit then + v = i + elseif a < 2 * flimit then + v = if i > 0 then 2 * flimit - a else a - 2 * flimit + end + -- libtheora's table stops at index -127 (127 - i - flimit >= 0) + if i < -127 then + v = 0 + end + bv[i + 129] = v + end + local coded = st.coded + for pli = 0, 2 do + local b = planes[pli + 1] + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local stride = st.stride[pli + 1] + local base = st.foff[pli + 1] + local fpos = st.fpos + for fy = 0, nv - 1 do + local row = base + fy * nh + for fx = 0, nh - 1 do + local fi = row + fx + 1 + if coded[fi] ~= 0 then + local p = fpos[fi] + if fx > 0 then + filterH(b, p, stride, bv) + end + if fy > 0 then + filterV(b, p, stride, bv) + end + if fx + 1 < nh and coded[fi + 1] == 0 then + filterH(b, p + 8, stride, bv) + end + if fy + 1 < nv and coded[fi + nh] == 0 then + filterV(b, p + 8 * stride, stride, bv) + end + end + end + end + end +end + +-- extend each plane's edge pixels into its padding (for unrestricted motion vectors) +local function borders(st: State, planes: { buffer }) + for pli = 1, 3 do + local b = planes[pli] + local stride, px, py = st.stride[pli], st.padx[pli], st.pady[pli] + local w, h = st.pw[pli], st.ph[pli] + for y = 0, h - 1 do + local o = (y + py) * stride + bfill(b, o, readu8(b, o + px), px) + bfill(b, o + px + w, readu8(b, o + px + w - 1), px) + end + local top, bot = py * stride, (py + h - 1) * stride + for k = 1, py do + bcopy(b, top - k * stride, b, top, stride) + bcopy(b, bot + k * stride, b, bot, stride) + end + end +end + +-- ------------------------------------------------------------------------------------------------ frame decode +-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in +-- st.refs[st.shown]. +function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) + if len <= 0 then + return "dup", nil + end + -- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first + local bb = buffer.create(len + 24) + bcopy(bb, 0, data, off, len) + local maxp = len * 8 + local pos = 0 + local function bits(n: number): number + if pos > maxp then + pos = maxp + end + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + pos += n + return w + end + local huff = st.huff + local function token(root: number): number + if pos > maxp then + pos = maxp + end + local o = root + while true do + local n = huff[o] + local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local e = huff[o + 1 + w] + if e >= 0 then + pos += e // 64 + return e % 64 + end + pos += n + o = -e + if pos > maxp then + pos = maxp + end + end + end + local function sbRun(): number + if bits(1) == 0 then + return 1 + elseif bits(1) == 0 then + return 2 + bits(1) + elseif bits(1) == 0 then + return 4 + bits(1) + elseif bits(1) == 0 then + return 6 + bits(2) + elseif bits(1) == 0 then + return 10 + bits(3) + elseif bits(1) == 0 then + return 18 + bits(4) + end + return 34 + bits(12) + end + local function blockRun(): number + if bits(1) == 0 then + return 1 + bits(1) + elseif bits(1) == 0 then + return 3 + bits(1) + elseif bits(1) == 0 then + return 5 + bits(1) + elseif bits(1) == 0 then + return 7 + bits(2) + elseif bits(1) == 0 then + return 11 + bits(2) + end + return 15 + bits(4) + end + + -- frame header + if bits(1) ~= 0 then + return nil, "not a data packet" + end + local intra = bits(1) == 0 + local qis = { bits(6) } + if bits(1) == 1 then + table.insert(qis, bits(6)) + if bits(1) == 1 then + table.insert(qis, bits(6)) + end + end + if intra then + if bits(3) ~= 0 then + return nil, "unsupported: reserved keyframe bits set" + end + end + local coded, refi, fmode, dcv, tis, qii = st.coded, st.refi, st.fmode, st.dcv, st.tis, st.qii + local mvx, mvy = st.mvx, st.mvy + local sbFr, sbQuadValid, sbPlane = st.sbFr, st.sbQuadValid, st.sbPlane + local clist, ncl = st.clist, st.ncl + local mbMode = st.mbMode + local nsbs = st.nsbs + local total = 0 + if intra then + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for sbi = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + for q = 0, 3 do + if sbQuadValid[sbi * 4 + q + 1] then + for bi = 0, 3 do + local fi = sbFr[sbi * 16 + q * 4 + bi + 1] + if fi ~= 0 then + coded[fi] = 1 + refi[fi] = SELF + fmode[fi] = INTRA + n += 1 + list[n] = fi + end + end + end + end + end + ncl[pli + 1] = n + total += n + end + else + -- partially coded super blocks, then fully coded ones among the rest + local partial, full = table.create(nsbs, false), table.create(nsbs, false) + local npartial = 0 + local flag = bits(1) + local sbi = 0 + while sbi < nsbs do + local run = sbRun() + local fullRun = run >= 4129 + repeat + partial[sbi + 1] = flag == 1 + npartial += flag + sbi += 1 + run -= 1 + until run <= 0 or sbi >= nsbs + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + end + if npartial < nsbs then + sbi = 0 + while partial[sbi + 1] do + sbi += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while sbi < nsbs do + if not partial[sbi + 1] then + if run <= 0 then + break + end + run -= 1 + full[sbi + 1] = flag == 1 + end + sbi += 1 + end + if fullRun and sbi < nsbs then + flag = bits(1) + else + flag = 1 - flag + end + until sbi >= nsbs + end + -- block flags + local bflag = 0 + if npartial > 0 then + bflag = 1 - bits(1) + end + local run = 0 + for pli = 0, 2 do + local list, n = clist[pli + 1], 0 + for s = sbPlane[pli + 1], sbPlane[pli + 2] - 1 do + local isFull, isPartial = full[s + 1], partial[s + 1] + for q = 0, 3 do + if sbQuadValid[s * 4 + q + 1] then + local quadCoded = 0 + for bi = 0, 3 do + local fi = sbFr[s * 16 + q * 4 + bi + 1] + if fi ~= 0 then + local c = 0 + if isFull then + c = 1 + elseif isPartial then + if run <= 0 then + run = blockRun() + bflag = 1 - bflag + end + run -= 1 + c = bflag + end + coded[fi] = c + refi[fi] = NONE + if c == 1 then + n += 1 + list[n] = fi + quadCoded = 1 + end + end + end + if pli == 0 then + mbMode[s * 4 + q + 1] = quadCoded + end + end + end + end + ncl[pli + 1] = n + total += n + end + if total == 0 then + return "dup", nil + end + -- macro block modes + local scheme = bits(3) + local alphabet: { number } + if scheme == 0 then + alphabet = table.create(8, NOMV) + for mi = 1, 8 do + alphabet[bits(3) + 1] = ALPHABETS[7][mi] + end + else + alphabet = ALPHABETS[scheme] + end + for mbi = 1, st.nmbs do + if mbMode[mbi] > 0 then + local idx: number + if scheme == 7 then + idx = bits(3) + else + local e = MODE_VLC[bits(7) + 1] + pos -= 7 - e % 8 + idx = e // 8 + end + mbMode[mbi] = alphabet[idx + 1] + end + end + -- motion vectors + local clc = bits(1) == 1 + local function mv(): number + if clc then + local v = bits(6) + return if v % 2 == 1 then -(v // 2) else v // 2 + end + local e = MV_VLC[bits(8) + 1] + pos -= 8 - e % 16 + return e // 16 - 32 + end + local mbFr, mapIdx = st.mbFr, st.mapIdx + local nmap = #mapIdx + local lastX, lastY, priorX, priorY = 0, 0, 0, 0 + local lx, ly = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local cx, cy = { 0, 0, 0, 0 }, { 0, 0, 0, 0 } + local pf = st.pf + for mbi = 0, st.nmbs - 1 do + local mode = mbMode[mbi + 1] + if mode >= 0 then + local o = mbi * 12 + if mode == FOURMV then + priorX, priorY = lastX, lastY + for bi = 1, 4 do + local fi = mbFr[o + bi] + if coded[fi] ~= 0 then + refi[fi] = PREV + fmode[fi] = FOURMV + local x = mv() + local y = mv() + lx[bi], ly[bi] = x, y + lastX, lastY = x, y + mvx[fi], mvy[fi] = x, y + else + lx[bi], ly[bi] = 0, 0 + end + end + if pf == 0 then + local sx, sy = lx[1] + lx[2] + lx[3] + lx[4], ly[1] + ly[2] + ly[3] + ly[4] + cx[1] = (sx + 2 - (if sx < 0 then 1 else 0)) // 4 + cy[1] = (sy + 2 - (if sy < 0 then 1 else 0)) // 4 + elseif pf == 2 then + local sx, sy = lx[1] + lx[2], ly[1] + ly[2] + cx[1] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[1] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + sx, sy = lx[3] + lx[4], ly[3] + ly[4] + cx[3] = (sx + 1 - (if sx < 0 then 1 else 0)) // 2 + cy[3] = (sy + 1 - (if sy < 0 then 1 else 0)) // 2 + else + for k = 1, 4 do + cx[k], cy[k] = lx[k], ly[k] + end + end + for m = 5, nmap do + local mi = mapIdx[m] + local fi = mbFr[o + mi + 1] + if coded[fi] ~= 0 then + local bi = mi % 4 + 1 + refi[fi] = PREV + fmode[fi] = FOURMV + mvx[fi], mvy[fi] = cx[bi], cy[bi] + end + end + else + local x, y = 0, 0 + if mode == INTER_MV then + priorX, priorY = lastX, lastY + x = mv() + y = mv() + lastX, lastY = x, y + elseif mode == MV_LAST then + x, y = lastX, lastY + elseif mode == MV_LAST2 then + x, y = priorX, priorY + priorX, priorY = lastX, lastY + lastX, lastY = x, y + elseif mode == GOLD_MV then + x = mv() + y = mv() + end + local r = FRAME_FOR_MODE[mode] + for m = 1, nmap do + local fi = mbFr[o + mapIdx[m] + 1] + if coded[fi] ~= 0 then + refi[fi] = r + fmode[fi] = mode + mvx[fi], mvy[fi] = x, y + end + end + end + end + end + end + + -- block qi indices (over every coded fragment, planes in order) + local nqis = #qis + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + local fi = list[k] + qii[fi] = 0 + dcv[fi] = 0 + tis[fi] = 0 + end + end + if nqis > 1 then + local all = table.create(total, 0) + local n = 0 + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + n += 1 + all[n] = list[k] + end + end + local flag = bits(1) + local nqi1 = 0 + local k = 1 + while k <= total do + local run = sbRun() + local fullRun = run >= 4129 + repeat + qii[all[k]] = flag + nqi1 += flag + k += 1 + run -= 1 + until run <= 0 or k > total + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + end + if nqis == 3 and nqi1 > 0 then + k = 1 + while qii[all[k]] == 0 do + k += 1 + end + flag = bits(1) + repeat + local run = sbRun() + local fullRun = run >= 4129 + while k <= total do + local fi = all[k] + if qii[fi] ~= 0 then + if run <= 0 then + break + end + run -= 1 + qii[fi] += flag + end + k += 1 + end + if fullRun and k <= total then + flag = bits(1) + else + flag = 1 - flag + end + until k > total + end + end + + -- DCT tokens: coefficient by coefficient, plane by plane, block by block in coded order; an EOB run ends the + -- next blocks that still wait for a token at their position + local coef, last = st.coef, st.last + local act = st.act + local nact = { 0, 0, 0 } + for pli = 1, 3 do + local src, dstl = clist[pli], act[pli] + for k = 1, ncl[pli] do + dstl[k] = src[k] + end + nact[pli] = ncl[pli] + end + local roots = st.roots + local hy: number = bits(4) + local hc: number = bits(4) + local eobs = 0 + for zzi = 0, 63 do + if zzi == 1 then + hy = bits(4) + hc = bits(4) + end + local grp: number = if zzi == 0 then 0 elseif zzi < 6 then 16 elseif zzi < 15 then 32 elseif zzi < 28 then 48 else 64 + for pli = 1, 3 do + local sel: number = if pli == 1 then hy else hc + local root = roots[sel + grp + 1] + local list = act[pli] + local n = nact[pli] + local w = 0 + for k = 1, n do + local fi = list[k] + local t = tis[fi] + if t == zzi then + if eobs > 0 then + eobs -= 1 + t = 64 + else + local tok = token(root) + local ex = TOKEN_EXTRA[tok] + local eb = if ex > 0 then bits(ex) else 0 + if tok < 7 then + local run: number + if tok < 3 then + run = tok + 1 + elseif tok == 3 then + run = 4 + eb + elseif tok == 4 then + run = 8 + eb + elseif tok == 5 then + run = 16 + eb + else + run = if eb == 0 then 2 ^ 31 else eb + end + eobs = run - 1 + t = 64 + elseif tok < 9 then + t = zzi + eb + 1 + else + local v, r = 0, 0 + if tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + local p = zzi + r + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p + end + t = p + 1 + end + end + tis[fi] = t + end + if t < 64 then + w += 1 + list[w] = fi + end + end + nact[pli] = w + end + end + + -- DC prediction (raster order per plane) + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end + + -- reconstruction into a free reference buffer + local self = 1 + while self == st.gold or self == st.prev do + self += 1 + end + local dst = st.refs[self] + if not intra then + local src = st.refs[st.prev] + for pli = 1, 3 do + bcopy(dst[pli], 0, src[pli], 0, st.planeSize[pli]) + end + end + for pli = 1, 3 do + local list = clist[pli] + for k = 1, ncl[pli] do + reconFrag(st, list[k], qis, dst) + end + end + local flimit = st.lflim[qis[1] + 1] + if flimit ~= 0 then + loopFilter(st, dst, flimit) + end + borders(st, dst) + if intra then + st.gold, st.prev = self, self + st.keyframes += 1 + else + st.prev = self + end + st.shown = self + return if intra then "key" else "inter", nil +end + +-- ------------------------------------------------------------------------------------------------ output +-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose +-- top-left corner is (x0, y0) counted from the top of the plane +function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer + local src = st.refs[st.shown][pli + 1] + local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] + local out = buffer.create(w * h) + for y = 0, h - 1 do + local row = ph - 1 - (y0 + y) -- Theora rows count from the bottom + bcopy(out, y * w, src, origin + row * stride + x0, w) + end + return out +end + +-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 +-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off] +function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) + for r = 0, oh - 1 do + local r0 = math.min(2 * r, ch - 1) + local r1 = math.min(2 * r + 1, ch - 1) + local a, b = r0 * cw, r1 * cw + local o = off + r * ow + if hdec == 1 then + for c = 0, math.min(ow, cw) - 1 do + writeu8(dst, o + c, (readu8(src, a + c) + readu8(src, b + c) + 1) // 2) + end + else + for c = 0, ow - 1 do + local c0 = math.min(2 * c, cw - 1) + local c1 = math.min(2 * c + 1, cw - 1) + writeu8(dst, o + c, (readu8(src, a + c0) + readu8(src, a + c1) + readu8(src, b + c0) + readu8(src, b + c1) + 2) // 4) + end + end + end +end + +return D diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau new file mode 100644 index 0000000..2d88abd --- /dev/null +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -0,0 +1,370 @@ +--!strict +-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / +-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis +-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the +-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman +-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause: +-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking; +-- the table layout here is simpler). Never throws: bad headers return nil, message. +local Bits = require("@formats/core/Bits") + +local H = {} + +export type Info = { + versionMajor: number, + versionMinor: number, + versionSub: number, + frameWidth: number, -- coded frame size (multiples of 16) + frameHeight: number, + picWidth: number, -- the picture region (the displayed part) + picHeight: number, + picX: number, -- from the left + picY: number, -- from the bottom, as stored + fpsNum: number, + fpsDen: number, + aspectNum: number, + aspectDen: number, + colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG + bitrate: number, + quality: number, + granuleShift: number, + pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved) +} + +export type Setup = { + lflim: { number }, -- [qi + 1]: loop filter limit + dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora + huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable) + roots: { number }, -- [table + 1]: the root node offset in huff +} + +-- the zig-zag scan: natural index of the coefficient at scan position zzi +H.ZIGZAG = { + 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +} + +local function ilog(v: number): number + local n = 0 + while v > 0 do + n += 1 + v = v // 2 + end + return n +end + +-- ------------------------------------------------------------------------------------------------ identification +-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora" +function H.info(b: buffer, off: number, len: number): (Info?, string?) + if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora identification header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + local info: Info = { + versionMajor = br:read(8), + versionMinor = br:read(8), + versionSub = br:read(8), + frameWidth = br:read(16) * 16, + frameHeight = br:read(16) * 16, + picWidth = br:read(24), + picHeight = br:read(24), + picX = br:read(8), + picY = br:read(8), + fpsNum = br:read(32), + fpsDen = br:read(32), + aspectNum = br:read(24), + aspectDen = br:read(24), + colorspace = br:read(8), + bitrate = br:read(24), + quality = br:read(6), + granuleShift = br:read(5), + pixelFormat = br:read(2), + } + local reserved = br:read(3) + if br.err then + return nil, "truncated identification header" + end + if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then + return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor + end + if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then + return nil, "bad frame / picture size" + end + if info.fpsNum == 0 or info.fpsDen == 0 then + return nil, "bad frame rate" + end + if info.pixelFormat == 1 or reserved ~= 0 then + return nil, "reserved pixel format" + end + return info, nil +end + +-- ------------------------------------------------------------------------------------------------ comment +-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora" +function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, nil, "not a Theora comment header" + end + local p, e = off + 7, off + len + local function str(): string? + if p + 4 > e then + return nil + end + local n = buffer.readu32(b, p) + p += 4 + if n > e - p then + return nil + end + local s = buffer.readstring(b, p, n) + p += n + return s + end + local vendor = str() + if not vendor or p + 4 > e then + return nil, nil, "truncated comment header" + end + local count = buffer.readu32(b, p) + p += 4 + if count * 4 > e - p then + return nil, nil, "bad comment count" + end + local list: { string } = {} + for _ = 1, count do + local s = str() + if not s then + return nil, nil, "truncated comment header" + end + table.insert(list, s) + end + return vendor, list, nil +end + +-- ------------------------------------------------------------------------------------------------ Huffman trees +-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in +-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf +-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). +local MAXBITS = 8 + +local function readTree(br: any): ({ number }?, { number }?, { number }?) + -- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root) + local kid0, kid1, tok = { 0 }, { 0 }, { -1 } + -- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length + local code, len, nleaves = 0, 0, 0 + while true do + local bit = br:read(1) + if br.err then + return nil, nil, nil + end + if bit == 0 then + len += 1 + if len > 32 then + return nil, nil, nil + end + else + nleaves += 1 + if nleaves > 32 then + return nil, nil, nil + end + local t = br:read(5) + -- insert the leaf + local n = 1 + for d = 1, len do + local k = (code // 2 ^ (32 - d)) % 2 + local kids = if k == 0 then kid0 else kid1 + local nx = kids[n] + if nx == 0 then + nx = #tok + 1 + kid0[nx], kid1[nx], tok[nx] = 0, 0, -1 + kids[n] = nx + end + n = nx + end + tok[n] = t + if len <= 0 then + break + end + -- the next codeword: clear the trailing 1 bits, then set the last 0 bit + local cb = 2 ^ (32 - len) + while len > 0 and (code // cb) % 2 == 1 do + code -= cb + cb *= 2 + len -= 1 + end + if len <= 0 then + break + end + code += cb + end + end + return kid0, kid1, tok +end + +local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number + local heights: { [number]: number } = {} + local function height(n: number): number + local h = heights[n] + if h then + return h + end + h = 0 + if tok[n] < 0 then + local a = if kid0[n] ~= 0 then height(kid0[n]) else 0 + local c = if kid1[n] ~= 0 then height(kid1[n]) else 0 + h = 1 + math.max(a, c) + end + heights[n] = h + return h + end + local function node(n: number): number + local nb = math.clamp(height(n), 1, MAXBITS) + local off = #out + 1 + out[off] = nb + local size = 2 ^ nb + for i = 1, size do + out[off + i] = 0 + end + for i = 0, size - 1 do + local cur, d = n, 0 + while d < nb and tok[cur] < 0 do + local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local nx = if bit == 0 then kid0[cur] else kid1[cur] + d += 1 + cur = nx + if nx == 0 then + break + end + end + if cur == 0 then + out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0 + elseif tok[cur] >= 0 then + out[off + 1 + i] = d * 64 + tok[cur] + else + out[off + 1 + i] = -node(cur) + end + end + return off + end + return node(1) +end + +-- ------------------------------------------------------------------------------------------------ setup +local DC_MIN = { 16, 32 } +local AC_MIN = { 8, 16 } + +-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" +function H.setup(b: buffer, off: number, len: number): (Setup?, string?) + if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then + return nil, "not a Theora setup header" + end + local br = Bits.msbReader(b, off + 7, len - 7) + -- loop filter limits, AC / DC scales + local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0) + local nb = br:read(3) + for qi = 1, 64 do + lflim[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + acScale[qi] = br:read(nb) + end + nb = br:read(4) + 1 + for qi = 1, 64 do + dcScale[qi] = br:read(nb) + end + local nbms = br:read(9) + 1 + local bms: { { number } } = {} + for m = 1, nbms do + local mat = table.create(64, 0) + for ci = 1, 64 do + mat[ci] = br:read(8) + end + bms[m] = mat + end + if br.err then + return nil, "truncated setup header" + end + -- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based) + local ranges: { { sizes: { number }, idx: { number } } } = {} + local mb = ilog(nbms - 1) + for i = 0, 5 do + local qti, pli = i // 3, i % 3 + local copy = false + if i > 0 and br:read(1) == 0 then + copy = true + local from = i - 1 + if qti > 0 and br:read(1) == 1 then + from = pli -- the same plane of the intra set + end + ranges[i + 1] = ranges[from + 1] + end + if not copy then + local sizes, idx = {}, { br:read(mb) } + local qi = 0 + while qi < 63 do + local s = br:read(ilog(62 - qi)) + 1 + table.insert(sizes, s) + qi += s + table.insert(idx, br:read(mb)) + end + if qi > 63 then + return nil, "bad quant ranges" + end + for _, m in idx do + if m >= nbms then + return nil, "bad base matrix index" + end + end + ranges[i + 1] = { sizes = sizes, idx = idx } + end + end + if br.err then + return nil, "truncated setup header" + end + -- the dequantisation tables (oc_dequant_tables_init) + local dequant = buffer.create(64 * 6 * 64 * 2) + local base = table.create(64, 0) + for qti = 0, 1 do + for pli = 0, 2 do + local r = ranges[qti * 3 + pli + 1] + local qi = 0 + for qri = 0, #r.sizes do + local m0 = bms[r.idx[qri + 1] + 1] + table.move(m0, 1, 64, 1, base) + local qiStart = qi + local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1] + while true do + local o = ((qi * 3 + pli) * 2 + qti) * 64 + local q = (dcScale[qi + 1] * base[1] // 100) * 4 + buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096)) + for zzi = 1, 63 do + q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4 + buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096)) + end + qi += 1 + if qi >= qiEnd then + break + end + -- interpolate the next base matrix + local m1 = bms[r.idx[qri + 2] + 1] + local sz = r.sizes[qri + 1] + for ci = 1, 64 do + base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz) + end + end + end + end + end + -- the 80 Huffman trees + local huff: { number } = {} + local roots: { number } = {} + for t = 1, 80 do + local k0, k1, tk = readTree(br) + if not k0 or not k1 or not tk then + return nil, "bad Huffman tree " .. (t - 1) + end + roots[t] = buildTable(huff, k0, k1, tk) + end + return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil +end + +return H diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau new file mode 100644 index 0000000..dd99346 --- /dev/null +++ b/src/Formats/codecs/video/Theora/init.luau @@ -0,0 +1,270 @@ +--!strict +-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska +-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau +-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). +-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV +-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes, +-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau); +-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout). +-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too). +-- +-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate +-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err +-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region +-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down +-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position +-- +-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local VorbisComment = require("@formats/codecs/audio/VorbisComment") +local Header = require("@formats/codecs/video/Theora/Header") +local Decoder = require("@formats/codecs/video/Theora/Decoder") + +local Theora = {} + +export type Options = { + maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) +} + +local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } + +-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil +function Theora.isHeader(b: buffer, off: number?, len: number?): number? + local o = off or 0 + local n = len or (buffer.len(b) - o) + if n < 7 then + return nil + end + local t = buffer.readu8(b, o) + if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then + return t - 0x7F + end + return nil +end + +-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil) +function Theora.splitConfig(c: buffer): { buffer }? + local n = buffer.len(c) + if n < 3 or buffer.readu8(c, 0) ~= 2 then + return nil + end + local p, lens = 1, {} + for k = 1, 2 do + local size = 0 + repeat + if p >= n then + return nil + end + local b = buffer.readu8(c, p) + size += b + p += 1 + until b < 255 + lens[k] = size + end + lens[3] = n - p - lens[1] - lens[2] + if lens[3] < 0 then + return nil + end + local out = {} + for k = 1, 3 do + out[k] = buffer.create(lens[k]) + buffer.copy(out[k], 0, c, p, lens[k]) + p += lens[k] + end + return out +end + +-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) +function Theora.granuleFrame(info: Header.Info, g: number): number + if g < 0 then + return -1 + end + local shift = 2 ^ info.granuleShift + local key = g // shift + local f = key + g % shift + -- since bitstream 3.2.1 the first frame is granule 1 + local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub + if v >= 0x030201 then + f -= 1 + end + return f +end + +-- ------------------------------------------------------------------------------------------------ decoder +local Dec = {} +Dec.__index = Dec + +export type TheoraDecoder = typeof(setmetatable( + {} :: { + info: Header.Info, + vendor: string, + comments: { string }, + tags: { [string]: string }, + width: number, -- the picture region + height: number, + frameRate: number, + pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" + aspect: number, -- pixel aspect ratio (1 when unknown) + frames: number, -- packets decoded (dupes included) + _st: Decoder.State, + _any: boolean, -- a frame was decoded + }, + Dec +)) + +-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config +function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) + local list: { buffer }? = nil + if type(headers) == "buffer" then + list = Theora.splitConfig(headers) + elseif type(headers) == "table" then + list = headers + end + if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then + return nil, Err.new(Err.CORRUPT, "missing Theora headers") + end + local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) + if not ok or not info then + return nil, Err.from(if ok then ierr else tostring(info)) + end + local maxPixels = opts and opts.maxPixels or 4096 * 2304 + if info.frameWidth * info.frameHeight > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") + end + local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) + if not ok2 or not vendor or not comments then + return nil, Err.from(if ok2 then cerr else tostring(vendor)) + end + local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) + if not ok3 or not setup then + return nil, Err.from(if ok3 then serr else tostring(setup)) + end + local st = Decoder.new(info, setup) + local tags = VorbisComment.tags(comments) + return setmetatable({ + info = info, + vendor = vendor, + comments = comments, + tags = tags, + width = info.picWidth, + height = info.picHeight, + frameRate = info.fpsNum / info.fpsDen, + pixelFormat = PIXEL_FORMATS[info.pixelFormat], + aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1, + frames = 0, + _st = st, + _any = false, + }, Dec), nil +end + +-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil). +function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) + local o = off or 0 + local n = len or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "decode: range outside the buffer") + end + if n > 0 and buffer.readu8(data, o) >= 0x80 then + return nil, nil + end + local kind, msg = Decoder.decode(self._st, data, o, n) + if not kind then + return nil, Err.from(msg) + end + self.frames += 1 + if kind ~= "dup" then + self._any = true + end + return kind, nil +end + +-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data) +function Dec.reset(self: TheoraDecoder) + local st = self._st + st.shown = st.prev +end + +local function window(self: TheoraDecoder): (number, number, number, number) + local info = self.info + -- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom) + return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight +end + +-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width, +-- chroma height +function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) + local st = self._st + local x0, y0, w, h = window(self) + local hd, vd = st.hdec, st.vdec + local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd + local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd + cw = math.min(cw, st.pw[2] - cx0) + ch = math.min(ch, st.ph[2] - cy0) + return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch +end + +-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down) +function Dec.image(self: TheoraDecoder): Types.Image + local y, u, v, cw, ch = self:planes() + local w, h = self.width, self.height + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local ow, oh = (w + 1) // 2, (h + 1) // 2 + buffer.copy(px, 0, y, 0, w * h) + local st = self._st + if st.hdec == 1 and st.vdec == 1 then + for r = 0, oh - 1 do + local sr = math.min(r, ch - 1) + buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw)) + buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw)) + end + else + Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh) + Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh) + end + img.meta.yuv = { range = "limited", matrix = "bt601" } + img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace } + return img +end + +-- ------------------------------------------------------------------------------------------------ registry +-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config +-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat +function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + if not track.config then + return nil, Err.new(Err.CORRUPT, "Theora track without its headers") + end + local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels }) + if not dec then + return nil, err + end + local d = dec :: TheoraDecoder + local pending: { any } = {} + local self: any = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local kind, e = d:decode(packet.data) + if not kind then + return e + end + if d._any then + table.insert(pending, { d:image(), packet.pts, kind == "key" }) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local p = table.remove(pending, 1) + if not p then + return nil, nil, nil + end + return p[1], p[2], p[3] + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(pending) + d:reset() + end + return self, nil +end + +return Theora diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..d986129 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv +-- builds the same); one picture per packet, empty packets repeat the previous one +local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Theora = require("@formats/codecs/video/Theora") + return Theora.newVideoDecoder(track, opts) +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -307,7 +314,7 @@ local BUILTIN: { Entry } = { { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, { id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } }, { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, - { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, + { id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, } diff --git a/tests/codecs/theora.luau b/tests/codecs/theora.luau new file mode 100644 index 0000000..f6dbbf9 --- /dev/null +++ b/tests/codecs/theora.luau @@ -0,0 +1,285 @@ +-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every +-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 / +-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions +-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames +-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in; +-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry. +-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes +-- (headers, key and inter frames). +local T = require("@tests/T") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Ogg = require("@formats/containers/Ogg") +local Mkv = require("@formats/video/mkv") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("theora") + +local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" } +local FIXTURES: { [string]: any } = { + q6 = require("@tests/gen/theora_q6"), + q0 = require("@tests/gen/theora_q0"), + q10 = require("@tests/gen/theora_q10"), + motion = require("@tests/gen/theora_motion"), + odd = require("@tests/gen/theora_odd"), + static = require("@tests/gen/theora_static"), + yuv422 = require("@tests/gen/theora_yuv422"), + yuv444 = require("@tests/gen/theora_yuv444"), + odd444 = require("@tests/gen/theora_odd444"), + crop = require("@tests/gen/theora_crop"), + crop422 = require("@tests/gen/theora_crop422"), +} + +-- the Theora packets of an Ogg file: headers, data packets +local function packets(file: buffer): ({ buffer }, { buffer }) + local d = Ogg.open(file) + local serial = d:find("theora") + local hdrs, data = {}, {} + for p in d:packets(serial) do + if #hdrs < 3 then + table.insert(hdrs, Ogg.copy(p)) + else + table.insert(data, Ogg.copy(p)) + end + end + return hdrs, data +end + +-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes +local function crc(y: buffer, u: buffer, v: buffer): number + local a = Adler32.of(y, nil, nil, 0) + a = Adler32.of(u, nil, nil, a) + return Adler32.of(v, nil, nil, a) +end + +local samples: { buffer } = {} +local headerSets: { { buffer } } = {} + +-- 1. every fixture, every frame +for _, name in CASES do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + table.insert(headerSets, hdrs) + local dec, err = Theora.new(hdrs) + t:check(dec ~= nil, name .. ": headers: " .. tostring(err)) + if dec then + t:eq(dec.width, fx.width, name .. ": width") + t:eq(dec.height, fx.height, name .. ": height") + t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format") + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local bad, dupes, prev = 0, 0, nil :: number? + for k, p in data do + local kind, e = dec:decode(p) + if not kind then + bad += 1 + t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e)) + continue + end + local y, u, v = dec:planes() + local c = crc(y, u, v) + local w = want[k - 1] + if kind == "dup" then + dupes += 1 + t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1)) + if c ~= prev then + bad += 1 + end + elseif w ~= c then + bad += 1 + end + prev = c + end + t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)") + t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg") + table.insert(samples, data[1]) + if data[2] then + table.insert(samples, data[2]) + end + end +end + +-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows +do + local fx = require("@tests/gen/theora_dupe") :: any + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + local bad, prev = 0, nil :: number? + for k, p in data do + local kind = dec:decode(p) + local y, u, v = dec:planes() + local c = crc(y, u, v) + if k == 6 then + t:eq(kind, "dup", "dupe: the empty packet") + t:eq(buffer.len(p), 0, "dupe: it is empty") + t:eq(c, prev, "dupe: repeats the previous picture") + elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then + bad += 1 + end + prev = c + end + t:eq(bad, 0, "dupe: the other frames") +end + +-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4) +for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do + local fx = FIXTURES[name] + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + dec:decode(data[1]) + dec:decode(data[2]) + local img = dec:image() + local y, u, v, cw, ch = dec:planes() + local w, h = dec.width, dec.height + local ow, oh = (w + 1) // 2, (h + 1) // 2 + t:eq(img.format, "yuv420p", name .. ": image format") + t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size") + t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes") + t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma") + local bad = 0 + for r = 0, oh - 1 do + for c = 0, ow - 1 do + local want + if fx.pixfmt == "yuv420p" then + want = buffer.readu8(u, math.min(r, ch - 1) * cw + c) + elseif fx.pixfmt == "yuv422p" then + want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2 + else + local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1) + local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1) + want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4 + end + if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then + bad += 1 + end + end + end + t:eq(bad, 0, name .. ": U downsampled") + local _ = v + t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix") +end + +-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv +do + t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA") + t:check(Video.canDecode("theora"), "registry: theora decodes") + local fx = require("@tests/gen/theora_mkv") :: any + local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer)) + t:check(v ~= nil, "mkv: open: " .. tostring(err)) + if v then + t:eq(v.codec, "theora", "mkv: codec") + local n, bad, shown = 0, 0, 0 + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + while true do + local f, e = v:nextFrame() + if not f then + t:check(e == nil, "mkv: frames: " .. tostring(e)) + break + end + local img = f.image + local w = want[math.floor(f.pts * 25 + 0.5)] + if w then + shown += 1 + if Adler32.of(img.pixels, nil, nil, 0) ~= w then + bad += 1 + end + end + n += 1 + end + t:eq(bad, 0, "mkv: frames as ffmpeg's") + t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows") + end +end + +-- 5. API details and errors +do + local fx = FIXTURES.q6 + local hdrs, data = packets(Base64.decode(fx.file) :: buffer) + local dec = Theora.new(hdrs) :: Theora.TheoraDecoder + t:eq(dec.frameRate, 25, "frame rate") + t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag") + t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification") + t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup") + t:eq(Theora.isHeader(data[1]), nil, "isHeader: data") + local kind, e = dec:decode(hdrs[2]) + t:check(kind == nil and e == nil, "a header packet in the data is skipped") + t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)") + t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3") + -- the Xiph-laced config Matroska uses + local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) } + local w = Bytes.writer(64) + w:u8(2) + for _, l in lens do + local x = l + while x >= 255 do + w:u8(255) + x -= 255 + end + w:u8(x) + end + for _, h in hdrs do + w:bytes(h) + end + local cfg = w:finish() + local parts = Theora.splitConfig(cfg) + t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig") + t:check(Theora.new(cfg) ~= nil, "new(config)") + local d2, e2 = Theora.new({ hdrs[1], hdrs[2] }) + t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT") + local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] }) + t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT") + local cut = buffer.create(100) + buffer.copy(cut, 0, hdrs[3], 0, 100) + local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut }) + t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4)) + local _, e5 = Theora.new(hdrs, { maxPixels = 1000 }) + t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e6 = dec:decode(data[1], 5, buffer.len(data[1])) + t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer") + -- an inter frame before any keyframe decodes over grey + local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder + t:check(fresh:decode(data[2]) == "inter", "an inter frame first") + local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg } + local vd = Theora.newVideoDecoder(track) + t:check(vd ~= nil, "newVideoDecoder") + if vd then + vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] }) + local img, pts, key = vd:receive() + t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture") + vd:reset() + t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures") + end + local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any) + t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config") +end + +-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets) +do + local hdrs = headerSets[1] + t:fuzz("headers", function(b: buffer) + return Theora.new({ hdrs[1], hdrs[2], b }) + end, { hdrs[3] }, { mutations = 24, garbage = 50 }) + t:fuzz("identification", function(b: buffer) + return Theora.new({ b, hdrs[2], hdrs[3] }) + end, { hdrs[1] }, { mutations = 24, garbage = 20 }) + for i, h in headerSets do + local dec = Theora.new(h) :: Theora.TheoraDecoder + local s = { samples[2 * i - 1], samples[2 * i] } + dec:decode(s[1]) + t:fuzz("frames " .. CASES[i], function(b: buffer) + local kind = dec:decode(b) + dec:planes() + return kind + end, s, { mutations = 12, garbage = 20, seed = i }) + end +end + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py new file mode 100644 index 0000000..4395444 --- /dev/null +++ b/tools/fixtures/theora.py @@ -0,0 +1,195 @@ +# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's +# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions +# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a +# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode +# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per +# frame over the packed planes of the picture region, with the frame's pts. +# tests/gen/theora_.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } } +# tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original) +# tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64), +# rate, channels } +# tests/gen/theora_mkv.luau { file (base64 .mkv), frames } +# tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau +import base64, os, shutil, struct, subprocess, tempfile, zlib + +FF = ["-hide_banner", "-loglevel", "error", "-y"] + + +def b64(b): + return base64.b64encode(b).decode() + + +def src(kind, w, h, rate, t): + return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)] + + +# name: (input args, encoder args, pixel format) +CASES = { + "q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"), + "q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"), + "q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"), + "motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"), + "odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"), + "static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"), + "yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"), + "yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"), + "odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"), +} +# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd +# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched +# file (-flags unaligned: the exact crop) +PATCH = { + "crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)), + "crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)), +} + + +def crc32(b): + return zlib.crc32(b) & 0xFFFFFFFF + + +def ogg_pages(data): + """yield (header fields, segment table, body) of each Ogg page""" + i = 0 + while i + 27 <= len(data): + assert data[i:i + 4] == b"OggS" + flags, granule, serial, seq = data[i + 5], struct.unpack_from("> 24) ^ x) & 0xFF]) & 0xFFFFFFFF + return c + + +def page(flags, granule, serial, seq, packets_segs, body): + head = b"OggS" + bytes([0, flags]) + struct.pack("> 5 + out = [] + seq = 0 + frames = [] + data_packets = packets[3:] + data_packets = data_packets[:after] + [b""] + data_packets[after:] + key = 0 + for k, p in enumerate(packets[:3]): + segs = [255] * (len(p) // 255) + [len(p) % 255] + out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p)) + seq += 1 + for k, p in enumerate(data_packets): + n = k + 1 + if len(p) > 0 and not (p[0] & 0x40): + key = n + segs = [255] * (len(p) // 255) + [len(p) % 255] + g = (key << shift) | (n - key) + out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p)) + seq += 1 + return b"".join(out) + + +def patch_picture(data, w, h, x, y): + """rewrite the first page (the identification header) with another picture region""" + out = bytearray(data) + n = out[26] + o = 27 + n # the packet starts here + assert out[o:o + 7] == b"\x80theora" + out[o + 14:o + 17] = w.to_bytes(3, "big") + out[o + 17:o + 20] = h.to_bytes(3, "big") + out[o + 20] = x + out[o + 21] = y + plen = 27 + n + sum(out[27:27 + n]) + out[22:26] = b"\0\0\0\0" + struct.pack_into(" Date: Sat, 31 Oct 2026 14:17:28 -0500 Subject: [PATCH 14/54] ws-3d3-b: model/x (DirectX .x read: text, binary, MSZIP tzip / bzip, 32 / 64-bit floats; frames, meshes with normals / uvs / colours, materials and textures, skins, animation sets); assimp's test models plus bin 0064 / tzip variants match assimp's counts, bones, animations and world bounds --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/x/Build.luau | 560 +++++++++++++++++++++++++++++++++ src/Formats/model/x/Parse.luau | 306 ++++++++++++++++++ src/Formats/model/x/init.luau | 152 +++++++++ tests/model/x.luau | 312 ++++++++++++++++++ tools/fixtures/x.py | 126 ++++++++ 7 files changed, 1469 insertions(+) create mode 100644 src/Formats/model/x/Build.luau create mode 100644 src/Formats/model/x/Parse.luau create mode 100644 src/Formats/model/x/init.luau create mode 100644 tests/model/x.luau create mode 100644 tools/fixtures/x.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 8d51802..998e47b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -45,6 +45,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 4f92213..d44f2b4 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -494,6 +494,18 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "x", + category = "model", + path = "model/x", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, + load = function() + return require("@formats/model/x") + end, + }, { name = "step", category = "cad", diff --git a/src/Formats/model/x/Build.luau b/src/Formats/model/x/Build.luau new file mode 100644 index 0000000..2acb8f3 --- /dev/null +++ b/src/Formats/model/x/Build.luau @@ -0,0 +1,560 @@ +--!strict +-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is +-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding +-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). +-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep +-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Rig = require("@formats/codecs/model/Rig") +local Parse = require("@formats/model/x/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Node = Parse.Node + +-- a cursor over an object's flattened values +type Vals = { v: { any }, i: number } +local function num(c: Vals): number + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "number" then + error("expected a number in the data", 0) + end + return x +end +local function str(c: Vals): string + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "string" then + error("expected a string in the data", 0) + end + return x +end +local function count(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad count " .. n, 0) + end + return n +end + +-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +local function mirror(m: { number }): { number } + local o = table.clone(m) + for _, k in { 3, 7, 9, 10, 12, 15 } do + o[k] = -o[k] + end + return o +end + +local function matrix(c: Vals): { number } + local m = table.create(16) :: { number } + for k = 1, 16 do + m[k] = num(c) + end + return mirror(m) +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material + local c: Vals = { v = node.vals, i = 1 } + local mat = Scene.material(node.name) + local r, g, b, a = num(c), num(c), num(c), num(c) + local power = num(c) + local sr, sg, sb = num(c), num(c), num(c) + local er, eg, eb = num(c), num(c), num(c) + mat.baseColor = { r, g, b, a } + if a < 1 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1) + mat.emissive = { er, eg, eb } + local textures = {} + for _, k in node.kids do + local lt = string.lower(k.type) + if lt == "texturefilename" or lt == "normalmapfilename" then + local path = k.vals[1] + if type(path) == "string" and path ~= "" then + path = string.gsub(path, "\\\\", "\\") + local uri = string.gsub(path, "\\", "/") + local ti = texCache[uri] + if not ti then + local base = string.match(uri, "([^/]+)$") or uri + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] }) + ti = #scene.textures + texCache[uri] = ti + end + table.insert(textures, uri) + if lt == "normalmapfilename" then + mat.normalTexture = mat.normalTexture or { texture = ti } + else + mat.baseColorTexture = mat.baseColorTexture or { texture = ti } + end + end + end + end + mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } } + return mat +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Bones = { { name: string, matrix: { number } } } +type Ctx = { + scene: Types.Scene, + globalMats: { [string]: number }, + texCache: { [string]: number }, + nodeByName: { [string]: number }, + pendingSkins: { { node: number, bones: Bones } }, + maxVertices: number, + skippedFaces: number, +} + +local function accessorF32(values: { number }, comps: number): Types.Accessor + local n = #values + local b = buffer.create(n * 4) + for i = 1, n do + writef32(b, (i - 1) * 4, values[i]) + end + return Scene.accessor(b, "f32", comps, n // comps) +end + +-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) +local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) + local scene = ctx.scene + local c: Vals = { v = m.vals, i = 1 } + local nv = count(c, ctx.maxVertices) + local pos = table.create(nv * 3) :: { number } + for k = 1, nv * 3 do + pos[k] = num(c) + end + local nf = count(c, ctx.maxVertices) + local faces = table.create(nf) :: { { number } } + local corners = 0 + for f = 1, nf do + local n = count(c, ctx.maxVertices) + corners += n + if corners > ctx.maxVertices then + error("limit: more than " .. ctx.maxVertices .. " face corners", 0) + end + local face = table.create(n) :: { number } + for k = 1, n do + local idx = count(c, 2 ^ 32) + if idx >= nv then + error("face index " .. idx .. " out of range", 0) + end + face[k] = idx + end + faces[f] = face + end + -- the optional data objects + local normals: { number }? = nil + local nfaces: { { number } }? = nil + local uvSets: { { number } } = {} + local colors: { { number } } = {} + local faceMat: { number } = {} + local mats: { number } = {} + local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {} + for _, k in m.kids do + local kc: Vals = { v = k.vals, i = 1 } + if k.type == "MeshNormals" then + local nn = count(kc, ctx.maxVertices) + local nr = table.create(nn * 3) :: { number } + for q = 1, nn * 3 do + nr[q] = num(kc) + end + local nnf = count(kc, ctx.maxVertices) + local nfs = table.create(nnf) :: { { number } } + for f = 1, nnf do + local n = count(kc, ctx.maxVertices) + local face = table.create(n) :: { number } + for q = 1, n do + face[q] = count(kc, 2 ^ 32) + end + nfs[f] = face + end + normals, nfaces = nr, nfs + elseif k.type == "MeshTextureCoords" then + local n = count(kc, ctx.maxVertices) + local uv = table.create(n * 2) :: { number } + for q = 1, n * 2 do + uv[q] = num(kc) + end + if n == nv then + table.insert(uvSets, uv) + end + elseif k.type == "MeshVertexColors" then + local n = count(kc, ctx.maxVertices) + local col = table.create(nv * 4, 1) :: { number } + for _ = 1, n do + local idx = count(kc, 2 ^ 32) + local r, g, b, a = num(kc), num(kc), num(kc), num(kc) + if idx < nv then + col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a + end + end + table.insert(colors, col) + elseif k.type == "MeshMaterialList" then + count(kc, 2 ^ 20) -- material count (the objects below are authoritative) + local ni = count(kc, ctx.maxVertices) + for q = 1, ni do + faceMat[q] = count(kc, 2 ^ 20) + end + for _, mk in k.kids do + if mk.type == "@ref" then + table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0) + elseif mk.type == "Material" then + table.insert(scene.materials, material(scene, mk, ctx.texCache)) + table.insert(mats, #scene.materials) + end + end + elseif k.type == "SkinWeights" then + local name = str(kc) + local n = count(kc, ctx.maxVertices) + local verts = table.create(n) :: { number } + for q = 1, n do + verts[q] = count(kc, 2 ^ 32) + end + local weights = table.create(n) :: { number } + for q = 1, n do + weights[q] = num(kc) + end + table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) + end + end + -- material per face (a single index applies to every face) + local function matOf(f: number): number + local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] + return if mi then mi + 1 else 1 + end + -- unique vertices per (position, normal index) + local key: { [number]: number } = {} + local srcPos: { number } = {} + local srcNrm: { number } = {} + local groups: { [number]: { number } } = {} + local order: { number } = {} + local faceSizes: { [number]: { number } } = {} + local nNormals = if normals then #normals // 3 else 0 + for f, face in faces do + local n = #face + if n < 3 then + ctx.skippedFaces += 1 + else + local nface = nfaces and nfaces[f] + local vs = table.create(n) :: { number } + for k = 1, n do + local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept + local p = face[src] + local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 + local kk = p * (nNormals + 1) + q + 1 + local v = key[kk] + if not v then + table.insert(srcPos, p) + table.insert(srcNrm, q) + v = #srcPos - 1 + key[kk] = v + end + vs[k] = v + end + local mi = matOf(f) + local g = groups[mi] + if not g then + g = {} + groups[mi] = g + faceSizes[mi] = {} + table.insert(order, mi) + end + if triangulate then + for k = 2, n - 1 do + table.insert(g, vs[1]) + table.insert(g, vs[k]) + table.insert(g, vs[k + 1]) + end + else + table.move(vs, 1, n, #g + 1, g) + table.insert(faceSizes[mi], n) + end + end + end + if #order == 0 then + return nil, nil + end + table.sort(order) + -- shared vertex attributes (one vertex buffer for every primitive of the mesh) + local nout = #srcPos + local P = table.create(nout * 3) :: { number } + for v = 1, nout do + local p = srcPos[v] * 3 + P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3] + end + local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) } + if normals then + local N = table.create(nout * 3, 0) :: { number } + for v = 1, nout do + local q = srcNrm[v] + if q >= 0 then + N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3] + end + end + attributes.NORMAL = accessorF32(N, 3) + end + for s, uv in uvSets do + local U = table.create(nout * 2) :: { number } + for v = 1, nout do + local p = srcPos[v] * 2 + U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2] + end + attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2) + end + for s, col in colors do + local C = table.create(nout * 4) :: { number } + for v = 1, nout do + local p = srcPos[v] * 4 + C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4] + end + attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4) + end + if #bones > 0 then + local lists = table.create(nout) :: { { number } } + local byPos: { [number]: { number } } = {} + for j, bone in bones do + for q, vi in bone.verts do + local l = byPos[vi] + if not l then + l = {} + byPos[vi] = l + end + table.insert(l, j - 1) + table.insert(l, bone.weights[q] or 0) + end + end + for v = 1, nout do + lists[v] = byPos[srcPos[v]] or {} + end + attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists) + end + local skinBones: Bones? = nil + if #bones > 0 then + local list: Bones = {} + for _, bone in bones do + table.insert(list, { name = bone.name, matrix = bone.matrix }) + end + skinBones = list + end + local prims: { Types.Primitive } = {} + for _, mi in order do + local idx = groups[mi] + local ib = buffer.create(#idx * 4) + for k, x in idx do + writeu32(ib, (k - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" } + local mat = mats[mi] + prim.material = if mat and mat > 0 then mat else nil + if not triangulate then + prim.mode = "polygons" + local fs = faceSizes[mi] + local fb = buffer.create(#fs * 4) + for k, x in fs do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #fs) + end + table.insert(prims, prim) + end + table.insert(scene.meshes, { name = m.name, primitives = prims }) + return #scene.meshes, skinBones +end + +-- ------------------------------------------------------------------------------------------------ frames +local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number) + if depth > 200 then + error("frames nested too deep", 0) + end + local scene = ctx.scene + local node: Types.Node = { name = f.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + if f.name and ctx.nodeByName[f.name] == nil then + ctx.nodeByName[f.name] = ni + end + if parent then + table.insert(scene.nodes[parent].children, ni) + else + table.insert(scene.roots, ni) + end + local first = true + for _, k in f.kids do + if k.type == "FrameTransformMatrix" then + local m = matrix({ v = k.vals, i = 1 }) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + else + node.matrix = m + end + elseif k.type == "Mesh" then + -- the first mesh on the frame's node, more as child nodes + local mi, bones = mesh(ctx, k, triangulate) + if mi then + local holder = ni + if first then + node.mesh = mi + first = false + else + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + holder = #scene.nodes + table.insert(node.children, holder) + end + if bones then + table.insert(ctx.pendingSkins, { node = holder, bones = bones }) + end + end + elseif k.type == "Frame" then + frame(ctx, k, ni, triangulate, depth + 1) + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel + return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" } +end + +local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation? + local channels: { Types.Channel } = {} + for _, a in set.kids do + if a.type == "Animation" then + local target: string? = nil + for _, k in a.kids do + if k.type == "@ref" then + target = k.name + end + end + local node = target and ctx.nodeByName[target] + if node then + for _, k in a.kids do + if k.type == "AnimationKey" then + local c: Vals = { v = k.vals, i = 1 } + local kind = num(c) + local nk = count(c, ctx.maxVertices) + local times = table.create(nk) :: { number } + local T, R, S = {}, {}, {} + for q = 1, nk do + times[q] = num(c) / tps + local nvals = count(c, 16) + if kind == 0 and nvals == 4 then + local w, x, y, z = num(c), num(c), num(c), num(c) + -- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y + table.move({ x, y, -z, w }, 1, 4, #R + 1, R) + elseif (kind == 1 or kind == 2) and nvals == 3 then + local x, y, z = num(c), num(c), num(c) + if kind == 1 then + table.move({ x, y, z }, 1, 3, #S + 1, S) + else + table.move({ x, y, -z }, 1, 3, #T + 1, T) + end + elseif (kind == 3 or kind == 4) and nvals == 16 then + local t, r, s = Mat4.decompose(matrix(c)) + table.move(t, 1, 3, #T + 1, T) + table.move(r, 1, 4, #R + 1, R) + table.move(s, 1, 3, #S + 1, S) + else + error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0) + end + end + if #T == nk * 3 and nk > 0 then + table.insert(channels, channel(times, T, 3, node, "translation")) + end + if #R == nk * 4 and nk > 0 then + table.insert(channels, channel(times, R, 4, node, "rotation")) + end + if #S == nk * 3 and nk > 0 then + table.insert(channels, channel(times, S, 3, node, "scale")) + end + end + end + end + end + end + if #channels == 0 then + return nil + end + return { name = set.name, channels = channels } +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 } + local tps = 4800 + for _, k in root.kids do + if k.type == "Material" then + table.insert(scene.materials, material(scene, k, ctx.texCache)) + if k.name then + ctx.globalMats[k.name] = #scene.materials + end + elseif k.type == "AnimTicksPerSecond" then + local v = k.vals[1] + if type(v) == "number" and v > 0 then + tps = v + end + end + end + for _, k in root.kids do + if k.type == "Frame" then + frame(ctx, k, nil, triangulate, 0) + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + table.insert(scene.roots, #scene.nodes) + if bones then + table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones }) + end + end + end + -- skins: bone names -> frames + for _, ps in ctx.pendingSkins do + local joints: { number } = {} + local ibm = buffer.create(#ps.bones * 64) + for j, bone in ps.bones do + local ni = ctx.nodeByName[bone.name] + if not ni then + -- a bone without a frame: an extra root node keeps the joint numbering + table.insert(scene.nodes, { name = bone.name, children = {} }) + ni = #scene.nodes + table.insert(scene.roots, ni) + ctx.nodeByName[bone.name] = ni + end + joints[j] = ni + for k = 1, 16 do + writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, #ps.bones) + acc.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc }) + scene.nodes[ps.node].skin = #scene.skins + end + for _, k in root.kids do + if k.type == "AnimationSet" then + local anim = animationSet(ctx, k, tps) + if anim then + table.insert(scene.animations, anim) + end + end + end + scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces } + return scene, nil +end + +return Build diff --git a/src/Formats/model/x/Parse.luau b/src/Formats/model/x/Parse.luau new file mode 100644 index 0000000..e770dd9 --- /dev/null +++ b/src/Formats/model/x/Parse.luau @@ -0,0 +1,306 @@ +--!strict +-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the +-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and +-- binary tokens), checked against what assimp's XFileParser accepts (no code taken). +-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and +-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), +-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. +-- Text: ; and , separators, // and # comments, quoted strings, s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). +-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and +-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Parse = {} + +export type Node = { type: string, name: string?, vals: { any }, kids: { Node } } + +local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring + +-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), +-- "punct", "eof"; err holds a message after a bad token +type Lexer = { next: () -> (string, any), err: string? } + +local KEYWORDS: { [number]: string } = { + [0x1F] = "template", + [0x28] = "WORD", + [0x29] = "DWORD", + [0x2A] = "FLOAT", + [0x2B] = "DOUBLE", + [0x2C] = "CHAR", + [0x2D] = "UCHAR", + [0x2E] = "SWORD", + [0x2F] = "SDWORD", + [0x30] = "void", + [0x31] = "string", + [0x32] = "unicode", + [0x33] = "cstring", + [0x34] = "array", +} + +-- ------------------------------------------------------------------------------------------------ text +local function textLexer(s: string): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = 1 + local n = #s + lex.next = function(): (string, any) + while true do + local _, e = string.find(s, "^[%s,;]+", p) + if e then + p = e + 1 + end + if p > n then + return "eof", nil + end + local c = string.byte(s, p) + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + local nl = string.find(s, "[\r\n]", p) + p = if nl then nl + 1 else n + 1 + else + break + end + end + local c = string.byte(s, p) + if c == 123 then + p += 1 + return "{", nil + elseif c == 125 then + p += 1 + return "}", nil + elseif c == 34 then + local q = string.find(s, '"', p + 1, true) + if not q then + lex.err = "unterminated string" + p = n + 1 + return "eof", nil + end + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "str", v + elseif c == 60 then + local q = string.find(s, ">", p + 1, true) or n + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "guid", v + end + local _, e = string.find(s, '^[^%s,;{}"]+', p) + local tok = string.sub(s, p, e :: number) + p = (e :: number) + 1 + if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + return "num", tonumber(tok) or 0 + end + return "id", tok + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ binary +local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = from + local function fail(msg: string): (string, any) + lex.err = msg + p = limit + return "eof", nil + end + lex.next = function(): (string, any) + if p + 2 > limit then + return "eof", nil + end + local tok = readu16(b, p) + p += 2 + if tok == 0x0A then + return "{", nil + elseif tok == 0x0B then + return "}", nil + elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token) + if p + 4 > limit then + return fail("truncated name") + end + local len = readu32(b, p) + p += 4 + if len > limit - p then + return fail("truncated name") + end + local v = readstring(b, p, len) + p += len + if tok == 2 then + p = math.min(p + 2, limit) + return "str", v + end + return "id", v + elseif tok == 3 then + if p + 4 > limit then + return fail("truncated integer") + end + local v = readu32(b, p) + p += 4 + return "num", v + elseif tok == 5 then + if p + 16 > limit then + return fail("truncated guid") + end + p += 16 + return "guid", "" + elseif tok == 6 or tok == 7 then + if p + 4 > limit then + return fail("truncated list") + end + local count = readu32(b, p) + p += 4 + local size = if tok == 6 then 4 else floatSize + if count > (limit - p) // size then + return fail("truncated list") + end + local out = table.create(count) :: { number } + if tok == 6 then + for i = 1, count do + out[i] = readu32(b, p) + p += 4 + end + elseif size == 8 then + for i = 1, count do + out[i] = readf64(b, p) + p += 8 + end + else + for i = 1, count do + out[i] = readf32(b, p) + p += 4 + end + end + return "list", out + elseif tok >= 0x0C and tok <= 0x14 then + return "punct", nil + elseif KEYWORDS[tok] then + return "id", KEYWORDS[tok] + end + return fail(string.format("unknown binary token 0x%x", tok)) + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ tree +local function tree(lex: Lexer, maxValues: number): (Node?, string?) + local queue: { { any } } = {} + local function take(): (string, any) + local q = table.remove(queue, 1) + if q then + return q[1], q[2] + end + return lex.next() + end + local function peek(k: number): string + while #queue < k do + local kind, v = lex.next() + table.insert(queue, { kind, v }) + if kind == "eof" then + break + end + end + local q = queue[k] + return if q then q[1] else "eof" + end + local budget = maxValues + -- skips a template / unknown block whose "{" was just read + local function skipBlock(): string? + local depth = 1 + while depth > 0 do + local kind = take() + if kind == "eof" then + return "unexpected end of file in a template" + elseif kind == "{" then + depth += 1 + elseif kind == "}" then + depth -= 1 + end + end + return nil + end + local body: (Node, number) -> string? + -- an object whose type token was read: [name] { ... } + local function object(parent: Node, typ: string, depth: number): string? + local name: string? = nil + local kind, v = take() + if kind ~= "{" then + name = if v ~= nil then tostring(v) else nil + kind = take() + if kind ~= "{" then + return "expected { after " .. typ + end + end + if typ == "template" then + return skipBlock() + end + local node: Node = { type = typ, name = name, vals = {}, kids = {} } + table.insert(parent.kids, node) + return body(node, depth + 1) + end + body = function(node: Node, depth: number): string? + if depth > 200 then + return "objects nested too deep" + end + local vals = node.vals + while true do + local kind, v = take() + if kind == "}" then + return nil + elseif kind == "eof" then + return if depth == 0 then nil else "unexpected end of file in " .. node.type + elseif kind == "num" or kind == "str" then + budget -= 1 + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + vals[#vals + 1] = v + elseif kind == "list" then + budget -= #v + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + table.move(v, 1, #v, #vals + 1, vals) + elseif kind == "{" then + -- a reference: { name [guid] } + local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} } + while true do + local k2, v2 = take() + if k2 == "}" then + break + elseif k2 == "eof" then + return "unexpected end of file in a reference" + elseif (k2 == "id" or k2 == "num") and ref.name == nil then + ref.name = tostring(v2) + end + end + table.insert(node.kids, ref) + elseif kind == "id" then + local k1 = peek(1) + if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then + local err = object(node, v, depth) + if err then + return err + end + end + -- a lone identifier (an enum value): ignored + end + -- guid / punct: ignored + if lex.err then + return lex.err + end + end + end + local root: Node = { type = "@root", name = nil, vals = {}, kids = {} } + local err = body(root, 0) + if err then + return nil, err + end + if lex.err then + return nil, lex.err + end + return root, nil +end + +-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message +function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) + local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) + return tree(lex, maxValues) +end + +return Parse diff --git a/src/Formats/model/x/init.luau b/src/Formats/model/x/init.luau new file mode 100644 index 0000000..183b5e7 --- /dev/null +++ b/src/Formats/model/x/init.luau @@ -0,0 +1,152 @@ +--!strict +-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", +-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format +-- specification and the standard templates, checked against assimp's X importer and test models. +-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per +-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal +-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global +-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, +-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), +-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four +-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, +-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. +-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. +-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in +-- meta.source.skippedFaces). +-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key +-- interpolation options (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Parse = require("@formats/model/x/Parse") +local Build = require("@formats/model/x/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local X = { + name = "x", + category = "model", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25) + maxValues: number?, -- refuse files with more numbers than this (default 2^27) + maxBytes: number?, -- refuse compressed files inflating to more (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" } +local WINDOW = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function X.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "xof " then + return 0 + end + return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MSZIP: a u32 total size (with the header), then blocks (u16 uncompressed size, u16 compressed size, "CK", deflate data); each block +-- may refer back into the previous block's output. That history is handed to the inflater as a stored block in +-- front of the compressed one (both start on a byte boundary), and cut off the output again. +local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) + end + local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p) + end + p += 4 + local out = buffer.create(total) + local o = 0 + while p + 6 <= limit and o < total do + local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2) + if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then + return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p) + end + local data, dlen = p + 6, math.min(csize - 2, limit - p - 6) + local hist = math.min(o, WINDOW) + local src = buffer.create(5 + hist + dlen) + buffer.writeu8(src, 0, 0) -- BFINAL 0, stored + buffer.writeu16(src, 1, hist) + buffer.writeu16(src, 3, bit32.bxor(hist, 0xFFFF)) + buffer.copy(src, 5, out, o - hist, hist) + buffer.copy(src, 5 + hist, b, data, dlen) + local inflated, err = Deflate.inflate(src) + if not inflated then + return nil, Err.new(err.code, "MSZIP block: " .. err.message, p) + end + local got = buffer.len(inflated) - hist + if got ~= usize or o + got > total then + return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p) + end + buffer.copy(out, o, inflated, hist, got) + o += got + p = data + csize - 2 + end + if o < total then + return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p) + end + return out, nil +end + +function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 16 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", base) + end + if buffer.readstring(b, base, 4) ~= "xof " then + return nil, Err.new(Err.CORRUPT, "no xof header", base) + end + local enc = buffer.readstring(b, base + 8, 4) + local kind = ENCODINGS[enc] + if not kind then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8) + end + local bits = buffer.readstring(b, base + 12, 4) + local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0 + if floatSize == 0 then + return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12) + end + local data: buffer, from: number, to: number = b, base + 16, limit + if enc == "tzip" or enc == "bzip" then + local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30) + if not inflated then + return nil, err + end + data, from, to = inflated, 0, buffer.len(inflated) + end + local maxValues: number = opts and opts.maxValues or 2 ^ 27 + local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root)) + end + if not root then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, root, opts) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + local src = scene.meta.source :: { [string]: any } + src.version = buffer.readstring(b, base + 4, 4) + src.encoding = kind + src.compressed = enc == "tzip" or enc == "bzip" + src.floatSize = floatSize * 8 + return scene, nil +end + +return X diff --git a/tests/model/x.luau b/tests/model/x.luau new file mode 100644 index 0000000..119cbdc --- /dev/null +++ b/tests/model/x.luau @@ -0,0 +1,312 @@ +-- model/x tests: assimp's DirectX test models (text, binary 32-bit, MSZIP-compressed binary) and variants made by +-- tools/fixtures/x.py (binary with 64-bit floats, MSZIP-compressed text), against assimp (meshes per material, faces, +-- corners, materials, animations, bones, world bounds); frames, materials and textures, vertex colours, skins +-- (influences, inverse bind matrices against the bind pose), animation keys (the rotation convention against the +-- bind pose); an inline text file; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x.py. +local T = require("@tests/T") +local X = require("@formats/model/x") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/x_cases") + +local t = T.suite("x") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return X.decode(Bytes.reader(b), opts) +end + +t:eq(X.name, "x", "name") +t:eq(X.category, "model", "category") +t:check(X.caps.decode and not X.caps.encode, "caps") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- assimp's counts: meshes (one per material), faces, corners, bones (joints with weight in each mesh) +local function counts(scene: any): (number, number, number, number) + local meshes, faces, corners, bones = 0, 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + meshes += 1 + corners += p.indices.count + faces += if p.mode == "polygons" then p.faces.count else p.indices.count // 3 + local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0 + if J and W then + local used = {} + local gj, gw = assert(Types.Scene.reader(J)), assert(Types.Scene.reader(W)) + for k = 0, p.indices.count - 1 do + local v = buffer.readu32(p.indices.data, k * 4) + for c = 0, 3 do + if gw(v, c) > 0 then + used[gj(v, c)] = true + end + end + end + for _ in used do + bones += 1 + end + end + end + end + return meshes, faces, corners, bones +end + +local function bounds(scene: any): ({ number }?, { number }?) + local merged = MeshOps.merge(scene) + if not merged then + return nil, nil + end + return MeshOps.bounds(merged) +end + +local function boundsMatch(lo: { number }?, hi: { number }?, a: any, eps: number): boolean + if not lo or not hi then + return false + end + for k = 1, 3 do + if not near(lo[k], a.min[k], eps) or not near(hi[k], a.max[k], eps) then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ assimp +local scenes, byName = {}, {} +local checked = 0 +for i, c in Cases do + byName[c.name] = c + local a = c.assimp + local scene, err = decode(c.data, { triangulate = false }) + if a.failed then + t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[c.name] = scene + local meshes, faces, corners, bones = counts(scene) + t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces + scene.meta.source.skippedFaces, a.faces, c.name .. ": faces (assimp)") + if scene.meta.source.skippedFaces == 0 then + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + end + t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp, its default when none)") + t:eq(#scene.animations, a.animations or 0, c.name .. ": animations (assimp)") + t:eq(bones, a.bones or 0, c.name .. ": bones (assimp)") + if a.min then + local lo, hi = bounds(scene) + t:check(boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-")) + end + checked += 1 + end +end +t:note("%d files checked against assimp", checked) + +-- variants decode like their originals +for _, c in Cases do + if c.of then + local a, b = scenes[c.name], scenes[c.of] + if a and b then + local m1, f1, c1 = counts(a) + local m2, f2, c2 = counts(b) + t:check(m1 == m2 and f1 == f2 and c1 == c2, c.name .. ": same counts as " .. c.of) + local la, ha = bounds(a) + local lb, hb = bounds(b) + t:check(la and lb and boundsMatch(la, ha, { min = lb, max = hb }, 1e-5), c.name .. ": same bounds as " .. c.of) + t:eq(#a.animations, #b.animations, c.name .. ": same animations") + end + end +end + +-- ------------------------------------------------------------------------------------------------ details +do + local s = scenes["models/kwxport_test_cubewithvcolors.x"] + local p = s.meshes[1].primitives[1] + t:check(p.attributes.COLOR_0 and p.attributes.COLOR_0.components == 4, "vertex colours -> COLOR_0") + t:eq(s.meta.source.encoding, "text", "text encoding") + local b = scenes["models/test_cube_binary.x"] + t:eq(b.meta.source.encoding, "binary", "binary encoding") + local z = scenes["models/test_cube_compressed.x"] + t:check(z.meta.source.compressed, "bzip") + local v = scenes["variant/test_cube_text.bin64.x"] + t:eq(v.meta.source.floatSize, 64, "64-bit floats") +end +do + -- textures: uri names, TEXCOORD_0 + local s = scenes["models/test.x"] + local any = false + for _, m in s.materials do + if m.baseColorTexture then + local tex = s.textures[m.baseColorTexture.texture] + any = any or (type(tex.uri) == "string" and #tex.uri > 0) + end + end + t:check(any, "test.x: a texture file name") + t:check(s.meshes[1].primitives[1].attributes.TEXCOORD_0, "test.x: TEXCOORD_0") +end +do + -- skins: the inverse bind matrix of each joint times the joint's world bind matrix is about the same for all + -- joints (the mesh node's world matrix): checks the matrix layout and the handedness conversion together + local checkedSkins, consistent = 0, 0 + for name, s in scenes do + for _, node in s.nodes do + if node.skin then + local skin = s.skins[node.skin] + local world = {} + local function worldOf(i: number): { number } + if world[i] then + return world[i] + end + local m = Types.Scene.nodeMatrix(s.nodes[i]) + for pi, pn in s.nodes do + if table.find(pn.children, i) then + m = Types.Scene.mul(worldOf(pi), m) + break + end + end + world[i] = m + return m + end + local get = assert(Types.Scene.reader(skin.inverseBindMatrices)) + local ref: { number }? = nil + local ok, total = 0, 0 + for j, joint in skin.joints do + local inv = {} + for k = 1, 16 do + inv[k] = get(j - 1, k - 1) + end + local m = Types.Scene.mul(worldOf(joint), inv) + total += 1 + if not ref then + ref = m + ok += 1 + else + local same = true + for k = 1, 16 do + same = same and math.abs(m[k] - (ref :: any)[k]) < 1e-2 * math.max(1, math.abs(m[k])) + end + ok += if same then 1 else 0 + end + end + t:note("%s: skin %d: bind pose consistent for %d / %d joints", name, node.skin, ok, total) + checkedSkins += 1 + consistent += if ok >= total * 0.9 then 1 else 0 + end + end + end + -- (anim_test.x's frames are not in the bind pose) + t:check(checkedSkins >= 4 and consistent >= checkedSkins * 0.7, string.format("skins consistent with the frames (%d / %d)", consistent, checkedSkins)) +end +do + -- the rotation key convention: an animation's first rotation key mostly equals the bone's bind rotation + local same, total = 0, 0 + for _, s in scenes do + for _, anim in s.animations do + for _, ch in anim.channels do + if ch.path == "rotation" then + local node = s.nodes[ch.node] + local r = node.rotation + if r then + local get = assert(Types.Scene.reader(ch.output)) + local dot = 0 + for k = 0, 3 do + dot += get(0, k) * r[k + 1] + end + total += 1 + same += if math.abs(dot) > 0.999 then 1 else 0 + end + end + end + end + end + t:check(total > 0 and same >= total * 0.5, string.format("first rotation keys match the bind pose (%d / %d)", same, total)) +end + +-- ------------------------------------------------------------------------------------------------ inline file +local CUBE = [[xof 0303txt 0032 +// a quad and a triangle, two materials, one animated frame +Material Red { 1.0; 0.0; 0.0; 1.0;; 10.0; 0.5; 0.5; 0.5;; 0.0; 0.0; 0.0;; TextureFilename { "tex\\red.png"; } } +AnimTicksPerSecond { 100; } +Frame Root { + FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 1,2,3,1;; } + Mesh Shape { + 5; + 0;0;0;, 1;0;0;, 1;1;0;, 0;1;0;, 2;0;0;; + 2; + 4;0,1,2,3;, + 3;1,4,2;; + MeshMaterialList { 2; 2; 0, 1;; { Red } Material Blue { 0;0;1;0.5;; 1; 0;0;0;; 0;0;0;; } } + MeshNormals { 1; 0;0;-1;; 2; 4;0,0,0,0;, 3;0,0,0;; } + MeshTextureCoords { 5; 0;0;, 1;0;, 1;1;, 0;1;, 0.5;0.5;; } + } +} +AnimationSet Move { + Animation { { Root } AnimationKey { 2; 2; 0; 3; 1;2;3;;, 100; 3; 1;2;5;;; } } +} +]] +do + local s, err = decode(CUBE, { triangulate = false }) + t:check(s, "inline: " .. tostring(err)) + t:eq(#s.nodes, 1, "inline: one frame") + local root = s.nodes[1] + t:check(root.translation and root.translation[1] == 1 and root.translation[3] == -3, "inline: translation, z negated") + t:eq(#s.materials, 2, "inline: global + inline material") + t:eq(s.materials[1].name, "Red", "inline: material name") + t:eq(s.textures[1].uri, "tex/red.png", "inline: texture uri (backslash -> slash)") + t:eq(s.materials[2].alphaMode, "blend", "inline: alpha < 1 -> blend") + local prims = s.meshes[1].primitives + t:eq(#prims, 2, "inline: one primitive per material") + t:eq(prims[1].material, 1, "inline: first face -> Red (referenced)") + t:eq(prims[2].material, 2, "inline: second face -> Blue") + t:eq(prims[1].faces.count, 1, "inline: the quad kept") + local N = assert(Types.Scene.reader(prims[1].attributes.NORMAL)) + t:eq(N(0, 2), 1, "inline: normal z negated") + local anim = s.animations[1] + t:eq(anim.name, "Move", "inline: animation name") + local ch = anim.channels[1] + t:eq(ch.path, "translation", "inline: position key") + local ti, to = assert(Types.Scene.reader(ch.input)), assert(Types.Scene.reader(ch.output)) + t:eq(ti(1, 0), 1, "inline: ticks -> seconds") + t:eq(to(1, 2), -5, "inline: key z negated") + local tri = decode(CUBE) + t:eq(tri.meshes[1].primitives[1].indices.count, 6, "inline: quad fan-triangulated") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("xof 0303txt 00") + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local _, e2 = decode("xof 0303zzz 0032") + t:check(e2 and e2.code == Err.UNSUPPORTED, "encoding: " .. tostring(e2)) + local _, e3 = decode("xof 0303txt 0016 Frame {}") + t:check(e3 and e3.code == Err.CORRUPT, "float size: " .. tostring(e3)) + local _, e4 = decode("xof 0303txt 0032 Frame A { Mesh { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3; 0,1,7;; } }") + t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) + local _, e5 = decode("xof 0303txt 0032 Frame A { ") + t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5)) + local _, e6 = decode(CUBE, { maxValues = 10 }) + t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6)) + t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { CUBE } + for _, c in Cases do + if #c.data < 12000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = X.decode(Bytes.reader(b), { triangulate = false }) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/x.py b/tools/fixtures/x.py new file mode 100644 index 0000000..d10bb7e --- /dev/null +++ b/tools/fixtures/x.py @@ -0,0 +1,126 @@ +# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary; +# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the +# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with +# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners, +# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too. +# tests/gen/x_cases.luau { name, data, assimp = { ... } } +import importlib.util, os, re, struct, zlib + +INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+') + + +def to_binary64(text): + """a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)""" + body = text[16:] + out = bytearray(b"xof 0303bin 0064") + toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))] + i, nums = 0, [] + + def flush(): + while nums: + isf = nums[0][0] + run = [] + while nums and nums[0][0] == isf: + run.append(nums.pop(0)[1]) + if isf: + out.extend(struct.pack(" "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary""" + body = text[16:] + out = bytearray(b"xof 0303tzip0032") + struct.pack(" Date: Sat, 31 Oct 2026 14:19:08 -0500 Subject: [PATCH 15/54] ws-3d3: model/3ds (Autodesk 3D Studio) read + write Meshes (smoothing-group normals, uvs, mesh matrix, per-face materials), Phong materials with texture maps (uri), cameras, lights, the keyframer (hierarchy, pivots, instances, dummies, position / rotation / scale / camera tracks -> one animation). Writer: objects, materials, cameras, lights, keyframer. Tested against assimp (test models, its 3DS exporter, and reading our files). --- docs/FORMATS.md | 1 + docs/guide/scene.md | 35 +- src/Formats/Registry.luau | 12 + src/Formats/model/3ds/Build.luau | 663 ++++++++++++++++++++++++ src/Formats/model/3ds/Read.luau | 506 ++++++++++++++++++ src/Formats/model/3ds/Write.luau | 859 +++++++++++++++++++++++++++++++ src/Formats/model/3ds/init.luau | 100 ++++ tests/model/3ds.luau | 602 ++++++++++++++++++++++ tools/fixtures/3ds.py | 101 ++++ tools/fixtures/_3ds_encode.luau | 44 ++ 10 files changed, 2921 insertions(+), 2 deletions(-) create mode 100644 src/Formats/model/3ds/Build.luau create mode 100644 src/Formats/model/3ds/Read.luau create mode 100644 src/Formats/model/3ds/Write.luau create mode 100644 src/Formats/model/3ds/init.luau create mode 100644 tests/model/3ds.luau create mode 100644 tools/fixtures/3ds.py create mode 100644 tools/fixtures/_3ds_encode.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..ce760a5 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,6 +34,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | +| model | 3ds | .3ds | yes | yes | materials: true, textures: true, animation: true, cameras: true, lights: true, instancing: true | `tests/model/3ds.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..211ff7b 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -290,7 +290,7 @@ the binary container. | glTF | `external = true` writes `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | | OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | | STL | | `ascii = true` (default binary), `normals = "attribute"` | -| PLY, OFF, FBX, DAE, 3MF, USDA, VOX | see [FORMATS.md](../FORMATS.md) and the format's options | | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS | see [FORMATS.md](../FORMATS.md) and the format's options | | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -378,6 +378,36 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves assert(F.load(vox).voxels[1].size[1] == 4) ``` +## 3D Studio (3DS) + +`.3ds` files load with their keyframer: the node hierarchy, pivots, instances of one object, the first key of each +track as the node's TRS and, when tracks have several keys, one animation (frames / `opts.fps`, default 30). +Normals come from the smoothing groups (`normals = false` keeps the file's shared vertices); the groups stay in +`prim.extras["3ds"].smoothing` and are written back. Materials are Phong (the raw values in `extras["3ds"]`), texture +maps become textures with a `uri` only (`F.model.loadTextures` reads them). Cameras get `yfov` from the lens at a +4:3 aspect and look at their target; omni lights are `point`, spotlights `spot`. The writer puts one object per mesh +(split past 65535 vertices), its first instance's world matrix as the mesh matrix, and the scene's first animation +into the keyframer. + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles", material = 1 }, "tri") +scene.materials[1] = S.material("red") +scene.materials[1].baseColor = { 1, 0, 0, 1 } +scene.nodes[1].translation = { 0, 0, 2 } +local bytes = assert(F.save(scene, nil, { format = "3ds" })) +local back = assert(F.load(bytes)) -- detected by its 0x4D4D main chunk +assert(back.meta.source.format == "3ds" and back.meta.up == "z") +local prim = back.meshes[1].primitives[1] +assert(prim.attributes.NORMAL and prim.extras["3ds"].smoothing[1] == 1) +assert(back.materials[prim.material].baseColor[1] == 1) +assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the node transform +``` + ## Formats | Format | Read | Write | Notes | @@ -392,6 +422,7 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| 3DS | yes | yes | keyframer hierarchy and animation, Phong materials, texture names, cameras, lights; Z up | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..8fbf340 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/y4m") end, }, + { + name = "3ds", + category = "model", + path = "model/3ds", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, + load = function() + return require("@formats/model/3ds") + end, + }, { name = "3mf", category = "model", diff --git a/src/Formats/model/3ds/Build.luau b/src/Formats/model/3ds/Build.luau new file mode 100644 index 0000000..a652cf2 --- /dev/null +++ b/src/Formats/model/3ds/Build.luau @@ -0,0 +1,663 @@ +--!strict +-- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world +-- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) * +-- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix +-- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key +-- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's +-- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position +-- are averaged; group 0 is flat). Times are frame / fps. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Read = require("@formats/model/3ds/Read") + +local Build = {} + +local S = Types.Scene +local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32 +local band = bit32.band +local sqrt, abs = math.sqrt, math.abs + +export type Options = { normals: boolean?, flipV: boolean?, fps: number? } + +-- ------------------------------------------------------------------------------------------------ math +-- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4 +local function meshMatrix(m: { number }?): { number } + if not m then + return Mat4.identity() + end + return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 } +end +Build.meshMatrix = meshMatrix + +local function det3(m: { number }): number + return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) +end +Build.det3 = det3 + +-- q(a) * q(b) +local function qmul(a: { number }, b: { number }): { number } + local ax, ay, az, aw = a[1], a[2], a[3], a[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + return { + aw * bx + ax * bw + ay * bz - az * by, + aw * by - ax * bz + ay * bw + az * bx, + aw * bz + ax * by - ay * bx + az * bw, + aw * bw - ax * bx - ay * by - az * bz, + } +end +Build.qmul = qmul + +-- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise) +local function keyQuat(angle: number, x: number, y: number, z: number): { number } + if x == 0 and y == 0 and z == 0 then + return { 0, 0, 0, 1 } + end + return Mat4.axisAngle(x, y, z, -math.deg(angle)) +end + +local function normalize(x: number, y: number, z: number): (number, number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0, 0 + end + return x / l, y / l, z / l, l +end + +-- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z) +function Build.lookAt(p: { number }, t: { number }, roll: number): { number } + local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3]) + if l == 0 then + fx, fy, fz = 0, 1, 0 + end + local ux, uy, uz = 0, 0, 1 + if abs(fz) > 0.999999 then + ux, uy, uz = 0, 1, 0 + end + -- right = forward x up, up = right x forward + local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux) + ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx + local a = math.rad(roll) + local c, s = math.cos(a), math.sin(a) + local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz + local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz + return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 }) +end + +-- ------------------------------------------------------------------------------------------------ accessors +local function floats(values: { number }, comps: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, #values // comps) + for i = 1, (#values // comps) * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" } + +local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number } + local byName: { [string]: number } = {} + local texByFile: { [string]: number } = {} + local function texture(m: Read.Map): Types.TextureRef? + local file = m.file + if not file or file == "" then + return nil + end + local ti = texByFile[file] + if not ti then + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + local tiling = m.tiling or 0 + local wrap: any = if band(tiling, 0x10) ~= 0 then "clamp" elseif band(tiling, 0x2) ~= 0 then "mirror" else "repeat" + local tex: Types.Texture = { name = file, uri = file, mime = MIME[ext] :: string?, sampler = { wrapS = wrap, wrapT = wrap } } + table.insert(scene.textures, tex) + ti = #scene.textures + texByFile[file] = ti + end + local ref: Types.TextureRef = { texture = ti } + local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0 + if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then + ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) } + end + return ref + end + for i, m in raw.materials do + local mat = S.material(m.name) + local d = m.diffuse or { 0.5, 0.5, 0.5 } + local transparency = math.clamp(m.transparency or 0, 0, 1) + mat.baseColor = { d[1], d[2], d[3], 1 - transparency } + mat.metallic = 0 + mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1) + local si = m.selfIllum or 0 + if si > 0 then + mat.emissive = { d[1] * si, d[2] * si, d[3] * si } + end + mat.alphaMode = if transparency > 0 then "blend" else "opaque" + mat.doubleSided = m.twoSided + local maps: { [string]: any } = {} + for kind, mp in m.maps do + local ref = texture(mp) + maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture } + if kind == "diffuse" then + mat.baseColorTexture = ref + elseif kind == "selfIllum" and ref then + mat.emissiveTexture = ref + if si <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + mat.extras = { + ["3ds"] = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess, + shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum, + shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps, + }, + } + table.insert(scene.materials, mat) + local key = string.lower(m.name) + if byName[key] == nil then + byName[key] = i + end + end + return byName +end + +-- ------------------------------------------------------------------------------------------------ meshes +-- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved +-- by xf (world -> the node's local space) +local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh + local nv, nf = m.nv, m.nf + local pos, faces = m.positions, m.faces + -- local positions + local lp = table.create(nv * 3, 0) + for v = 0, nv - 1 do + local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)) + lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z + end + -- faces with valid corners, their materials + local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0) + local valid = table.create(nf, false) + for f = 0, nf - 1 do + local a, b, c = readu16(faces :: buffer, f * 8), readu16(faces :: buffer, f * 8 + 2), readu16(faces :: buffer, f * 8 + 4) + fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c + valid[f + 1] = a < nv and b < nv and c < nv + end + local fmat = table.create(nf, 0) + for _, fm in m.faceMats do + local mi = matByName[string.lower(fm.name)] or 0 + for _, f in fm.faces do + if f < nf then + fmat[f + 1] = mi + end + end + end + local smooth = m.smoothing + local doNormals = opts.normals ~= false + -- face normals (area weighted) and the faces around each distinct position + local fn = table.create(nf * 3, 0) + local around: { [number]: { number } } = {} + local group = table.create(nv, 0) + if doNormals then + local keyToGroup: { [string]: number } = {} + for v = 0, nv - 1 do + local k = buffer.readstring(pos, v * 12, 12) + local g = keyToGroup[k] + if not g then + g = v + keyToGroup[k] = g + end + group[v + 1] = g + end + for f = 1, nf do + if valid[f] then + local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3 + local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3] + local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3] + fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { fa[f], fb[f], fc[f] } do + local g = group[v + 1] + local list = around[g] + if not list then + list = {} + around[g] = list + end + if list[#list] ~= f then + table.insert(list, f) + end + end + end + end + end + local function sgOf(f: number): number + return if smooth then readu32(smooth, (f - 1) * 4) else 1 + end + local function cornerNormal(f: number, v: number, sg: number): (number, number, number) + local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] + if sg ~= 0 then + local sx, sy, sz = 0, 0, 0 + for _, g in around[group[v + 1]] do + if band(sgOf(g), sg) ~= 0 then + sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3] + end + end + local nx, ny, nz, l = normalize(sx, sy, sz) + if l > 0 then + return nx, ny, nz + end + end + local nx, ny, nz = normalize(x, y, z) + return nx, ny, nz + end + -- primitives in the order their material first appears + local order: { number } = {} + local byMat: { [number]: { number } } = {} + for f = 1, nf do + if valid[f] then + local mi = fmat[f] + if not byMat[mi] then + byMat[mi] = {} + table.insert(order, mi) + end + table.insert(byMat[mi], f) + end + end + local uvs, nuv = m.uvs, m.nuv + local flipV = opts.flipV ~= false + local out: Types.Mesh = { name = name, primitives = {} } + for _, mi in order do + local list = byMat[mi] + local remap: { [number]: number } = {} + local P: { number }, N: { number }, U: { number } = {}, {}, {} + local idx = table.create(#list * 3, 0) + local sgs = table.create(#list, 0) + local count = 0 + for i, f in list do + local sg = sgOf(f) + sgs[i] = sg + for k, v in { fa[f], fb[f], fc[f] } do + local key = if not doNormals then v elseif sg ~= 0 then v * 4294967296 + sg else -(f * 65536 + v + 1) + local o: number = remap[key] or -1 + if o < 0 then + o = count + count += 1 + remap[key] = o + P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] + if doNormals then + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg) + end + if uvs then + local u: number, w: number = 0, 0 + if v < nuv then + u = readf32(uvs, v * 8) + w = readf32(uvs, v * 8 + 4) + end + U[o * 2 + 1] = u + U[o * 2 + 2] = if flipV then 1 - w else w + end + end + idx[(i - 1) * 3 + k] = o + end + end + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3) }, + indices = ind, + mode = "triangles", + material = if mi > 0 then mi else nil, + extras = { ["3ds"] = { smoothing = sgs } }, + } + if doNormals then + prim.attributes.NORMAL = floats(N, 3) + end + if uvs then + prim.attributes.TEXCOORD_0 = floats(U, 2) + end + table.insert(out.primitives, prim) + end + return out +end + +-- ------------------------------------------------------------------------------------------------ tracks +-- the value of a track at a frame (linear between keys, clamped at the ends) +local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number } + if not t or #t.frames == 0 then + return default + end + local fr, vals, n = t.frames, t.values, t.size + local function at(k: number): { number } + local r = table.create(n, 0) + for c = 1, n do + r[c] = vals[(k - 1) * n + c] + end + return r + end + if frame <= fr[1] then + return at(1) + end + for k = 1, #fr - 1 do + local f0, f1 = fr[k], fr[k + 1] + if frame <= f1 then + local u = if f1 > f0 then (frame - f0) / (f1 - f0) else 1 + local a, b = at(k), at(k + 1) + for c = 1, n do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return at(#fr) +end + +local function first(t: Read.Track?, default: { number }): { number } + return evalTrack(t, -math.huge, default) +end + +local function scaleKey(v: { number }): { number } + return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] } +end + +-- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys +local function rotations(t: Read.Track): ({ number }, { { number } }) + local frames, quats = {}, {} + local acc: { number }? = nil + for k = 1, #t.frames do + local o = (k - 1) * 4 + local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4] + if acc == nil then + acc = keyQuat(angle, x, y, z) + else + local prev = acc :: { number } + local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64) + local f0 = frames[#frames] + for s = 1, steps - 1 do + table.insert(frames, f0 + (t.frames[k] - f0) * s / steps) + table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z))) + end + acc = qmul(prev, keyQuat(angle, x, y, z)) + end + local q = acc :: { number } + local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if n > 0 then + q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n } + end + acc = q + table.insert(frames, t.frames[k]) + table.insert(quats, q) + end + return frames, quats +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene + local o: Options = opts or {} + local fps = o.fps or 30 + local scene = S.new() + local matByName = materials(raw, scene) + -- objects by name + local objByName: { [string]: Read.Object } = {} + for _, obj in raw.objects do + if objByName[obj.name] == nil then + objByName[obj.name] = obj + end + local low = string.lower(obj.name) + if objByName[low] == nil then + objByName[low] = obj + end + end + local function findObj(name: string): Read.Object? + return objByName[name] or objByName[string.lower(name)] + end + local meshCache: { [any]: number } = {} + local function meshOf(obj: Read.Object, pivot: { number }?, placed: boolean): number? + local m = obj.mesh + if not m or m.nf == 0 or not m.faces then + return nil + end + local pv = pivot or { 0, 0, 0 } + local key = obj.name .. (if placed then string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) else "|free") + if meshCache[key] then + return meshCache[key] + end + local M = meshMatrix(m.matrix) + local inv = Mat4.inverse(M) or Mat4.identity() + local xf = inv + if placed then + if det3(M) < 0 then + xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf) + end + xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf) + end + local me = mesh(obj.name, m, xf, matByName, o) + if #me.primitives == 0 then + return nil + end + table.insert(scene.meshes, me) + meshCache[key] = #scene.meshes + return #scene.meshes + end + local camIndex: { [Read.Object]: number } = {} + local function cameraOf(obj: Read.Object): number + if camIndex[obj] then + return camIndex[obj] + end + local c = obj.camera :: Read.Camera + local hfov = if c.lens > 1e-3 then 2400 / c.lens else 45 + hfov = math.clamp(hfov, 0.01, 179) + local aspect = 4 / 3 + local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect) + local near = if c.near and c.near > 0 then c.near else 0.1 + local far = if c.far and c.far > near then c.far else nil + local cam: Types.Camera = { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + table.insert(scene.cameras, cam) + camIndex[obj] = #scene.cameras + return #scene.cameras + end + local lightIndex: { [Read.Object]: number } = {} + local function lightOf(obj: Read.Object): number + if lightIndex[obj] then + return lightIndex[obj] + end + local l = obj.light :: Read.Light + local L: Types.Light = { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier } + if l.spot then + L.type = "spot" + local hot = math.clamp(l.spot.hotspot, 0, 179.9) + local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9) + L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2 + end + if l.attenuate and l.outer and l.outer > 0 then + L.range = l.outer + end + table.insert(scene.lights, L) + lightIndex[obj] = #scene.lights + return #scene.lights + end + + local kf = raw.keyframer + local kfNodes = if kf then kf.nodes else {} + -- targets of cameras / spotlights by name + local targets: { [string]: Read.Node } = {} + for _, n in kfNodes do + if n.kind == "target" or n.kind == "lightTarget" then + targets[n.name] = targets[n.name] or n + end + end + local placedObj: { [Read.Object]: boolean } = {} + local sceneOf: { [number]: number } = {} -- kf id -> scene node + local channels: { Types.Channel } = {} + local function channel(node: number, path: any, times: { number }, values: { number }, comps: number) + for i = 1, #times do + times[i] /= fps + end + local ch: Types.Channel = { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" } + table.insert(channels, ch) + end + local function addNode(n: Types.Node, parent: number?): number + table.insert(scene.nodes, n) + local i = #scene.nodes + if parent then + table.insert(scene.nodes[parent].children, i) + else + table.insert(scene.roots, i) + end + return i + end + + for k, kn in kfNodes do + local kind = kn.kind + if kind == "target" or kind == "lightTarget" or kind == "ambient" then + continue + end + local id = kn.id or (k - 1) + local parent = if kn.parent >= 0 then sceneOf[kn.parent] else nil + local obj = findObj(kn.name) + local tr = kn.tracks + local name = if kn.instance and kn.instance ~= "" then kn.instance else kn.name + local node: Types.Node = { name = name, children = {} } + local x3ds: { [string]: any } = { kind = kind, object = kn.name, id = id, pivot = kn.pivot } + node.extras = { ["3ds"] = x3ds } + local animated = false + if kind == "object" then + if obj and obj.mesh then + node.mesh = meshOf(obj, kn.pivot, true) + placedObj[obj] = true + x3ds.hidden = obj.hidden or nil + end + node.translation = first(tr.pos, { 0, 0, 0 }) + node.rotation = if tr.rot and #tr.rot.frames > 0 then (select(2, rotations(tr.rot)) :: any)[1] else { 0, 0, 0, 1 } + node.scale = scaleKey(first(tr.scl, { 1, 1, 1 })) + local ni = addNode(node, parent) + sceneOf[id] = ni + if tr.pos and #tr.pos.frames > 1 then + channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3) + end + if tr.rot and #tr.rot.frames > 1 then + local frames, quats = rotations(tr.rot) + local vals = {} + for _, q in quats do + table.move(q, 1, 4, #vals + 1, vals) + end + channel(ni, "rotation", frames, vals, 4) + end + if tr.scl and #tr.scl.frames > 1 then + local vals = {} + for i = 1, #tr.scl.frames do + local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] }) + table.move(v, 1, 3, #vals + 1, vals) + end + channel(ni, "scale", table.clone(tr.scl.frames), vals, 3) + end + else + -- cameras and lights: position, target, roll + local isCam = kind == "camera" + local cam = if obj and isCam then obj.camera else nil + local lit = if obj and not isCam then obj.light else nil + local tgt = targets[kn.name] + local basePos = if cam then cam.pos elseif lit then lit.pos else { 0, 0, 0 } + local baseTgt = if cam then cam.target elseif lit and lit.spot then lit.spot.target else nil + local aims = isCam or kind == "spot" or baseTgt ~= nil + local function pose(frame: number): ({ number }, { number }?) + local p = evalTrack(tr.pos, frame, basePos) + if not aims then + return p, nil + end + local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] }) + local roll = evalTrack(tr.roll, frame, { if cam then cam.roll else 0 })[1] + return p, Build.lookAt(p, t, roll) + end + local p0, r0 = pose(-math.huge) + node.translation, node.rotation = p0, r0 + if cam then + node.camera = cameraOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.lens, x3ds.roll = cam.lens, cam.roll + elseif lit then + node.light = lightOf(obj :: Read.Object) + placedObj[obj :: Read.Object] = true + x3ds.off = lit.off or nil + end + local ni = addNode(node, parent) + sceneOf[id] = ni + -- every key time of the position, roll and target tracks + local set: { [number]: boolean } = {} + local times: { number } = {} + for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do + if t and #t.frames > 1 then + animated = true + end + for _, f in (if t then t.frames else {}) :: { number } do + if not set[f] then + set[f] = true + table.insert(times, f) + end + end + end + if animated then + table.sort(times) + local tv, rv = {}, {} + for _, f in times do + local p, r = pose(f) + table.move(p, 1, 3, #tv + 1, tv) + if r then + table.move(r, 1, 4, #rv + 1, rv) + end + end + channel(ni, "translation", table.clone(times), tv, 3) + if aims then + channel(ni, "rotation", times, rv, 4) + end + end + end + end + -- objects the keyframer does not place (or files without one): at their own matrix / position + for _, obj in raw.objects do + if placedObj[obj] then + continue + end + local node: Types.Node = { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } } + if obj.mesh then + local mi = meshOf(obj, nil, false) + if not mi then + continue + end + node.mesh = mi + if obj.mesh.matrix then + node.matrix = meshMatrix(obj.mesh.matrix) + end + elseif obj.camera then + local c = obj.camera + node.camera = cameraOf(obj) + node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll) + elseif obj.light then + local l = obj.light + node.light = lightOf(obj) + node.translation = l.pos + if l.spot then + node.rotation = Build.lookAt(l.pos, l.spot.target, 0) + end + else + continue + end + addNode(node, nil) + end + if #channels > 0 then + table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels }) + end + scene.meta.up = "z" + scene.meta.source = { + format = "3ds", + version = raw.version, + meshVersion = raw.meshVersion, + masterScale = raw.masterScale, + ambient = raw.ambient, + keyframer = kf ~= nil, + frames = if kf and kf.first then { kf.first, kf.last } else nil, + fps = fps, + } + return scene +end + +return Build diff --git a/src/Formats/model/3ds/Read.luau b/src/Formats/model/3ds/Read.luau new file mode 100644 index 0000000..648b4c5 --- /dev/null +++ b/src/Formats/model/3ds/Read.luau @@ -0,0 +1,506 @@ +--!strict +-- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read +-- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their +-- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes +-- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code). +-- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is +-- clipped to the parent. Never throws on bad data: returns nil, message, offset. +local Read = {} + +local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32 +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ chunk ids +local C = { + MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100, + RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031, + AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130, + UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620, + ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700, + CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010, + MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030, + MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084, + MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351, + MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C, + KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011, + NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022, + TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028, +} +Read.C = C + +-- material map chunks -> their name in Raw materials +Read.MAPS = { + [0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular", + [0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection", +} +-- keyframer node chunks -> kind +local NODE_KINDS = { + [0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light", + [0xB006] = "lightTarget", [0xB007] = "spot", +} +-- track chunks -> (field, values per key) +local TRACKS: { [number]: { any } } = { + [0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 }, + [0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Map = { file: string?, strength: number?, tiling: number?, uscale: number?, vscale: number?, uoffset: number?, voffset: number?, angle: number? } +export type Material = { + name: string, + ambient: { number }?, diffuse: { number }?, specular: { number }?, + shininess: number?, shinStrength: number?, transparency: number?, selfIllum: number?, -- fractions 0..1 + twoSided: boolean, wire: boolean, shading: number?, + maps: { [string]: Map }, +} +export type Mesh = { + nv: number, positions: buffer, -- nv * 3 f32 (world space) + nuv: number, uvs: buffer?, -- nuv * 2 f32 + nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags) + faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers + smoothing: buffer?, -- nf u32 + matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space) +} +export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? } +export type Light = { + pos: { number }, color: { number }, multiplier: number, off: boolean, attenuate: boolean, + inner: number?, outer: number?, spot: { target: { number }, hotspot: number, falloff: number }?, +} +export type Object = { name: string, hidden: boolean, mesh: Mesh?, camera: Camera?, light: Light? } +export type Track = { frames: { number }, values: { number }, size: number, flags: number } +export type Node = { + kind: string, id: number?, name: string, parent: number, flags: number, instance: string?, pivot: { number }?, + tracks: { [string]: Track }, +} +export type Raw = { + version: number?, meshVersion: number?, masterScale: number?, ambient: { number }?, + materials: { Material }, objects: { Object }, + keyframer: { name: string?, length: number?, first: number?, last: number?, nodes: { Node } }?, + vertices: number, +} + +-- ------------------------------------------------------------------------------------------------ helpers +type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw } + +-- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error +local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?) + local b = ctx.b + while p + 6 <= stop do + local id, size = readu16(b, p), readu32(b, p + 2) + if size < 6 then + return nil, nil -- padding or garbage after the last chunk + end + local e = p + size + if e > ctx.limit then + return string.format("chunk 0x%04x runs past the end of the data", id), p + end + local err, at = fn(id, p + 6, math.min(e, stop)) + if err then + return err, at + end + p = e + end + return nil, nil +end + +-- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil +local function cstring(b: buffer, p: number, stop: number): (string?, number) + for q = p, stop - 1 do + if readu8(b, q) == 0 then + return buffer.readstring(b, p, q - p), q + 1 + end + end + return nil, stop +end + +local function vec3(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } +end + +-- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else) +local function color(ctx: Ctx, p: number, stop: number): { number }? + local b = ctx.b + local main: { number }?, lin: { number }? = nil, nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then + local c = vec3(b, q) + if id == C.RGBF then + main = main or c + else + lin = lin or c + end + elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then + local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 } + if id == C.RGBB then + main = main or c + else + lin = lin or c + end + end + return nil, nil + end) + return main or lin +end + +-- a percentage chunk list -> a fraction 0..1 +local function percent(ctx: Ctx, p: number, stop: number): number? + local b = ctx.b + local v: number? = nil + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if v == nil and id == C.PERCENTW and e - q >= 2 then + v = readu16(b, q) / 100 + elseif v == nil and id == C.PERCENTF and e - q >= 4 then + v = readf32(b, q) / 100 + end + return nil, nil + end) + return v +end + +-- ------------------------------------------------------------------------------------------------ materials +local function map(ctx: Ctx, p: number, stop: number): Map + local b = ctx.b + local m: Map = {} + m.strength = percent(ctx, p, stop) + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.MAP_FILE then + m.file = cstring(b, q, e) + elseif id == C.MAP_TILING and n >= 2 then + m.tiling = readu16(b, q) + elseif n >= 4 then + local v = readf32(b, q) + if id == C.MAP_USCALE then + m.uscale = v + elseif id == C.MAP_VSCALE then + m.vscale = v + elseif id == C.MAP_UOFFSET then + m.uoffset = v + elseif id == C.MAP_VOFFSET then + m.voffset = v + elseif id == C.MAP_ANGLE then + m.angle = v + end + end + return nil, nil + end) + return m +end + +local function material(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local m: Material = { name = "", twoSided = false, wire = false, maps = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MAT_NAME then + m.name = cstring(b, q, e) or "" + elseif id == C.MAT_AMBIENT then + m.ambient = color(ctx, q, e) + elseif id == C.MAT_DIFFUSE then + m.diffuse = color(ctx, q, e) + elseif id == C.MAT_SPECULAR then + m.specular = color(ctx, q, e) + elseif id == C.MAT_SHININESS then + m.shininess = percent(ctx, q, e) + elseif id == C.MAT_SHIN_STRENGTH then + m.shinStrength = percent(ctx, q, e) + elseif id == C.MAT_TRANSPARENCY then + m.transparency = percent(ctx, q, e) + elseif id == C.MAT_SELF_ILPCT then + m.selfIllum = percent(ctx, q, e) + elseif id == C.MAT_TWO_SIDE then + m.twoSided = true + elseif id == C.MAT_WIRE then + m.wire = true + elseif id == C.MAT_SHADING and e - q >= 2 then + m.shading = readu16(b, q) + elseif Read.MAPS[id] then + m.maps[Read.MAPS[id]] = map(ctx, q, e) + end + return nil, nil + end) + table.insert(ctx.raw.materials, m) +end + +-- ------------------------------------------------------------------------------------------------ objects +local function faceList(ctx: Ctx, mesh: Mesh, p: number, stop: number): (string?, number?) + local b = ctx.b + if stop - p < 2 then + return "truncated face list", p + end + local nf = readu16(b, p) + if p + 2 + nf * 8 > stop then + return "face list runs past its chunk", p + end + local faces = buffer.create(nf * 8) + buffer.copy(faces, 0, b, p + 2, nf * 8) + mesh.nf, mesh.faces = nf, faces + return each(ctx, p + 2 + nf * 8, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.FACE_MAT then + local name, r = cstring(b, q, e) + if not name or r + 2 > e then + return "bad face material list", q + end + local n = readu16(b, r) + if r + 2 + n * 2 > e then + return "face material list runs past its chunk", q + end + local list: { number } = {} + for i = 0, n - 1 do + list[i + 1] = readu16(b, r + 2 + i * 2) + end + table.insert(mesh.faceMats, { name = name, faces = list }) + elseif id == C.SMOOTH then + local n = math.min(nf, (e - q) // 4) + local s = buffer.create(nf * 4) + buffer.copy(s, 0, b, q, n * 4) + mesh.smoothing = s + end + return nil, nil + end) +end + +local function trimesh(ctx: Ctx, p: number, stop: number): (Mesh?, string?, number?) + local b = ctx.b + local mesh: Mesh = { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} } + local err, at = each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERTICES or id == C.UVS then + if e - q < 2 then + return "truncated vertex list", q + end + local n = readu16(b, q) + local size = if id == C.VERTICES then 12 else 8 + if q + 2 + n * size > e then + return "vertex list runs past its chunk", q + end + local data = buffer.create(n * size) + buffer.copy(data, 0, b, q + 2, n * size) + if id == C.VERTICES then + ctx.raw.vertices += n + if ctx.raw.vertices > ctx.maxVertices then + return "limit: more than " .. ctx.maxVertices .. " vertices", q + end + mesh.nv, mesh.positions = n, data + else + mesh.nuv, mesh.uvs = n, data + end + elseif id == C.FACES then + return faceList(ctx, mesh, q, e) + elseif id == C.MATRIX and e - q >= 48 then + local m: { number } = {} + for i = 0, 11 do + m[i + 1] = readf32(b, q + i * 4) + end + mesh.matrix = m + end + return nil, nil + end) + if err then + return nil, err, at + end + return mesh, nil, nil +end + +local function camera(ctx: Ctx, p: number, stop: number): Camera? + local b = ctx.b + if stop - p < 32 then + return nil + end + local cam: Camera = { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) } + each(ctx, p + 32, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.CAM_RANGES and e - q >= 8 then + cam.near, cam.far = readf32(b, q), readf32(b, q + 4) + end + return nil, nil + end) + return cam +end + +local function light(ctx: Ctx, p: number, stop: number): Light? + local b = ctx.b + if stop - p < 12 then + return nil + end + local l: Light = { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false } + l.color = color(ctx, p + 12, stop) or l.color + each(ctx, p + 12, stop, function(id: number, q: number, e: number): (string?, number?) + local n = e - q + if id == C.SPOT and n >= 20 then + l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) } + elseif id == C.LIGHT_OFF then + l.off = true + elseif id == C.ATTENUATE then + l.attenuate = true + elseif id == C.MULTIPLIER and n >= 4 then + l.multiplier = readf32(b, q) + elseif id == C.INNER_RANGE and n >= 4 then + l.inner = readf32(b, q) + elseif id == C.OUTER_RANGE and n >= 4 then + l.outer = readf32(b, q) + end + return nil, nil + end) + return l +end + +local function object(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + local name, q = cstring(b, p, stop) + if not name then + return "object without a name", p + end + local obj: Object = { name = name, hidden = false } + local err, at = each(ctx, q, stop, function(id: number, r: number, e: number): (string?, number?) + if id == C.TRIMESH then + local mesh, merr, mat = trimesh(ctx, r, e) + if not mesh then + return merr, mat + end + obj.mesh = mesh + elseif id == C.CAMERA then + obj.camera = camera(ctx, r, e) + elseif id == C.LIGHT then + obj.light = light(ctx, r, e) + elseif id == C.OBJ_HIDDEN then + obj.hidden = true + end + return nil, nil + end) + if err then + return err, at + end + table.insert(ctx.raw.objects, obj) + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ keyframer +-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of +-- tension / continuity / bias / ease to / ease from), then the values +local function track(b: buffer, p: number, stop: number, size: number): Track? + if stop - p < 14 then + return nil + end + local flags, n = readu16(b, p), readu32(b, p + 10) + local t: Track = { frames = {}, values = {}, size = size, flags = flags } + p += 14 + for _ = 1, n do + if p + 6 > stop then + break + end + local frame, spline = readu32(b, p), readu16(b, p + 4) + p += 6 + for bit = 0, 4 do + if band(spline, bit32.lshift(1, bit)) ~= 0 then + p += 4 + end + end + if p + size * 4 > stop then + break + end + table.insert(t.frames, frame) + for k = 0, size - 1 do + table.insert(t.values, readf32(b, p + k * 4)) + end + p += size * 4 + end + return t +end + +local function node(ctx: Ctx, kind: string, p: number, stop: number, list: { Node }) + local b = ctx.b + local n: Node = { kind = kind, name = "", parent = -1, flags = 0, tracks = {} } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.NODE_ID and e - q >= 2 then + n.id = readu16(b, q) + elseif id == C.NODE_HDR then + local name, r = cstring(b, q, e) + n.name = name or "" + if r + 6 <= e then + n.flags = readu16(b, r) + n.parent = readi16(b, r + 4) + end + elseif id == C.NODE_INSTANCE then + n.instance = cstring(b, q, e) + elseif id == C.NODE_PIVOT and e - q >= 12 then + n.pivot = vec3(b, q) + elseif TRACKS[id] then + local spec = TRACKS[id] + n.tracks[spec[1]] = track(b, q, e, spec[2]) + end + return nil, nil + end) + table.insert(list, n) +end + +local function keyframer(ctx: Ctx, p: number, stop: number) + local b = ctx.b + local kf = { nodes = {} :: { Node }, name = nil :: string?, length = nil :: number?, first = nil :: number?, last = nil :: number? } + each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.KF_HDR and e - q >= 2 then + local name, r = cstring(b, q + 2, e) + kf.name = name + if r + 4 <= e then + kf.length = readu32(b, r) + end + elseif id == C.KF_FRAMES and e - q >= 8 then + kf.first, kf.last = readu32(b, q), readu32(b, q + 4) + elseif NODE_KINDS[id] then + node(ctx, NODE_KINDS[id], q, e, kf.nodes) + end + return nil, nil + end) + ctx.raw.keyframer = kf +end + +-- ------------------------------------------------------------------------------------------------ parse +local function editor(ctx: Ctx, p: number, stop: number): (string?, number?) + local b = ctx.b + return each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?) + if id == C.MATERIAL then + material(ctx, q, e) + elseif id == C.OBJECT then + return object(ctx, q, e) + elseif id == C.MESH_VERSION and e - q >= 4 then + ctx.raw.meshVersion = readu32(b, q) + elseif id == C.MASTER_SCALE and e - q >= 4 then + ctx.raw.masterScale = readf32(b, q) + elseif id == C.AMBIENT_LIGHT then + ctx.raw.ambient = color(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) -- some writers nest it here + end + return nil, nil + end) +end + +-- parse(b, base, limit, opts) -> Raw | nil, message, offset +function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?) + if limit - base < 6 or readu16(b, base) ~= C.MAIN then + return nil, "not a 3DS file (no 0x4D4D main chunk)", base + end + local raw: Raw = { materials = {}, objects = {}, vertices = 0 } + local ctx: Ctx = { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw } + local size = readu32(b, base + 2) + if size < 6 then + return nil, "bad main chunk size", base + end + -- a main chunk declared longer than the data: truncated + if base + size > limit then + return nil, "truncated: the main chunk runs past the end of the data", base + end + local err, at = each(ctx, base + 6, base + size, function(id: number, q: number, e: number): (string?, number?) + if id == C.VERSION and e - q >= 4 then + raw.version = readu32(b, q) + elseif id == C.EDITOR then + return editor(ctx, q, e) + elseif id == C.KEYFRAMER then + keyframer(ctx, q, e) + end + return nil, nil + end) + if err then + return nil, err, at + end + return raw, nil, nil +end + +return Read diff --git a/src/Formats/model/3ds/Write.luau b/src/Formats/model/3ds/Write.luau new file mode 100644 index 0000000..c094afd --- /dev/null +++ b/src/Formats/model/3ds/Write.luau @@ -0,0 +1,859 @@ +--!strict +-- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world +-- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's +-- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1 +-- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with +-- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and +-- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in +-- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key +-- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas. +-- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Read = require("@formats/model/3ds/Read") +local Build = require("@formats/model/3ds/Build") + +local Write = {} + +local C = Read.C +local S = Types.Scene +local writeu32 = buffer.writeu32 +local sqrt, abs = math.sqrt, math.abs + +export type Options = { flipV: boolean?, fps: number?, name: string?, files: { [string]: any }?, smoothing: boolean? } + +-- ------------------------------------------------------------------------------------------------ chunks +type W = Bytes.Writer +local function open(w: W, id: number): number + local at = w.pos + w:u16le(id) + w:u32le(0) + return at +end +local function close(w: W, at: number) + writeu32(w.buf, at + 2, w.pos - at) +end +local function leaf(w: W, id: number, fn: () -> ()) + local at = open(w, id) + fn() + close(w, at) +end +local function name(s: string?, fallback: string): string + local n = string.gsub(s or "", "%z", "") + if n == "" then + n = fallback + end + return string.sub(n, 1, 63) +end + +local function colorChunk(w: W, id: number, c: { number }) + leaf(w, id, function() + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(c[k] or 0) + end + end) + leaf(w, C.RGBB, function() + for k = 1, 3 do + w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255)) + end + end) + end) +end +local function percentChunk(w: W, id: number, v: number) + leaf(w, id, function() + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100)) + end) + leaf(w, C.PERCENTF, function() + w:f32le(v * 100) + end) + end) +end + +-- ------------------------------------------------------------------------------------------------ math +local function world(scene: Types.Scene): ({ [number]: { number } }, { [number]: number }, { number }) + local W: { [number]: { number } } = {} + local parent: { [number]: number } = {} + local order: { number } = {} + local function visit(i: number, p: number?, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or W[i] or depth > 256 then + return + end + W[i] = S.mul(pm, S.nodeMatrix(n)) + parent[i] = p or 0 + table.insert(order, i) + for _, c in n.children or {} do + visit(c, i, W[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, nil, S.IDENTITY, 0) + end + return W, parent, order +end + +local function col(m: { number }, c: number): (number, number, number) + return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3] +end +local function unit(x: number, y: number, z: number): (number, number, number) + local l = sqrt(x * x + y * y + z * z) + if l < 1e-30 then + return 0, 0, 0 + end + return x / l, y / l, z / l +end + +-- a quaternion -> the 3DS (clockwise angle, axis) +local function axisAngle(q: { number }): (number, number, number, number) + local x, y, z, w = q[1], q[2], q[3], q[4] + local n = sqrt(x * x + y * y + z * z + w * w) + if n < 1e-30 then + return 0, 0, 0, 0 + end + x, y, z, w = x / n, y / n, z / n, w / n + local s = sqrt(x * x + y * y + z * z) + if s < 1e-12 then + return 0, 0, 0, 0 + end + local angle = 2 * math.atan2(s, w) + return -angle, x / s, y / s, z / s +end + +local function conj(q: { number }): { number } + return { -q[1], -q[2], -q[3], q[4] } +end + +-- a channel's value at a time (linear; rotations normalized lerp along the short way) +local function sample(ch: Types.Channel, t: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local comps = if ch.path == "rotation" then 4 else 3 + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = table.create(comps, 0) + for c = 1, comps do + r[c] = OUT(e, c - 1) + end + return r + end + if n == 0 then + return if comps == 4 then { 0, 0, 0, 1 } else { 0, 0, 0 } + end + if t <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if t <= t1 then + if ch.interpolation == "STEP" or t1 <= t0 then + return if t >= t1 then v(k + 1) else v(k) + end + local u = (t - t0) / (t1 - t0) + local a, b = v(k), v(k + 1) + if comps == 4 and a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then + b = { -b[1], -b[2], -b[3], -b[4] } + end + for c = 1, comps do + a[c] += (b[c] - a[c]) * u + end + return a + end + end + return v(n - 1) +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" } + +local function textureFiles(scene: Types.Scene, opts: Options): { [number]: string } + local files = opts.files + local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture" + local out: { [number]: string } = {} + for i, tex in scene.textures do + local file = tex.uri + if not file or file == "" or string.sub(file, 1, 5) == "data:" then + file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + if tex.data and type(files) == "table" then + files[file] = tex.data + end + end + out[i] = file + end + return out +end + +local MAP_IDS: { [string]: number } = {} +for id, kind in Read.MAPS do + MAP_IDS[kind] = id +end +local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" } + +local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [number]: string }) + local x = (m.extras and m.extras["3ds"] or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + local diffuse = { bc[1], bc[2], bc[3] } + local shininess = math.clamp(1 - (m.roughness or 1), 0, 1) + local transparency = math.clamp(1 - (bc[4] or 1), 0, 1) + local e = m.emissive or { 0, 0, 0 } + local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1) + local at = open(w, C.MATERIAL) + leaf(w, C.MAT_NAME, function() + w:cstring(mname) + end) + colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse) + colorChunk(w, C.MAT_DIFFUSE, diffuse) + colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 }) + percentChunk(w, C.MAT_SHININESS, shininess) + percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5) + percentChunk(w, C.MAT_TRANSPARENCY, transparency) + percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum) + leaf(w, C.MAT_SHADING, function() + w:u16le(x.shading or 3) + end) + if m.doubleSided then + leaf(w, C.MAT_TWO_SIDE, function() end) + end + if x.wire then + leaf(w, C.MAT_WIRE, function() end) + end + -- maps: the PBR texture refs first, then the other kinds model/3ds read + local maps: { [string]: any } = {} + local function fromRef(ref: Types.TextureRef?, saved: any): any + if not ref or not files[ref.texture] then + return nil + end + local s = saved or {} + local tf = ref.transform + return { + file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling, + uscale = if tf and tf.scale then tf.scale[1] else s.uscale, vscale = if tf and tf.scale then tf.scale[2] else s.vscale, + uoffset = if tf and tf.offset then tf.offset[1] else s.uoffset, voffset = if tf and tf.offset then tf.offset[2] else s.voffset, + angle = if tf and tf.rotation then math.deg(tf.rotation) else s.angle, + } + end + local saved = (x.maps or {}) :: { [string]: any } + maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse) + maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum) + for kind, s in saved do + if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then + maps[kind] = fromRef(if s.texture then { texture = s.texture } else nil, s) + end + end + for _, kind in MAP_ORDER do + local mp = maps[kind] + if mp then + local mat = open(w, MAP_IDS[kind]) + leaf(w, C.PERCENTW, function() + w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100)) + end) + leaf(w, C.MAP_FILE, function() + w:cstring(name(mp.file, "texture")) + end) + if mp.tiling then + leaf(w, C.MAP_TILING, function() + w:u16le(mp.tiling) + end) + end + for _, f in { { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } } do + local v = f[2] + if type(v) == "number" then + leaf(w, f[1], function() + w:f32le(v) + end) + end + end + close(w, mat) + end + end + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } } + +-- the mesh as 3DS parts (local space), or nil, message +local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?) + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean + return n == "TEXCOORD_0" or n == "NORMAL" + end, { triangulate = true }) + if not merged then + return nil, err + end + local P = merged.attrs.POSITION.values + local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values + local T = merged.attrs.TEXCOORD_0 + local tv, tc = if T then T.values else nil, if T then T.components else 0 + local flipV = opts.flipV ~= false + local corners = merged.corners + -- per face: material, smoothing group + local nf = #corners // 3 + local fmat, fsg = table.create(nf, 0), table.create(nf, 1) + for _, part in merged.parts do + local prim: any = part.prim + local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing + local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles" + for f = part.firstFace + 1, part.firstFace + part.faceCount do + fmat[f] = if type(prim.material) == "number" then prim.material else 0 + if savedOk then + fsg[f] = saved[f - part.firstFace] + elseif N then + -- flat when every corner normal is the face normal + local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3] + local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] } + local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] } + local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]) + local flat = true + for _, v in { a, b, c } do + local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3]) + if vx * nx + vy * ny + vz * nz < 0.9998 then + flat = false + end + end + fsg[f] = if flat then 0 else 1 + end + end + end + local out: { Part } = {} + local cur: Part? = nil + local remap: { [number]: number } = {} + local count = 0 + for f = 1, nf do + local fresh = 0 + for k = 1, 3 do + if not remap[corners[f * 3 - 3 + k]] then + fresh += 1 + end + end + if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then + cur = { name = if #out == 0 then base else string.sub(base, 1, 56) .. "." .. #out, positions = {}, uvs = if tv then {} else nil, faces = {}, smooth = {}, mats = {} } + table.insert(out, cur :: Part) + remap, count = {}, 0 + end + local p = cur :: Part + for k = 1, 3 do + local v = corners[f * 3 - 3 + k] + local o = remap[v] + if not o then + o = count + count += 1 + remap[v] = o + table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions) + if tv and p.uvs then + local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0 + table.insert(p.uvs, u) + table.insert(p.uvs, if flipV then 1 - vv else vv) + end + end + table.insert(p.faces, o) + end + table.insert(p.smooth, fsg[f]) + local mi = fmat[f] + if mi > 0 then + p.mats[mi] = p.mats[mi] or {} + table.insert(p.mats[mi], #p.smooth - 1) + end + end + return out, nil +end + +local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: string }) + local at = open(w, C.OBJECT) + w:cstring(part.name) + local tm = open(w, C.TRIMESH) + local nv = #part.positions // 3 + leaf(w, C.VERTICES, function() + w:u16le(nv) + local p = part.positions + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3]) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + if part.uvs then + local uvs = part.uvs + leaf(w, C.UVS, function() + w:u16le(nv) + for i = 1, nv * 2 do + w:f32le(uvs[i] or 0) + end + end) + end + leaf(w, C.MATRIX, function() + for _, c in { 0, 1, 2, 3 } do + local x, y, z = col(M, c) + w:f32le(x) + w:f32le(y) + w:f32le(z) + end + end) + local fl = open(w, C.FACES) + local nf = #part.smooth + w:u16le(nf) + for f = 0, nf - 1 do + w:u16le(part.faces[f * 3 + 1]) + w:u16le(part.faces[f * 3 + 2]) + w:u16le(part.faces[f * 3 + 3]) + w:u16le(7) -- edges AB, BC, CA visible + end + local mats: { number } = {} + for mi in part.mats do + table.insert(mats, mi) + end + table.sort(mats) + for _, mi in mats do + local list = part.mats[mi] + leaf(w, C.FACE_MAT, function() + w:cstring(matNames[mi]) + w:u16le(#list) + for _, f in list do + w:u16le(f) + end + end) + end + leaf(w, C.SMOOTH, function() + for _, s in part.smooth do + w:u32le(s) + end + end) + close(w, fl) + close(w, tm) + close(w, at) +end + +-- ------------------------------------------------------------------------------------------------ cameras / lights +-- the eye, target and roll of a node's world matrix (looking down -Z, Y up) +local function aim(m: { number }, dist: number): ({ number }, { number }, number) + local p = { m[13], m[14], m[15] } + local fx, fy, fz = unit(-m[9], -m[10], -m[11]) + if fx == 0 and fy == 0 and fz == 0 then + fx, fy, fz = 0, 0, -1 + end + local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist } + -- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis + local q0 = Build.lookAt(p, t, 0) + local m0 = Mat4.fromQuat(q0) + local ux, uy, uz = unit(m[5], m[6], m[7]) + local cu = ux * m0[5] + uy * m0[6] + uz * m0[7] + local cr = ux * m0[1] + uy * m0[2] + uz * m0[3] + return p, t, math.deg(math.atan2(-cr, cu)) +end + +local function writeCamera(w: W, cname: string, cam: Types.Camera, m: { number }, dist: number) + local p, t, roll = aim(m, dist) + local aspect = cam.aspect or 4 / 3 + local yfov = if cam.type == "perspective" and cam.yfov then cam.yfov else math.rad(45) + local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect)) + local at = open(w, C.OBJECT) + w:cstring(cname) + local c = open(w, C.CAMERA) + for _, v in { p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) } do + w:f32le(v) + end + leaf(w, C.CAM_RANGES, function() + w:f32le(cam.znear or 0) + w:f32le(cam.zfar or 1000) + end) + close(w, c) + close(w, at) +end + +local function writeLight(w: W, lname: string, l: Types.Light, m: { number }, dist: number) + local p, t = aim(m, dist) + local at = open(w, C.OBJECT) + w:cstring(lname) + local c = open(w, C.LIGHT) + for k = 13, 15 do + w:f32le(m[k]) + end + leaf(w, C.RGBF, function() + for k = 1, 3 do + w:f32le(l.color and l.color[k] or 1) + end + end) + if l.type ~= "point" then + local inner = if l.type == "spot" then (l.innerCone or 0) else math.rad(45) + local outer = if l.type == "spot" then (l.outerCone or math.pi / 4) else math.rad(45) + leaf(w, C.SPOT, function() + for k = 1, 3 do + w:f32le(t[k]) + end + w:f32le(math.deg(inner * 2)) + w:f32le(math.deg(math.max(outer, inner) * 2)) + end) + end + if l.range and l.range > 0 then + leaf(w, C.ATTENUATE, function() end) + leaf(w, C.OUTER_RANGE, function() + w:f32le(l.range :: number) + end) + end + leaf(w, C.MULTIPLIER, function() + w:f32le(l.intensity or 1) + end) + close(w, c) + close(w, at) + return p +end + +-- ------------------------------------------------------------------------------------------------ keyframer +local function writeTrack(w: W, id: number, frames: { number }, values: { number }, size: number) + leaf(w, id, function() + w:u16le(0) + w:u32le(0) + w:u32le(0) + w:u32le(#frames) + for k, f in frames do + w:u32le(f) + w:u16le(0) + for c = 1, size do + w:f32le(values[(k - 1) * size + c]) + end + end + end) +end + +type KfNode = { + chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1 + frames: { [string]: { number } }, values: { [string]: { number } }, +} + +-- frames (rounded, strictly increasing) and the indices of the channel keys they keep +local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number }) + local IN = S.reader(ch.input) :: any + local frames, keep = {}, {} + for k = 0, ch.input.count - 1 do + local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5)) + if #frames == 0 or f > frames[#frames] then + table.insert(frames, f) + table.insert(keep, k) + end + end + return frames, keep +end + +local function channelValues(ch: Types.Channel, keep: { number }, comps: number): { { number } } + local OUT = S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + local out = {} + for _, k in keep do + local e = if cubic then k * 3 + 1 else k + local v = table.create(comps, 0) + for c = 1, comps do + v[c] = OUT(e, c - 1) + end + table.insert(out, v) + end + return out +end + +local function rotTrack(quats: { { number } }): { number } + local vals = {} + local prev: { number }? = nil + for _, q in quats do + local d = q + if prev then + d = Build.qmul(conj(prev), q) + if d[4] < 0 then + d = { -d[1], -d[2], -d[3], -d[4] } + end + end + local a, x, y, z = axisAngle(d) + table.insert(vals, a) + table.insert(vals, x) + table.insert(vals, y) + table.insert(vals, z) + prev = q + end + return vals +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local fps = o.fps or 30 + local W, parentOf, order = world(scene) + local w = Bytes.writer(65536) + local main = open(w, C.MAIN) + leaf(w, C.VERSION, function() + w:u32le(3) + end) + local ed = open(w, C.EDITOR) + leaf(w, C.MESH_VERSION, function() + w:u32le(3) + end) + -- materials (unique names) + local files = textureFiles(scene, o) + local matNames: { [number]: string } = {} + local used: { [string]: boolean } = {} + local function unique(base: string): string + local n, k = base, 1 + while used[string.lower(n)] do + k += 1 + n = string.sub(base, 1, 56) .. "_" .. k + end + used[string.lower(n)] = true + return n + end + for i, m in scene.materials do + matNames[i] = unique(name(m.name, "Material" .. i)) + writeMaterial(w, m, matNames[i], files) + end + leaf(w, C.MASTER_SCALE, function() + w:f32le(1) + end) + -- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer) + used = {} + local firstNode: { [number]: number } = {} + for _, i in order do + local mi = scene.nodes[i].mesh + if mi and scene.meshes[mi] and not firstNode[mi] then + firstNode[mi] = i + end + end + local meshParts: { [number]: { Part } } = {} + local meshM: { [number]: { number } } = {} + for mi, mesh in scene.meshes do + local ni = firstNode[mi] + if ni == nil and #scene.nodes > 0 then + continue + end + local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o) + if not list then + return nil, err + end + local M = if ni then W[ni] else S.IDENTITY + if not Mat4.inverse(M) then + M = S.IDENTITY + end + meshParts[mi], meshM[mi] = list, M + for _, part in list do + used[string.lower(part.name)] = true + writeMesh(w, part, M, matNames) + end + end + -- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors + local KW: { [number]: { number } } = {} + for _, i in order do + local n = scene.nodes[i] + local m = W[i] + if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then + m = S.mul(m, Mat4.scaling(-1, 1, 1)) + end + KW[i] = m + end + local kfs: { KfNode } = {} + local kfOf: { [number]: number } = {} + local anim = scene.animations[1] + local byNode: { [number]: { [string]: Types.Channel } } = {} + if anim then + for _, ch in anim.channels do + if ch.path ~= "weights" then + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + end + local lastFrame = 0 + local function single(v: { number }): { number } + return table.clone(v) + end + for _, i in order do + local n = scene.nodes[i] + local p = parentOf[i] + local pk = if p ~= 0 then kfOf[p] else nil + local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) + local dist = 100 + local x3ds = n.extras and n.extras["3ds"] + local function placeCamLight(kind: number, objName: string, tgtChunk: number?) + local pos, tgt, roll = aim(W[i], dist) + local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } + table.insert(kfs, kn) + local idx = #kfs + -- animated root cameras / lights: position, target and roll at the key times + local chs: any = if p == 0 then byNode[i] else nil + local targetFrames, targetVals = { 0 }, tgt + if chs and (chs.translation or chs.rotation) then + local fr: { [number]: boolean } = {} + local frames: { number } = {} + local list: { Types.Channel } = {} + table.insert(list, chs.translation) + table.insert(list, chs.rotation) + for _, ch in list do + for _, f in (frameKeys(ch, fps)) do + if not fr[f] then + fr[f] = true + table.insert(frames, f) + end + end + end + table.sort(frames) + local pv, tv, rv = {}, {}, {} + for _, f in frames do + local t = f / fps + local ct, cr = chs.translation, chs.rotation + local tr = if ct then sample(ct, t) else { W[i][13], W[i][14], W[i][15] } + local rq = if cr then sample(cr, t) else (n.rotation or { 0, 0, 0, 1 }) + local sc = n.scale or { 1, 1, 1 } + local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist) + table.move(ps, 1, 3, #pv + 1, pv) + table.move(ts, 1, 3, #tv + 1, tv) + table.insert(rv, rs) + lastFrame = math.max(lastFrame, f) + end + kn.frames.pos, kn.values.pos = frames, pv + kn.frames.roll, kn.values.roll = frames, rv + targetFrames, targetVals = frames, tv + end + if tgtChunk then + table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } }) + end + if kind ~= 0xB003 then + kn.frames.roll, kn.values.roll = nil :: any, nil :: any + end + return idx + end + local function camLight(onlyThis: boolean): number? + if not camOrLight then + return nil + end + local idx: number? = nil + if n.camera and scene.cameras[n.camera] then + local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera)) + writeCamera(w, cname, scene.cameras[n.camera], W[i], dist) + idx = placeCamLight(0xB003, cname, 0xB004) + end + if n.light and scene.lights[n.light] then + local l = scene.lights[n.light] + local lname = unique(name(l.name or n.name, "Light" .. n.light)) + writeLight(w, lname, l, W[i], dist) + local k = placeCamLight(if l.type == "point" then 0xB005 else 0xB007, lname, if l.type == "point" then nil else 0xB006) + idx = idx or k + end + if onlyThis and idx then + kfOf[i] = idx + -- the node's frame in the keyframer: the camera / light pose + local kn = kfs[idx] + local pos = kn.values.pos + local m: { number } = W[i] + if kn.chunk == 0xB005 then + KW[i] = Mat4.translation(pos[1], pos[2], pos[3]) + else + local _, tgt, roll = aim(m, dist) + KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, if kn.chunk == 0xB003 then roll else 0), nil) + end + end + return idx + end + local _ = x3ds + if n.mesh == nil and camOrLight then + camLight(true) + continue + end + -- an object node (or a dummy) with the node's transform relative to its keyframer parent + local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY + local inv = Mat4.inverse(pkw) or Mat4.identity() + local L = S.mul(inv, KW[i]) + local t, r, s = Mat4.decompose(L) + local plist = if n.mesh then meshParts[n.mesh] else nil + local objName = if plist then plist[1].name else "$$$DUMMY" + local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil + local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } } + -- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree) + local chs = byNode[i] + if chs then + local own = S.nodeMatrix(n) + local same = true + for k = 1, 16 do + if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then + same = false + end + end + if same then + for path, field in { translation = "pos", rotation = "rot", scale = "scl" } :: { [string]: string } do + local ch = chs[path] + if ch then + local frames, keep = frameKeys(ch, fps) + local vals = channelValues(ch, keep, if path == "rotation" then 4 else 3) + lastFrame = math.max(lastFrame, frames[#frames] or 0) + kn.frames[field] = frames + if path == "rotation" then + kn.values[field] = rotTrack(vals) + else + local flat = {} + for _, v in vals do + table.move(v, 1, 3, #flat + 1, flat) + end + kn.values[field] = flat + end + end + end + end + end + table.insert(kfs, kn) + kfOf[i] = #kfs + for k = 2, if plist then #plist else 0 do + local extra = table.clone(kn) + extra.name, extra.instance = (plist :: { Part })[k].name, nil + table.insert(kfs, extra) + end + camLight(false) + end + close(w, ed) + -- the keyframer + local kf = open(w, C.KEYFRAMER) + leaf(w, C.KF_HDR, function() + w:u16le(5) + w:cstring("MAXSCENE") + w:u32le(math.max(lastFrame, 100)) + end) + leaf(w, C.KF_FRAMES, function() + w:u32le(0) + w:u32le(math.max(lastFrame, 100)) + end) + for id, kn in kfs do + local nc = open(w, kn.chunk) + leaf(w, C.NODE_ID, function() + w:u16le(id - 1) + end) + leaf(w, C.NODE_HDR, function() + w:cstring(kn.name) + w:u16le(0x4000) + w:u16le(0) + w:u16le(if kn.parent >= 0 then kn.parent else 0xFFFF) + end) + if kn.instance then + leaf(w, C.NODE_INSTANCE, function() + w:cstring(kn.instance :: string) + end) + end + if kn.chunk == 0xB002 then + leaf(w, C.NODE_PIVOT, function() + w:f32le(0) + w:f32le(0) + w:f32le(0) + end) + end + for _, tr in { { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } } do + local field = tr[1] :: string + local frames = kn.frames[field] + if frames then + writeTrack(w, tr[2] :: number, frames, kn.values[field], tr[3] :: number) + end + end + close(w, nc) + end + close(w, kf) + close(w, main) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write diff --git a/src/Formats/model/3ds/init.luau b/src/Formats/model/3ds/init.luau new file mode 100644 index 0000000..2e7b581 --- /dev/null +++ b/src/Formats/model/3ds/init.luau @@ -0,0 +1,100 @@ +--!strict +-- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the +-- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference +-- for transforms and conventions; no code ported) and lib3ds (layouts only). +-- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix, +-- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and +-- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials +-- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided, +-- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as +-- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset / +-- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the +-- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range), +-- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object, +-- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position / +-- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from +-- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects +-- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not +-- applied), the keyframer frame range. +-- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first +-- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural +-- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on +-- write), vertex colours / normals (3DS has neither; normals come from smoothing groups). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/3ds/Read") +local Build = require("@formats/model/3ds/Build") +local Write = require("@formats/model/3ds/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeDs = { + name = "3ds", + category = "model", + extensions = { "3ds" }, + mime = { "application/x-3ds", "image/x-3ds" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices) + flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention) + fps: number?, -- keyframer frames per second (default 30, 3ds Max's default) + maxVertices: number?, -- refuse more vertices in total (default 2^24) +} +export type EncodeOptions = { + flipV: boolean?, -- default true (the inverse of decode) + fps: number?, -- seconds -> keyframer frames (default 30) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeDs.sniff(r: Bytes.Reader): number + local h = r:peek(8) + if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then + return 0 + end + local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8) + local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216 + local child = c1 + c2 * 256 + if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then + return 0 + end + return if size == r.limit - r.pos then 0.95 else 0.7 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts) + if not raw then + return nil, Err.from(msg, at) + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene = pcall(Build.scene, raw, opts :: any) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeDs.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 ok, out, err = pcall(Write.encode, scene, opts :: any) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return ThreeDs diff --git a/tests/model/3ds.luau b/tests/model/3ds.luau new file mode 100644 index 0000000..52aeb63 --- /dev/null +++ b/tests/model/3ds.luau @@ -0,0 +1,602 @@ +-- model/3ds tests: assimp's 3DS test models (meshes, materials, textures, keyframer hierarchies, pivots, camera / +-- target / rotation animation, cameras, lights) and assimp's 3DS exporter output, against assimp (meshes, faces, +-- corners, materials, animations, cameras, lights, world bounds); the keyframer placing every mesh where its mesh +-- matrix says; round trips through our writer (world triangles, materials, textures, cameras, lights, sampled +-- animation) for the reference files and for glTF sample models; assimp reading our files like the originals +-- (3ds_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/3ds.py. +local T = require("@tests/T") +local F = require("@formats") +local ThreeDs = require("@formats/model/3ds") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/3ds_cases") +local Picks = require("@tests/gen/3ds_gltf") +local Xcheck = require("@tests/gen/3ds_xcheck") + +local t = T.suite("3ds") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return ThreeDs.decode(Bytes.reader(b), opts) +end + +t:eq(ThreeDs.name, "3ds", "name") +t:eq(ThreeDs.category, "model", "category") +t:check(ThreeDs.caps.decode and ThreeDs.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- placed primitives, triangles, corners +local function counts(scene: any): (number, number, number) + local prims, faces, corners = 0, 0, 0 + local seen = {} + for _, pl in S.flatten(scene) do + if not seen[pl.primitive] then + seen[pl.primitive] = true + prims += 1 + faces += pl.primitive.indices.count // 3 + corners += pl.primitive.indices.count + end + end + return prims, faces, corners +end + +local function noMaterial(scene: any): boolean + for _, m in scene.meshes do + for _, p in m.primitives do + if p.material == nil then + return true + end + end + end + return false +end + +-- assimp's default material: an existing grey untextured material named "*default*" is reused +local function defaultReused(scene: any): boolean + for _, m in scene.materials do + local c = m.baseColor + if string.find(string.lower(m.name or ""), "default", 1, true) and c[1] == c[2] and c[1] == c[3] and not m.baseColorTexture then + local x = m.extras["3ds"].maps + if next(x) == nil then + return true + end + end + end + return false +end + +-- world bounds: as they are, or under assimp's Z-up -> Y-up root rotation (x, z, -y) +local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean + local function eq(a: { number }, b: { number }): boolean + for k = 1, 3 do + if not near(a[k], want.min[k], eps) or not near(b[k], want.max[k], eps) then + return false + end + end + return true + end + return eq(lo, hi) or eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }) +end + +local function bstr(lo: any, hi: any): string + if not lo then + return "-" + end + return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +-- ------------------------------------------------------------------------------------------------ reference files +-- assimp ignores the camera / light frame of their children (CameraRollAnimWithChildObject: a box linked to the +-- camera); our bounds follow the mesh matrices there (checked below) +local ASSIMP_BOUNDS_DIFFER = { ["assimp/models/CameraRollAnimWithChildObject.3ds"] = true } +local function boundsDiffer(i: number): boolean + return ASSIMP_BOUNDS_DIFFER[Cases[i].name] == true +end +local scenes = {} +local checked = 0 +for i, c in Cases do + local scene, err = decode(c.data) + local a = c.assimp + if a.failed then + t:note("%s: assimp rejects it; we read it: %s", c.name, tostring(scene ~= nil)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + if scene then + local prims, faces, corners = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)") + t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + local extra = if noMaterial(scene) and not defaultReused(scene) then 1 else 0 + t:eq(#scene.materials + extra, a.materials, c.name .. ": materials (assimp, + its default)") + if a.min and not ASSIMP_BOUNDS_DIFFER[c.name] then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsMatch(lo, hi, a, 1e-3), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " want " .. bstr(a.min, a.max)) + end + checked += 1 + end + end +end +t:note("%d files against assimp", checked) + +-- the keyframer places every mesh where its mesh matrix put the stored (world space) vertices +do + local n = 0 + for i, c in Cases do + local scene = scenes[i] + if scene and scene.meta.source.keyframer and #scene.animations == 0 and string.sub(c.name, 1, 7) == "assimp/" then + local raw = decode(c.data, { normals = false }) + local flat = decode(c.data, { normals = false }) + -- the file's vertices: the meshes placed at identity (Read only; via the writer-free path: raw bounds) + local lo, hi = MeshOps.bounds(MeshOps.merge(raw)) + local _ = flat + local Read = require("@formats/model/3ds/Read") + local parsed = Read.parse(buffer.fromstring(c.data), 0, #c.data) + local plo, phi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local placed: { [string]: boolean } = {} + for _, kn in parsed.keyframer.nodes do + if kn.kind == "object" then + placed[kn.name] = true + end + end + for _, o in parsed.objects do + if o.mesh and o.mesh.nf > 0 and placed[o.name] then + for v = 0, o.mesh.nv - 1 do + for k = 1, 3 do + local x = buffer.readf32(o.mesh.positions, (v * 3 + k - 1) * 4) + plo[k], phi[k] = math.min(plo[k], x), math.max(phi[k], x) + end + end + end + end + if lo and plo[1] <= phi[1] then + local ok = true + for k = 1, 3 do + ok = ok and near(lo[k], plo[k], 2e-3) and near(hi[k], phi[k], 2e-3) + end + t:check(ok, c.name .. ": keyframer world bounds = the stored vertices " .. bstr(lo, hi) .. " / " .. bstr(plo, phi)) + n += 1 + end + end + end + t:note("%d keyframer scenes match their stored vertices", n) +end + +-- ------------------------------------------------------------------------------------------------ round trips +local function triArea(prim: any): number + local P = S.reader(prim.attributes.POSITION) :: any + local I = S.reader(prim.indices) :: any + local area = 0 + for tri = 0, prim.indices.count // 3 - 1 do + local a, b, c = I(tri * 3, 0), I(tri * 3 + 1, 0), I(tri * 3 + 2, 0) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- the world matrices of the nodes with a camera / light, in tree order +local function worldOf(s: any, field: string): { { number } } + local out = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local w = S.mul(parent, S.nodeMatrix(n)) + if n[field] then + table.insert(out, { w = w, item = n[field] }) + end + for _, c in n.children do + visit(c, w) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + return out +end + +-- channel value at a time (LINEAR / STEP; quaternions lerped the short way) +local function evalCh(ch: any, time: number, comps: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + if ch.interpolation == "STEP" or t1 <= t0 then + return if time >= t1 then v(k + 1) else v(k) + end + local u = (time - t0) / (t1 - t0) + local a0, a1 = v(k), v(k + 1) + if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + return r + end + end + return v(n - 1) +end + +-- the world matrix of every named node at a time (animations[1] applied) +local function posed(s: any, time: number): { [string]: { number } } + local byNode: { [number]: { [string]: any } } = {} + local anim = s.animations[1] + if anim then + for _, ch in anim.channels do + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + end + local out = {} + local count: { [string]: number } = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local m + local chs = byNode[i] + if chs then + local tr = if chs.translation then evalCh(chs.translation, time, 3) else (n.translation or { 0, 0, 0 }) + local r = if chs.rotation then evalCh(chs.rotation, time, 4) else (n.rotation or { 0, 0, 0, 1 }) + local sc = if chs.scale then evalCh(chs.scale, time, 3) else (n.scale or { 1, 1, 1 }) + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + local Mat4 = require("@formats/codecs/model/Mat4") + m = Mat4.compose(tr, r, sc) + else + m = S.nodeMatrix(n) + end + local w = S.mul(parent, m) + local key = if n.mesh then "mesh" .. n.mesh elseif n.camera then "camera" else if n.light then "light" else nil + if key then + count[key] = (count[key] or 0) + 1 + out[key .. "#" .. count[key]] = w + end + for _, c in n.children do + visit(c, w) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + return out +end + +local function compare(a: any, b: any, label: string, eps: number, animTimes: { number }?) + local ma, mb = MeshOps.merge(a), MeshOps.merge(b) + local na = if ma and ma.indices then ma.indices.count // 3 else 0 + local nb = if mb and mb.indices then mb.indices.count // 3 else 0 + t:eq(nb, na, label .. ": triangles") + if na > 0 and nb > 0 then + t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb))) + local la, ha = MeshOps.bounds(ma) + local lb, hb = MeshOps.bounds(mb) + local ok = true + for k = 1, 3 do + ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps) + end + t:check(ok, label .. ": bounds " .. bstr(la, ha) .. " / " .. bstr(lb, hb)) + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + t:check(m.doubleSided == m2.doubleSided, label .. ": material " .. k .. " two-sided") + end + end + for _, field in { "camera", "light" } do + local pa, pb = worldOf(a, field), worldOf(b, field) + t:eq(#pb, #pa, label .. ": " .. field .. " nodes") + for k, e in pa do + local w = e.w + local w2 = pb[k] and pb[k].w + local ok = w2 ~= nil + if w2 then + -- position and view axis (3DS cameras and lights carry no scale) + for _, q in { 13, 14, 15 } do + ok = ok and near(w[q], w2[q], 1e-4) + end + if field == "camera" or a.lights[e.item].type ~= "point" then + local function z(m: { number }): (number, number, number) + local l = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + return m[9] / l, m[10] / l, m[11] / l + end + local x1, y1, z1 = z(w) + local x2, y2, z2 = z(w2) + ok = ok and x1 * x2 + y1 * y2 + z1 * z2 > 0.9999 + end + end + t:check(ok, label .. ": " .. field .. " " .. k .. " placement") + end + end + -- the horizontal field of view (3DS stores a lens, not the aspect) + for k, c in a.cameras do + local c2 = b.cameras[k] + if c2 and c.type == "perspective" then + local function hfov(cam: any): number + return 2 * math.atan(math.tan(cam.yfov / 2) * (cam.aspect or 4 / 3)) + end + t:check(near(hfov(c), hfov(c2), 1e-5), label .. ": camera " .. k .. " fov") + end + end + -- one timeline: the first animation's node transforms + local trs = false + for _, ch in (if a.animations[1] then a.animations[1].channels else {}) :: { any } do + trs = trs or ch.path ~= "weights" + end + t:eq(#b.animations, if trs then 1 else 0, label .. ": animations") + if animTimes and #a.animations > 0 then + local bad, n = 0, 0 + for _, time in animTimes do + local pa, pb = posed(a, time), posed(b, time) + for nm, w in pa do + local w2 = pb[nm] + if w2 then + for q = 1, 16 do + if not near(w[q], w2[q], 2e-3) then + bad += 1 + end + end + n += 1 + end + end + end + t:check(bad == 0 and n > 0, string.format("%s: posed world matrices: %d values of %d nodes x times differ", label, bad, n)) + end +end + +local TIMES = { 0, 0.1, 0.5, 1, 1.5, 2, 3.3, 5, 8 } +local nrt = 0 +for i, c in Cases do + local scene = scenes[i] + if scene then + local out, err = ThreeDs.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name, 1e-4, TIMES) + local p1, f1 = counts(scene) + local p2, f2 = counts(back) + t:check(p1 == p2 and f1 == f2, c.name .. ": primitives and faces kept") + -- the smoothing groups come back, so the normals do + local same = true + for mi, m in scene.meshes do + local m2 = back.meshes[mi] + for pi, p in m.primitives do + local p2 = m2 and m2.primitives[pi] + if not p2 or p2.attributes.POSITION.count ~= p.attributes.POSITION.count then + same = false + end + end + end + t:check(same, c.name .. ": vertex splits (smoothing groups) kept") + end + nrt += 1 + end +end + +-- glTF sample models through 3DS +local gltfScenes = {} +local ng = 0 +for gi, g in Picks do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + gltfScenes[gi] = scene + local out, err = ThreeDs.encode(scene, { fps = 1000 }) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer, { fps = 1000 }) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + -- skins and morph targets are not 3DS; STEP / CUBICSPLINE keys become linear + local linear = true + for _, an in scene.animations do + for _, ch in an.channels do + if ch.interpolation ~= "LINEAR" or ch.path == "weights" then + linear = false + end + end + end + compare(scene, back, "glTF " .. g.name, 2e-4, if linear and #scene.skins == 0 then TIMES else nil) + ng += 1 + end + end +end +t:note("%d reference files and %d glTF models through our writer and back", nrt, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +-- assimp reads our files like the originals +local nx = 0 +for _, x in Xcheck do + local a = x.assimp + t:check(not a.failed, x.name .. ": assimp reads our file") + if not a.failed then + local scene, want + if x.case then + scene, want = scenes[x.case], Cases[x.case].assimp + else + scene = gltfScenes[x.gltf] + end + if scene then + local _, faces, corners = counts(scene) + t:eq(a.faces, faces, x.name .. ": assimp faces of our file") + t:eq(a.vertices, corners, x.name .. ": assimp corners of our file") + t:eq(a.cameras, #worldOf(scene, "camera"), x.name .. ": assimp cameras of our file") + t:eq(a.lights, #worldOf(scene, "light"), x.name .. ": assimp lights of our file") + if want and not want.failed then + t:eq(a.meshes, want.meshes, x.name .. ": assimp meshes of our file") + t:eq(a.animations, want.animations, x.name .. ": assimp animations of our file") + end + if a.min and not (x.case and boundsDiffer(x.case)) then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsMatch(lo, hi, a, 1e-3), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + nx += 1 + end + end +end +t:note("%d of our files read back by assimp", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local tex = byName["assimp/models/cube_with_diffuse_texture.3DS"] + if tex then + local m = tex.materials[1] + t:check(m.baseColorTexture and tex.textures[m.baseColorTexture.texture].uri ~= nil, "diffuse map -> baseColorTexture with a uri") + t:check(tex.textures[1].data == nil, "texture files are not read") + t:check(tex.meshes[1].primitives[1].attributes.TEXCOORD_0 ~= nil and tex.meshes[1].primitives[1].attributes.NORMAL ~= nil, "uvs and normals") + t:eq(tex.meta.up, "z", "3DS is Z up") + end + local spec = byName["assimp/models/cube_with_specular_texture.3DS"] + if spec then + t:check(spec.materials[1].extras["3ds"].maps.specular ~= nil, "specular map kept in extras") + end + local alpha = byName["assimp/models/cubes_with_alpha.3DS"] + if alpha then + local blended = 0 + for _, m in alpha.materials do + if m.alphaMode == "blend" and m.baseColor[4] < 1 then + blended += 1 + end + end + t:check(blended > 0, "transparency -> alpha " .. blended) + end + local cam = byName["assimp/models/CameraRollAnim.3ds"] + if cam then + local c = cam.cameras[1] + -- 2400 / 53.33 mm = 45 degrees horizontal at 4:3 + t:check(near(2 * math.atan(math.tan(c.yfov / 2) * c.aspect), math.rad(45), 1e-4), "camera lens -> fov " .. math.deg(c.yfov)) + local paths = {} + for _, ch in cam.animations[1].channels do + paths[ch.path] = true + end + t:check(paths.rotation, "camera roll -> a rotation channel") + end + local child = byName["assimp/models/CameraRollAnimWithChildObject.3ds"] + if child then + local camNode + for _, n in child.nodes do + if n.camera then + camNode = n + end + end + t:check(camNode and #camNode.children == 1 and child.nodes[camNode.children[1]].name == "Box02", "a box linked to the camera") + end + local spin = byName["assimp/models/RotatingCube.3DS"] + if spin then + local ch = spin.animations[1].channels[1] + t:check(ch.path == "rotation" and ch.input.count > 100, "rotation keys accumulated: " .. ch.input.count) + end + local pyr = byName["assimp/models-nonbsd/pyramob.3DS"] + if pyr then + local types = {} + for _, l in pyr.lights do + types[l.type] = true + end + t:check(types.point and types.spot, "omni and spot lights") + end + -- the api + local s = F.load(Cases[1].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "3ds", "F.load detects 3DS") + local viaApi = F.save(s, nil, { format = "3ds" }) + t:check(viaApi and buffer.readu16(viaApi, 0) == 0x4D4D, "F.save format 3ds") + -- normals = false keeps the file's vertices + local raw = decode(Cases[1].data, { normals = false }) + t:check(raw and raw.meshes[1].primitives[1].attributes.NORMAL == nil, "normals = false") + -- a hand-made scene: two instances of one mesh, a texture without uri goes to opts.files + local p = S.accessor(nil, "f32", 3, 3) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local uv = S.accessor(nil, "f32", 2, 3) + local tri = S.fromPrimitive({ attributes = { POSITION = p, TEXCOORD_0 = uv }, mode = "triangles", material = 1 }, "tri") + tri.materials[1] = S.material("red") + tri.materials[1].baseColor = { 1, 0, 0, 1 } + tri.materials[1].baseColorTexture = { texture = 1 } + tri.textures[1] = { data = buffer.fromstring("\137PNG"), mime = "image/png" } + tri.nodes[2] = { name = "copy", children = {}, mesh = 1, translation = { 5, 0, 0 } } + table.insert(tri.roots, 2) + local files = {} + local out = ThreeDs.encode(tri, { name = "tri.3ds", files = files }) :: buffer + t:check(files["tri_1.png"] ~= nil, "embedded texture bytes -> opts.files") + local back = decode(out) + t:check(back and #back.meshes == 1 and #back.nodes == 2 and back.nodes[2].mesh == 1, "instances share one mesh") + t:eq(back.textures[1].uri, "tri_1.png", "the texture's file name") + local lo, hi = MeshOps.bounds(MeshOps.merge(back)) + t:check(lo[1] == 0 and hi[1] == 6, "the instance stands at x = 5") + t:eq(back.nodes[2].name, "copy", "instance name") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local empty = decode("MM\6\0\0\0") + t:check(empty and #empty.meshes == 0 and #empty.nodes == 0, "an empty main chunk: an empty scene") + local data = Cases[1].data + local _, e2 = decode(string.sub(data, 1, #data // 2)) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2)) + local _, e3 = decode("not a 3ds file at all") + t:check(e3 and e3.code == Err.CORRUPT, "garbage: " .. tostring(e3)) + local _, e4 = decode(data, { maxVertices = 3 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = ThreeDs.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + t:check(ThreeDs.sniff(Bytes.reader(buffer.fromstring(data))) > 0.5, "sniff") + t:eq(ThreeDs.sniff(Bytes.reader(buffer.fromstring("MM junk junk junk"))), 0, "sniff junk") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for i, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = ThreeDs.decode(Bytes.reader(b)) + if s then + ThreeDs.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 6 }) +end + +t:done() diff --git a/tools/fixtures/3ds.py b/tools/fixtures/3ds.py new file mode 100644 index 0000000..0a6c271 --- /dev/null +++ b/tools/fixtures/3ds.py @@ -0,0 +1,101 @@ +# 3DS fixtures (tools/fixtures.py): assimp's 3DS test models (test/models/3DS and test/models-nonbsd/3DS: meshes, +# materials, textures, keyframer hierarchies, pivots, rotation / camera / target animation, cameras, lights; read from +# the nixpkgs assimp source, never committed) and files written by assimp's 3DS exporter from glTF sample models, with +# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, cameras, lights, +# nodes; world bounds from its PreTransformVertices export). Then our encoder's output (tools/fixtures/_3ds_encode.luau, +# from every case and the glTF models) read back by assimp. (Blender 5's 3DS importer is an extension that is not +# installed by default, so assimp is the only reference.) +# tests/gen/3ds_cases.luau { name, data, assimp } +# tests/gen/3ds_gltf.luau glTF sample models for the writer round trips: { name, data, files } +# tests/gen/3ds_xcheck.luau { name, case? | gltf?, assimp } +import importlib.util, os + +INPUTS = ["src/Formats/model/3ds", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/_3ds_encode.luau"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +GLTF = ("Box", "BoxTextured", "BoxVertexColors", "Cameras", "SimpleMeshes", "RiggedSimple", "SimpleSkin", "MultiUVTest", + "NegativeScaleTest", "PointLightIntensityTest", "AnimatedTriangle", "TextureCoordinateTest", "TextureTransformTest", + "InterpolationTest", "LightVisibility") + + +def reference(ctx, M, X, paths, tmp): + out = [] + for p, a in zip(paths, M.assimp_info(ctx, paths, raw=True)): + a.update(X.assimp_extra(ctx, p)) + a.pop("min", None) + a.pop("max", None) + a.pop("perMesh", None) + if not a.get("failed"): + a.update(X.ptv_bounds(ctx, p, tmp)) + out.append(a) + return out + + +def generate(ctx): + M = load(ctx, "_model_ref") + X = load(ctx, "fbx") + tmp = M.tempdir() + src = X.assimp_src(ctx) + cases = [] + for sub in ("models", "models-nonbsd"): + d = os.path.join(src, "test", sub, "3DS") + for f in sorted(os.listdir(d)): + if f.lower().endswith(".3ds"): + cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f)}) + # assimp's exporter + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if not mains: + continue + main = os.path.join(d, mains[0]) + picks.append({"name": model + "/" + variant, "data": open(main, "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + out = os.path.join(tmp, model + ".3ds") + try: + ctx.nix("assimp", ["assimp", "export", main, out, "-f3ds"]) + cases.append({"name": "assimp-export/" + model + ".3ds", "path": out}) + except Exception: + pass + break + refs = reference(ctx, M, X, [c["path"] for c in cases], tmp) + for c, a in zip(cases, refs): + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("3ds_cases", cases) + ctx.emit("3ds_gltf", picks) + + # assimp reads our files + ours = M.luau_encode(ctx, "tools/fixtures/_3ds_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".3ds")) + paths = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + paths.append(p) + xs = [] + for n, a in zip(names, reference(ctx, M, X, paths, xtmp)): + kind, idx = n[:-4].split("_") + e = {"name": n, "assimp": a} + e["case" if kind == "case" else "gltf"] = int(idx) + xs.append(e) + ctx.emit("3ds_xcheck", xs) diff --git a/tools/fixtures/_3ds_encode.luau b/tools/fixtures/_3ds_encode.luau new file mode 100644 index 0000000..98b3b95 --- /dev/null +++ b/tools/fixtures/_3ds_encode.luau @@ -0,0 +1,44 @@ +-- tools/fixtures/_3ds_encode: run by tools/fixtures/3ds.py (luau CLI, repo root): decodes every 3DS case and every +-- glTF sample model with our readers and writes them with our 3DS writer, printing "\t" lines for assimp +-- to read back. Files: case_.3ds, gltf_.3ds. +local ThreeDs = require("@formats/model/3ds") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/3ds_cases") +local Picks = require("@tests/gen/3ds_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function emit(name: string, scene: any) + local out, err = ThreeDs.encode(scene) + if out then + print(name .. "\t" .. hex(out)) + else + print("encode failed " .. name .. ": " .. tostring(err)) + end +end + +for i, c in Cases do + local scene, err = ThreeDs.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + emit(string.format("case_%d.3ds", i), scene) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end +for i, g in Picks do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + if scene then + emit(string.format("gltf_%d.3ds", i), scene) + end +end From 8e3873c9fbafbe45d7330de528a1df47b45ebb75 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:20:17 -0500 Subject: [PATCH 16/54] codecs/video/Legacy: Cinepak, Microsoft Video 1, QuickTime RLE / SMC and FLIC decoders Registry decoders (codecs/video/Video BUILTIN: cvid, CRAM / MSVC / WHAM, 'rle ', 'smc ', AFLC), rgba8 pictures painted over the previous picture, palettes from track.palette (or packet.palette). Bit-exact with ffmpeg on 28 AVI / MOV / MKV fixtures (tools/fixtures/legacy.py: ffmpeg's encoders plus encoders in _legacy_mux.py for QuickTime RLE 1/2/4/8-bit, 8-bit MS Video 1 and Cinepak). Also fixes QtPalette's big-endian reads. --- docs/FORMATS.md | 1 + src/Formats/codecs/video/Legacy/Cinepak.luau | 303 ++++++++++++++ src/Formats/codecs/video/Legacy/Flic.luau | 372 +++++++++++++++++ src/Formats/codecs/video/Legacy/Msvideo1.luau | 121 ++++++ src/Formats/codecs/video/Legacy/Picture.luau | 115 ++++++ src/Formats/codecs/video/Legacy/QtRle.luau | 276 +++++++++++++ src/Formats/codecs/video/Legacy/Smc.luau | 183 +++++++++ src/Formats/codecs/video/Legacy/init.luau | 187 +++++++++ src/Formats/codecs/video/Video/init.luau | 14 + src/Formats/containers/IsoBmff/QtPalette.luau | 9 +- src/Formats/video/mkv/Parse.luau | 5 +- tests/codecs/legacy.luau | 113 ++++++ tools/fixtures/_legacy_mux.py | 375 ++++++++++++++++++ tools/fixtures/legacy.py | 100 +++++ 14 files changed, 2171 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Cinepak.luau create mode 100644 src/Formats/codecs/video/Legacy/Flic.luau create mode 100644 src/Formats/codecs/video/Legacy/Msvideo1.luau create mode 100644 src/Formats/codecs/video/Legacy/Picture.luau create mode 100644 src/Formats/codecs/video/Legacy/QtRle.luau create mode 100644 src/Formats/codecs/video/Legacy/Smc.luau create mode 100644 src/Formats/codecs/video/Legacy/init.luau create mode 100644 tests/codecs/legacy.luau create mode 100644 tools/fixtures/_legacy_mux.py create mode 100644 tools/fixtures/legacy.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..b7c26a7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -133,5 +133,6 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the + - codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Legacy/Cinepak.luau b/src/Formats/codecs/video/Legacy/Cinepak.luau new file mode 100644 index 0000000..a7ed8d9 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Cinepak.luau @@ -0,0 +1,303 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 +-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description +-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 +-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame +-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are +-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra +-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak +-- decoder. Never throws: every read is range-checked against its chunk. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 +local band = bit32.band + +local Cinepak = {} + +local MAX_STRIPS = 32 +-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index) +local ENTRY = 16 +local BOOK = 256 * ENTRY + +export type State = { + books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip) + filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet) +} + +function Cinepak.state(): State + return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 } +end + +local function be16(d: buffer, o: number): number + return readu8(d, o) * 256 + readu8(d, o + 1) +end +local function be24(d: buffer, o: number): number + return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2) +end +local function be32(d: buffer, o: number): number + return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3) +end + +local function clip(v: number): number + return if v < 0 then 0 elseif v > 255 then 255 else v +end + +-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set +local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number) + local six = band(id, 4) == 0 + local partial = band(id, 1) ~= 0 + local size = if six then 6 else 4 + local flag, mask = 0, 0 + for i = 0, 255 do + if partial then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + end + if not partial or band(flag, mask) ~= 0 then + if p + size > stop then + return + end + local e = book + i * ENTRY + local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3) + if six then + local u, v = readu8(d, p + 4), readu8(d, p + 5) + if u >= 128 then + u -= 256 + end + if v >= 128 then + v -= 256 + end + local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero) + local dr, dg, db = 2 * v, -uh - v, 2 * u + writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000) + writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000) + writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000) + writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000) + else + writeu32(books, e, y0 * 0x10101 + 0xFF000000) + writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000) + writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000) + writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000) + end + p += size + end + end +end + +-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data +local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, + stop: number, x1: number, y1: number, x2: number, y2: number): boolean + local stride = pic.stride + local pal = pic.idx + local px = (pal or pic.rgba) :: buffer + local flag, mask = 0, 0 + local inter = band(id, 1) ~= 0 + local v1only = band(id, 2) ~= 0 + for y = y1, y2 - 1, 4 do + for x = x1, x2 - 1, 4 do + local paint = true + if inter then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + paint = band(flag, mask) ~= 0 + end + if paint then + local useV1 = v1only + if not v1only then + mask //= 2 + if mask == 0 then + if p + 4 > stop then + return false + end + flag = be32(d, p) + p += 4 + mask = 0x80000000 + end + useV1 = band(flag, mask) == 0 + end + local o = y * stride + x + if useV1 then + if p >= stop then + return false + end + local e = v1 + readu8(d, p) * ENTRY + p += 1 + -- each of the 4 entries fills a 2x2 square + local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12) + if pal then + a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256 + writeu32(px, o, a * 0x0101 + b * 0x01010000) + writeu32(px, o + stride, a * 0x0101 + b * 0x01010000) + writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000) + writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000) + else + for r = 0, 3 do + local q = (o + r * stride) * 4 + local l, rr = if r < 2 then a else c, if r < 2 then b else e4 + writeu32(px, q, l) + writeu32(px, q + 4, l) + writeu32(px, q + 8, rr) + writeu32(px, q + 12, rr) + end + end + else + if p + 4 > stop then + return false + end + local e0 = v4 + readu8(d, p) * ENTRY + local e1 = v4 + readu8(d, p + 1) * ENTRY + local e2 = v4 + readu8(d, p + 2) * ENTRY + local e3 = v4 + readu8(d, p + 3) * ENTRY + p += 4 + -- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right) + if pal then + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = o + r * stride + writeu8(px, q, readu8(books, l + off)) + writeu8(px, q + 1, readu8(books, l + off + 4)) + writeu8(px, q + 2, readu8(books, rr + off)) + writeu8(px, q + 3, readu8(books, rr + off + 4)) + end + else + for r = 0, 3 do + local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3 + local off = (r % 2) * 8 + local q = (o + r * stride) * 4 + writeu32(px, q, readu32(books, l + off)) + writeu32(px, q + 4, readu32(books, l + off + 4)) + writeu32(px, q + 8, readu32(books, rr + off)) + writeu32(px, q + 12, readu32(books, rr + off + 4)) + end + end + end + end + end + end + return true +end + +-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this +-- packet (an empty frame); false + message = an error +function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) + local n = buffer.len(d) + if n < 10 then + return false, "frame too short" + end + local strips = be16(d, 8) + if strips == 0 and not (pic.idx and newPalette) then + return false, nil + end + local size = be24(d, 1) + if n < size * 5 // 100 then + return false, "frame shorter than its header says" + end + if st.filmSkip < 0 then + if size == 0 then + return false, "unsupported: a zero frame size" + end + if size ~= n and n % size ~= 0 then + if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6 + and readu8(d, 14) == 0 and readu8(d, 15) == 0 then + st.filmSkip = 6 + else + st.filmSkip = 2 + end + else + st.filmSkip = 0 + end + end + local skip = st.filmSkip + if n < 10 + skip + strips * 12 then + return false, "truncated strip headers" + end + if strips > 0 then + local ss = be24(d, 10 + skip + 1) + if ss < 12 or ss > size then + return false, "bad strip size" + end + end + local flags = readu8(d, 0) + local p = 10 + skip + strips = math.min(strips, MAX_STRIPS) + local books = st.books + -- the coded area: the size rounded up to whole blocks (the picture's plane) + local cw, ch = pic.stride, pic.rows + local y0 = 0 + for i = 0, strips - 1 do + if p + 12 > n then + return true, nil + end + local sy1 = be16(d, p + 4) + local sx1 = be16(d, p + 6) + local sy2, sx2 = be16(d, p + 8), be16(d, p + 10) + if sy1 == 0 then + sy1 = y0 + sy2 = y0 + sy2 + end + local ssize = be24(d, p + 1) - 12 + if ssize < 0 then + return true, nil + end + p += 12 + local stop = math.min(n, p + ssize) + local v4 = i * 2 * BOOK + local v1 = v4 + BOOK + if i > 0 and band(flags, 1) == 0 then + buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) + end + -- the strip's chunks: codebooks, then one vector chunk + -- (strips start on block boundaries in every known stream: the plane holds whole blocks only) + if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then + return true, nil + end + local q = p + local done = false + while q + 4 <= stop do + local id = readu8(d, q) + local csize = be24(d, q + 1) - 4 + if csize < 0 then + return true, nil + end + q += 4 + local cstop = math.min(stop, q + csize) + if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then + codebook(books, v4, id, d, q, cstop) + elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then + codebook(books, v1, id, d, q, cstop) + elseif id == 0x30 or id == 0x31 or id == 0x32 then + if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then + return true, nil + end + done = true + break + end + q = cstop + end + if not done then + return true, nil + end + p = stop + y0 = sy2 + end + return true, nil +end + +return Cinepak diff --git a/src/Formats/codecs/video/Legacy/Flic.luau b/src/Formats/codecs/video/Legacy/Flic.luau new file mode 100644 index 0000000..99c72f7 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Flic.luau @@ -0,0 +1,372 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is +-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's +-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit +-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK +-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX +-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); +-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet +-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames. +-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture). +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local bfill = buffer.fill + +local Flic = {} + +-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette +export type State = { + pic: Picture.Picture, + depth: number, -- 8, 15, 16, 24 + bpp: number, -- bytes per pixel +} + +-- state(w, h, depth) -> State | nil, message +function Flic.state(w: number, h: number, depth: number): (State?, string?) + local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 + if bpp == 0 then + return nil, "unsupported: " .. depth .. "-bit FLIC" + end + local pic = Picture.new(w * bpp, h, true) + pic.w = w + return { pic = pic, depth = depth, bpp = bpp }, nil +end + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- decode(st, data) -> true | false, message +function Flic.decode(st: State, d: buffer): (boolean, string?) + local pic = st.pic + local px = pic.idx :: buffer + local pal = pic.pal + local w, h = pic.w, pic.h + local bpp = st.bpp + local deep = bpp > 1 + local stride = pic.stride + local limit = stride * h + local n = buffer.len(d) + if n < 16 then + return false, "frame too short" + end + local p = 0 + local function u8(): number + local v = if p < n then readu8(d, p) else 0 + p += 1 + return v + end + local function u16(): number + local a = u8() + return a + u8() * 256 + end + local frameSize = math.min(readu32(d, 0), n) + local chunks = readu8(d, 6) + readu8(d, 7) * 256 + if frameSize < 16 then + return false, "bad frame size" + end + frameSize -= 16 + p = 16 + while frameSize >= 6 and chunks > 0 and n - p >= 4 do + local size = readu32(d, p) + if size > frameSize then + size = frameSize + end + local after = p + size + p += 4 + local typ = u16() + if typ == 4 or typ == 11 then + if not deep then + -- palette packets: skip count, change count (0 = 256), r g b + local shift = typ == 11 + local packets = u16() + local at = 0 + for _ = 1, packets do + at += u8() + local count = u8() + if count == 0 then + count = 256 + end + if p + count * 3 > after then + break + end + for _ = 1, count do + if at >= 256 then + at = 0 + end + local r, g, b = u8(), u8(), u8() + if shift then + -- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below + r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256 + r, g, b = r + r // 64, g + g // 64, b + b // 64 + end + writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000) + at += 1 + end + end + end + elseif typ == 7 or (deep and typ == 27) then + -- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode) + local y = 0 + local lines = u16() + while lines > 0 do + if p + 2 > after then + break + end + if y > limit then + return false, "delta past the picture" + end + local lp = u16() + if lp >= 0x8000 then + lp -= 0x10000 + end + if deep then + if lp < 0 then + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + end + elseif lp < 0 and lp >= -0x4000 then + -- 0xC000 .. 0xFFFF: skip lines + if -lp > h then + return false, "bad line skip" + end + y += -lp * stride + continue + elseif lp < 0 then + -- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its + -- padded row instead: the same pixel when rows are not padded) + local q = y + w - 1 + if q < 0 or q >= limit then + return false, "delta past the picture" + end + writeu8(px, q, lp % 256) + continue + elseif lp >= 0x4000 then + continue -- undefined opcode + end + lines -= 1 + local q = y + for _ = 1, lp do + if p + 2 > after then + break + end + q += u8() * bpp + local run = s8(u8()) + if deep then + local cnt = if run < 0 then -run else run + if q + cnt * bpp > limit then + return false, "delta past the picture" + end + if run < 0 then + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + else + if p + cnt * bpp > after then + break + end + buffer.copy(px, q, d, p, cnt * bpp) + p += cnt * bpp + q += cnt * bpp + end + elseif run < 0 then + local cnt = -run + local a, b = u8(), u8() + if q + cnt * 2 > limit then + return false, "delta past the picture" + end + for _ = 1, cnt do + writeu8(px, q, a) + writeu8(px, q + 1, b) + q += 2 + end + else + if q + run * 2 > limit then + return false, "delta past the picture" + end + if p + run * 2 > after then + break + end + buffer.copy(px, q, d, p, run * 2) + p += run * 2 + q += run * 2 + end + end + y += stride + end + elseif typ == 12 and not deep then + -- byte-oriented delta (LC): first line, line count, per line packets of (skip, run) + local first = u16() + if first >= h then + return false, "bad first line" + end + local y = first * stride + local lines = u16() + while lines > 0 do + local q = y + if q > limit then + return false, "delta past the picture" + end + if p + 1 > after then + break + end + local packets = u8() + for _ = 1, packets do + if p + 1 > after then + break + end + q += u8() + local run = s8(u8()) + if run > 0 then + if q + run > limit then + return false, "delta past the picture" + end + if p + run > after then + break + end + buffer.copy(px, q, d, p, run) + p += run + q += run + elseif run < 0 then + local v = u8() + if q - run > limit then + return false, "delta past the picture" + end + bfill(px, q, v, -run) + q -= run + end + end + y += stride + lines -= 1 + end + elseif typ == 13 then + bfill(px, 0, 0, limit) + elseif typ == 15 or (deep and typ == 25) then + -- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals + local unit = if typ == 25 then bpp else 1 + local y = 0 + for _ = 1, h do + local q = y + p += 1 -- the packet count (unused) + local left = if typ == 25 then w else w * bpp + while left > 0 do + if p + 1 > after then + break + end + local run = s8(u8()) + if run == 0 and not deep then + return false, "zero byte run" + end + if run > 0 then + if q + run * unit > limit then + return false, "run past the picture" + end + if unit == 1 then + bfill(px, q, u8(), run) + q += run + else + local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0 + for _ = 1, run do + writeu8(px, q, a) + writeu8(px, q + 1, b) + if bpp == 3 then + writeu8(px, q + 2, c) + end + q += bpp + end + end + left -= run + else + local cnt = -run + if q + cnt * unit > limit then + return false, "run past the picture" + end + if p + cnt * unit > after then + break + end + buffer.copy(px, q, d, p, cnt * unit) + p += cnt * unit + q += cnt * unit + left -= cnt + end + end + y += stride + end + elseif typ == 16 or (deep and typ == 26) then + -- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more) + local row = w * bpp + local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4 + local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h + if ok then + if deep and n - p < row * h then + return false, "truncated copy chunk" + end + for y = 0, h - 1 do + local s = p + y * padded + local cnt = math.max(0, math.min(row, n - s)) + if cnt > 0 then + buffer.copy(px, y * stride, d, s, cnt) + end + end + p += padded * h + end + end + -- typ 18 (PSTAMP) and unknown chunks are skipped + if after - p >= 0 then + p = after + else + break + end + frameSize -= size + chunks -= 1 + end + return true, nil +end + +-- image(st) -> a fresh rgba8 Image +function Flic.image(st: State): Types.Image + local pic = st.pic + if st.bpp == 1 then + return Picture.image(pic) + end + local w, h = pic.w, pic.h + local img = Types.Image.new(w, h, "rgba8") + local out = img.pixels + local px = pic.idx :: buffer + local stride = pic.stride + if st.bpp == 3 then + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 3 + writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000) + end + end + else + local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565() + local mask = if st.depth == 15 then 32768 else 65536 + for y = 0, h - 1 do + local s, o = y * stride, y * w * 4 + for x = 0, w - 1 do + local q = s + x * 2 + writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4)) + end + end + end + return img +end + +return Flic diff --git a/src/Formats/codecs/video/Legacy/Msvideo1.luau b/src/Formats/codecs/video/Legacy/Msvideo1.luau new file mode 100644 index 0000000..417ad45 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Msvideo1.luau @@ -0,0 +1,121 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit +-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows +-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour +-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour +-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture. +-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band = bit32.band + +local Msvideo1 = {} + +-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 +-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)] +local function quadrant(x: number, y: number): number + return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) +end + +-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit) +function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) + local n = buffer.len(d) + local bw, bh = pic.w // 4, pic.h // 4 + if n < bw * bh // 512 then + return false, "frame too small" + end + local stride = pic.stride + local total = bw * bh + local skip = 0 + local p = 0 + local wide = bits ~= 8 + local px = (if wide then pic.rgba else pic.idx) :: buffer + local lut = if wide then Picture.rgb555() else nil + local c = table.create(8, 0) + for by = bh - 1, 0, -1 do + for bx = 0, bw - 1 do + if skip ~= 0 then + skip -= 1 + total -= 1 + continue + end + if p + 2 > n then + return true, nil + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + if a == 0 and b == 0 and total == 0 then + return true, nil + end + -- the block's bottom-left pixel; its rows go up + local o = (by * 4 + 3) * stride + bx * 4 + if band(b, 0xFC) == 0x84 then + skip = (b - 0x84) * 256 + a - 1 + elseif b < 0x80 or (not wide and b >= 0x90) then + local flags = b * 256 + a + local eight + if wide then + if p + 4 > n then + return true, nil + end + c[1], c[2] = readu16(d, p), readu16(d, p + 2) + p += 4 + eight = c[1] >= 0x8000 + if eight then + if p + 12 > n then + return true, nil + end + for k = 3, 8 do + c[k] = readu16(d, p) + p += 2 + end + end + else + eight = b >= 0x90 + local cnt = if eight then 8 else 2 + if p + cnt > n then + return true, nil + end + for k = 1, cnt do + c[k] = readu8(d, p) + p += 1 + end + end + for y = 0, 3 do + local row = o - y * stride + for x = 0, 3 do + local k = (if band(flags, 1) == 1 then 1 else 2) + if eight then + k += quadrant(x, y) + end + flags = flags // 2 + if lut then + writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4)) + else + writeu8(px, row + x, c[k]) + end + end + end + else + local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a + for y = 0, 3 do + local row = o - y * stride + if lut then + for x = 0, 3 do + writeu32(px, (row + x) * 4, v) + end + else + writeu32(px, row, v * 0x01010101) + end + end + end + total -= 1 + end + end + return true, nil +end + +return Msvideo1 diff --git a/src/Formats/codecs/video/Legacy/Picture.luau b/src/Formats/codecs/video/Legacy/Picture.luau new file mode 100644 index 0000000..e4080c6 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Picture.luau @@ -0,0 +1,115 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame +-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, +-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past +-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication +-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in formats-luau. +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +local readu32, writeu32 = buffer.readu32, buffer.writeu32 + +local Picture = {} + +export type Picture = { + w: number, + h: number, + stride: number, -- index plane: bytes per row; rgba plane: pixels per row + rows: number, + idx: buffer?, -- u8 index plane, stride * rows bytes (palettised) + rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour) + pal: buffer, -- 256 u32 entries, bytes R, G, B, A +} + +-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...) +function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture + local pw, ph = padW or 1, padH or 1 + local stride = ((w + pw - 1) // pw) * pw + local rows = ((h + ph - 1) // ph) * ph + local pal = buffer.create(1024) + if palette and buffer.len(palette) >= 1024 then + buffer.copy(pal, 0, palette, 0, 1024) + end + local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal } + if palettised then + p.idx = buffer.create(stride * rows) + else + p.rgba = buffer.create(stride * rows * 4) + end + return p +end + +-- image(p) -> a fresh rgba8 Image of the visible w x h +function Picture.image(p: Picture): Types.Image + local w, h = p.w, p.h + local img = Types.Image.new(w, h, "rgba8") + local idx, rgba = p.idx, p.rgba + if idx then + Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal) + elseif rgba then + if p.stride == w then + buffer.copy(img.pixels, 0, rgba, 0, w * h * 4) + else + for y = 0, h - 1 do + buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4) + end + end + end + return img +end + +-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track +function Picture.setPalette(p: Picture, src: buffer) + if buffer.len(src) >= 1024 then + buffer.copy(p.pal, 0, src, 0, 1024) + end +end + +local lut555: buffer? = nil +local lut565: buffer? = nil + +-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries +function Picture.rgb555(): buffer + local t = lut555 + if t then + return t + end + local b = buffer.create(32768 * 4) + for v = 0, 32767 do + local r, g, bl = v // 1024, (v // 32) % 32, v % 32 + r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut555 = b + return b +end + +-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries +function Picture.rgb565(): buffer + local t = lut565 + if t then + return t + end + local b = buffer.create(65536 * 4) + for v = 0, 65535 do + local r, g, bl = v // 2048, (v // 32) % 64, v % 32 + r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4 + writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000) + end + lut565 = b + return b +end + +-- copy of a picture's plane (for decoders that read the previous picture while writing the next) +function Picture.clonePlane(p: Picture): buffer + local src = (p.idx or p.rgba) :: buffer + local c = buffer.create(buffer.len(src)) + buffer.copy(c, 0, src, 0) + return c +end + +local _ = readu32 + +return Picture diff --git a/src/Formats/codecs/video/Legacy/QtRle.luau b/src/Formats/codecs/video/Legacy/QtRle.luau new file mode 100644 index 0000000..2c687e8 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/QtRle.luau @@ -0,0 +1,276 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and +-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File +-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per +-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). +-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its +-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames +-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read +-- and write is range-checked (a damaged frame stops where the damage is). +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local QtRle = {} + +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line) +local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number) + row -= stride + local q = row + lines += 1 + while lines > 0 do + if p + 2 > n then + return + end + local skip = readu8(d, p) + local code = s8(readu8(d, p + 1)) + p += 2 + if code == 0 then + return + end + if skip >= 128 then + lines -= 1 + row += stride + q = row + 16 * (skip - 128) + else + q += 16 * skip + end + if q < 0 or q > limit then + return + end + if code ~= -1 then + if code < 0 then + local cnt = -code + if p + 2 > n or q + cnt * 16 > limit then + return + end + local a, b = readu8(d, p), readu8(d, p + 1) + p += 2 + for _ = 1, cnt do + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(b, k), 1)) + q += 1 + end + end + else + local cnt = code * 2 + if p + cnt > n or q + cnt * 8 > limit then + return + end + for _ = 1, cnt do + local a = readu8(d, p) + p += 1 + for k = 7, 0, -1 do + writeu8(px, q, band(rshift(a, k), 1)) + q += 1 + end + end + end + end + end +end + +-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups +local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) + local group = 32 // bpp -- pixels per 4 bytes + local per = 8 // bpp -- pixels per byte + local mask = 2 ^ bpp - 1 + for _ = 1, lines do + if p >= n then + return + end + local q = row + group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += group * (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + elseif code < 0 then + local cnt = -code + if p + 4 > n or q + cnt * group > limit then + return + end + if bpp == 8 then + local v = readu32(d, p) + for _ = 1, cnt do + writeu32(px, q, v) + q += 4 + end + else + local v0 = q + for b = 0, 3 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + for _ = 2, cnt do + buffer.copy(px, q, px, v0, group) + q += group + end + end + p += 4 + else + local bytes = code * 4 + if p + bytes > n or q + bytes * per > limit then + return + end + if bpp == 8 then + buffer.copy(px, q, d, p, bytes) + q += bytes + else + for b = 0, bytes - 1 do + local byte = readu8(d, p + b) + for k = per - 1, 0, -1 do + writeu8(px, q, band(rshift(byte, k * bpp), mask)) + q += 1 + end + end + end + p += bytes + end + end + row += stride + end +end + +-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels) +local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number) + local bpp = depth // 8 + local lut = if depth == 16 then Picture.rgb555() else nil + for _ = 1, lines do + if p >= n then + return + end + local q = row + (readu8(d, p) - 1) + p += 1 + if q < 0 or q > limit then + return + end + while true do + if p >= n then + return + end + local code = s8(readu8(d, p)) + p += 1 + if code == -1 then + break + end + if p >= n then + return + end + if code == 0 then + q += readu8(d, p) - 1 + p += 1 + if q < 0 or q > limit then + return + end + else + local cnt = if code < 0 then -code else code + local need = if code < 0 then bpp else bpp * cnt + if p + need > n or q + cnt > limit then + return + end + for _ = 1, cnt do + local v + if lut then + v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4) + elseif bpp == 3 then + v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000 + else + v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216 + end + writeu32(px, q * 4, v) + q += 1 + if code > 0 then + p += bpp + end + end + if code < 0 then + p += bpp + end + end + end + row += stride + end +end + +-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message +function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) + local n = buffer.len(d) + if n < 8 then + return true, nil -- no change + end + local p = 4 + local header = readu8(d, p) * 256 + readu8(d, p + 1) + p += 2 + local h = pic.h + local start, lines = 0, h + if band(header, 8) ~= 0 then + if n < 14 then + return true, nil + end + start = readu8(d, p) * 256 + readu8(d, p + 1) + lines = readu8(d, p + 4) * 256 + readu8(d, p + 5) + p += 8 + if lines > h - start then + return true, nil + end + end + local stride = pic.stride + local bits = if depth > 32 then depth - 32 else depth + local idx, rgba = pic.idx, pic.rgba + if idx and bits <= 8 then + local limit = stride * h + if bits == 1 then + decode1(idx, stride, limit, d, p, n, start * stride, lines) + else + decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits) + end + elseif rgba and (bits == 16 or bits == 24 or bits == 32) then + decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits) + else + return false, "unsupported: depth " .. depth + end + return true, nil +end + +-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs +function QtRle.palettised(depth: number): boolean + return depth <= 8 or depth > 32 +end +function QtRle.pad(depth: number): number + local bits = if depth > 32 then depth - 32 else depth + return if bits <= 8 then 32 // math.max(1, bits) else 1 +end + +return QtRle diff --git a/src/Formats/codecs/video/Legacy/Smc.luau b/src/Formats/codecs/video/Legacy/Smc.luau new file mode 100644 index 0000000..6ff9a60 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smc.luau @@ -0,0 +1,183 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description +-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble +-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour +-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index: +-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc +-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row +-- above). Never throws: reads past the data give zeros, the block count bounds every write. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smc = {} + +-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames) +function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) + local px = pic.idx :: buffer + local n = buffer.len(d) + local stride = pic.stride -- a multiple of 4: the plane holds whole blocks + local bh = pic.rows // 4 + local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4) + if total // 1024 > n then + return false, "frame too small" + end + local blocksWide = (pic.w + 3) // 4 + local p = 4 -- flags byte + 24-bit chunk size + -- block position: bx, by (blocks) + local bx, by = 0, 0 + local pairI, quadI, octI = 0, 0, 0 + -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) + local function u8(): number + if p < n then + local v = readu8(d, p) + p += 1 + return v + end + return 0 + end + local function advance() + bx += 1 + if bx >= blocksWide then + bx = 0 + by += 1 + end + total -= 1 + end + while total > 0 do + if p >= n then + return false, "truncated" + end + local op = readu8(d, p) + p += 1 + local kind = rshift(op, 4) + local count: number + if kind < 8 then + count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15) + else + count = band(op, 15) + 1 + end + if kind <= 1 then + for _ = 1, count do + if total <= 0 then + break + end + advance() + end + elseif kind <= 5 then + -- repeat the last block (2, 3) or the last pair of blocks (4, 5) + local pair = kind >= 4 + local back = if pair then 2 else 1 + local pos = by * blocksWide + bx + if pos < back then + return false, "repeat before any block" + end + local reps = if pair then count * 2 else count + local srcA = pos - back + local srcB = pos - 1 + for k = 0, reps - 1 do + if total <= 0 or by >= bh then + break + end + local s = if pair and k % 2 == 1 then srcB else srcA + local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4 + local o, so = by * 4 * stride + bx * 4, sy * stride + sx + for r = 0, 3 do + writeu32(px, o + r * stride, readu32(px, so + r * stride)) + end + advance() + end + elseif kind <= 7 then + local c = u8() + local v = c * 0x01010101 + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for r = 0, 3 do + writeu32(px, o + r * stride, v) + end + advance() + end + elseif kind <= 13 then + -- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds) + local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8 + local base = if size == 2 then 0 elseif size == 4 then 512 else 1536 + local entry: number + if kind % 2 == 0 then + local i = if size == 2 then pairI elseif size == 4 then quadI else octI + for k = 0, size - 1 do + writeu8(tables, base + i * size + k, u8()) + end + entry = i + i = (i + 1) % 256 + if size == 2 then + pairI = i + elseif size == 4 then + quadI = i + else + octI = i + end + else + entry = u8() + end + local t = base + entry * size + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + if size == 2 then + local f = u8() * 256 + u8() + for k = 0, 15 do + local bit = band(rshift(f, 15 - k), 1) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit)) + end + elseif size == 4 then + local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8() + for k = 0, 15 do + local i = band(rshift(f, 30 - 2 * k), 3) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + else + -- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel) + local v1 = u8() * 256 + u8() + local v2 = u8() * 256 + u8() + local v3 = u8() * 256 + u8() + local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4) + local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15) + for k = 0, 15 do + local f = if k < 8 then fa else fb + local i = band(rshift(f, 21 - 3 * (k % 8)), 7) + writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i)) + end + end + advance() + end + else + -- 16-colour blocks + for _ = 1, count do + if total <= 0 or by >= bh then + break + end + local o = by * 4 * stride + bx * 4 + for k = 0, 15 do + writeu8(px, o + (k // 4) * stride + k % 4, u8()) + end + advance() + end + end + end + return true, nil +end + +-- tables() -> the colour group scratch (pairs, quads, octets) +function Smc.tables(): buffer + return buffer.create(512 + 1024 + 2048) +end + +return Smc diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau new file mode 100644 index 0000000..51729a4 --- /dev/null +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -0,0 +1,187 @@ +--!strict +-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. +-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk +-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", +-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's +-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns +-- a fresh copy. +-- +-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the +-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that +-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). +-- +-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- +-- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Picture = require("@formats/codecs/video/Legacy/Picture") +local Flic = require("@formats/codecs/video/Legacy/Flic") +local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") +local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") +local QtRle = require("@formats/codecs/video/Legacy/QtRle") +local Smc = require("@formats/codecs/video/Legacy/Smc") + +local Legacy = {} + +Legacy.Picture = Picture +Legacy.Flic = Flic +Legacy.Cinepak = Cinepak +Legacy.Msvideo1 = Msvideo1 +Legacy.QtRle = QtRle +Legacy.Smc = Smc +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } + +export type Options = { + maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) + [string]: any, +} + +-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err? +type Codec = { + make: (track: Types.Track) -> (any, string?), + step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), +} + +local function fail(msg: string?): Err.Err + return Err.from(msg or "corrupt frame") +end + +local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean + local pal = (packet :: any).palette + if type(pal) == "buffer" then + Picture.setPalette(pic, pal) + return true + end + return false +end + +local CODECS: { [string]: Codec } = { + qtrle = { + make = function(t) + local depth = t.bitsPerPixel or 24 + local bits = if depth > 32 then depth - 32 else depth + if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then + return nil, "unsupported: depth " .. depth + end + return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = QtRle.decode(st.pic, data, st.depth) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + smc = { + make = function(t) + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + local ok, msg = Smc.decode(st.pic, data, st.tables) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + msvideo1 = { + make = function(t) + if (t.width :: number) < 4 or (t.height :: number) < 4 then + return nil, "smaller than one block" + end + local bits = if t.bitsPerPixel == 8 then 8 else 16 + return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil + end, + step = function(st, data, packet) + if st.bits == 8 then + packetPalette(st.pic, packet) + end + local ok, msg = Msvideo1.decode(st.pic, data, st.bits) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, + cinepak = { + make = function(t) + local pal = t.bitsPerPixel == 8 + return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil + end, + step = function(st, data, packet) + local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet) + local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal) + if not ok then + return nil, if msg then fail(msg) else nil + end + return Picture.image(st.pic), nil + end, + }, + flic = { + make = function(t) + return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) + end, + step = function(st, data, _packet) + local ok, msg = Flic.decode(st, data) + if not ok then + return nil, fail(msg) + end + return Flic.image(st), nil + end, + }, +} + +-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err +function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) + local codec = CODECS[id] + if not codec then + return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id)) + end + local w, h = track.width or 0, track.height or 0 + if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then + return nil, Err.new(Err.CORRUPT, "video track without a valid size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max or w > 32768 or h > 32768 then + return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit") + end + local st, msg = codec.make(track) + if not st then + return nil, fail(msg) + end + -- Video.simpleDecoder, without requiring the registry (which requires this module) + local queue: { any } = {} + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local ok, img, err = pcall(codec.step, st, packet.data, packet) + if not ok then + return Err.new(Err.CORRUPT, "decoder failed: " .. tostring(img)) + end + if img then + table.insert(queue, { img, packet.pts, packet.keyframe }) + end + return err + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) end + function self.reset(_: any) + table.clear(queue) + st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) + end + return self :: any, nil +end + +return Legacy diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..1b7cde8 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -294,6 +294,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec return H264.newVideoDecoder(track, opts) end +-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy) +local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) + return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + return require("@formats/codecs/video/Legacy").newDecoder(id, track, opts) + end +end + -- ------------------------------------------------------------------------------------------------ registry -- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased. local BUILTIN: { Entry } = { @@ -309,6 +316,13 @@ local BUILTIN: { Entry } = { { id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } }, { id = "theora", name = "Theora", matroska = { "V_THEORA" } }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, + -- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette) + { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, + { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, + { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, + { id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") }, + { id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") }, + { id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") }, } local byId: { [string]: Entry } = {} diff --git a/src/Formats/containers/IsoBmff/QtPalette.luau b/src/Formats/containers/IsoBmff/QtPalette.luau index 2034dc3..91b4524 100644 --- a/src/Formats/containers/IsoBmff/QtPalette.luau +++ b/src/Formats/containers/IsoBmff/QtPalette.luau @@ -10,7 +10,14 @@ -- -- depth: the stored depth (24, 32, 40, ...), palette: 256 u32 entries (bytes R, G, B, 0xFF) | nil -- -- Never throws. -local readu8, readu16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32 +local readu8, writeu32 = buffer.readu8, buffer.writeu32 + +local function readu16(b: buffer, o: number): number -- big-endian + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function readu32(b: buffer, o: number): number + return readu16(b, o) * 65536 + readu16(b, o + 2) +end local QtPalette = {} diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index 252a004..b4766d4 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -313,8 +313,9 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) - if t.kind == "video" and t.config then - vfwOrQuickTime(t, codecId, t.config) + local cfg: buffer? = t.config + if t.kind == "video" and cfg then + vfwOrQuickTime(t, codecId, cfg) end if t.kind == "audio" then t.sampleRate = t.sampleRate or 8000 diff --git a/tests/codecs/legacy.luau b/tests/codecs/legacy.luau new file mode 100644 index 0000000..236f7d2 --- /dev/null +++ b/tests/codecs/legacy.luau @@ -0,0 +1,113 @@ +-- codecs/video/Legacy tests: Cinepak (24-bit, grey, 8-bit palettised, several strips, a 92x68 size), Microsoft Video 1 +-- (16-bit, 8-bit with an AVI palette), QuickTime RLE (depths 1 / 2 / 4 / 8 with colour tables, default Macintosh +-- tables and grey ramps; 16 / 24 / 32-bit and grey from ffmpeg) and QuickTime SMC, in AVI, MOV and MKV: every frame +-- equals ffmpeg's decode (CRC-32 of rgba); seeking; the registry entries; the fuzz pass on each codec's packet decoder. +-- Fixtures: tools/fixtures/legacy.py. +local T = require("@tests/T") +local F = require("@formats") +local Crc32 = require("@formats/core/Crc32") +local Video = require("@formats/codecs/video/Video") +local Legacy = require("@formats/codecs/video/Legacy") +local Fx = require("@tests/gen/legacy_cases") + +local t = T.suite("legacy") + +-- the registry +t:eq(Video.fromFourcc("cvid"), "cinepak", "cvid") +t:eq(Video.fromFourcc("CRAM"), "msvideo1", "CRAM") +t:eq(Video.fromFourcc("msvc"), "msvideo1", "msvc") +t:eq(Video.fromFourcc("rle "), "qtrle", "rle ") +t:eq(Video.fromFourcc("smc "), "smc", "smc ") +for _, id in Legacy.CODECS do + t:check(Video.canDecode(id), id .. ": decodable") +end + +local samples: { [string]: { any } } = {} + +for _, c in Fx do + local label = c.name + local v, err = F.video.open(c.data) + t:check(v ~= nil, label .. ": open: " .. tostring(err)) + if v then + t:eq(v.codec, c.codec, label .. ": codec") + t:eq(v.width, c.width, label .. ": width") + local n, bad, first = 0, 0, nil + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": decode error " .. tostring(ferr)) + break + end + n += 1 + local img = f.image + if img.format ~= "rgba8" or img.width ~= c.width or Crc32.of(img.pixels) ~= c.frames[n] then + bad += 1 + first = first or n + end + end + t:check(n == #c.frames and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ, first %s)", label, n - bad, #c.frames, bad, tostring(first))) + -- seeking: back to the start, the first frame again + v:seek(0) + local f = v:nextFrame() + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[1], label .. ": seek(0)") + -- packets for the fuzz pass + local dmx = v.demuxer + local tr = dmx:track("video") + if not samples[c.codec] then + local list = {} + for k = 1, math.min(3, dmx:count(tr.id)) do + table.insert(list, dmx:get(tr.id, k).data) + end + samples[c.codec] = { track = tr, packets = list } + end + end +end + +-- the fuzz pass on the native packet decoders (no pcall in between) +local P = Legacy.Picture +local raw: { [string]: (tr: any) -> (buffer) -> any } = { + cinepak = function(tr) + return function(b) + local pic = P.new(tr.width, tr.height, tr.bitsPerPixel == 8, 4, 4, tr.palette) + return Legacy.Cinepak.decode(pic, b, Legacy.Cinepak.state(), false) + end + end, + msvideo1 = function(tr) + return function(b) + local bits = if tr.bitsPerPixel == 8 then 8 else 16 + return Legacy.Msvideo1.decode(P.new(tr.width, tr.height, bits == 8, 4, 4), b, bits) + end + end, + qtrle = function(tr) + return function(b) + local d = tr.bitsPerPixel or 24 + for _, depth in { d, 1, 2, 4, 8, 16, 32 } do + Legacy.QtRle.decode(P.new(tr.width, tr.height, Legacy.QtRle.palettised(depth), Legacy.QtRle.pad(depth), 1), b, depth) + end + return true + end + end, + smc = function(tr) + return function(b) + return Legacy.Smc.decode(P.new(tr.width, tr.height, true, 4, 4), b, Legacy.Smc.tables()) + end + end, +} +for id, s in samples do + local fn = raw[id] + if fn then + t:fuzz(id .. " packets", fn(s.track), s.packets, { mutations = 24, garbage = 60 }) + end +end +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + if not v:nextFrame() then + break + end + end + end + return v +end, { Fx[1].data, Fx[#Fx].data }, { mutations = 8, garbage = 20 }) +t:done() diff --git a/tools/fixtures/_legacy_mux.py b/tools/fixtures/_legacy_mux.py new file mode 100644 index 0000000..c00c674 --- /dev/null +++ b/tools/fixtures/_legacy_mux.py @@ -0,0 +1,375 @@ +# Shared helpers for the legacy video fixture generators (legacy.py), loaded by path: tiny AVI and QuickTime MOV +# writers (one video track, constant frame rate) for streams encoded here, and small encoders for what ffmpeg cannot +# encode: QuickTime RLE at depths 1 / 2 / 4 / 8, Microsoft Video 1 at 8 bits, Cinepak at 8 bits (palettised). +import struct + + +def le16(v): + return struct.pack("H", v & 0xFFFF) + + +def be32(v): + return struct.pack(">I", v & 0xFFFFFFFF) + + +# ---------------------------------------------------------------------------------------------------- AVI +def _ck(cid, body): + return cid + le32(len(body)) + body + (b"\0" if len(body) & 1 else b"") + + +def _lst(kind, body): + return b"LIST" + le32(len(body) + 4) + kind + body + + +def bitmapinfo(w, h, bits, fourcc, palette=None): + """BITMAPINFOHEADER (+ palette: a list of (r, g, b) stored as B, G, R, 0)""" + n = len(palette) if palette else 0 + out = le32(40) + le32(w) + le32(h) + le16(1) + le16(bits) + fourcc + le32(w * h * max(1, bits // 8)) + \ + le32(0) + le32(0) + le32(n) + le32(0) + for r, g, b in palette or []: + out += bytes([b, g, r, 0]) + return out + + +def avi(w, h, fourcc, strf, frames, keys, fps=10): + """an AVI file: one video stream, frames = [bytes], keys = [bool]""" + n = len(frames) + avih = le32(1000000 // fps) + le32(0) + le32(0) + le32(0x10) + le32(n) + le32(0) + le32(1) + \ + le32(max(len(f) for f in frames)) + le32(w) + le32(h) + bytes(16) + strh = b"vids" + fourcc + le32(0) + le16(0) + le16(0) + le32(0) + le32(1) + le32(fps) + le32(0) + le32(n) + \ + le32(max(len(f) for f in frames)) + struct.pack("= len(g): + if first: + body += bytes([0x80 | skip, 0xFF]) + first = False + break + j = i + while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126: + j += 1 + sb = (0x80 if first else 0) | skip + first = False + if j > i: + body += bytes([sb, 256 - (j - i + 1)]) + _pack(g[i], 1) + i = j + 1 + else: + k = i + while k < len(g) and k - i < 63 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]): + k += 1 + k = max(k, i + 1) + body += bytes([sb, k - i]) + b"".join(_pack(x, 1) for x in g[i:k]) + i = k + if first: + body += bytes([0x80, 0xFF]) + continue + line = bytearray([1]) + i = 0 + while i < len(g): + skip = 0 + while pg and i < len(g) and g[i] == pg[i] and skip < 250: + skip += 1 + i += 1 + if i >= len(g): + break + if skip: + line += bytes([0, skip + 1]) + j = i + while j + 1 < len(g) and g[j + 1] == g[i] and j - i < 126: + j += 1 + if j > i: + line += bytes([256 - (j - i + 1)]) + _pack(g[i], bits) + i = j + 1 + else: + k = i + while k < len(g) and k - i < 127 and not (pg and g[k] == pg[k]) and not (k + 1 < len(g) and g[k + 1] == g[k]): + k += 1 + k = max(k, i + 1) + line += bytes([k - i]) + b"".join(_pack(x, bits) for x in g[i:k]) + i = k + line += b"\xff" + body += line + if bits == 1: + body += b"\x00\x00" + else: + body += b"\x00" + head = be16(8) + be16(y0) + be16(0) + be16(y1 - y0) + be16(0) + return be32(4 + len(head) + len(body)) + head + bytes(body) + + +# ---------------------------------------------------------------------------------------------------- MS Video 1 +def _block(img, bx, by): + """the 16 pixels of a block, MS Video 1 order: bottom row first, left to right""" + return [img[by * 4 + 3 - y][bx * 4 + x] for y in range(4) for x in range(4)] + + +def msvc8_frame(img, prev): + """one 8-bit CRAM frame: skips for unchanged blocks, 1-colour, 2-colour or 8-colour blocks""" + h, w = len(img), len(img[0]) + bw, bh = w // 4, h // 4 + out = bytearray() + skip = 0 + + def flush(): + nonlocal skip + while skip: + k = min(skip, 1023) + out.extend([k & 0xFF, 0x84 + (k >> 8)]) + skip -= k + + for by in range(bh - 1, -1, -1): + for bx in range(bw): + px = _block(img, bx, by) + if prev and px == _block(prev, bx, by): + skip += 1 + continue + flush() + cols = sorted(set(px), key=lambda c: (-px.count(c), c)) + if len(cols) == 1: + out.extend([px[0], 0x80]) + elif len(cols) == 2: + c0 = px[15] # pixel 15's flag bit is 0: it takes colours[1] + c1 = cols[0] if cols[0] != c0 else cols[1] + flags = sum(1 << i for i in range(16) if px[i] == c1) + out.extend([flags & 0xFF, flags >> 8, c1, c0]) + else: + # 8-colour: a pair per quadrant; pixel 12 and 15 take the first colour of their quadrant (flags >= 0x9000) + colours = [0] * 8 + flags = 0 + for q, (qx, qy) in enumerate([(0, 0), (2, 0), (0, 2), (2, 2)]): + ids = [(qy + y) * 4 + qx + x for y in range(2) for x in range(2)] + vals = [px[i] for i in ids] + key = {2: 12, 3: 15}.get(q) + a = px[key] if key is not None else sorted(set(vals), key=lambda c: (-vals.count(c), c))[0] + rest = [v for v in vals if v != a] + b = rest[0] if rest else a + base = ((qy & 2) << 1) + (qx & 2) + colours[base], colours[base + 1] = a, b + for i in ids: + if px[i] == a: + flags |= 1 << i + else: + px[i] = b + out.extend([flags & 0xFF, flags >> 8] + colours) + flush() + return bytes(out) + + +# ---------------------------------------------------------------------------------------------------- Cinepak (8-bit) +def cvid8_frame(img, prev, first): + """one palettised Cinepak frame: one strip, a V1 codebook of 4-index entries (each a 2x2 square of one colour per + entry quarter) and a V4 codebook; blocks are V1 when their four 2x2 squares are uniform, else V4 (from the + codebook of 2x2 squares); inter frames skip unchanged blocks""" + h, w = len(img), len(img[0]) + blocks = [(x, y) for y in range(0, h, 4) for x in range(0, w, 4)] + v1, v4 = {}, {} + + def sq(x, y): + return (img[y][x], img[y][x + 1], img[y + 1][x], img[y + 1][x + 1]) + + plan = [] + for (x, y) in blocks: + if prev is not None and all(img[y + j][x + i] == prev[y + j][x + i] for j in range(4) for i in range(4)): + plan.append(None) + continue + q = [sq(x, y), sq(x + 2, y), sq(x, y + 2), sq(x + 2, y + 2)] + if all(len(set(s)) == 1 for s in q) and len(v1) < 256: + e = (q[0][0], q[1][0], q[2][0], q[3][0]) + v1.setdefault(e, len(v1)) + plan.append(("v1", v1[e])) + else: + ids = [] + for s in q: + if s not in v4 and len(v4) < 256: + v4[s] = len(v4) + ids.append(v4.get(s, 0)) + plan.append(("v4", ids)) + + def book(cid, entries): + data = b"".join(bytes(e) for e, _ in sorted(entries.items(), key=lambda kv: kv[1])) + return bytes([cid]) + (4 + len(data)).to_bytes(3, "big") + data + + chunks = b"" + if v4: + chunks += book(0x24, v4) + if v1: + chunks += book(0x26, v1) + bits, data = [], bytearray() + inter = prev is not None + # flags (MSB first, 32 per word) are interleaved with the indexes in decode order + words = bytearray() + flagbuf = [] + + def flag(b): + flagbuf.append(b) + if len(flagbuf) == 1: + words.extend(b"FLAG") # placeholder, patched below + pos_stack.append(len(words) - 4) + if len(flagbuf) == 32: + patch() + + pos_stack = [] + + def patch(): + v = 0 + for i, b in enumerate(flagbuf): + v |= b << (31 - i) + p = pos_stack.pop() + words[p:p + 4] = v.to_bytes(4, "big") + flagbuf.clear() + + for item in plan: + if inter: + flag(0 if item is None else 1) + if item is None: + continue + flag(1 if item[0] == "v4" else 0) + if item[0] == "v1": + words.append(item[1]) + else: + words.extend(item[1]) + if flagbuf: + patch() + vid = (0x31 if inter else 0x30) + chunks += bytes([vid]) + (4 + len(words)).to_bytes(3, "big") + bytes(words) + strip = bytes([0x10 if first else 0x11]) + (12 + len(chunks)).to_bytes(3, "big") + be16(0) + be16(0) + be16(h) + \ + be16(w) + chunks + size = 10 + len(strip) + return bytes([0]) + size.to_bytes(3, "big") + be16(w) + be16(h) + be16(1) + strip diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py new file mode 100644 index 0000000..863b866 --- /dev/null +++ b/tools/fixtures/legacy.py @@ -0,0 +1,100 @@ +# Legacy video codec fixtures (tools/fixtures.py): Cinepak, Microsoft Video 1, QuickTime RLE and QuickTime SMC +# streams in AVI, MOV and MKV. ffmpeg encodes what it can (cinepak rgb24 / gray, msvideo1 rgb555, qtrle rgb24 / +# rgb555 / argb / gray, smc pal8); tools/fixtures/_legacy_mux.py encodes the rest (QuickTime RLE at 1 / 2 / 4 / 8 bits +# with colour tables and the default Macintosh palettes, 8-bit Microsoft Video 1 and Cinepak with AVI palettes). The +# reference is ffmpeg's decode of every file: the CRC-32 of each frame as rgba. +# tests/gen/legacy_cases.luau { { name, data, codec, width, height, frames = { crc } } } +import importlib.util, os, tempfile, zlib + +_here = os.path.dirname(os.path.abspath(__file__)) + + +def _load(name): + spec = importlib.util.spec_from_file_location(name, os.path.join(_here, name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +V = _load("_video") +M = _load("_legacy_mux") + +INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_legacy_mux.py"] + +W, H = 128, 96 +SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=10" % (W, H), "-t", "1"] + + +def rgba_crcs(path, w, h): + raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"]) + n = w * h * 4 + return [zlib.crc32(raw[i:i + n]) & 0xffffffff for i in range(0, len(raw) - n + 1, n)] + + +def case(tmp, name, codec, w=W, h=H): + path = os.path.join(tmp, name) + return {"name": name, "data": open(path, "rb").read(), "codec": codec, "width": w, "height": h, + "frames": rgba_crcs(path, w, h)} + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="legacyfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + cases = [] + # ffmpeg's encoders + for ext in ("avi", "mov", "mkv"): + ff(*SRC, "-c:v", "cinepak", "cinepak." + ext) + cases.append(case(tmp, "cinepak." + ext, "cinepak")) + ff(*SRC, "-c:v", "cinepak", "-pix_fmt", "gray", "cinepak_gray.avi") + cases.append(case(tmp, "cinepak_gray.avi", "cinepak")) + ff("-f", "lavfi", "-i", "testsrc2=size=92x68:rate=10", "-t", "0.5", "-c:v", "cinepak", "cinepak_odd.mov") + cases.append(case(tmp, "cinepak_odd.mov", "cinepak", 92, 68)) + ff(*SRC, "-c:v", "cinepak", "-min_strips", "3", "-max_strips", "3", "-skip_empty_cb", "1", "cinepak_strips.avi") + cases.append(case(tmp, "cinepak_strips.avi", "cinepak")) + for ext in ("avi", "mov", "mkv"): + ff(*SRC, "-c:v", "msvideo1", "msvideo1." + ext) + cases.append(case(tmp, "msvideo1." + ext, "msvideo1")) + for pf in ("rgb24", "rgb555be", "argb", "gray"): + ff(*SRC, "-c:v", "qtrle", "-pix_fmt", pf, "qtrle_%s.mov" % pf) + cases.append(case(tmp, "qtrle_%s.mov" % pf, "qtrle")) + ff("-f", "lavfi", "-i", "testsrc2=size=100x60:rate=10", "-t", "0.5", "-c:v", "qtrle", "-pix_fmt", "argb", "qtrle_odd.mov") + cases.append(case(tmp, "qtrle_odd.mov", "qtrle", 100, 60)) + for ext in ("mov", "mkv"): # (ffmpeg's AVI muxer has no tag for smc: it writes raw pal8) + ff(*SRC, "-c:v", "smc", "smc." + ext) + cases.append(case(tmp, "smc." + ext, "smc")) + # streams encoded here + w, h, n = 64, 48, 8 + for bits in (1, 2, 4, 8): + imgs = M.index_frames(w, h, n, 1 << bits, seed=bits) + frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)] + keys = [i == 0 for i in range(n)] + # a colour table in the sample description, and the Macintosh default table + pal = M.palette(1 << bits, seed=bits) + name = "qtrle_%d_ctab.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits, colors=pal), frames, keys)) + cases.append(case(tmp, name, "qtrle", w, h)) + name = "qtrle_%d_default.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, bits), frames, keys)) + cases.append(case(tmp, name, "qtrle", w, h)) + # grey depths (0x20 + bits) with the default table id: grey ramps + for bits in (2, 4): + imgs = M.index_frames(w, h, 4, 1 << bits, seed=10 + bits) + frames = [M.qtrle_frame(img, imgs[i - 1] if i else None, bits) for i, img in enumerate(imgs)] + name = "qtrle_%d_grey.mov" % bits + open(os.path.join(tmp, name), "wb").write(M.mov(w, h, M.qt_entry(b"rle ", w, h, 32 + bits), frames, [True] + [False] * 3)) + cases.append(case(tmp, name, "qtrle", w, h)) + # 8-bit Microsoft Video 1 and Cinepak with an AVI palette + pal = M.palette(256, seed=3) + imgs = M.index_frames(w, h, n, 256, seed=5) + frames = [M.msvc8_frame(img, imgs[i - 1] if i else None) for i, img in enumerate(imgs)] + open(os.path.join(tmp, "msvideo1_8.avi"), "wb").write( + M.avi(w, h, b"CRAM", M.bitmapinfo(w, h, 8, b"CRAM", pal), frames, [i == 0 for i in range(n)])) + cases.append(case(tmp, "msvideo1_8.avi", "msvideo1", w, h)) + imgs = M.index_frames(w, h, n, 200, seed=6) + frames = [M.cvid8_frame(img, imgs[i - 1] if i else None, i == 0) for i, img in enumerate(imgs)] + open(os.path.join(tmp, "cinepak_8.avi"), "wb").write( + M.avi(w, h, b"cvid", M.bitmapinfo(w, h, 8, b"cvid", pal), frames, [i == 0 for i in range(n)])) + cases.append(case(tmp, "cinepak_8.avi", "cinepak", w, h)) + for c in cases: + assert c["frames"], c["name"] + ": ffmpeg decoded no frame" + ctx.emit("legacy_cases", cases) From 672948f7d7f07debac590b2331b3ca9d50b39fd1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:21:04 -0500 Subject: [PATCH 17/54] ws-tex: image/dds (read every DXGI / legacy FourCC / bit-mask format, mips, cube, arrays, volumes; write rgba8 / BC1/3/4/5 / 16-bit / float) New shared codecs: codecs/image/Texel (uncompressed GPU texel formats incl. packed, shared exponent, YUY2), codecs/image/Texture (dispatch over Bcn / Etc / Texel, surface assembly, mip halving). Tested against nvcompress / nvassemble / ImageMagick files (Pillow per surface, Godot for BC6H floats), hand-written formats, and our files read back by Pillow + nvddsinfo. --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 12 + src/Formats/codecs/image/Texel.luau | 398 +++++++++++++++++++++ src/Formats/codecs/image/Texture.luau | 162 +++++++++ src/Formats/image/dds/init.luau | 497 ++++++++++++++++++++++++++ tests/image/dds.luau | 212 +++++++++++ tools/fixtures/_tex_encode.luau | 75 ++++ tools/fixtures/dds.py | 332 +++++++++++++++++ 8 files changed, 1691 insertions(+) create mode 100644 src/Formats/codecs/image/Texel.luau create mode 100644 src/Formats/codecs/image/Texture.luau create mode 100644 src/Formats/image/dds/init.luau create mode 100644 tests/image/dds.luau create mode 100644 tools/fixtures/_tex_encode.luau create mode 100644 tools/fixtures/dds.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 7b021d0..2acc70d 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | +| image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | @@ -123,6 +124,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 (native), shared by the bitmap formats (BMP, - codecs/image/Quantize: palette quantization of rgba8 pixels. A codec (layer 1): image/gif (and later any palette - codecs/image/Raster: an antialiased scanline rasterizer for paths of lines, quadratic and cubic Béziers, under an affine + - codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers + - codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): - codecs/image/Vp8: the VP8 video codec (RFC 6386), decode only. A codec (layer 1): image/webp uses it for lossy frames, the - codecs/image/Vp8L: WebP lossless (VP8L, "WebP Lossless Bitstream Specification", RFC 9649 section 3). A codec (layer 1): - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..a375d4a 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -26,6 +26,18 @@ local list: { Entry } = { return require("@formats/image/bmp") end, }, + { + name = "dds", + category = "image", + path = "image/dds", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, + load = function() + return require("@formats/image/dds") + end, + }, { name = "gif", category = "image", diff --git a/src/Formats/codecs/image/Texel.luau b/src/Formats/codecs/image/Texel.luau new file mode 100644 index 0000000..cdd3ff5 --- /dev/null +++ b/src/Formats/codecs/image/Texel.luau @@ -0,0 +1,398 @@ +--!strict +--!native +--!optimize 2 +-- codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats, shared by the texture containers +-- (DDS's DXGI and legacy bit-mask formats, KTX's Vulkan / OpenGL formats, ...). New in formats-luau. Formats are named +-- lower case, channels from the lowest address / bit up (DXGI order): r8, rg8, rgb8, bgr8, rgba8, bgra8, bgrx8, a8, +-- l8, la8, r16, rgba16, *s (snorm), *ui / *i (integers), *f (half / float: r16f ... rgba32f), and the packed ones: +-- b5g6r5, r5g6b5, b5g5r5a1, a1b5g5r5, b4g4r4a4, a4b4g4r4, a4r4g4b4, rgb10a2, bgr10a2, r11g11b10f, rgb9e5; any other +-- bit-mask layout through Texel.masked(bytes, rMask, gMask, bMask, aMask, luminance?). Never throws. +-- +-- local px, fmt = Texel.decode("bgra8", buf, offset, w, h) -- rgba8 pixels +-- local px, fmt = Texel.decode("rgba16f", buf, offset, w, h, true) -- native: rgbaf32 (float) / rgba16 (16-bit) +-- local desc = Texel.masked(2, 0xF800, 0x07E0, 0x001F, 0) -- a descriptor, accepted by decode +-- +-- Channels: one-channel formats (r*, l*) are grey (r = g = b), two-channel ones red + green; missing alpha is opaque. +-- rgba8 output: unorm rescaled with rounding, snorm biased (8-bit: s + 128), floats clamped to 0..1, integers clamped +-- to 0..255. Native output: rgba8 when every channel fits 8 bits unsigned, rgba16 for 9..16-bit unorm, else rgbaf32 +-- (snorm -> -1..1, integers as their values). +local Half = require("@formats/codecs/image/Half") + +local Texel = {} + +export type Channel = { c: string, shift: number, bits: number } -- packed channels (c = r g b a l) +export type Desc = { + bytes: number, -- per texel + kind: "array" | "packed" | "r11g11b10f" | "rgb9e5" | "pair" | "ayuv", + size: number?, -- array: bytes per component (1, 2, 4) + type: string?, -- array: unorm / snorm / uint / sint / float + order: string?, -- array: the components in memory (r g b a l x); pair: the 4 bytes of 2 pixels (yuyv, uyvy, rgbg, grgb) + channels: { Channel }?, -- packed: unorm fields of a little-endian 16 / 32-bit word +} + +local readu8, readu16, readu32, readi8, readi16, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32, buffer.readf32 +local writeu8, writeu16, writeu32, writef32 = buffer.writeu8, buffer.writeu16, buffer.writeu32, buffer.writef32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift +local HALF = Half.TABLE + +-- ------------------------------------------------------------------------------------------------ formats +local FORMATS: { [string]: Desc } = {} +local function array(name: string, size: number, typ: string, order: string) + FORMATS[name] = { bytes = size * #order, kind = "array", size = size, type = typ, order = order } +end +for _, o in { "r", "rg", "rgb", "rgba" } do + array(o .. "8", 1, "unorm", o) + array(o .. "8s", 1, "snorm", o) + array(o .. "8ui", 1, "uint", o) + array(o .. "8i", 1, "sint", o) + array(o .. "16", 2, "unorm", o) + array(o .. "16s", 2, "snorm", o) + array(o .. "16ui", 2, "uint", o) + array(o .. "16i", 2, "sint", o) + array(o .. "16f", 2, "float", o) + array(o .. "32ui", 4, "uint", o) + array(o .. "32i", 4, "sint", o) + array(o .. "32f", 4, "float", o) +end +array("bgr8", 1, "unorm", "bgr") +array("bgra8", 1, "unorm", "bgra") +array("bgrx8", 1, "unorm", "bgrx") +array("rgbx8", 1, "unorm", "rgbx") +array("a8", 1, "unorm", "a") +array("l8", 1, "unorm", "l") +array("la8", 1, "unorm", "la") +array("l16", 2, "unorm", "l") +array("la16", 2, "unorm", "la") +array("a16", 2, "unorm", "a") + +local function packed(name: string, bytes: number, spec: { any }) + local ch: { Channel } = {} + for i = 1, #spec, 3 do + table.insert(ch, { c = spec[i], shift = spec[i + 1], bits = spec[i + 2] }) + end + FORMATS[name] = { bytes = bytes, kind = "packed", channels = ch } +end +packed("b5g6r5", 2, { "b", 0, 5, "g", 5, 6, "r", 11, 5 }) +packed("r5g6b5", 2, { "r", 0, 5, "g", 5, 6, "b", 11, 5 }) +packed("b5g5r5a1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5, "a", 15, 1 }) +packed("b5g5r5x1", 2, { "b", 0, 5, "g", 5, 5, "r", 10, 5 }) +packed("a1b5g5r5", 2, { "a", 0, 1, "b", 1, 5, "g", 6, 5, "r", 11, 5 }) +packed("a1r5g5b5", 2, { "a", 0, 1, "r", 1, 5, "g", 6, 5, "b", 11, 5 }) +packed("b4g4r4a4", 2, { "b", 0, 4, "g", 4, 4, "r", 8, 4, "a", 12, 4 }) +packed("r4g4b4a4", 2, { "r", 0, 4, "g", 4, 4, "b", 8, 4, "a", 12, 4 }) +packed("a4b4g4r4", 2, { "a", 0, 4, "b", 4, 4, "g", 8, 4, "r", 12, 4 }) +packed("a4r4g4b4", 2, { "a", 0, 4, "r", 4, 4, "g", 8, 4, "b", 12, 4 }) +packed("rgb10a2", 4, { "r", 0, 10, "g", 10, 10, "b", 20, 10, "a", 30, 2 }) +packed("bgr10a2", 4, { "b", 0, 10, "g", 10, 10, "r", 20, 10, "a", 30, 2 }) +packed("r3g3b2", 1, { "b", 0, 2, "g", 2, 3, "r", 5, 3 }) +FORMATS.r11g11b10f = { bytes = 4, kind = "r11g11b10f" } +FORMATS.rgb9e5 = { bytes = 4, kind = "rgb9e5" } +-- 4:2:2 pairs (2 pixels in 4 bytes; bytes = per pixel) and 4:4:4 AYUV (bytes V U Y A); Y'CbCr is BT.601 limited range +FORMATS.yuy2 = { bytes = 2, kind = "pair", order = "yuyv" } +FORMATS.uyvy = { bytes = 2, kind = "pair", order = "uyvy" } +FORMATS.rgbg = { bytes = 2, kind = "pair", order = "rgbg" } +FORMATS.grgb = { bytes = 2, kind = "pair", order = "grgb" } +FORMATS.ayuv = { bytes = 4, kind = "ayuv" } +Texel.FORMATS = FORMATS + +-- masked(bytes, r, g, b, a, luminance?) -> a packed descriptor from bit masks (DDS legacy pixel formats); luminance: +-- the r mask is a luminance channel +function Texel.masked(bytes: number, r: number, g: number, b: number, a: number, luminance: boolean?): Desc? + if bytes < 1 or bytes > 4 then + return nil + end + local ch: { Channel } = {} + for i, m in { r, g, b, a } do + if m ~= 0 then + local shift = 0 + while band(m, lshift(1, shift)) == 0 and shift < 31 do + shift += 1 + end + local bits = 0 + while shift + bits < 32 and band(m, lshift(1, shift + bits)) ~= 0 do + bits += 1 + end + local name = if i == 1 then (if luminance then "l" else "r") elseif i == 2 then "g" elseif i == 3 then "b" else "a" + table.insert(ch, { c = name, shift = shift, bits = bits }) + end + end + if #ch == 0 then + return nil + end + return { bytes = bytes, kind = "packed", channels = ch } +end + +-- size(fmt, w, h) -> bytes (rows tightly packed) | nil +function Texel.size(fmt: string | Desc, w: number, h: number): number? + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil + end + return if d.kind == "pair" then ((w + 1) // 2) * 4 * h else d.bytes * w * h +end + +-- ------------------------------------------------------------------------------------------------ helpers +-- the native output of a descriptor: rgba8 / rgba16 / rgbaf32 +local function nativeOf(d: Desc): string + if d.kind == "array" then + local t, s = d.type, d.size :: number + if t == "float" or t == "snorm" or t == "sint" or (t == "uint" and s > 1) then + return "rgbaf32" + end + return if s == 1 then "rgba8" else "rgba16" + elseif d.kind == "packed" then + local wide = false + for _, c in d.channels :: { Channel } do + wide = wide or c.bits > 8 + end + return if wide then "rgba16" else "rgba8" + end + return "rgbaf32" +end +Texel.nativeOf = nativeOf + +local function uf11(v: number): number + local e, m = rshift(v, 6), band(v, 63) + if e == 0 then + return m / 64 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 64) * 2 ^ (e - 15) +end +local function uf10(v: number): number + local e, m = rshift(v, 5), band(v, 31) + if e == 0 then + return m / 32 * 2 ^ -14 + elseif e == 31 then + return if m == 0 then math.huge else 0 / 0 + end + return (1 + m / 32) * 2 ^ (e - 15) +end + +-- one component at q of an array format -> a float (native meaning) and its rgba8 byte +local function component(src: buffer, q: number, size: number, typ: string): (number, number) + if typ == "unorm" then + if size == 1 then + local v = readu8(src, q) + return v / 255, v + elseif size == 2 then + local v = readu16(src, q) + return v / 65535, (v * 255 + 32767) // 65535 + end + local v = readu32(src, q) + return v / 4294967295, math.floor(v / 4294967295 * 255 + 0.5) + elseif typ == "snorm" then + if size == 1 then + local v = math.max(readi8(src, q), -127) + return v / 127, v + 128 + elseif size == 2 then + local v = math.max(readi16(src, q), -32767) + return v / 32767, math.floor(v * 127 / 32767 + 0.5) + 128 + end + local v = math.max(readi32(src, q), -2147483647) + return v / 2147483647, math.floor(v * 127 / 2147483647 + 0.5) + 128 + elseif typ == "float" then + local f = if size == 2 then HALF[readu16(src, q)] else readf32(src, q) + local c = if f ~= f then 0 elseif f < 0 then 0 elseif f > 1 then 1 else f + return f, math.floor(c * 255 + 0.5) + elseif typ == "uint" then + local v = if size == 1 then readu8(src, q) elseif size == 2 then readu16(src, q) else readu32(src, q) + return v, math.min(v, 255) + end + local v = if size == 1 then readi8(src, q) elseif size == 2 then readi16(src, q) else readi32(src, q) + return v, math.clamp(v, 0, 255) +end + +-- BT.601 limited-range Y'CbCr -> an rgba8 u32 +local function ycc(y: number, u: number, v: number, a: number): number + local c, d, e = 1.164 * (y - 16), u - 128, v - 128 + local r = math.clamp(math.floor(c + 1.596 * e + 0.5), 0, 255) + local g = math.clamp(math.floor(c - 0.392 * d - 0.813 * e + 0.5), 0, 255) + local b = math.clamp(math.floor(c + 2.017 * d + 0.5), 0, 255) + return r + g * 256 + b * 65536 + a * 16777216 +end + +-- the 4:2:2 pair formats and AYUV -> rgba8 (out is always rgba8: 8-bit sources) +local function yuv(d: Desc, src: buffer, offset: number, w: number, h: number, pitch: number, dst: buffer): buffer + local n = 0 + local order = d.order or "" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + if d.kind == "ayuv" then + local q = s + x * 4 + writeu32(dst, n, ycc(readu8(src, q + 2), readu8(src, q + 1), readu8(src, q), readu8(src, q + 3))) + else + local q = s + (x // 2) * 4 + local b0, b1, b2, b3 = readu8(src, q), readu8(src, q + 1), readu8(src, q + 2), readu8(src, q + 3) + local odd = x % 2 == 1 + if order == "yuyv" then + writeu32(dst, n, ycc(if odd then b2 else b0, b1, b3, 255)) + elseif order == "uyvy" then + writeu32(dst, n, ycc(if odd then b3 else b1, b0, b2, 255)) + elseif order == "rgbg" then + writeu32(dst, n, b0 + (if odd then b3 else b1) * 256 + b2 * 65536 + 0xFF000000) + else + writeu32(dst, n, b1 + (if odd then b2 else b0) * 256 + b3 * 65536 + 0xFF000000) + end + end + n += 4 + end + end + return dst +end + +-- ------------------------------------------------------------------------------------------------ decode +-- decode(fmt, src, offset, w, h, native?, rowPitch?) -> pixels, pixel format ("rgba8" / "rgba16" / "rgbaf32") | nil, +-- message. rowPitch: bytes per source row (default tight). +function Texel.decode(fmt: string | Desc, src: buffer, offset: number, w: number, h: number, native: boolean?, rowPitch: number?): (buffer?, string) + local d = if type(fmt) == "string" then FORMATS[fmt] else fmt + if not d then + return nil, "unsupported: unknown texel format " .. tostring(fmt) + end + local tb = d.bytes + local rowBytes = if d.kind == "pair" then ((w + 1) // 2) * 4 else tb * w + local pitch = rowPitch or rowBytes + if w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 or pitch < rowBytes then + return nil, "bad image size" + end + if offset < 0 or offset + pitch * (h - 1) + rowBytes > buffer.len(src) then + return nil, "truncated: texel data runs past the end" + end + local out = if native and d.kind ~= "pair" and d.kind ~= "ayuv" then nativeOf(d) else "rgba8" + local bpp = if out == "rgba8" then 4 elseif out == "rgba16" then 8 else 16 + local dst = buffer.create(w * h * bpp) + local n = 0 + if d.kind == "array" then + local order, size, typ = d.order :: string, d.size :: number, d.type :: string + -- fast paths + if size == 1 and typ == "unorm" and out == "rgba8" and (order == "rgba" or order == "bgra" or order == "bgrx" or order == "rgbx") then + local swap = order == "bgra" or order == "bgrx" + local opaque = order == "bgrx" or order == "rgbx" + for y = 0, h - 1 do + local s = offset + y * pitch + for x = 0, w - 1 do + local v = readu32(src, s + x * 4) + if swap then + v = band(v, 0xFF00FF00) + band(rshift(v, 16), 0xFF) + lshift(band(v, 0xFF), 16) + end + if opaque then + v = band(v, 0xFFFFFF) + 0xFF000000 + end + writeu32(dst, n, v) + n += 4 + end + end + return dst, out + end + local nc = #order + local map = table.create(nc, 0) -- component -> output channel 0..3, 4 = grey, -1 = skip + for i = 1, nc do + local c = string.sub(order, i, i) + map[i] = if c == "r" then (if nc == 1 then 4 else 0) elseif c == "g" then 1 elseif c == "b" then 2 elseif c == "a" then 3 elseif c == "l" then 4 else -1 + end + local f = table.create(4, 0) + local q8 = table.create(4, 0) + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + f[1], f[2], f[3], f[4] = 0, 0, 0, 1 + q8[1], q8[2], q8[3], q8[4] = 0, 0, 0, 255 + for i = 1, nc do + local m = map[i] + if m >= 0 then + local fv, bv = component(src, s, size, typ) + if m == 4 then + f[1], f[2], f[3] = fv, fv, fv + q8[1], q8[2], q8[3] = bv, bv, bv + else + f[m + 1], q8[m + 1] = fv, bv + end + end + s += size + end + if out == "rgba8" then + writeu32(dst, n, q8[1] + q8[2] * 256 + q8[3] * 65536 + q8[4] * 16777216) + elseif out == "rgba16" then + for c = 0, 3 do + writeu16(dst, n + c * 2, math.floor(math.clamp(f[c + 1], 0, 1) * 65535 + 0.5)) + end + else + for c = 0, 3 do + writef32(dst, n + c * 4, f[c + 1]) + end + end + n += bpp + end + end + return dst, out + elseif d.kind == "packed" then + local chs = d.channels :: { Channel } + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = if tb == 1 then readu8(src, s) elseif tb == 2 then readu16(src, s) elseif tb == 3 then readu16(src, s) + readu8(src, s + 2) * 65536 else readu32(src, s) + s += tb + local r, g, b, a = 0, 0, 0, 1 + for _, c in chs do + local maxv = lshift(1, c.bits) - 1 + local x = band(rshift(v, c.shift), maxv) / (if c.bits >= 32 then 4294967295 else maxv) + local k = c.c + if k == "r" then + r = x + elseif k == "g" then + g = x + elseif k == "b" then + b = x + elseif k == "a" then + a = x + else + r, g, b = x, x, x + end + end + if out == "rgba8" then + writeu32(dst, n, math.floor(r * 255 + 0.5) + math.floor(g * 255 + 0.5) * 256 + math.floor(b * 255 + 0.5) * 65536 + math.floor(a * 255 + 0.5) * 16777216) + else + writeu16(dst, n, math.floor(r * 65535 + 0.5)) + writeu16(dst, n + 2, math.floor(g * 65535 + 0.5)) + writeu16(dst, n + 4, math.floor(b * 65535 + 0.5)) + writeu16(dst, n + 6, math.floor(a * 65535 + 0.5)) + end + n += bpp + end + end + return dst, out + end + if d.kind == "pair" or d.kind == "ayuv" then + return yuv(d, src, offset, w, h, pitch, dst), out + end + -- shared-exponent / packed floats + local nine = d.kind == "rgb9e5" + for y = 0, h - 1 do + local s = offset + y * pitch + for _ = 0, w - 1 do + local v = readu32(src, s) + s += 4 + local sc = if nine then 2 ^ (rshift(v, 27) - 24) else 0 + local r: number = if nine then band(v, 511) * sc else uf11(band(v, 2047)) + local g: number = if nine then band(rshift(v, 9), 511) * sc else uf11(band(rshift(v, 11), 2047)) + local b: number = if nine then band(rshift(v, 18), 511) * sc else uf10(rshift(v, 22)) + if out == "rgba8" then + local function q(x: number): number + return if x ~= x or x <= 0 then 0 elseif x >= 1 then 255 else math.floor(x * 255 + 0.5) + end + writeu32(dst, n, q(r) + q(g) * 256 + q(b) * 65536 + 0xFF000000) + else + writef32(dst, n, r) + writef32(dst, n + 4, g) + writef32(dst, n + 8, b) + writef32(dst, n + 12, 1) + end + n += bpp + end + end + return dst, out +end + +return Texel diff --git a/src/Formats/codecs/image/Texture.luau b/src/Formats/codecs/image/Texture.luau new file mode 100644 index 0000000..98f719f --- /dev/null +++ b/src/Formats/codecs/image/Texture.luau @@ -0,0 +1,162 @@ +--!strict +-- codecs/image/Texture: one entry point over the texture pixel codecs for the texture containers (DDS, KTX, VTF, ...): +-- a format name is a BCn kind (codecs/image/Bcn), an ETC / EAC kind (codecs/image/Etc) or a texel format +-- (codecs/image/Texel); decode / size dispatch on it, surfaces() assembles mip levels / faces / layers into one +-- Types.Image, halve() makes the next mip level of an image for writers. New in formats-luau. Never throws. +-- +-- local px, pf = Texture.decode("bc7", buf, offset, w, h, native) -- pixels + their pixel format +-- Texture.size("etc2_rgb", w, h) -- bytes of one surface +-- local img = Texture.image(px, pf, w, h) -- a Types.Image around them +-- local smaller = Texture.halve(img) -- box-filtered next mip level +local Types = require("@formats/Types") +local Bcn = require("@formats/codecs/image/Bcn") +local Etc = require("@formats/codecs/image/Etc") +local Texel = require("@formats/codecs/image/Texel") +local Half = require("@formats/codecs/image/Half") + +local Texture = {} + +-- known(name) -> "bcn" | "etc" | "texel" | nil +function Texture.known(name: string): string? + if Bcn.BLOCK[name] then + return "bcn" + elseif Etc.BLOCK[name] then + return "etc" + elseif Texel.FORMATS[name] then + return "texel" + end + return nil +end + +-- size(name, w, h) -> bytes of a w x h surface | nil +function Texture.size(name: string, w: number, h: number): number? + return Bcn.size(name, w, h) or Etc.size(name, w, h) or Texel.size(name, w, h) +end + +-- block(name) -> block width, height, bytes (1, 1, texel bytes for texel formats) | nil +function Texture.block(name: string): (number?, number?, number?) + local b = Bcn.BLOCK[name] or Etc.BLOCK[name] + if b then + return 4, 4, b + end + local d = Texel.FORMATS[name] + if d then + return 1, 1, d.bytes + end + return nil, nil, nil +end + +-- decode(name, src, offset, w, h, native?) -> pixels, pixel format | nil, message. Without native the result is +-- rgba8 (BC6H and float texels clamped to 0..1); native keeps rgbaf32 (BC6H, floats) / rgba16 (EAC, 16-bit unorm). +function Texture.decode(name: string, src: buffer, offset: number, w: number, h: number, native: boolean?): (buffer?, string) + if Bcn.BLOCK[name] then + local px, err = Bcn.decode(name, src, offset, w, h) + if not px then + return nil, err or "bad block data" + end + if Bcn.FLOAT[name] then + if native then + return px, "rgbaf32" + end + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + buffer.writeu8(out, i * 4 + c, if v ~= v or v <= 0 then 0 elseif v >= 1 then 255 else math.floor(v * 255 + 0.5)) + end + end + return out, "rgba8" + end + return px, "rgba8" + elseif Etc.BLOCK[name] then + local wide = native == true and string.sub(name, 1, 3) == "eac" + local px, err = Etc.decode(name, src, offset, w, h, nil, 0, wide) + if not px then + return nil, err or "bad block data" + end + return px, if wide then "rgba16" else "rgba8" + end + return Texel.decode(name, src, offset, w, h, native) +end + +-- image(pixels, pixel format, w, h) -> Types.Image +function Texture.image(px: buffer, pf: string, w: number, h: number): Types.Image + local img = Types.Image.new(0, 0, pf :: any) + img.width, img.height, img.pixels = w, h, px + return img +end + +export type Surface = { level: number, layer: number, face: number, slice: number, image: Types.Image } + +-- assemble(surfaces, layout) -> the Image of the first surface with img.frames = every level-0 surface (faces / +-- layers / depth slices in order, when more than one) and img.meta.mipmaps = the smaller levels of the first surface +function Texture.assemble(list: { Surface }, layout: string): Types.Image? + local first: Types.Image? = nil + local frames: { Types.Frame } = {} + local mips: { Types.Image } = {} + for _, s in list do + if s.level == 0 then + first = first or s.image + local fr: Types.Frame = { image = s.image, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + table.insert(frames, fr) + elseif s.layer == 0 and s.face == 0 and s.slice == 0 then + mips[s.level] = s.image + end + end + if not first then + return nil + end + local img = Texture.image(first.pixels, first.format, first.width, first.height) + if #frames > 1 then + img.frames = frames + end + if #mips > 0 then + img.meta.mipmaps = mips + end + img.meta.layout = layout + return img +end + +-- halve(img) -> the next mip level (each dimension halved, at least 1; 2 x 2 box filter), same pixel format +-- (rgba8 / rgba16 / rgbaf32) +function Texture.halve(img: Types.Image): Types.Image + local w, h = img.width, img.height + local nw, nh = math.max(1, w // 2), math.max(1, h // 2) + local fmt = img.format + local out = Types.Image.new(nw, nh, fmt) + local src, dst = img.pixels, out.pixels + local cs = if fmt == "rgba8" then 1 elseif fmt == "rgba16" then 2 else 4 + local function get(x: number, y: number, c: number): number + local o = ((math.min(y, h - 1) * w + math.min(x, w - 1)) * 4 + c) * cs + return if cs == 1 then buffer.readu8(src, o) elseif cs == 2 then buffer.readu16(src, o) else buffer.readf32(src, o) + end + for y = 0, nh - 1 do + for x = 0, nw - 1 do + for c = 0, 3 do + local x0, y0 = x * 2, y * 2 + local v = (get(x0, y0, c) + get(x0 + 1, y0, c) + get(x0, y0 + 1, c) + get(x0 + 1, y0 + 1, c)) / 4 + local o = ((y * nw + x) * 4 + c) * cs + if cs == 1 then + buffer.writeu8(dst, o, math.floor(v + 0.5)) + elseif cs == 2 then + buffer.writeu16(dst, o, math.floor(v + 0.5)) + else + buffer.writef32(dst, o, v) + end + end + end + end + return out +end + +-- toHalf(rgbaf32 pixels, n) -> rgba16f texels (for writers) +function Texture.toHalf(px: buffer, n: number): buffer + local out = buffer.create(n * 8) + local from = Half.fromFloat + for i = 0, n * 4 - 1 do + buffer.writeu16(out, i * 2, from(buffer.readf32(px, i * 4))) + end + return out +end + +return Texture diff --git a/src/Formats/image/dds/init.luau b/src/Formats/image/dds/init.luau new file mode 100644 index 0000000..9b71ecf --- /dev/null +++ b/src/Formats/image/dds/init.luau @@ -0,0 +1,497 @@ +--!strict +-- image/dds: DirectDraw Surface (Microsoft "DDS" programming guide: DDS_HEADER, DDS_PIXELFORMAT, DDS_HEADER_DXT10; new +-- code). Decode: every DXGI format with a pixel layout (BC1..BC7 through codecs/image/Bcn; the uncompressed UNORM / +-- SNORM / UINT / SINT / FLOAT / packed / shared-exponent ones and YUY2 / AYUV / RGBG through codecs/image/Texel), the +-- legacy FourCC codes (DXT1..DXT5, ATI1 / BC4U / BC4S, ATI2 / BC5U / BC5S, RXGB, YUY2 / UYVY / RGBG / GRGB, the +-- D3DFMT float / 16-bit numbers) and legacy bit-mask RGB / luminance / alpha formats; mip chains, cube maps (all six +-- faces or a subset), texture arrays (DX10 arraySize) and volume textures. The first surface is the image; when there +-- are more (faces, layers, depth slices) img.frames lists every one of them (meta.layout = "2d" / "cube" / "array" / +-- "volume", meta.faces), and with opts.mips the smaller levels of the first surface go to img.meta.mipmaps. rgba8 by +-- default (BC6H and float formats clamped to 0..1); opts.native keeps rgbaf32 / rgba16 where the source has more. +-- Encode: rgba8 as uncompressed (R8G8B8A8 / B8G8R8A8), BC1 / BC3 / BC4 / BC5 (legacy FourCC headers), rgba16 / rgbaf32 +-- as DX10 R16G16B16A16_UNORM / R32G32B32A32_FLOAT / R16G16B16A16_FLOAT; optional mip chains (box filter) and the +-- frames as a texture array or a cube map. Not supported: planar video formats (NV12, P010, ...), palettes (P8), +-- 1-bit R1_UNORM, the depth-stencil formats with stencil channels, BC encoders other than 1 / 3 / 4 / 5. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Bcn = require("@formats/codecs/image/Bcn") +local Texel = require("@formats/codecs/image/Texel") +local Texture = require("@formats/codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Dds = { + name = "dds", + category = "image", + extensions = { "dds" }, + mime = { "image/vnd-ms.dds", "image/x-dds" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Bcn", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H sources (default false: rgba8) + mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) + surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) + maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface) +} +export type EncodeOptions = { + format: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: + -- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones + mips: boolean?, -- write a full mip chain (default false) + dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays) + cube: boolean?, -- write img.frames (6) as a cube map (default: when img.meta.layout == "cube") + alphaThreshold: number?, -- BC1: alpha below this is transparent (default 128) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- DXGI_FORMAT -> texture format name, sRGB +local DXGI: { [number]: string } = { + [1] = "rgba32f", [2] = "rgba32f", [3] = "rgba32ui", [4] = "rgba32i", + [5] = "rgb32f", [6] = "rgb32f", [7] = "rgb32ui", [8] = "rgb32i", + [9] = "rgba16", [10] = "rgba16f", [11] = "rgba16", [12] = "rgba16ui", [13] = "rgba16s", [14] = "rgba16i", + [15] = "rg32f", [16] = "rg32f", [17] = "rg32ui", [18] = "rg32i", + [23] = "rgb10a2", [24] = "rgb10a2", [26] = "r11g11b10f", + [27] = "rgba8", [28] = "rgba8", [29] = "rgba8", [30] = "rgba8ui", [31] = "rgba8s", [32] = "rgba8i", + [33] = "rg16", [34] = "rg16f", [35] = "rg16", [36] = "rg16ui", [37] = "rg16s", [38] = "rg16i", + [39] = "r32f", [40] = "r32f", [41] = "r32f", [42] = "r32ui", [43] = "r32i", + [48] = "rg8", [49] = "rg8", [50] = "rg8ui", [51] = "rg8s", [52] = "rg8i", + [53] = "r16", [54] = "r16f", [55] = "r16", [56] = "r16", [57] = "r16ui", [58] = "r16s", [59] = "r16i", + [60] = "r8", [61] = "r8", [62] = "r8ui", [63] = "r8s", [64] = "r8i", [65] = "a8", + [67] = "rgb9e5", [68] = "rgbg", [69] = "grgb", + [70] = "bc1", [71] = "bc1", [72] = "bc1", [73] = "bc2", [74] = "bc2", [75] = "bc2", [76] = "bc3", [77] = "bc3", [78] = "bc3", + [79] = "bc4", [80] = "bc4", [81] = "bc4s", [82] = "bc5", [83] = "bc5", [84] = "bc5s", + [85] = "b5g6r5", [86] = "b5g5r5a1", [87] = "bgra8", [88] = "bgrx8", [90] = "bgra8", [91] = "bgra8", [92] = "bgrx8", [93] = "bgrx8", + [94] = "bc6h", [95] = "bc6h", [96] = "bc6hs", [97] = "bc7", [98] = "bc7", [99] = "bc7", + [100] = "ayuv", [107] = "yuy2", [115] = "b4g4r4a4", [191] = "a4b4g4r4", +} +local SRGB = { [29] = true, [72] = true, [75] = true, [78] = true, [91] = true, [93] = true, [99] = true } +-- legacy FourCC codes (strings and D3DFMT numbers) +local FOURCC: { [string]: string } = { + DXT1 = "bc1", DXT2 = "bc2", DXT3 = "bc2", DXT4 = "bc3", DXT5 = "bc3", RXGB = "bc3", + ATI1 = "bc4", BC4U = "bc4", BC4S = "bc4s", ATI2 = "bc5", BC5U = "bc5", BC5S = "bc5s", + YUY2 = "yuy2", UYVY = "uyvy", RGBG = "rgbg", GRGB = "grgb", +} +local D3DFMT: { [number]: string } = { + [36] = "rgba16", [110] = "rgba16s", [111] = "r16f", [112] = "rg16f", [113] = "rgba16f", + [114] = "r32f", [115] = "rg32f", [116] = "rgba32f", [117] = "rg8s", [60] = "rg8s", [63] = "rgba8s", [64] = "rg16s", +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } +local MAGIC = "DDS " + +local DDSD_MIPMAPCOUNT, DDSD_DEPTH = 0x20000, 0x800000 +local DDPF_ALPHAPIXELS, DDPF_ALPHA, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, DDPF_BUMPDUDV = 0x1, 0x2, 0x4, 0x40, 0x20000, 0x80000 +local CAPS2_CUBEMAP, CAPS2_VOLUME = 0x200, 0x200000 +local MISC_CUBE = 0x4 + +local band = bit32.band + +-- ------------------------------------------------------------------------------------------------ sniff +function Dds.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, MAGIC .. "\124\0\0\0"), Sniff.magic(r, MAGIC, 0, 0.6)) +end + +-- ------------------------------------------------------------------------------------------------ decode +export type Info = { + width: number, + height: number, + depth: number, + mips: number, + format: string, -- the texture format name (codecs/image/Texture) + layout: string, -- "2d" | "cube" | "array" | "volume" + layers: number, + faces: { string }, -- cube faces present (in file order), else { } + srgb: boolean, + dxgi: number?, + fourcc: string?, + dataOffset: number, -- relative to the file start + alphaMode: number?, + premultiplied: boolean?, + masked: Texel.Desc?, -- legacy bit-mask formats (format = "masked" unless the masks have a name) +} + +local function u32(b: buffer, o: number): number + return buffer.readu32(b, o) +end + +-- info(r) -> Info | nil, Err (the headers only) +function Dds.info(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 128 or buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(if n < 128 and n >= 4 and buffer.readstring(b, o, 4) == MAGIC then Err.TRUNCATED else Err.CORRUPT, "not a DDS file", o) + end + if u32(b, o + 4) ~= 124 then + return nil, Err.new(Err.CORRUPT, "bad header size " .. u32(b, o + 4), o + 4) + end + local flags = u32(b, o + 8) + local h, w = u32(b, o + 12), u32(b, o + 16) + local depth = u32(b, o + 24) + local mips = u32(b, o + 28) + local pfFlags, fourccNum = u32(b, o + 80), u32(b, o + 84) + local bitCount = u32(b, o + 88) + local rm, gm, bm, am = u32(b, o + 92), u32(b, o + 96), u32(b, o + 100), u32(b, o + 104) + local caps2 = u32(b, o + 112) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, string.format("bad size %d x %d", w, h), o + 12) + end + if band(flags, DDSD_MIPMAPCOUNT) == 0 and mips > 1 and band(u32(b, o + 108), 0x400000) == 0 then + mips = 1 -- a count without the flag or the caps bit: some writers leave garbage + end + mips = math.max(1, mips) + local maxMips = 1 + do + local m = math.max(w, h, depth) + while m > 1 do + m //= 2 + maxMips += 1 + end + end + if mips > maxMips then + return nil, Err.new(Err.CORRUPT, "more mip levels than the size allows", o + 28) + end + local info: Info = { + width = w, + height = h, + depth = 1, + mips = mips, + format = "", + layout = "2d", + layers = 1, + faces = {}, + srgb = false, + dataOffset = 128, + } + local volume = band(caps2, CAPS2_VOLUME) ~= 0 or band(flags, DDSD_DEPTH) ~= 0 and depth > 1 + if band(pfFlags, DDPF_FOURCC) ~= 0 then + local fourcc = buffer.readstring(b, o + 84, 4) + if fourcc == "DX10" then + if n < 148 then + return nil, Err.new(Err.TRUNCATED, "missing DX10 header", o + 128) + end + local dxgi, dim, misc, arr, misc2 = u32(b, o + 128), u32(b, o + 132), u32(b, o + 136), u32(b, o + 140), u32(b, o + 144) + info.dxgi = dxgi + info.dataOffset = 148 + local name = DXGI[dxgi] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "DXGI format " .. dxgi, o + 128) + end + info.format = name + info.srgb = SRGB[dxgi] == true + info.alphaMode = band(misc2, 7) + info.premultiplied = band(misc2, 7) == 2 + info.layers = math.max(1, arr) + if info.layers > 4096 then + return nil, Err.new(Err.CORRUPT, "array size " .. arr, o + 140) + end + if dim == 4 then + volume = true + elseif dim ~= 2 and dim ~= 3 and dim ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad resource dimension " .. dim, o + 132) + else + volume = false + end + if band(misc, MISC_CUBE) ~= 0 then + info.layout = "cube" + info.faces = table.clone(FACES) + elseif info.layers > 1 then + info.layout = "array" + end + else + info.fourcc = fourcc + local name = FOURCC[fourcc] or D3DFMT[fourccNum] + if not name then + return nil, Err.new(Err.UNSUPPORTED, "FourCC " .. string.format("%q", fourcc), o + 84) + end + info.format = name + info.premultiplied = fourcc == "DXT2" or fourcc == "DXT4" + end + elseif band(pfFlags, DDPF_RGB + DDPF_LUMINANCE + DDPF_ALPHA + DDPF_BUMPDUDV + 0x200) ~= 0 then + local bytes = bitCount // 8 + if bitCount % 8 ~= 0 or bytes < 1 or bytes > 4 then + return nil, Err.new(Err.UNSUPPORTED, bitCount .. "-bit pixels", o + 88) + end + local lum = band(pfFlags, DDPF_LUMINANCE) ~= 0 + local alphaOnly = band(pfFlags, DDPF_ALPHA) ~= 0 and band(pfFlags, DDPF_RGB + DDPF_LUMINANCE) == 0 + local a = if band(pfFlags, DDPF_ALPHAPIXELS + DDPF_ALPHA) ~= 0 then am else 0 + local d + if alphaOnly then + d = Texel.masked(bytes, 0, 0, 0, if am ~= 0 then am else 0xFF) + elseif band(pfFlags, DDPF_BUMPDUDV) ~= 0 then + d = nil -- signed bump maps: handled by the D3DFMT names when they come as FourCC + else + d = Texel.masked(bytes, rm, if lum then 0 else gm, if lum then 0 else bm, a, lum) + end + if not d then + return nil, Err.new(Err.UNSUPPORTED, "pixel format masks", o + 92) + end + -- the common masks map onto named texel formats (fast paths, sane names) + local key = string.format("%d:%x:%x:%x:%x:%s", bitCount, rm, gm, bm, a, tostring(lum)) + local named = ({ + ["32:ff:ff00:ff0000:ff000000:false"] = "rgba8", + ["32:ff0000:ff00:ff:ff000000:false"] = "bgra8", + ["32:ff0000:ff00:ff:0:false"] = "bgrx8", + ["32:ff:ff00:ff0000:0:false"] = "rgbx8", + ["24:ff0000:ff00:ff:0:false"] = "bgr8", + ["24:ff:ff00:ff0000:0:false"] = "rgb8", + ["8:ff:0:0:0:true"] = "l8", + ["16:ffff:0:0:0:true"] = "l16", + } :: { [string]: string })[key] + info.format = named or "masked" + info.masked = d + else + return nil, Err.new(Err.UNSUPPORTED, string.format("pixel format flags 0x%x", pfFlags), o + 80) + end + if volume then + info.layout = "volume" + info.depth = math.max(1, depth) + if info.depth > 2048 then + return nil, Err.new(Err.CORRUPT, "depth " .. depth, o + 24) + end + elseif band(caps2, CAPS2_CUBEMAP) ~= 0 and not info.dxgi then + info.layout = "cube" + for i, f in FACES do + if band(caps2, bit32.lshift(0x400, i - 1)) ~= 0 then + table.insert(info.faces, f) + end + end + if #info.faces == 0 then + info.faces = table.clone(FACES) + end + end + return info, nil +end + +-- the bytes of one surface of format f +local function surfaceSize(info: any, w: number, h: number): number + if info.format == "masked" then + return (info.masked :: Texel.Desc).bytes * w * h + end + return Texture.size(info.format, w, h) :: number +end + +function Dds.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Dds.info(r) + if not info then + return nil, ierr + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base = r.buf, r.base + local p = base + info.dataOffset + local limit = r.limit + local count = if info.layout == "cube" then #info.faces * info.layers else info.layers + local list: { Texture.Surface } = {} + local pixels = 0 + local stop = false + for layer = 0, count - 1 do + local w, h, d = info.width, info.height, info.depth + for level = 0, info.mips - 1 do + local size = surfaceSize(info, w, h) + for slice = 0, d - 1 do + local want = (level == 0 and (wantAll or (layer == 0 and slice == 0))) or (wantMips and layer == 0 and slice == 0) + if want then + if p + size > limit then + if level > 0 or layer > 0 or slice > 0 then + stop = true -- a cut mip chain / later surface: keep what decoded + break + end + return nil, Err.new(Err.TRUNCATED, "surface data runs past the end", p) + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local px, pf + if info.format == "masked" then + px, pf = Texel.decode(info.masked :: Texel.Desc, b, p, w, h, native) + else + px, pf = Texture.decode(info.format, b, p, w, h, native) + end + if not px then + return nil, Err.from(pf, p) + end + local face = if info.layout == "cube" then layer % #info.faces else 0 + table.insert(list, { level = level, layer = layer, face = face, slice = slice, image = Texture.image(px, pf, w, h) }) + end + p += size + end + if stop then + break + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + if stop then + break + end + end + local img = Texture.assemble(list, info.layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no surface data", base + info.dataOffset) + end + if info.layout == "cube" then + img.meta.faces = info.faces + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(info.format, "f$") or info.format == "bc6h" or info.format == "bc6hs" or info.format == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.source = { + format = "dds", + pixelFormat = info.format, + dxgi = info.dxgi, + fourcc = info.fourcc, + mips = info.mips, + layers = info.layers, + depth = info.depth, + premultiplied = info.premultiplied, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local BYTES_PF: { [string]: number } = { rgba8 = 4, bgra8 = 4, rgba16 = 8, rgba16f = 8, rgba32f = 16 } +local DX10_OUT: { [string]: number } = { rgba8 = 28, bgra8 = 87, bc1 = 71, bc3 = 77, bc4 = 80, bc5 = 83, rgba16 = 11, rgba16f = 10, rgba32f = 2 } + +-- the surface bytes of one image in format f +local function surface(img: Types.Image, f: string, opts: EncodeOptions?): (buffer?, Err.Err?) + local w, h, px = img.width, img.height, img.pixels + if f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" then + local blocks, err = Bcn.encode(f, px, w, h, opts and { alphaThreshold = opts.alphaThreshold } or nil) + if not blocks then + return nil, Err.new(Err.ARG, tostring(err)) + end + return blocks, nil + elseif f == "bgra8" then + local out = buffer.create(w * h * 4) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + buffer.writeu32(out, i * 4, band(v, 0xFF00FF00) + band(bit32.rshift(v, 16), 0xFF) + bit32.lshift(band(v, 0xFF), 16)) + end + return out, nil + elseif f == "rgba16f" then + return Texture.toHalf(px, w * h), nil + end + local out = buffer.create(w * h * (BYTES_PF[f] :: number)) + buffer.copy(out, 0, px, 0, buffer.len(out)) + return out, nil +end + +local function writeHeader(out: Bytes.Writer, w: number, h: number, f: string, mips: number, dx10: boolean, layers: number, cube: boolean) + local blockFmt = f == "bc1" or f == "bc3" or f == "bc4" or f == "bc5" + out:string(MAGIC) + out:u32le(124) + local flags = 0x1007 + (if mips > 1 then DDSD_MIPMAPCOUNT else 0) + (if blockFmt then 0x80000 else 0x8) + out:u32le(flags) + out:u32le(h) + out:u32le(w) + out:u32le(if blockFmt then Texture.size(f, w, h) :: number else w * (BYTES_PF[f] :: number)) + out:u32le(0) + out:u32le(if mips > 1 then mips else 0) + out:fill(0, 44) + -- DDS_PIXELFORMAT + out:u32le(32) + if dx10 then + out:u32le(DDPF_FOURCC) + out:string("DX10") + out:fill(0, 20) + elseif blockFmt then + out:u32le(DDPF_FOURCC) + out:string(({ bc1 = "DXT1", bc3 = "DXT5", bc4 = "ATI1", bc5 = "ATI2" } :: { [string]: string })[f]) + out:fill(0, 20) + else + out:u32le(DDPF_RGB + DDPF_ALPHAPIXELS) + out:u32le(0) + out:u32le(32) + if f == "bgra8" then + out:u32le(0xFF0000) + out:u32le(0xFF00) + out:u32le(0xFF) + else + out:u32le(0xFF) + out:u32le(0xFF00) + out:u32le(0xFF0000) + end + out:u32le(0xFF000000) + end + out:u32le(0x1000 + (if mips > 1 then 0x400008 else 0) + (if cube then 0x8 else 0)) + out:u32le(if cube then 0xFE00 else 0) + out:fill(0, 12) + if dx10 then + out:u32le(DX10_OUT[f]) + out:u32le(3) + out:u32le(if cube then MISC_CUBE else 0) + out:u32le(if cube then layers // 6 else layers) + out:u32le(0) + end +end + +function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.format) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f") + if not DX10_OUT[f] then + return nil, Err.new(Err.ARG, "unknown format " .. tostring(f)) + end + local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8" + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("format %s needs an %s Image", f, needs)) + end + -- surfaces: the frames (array / cube faces) or the image + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and #images % 6 ~= 0 then + return nil, Err.new(Err.ARG, "a cube map needs 6 faces per layer") + end + local dx10 = (opts and opts.dx10) or f == "rgba16" or f == "rgba16f" or f == "rgba32f" or (#images > 1 and not (cube and #images == 6)) + local mips = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + mips += 1 + end + end + local out = Bytes.writer(img.width * img.height * 4 * #images + 200) + writeHeader(out, img.width, img.height, f, mips, dx10, #images, cube == true) + for _, im in images do + local level = im + for m = 1, mips do + local data, err = surface(level, f, opts) + if not data then + return nil, err + end + out:bytes(data) + if m < mips then + level = Texture.halve(level) + end + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +Dds.DXGI = DXGI + +return Dds diff --git a/tests/image/dds.luau b/tests/image/dds.luau new file mode 100644 index 0000000..f55a1df --- /dev/null +++ b/tests/image/dds.luau @@ -0,0 +1,212 @@ +-- image/dds tests: files from NVIDIA Texture Tools (BGRA, BC1..BC7 incl. BC6H, mips, DX10, cube / array / volume) +-- and ImageMagick against every surface's reference decode (Pillow per surface, Godot floats for BC6H); hand-written +-- uncompressed DXGI / legacy / FourCC formats against their values (rgba8 and native floats); our encoder's files read +-- by Pillow and nvddsinfo, and round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dds.py. +local T = require("@tests/T") +local Dds = require("@formats/image/dds") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/dds") + +local t = T.suite("dds") + +t:eq(Dds.name, "dds", "name") +t:check(Dds.caps.decode and Dds.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Dds.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +local function maxDiff(a: buffer, b: buffer, n: number): number + local worst = 0 + for i = 0, n * 4 - 1 do + worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))) + end + return worst +end + +-- tool-written files +local surfaces = 0 +for _, c in Fx.cases do + local img, err = dec(c.data, { mips = true }) + t:check(img, c.name .. ": " .. tostring(err)) + t:eq(img.meta.layout, c.layout, c.name .. ": layout") + t:eq(img.meta.source.mips, c.mips, c.name .. ": mips") + local frames = img.frames or { { image = img } } + local native = nil + for _, s in c.surfaces do + local im + if s.level == 0 then + local idx = s.layer * (if c.layout == "volume" then c.depth else 1) + s.slice + 1 + im = frames[idx] and frames[idx].image + else + im = img.meta.mipmaps and img.meta.mipmaps[s.level] + end + local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice) + t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size") + if s.floats then + native = native or dec(c.data, { native = true, mips = true }) + local nim = if s.level == 0 then native else native.meta.mipmaps[s.level] + t:eq(nim.format, "rgbaf32", label .. ": native rgbaf32") + local g = buffer.fromstring(s.floats) + local worst = 0 + for i = 0, s.w * s.h * 4 - 1 do + if i % 4 ~= 3 then + local a, b = buffer.readf32(nim.pixels, i * 4), buffer.readf32(g, i * 4) + worst = math.max(worst, math.abs(a - b) / math.max(math.abs(b), 1e-3)) + end + end + t:check(worst < 1e-3, label .. ": floats against Godot " .. worst) + else + local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h) + t:check(d <= s.tol, string.format("%s: %d off the reference", label, d)) + end + surfaces += 1 + end + -- surfaces = false keeps only the first + local one = dec(c.data, { surfaces = false }) + t:check(one and one.frames == nil, c.name .. ": surfaces = false") +end +t:note("%d tool-written files, %d surfaces match the references", #Fx.cases, surfaces) + +-- hand-written formats +for _, c in Fx.hand do + local img, err = dec(c.data) + t:check(img, c.name .. ": " .. tostring(err)) + local n = img.width * img.height + local d = maxDiff(img.pixels, buffer.fromstring(c.rgba8), n) + t:check(d <= 1, string.format("%s: rgba8 %d off", c.name, d)) + if c.floats then + local nimg = dec(c.data, { native = true }) + local f = buffer.fromstring(c.floats) + local worst = 0 + local bpp = Types.BPP[nimg.format] + for i = 0, n * 4 - 1 do + local want = buffer.readf32(f, i * 4) + local got + if nimg.format == "rgbaf32" then + got = buffer.readf32(nimg.pixels, i * 4) + elseif nimg.format == "rgba16" then + got = buffer.readu16(nimg.pixels, i * 2) / 65535 + else + got = buffer.readu8(nimg.pixels, i) / 255 + end + worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want))) + end + local tol = if nimg.format == "rgba8" then 1 / 255 elseif nimg.format == "rgba16" then 1 / 65535 else 1e-6 + t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", c.name, nimg.format, worst)) + t:check(bpp ~= nil, c.name .. ": a standard format") + end +end +t:note("%d hand-written formats match", #Fx.hand) + +-- our encoder: Pillow / nvddsinfo read the files, and they round-trip +local function source(w: number, h: number): buffer + local px = buffer.create(w * h * 4) + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5)) + buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5)) + end + end + return px +end +local src = source(37, 23) +for _, o in Fx.ours do + local img, err = dec(o.data, { mips = true, native = true }) + t:check(img, o.name .. ": " .. tostring(err)) + t:check(o.width == img.width and o.height == img.height, o.name .. ": nvddsinfo size") + local mips = img.meta.source.mips + t:eq(math.max(1, o.mipcount), mips, o.name .. ": nvddsinfo mip count") + if string.find(o.name, "mips") or string.find(o.name, "rgba16") or string.find(o.name, "rgba32f") or string.find(o.name, "cube") or string.find(o.name, "dx10") then + if not string.find(o.name, "rgba16f") and not string.find(o.name, "array") then + t:check(mips > 1 and #img.meta.mipmaps == mips - 1, o.name .. ": a mip chain") + end + end + if o.pillow then + local p = buffer.fromstring(o.pillow) + local exact = string.find(o.name, "rgba8") or string.find(o.name, "bgra8") + local d = maxDiff(img.pixels, p, img.width * img.height) + t:check(d == 0, string.format("%s: Pillow reads %d off our decode", o.name, d)) + if exact then + t:eq(buffer.tostring(p), buffer.tostring(src), o.name .. ": Pillow reads the source exactly") + end + end + if string.find(o.name, "cube") then + t:eq(img.meta.layout, "cube", o.name .. ": cube") + t:eq(#img.frames, 6, o.name .. ": 6 faces") + t:check(string.find(o.caps2, "FE00", 1, true) ~= nil, o.name .. ": nvddsinfo sees all faces") + elseif string.find(o.name, "array") then + t:eq(#img.frames, 6, o.name .. ": 6 layers") + t:eq(o.array, "6", o.name .. ": nvddsinfo array size") + end + if string.find(o.name, "rgba32f") then + t:check(string.find(o.dxgi, "R32G32B32A32_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi) + t:eq(img.format, "rgbaf32", o.name .. ": rgbaf32") + t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-6, o.name .. ": float values kept") + elseif string.find(o.name, "rgba16f") then + t:check(string.find(o.dxgi, "R16G16B16A16_FLOAT", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi) + t:check(math.abs(buffer.readf32(img.pixels, 36 * 16) - 4) < 1e-3, o.name .. ": half values") + elseif string.find(o.name, "rgba16") then + t:check(string.find(o.dxgi, "R16G16B16A16_UNORM", 1, true) ~= nil, o.name .. ": DXGI format " .. o.dxgi) + t:eq(img.format, "rgba16", o.name .. ": rgba16") + end +end +t:note("%d of our files read by Pillow / nvddsinfo", #Fx.ours) + +-- round trips +do + local img = Types.Image.new(37, 23) + img.pixels = src + for _, f in { "rgba8", "bgra8" } do + local back = dec(Dds.encode(img, { format = f :: any }) :: buffer) + t:eq(buffer.tostring(back.pixels), buffer.tostring(src), f .. " round trip") + end + local f = Types.Image.new(3, 2, "rgbaf32") + for i = 0, 23 do + buffer.writef32(f.pixels, i * 4, i * 0.37 - 2) + end + local back = dec(Dds.encode(f) :: buffer, { native = true }) + t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip") + local _, e1 = Dds.encode(f, { format = "bc1" }) + t:check(e1 and e1.code == Err.ARG, "bc1 needs rgba8") + local _, e2 = Dds.encode(img, { format = "bc7" :: any }) + t:check(e2 and e2.code == Err.ARG, "no bc7 encoder") +end + +-- sniff and errors +do + local c = Fx.cases[1] + t:eq(Dds.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Dds.sniff(Bytes.reader(buffer.fromstring("DDX \124\0\0\0"))), 0, "sniff other") + local _, e = dec(string.sub(c.data, 1, 100)) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = dec(string.sub(c.data, 1, 140)) + t:check(e2 and e2.code == Err.TRUNCATED, "no pixels: " .. tostring(e2)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, 4, 100) + local _, e3 = dec(bad) + t:check(e3 and e3.code == Err.CORRUPT, "bad header size") + local _, e4 = dec(c.data, { maxPixels = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "limit") + local info = Dds.info(Bytes.reader(buffer.fromstring(c.data))) + t:check(info and info.width > 0, "info") +end + +local samples = {} +for i, c in Fx.cases do + if i % 3 == 0 then + table.insert(samples, c.data) + end +end +for _, c in Fx.hand do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return dec(b, { mips = true }) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau new file mode 100644 index 0000000..cd0d87d --- /dev/null +++ b/tools/fixtures/_tex_encode.luau @@ -0,0 +1,75 @@ +-- tools/fixtures/_tex_encode.luau: our texture encoders' output for the reference tools to read (run by +-- tools/fixtures/{dds,ktx,exr}.py as `luau tools/fixtures/_tex_encode.luau -a `). Prints "name\thex" lines. +-- The source images are generated here (tools/fixtures/_tex_reference.py makes the same ones: source()). +local Types = require("@formats/Types") + +local which = ({ ... } :: { string })[1] or "dds" + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +-- the test pattern (x, y, channel) -> 0..1, the same formula as _tex_reference.source() +local function value(x: number, y: number, c: number, w: number, h: number, salt: number): number + if c == 0 then + return x / math.max(1, w - 1) + elseif c == 1 then + return y / math.max(1, h - 1) + elseif c == 2 then + return ((x * 7 + y * 13 + salt * 31) % 64) / 63 + end + return ((x + y + salt) % 5) / 4 +end + +local function image(w: number, h: number, fmt: string, salt: number, scale: number?): Types.Image + local img = Types.Image.new(w, h, fmt :: any) + for y = 0, h - 1 do + for x = 0, w - 1 do + for c = 0, 3 do + local v = value(x, y, c, w, h, salt) + local o = (y * w + x) * 4 + c + if fmt == "rgba8" then + buffer.writeu8(img.pixels, o, math.floor(v * 255 + 0.5)) + elseif fmt == "rgba16" then + buffer.writeu16(img.pixels, o * 2, math.floor(v * 65535 + 0.5)) + else + buffer.writef32(img.pixels, o * 4, if c < 3 then v * (scale or 1) else v) + end + end + end + end + return img +end + +local function emit(name: string, b: buffer?, err: any?) + if not b then + error(name .. ": " .. tostring(err)) + end + print(name .. "\t" .. hex(b)) +end + +if which == "dds" then + local Dds = require("@formats/image/dds") + local img = image(37, 23, "rgba8", 0) + for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do + emit("ours_" .. f .. ".dds", Dds.encode(img, { format = f :: any })) + emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { format = f :: any, mips = true })) + end + emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true })) + emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true })) + emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true })) + emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" })) + local cube = image(16, 16, "rgba8", 0) + cube.frames = {} + for i = 1, 6 do + cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + end + cube.meta.layout = "cube" + emit("ours_cube.dds", Dds.encode(cube, { mips = true })) + cube.meta.layout = "array" + emit("ours_array_bc1.dds", Dds.encode(cube, { format = "bc1" })) +end diff --git a/tools/fixtures/dds.py b/tools/fixtures/dds.py new file mode 100644 index 0000000..95957b4 --- /dev/null +++ b/tools/fixtures/dds.py @@ -0,0 +1,332 @@ +# DDS fixtures (tools/fixtures.py): +# - files written by NVIDIA Texture Tools (nvcompress: uncompressed BGRA, BC1 / BC1a / BC2 / BC3 / BC4 / BC5 / BC6H / +# BC7, with and without mip chains, legacy and DX10 headers; nvassemble: cube maps, arrays, volumes) and by +# ImageMagick (none / DXT1 / DXT5 with mip maps); +# - hand-written ones for the uncompressed DXGI and legacy formats nothing here writes (floats, snorm, packed, +# shared exponent, YUY2, luminance, bit masks, D3DFMT numbers), with the values they hold; +# - our encoder's files (tools/fixtures/_tex_encode.luau -a dds) read back by Pillow and nvddsinfo. +# Reference pixels: every surface is cut out here (an independent walk of the DDS layout) and decoded by Pillow +# (BCn through a one-surface DX10 file; BC6H by Godot as floats); the hand-written files carry their expected values. +# tests/gen/dds.luau { cases = { { name, data, layout, mips, layers, depth, surfaces = { { level, layer, slice, w, +# h, rgba?, floats?, tol } } } }, ours = { { name, data, pillow?, info } } } +import importlib.util, json, math, os, random, shutil, struct, subprocess, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/dds", "src/Formats/codecs/image/Bcn", "src/Formats/codecs/image/Texture.luau"] + +BLOCK = {"bc1": 8, "bc2": 16, "bc3": 16, "bc4": 8, "bc5": 16, "bc6h": 16, "bc7": 16} +DXGI_BC = {70: "bc1", 71: "bc1", 72: "bc1", 73: "bc2", 74: "bc2", 75: "bc2", 76: "bc3", 77: "bc3", 78: "bc3", 79: "bc4", + 80: "bc4", 82: "bc5", 83: "bc5", 94: "bc6h", 95: "bc6h", 97: "bc7", 98: "bc7", 99: "bc7"} +FOURCC_BC = {b"DXT1": "bc1", b"DXT3": "bc2", b"DXT5": "bc3", b"ATI1": "bc4", b"BC4U": "bc4", b"ATI2": "bc5", b"BC5U": "bc5"} + + +def png(w, h, rgba): + raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) + + +def source(w, h, salt=0): + out = bytearray() + for y in range(h): + for x in range(w): + r = x / max(1, w - 1) + g = y / max(1, h - 1) + b = ((x * 7 + y * 13 + salt * 31) % 64) / 63 + a = ((x + y + salt) % 5) / 4 + out += bytes(int(v * 255 + 0.5) for v in (r, g, b, a)) + return bytes(out) + + +def layout(data): + """an independent walk of a DDS file: (info, [(level, layer, slice, w, h, format, offset, size)])""" + flags, h, w, pitch, depth, mips = struct.unpack("<6I", data[8:32]) + pf_flags, fourcc, bits, rm, gm, bm, am = struct.unpack(" rgba8 with rounding (the Texel rule)""" + out = bytearray() + nb = bits // 8 + for i in range(0, len(raw), nb): + v = int.from_bytes(raw[i:i + nb], "little") + px = [] + for k, m in enumerate(masks): + if m == 0: + px.append(255 if k == 3 else 0) + continue + sh = (m & -m).bit_length() - 1 + mx = m >> sh + px.append(int(((v & m) >> sh) / mx * 255 + 0.5)) + out += bytes(px) + return bytes(out) + + +def references(ctx, cases): + """fill c["surfaces"] for files from the tools: Pillow per surface (BCn / masks), Godot floats for BC6H""" + pil_files, pil_targets, gd_jobs, gd_targets = [], [], [], [] + for c in cases: + info, surf = layout(c["data"]) + c["layout"] = "volume" if info["volume"] else ("cube" if info["cube"] else ("array" if info["layers"] > 1 else "2d")) + c["mips"], c["layers"], c["depth"] = info["mips"], info["layers"], info["depth"] + c["surfaces"] = [] + for (level, layer, s, w, h, fmt, off, size) in surf: + if level > 0 and (layer > 0 or s > 0): + continue + sd = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": 0} + raw = c["data"][off:off + size] + c["surfaces"].append(sd) + if fmt == "bc6h": + gd_jobs.append((raw, w, h, R.GODOT["bc6h"], True)) + gd_targets.append(sd) + elif fmt in BLOCK: + dx = {"bc1": 71, "bc2": 74, "bc3": 77, "bc4": 80, "bc5": 83, "bc7": 98}[fmt] + pil_files.append(R.dds_dx10(w, h, dx, raw)) + pil_targets.append((sd, fmt)) + elif fmt.startswith("rgb"): + sd["rgba"] = mask_decode(raw, info["bits"], info["masks"]) + elif fmt == "dxgi28": + sd["rgba"] = raw + elif fmt == "dxgi87": + sd["rgba"] = bytes(raw[i + k] for i in range(0, len(raw), 4) for k in (2, 1, 0, 3)) + for (sd, fmt), (mode, w, h, raw) in zip(pil_targets, R.pillow(ctx, pil_files)): + rgba = R.rgba_from(mode, raw) + if fmt == "bc5": + rgba = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(rgba)) + sd["rgba"] = rgba + for sd, out in zip(gd_targets, R.godot(ctx, gd_jobs)): + sd["floats"] = out + + +def hand_cases(rng): + """uncompressed formats with known values: (name, dds bytes, expected rgba8, expected floats or None)""" + W, H = 5, 3 + cases = [] + + def f32(v): + return struct.unpack("= 1 else int(v * 255 + 0.5)) + + def add(name, dds, texels): + """texels: list of (r, g, b, a) floats (the native values) -> expected rgba8 by the rules""" + cases.append({"name": name, "data": dds, "rgba8": bytes(q8(v) for t in texels for v in t), + "floats": b"".join(struct.pack("<4f", *t) for t in texels)}) + + # floats + vals = [(rng.uniform(-0.5, 3), rng.uniform(0, 1), rng.uniform(0, 1.5), rng.uniform(0, 1)) for _ in range(W * H)] + data = b"".join(struct.pack("<4f", *v) for v in vals) + add("dxgi R32G32B32A32_FLOAT", R.dds_dx10(W, H, 2, data), [tuple(f32(x) for x in v) for v in vals]) + data = b"".join(struct.pack("<4e", *v) for v in vals) + add("dxgi R16G16B16A16_FLOAT", R.dds_dx10(W, H, 10, data), [tuple(half(x) for x in v) for v in vals]) + add("d3dfmt 113 (A16B16G16R16F)", R.dds_fourcc(W, H, struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) + + def uf(v, mb): + e, m = v >> mb, v & ((1 << mb) - 1) + if e == 0: + return m / (1 << mb) * 2 ** -14 + return (1 + m / (1 << mb)) * 2 ** (e - 15) + p11 = [rng.getrandbits(32) & ~((1 << 30) | (1 << 9) | (1 << 20)) for _ in range(W * H)] # keep exponents < 31 + add("dxgi R11G11B10_FLOAT", R.dds_dx10(W, H, 26, b"".join(struct.pack("> 11) & 2047, 6), uf(v >> 22, 5), 1.0) for v in p11]) + add("dxgi R9G9B9E5_SHAREDEXP", R.dds_dx10(W, H, 67, b"".join(struct.pack("> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32]) + p16 = [rng.getrandbits(16) for _ in range(W * H)] + add("dxgi B5G6R5_UNORM", R.dds_dx10(W, H, 85, b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16]) + add("dxgi B5G5R5A1_UNORM", R.dds_dx10(W, H, 86, b"".join(struct.pack("> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16]) + add("dxgi B4G4R4A4_UNORM", R.dds_dx10(W, H, 115, b"".join(struct.pack("> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16]) + # legacy masks + def legacy(bits, flags, masks, data): + pf = struct.pack("<2I4s5I", 32, flags, b"\0\0\0\0", bits, *masks) + return R.dds_header(W, H, pf) + data + add("legacy R5G6B5", legacy(16, 0x40, (0xF800, 0x7E0, 0x1F, 0), b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in p16]) + add("legacy A1R5G5B5", legacy(16, 0x41, (0x7C00, 0x3E0, 0x1F, 0x8000), b"".join(struct.pack("> 10) & 31) / 31, ((v >> 5) & 31) / 31, (v & 31) / 31, (v >> 15) * 1.0) for v in p16]) + add("legacy X8R8G8B8", legacy(32, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32]) + add("legacy R8G8B8 (24-bit)", legacy(24, 0x40, (0xFF0000, 0xFF00, 0xFF, 0), b"".join(struct.pack("> 16) & 255) / 255, ((v >> 8) & 255) / 255, (v & 255) / 255, 1.0) for v in p32]) + add("legacy A2B10G10R10", legacy(32, 0x41, (0x3FF, 0xFFC00, 0x3FF00000, 0xC0000000), b"".join(struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) + add("legacy L8", legacy(8, 0x20000, (0xFF, 0, 0, 0), bytes(v[0] for v in u8)), [(v[0] / 255,) * 3 + (1.0,) for v in u8]) + add("legacy A8L8", legacy(16, 0x20001, (0xFF, 0, 0, 0xFF00), bytes(x for v in u8 for x in (v[0], v[3]))), + [(v[0] / 255,) * 3 + (v[3] / 255,) for v in u8]) + add("legacy A8", legacy(8, 0x2, (0, 0, 0, 0xFF), bytes(v[3] for v in u8)), [(0.0, 0.0, 0.0, v[3] / 255) for v in u8]) + add("legacy A4R4G4B4", legacy(16, 0x41, (0xF00, 0xF0, 0xF, 0xF000), b"".join(struct.pack("> 8) & 15) / 15, ((v >> 4) & 15) / 15, (v & 15) / 15, (v >> 12) / 15) for v in p16]) + # YUY2 (BT.601 limited range) + def ycc(y, u, v): + c, d, e = 1.164 * (y - 16), u - 128, v - 128 + cl = lambda x: max(0, min(255, int(math.floor(x + 0.5)))) + return (cl(c + 1.596 * e), cl(c - 0.392 * d - 0.813 * e), cl(c + 2.017 * d), 255) + W2 = 6 + yuy = bytes(rng.randrange(16, 240) for _ in range(W2 * H * 2)) + exp = [] + for y in range(H): + for x in range(W2): + q = y * W2 * 2 + (x // 2) * 4 + exp.append(ycc(yuy[q + (2 if x % 2 else 0)], yuy[q + 1], yuy[q + 3])) + pf = struct.pack("<2I4s5I", 32, 4, b"YUY2", 0, 0, 0, 0, 0) + cases.append({"name": "fourcc YUY2", "data": R.dds_header(W2, H, pf) + yuy, "rgba8": bytes(v for t in exp for v in t)}) + return cases + + +def generate(ctx): + rng = random.Random(5) + work = tempfile.mkdtemp(prefix="formats-dds-") + try: + cases = _tools(ctx, work) + references(ctx, cases) + hand = hand_cases(rng) + ours = _ours(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + ctx.emit("dds", {"cases": cases, "hand": hand, "ours": ours}) + + +def _tools(ctx, work): + cases = [] + for name, w, h in (("a", 37, 23), ("b", 64, 32)): + with open(os.path.join(work, name + ".png"), "wb") as f: + f.write(png(w, h, source(w, h))) + jobs = [] + for src in ("a", "b"): + for fl in ("-rgb", "-bc1", "-bc1a", "-bc2", "-bc3", "-bc4", "-bc5", "-bc7"): + jobs.append((src, fl, [])) + jobs.append((src, "-bc1", ["-nomips", "-dds10"])) + jobs.append(("a", "-bc6", ["-nomips"])) + script = [] + for src, fl, extra in jobs: + out = "%s%s%s.dds" % (src, fl, "".join(extra)) + script.append("nvcompress -silent %s %s %s.png %s" % (fl, " ".join(extra), src, out)) + for i in range(6): + with open(os.path.join(work, "f%d.png" % i), "wb") as f: + f.write(png(16, 16, source(16, 16, i + 1))) + faces = " ".join("f%d.png" % i for i in range(6)) + script.append("nvassemble -cube %s -o cube.dds" % faces) + script.append("nvassemble -array f0.png f1.png f2.png -o array.dds") + script.append("nvassemble -volume f0.png f1.png f2.png f3.png -o volume.dds") + ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(script))]) + im = [] + for comp in ("none", "dxt1", "dxt5"): + im.append("magick a.png -define dds:compression=%s -define dds:mipmaps=3 im_%s.dds" % (comp, comp)) + ctx.nix("imagemagick", ["sh", "-c", "cd %s && %s" % (work, " && ".join(im))]) + names = ["%s%s%s.dds" % (s, f, "".join(e)) for s, f, e in jobs] + ["cube.dds", "array.dds", "volume.dds"] + ["im_%s.dds" % c for c in ("none", "dxt1", "dxt5")] + for n in names: + cases.append({"name": n, "data": open(os.path.join(work, n), "rb").read()}) + return cases + + +def _ours(ctx, work): + exe = shutil.which("luau") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "dds"], cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + n, hx = line.split("\t", 1) + files[n] = bytes.fromhex(hx.strip()) + out = [] + pil, pil_idx = [], [] + names = sorted(files) + for n in names: + with open(os.path.join(work, n), "wb") as f: + f.write(files[n]) + info = ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && for f in %s; do echo \"== $f\"; nvddsinfo $f; done" % (work, " ".join(names))]).decode(errors="replace") + blocks = {} + for part in info.split("== ")[1:]: + n, body = part.split("\n", 1) + blocks[n.strip()] = body + for i, n in enumerate(names): + body = blocks.get(n, "") + def field(key): + for line in body.split("\n"): + if line.strip().startswith(key): + return line.split(":", 1)[1].strip() + return "" + e = {"name": n, "data": files[n], "width": int(field("Width") or 0), "height": int(field("Height") or 0), + "mipcount": int(field("Mipmap count") or 0), "dxgi": field("DXGI Format"), "array": field("Array size"), + "caps2": field("Caps 2")} + out.append(e) + if not any(k in n for k in ("rgba16", "rgba32f", "rgba16f", "cube", "array")): + pil.append(files[n]) + pil_idx.append(i) + for i, (mode, w, h, raw) in zip(pil_idx, R.pillow(ctx, pil)): + out[i]["pillow"] = R.rgba_from(mode, raw) + out[i]["pillowMode"] = mode + return out From 4dcb0051807c30ec6feb8894a8a6ff6600662a6e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:22:39 -0500 Subject: [PATCH 18/54] ws-video2-theora: video/ogv, Ogg video (Theora + Vorbis / Opus / FLAC) Demuxes every logical stream of the first Ogg group into containers/Demux: Theora (frame times from granules, Xiph-laced headers as track.config, comment tags in meta.tags), Vorbis / Opus / FLAC audio (headers in track.config) for the api's openAudio hook; open = Video.open. Sniff claims only Ogg files with a Theora BOS page. encode remuxes Theora (+ Vorbis / Opus pages from AudioWrap, interleaved by time). codecs/video/Theora gains info / comment helpers. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Theora/init.luau | 33 +- src/Formats/video/ogv/init.luau | 407 ++++++++++++++++++++++ tests/video/ogv.luau | 211 +++++++++++ tools/fixtures/theora.py | 10 + 6 files changed, 667 insertions(+), 7 deletions(-) create mode 100644 src/Formats/video/ogv/init.luau create mode 100644 tests/video/ogv.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5f34e95..d1c5a0e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -33,6 +33,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..206913c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -350,6 +350,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return require("@formats/video/ogv") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau index dd99346..c607c0e 100644 --- a/src/Formats/codecs/video/Theora/init.luau +++ b/src/Formats/codecs/video/Theora/init.luau @@ -23,6 +23,8 @@ local Decoder = require("@formats/codecs/video/Theora/Decoder") local Theora = {} +export type Info = Header.Info + export type Options = { maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) } @@ -75,6 +77,24 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + -- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then @@ -124,24 +144,23 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then return nil, Err.new(Err.CORRUPT, "missing Theora headers") end - local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) - if not ok or not info then - return nil, Err.from(if ok then ierr else tostring(info)) + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr end local maxPixels = opts and opts.maxPixels or 4096 * 2304 if info.frameWidth * info.frameHeight > maxPixels then return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") end - local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) - if not ok2 or not vendor or not comments then - return nil, Err.from(if ok2 then cerr else tostring(vendor)) + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr end local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) if not ok3 or not setup then return nil, Err.from(if ok3 then serr else tostring(setup)) end local st = Decoder.new(info, setup) - local tags = VorbisComment.tags(comments) return setmetatable({ info = info, vendor = vendor, diff --git a/src/Formats/video/ogv/init.luau b/src/Formats/video/ogv/init.luau new file mode 100644 index 0000000..0750440 --- /dev/null +++ b/src/Formats/video/ogv/init.luau @@ -0,0 +1,407 @@ +--!strict +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in formats-luau, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Demux = require("@formats/containers/Demux") +local AudioWrap = require("@formats/containers/AudioWrap") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + verify: boolean?, -- false: skip the page CRC checks (default true) + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv diff --git a/tests/video/ogv.luau b/tests/video/ogv.luau new file mode 100644 index 0000000..d1e0093 --- /dev/null +++ b/tests/video/ogv.luau @@ -0,0 +1,211 @@ +-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora +-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open +-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track +-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv) +-- read back, errors and the fuzz no-throw pass. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Ogv = require("@formats/video/ogv") +local Theora = require("@formats/codecs/video/Theora") +local AudioWrap = require("@formats/containers/AudioWrap") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("ogv") + +local AV = require("@tests/gen/theora_av") :: any +local Q0 = require("@tests/gen/theora_q0") :: any +local DUPE = require("@tests/gen/theora_dupe") :: any +local MKV = require("@tests/gen/theora_mkv") :: any +local OPUS = require("@tests/gen/theora_opus") :: any +local FLAC = require("@tests/gen/theora_flac") :: any + +local function file(fx: any): buffer + return Base64.decode(fx.file) :: buffer +end + +-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not +-- show (empty packets) must repeat the previous one +local function frames(v: any, fx: any, label: string, fps: number) + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local n, bad, shown, prev = 0, 0, 0, nil :: number? + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + local w = want[math.floor(f.pts * fps + 0.5)] + if w then + shown += 1 + if c ~= w then + bad += 1 + end + elseif c ~= prev then + bad += 1 + end + prev = c + end + t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)") + t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows") + return n +end + +-- 1. contract and sniffing +t:eq(Ogv.name, "ogv", "name") +t:eq(Ogv.category, "video", "category") +t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension") +t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis") +t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg") + +-- 2. Theora + Vorbis through the api +local v, err = F.video.open(file(AV)) +t:check(v ~= nil, "open: " .. tostring(err)) +if v then + t:eq(v.format, "ogv", "format") + t:eq(v.codec, "theora", "codec") + t:eq(v.width * 1000 + v.height, 160120, "size") + t:eq(v.frameRate, 25, "frame rate") + local dmx = v.demuxer :: any + t:eq(#dmx.tracks, 2, "two tracks") + local vt, at = dmx:track("video"), dmx:track("audio") + t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track") + t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track") + t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers") + t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration) + t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header") + local first = dmx:get(vt.id, 1) + t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0") + t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame") + frames(v, AV, "av", 25) + local pcm = Base64.decode(AV.pcm) :: buffer + C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20) + -- seeking + v:seek(0.5) + local f = v:nextFrame() + t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts)) + if f then + local want = nil + for _, w in AV.frames do + if w[1] == math.floor(f.pts * 25 + 0.5) then + want = w[2] + end + end + t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's") + end + -- remux ogv -> ogv + v:reset() + local out, rerr = F.save(v, nil, { format = "ogv" }) + t:check(out ~= nil, "remux: " .. tostring(rerr)) + if out then + t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff") + local v2 = F.video.open(out) :: any + t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks") + if v2 then + frames(v2, AV, "remux", 25) + C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20) + end + end + -- remux ogv -> mkv (V_THEORA) + v:reset() + local mk, merr = F.save(v, nil, { format = "mkv" }) + t:check(mk ~= nil, "to mkv: " .. tostring(merr)) + if mk then + local v3 = F.video.open(mk) :: any + t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track") + if v3 then + frames(v3, AV, "to mkv", 25) + end + end +end + +-- 3. Opus and FLAC audio tracks (FLAC: exact) +for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do + local fx, codec, rate = c[1], c[2], c[3] + local vd, e = F.video.open(file(fx)) + t:check(vd ~= nil, codec .. ": open: " .. tostring(e)) + if vd then + local at = (vd.demuxer :: any):track("audio") + t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track") + frames(vd, fx, codec, 25) + C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20) + if codec == "opus" then + vd:reset() + local out = F.save(vd, nil, { format = "ogv" }) + local v2 = out and F.video.open(out) :: any + t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio") + if v2 then + C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20) + end + end + end +end + +-- 4. an empty packet: a repeated frame with its own time +do + local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any + local n = 0 + local prev, dupAt = nil, nil + while true do + local f = vd:nextFrame() + if not f then + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + if n == 6 then + dupAt = f.pts + t:eq(c, prev, "dupe: frame 6 repeats frame 5") + end + prev = c + end + t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet") + t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)") + t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error") +end + +-- 5. Theora in Matroska -> ogv +do + local mv = F.video.open(file(MKV)) :: any + local out, e = F.save(mv, nil, { format = "ogv" }) + t:check(out ~= nil, "mkv -> ogv: " .. tostring(e)) + if out then + local v2 = Ogv.open(Bytes.reader(out)) :: any + frames(v2, MKV, "mkv -> ogv", 25) + end +end + +-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails +do + local vd = Ogv.open(Bytes.reader(file(AV))) :: any + local at = vd.demuxer:track("audio") + local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer + t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv") + local a = F.load(ogg, { name = "x.ogg" }) + t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio") + local v4, e4 = Ogv.open(Bytes.reader(ogg)) + t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")") + local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any) + t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED") + local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage"))) + t:check(eg ~= nil, "garbage: an error") + local cut = buffer.create(5000) + buffer.copy(cut, 0, file(Q0), 0, 5000) + local vc = Ogv.open(Bytes.reader(cut)) + t:check(vc ~= nil, "a truncated file opens") +end + +-- 7. fuzz +t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 4395444..7d05299 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -8,6 +8,7 @@ # tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original) # tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64), # rate, channels } +# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio # tests/gen/theora_mkv.luau { file (base64 .mkv), frames } # tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib @@ -184,6 +185,15 @@ def generate(ctx): pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"]) ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"), "width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2}) + # Theora + Opus, Theora + FLAC (mono, 0.5 s) + for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)): + path = os.path.join(tmp, "a_" + name + ".ogv") + ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, + "-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc + + ["-shortest", path]) + pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"]) + ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"), + "width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1}) # Theora in Matroska (CodecPrivate: the three headers, Xiph-laced) mkv = os.path.join(tmp, "t.mkv") ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv]) From a1d2e7218cd88f1a04f4b63e37502789ccabfb02 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:24:29 -0500 Subject: [PATCH 19/54] video/fli: FLI / FLC / FLX animations (read) Header (FLI 1/70 s, FLC ms, depths 8 / 15 / 16 / 24), frame chunks into containers/Demux, open() through the registry's flic decoder (codecs/video/Legacy/Flic); the ring frame is dropped unless opts.ringFrame. Fixtures encoded by tools/fixtures/fli.py (every chunk type) with ffmpeg's decode as the reference: bit-exact. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/video/fli/init.luau | 157 +++++++++++++ tests/video/fli.luau | 105 +++++++++ tools/fixtures/fli.py | 395 ++++++++++++++++++++++++++++++++ 5 files changed, 670 insertions(+) create mode 100644 src/Formats/video/fli/init.luau create mode 100644 tests/video/fli.luau create mode 100644 tools/fixtures/fli.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index b7c26a7..13d1e91 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -28,6 +28,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | | video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | fli | .fli .flc .flx | yes | - | streaming: true, video: "flic", depths: 8, 15, 16, 24 | `tests/video/fli.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | | video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 288846f..d26e1e1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -290,6 +290,18 @@ local list: { Entry } = { return require("@formats/video/avi") end, }, + { + name = "fli", + category = "video", + path = "video/fli", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, + load = function() + return require("@formats/video/fli") + end, + }, { name = "h264", category = "video", diff --git a/src/Formats/video/fli/init.luau b/src/Formats/video/fli/init.luau new file mode 100644 index 0000000..8224d48 --- /dev/null +++ b/src/Formats/video/fli/init.luau @@ -0,0 +1,157 @@ +--!strict +-- video/fli: Autodesk Animator FLI / Animator Pro FLC / FLX animations. New in formats-luau, written from the FLIC +-- file format description (Jim Kent, "FLC - Animator Pro Flic Files"; MultimediaWiki "FLIC"). +-- Read: the 128-byte header (FLI 0xAF11: speed in 1/70 s; FLC 0xAF12 / DTA 0xAF44: speed in ms; depth 8, 15, 16, 24: +-- an FLC that says 16 bits holds 5-5-5 pixels, as Animator Pro wrote them), prefix and other non-frame chunks skipped, +-- every frame chunk (0xF1FA, and 0xF5FA) a packet of a Demuxer; open() returns a VideoDecoder whose frames are rgba8 +-- (codecs/video/Legacy: palette chunks, BRUN, LC, SS2, BLACK, COPY, the deep-colour DTA chunks). The ring frame (the +-- extra frame after `frames` that leads back to the first) is not shown. Fli.demux(r) gives the Demuxer. +-- Not supported: writing, 1-bit FLICs, the X-COM / Magic Carpet game variants (audio chunks, 6-bit COLOR_256). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") + +-- ------------------------------------------------------------------------------------------------ contract +local Fli = { + name = "fli", + category = "video", + extensions = { "fli", "flc", "flx" }, + mime = { "video/x-fli", "video/fli", "video/x-flc" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video" }, + caps = { decode = true, encode = false, streaming = true, video = { "flic" }, depths = { 8, 15, 16, 24 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 128 +local FLI, FLC, DTA = 0xAF11, 0xAF12, 0xAF44 +local FRAME, FRAME2 = 0xF1FA, 0xF5FA + +-- ------------------------------------------------------------------------------------------------ sniff +function Fli.sniff(r: Bytes.Reader): number + local s = r:peek(18) + if #s < 18 then + return 0 + end + local magic = string.byte(s, 5) + string.byte(s, 6) * 256 + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return 0 + end + local w = string.byte(s, 9) + string.byte(s, 10) * 256 + local h = string.byte(s, 11) + string.byte(s, 12) * 256 + if w > 4096 or h > 4096 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- demux(r, opts?) -> the Demuxer | nil, Err +function Fli.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + local n = limit - base + if n < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the 128-byte header") + end + local hr = Bytes.reader(b, base, HEADER) + hr:skip(4) + local magic = hr:u16le() + local frames = hr:u16le() + local w, h = hr:u16le(), hr:u16le() + local depth = hr:u16le() + hr:skip(2) + local speed = hr:u32le() + if hr.err then + return nil, hr.err + end + if magic ~= FLI and magic ~= FLC and magic ~= DTA then + return nil, Err.new(Err.CORRUPT, string.format("bad magic 0x%04x", magic), 4) + end + if magic == FLI then + speed = speed % 65536 + end + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "no picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + if magic == FLI or depth == 0 then + depth = 8 + elseif magic == FLC and depth == 16 then + depth = 15 -- Animator Pro's 16-bit FLCs hold 5-5-5 pixels + end + if speed == 0 then + speed = 5 + end + local scale = if magic == FLI then 70 else 1000 + local track: Types.Track = { + id = 1, + kind = "video", + codec = "flic", + codecTag = string.format("0x%04X", magic), + timescale = scale, + width = w, + height = h, + frameRate = scale / speed, + default = true, + bitsPerPixel = depth, + } + -- the frame chunks + local offs, sizes = {}, {} + local p = base + HEADER + while p + 6 <= limit do + local size = buffer.readu32(b, p) + local cm = buffer.readu16(b, p + 4) + if size < 6 then + break + end + if (cm == FRAME or cm == FRAME2) and size > 6 then + if p + size > limit then + break -- a truncated last frame + end + table.insert(offs, p) + table.insert(sizes, size) + end + p += size + end + local count = #offs + if frames > 0 and count > frames and not (opts and opts.ringFrame) then + count = frames -- the ring frame is not a frame of the animation + end + local dmx = Demux.new("fli", { track }, b, { + type = magic, + frames = frames, + depth = depth, + speed = speed, + ringFrame = #offs > frames and frames > 0, + }) + for i = 1, count do + dmx:add(1, (i - 1) * speed, nil, speed, i == 1, offs[i], sizes[i]) + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Fli.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Fli.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Fli diff --git a/tests/video/fli.luau b/tests/video/fli.luau new file mode 100644 index 0000000..b163dc9 --- /dev/null +++ b/tests/video/fli.luau @@ -0,0 +1,105 @@ +-- video/fli tests: FLI (COLOR_64, BRUN, LC, BLACK, COPY, PSTAMP, a ring frame), FLC (prefix chunk, COLOR_256, SS2 with +-- line skips and the last-byte opcode, an empty frame), an odd-size FLC, and 15 / 16 / 24-bit FLCs (BRUN, DTA_BRUN, +-- DELTA, DTA_LC, COPY, DTA_COPY, BLACK), all encoded by the fixture script: every frame equals ffmpeg's decode +-- (CRC-32 of rgba), frame rates, the ring frame option, seeking, errors, the fuzz pass. Fixtures: tools/fixtures/fli.py. +local T = require("@tests/T") +local F = require("@formats") +local Fli = require("@formats/video/fli") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/fli_cases") + +local t = T.suite("fli") +t:eq(Fli.name, "fli", "name") +t:eq(Fli.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +for _, c in Fx do + local label = c.name + t:check(Fli.sniff(reader(c.data)) > 0, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "fli", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "flic", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-9, label .. ": frame rate " .. v.frameRate) + t:eq(v.track.bitsPerPixel, c.depth, label .. ": depth") + local ring = v.demuxer.meta.ringFrame + local want = if ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.25) + local f = v:nextFrame() + local k = math.floor(0.25 * c.rate + 1 - 1e-9) + 1 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + if ring then + local v2 = Fli.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Fli.open(reader(string.sub(Fx[1].data, 1, 100))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local bad = Fx[1].data + bad = string.sub(bad, 1, 4) .. "\0\0" .. string.sub(bad, 7) + t:eq(Fli.sniff(reader(bad)), 0, "bad magic: no sniff") + local _, e2 = Fli.open(reader(bad)) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + local big = string.sub(Fx[1].data, 1, 8) .. "\255\15\255\15" .. string.sub(Fx[1].data, 13) + local _, e3 = Fli.open(reader(big), { maxPixels = 2 ^ 20 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Fli.open(Bytes.reader(b)) + if v then + while v:nextFrame() do + end + end + return v +end, samples, { mutations = 12, garbage = 40, keepHeader = 16 }) +-- the frame decoder itself (codecs/video/Legacy/Flic, native: no pcall in between) +local Flic = require("@formats/codecs/video/Legacy").Flic +for _, c in { Fx[1], Fx[2], Fx[4], Fx[6] } do + local d = Fli.demux(reader(c.data)) + local packets = {} + for k = 1, math.min(4, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " frames", function(b: buffer) + local st = Flic.state(c.width, c.height, c.depth) + if st then + Flic.decode(st, b) + return Flic.image(st) + end + return nil + end, packets, { mutations = 20, garbage = 30 }) +end +t:done() diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py new file mode 100644 index 0000000..0428f02 --- /dev/null +++ b/tools/fixtures/fli.py @@ -0,0 +1,395 @@ +# FLI / FLC fixtures (tools/fixtures.py): ffmpeg cannot write FLICs, so this encodes them (every chunk type: COLOR_64, +# COLOR_256, BRUN, LC / DELTA_FLI, SS2 / DELTA_FLC with line skips and the last-byte opcode, BLACK, COPY, PSTAMP; a +# prefix chunk and a ring frame; 15-bit FLC, 16-bit DTA and 24-bit FLC with BRUN / DTA_BRUN / DELTA / DTA_LC / COPY / +# DTA_COPY) and uses ffmpeg's decode as the reference (CRC-32 of each frame as rgba). +# tests/gen/fli_cases.luau { { name, data, width, height, depth, rate, frames = { crc } } } +import importlib.util, os, random, struct, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + + +def le16(v): + return struct.pack("= 2: + out.append(("rep", seq[i], j - i + 1)) + i = j + 1 + else: + k = i + while k < len(seq) and k - i < maxrun and not (k + 2 < len(seq) and seq[k] == seq[k + 1] == seq[k + 2]): + k += 1 + k = max(k, i + 1) + out.append(("lit", seq[i:k])) + i = k + return out + + +def brun_line(units, unit_bytes): + """BRUN line body: > 0 repeat, < 0 literal (units are byte strings of unit_bytes each)""" + out = bytes([0]) + for p in runs(units): + if p[0] == "rep": + out += bytes([p[2]]) + p[1] + else: + out += bytes([s8(-len(p[1]))]) + b"".join(p[1]) + return out + + +def brun(img, bpp, pixel_runs, typ=15): + lines = b"" + for row in img: + if pixel_runs: + units = [row[x] for x in range(len(row))] + else: + flat = b"".join(row) + units = [flat[i:i + 1] for i in range(len(flat))] + lines += brun_line(units, bpp) + return chunk(typ, lines) + + +def lc(img, prev): + """DELTA_FLI (LC): first changed line, line count, per line (skip, run) packets on bytes""" + h, w = len(img), len(img[0]) + ch = [y for y in range(h) if img[y] != prev[y]] + if not ch: + return chunk(12, le16(0) + le16(0)) + y0, y1 = ch[0], ch[-1] + 1 + out = le16(y0) + le16(y1 - y0) + for y in range(y0, y1): + row, prow = img[y], prev[y] + packets = [] + x = 0 + while x < w: + skip = 0 + while x < w and row[x] == prow[x] and skip < 255: + skip += 1 + x += 1 + if x >= w: + break + e = x + while e < w and row[e] != prow[e] and e - x < 127: + e += 1 + seg = [bytes([v]) for v in row[x:e]] + pieces = runs(seg) + first = True + for p in pieces: + sk = skip if first else 0 + first = False + if p[0] == "rep": + packets.append(bytes([sk, s8(-p[2])]) + p[1]) + else: + packets.append(bytes([sk, len(p[1])]) + b"".join(p[1])) + x = e + out += bytes([len(packets)]) + b"".join(packets) + return chunk(12, out) + + +def ss2(img, prev, last_byte=False): + """DELTA_FLC (SS2) on 8-bit pixels: word packets, line-skip words, the last-byte opcode on odd lines""" + h, w = len(img), len(img[0]) + out = b"" + count = 0 + skip_lines = 0 + for y in range(h): + row, prow = img[y], prev[y] + if row == prow: + skip_lines += 1 + continue + if skip_lines: + out += le16(-skip_lines) + skip_lines = 0 + body = b"" + packets = 0 + lastop = last_byte and y % 2 == 1 and row[w - 1] != prow[w - 1] + ww = w - (1 if lastop else 0) + words = [bytes(row[x:x + 2]) for x in range(0, ww - ww % 2, 2)] + pwords = [bytes(prow[x:x + 2]) for x in range(0, ww - ww % 2, 2)] + i = 0 + while i < len(words): + skip = 0 + while i < len(words) and words[i] == pwords[i] and skip < 127: + skip += 1 + i += 1 + if i >= len(words): + break + e = i + while e < len(words) and words[e] != pwords[e] and e - i < 127: + e += 1 + first = True + for p in runs(words[i:e]): + sk = skip * 2 if first else 0 + first = False + if p[0] == "rep": + body += bytes([sk, s8(-p[2])]) + p[1] + else: + body += bytes([sk, len(p[1])]) + b"".join(p[1]) + packets += 1 + i = e + if lastop: + out += le16(0x8000 | row[w - 1]) + out += le16(packets) + body + count += 1 + return chunk(7, le16(count) + out) + + +def delta_deep(img, prev, bpp, typ=7): + """DELTA / DTA_LC on 15/16/24-bit pixels: negative words skip lines, packets (skip pixels, run)""" + h, w = len(img), len(img[0]) + out, count, skip_lines = b"", 0, 0 + for y in range(h): + row, prow = img[y], prev[y] + if row == prow: + skip_lines += 1 + continue + if skip_lines: + out += le16(-skip_lines) + skip_lines = 0 + body, packets, x = b"", 0, 0 + while x < w: + skip = 0 + while x < w and row[x] == prow[x] and skip < 255: + skip += 1 + x += 1 + if x >= w: + break + e = x + while e < w and row[e] != prow[e] and e - x < 127: + e += 1 + first = True + for p in runs(row[x:e]): + sk = skip if first else 0 + first = False + if p[0] == "rep": + body += bytes([sk, s8(-p[2])]) + p[1] + else: + body += bytes([sk, len(p[1])]) + b"".join(p[1]) + packets += 1 + x = e + out += le16(packets) + body + count += 1 + return chunk(typ, le16(count) + out) + + +def copy8(img): + w = len(img[0]) + pad = (w + 3) // 4 * 4 - w + return le32(6 + len(img) * (w + pad)) + le16(16) + b"".join(bytes(r) + bytes(pad) for r in img) + + +def copy_deep(img, bpp, typ=16): + w = len(img[0]) + body = b"".join(b"".join(r) + (bytes(bpp) if w % 2 else b"") for r in img) + return le32(6 + len(body)) + le16(typ) + body + + +# ---------------------------------------------------------------------------------------------------- pictures +def idx_frames(w, h, n, colors, seed): + rnd = random.Random(seed) + out = [] + for t in range(n): + img = [[(x // 6 + y // 4 + (t // 4)) % colors for x in range(w)] for y in range(h)] + sx, sy = (t * 7) % (w - 16), (t * 3) % (h - 12) + for y in range(sy, sy + 12): + for x in range(sx, sx + 16): + img[y][x] = (200 + t) % colors + for y in range(h // 2, h // 2 + 4): + for x in range(w // 2, w // 2 + 10): + img[y][x] = rnd.randrange(colors) + out.append(img) + return out + + +def deep_frames(w, h, n, bpp, seed): + rnd = random.Random(seed) + out = [] + for t in range(n): + img = [] + for y in range(h): + row = [] + for x in range(w): + v = ((x * 37 + y * 11 + t * 3) // 8) & 0x7FFF if bpp == 2 else ((x * 4) & 255, (y * 5) & 255, (t * 20) & 255) + if 10 + t <= x < 26 + t and 8 <= y < 20: + v = 0x7C00 if bpp == 2 else (250, 10, 10) + if bpp == 2 and h // 2 <= y < h // 2 + 3 and w // 2 <= x < w // 2 + 7: + v = rnd.randrange(65536) + row.append(struct.pack(" Date: Sat, 31 Oct 2026 14:25:51 -0500 Subject: [PATCH 20/54] ws-video2: codecs/video/Mpeg2 (MPEG-1/2 core, Main profile, 4:2:2, field pictures, dual prime), bit-exact with ffmpeg -idct int Mpeg1 is now the Mpeg2 module under its old name (core, tables and VLCs moved to Mpeg2/). Dsp.mc takes separate source / destination strides; Dsp.edge emulates edges. containers/MpegEs: field-picture pairs are one access unit (pictureStructure). Registry: mpeg1 and mpeg2 decode through Mpeg2.newVideoDecoder; more MPEG-2 FourCCs. --- docs/FORMATS.md | 5 +- src/Formats/codecs/video/Dsp.luau | 50 +- src/Formats/codecs/video/Mpeg1/Decoder.luau | 942 ----------- src/Formats/codecs/video/Mpeg1/init.luau | 267 +-- src/Formats/codecs/video/Mpeg2/Decoder.luau | 1490 +++++++++++++++++ .../codecs/video/{Mpeg1 => Mpeg2}/Tables.luau | 45 +- .../codecs/video/{Mpeg1 => Mpeg2}/Vlc.luau | 46 +- src/Formats/codecs/video/Mpeg2/init.luau | 364 ++++ src/Formats/codecs/video/Video/init.luau | 53 +- src/Formats/containers/MpegEs.luau | 34 +- tests/codecs/mpeg2.luau | 302 ++++ tools/fixtures/mpeg2.py | 178 ++ 12 files changed, 2487 insertions(+), 1289 deletions(-) delete mode 100644 src/Formats/codecs/video/Mpeg1/Decoder.luau create mode 100644 src/Formats/codecs/video/Mpeg2/Decoder.luau rename src/Formats/codecs/video/{Mpeg1 => Mpeg2}/Tables.luau (73%) rename src/Formats/codecs/video/{Mpeg1 => Mpeg2}/Vlc.luau (68%) create mode 100644 src/Formats/codecs/video/Mpeg2/init.luau create mode 100644 tests/codecs/mpeg2.luau create mode 100644 tools/fixtures/mpeg2.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f36b9a6..acfcdbf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -132,7 +132,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... - **video** - - codecs/video/Dsp: block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the + - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the - - codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from + - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder + - codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau. diff --git a/src/Formats/codecs/video/Dsp.luau b/src/Formats/codecs/video/Dsp.luau index 6bdc215..02b875d 100644 --- a/src/Formats/codecs/video/Dsp.luau +++ b/src/Formats/codecs/video/Dsp.luau @@ -16,7 +16,8 @@ -- -- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it -- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3) --- Dsp.mc(src, dst, stride, sOff, dOff, size, hx, hy, avg) -- half-pel prediction, size 8 / 16 (multiple of 4) +-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block +-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE) local Dsp = {} local readu8 = buffer.readu8 @@ -654,20 +655,20 @@ function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: bool end -- ------------------------------------------------------------------------------------------------ motion --- Motion-compensated prediction of a size x size block (size 8 or 16; 4 for H.263 chroma is fine too: any multiple --- of 4) from src at sOff to dst at dOff, both with stride (twice the plane width for field prediction), half-pel --- flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what dst holds (the second --- prediction of a bidirectional block, rounding up). Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) --- >> 1; the 4-tap average splits each byte into its low 2 bits and high 6 bits so no lane overflows. -function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: number, size: number, hx: number, hy: number, avg: boolean) - for _ = 1, size do - for i = 0, size - 4, 4 do +-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst +-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what +-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for +-- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits +-- each byte into its low 2 bits and high 6 bits so no lane overflows. +function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) + for _ = 1, h do + for i = 0, w - 4, 4 do local p if hx == 0 then if hy == 0 then p = readu32(src, sOff + i) else - local a, b = readu32(src, sOff + i), readu32(src, sOff + i + stride) + local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride) p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) end elseif hy == 0 then @@ -675,10 +676,10 @@ function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: nu p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1) else local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1) - local c, d = readu32(src, sOff + i + stride), readu32(src, sOff + i + stride + 1) + local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1) local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202 - local h = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) - p = h + band(rshift(l, 2), 0x0F0F0F0F) + local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2) + p = hi + band(rshift(l, 2), 0x0F0F0F0F) end if avg then local q = readu32(dst, dOff + i) @@ -686,8 +687,27 @@ function Dsp.mc(src: buffer, dst: buffer, stride: number, sOff: number, dOff: nu end writeu32(dst, dOff + i, p) end - sOff += stride - dOff += stride + sOff += sStride + dOff += dStride + end +end + +-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to +-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture +-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes). +Dsp.EDGE_STRIDE = 32 +Dsp.EDGE_SIZE = 32 * 34 + 4 +function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) + for j = 0, h do + local sy = y + j + sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy + local row = base + sy * stride + local o = j * 32 + for i = 0, w do + local sx = x + i + sx = if sx < 0 then 0 elseif sx >= pw then pw - 1 else sx + writeu8(out, o + i, readu8(src, row + sx)) + end end end diff --git a/src/Formats/codecs/video/Mpeg1/Decoder.luau b/src/Formats/codecs/video/Mpeg1/Decoder.luau deleted file mode 100644 index 0431576..0000000 --- a/src/Formats/codecs/video/Mpeg1/Decoder.luau +++ /dev/null @@ -1,942 +0,0 @@ ---!strict ---!native --- codecs/video/Mpeg1/Decoder: the MPEG-1 video decoding core (ISO/IEC 11172-2; native, never throws): I, P and B pictures, --- half-pel motion compensation, custom quantiser matrices, sequence headers anywhere in the stream. Absorbed from --- mpeg1-luau e2e2898 (same author; src/Mpeg1/Decoder.luau, unchanged but for this header and the requires), a port --- of jsmpeg's decoder (src/mpeg1.js by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt) with these changes for --- speed and accuracy in Luau: --- * table-driven VLC decoding (Vlc.luau) on a 32-bit peek instead of a bit-by-bit tree walk; --- * an accurate integer IDCT (the LL&M / "islow" factorisation, 13-bit constants) instead of jsmpeg's AAN --- approximation, so P-picture drift stays close to ffmpeg's decode; dequantisation follows the standard --- (magnitude, truncation toward zero, oddification); --- * B pictures (forward, backward and interpolated prediction, skipped macroblocks), which jsmpeg skips; --- * motion compensation four bytes at a time (SWAR rounding averages); --- * BT.601 limited-range YCbCr -> RGBA8 (jsmpeg's canvas path treats Y as full range). --- --- The IDCT is not codecs/image/Dct's: it computes the same islow transform (its put mode is bit-identical to --- Dct.idctBlock with a unit quantiser and no level shift, checked on 20000 random blocks), but MPEG-1 adds the --- residual of P / B blocks to the prediction before clamping, dequantises into i32 coefficients itself (MPEG --- rounding and oddification, not JPEG's q multiply) and writes u8 samples four per writeu32, where Dct clamps to --- 0..maxv, dequantises JPEG-style and writes u16 planes. --- --- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. --- Native code must never throw (an error unwinding through native code crashes Roblox Studio): every read --- position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), motion --- vectors are clamped to the reference picture, and bad data ends the slice instead of raising. -local V = require("@formats/codecs/video/Mpeg1/Vlc") -local T = require("@formats/codecs/video/Mpeg1/Tables") -local Dsp = require("@formats/codecs/video/Dsp") - -local readu8 = buffer.readu8 -local writeu8 = buffer.writeu8 -local readu32 = buffer.readu32 -local writeu32 = buffer.writeu32 -local readi32 = buffer.readi32 -local writei32 = buffer.writei32 -local band = bit32.band -local bor = bit32.bor -local bxor = bit32.bxor -local lshift = bit32.lshift -local rshift = bit32.rshift -local bswap = bit32.byteswap - -local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~1.5 KB, the pos check runs per macroblock - -local D = {} - -D.PICTURE_I = 1 -D.PICTURE_P = 2 -D.PICTURE_B = 3 - -local ZZ = buffer.create(64) -local DEF_INTRA = buffer.create(64) -- scan order (Q[n] = matrix[ZZ[n]]) -local DEF_NON_INTRA = buffer.create(64) -for i = 0, 63 do - buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) - buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) - buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[T.ZIG_ZAG[i]]) -end - --- clamp to 0..255 by lookup: CLAMP[v + COFF] for any v in [-COFF, COFF]. IDCT outputs are bounded by --- 64 * 2048 / 4 = 32768 for any coefficients, plus a prediction of up to 255. -local COFF = 40000 -local CLAMP = buffer.create(2 * COFF + 256) -for i = 0, 2 * COFF + 255 do - buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255)) -end - --- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - --- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) --- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. --- the constant terms, plus COFF * 256 so the sums stay positive for rshift -local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 -local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 -local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 - -local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS -local CBP, CBP_BITS = V.CBP, V.CBP_BITS -local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS -local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS -local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS -local DCT_FIRST, DCT_NEXT = V.DCT_FIRST, V.DCT_NEXT -local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB -local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } -local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } - -local idct = Dsp.idct -local fillBlock = Dsp.fill -local mc = Dsp.mc -D.idct = idct -D.mc = mc - --- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path -local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) - -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four - local chw = cw // 2 - local w2 = w // 2 -- whole pixel pairs per row - local stride = w * 4 - for y = 0, h - 1, 2 do - local yo = y * cw - local co = (y // 2) * chw - local o = y * stride - local two = y + 1 < h - for _ = 1, w2 do - local cb, cr = readu8(Cb, co), readu8(Cr, co) - co += 1 - local rr = cr * 409 + RBIAS - local gg = GBIAS - cb * 100 - cr * 208 - local bb = cb * 516 + BBIAS - local yv = readu8(Y, yo) * 298 - writeu32(out, o, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) - yv = readu8(Y, yo + 1) * 298 - writeu32(out, o + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) - if two then - yv = readu8(Y, yo + cw) * 298 - writeu32(out, o + stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) - yv = readu8(Y, yo + cw + 1) * 298 - writeu32(out, o + stride + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) - end - yo += 2 - o += 8 - end - if w % 2 == 1 then - -- the last column of an odd width - local cb, cr = readu8(Cb, co), readu8(Cr, co) - local rr = cr * 409 + RBIAS - local gg = GBIAS - cb * 100 - cr * 208 - local bb = cb * 516 + BBIAS - for k = 0, if two then 1 else 0 do - local yv = readu8(Y, yo + k * cw) * 298 - writeu32(out, o + k * stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) - end - end - end -end -D.toRgba = toRgba - -export type Store = { y: buffer, cb: buffer, cr: buffer, w: number, h: number, cw: number, tref: number, ptype: number, tag: any } - -export type Core = { - -- data - write: (src: buffer, off: number, n: number) -> (), - -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when - -- no picture is complete or it could not be decoded), and whether more data is needed. - nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), - toRgba: (s: Store, out: buffer) -> (), - reset: () -> (), - state: { - width: number, - height: number, - codedWidth: number, - codedHeight: number, - frameRate: number, - aspect: number, - bitRate: number, - sizeChanged: boolean, - pictures: number, - errors: number, - skipped: number, - clamped: number, -- motion vectors pointing outside the reference (clamped) - maxPixels: number, - refOld: Store?, - refNew: Store?, - }, -} - -function D.new(maxPixels: number?): Core - local state = { - width = 0, - height = 0, - codedWidth = 0, - codedHeight = 0, - frameRate = 0, - aspect = 0, - bitRate = 0, - sizeChanged = false, - pictures = 0, - errors = 0, - skipped = 0, - clamped = 0, - maxPixels = maxPixels or 4096 * 2304, - refOld = nil :: Store?, - refNew = nil :: Store?, - } - - -- bitstream - local data = buffer.create(64 * 1024 + PAD) - local dataLen = 0 - local readByte = 0 -- next byte to look at for a start code - local scanPos = 0 -- resume point of the picture-end scan - local pos = 0 -- bit position inside data - local err = false - - -- sequence - local hasSeq = false - local mbW, mbH, mbSize = 0, 0, 0 - local cw, chw = 0, 0 -- luma / chroma strides (coded widths) - local intraQ = buffer.create(64) - local nonIntraQ = buffer.create(64) - buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) - buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) - local stores: { Store } = {} - local bStore: Store? = nil - - -- picture / slice / macroblock state - local ptype = 0 - local fullPelFw, fwRSize, fwF = false, 0, 1 - local fullPelBw, bwRSize, bwF = false, 0, 1 - local curY, curCb, curCr = data, data, data - local fwY, fwCb, fwCr = data, data, data - local bwY, bwCb, bwCr = data, data, data - local qs = 1 - local mbAddr, mbRow, mbCol = 0, 0, 0 - local dcY, dcCb, dcCr = 128, 128, 128 - local pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 - local mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 - local mbIntra = false - local motFw, motBw = false, false - local blk = buffer.create(256) - local ws = buffer.create(256) - - local function peek32(): number - local bp = rshift(pos, 3) - local w = bswap(readu32(data, bp)) - local s = band(pos, 7) - if s ~= 0 then - w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) - end - return w - end - - local function read(n: number): number - local v = rshift(peek32(), 32 - n) - pos += n - return v - end - - local function vlc(lut: buffer, k: number): number - local e = readu32(lut, rshift(peek32(), 32 - k) * 4) - local l = rshift(e, 16) - if l == 0 then - err = true - return 0 - end - pos += l - return band(e, 0xFFFF) - 32768 - end - - -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 - local function findStart(from: number, to: number): number - local i = from - while i + 3 < to do - local c = readu8(data, i + 2) - if c > 1 then - i += 3 - elseif c == 1 then - if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then - return i - end - i += 3 - else - i += 1 - end - end - return -1 - end - - local function newStore(): Store - local sz = cw * mbH * 16 - local y = buffer.create(sz) - local cb = buffer.create(sz // 4) - local cr = buffer.create(sz // 4) - buffer.fill(y, 0, 16) -- black until a picture is decoded into it - buffer.fill(cb, 0, 128) - buffer.fill(cr, 0, 128) - return { y = y, cb = cb, cr = cr, w = state.width, h = state.height, cw = cw, tref = 0, ptype = 0, tag = nil } - end - - -- sequence header at byte p (after the start code); returns false when invalid - local function sequenceHeader(p: number): boolean - pos = p * 8 - local w = read(12) - local h = read(12) - local aspect = read(4) - local rate = read(4) - local bitRate = read(18) - pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag - if w == 0 or h == 0 or w * h > state.maxPixels then - return false - end - if read(1) == 1 then - for i = 0, 63 do - local v = read(8) - writeu8(intraQ, i, if v == 0 then 1 else v) - end - else - buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) - end - if read(1) == 1 then - for i = 0, 63 do - local v = read(8) - writeu8(nonIntraQ, i, if v == 0 then 1 else v) - end - else - buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) - end - state.frameRate = T.PICTURE_RATE[rate] or 0 - state.aspect = aspect - state.bitRate = bitRate * 400 - if w ~= state.width or h ~= state.height then - state.width = w - state.height = h - mbW = (w + 15) // 16 - mbH = (h + 15) // 16 - mbSize = mbW * mbH - cw = mbW * 16 - chw = mbW * 8 - state.codedWidth = cw - state.codedHeight = mbH * 16 - stores = { newStore(), newStore() } - bStore = newStore() - state.refOld = nil - state.refNew = nil - state.sizeChanged = true - end - hasSeq = true - return true - end - - local function decodeMotion(rsize: number, f: number, pmv: number): number - local code = vlc(MOTION, MOTION_BITS) - local d = code - if code ~= 0 and f ~= 1 then - local r = read(rsize) - d = (math.abs(code) - 1) * f + r + 1 - if code < 0 then - d = -d - end - end - local v = pmv + d - if v > f * 16 - 1 then - v -= f * 32 - elseif v < -f * 16 then - v += f * 32 - end - return v - end - - -- prediction of the current macroblock from one reference (avg: average into the first prediction) - local function predict(rY: buffer, rCb: buffer, rCr: buffer, mvH: number, mvV: number, avg: boolean) - local ch = mbH * 16 - -- luma - local hx, hy = band(mvH, 1), band(mvV, 1) - local sx = mbCol * 16 + mvH // 2 - local sy = mbRow * 16 + mvV // 2 - if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + 16 + hy > ch then - -- outside the picture: a corrupt vector, clamped (full-pel) - hx, hy = 0, 0 - sx = if sx < 0 then 0 elseif sx > cw - 16 then cw - 16 else sx - sy = if sy < 0 then 0 elseif sy > ch - 16 then ch - 16 else sy - state.clamped += 1 - end - mc(rY, curY, cw, sy * cw + sx, mbRow * 16 * cw + mbCol * 16, 16, hx, hy, avg) - -- chroma: vector / 2 truncated toward zero - local cH = if mvH < 0 then -((-mvH) // 2) else mvH // 2 - local cV = if mvV < 0 then -((-mvV) // 2) else mvV // 2 - hx, hy = band(cH, 1), band(cV, 1) - sx = mbCol * 8 + cH // 2 - sy = mbRow * 8 + cV // 2 - local chh = mbH * 8 - if sx < 0 or sy < 0 or sx + 8 + hx > chw or sy + 8 + hy > chh then - hx, hy = 0, 0 - sx = if sx < 0 then 0 elseif sx > chw - 8 then chw - 8 else sx - sy = if sy < 0 then 0 elseif sy > chh - 8 then chh - 8 else sy - end - local so = sy * chw + sx - local dof = mbRow * 8 * chw + mbCol * 8 - mc(rCb, curCb, chw, so, dof, 8, hx, hy, avg) - mc(rCr, curCr, chw, so, dof, 8, hx, hy, avg) - end - - -- prediction of a non-intra macroblock from the current motion state - local function predictMb() - if ptype == 2 then - predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) - elseif motFw then - predict(fwY, fwCb, fwCr, mvFwH, mvFwV, false) - if motBw then - predict(bwY, bwCb, bwCr, mvBwH, mvBwV, true) - end - elseif motBw then - predict(bwY, bwCb, bwCr, mvBwH, mvBwV, false) - end - end - - -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 - -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do - -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock - -- before the gap. - local covered = 0 - local gapFw, gapBw = false, false - local gapFwH, gapFwV, gapBwH, gapBwV = 0, 0, 0, 0 - local hasRef = false - local function conceal(from: number, to: number) - if from > to or not hasRef then - return - end - local sFw, sBw, sFwH, sFwV, sBwH, sBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV - if ptype == 3 then - motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV - if not motFw and not motBw then - motFw = true - mvFwH, mvFwV = 0, 0 - end - elseif ptype == 2 and gapFw then - mvFwH, mvFwV = gapFwH, gapFwV - else - mvFwH, mvFwV = 0, 0 - end - local pt = ptype - if pt == 1 then - ptype = 2 -- a damaged I picture: copy the previous reference - end - for a = from, to do - mbRow = a // mbW - mbCol = a % mbW - predictMb() - end - ptype = pt - motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV = sFw, sBw, sFwH, sFwV, sBwH, sBwV - end - - -- one 8x8 block: coefficients, dequantisation, IDCT into the picture. False on a bitstream error. - local function decodeBlock(b: number): boolean - local n = 0 - local q: buffer - local onlyDc = true - if mbIntra then - local dc - if b < 4 then - local size = vlc(DC_LUMA, DC_LUMA_BITS) - dc = dcY - if size > 0 then - local diff = read(size) - if band(diff, lshift(1, size - 1)) == 0 then - diff = diff + 1 - lshift(1, size) - end - dc += diff - end - dcY = dc - else - local size = vlc(DC_CHROMA, DC_CHROMA_BITS) - dc = if b == 4 then dcCb else dcCr - if size > 0 then - local diff = read(size) - if band(diff, lshift(1, size - 1)) == 0 then - diff = diff + 1 - lshift(1, size) - end - dc += diff - end - if b == 4 then - dcCb = dc - else - dcCr = dc - end - end - if err then - return false - end - if dc < 0 or dc > 255 then - -- out of range (corrupt data): clamp, which also bounds the IDCT input - dc = if dc < 0 then 0 else 255 - if b < 4 then - dcY = dc - elseif b == 4 then - dcCb = dc - else - dcCr = dc - end - end - writei32(blk, 0, dc * 8) - q = intraQ - n = 1 - else - q = nonIntraQ - end - local lut = if n == 0 then DCT_FIRST else DCT_NEXT - local intra = mbIntra - local qscale = qs - while true do - -- inline peek - local bp = rshift(pos, 3) - local w = bswap(readu32(data, bp)) - local s = band(pos, 7) - if s ~= 0 then - w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) - end - local e = readu32(lut, rshift(w, 24) * 4) - if e >= SUB then - e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) - end - local l = rshift(e, 16) - if l == 0 then - err = true - return false - end - local v = band(e, 0xFFFF) - lut = DCT_NEXT - if v == EOB then - pos += l - break - end - local run, level, neg - if v == ESC then - -- 6-bit run, then an 8-bit level or 0x00 / 0x80 and 8 more bits - pos += l - run = read(6) - level = read(8) - if level == 0 then - level = read(8) - elseif level == 128 then - level = read(8) - 256 - elseif level > 128 then - level -= 256 - end - neg = level < 0 - if neg then - level = -level - end - if level == 0 then - err = true - return false - end - else - run = rshift(v, 8) - level = band(v, 255) - neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code - pos += l + 1 - end - n += run - if n > 63 then - err = true - return false - end - -- dequantise the magnitude (truncating), make it odd toward zero, clamp - local m - if intra then - m = (level * 2 * qscale * readu8(q, n)) // 16 - else - m = ((level * 2 + 1) * qscale * readu8(q, n)) // 16 - end - if band(m, 1) == 0 and m ~= 0 then - m -= 1 - end - if neg then - if m > 2048 then - m = 2048 - end - m = -m - elseif m > 2047 then - m = 2047 - end - local zz = readu8(ZZ, n) - if zz ~= 0 then - onlyDc = false - end - writei32(blk, zz * 4, m) - n += 1 - end - -- reconstruction - local dst, off, stride - if b < 4 then - dst = curY - stride = cw - off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) - else - dst = if b == 4 then curCb else curCr - stride = chw - off = mbRow * 8 * chw + mbCol * 8 - end - if onlyDc then - fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) - writei32(blk, 0, 0) - else - idct(blk, dst, off, stride, not intra) - buffer.fill(blk, 0, 0, 256) - end - return true - end - - local function resetMv() - pmvFwH, pmvFwV, pmvBwH, pmvBwV = 0, 0, 0, 0 - mvFwH, mvFwV, mvBwH, mvBwV = 0, 0, 0, 0 - end - - -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. - local function decodeMacroblock(first: boolean, endBits: number): boolean - local inc = 0 - local t = vlc(MBAI, MBAI_BITS) - while t == 34 and not err and pos < endBits do -- stuffing - t = vlc(MBAI, MBAI_BITS) - end - while t == 35 and not err and pos < endBits do -- escape - inc += 33 - t = vlc(MBAI, MBAI_BITS) - end - if err or t < 1 or t > 33 then - err = true - return false - end - inc += t - if first then - mbAddr += inc - if mbAddr > covered and mbAddr <= mbSize then - conceal(covered, mbAddr - 1) - end - else - if mbAddr + inc >= mbSize then - err = true - return false - end - if inc > 1 then - dcY, dcCb, dcCr = 128, 128, 128 - if ptype == 2 then - resetMv() - end - -- skipped macroblocks: P copies the reference (zero vector), B repeats the previous prediction - for _ = 2, inc do - mbAddr += 1 - mbRow = mbAddr // mbW - mbCol = mbAddr % mbW - if ptype == 1 then - err = true -- no skipped macroblocks in I pictures - return false - end - predictMb() - end - end - mbAddr += 1 - end - if mbAddr < 0 or mbAddr >= mbSize then - err = true - return false - end - mbRow = mbAddr // mbW - mbCol = mbAddr % mbW - covered = mbAddr + 1 - - local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) - if err then - return false - end - mbIntra = band(mt, 1) ~= 0 - if band(mt, 0x10) ~= 0 then - qs = read(5) - if qs == 0 then - err = true - return false - end - end - if mbIntra then - resetMv() - else - dcY, dcCb, dcCr = 128, 128, 128 - motFw = band(mt, 8) ~= 0 - motBw = band(mt, 4) ~= 0 - if motFw then - pmvFwH = decodeMotion(fwRSize, fwF, pmvFwH) - pmvFwV = decodeMotion(fwRSize, fwF, pmvFwV) - mvFwH = if fullPelFw then pmvFwH * 2 else pmvFwH - mvFwV = if fullPelFw then pmvFwV * 2 else pmvFwV - elseif ptype == 2 then - resetMv() - end - if motBw then - pmvBwH = decodeMotion(bwRSize, bwF, pmvBwH) - pmvBwV = decodeMotion(bwRSize, bwF, pmvBwV) - mvBwH = if fullPelBw then pmvBwH * 2 else pmvBwH - mvBwV = if fullPelBw then pmvBwV * 2 else pmvBwV - end - if err then - return false - end - predictMb() - end - local cbp - if band(mt, 2) ~= 0 then - cbp = vlc(CBP, CBP_BITS) - if err then - return false - end - else - cbp = if mbIntra then 63 else 0 - end - if cbp ~= 0 then - for b = 0, 5 do - if band(cbp, rshift(32, b)) ~= 0 then - if not decodeBlock(b) then - return false - end - end - end - end - return pos <= endBits - end - - local function decodeSlice(row: number, endByte: number) - if row > mbH then - return - end - mbAddr = (row - 1) * mbW - 1 - resetMv() - dcY, dcCb, dcCr = 128, 128, 128 - motFw, motBw = false, false - qs = read(5) - local endBits = endByte * 8 - while read(1) == 1 and pos < endBits do - pos += 8 - end - if qs == 0 then - return - end - local first = true - while true do - if not decodeMacroblock(first, endBits) then - state.errors += 1 - buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded - break - end - first = false - -- the slice ends at a start code (byte aligned) or at the end of the picture data - local i = rshift(pos + 7, 3) - if i >= endByte then - break - end - if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then - break - end - end - -- the motion state a gap after this slice repeats (B pictures) - if mbIntra then - gapFw, gapBw = false, false - else - gapFw, gapBw, gapFwH, gapFwV, gapBwH, gapBwV = motFw, motBw, mvFwH, mvFwV, mvBwH, mvBwV - end - end - - -- the picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop - local function decodePicture(p: number, stop: number, tag: any): Store? - pos = p * 8 - local tref = read(10) - ptype = read(3) - pos += 16 -- vbv_delay - if ptype < 1 or ptype > 3 then - state.skipped += 1 -- D pictures and invalid types - return nil - end - if ptype >= 2 then - fullPelFw = read(1) == 1 - local fcode = read(3) - if fcode == 0 then - state.skipped += 1 - return nil - end - fwRSize = fcode - 1 - fwF = lshift(1, fwRSize) - end - if ptype == 3 then - fullPelBw = read(1) == 1 - local bcode = read(3) - if bcode == 0 then - state.skipped += 1 - return nil - end - bwRSize = bcode - 1 - bwF = lshift(1, bwRSize) - end - -- references: P from the newest, B between the two newest - local target: Store - local refOld, refNew = state.refOld, state.refNew - if ptype == 1 then - target = if stores[1] == refNew then stores[2] else stores[1] - if refNew then - fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr - end - elseif ptype == 2 then - if refNew == nil then - state.skipped += 1 - return nil - end - target = if stores[1] == refNew then stores[2] else stores[1] - fwY, fwCb, fwCr = refNew.y, refNew.cb, refNew.cr - else - if refOld == nil or refNew == nil or bStore == nil then - state.skipped += 1 - return nil - end - target = bStore :: Store - local ro, rn = refOld :: Store, refNew :: Store - fwY, fwCb, fwCr = ro.y, ro.cb, ro.cr - bwY, bwCb, bwCr = rn.y, rn.cb, rn.cr - end - curY, curCb, curCr = target.y, target.cb, target.cr - err = false - covered = 0 - hasRef = refNew ~= nil - gapFw, gapBw = false, false - mbIntra = false - - -- slices - local at = findStart(rshift(pos + 7, 3), stop) - while at >= 0 do - local code = readu8(data, at + 3) - if code >= 0x01 and code <= 0xAF then - pos = (at + 4) * 8 - err = false - decodeSlice(code, stop) - local nb = rshift(pos + 7, 3) - if nb >= stop then - break - end - at = findStart(nb, stop) - elseif code == 0xB2 or code == 0xB5 then - at = findStart(at + 4, stop) - else - break - end - end - conceal(covered, mbSize - 1) - state.pictures += 1 - target.tref = tref - target.ptype = ptype - target.tag = tag - if ptype ~= 3 then - -- the new picture becomes the newest reference - state.refOld = refNew - state.refNew = target - end - return target - end - - local core = {} :: Core - core.state = state - - function core.write(src: buffer, off: number, n: number) - if n <= 0 then - return - end - -- drop consumed bytes, keeping the scan state relative - if readByte > 0 then - local keep = dataLen - readByte - if keep > 0 then - buffer.copy(data, 0, data, readByte, keep) - end - scanPos = math.max(0, scanPos - readByte) - dataLen = keep - readByte = 0 - end - local need = dataLen + n + PAD - if need > buffer.len(data) then - local cap = buffer.len(data) - while cap < need do - cap *= 2 - end - local nb = buffer.create(cap) - buffer.copy(nb, 0, data, 0, dataLen) - data = nb - end - buffer.copy(data, dataLen, src, off, n) - dataLen += n - buffer.fill(data, dataLen, 0, PAD) - end - - function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) - while true do - local at = findStart(readByte, dataLen) - if at < 0 then - -- keep the last 3 bytes: a start code may straddle the next write - readByte = math.max(readByte, dataLen - 3) - if atEnd then - readByte = dataLen - end - return nil, true - end - local code = readu8(data, at + 3) - if code == 0xB3 or code == 0x00 then - -- a unit is complete when the next unit start (or the end of the data) follows it - local stop = dataLen - do - local s = findStart(math.max(at + 4, scanPos), dataLen) - while s >= 0 do - local c = readu8(data, s + 3) - if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then - break - end - s = findStart(s + 4, dataLen) - end - if s < 0 then - if not atEnd then - scanPos = math.max(at + 4, dataLen - 3) - readByte = at - return nil, true - end - else - stop = s - end - end - scanPos = 0 - readByte = stop - if code == 0xB3 then - if not sequenceHeader(at + 4) then - state.errors += 1 - end - elseif hasSeq then - local s = decodePicture(at + 4, stop, tag) - if s then - return s, false - end - else - state.skipped += 1 - end - else - readByte = at + 4 -- GOP header, sequence end, user data, stray slices - end - end - end - - function core.toRgba(s: Store, out: buffer) - toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) - end - - function core.reset() - dataLen = 0 - readByte = 0 - scanPos = 0 - state.refOld = nil - state.refNew = nil - end - - return core -end - -return D diff --git a/src/Formats/codecs/video/Mpeg1/init.luau b/src/Formats/codecs/video/Mpeg1/init.luau index 25c7d10..54f1aa4 100644 --- a/src/Formats/codecs/video/Mpeg1/init.luau +++ b/src/Formats/codecs/video/Mpeg1/init.luau @@ -1,262 +1,11 @@ --!strict --- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from --- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder --- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, --- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. --- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom --- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display --- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau). --- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding. --- --- local dec = Mpeg1.new({ reorder = true, rgba = false }) --- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts --- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) --- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces --- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek --- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... } --- --- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). -local Types = require("@formats/Types") -local D = require("@formats/codecs/video/Mpeg1/Decoder") +-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder +-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / +-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2. +local Mpeg2 = require("@formats/codecs/video/Mpeg2") -local Mpeg1 = {} +export type Frame = Mpeg2.Frame +export type Options = Mpeg2.Options +export type Decoder = Mpeg2.Decoder -Mpeg1.PICTURE_I = 1 -Mpeg1.PICTURE_P = 2 -Mpeg1.PICTURE_B = 3 - -export type Frame = { - width: number, - height: number, - pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } - pictureType: number, -- 1 I, 2 P, 3 B - temporalReference: number, -- the picture's 10-bit display index within its GOP - index: number, -- frames returned so far (1-based) - tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) - -- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth, - -- chroma stride codedWidth / 2 - y: buffer, - cb: buffer, - cr: buffer, - codedWidth: number, -} - -export type Options = { - reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the - -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is - -- display order for streams without B-frames. - rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) - maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) -} - -local Decoder = {} -Decoder.__index = Decoder - -export type Decoder = typeof(setmetatable( - {} :: { - _core: D.Core, - _reorder: boolean, - _rgba: boolean, - _held: D.Store?, - _pixels: buffer?, - _count: number, - width: number, - height: number, - frameRate: number, - bitRate: number, - stats: { pictures: number, errors: number, skipped: number }, - }, - Decoder -)) - -function Mpeg1.new(opts: Options?): Decoder - local o: Options = if type(opts) == "table" then opts else {} - local core = D.new(o.maxPixels) - return setmetatable({ - _core = core, - _reorder = o.reorder == true, - _rgba = o.rgba ~= false, - _held = nil, - _pixels = nil, - _count = 0, - width = 0, - height = 0, - frameRate = 0, - bitRate = 0, - stats = { pictures = 0, errors = 0, skipped = 0 }, - }, Decoder) -end - -local function emit(self: Decoder, s: D.Store): Frame - local core = self._core - local pixels: buffer? = nil - if self._rgba then - local need = s.w * s.h * 4 - local px = self._pixels - if px == nil or buffer.len(px) ~= need then - px = buffer.create(need) - self._pixels = px - end - core.toRgba(s, px :: buffer) - pixels = px - end - self._count += 1 - return { - width = s.w, - height = s.h, - pixels = pixels, - pictureType = s.ptype, - temporalReference = s.tref, - index = self._count, - tag = s.tag, - y = s.y, - cb = s.cb, - cr = s.cr, - codedWidth = s.cw, - } -end - -local function sync(self: Decoder) - local st = self._core.state - self.width = st.width - self.height = st.height - self.frameRate = st.frameRate - self.bitRate = st.bitRate - self.stats.pictures = st.pictures - self.stats.errors = st.errors - self.stats.skipped = st.skipped -end - --- a decoded picture -> the frame to return now (nil while reordering holds it) -local function handle(self: Decoder, s: D.Store): Frame? - if not self._reorder or s.ptype == D.PICTURE_B then - return emit(self, s) - end - local prev = self._held - self._held = s - if prev then - return emit(self, prev) - end - return nil -end - -local function run(self: Decoder, atEnd: boolean, tag: any): Frame? - local core = self._core - while true do - local s, needData = core.nextPicture(atEnd, tag) - sync(self) - if s then - local f = handle(self, s) - if f then - return f - end - elseif needData then - return nil - end - end -end - -local function append(self: Decoder, data: any, offset: number?, len: number?): boolean - local src: buffer - if type(data) == "string" then - src = buffer.fromstring(data) - elseif type(data) == "buffer" then - src = data - else - return false - end - local total = buffer.len(src) - local off = math.floor(tonumber(offset) or 0) - if off < 0 or off > total then - return false - end - local n = math.floor(tonumber(len) or (total - off)) - if n < 0 or off + n > total then - return false - end - self._core.write(src, off, n) - return true -end - --- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. -function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean - return append(self, data, offset, len) -end - --- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is --- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). -function Decoder.decodeFrame(self: Decoder): Frame? - return run(self, false, nil) -end - --- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). --- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. -function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? - if not append(self, data, offset, len) then - return nil - end - return run(self, true, tag) -end - --- At the end of the stream: decodes what is left of the written data, then returns the reference picture held --- for reordering. Call until it returns nil. -function Decoder.flush(self: Decoder): Frame? - local f = run(self, true, nil) - if f then - return f - end - local held = self._held - if held then - self._held = nil - return emit(self, held) - end - return nil -end - --- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). -function Decoder.reset(self: Decoder) - self._core.reset() - self._held = nil -end - --- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to --- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8 --- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame. -function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image? - if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then - return nil - end - local w, h, cw = frame.width, frame.height, frame.codedWidth - if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then - return nil - end - local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 - if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then - return nil - end - local img - if rgba then - img = Types.Image.new(w, h) - D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) - else - img = Types.Image.new(w, h, "yuv420p") - local px = img.pixels - for y = 0, h - 1 do - buffer.copy(px, y * w, frame.y, y * cw, w) - end - local o = w * h - for y = 0, oh - 1 do - buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) - buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) - end - end - img.meta.source = { - format = "mpeg1", - pictureType = frame.pictureType, - temporalReference = frame.temporalReference, - range = if rgba then nil else "limited", - } - return img -end - -return Mpeg1 +return Mpeg2 diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau new file mode 100644 index 0000000..4cd982c --- /dev/null +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -0,0 +1,1490 @@ +--!strict +--!native +-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). +-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame +-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion +-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; +-- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser +-- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported: +-- 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js +-- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion +-- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int), +-- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid +-- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2 +-- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are +-- clamped (ffmpeg skips the prediction): both only matter for corrupt data. +-- +-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture. +-- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock), +-- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising. +local V = require("@formats/codecs/video/Mpeg2/Vlc") +local T = require("@formats/codecs/video/Mpeg2/Tables") +local Dsp = require("@formats/codecs/video/Dsp") + +local readu8 = buffer.readu8 +local writeu8 = buffer.writeu8 +local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local readi32 = buffer.readi32 +local writei32 = buffer.writei32 +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift +local bswap = bit32.byteswap +local idct = Dsp.idct +local fillBlock = Dsp.fill +local mc = Dsp.mc + +local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2 KB, the pos check runs per macroblock + +local D = {} + +D.PICTURE_I = 1 +D.PICTURE_P = 2 +D.PICTURE_B = 3 + +-- scan index -> natural position (zigzag, alternate); default matrices in natural order +local ZZ = buffer.create(64) +local ALT = buffer.create(64) +local DEF_INTRA = buffer.create(64) +local DEF_NON_INTRA = buffer.create(64) +for i = 0, 63 do + buffer.writeu8(ZZ, i, T.ZIG_ZAG[i]) + buffer.writeu8(ALT, i, T.ALTERNATE_SCAN[i]) + buffer.writeu8(DEF_INTRA, i, T.DEFAULT_INTRA_QUANT_MATRIX[i]) + buffer.writeu8(DEF_NON_INTRA, i, T.DEFAULT_NON_INTRA_QUANT_MATRIX[i]) +end +local NON_LINEAR = buffer.create(32) +for i = 0, 31 do + buffer.writeu8(NON_LINEAR, i, T.NON_LINEAR_QSCALE[i]) +end + +local COFF = 40000 + +local MBAI, MBAI_BITS = V.MBAI, V.MBAI_BITS +local CBP, CBP_BITS = V.CBP, V.CBP_BITS +local MOTION, MOTION_BITS = V.MOTION, V.MOTION_BITS +local DC_LUMA, DC_LUMA_BITS = V.DC_LUMA, V.DC_LUMA_BITS +local DC_CHROMA, DC_CHROMA_BITS = V.DC_CHROMA, V.DC_CHROMA_BITS +local DCT_FIRST, DCT_NEXT, DCT_B15 = V.DCT_FIRST, V.DCT_NEXT, V.DCT_B15 +local SUB, ESC, EOB = V.SUB, V.ESC, V.EOB +local MBTYPE = { V.MBTYPE_I, V.MBTYPE_P, V.MBTYPE_B } +local MBTYPE_BITS = { V.MBTYPE_I_BITS, V.MBTYPE_P_BITS, V.MBTYPE_B_BITS } + +-- BT.601 limited range: R = 1.164 (Y - 16) + 1.596 (Cr - 128), G = 1.164 (Y - 16) - 0.392 (Cb - 128) - 0.813 (Cr - +-- 128), B = 1.164 (Y - 16) + 2.017 (Cb - 128), in 8-bit fixed point. The rounding offsets (-128, -160, -72 / 256) +-- are fitted to ffmpeg's swscale output, which lands about half a level below round-to-nearest. +-- the constant terms, plus COFF * 256 so the sums stay positive for rshift +local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128 +local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160 +local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 + +-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path +local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four + local chw = cw // 2 + local w2 = w // 2 -- whole pixel pairs per row + local stride = w * 4 + for y = 0, h - 1, 2 do + local yo = y * cw + local co = (y // 2) * chw + local o = y * stride + local two = y + 1 < h + for _ = 1, w2 do + local cb, cr = readu8(Cb, co), readu8(Cr, co) + co += 1 + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + local yv = readu8(Y, yo) * 298 + writeu32(out, o, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + 1) * 298 + writeu32(out, o + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + if two then + yv = readu8(Y, yo + cw) * 298 + writeu32(out, o + stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + yv = readu8(Y, yo + cw + 1) * 298 + writeu32(out, o + stride + 4, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + yo += 2 + o += 8 + end + if w % 2 == 1 then + -- the last column of an odd width + local cb, cr = readu8(Cb, co), readu8(Cr, co) + local rr = cr * 409 + RBIAS + local gg = GBIAS - cb * 100 - cr * 208 + local bb = cb * 516 + BBIAS + for k = 0, if two then 1 else 0 do + local yv = readu8(Y, yo + k * cw) * 298 + writeu32(out, o + k * stride, math.clamp(rshift(yv + rr, 8) - COFF, 0, 255) + math.clamp(rshift(yv + gg, 8) - COFF, 0, 255) * 256 + math.clamp(rshift(yv + bb, 8) - COFF, 0, 255) * 65536 + 0xFF000000) + end + end + end +end +D.toRgba = toRgba + +-- YCbCr 4:2:2 planes -> RGBA8: chroma row y for luma row y, chroma column x // 2 +local function toRgba422(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer) + local chw = cw // 2 + for y = 0, h - 1 do + local o = y * w * 4 + for x = 0, w - 1 do + local c = y * chw + x // 2 + local cb, cr = readu8(Cb, c), readu8(Cr, c) + local yv = readu8(Y, y * cw + x) * 298 + local r = math.clamp(rshift(yv + cr * 409 + RBIAS, 8) - COFF, 0, 255) + local g = math.clamp(rshift(yv + GBIAS - cb * 100 - cr * 208, 8) - COFF, 0, 255) + local b = math.clamp(rshift(yv + cb * 516 + BBIAS, 8) - COFF, 0, 255) + writeu32(out, o + x * 4, r + g * 256 + b * 65536 + 0xFF000000) + end + end +end +D.toRgba422 = toRgba422 + +export type Store = { + y: buffer, + cb: buffer, + cr: buffer, + w: number, + h: number, + cw: number, -- luma stride (coded width); chroma stride cw / 2 + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + tref: number, + ptype: number, + tag: any, + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1: true) + fields: boolean, -- coded as two field pictures + tff: boolean, -- top_field_first + rff: boolean, -- repeat_first_field + clamped: number, -- predictions from outside the reference (edge-emulated) in the last picture decoded into it + concealed: { [number]: boolean }, -- macroblock rows (of the frame) with macroblocks no slice covered (concealed) +} + +export type Core = { + -- data + write: (src: buffer, off: number, n: number) -> (), + -- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when + -- no picture is complete or it could not be decoded), and whether more data is needed. A frame coded as two field + -- pictures comes back once, after its second field. + nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean), + toRgba: (s: Store, out: buffer) -> (), + reset: () -> (), + state: { + width: number, + height: number, + codedWidth: number, + codedHeight: number, + frameRate: number, + aspect: number, + bitRate: number, + mpeg2: boolean, + chroma: number, + progressive: boolean, -- progressive_sequence + profileLevel: number, + sizeChanged: boolean, + pictures: number, + errors: number, + skipped: number, + clamped: number, -- motion vectors pointing outside the reference (clamped) + maxPixels: number, + refOld: Store?, + refNew: Store?, + }, +} + +function D.new(maxPixels: number?): Core + local state = { + width = 0, + height = 0, + codedWidth = 0, + codedHeight = 0, + frameRate = 0, + aspect = 0, + bitRate = 0, + mpeg2 = false, + chroma = 1, + progressive = true, + profileLevel = 0, + sizeChanged = false, + pictures = 0, + errors = 0, + skipped = 0, + clamped = 0, + maxPixels = maxPixels or 4096 * 2304, + refOld = nil :: Store?, + refNew = nil :: Store?, + } + + -- bitstream + local data = buffer.create(64 * 1024 + PAD) + local dataLen = 0 + local readByte = 0 -- next byte to look at for a start code + local scanPos = 0 -- resume point of the picture-end scan + local pos = 0 -- bit position inside data + local err = false + + -- sequence + local hasSeq = false + local mpeg2 = false + local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 + local progSeq = true + local mbW, mbH = 0, 0 -- frame size in macroblocks + local cw, chw = 0, 0 -- luma / chroma strides (coded widths) + local lumaH, chromaH = 0, 0 -- plane heights (coded) + local intraQ = buffer.create(64) -- natural order + local nonIntraQ = buffer.create(64) + local chromaIntraQ = buffer.create(64) + local chromaNonIntraQ = buffer.create(64) + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + buffer.copy(chromaIntraQ, 0, DEF_INTRA, 0, 64) + buffer.copy(chromaNonIntraQ, 0, DEF_NON_INTRA, 0, 64) + local stores: { Store } = {} + local bStore: Store? = nil + -- the sequence header's values, applied (and the stores allocated) once its extension has been seen + local seqW, seqH = 0, 0 + + -- picture + local ptype = 0 + local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] + local fullPelFw, fullPelBw = false, false + local dcPrec = 0 + local picStruct = 3 -- 1 top field, 2 bottom field, 3 frame + local fpfd = true -- frame_pred_frame_dct + local concealMv = false + local qScaleType = 0 + local intraVlc = false + local scan = ZZ + local tff, rff, progFrame = true, false, true + local fieldPic = false + local secondField = false + local parity = 0 -- the current field (0 top, 1 bottom) + local mbRows, mbSize = 0, 0 -- of the current picture (field pictures: half the frame's rows) + local lstride, lbase, cstride, cbase = 0, 0, 0, 0 -- plane addressing of the current picture + local cur: Store? = nil + local curY, curCb, curCr = data, data, data + local fwS: Store? = nil + local bwS: Store? = nil + local pending: Store? = nil -- a first field waiting for its second + local pendingStruct = 0 + local pendingFw: Store? = nil + local pendingBw: Store? = nil + + -- slice / macroblock + local qscale = 2 + local mbAddr, mbRow, mbCol = 0, 0, 0 + local dcY, dcCb, dcCr = 128, 128, 128 + local mbIntra = false + local motFw, motBw = false, false + local motionType = 1 -- 1 frame (field pictures: field 16x16), 2 field (frame pictures), 3 16x8, 4 dual prime + local dctType = 0 + -- vectors: MV[(d * 4 + k) * 2 + c + 1] (direction d, vector k: 0 / 1 the two fields or halves, 2 / 3 dual-prime + -- opposite-parity vectors; component c); PMV[(d * 2 + r) * 2 + c + 1]; FSEL[d * 2 + r + 1] + local MV = table.create(16, 0) + local PMV = table.create(8, 0) + local FSEL = table.create(4, 0) + local blk = buffer.create(256) + + local function peek32(): number + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + return w + end + + local function read(n: number): number + local v = rshift(peek32(), 32 - n) + pos += n + return v + end + + local function vlc(lut: buffer, k: number): number + local e = readu32(lut, rshift(peek32(), 32 - k) * 4) + local l = rshift(e, 16) + if l == 0 then + err = true + return 0 + end + pos += l + return band(e, 0xFFFF) - 32768 + end + + -- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1 + local function findStart(from: number, to: number): number + local i = from + while i + 3 < to do + local c = readu8(data, i + 2) + if c > 1 then + i += 3 + elseif c == 1 then + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 then + return i + end + i += 3 + else + i += 1 + end + end + return -1 + end + + local function newStore(): Store + local y = buffer.create(cw * lumaH) + local cb = buffer.create(chw * chromaH) + local cr = buffer.create(chw * chromaH) + buffer.fill(y, 0, 16) -- black until a picture is decoded into it + buffer.fill(cb, 0, 128) + buffer.fill(cr, 0, 128) + return { + y = y, + cb = cb, + cr = cr, + w = state.width, + h = state.height, + cw = cw, + chroma = chroma, + tref = 0, + ptype = 0, + tag = nil, + mpeg2 = mpeg2, + progressive = true, + fields = false, + tff = true, + rff = false, + clamped = 0, + concealed = {}, + } + end + + local function loadMatrix(q: buffer) + for i = 0, 63 do + local v = read(8) + writeu8(q, readu8(ZZ, i), if v == 0 then 1 else v) + end + end + + -- the sequence (header + extension) takes effect: sizes and stores + local function applySequence(): boolean + local w, h = seqW, seqH + if w == 0 or h == 0 or w * h > state.maxPixels then + return false + end + local mh = if mpeg2 and not progSeq then 2 * ((h + 31) // 32) else (h + 15) // 16 + if w ~= state.width or h ~= state.height or mh ~= mbH or chroma ~= state.chroma or mpeg2 ~= state.mpeg2 then + state.width = w + state.height = h + state.chroma = chroma + state.mpeg2 = mpeg2 + mbW = (w + 15) // 16 + mbH = mh + cw = mbW * 16 + chw = mbW * 8 + lumaH = mbH * 16 + chromaH = if chroma == 2 then lumaH else lumaH // 2 + state.codedWidth = cw + state.codedHeight = lumaH + stores = { newStore(), newStore() } + bStore = newStore() + state.refOld = nil + state.refNew = nil + pending = nil + state.sizeChanged = true + end + state.progressive = progSeq + hasSeq = true + return true + end + + -- sequence header at byte p (after the start code); false when invalid + local function sequenceHeader(p: number): boolean + pos = p * 8 + local w = read(12) + local h = read(12) + local aspect = read(4) + local rate = read(4) + local bitRate = read(18) + pos += 1 + 10 + 1 -- marker, vbv_buffer_size, constrained_parameters_flag + if read(1) == 1 then + loadMatrix(intraQ) + else + buffer.copy(intraQ, 0, DEF_INTRA, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + else + buffer.copy(nonIntraQ, 0, DEF_NON_INTRA, 0, 64) + end + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + state.frameRate = T.PICTURE_RATE[rate] or 0 + state.aspect = aspect + state.bitRate = bitRate * 400 + seqW, seqH = w, h + mpeg2 = false -- until a sequence extension follows + chroma = 1 + progSeq = true + return w > 0 and h > 0 + end + + local function sequenceExtension() + state.profileLevel = read(8) + progSeq = read(1) == 1 + local cf = read(2) + seqW += lshift(read(2), 12) + seqH += lshift(read(2), 12) + state.bitRate += lshift(read(12), 18) * 400 + pos += 1 + 8 + 1 -- marker, vbv_buffer_size_extension, low_delay + local n = read(2) + local d = read(5) + state.frameRate = state.frameRate * (n + 1) / (d + 1) + mpeg2 = true + chroma = if cf == 2 then 2 else 1 -- 4:4:4 (3) is not supported: decoded as 4:2:0 (wrong but safe) + if cf == 3 then + state.errors += 1 + end + end + + local function quantMatrixExtension() + if read(1) == 1 then + loadMatrix(intraQ) + buffer.copy(chromaIntraQ, 0, intraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(nonIntraQ) + buffer.copy(chromaNonIntraQ, 0, nonIntraQ, 0, 64) + end + if read(1) == 1 then + loadMatrix(chromaIntraQ) + end + if read(1) == 1 then + loadMatrix(chromaNonIntraQ) + end + end + + local function fcode(v: number): number + return if v < 1 or v > 9 then 1 else v + end + + local function pictureCodingExtension() + fc00, fc01, fc10, fc11 = fcode(read(4)), fcode(read(4)), fcode(read(4)), fcode(read(4)) + dcPrec = read(2) + picStruct = read(2) + tff = read(1) == 1 + fpfd = read(1) == 1 + concealMv = read(1) == 1 + qScaleType = read(1) + intraVlc = read(1) == 1 + scan = if read(1) == 1 then ALT else ZZ + rff = read(1) == 1 + pos += 1 -- chroma_420_type + progFrame = read(1) == 1 + if picStruct == 0 then + picStruct = 3 + err = true + end + end + + -- an extension (00 00 01 B5) at byte p + local function extension(p: number) + pos = p * 8 + local id = read(4) + if id == 1 then + sequenceExtension() + elseif id == 3 then + quantMatrixExtension() + elseif id == 8 then + pictureCodingExtension() + end + end + + local function decodeMotion(f: number, pred: number): number + local code = vlc(MOTION, MOTION_BITS) + local d = code + local rsize = f - 1 + if code ~= 0 and rsize > 0 then + local r = read(rsize) + d = lshift(math.abs(code) - 1, rsize) + r + 1 + if code < 0 then + d = -d + end + end + local range = lshift(16, rsize) + return (pred + d + range) % (2 * range) - range + end + + -- ------------------------------------------------------------------------------------------------ prediction + -- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0: + -- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the + -- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the + -- first prediction. + local EDGE = buffer.create(Dsp.EDGE_SIZE) + local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean) + local stride, sb, db, ph = cw, 0, 0, lumaH + local cs, csb, cdb = chw, 0, 0 + if sp >= 0 then + stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2 + cs, csb, cdb = 2 * chw, sp * chw, dp * chw + end + -- luma + local hx, hy = band(mvx, 1), band(mvy, 1) + local sx = mbCol * 16 + (mvx - hx) // 2 + local sy = rowY + (mvy - hy) // 2 + local dOff = db + rowY * stride + mbCol * 16 + if sx < 0 or sy < 0 or sx + 16 + hx > cw or sy + h + hy > ph then + -- outside the reference (invalid in MPEG; ffmpeg's encoder writes such half-sample vectors at the right / + -- bottom edge): predicted from repeated edge samples, as the encoder meant (ffmpeg's decoder skips it) + Dsp.edge(rY, stride, sb, sx, sy, 16, h, cw, ph, EDGE) + mc(EDGE, 32, 0, curY, stride, dOff, 16, h, hx, hy, avg) + state.clamped += 1; + (cur :: Store).clamped += 1 + else + mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) + end + -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 + local mx = if mvx < 0 then -((-mvx) // 2) else mvx // 2 + local cx, cy, chh, cph, chx, chy + chx = band(mx, 1) + cx = mbCol * 8 + (mx - chx) // 2 + if chroma == 1 then + local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + chy = band(my, 1) + cy = rowY // 2 + (my - chy) // 2 + chh, cph = h // 2, ph // 2 + else + chy = band(mvy, 1) + cy = rowY + (mvy - chy) // 2 + chh, cph = h, ph + end + local cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * cs + mbCol * 8 + if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then + Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) + Dsp.edge(rCr, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) + mc(EDGE, 32, 0, curCr, cs, cdOff, 8, chh, chx, chy, avg) + else + local so = csb + cy * cs + cx + mc(rCb, cs, so, curCb, cs, cdOff, 8, chh, chx, chy, avg) + mc(rCr, cs, so, curCr, cs, cdOff, 8, chh, chx, chy, avg) + end + end + + -- the reference frame for field fs of direction d in a field picture: the second field of a P frame takes the + -- opposite parity from its own first field + local function fieldRef(d: number, fs: number): Store + if d == 0 then + if secondField and ptype == 2 and fs ~= parity then + return cur :: Store + end + return (fwS or cur) :: Store + end + return (bwS or cur) :: Store + end + + -- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock + local function predictDir(d: number, avg: boolean) + local o = d * 8 + if not fieldPic then + local r = (if d == 0 then fwS else bwS) or cur :: Store + local ry, rcb, rcr = r.y, r.cb, r.cr + if motionType == 1 then + mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 2 then + mcPart(ry, rcb, rcr, FSEL[d * 2 + 1], 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, FSEL[d * 2 + 2], 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + else -- dual prime: each field from the same parity (MV 0 / 1), averaged with the opposite parity (MV 2 / 3) + mcPart(ry, rcb, rcr, 0, 0, mbRow * 8, 8, MV[o + 1], MV[o + 2], avg) + mcPart(ry, rcb, rcr, 1, 1, mbRow * 8, 8, MV[o + 3], MV[o + 4], avg) + mcPart(ry, rcb, rcr, 1, 0, mbRow * 8, 8, MV[o + 5], MV[o + 6], true) + mcPart(ry, rcb, rcr, 0, 1, mbRow * 8, 8, MV[o + 7], MV[o + 8], true) + end + return + end + if motionType == 1 then + local fs = FSEL[d * 2 + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + elseif motionType == 3 then + for k = 0, 1 do + local fs = FSEL[d * 2 + k + 1] + local r = fieldRef(d, fs) + mcPart(r.y, r.cb, r.cr, fs, parity, mbRow * 16 + k * 8, 8, MV[o + k * 2 + 1], MV[o + k * 2 + 2], avg) + end + else -- dual prime: same parity, then the opposite one (the first field of this frame for a second field) + local r = (fwS or cur) :: Store + mcPart(r.y, r.cb, r.cr, parity, parity, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) + local q = if secondField then cur :: Store else r + mcPart(q.y, q.cb, q.cr, 1 - parity, parity, mbRow * 16, 16, MV[o + 5], MV[o + 6], true) + end + end + + -- the prediction of a non-intra macroblock from the current motion state + local function predictMb() + if ptype == 2 then + predictDir(0, false) + elseif motFw then + predictDir(0, false) + if motBw then + predictDir(1, true) + end + elseif motBw then + predictDir(1, false) + end + end + + local function resetPmv() + for i = 1, 8 do + PMV[i] = 0 + end + end + + -- a skipped macroblock's motion (13818-2 7.6.6): P a zero vector (field pictures: from the same parity); B the + -- previous macroblock's directions with its first vectors as frame (or same-parity field) prediction + local function skipMotion() + motionType = 1 + FSEL[1], FSEL[3] = parity, parity + if ptype == 2 then + resetPmv() + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = PMV[1], PMV[2] + MV[9], MV[10] = PMV[5], PMV[6] + end + end + + -- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 + -- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do + -- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock + -- before the gap. + local covered = 0 + local gapFw, gapBw = false, false + local GAP = table.create(16, 0) + local gapType = 1 + local hasRef = false + local SAVE = table.create(16, 0) + local function conceal(from: number, to: number) + if from > to or not hasRef then + return + end + local sFw, sBw, sType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, SAVE) + local f1, f2, f3, f4 = FSEL[1], FSEL[2], FSEL[3], FSEL[4] + if ptype == 3 and mpeg2 then + -- both references, zero vectors (ffmpeg's error concealment of B macroblocks, without its deblocking) + motFw, motBw, motionType = true, true, 1 + MV[1], MV[2], MV[9], MV[10] = 0, 0, 0, 0 + elseif ptype == 3 then + motFw, motBw, motionType = gapFw, gapBw, gapType + table.move(GAP, 1, 16, 1, MV) + if not motFw and not motBw then + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + end + else + motionType = 1 + if not (ptype == 2 and gapFw) then + MV[1], MV[2] = 0, 0 + else + MV[1], MV[2] = GAP[1], GAP[2] + end + end + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = parity, parity, parity, parity + local pt = ptype + if pt == 1 then + ptype = 2 -- a damaged I picture: copy the previous reference + end + local c = (cur :: Store).concealed + for a = from, to do + mbRow = a // mbW + mbCol = a % mbW + predictMb() + if fieldPic then + c[mbRow * 2] = true + c[mbRow * 2 + 1] = true + else + c[mbRow] = true + end + end + ptype = pt + motFw, motBw, motionType = sFw, sBw, sType + table.move(SAVE, 1, 16, 1, MV) + FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4 + end + + -- ------------------------------------------------------------------------------------------------ blocks + -- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture. + -- False on a bitstream error. + local function decodeBlock(b: number): boolean + local n = 0 + local q: buffer + local onlyDc = true + local luma = b < 4 + local parityOdd = 1 -- MPEG-2 mismatch control: 1 while the coefficient sum is even + if mbIntra then + local dc + local size + if luma then + size = vlc(DC_LUMA, DC_LUMA_BITS) + dc = dcY + else + size = vlc(DC_CHROMA, DC_CHROMA_BITS) + dc = if b % 2 == 0 then dcCb else dcCr + end + if size > 0 then + local diff = read(size) + if band(diff, lshift(1, size - 1)) == 0 then + diff = diff + 1 - lshift(1, size) + end + dc += diff + end + if err then + return false + end + local top = lshift(256, dcPrec) - 1 + if dc < 0 or dc > top then + dc = if dc < 0 then 0 else top -- corrupt data: clamped, which also bounds the IDCT input + end + if luma then + dcY = dc + elseif b % 2 == 0 then + dcCb = dc + else + dcCr = dc + end + local v = lshift(dc, 3 - dcPrec) + writei32(blk, 0, v) + parityOdd = bit32.bxor(1, band(v, 1)) + q = if luma then intraQ else chromaIntraQ + n = 1 + else + q = if luma then nonIntraQ else chromaNonIntraQ + end + local lut = if mbIntra and intraVlc then DCT_B15 elseif n == 0 then DCT_FIRST else DCT_NEXT + local nextLut = if mbIntra and intraVlc then DCT_B15 else DCT_NEXT + local intra = mbIntra + local qs = qscale + local m2 = mpeg2 + while true do + -- inline peek + local bp = rshift(pos, 3) + local w = bswap(readu32(data, bp)) + local s = band(pos, 7) + if s ~= 0 then + w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s)) + end + local e = readu32(lut, rshift(w, 24) * 4) + if e >= SUB then + e = readu32(lut, (band(e, 0xFFFF) * 256 + band(rshift(w, 16), 255)) * 4) + end + local l = rshift(e, 16) + if l == 0 then + err = true + return false + end + local v = band(e, 0xFFFF) + lut = nextLut + if v == EOB then + pos += l + break + end + local run, level, neg + if v == ESC then + pos += l + run = read(6) + if m2 then + -- a 12-bit signed level + level = read(12) + if level >= 2048 then + level -= 4096 + end + else + -- an 8-bit level or 0x00 / 0x80 and 8 more bits + level = read(8) + if level == 0 then + level = read(8) + elseif level == 128 then + level = read(8) - 256 + elseif level > 128 then + level -= 256 + end + end + neg = level < 0 + if neg then + level = -level + end + if level == 0 then + err = true + return false + end + else + run = rshift(v, 8) + level = band(v, 255) + neg = band(lshift(w, l), 0x80000000) ~= 0 -- the sign bit follows the code + pos += l + 1 + end + n += run + if n > 63 then + err = true + return false + end + local zz = readu8(scan, n) + -- dequantise the magnitude (ffmpeg's arithmetic); MPEG-1 makes it odd toward zero + local m + if intra then + m = (level * qs * readu8(q, zz)) // 16 + else + m = ((level * 2 + 1) * qs * readu8(q, zz)) // 32 + end + if not m2 then + if m == 0 then + m = -1 + elseif band(m, 1) == 0 then + m -= 1 + end + end + if neg then + m = -m + end + parityOdd = bit32.bxor(parityOdd, band(m, 1)) + -- saturate + if m > 2047 then + m = 2047 + elseif m < -2048 then + m = -2048 + end + if zz ~= 0 then + onlyDc = false + end + writei32(blk, zz * 4, m) + n += 1 + end + if m2 and parityOdd == 1 then + -- mismatch control: toggle the last coefficient's lowest bit + local v = readi32(blk, 252) + writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1) + onlyDc = false + end + -- reconstruction + local dst, off, stride + if luma then + dst = curY + if fieldPic then + stride = lstride + off = lbase + (mbRow * 16 + (if b >= 2 then 8 else 0)) * stride + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + elseif dctType == 1 then + stride = 2 * cw + off = (mbRow * 16 + (if b >= 2 then 1 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + else + stride = cw + off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) + end + else + dst = if b % 2 == 0 then curCb else curCr + local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock + if chroma == 1 then + stride = cstride + off = cbase + mbRow * 8 * stride + mbCol * 8 + elseif fieldPic then + stride = cstride + off = cbase + (mbRow * 16 + k * 8) * stride + mbCol * 8 + elseif dctType == 1 then + stride = 2 * chw + off = (mbRow * 16 + k) * chw + mbCol * 8 + else + stride = chw + off = (mbRow * 16 + k * 8) * chw + mbCol * 8 + end + end + if onlyDc then + fillBlock(dst, off, stride, (readi32(blk, 0) + 4) // 8, not intra) + writei32(blk, 0, 0) + else + idct(blk, dst, off, stride, not intra) + buffer.fill(blk, 0, 0, 256) + end + return true + end + + -- ------------------------------------------------------------------------------------------------ macroblocks + local function getQscale(code: number): number + if qScaleType == 1 then + return readu8(NON_LINEAR, code) + end + return code * 2 + end + + -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) + local function motionVectors(d: number) + local fh, fv = if d == 0 then fc00 else fc10, if d == 0 then fc01 else fc11 + local o, p, f = d * 8, d * 4, d * 2 + if motionType == 1 and not fieldPic then + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + if (d == 0 and fullPelFw) or (d == 1 and fullPelBw) then + x *= 2 + y *= 2 + end + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 2 then + -- field prediction in a frame picture: vertical predictors in frame units + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2] // 2) + PMV[p + r * 2 + 1] = x + PMV[p + r * 2 + 2] = y * 2 + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + elseif motionType == 1 then + -- field picture, 16x16 + FSEL[f + 1] = read(1) + local x = decodeMotion(fh, PMV[p + 1]) + local y = decodeMotion(fv, PMV[p + 2]) + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y, y + MV[o + 1], MV[o + 2] = x, y + elseif motionType == 3 then + -- 16x8 (field pictures) + for r = 0, 1 do + FSEL[f + r + 1] = read(1) + local x = decodeMotion(fh, PMV[p + r * 2 + 1]) + local y = decodeMotion(fv, PMV[p + r * 2 + 2]) + PMV[p + r * 2 + 1], PMV[p + r * 2 + 2] = x, y + MV[o + r * 2 + 1], MV[o + r * 2 + 2] = x, y + end + else + -- dual prime + local shift = if fieldPic then 0 else 1 + local x = decodeMotion(fh, PMV[p + 1]) + local dmx = if read(1) == 1 then 1 - 2 * read(1) else 0 + local y = decodeMotion(fv, if shift == 1 then PMV[p + 2] // 2 else PMV[p + 2]) + local dmy = if read(1) == 1 then 1 - 2 * read(1) else 0 + PMV[p + 1], PMV[p + 3] = x, x + PMV[p + 2], PMV[p + 4] = y * (shift + 1), y * (shift + 1) + MV[o + 1], MV[o + 2], MV[o + 3], MV[o + 4] = x, y, x, y + -- the opposite-parity vectors: scaled by the field distance, rounded away from zero + local xp, yp = if x > 0 then 1 else 0, if y > 0 then 1 else 0 + if not fieldPic then + local m = if tff then 1 else 3 + MV[o + 5] = (x * m + xp) // 2 + dmx + MV[o + 6] = (y * m + yp) // 2 + dmy - 1 + m = 4 - m + MV[o + 7] = (x * m + xp) // 2 + dmx + MV[o + 8] = (y * m + yp) // 2 + dmy + 1 + else + MV[o + 5] = (x + xp) // 2 + dmx + MV[o + 6] = (y + yp) // 2 + dmy + (if parity == 0 then -1 else 1) + end + end + end + + -- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data. + local function decodeMacroblock(first: boolean, endBits: number): boolean + local inc = 0 + local t = vlc(MBAI, MBAI_BITS) + while t == 34 and not err and pos < endBits do -- stuffing + t = vlc(MBAI, MBAI_BITS) + end + while t == 35 and not err and pos < endBits do -- escape + inc += 33 + t = vlc(MBAI, MBAI_BITS) + end + if err or t < 1 or t > 33 then + err = true + return false + end + inc += t + if first then + mbAddr += inc + if mbAddr > covered and mbAddr <= mbSize then + conceal(covered, mbAddr - 1) + end + else + if mbAddr + inc >= mbSize then + err = true + return false + end + if inc > 1 then + if ptype == 1 then + err = true -- no skipped macroblocks in I pictures + return false + end + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + skipMotion() + for _ = 2, inc do + mbAddr += 1 + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + predictMb() + end + end + mbAddr += 1 + end + if mbAddr < 0 or mbAddr >= mbSize then + err = true + return false + end + mbRow = mbAddr // mbW + mbCol = mbAddr % mbW + covered = mbAddr + 1 + + local mt = vlc(MBTYPE[ptype], MBTYPE_BITS[ptype]) + if err then + return false + end + mbIntra = band(mt, 1) ~= 0 + local pattern = band(mt, 2) ~= 0 + local fw = band(mt, 8) ~= 0 + local bw = band(mt, 4) ~= 0 + dctType = 0 + if mpeg2 then + if mbIntra or not (fw or bw) then + motionType = 1 + if not fieldPic and not fpfd and (mbIntra or pattern) then + dctType = read(1) + end + else + if not fieldPic and fpfd then + motionType = 1 + else + local mtc = read(2) + if fieldPic then + motionType = if mtc == 1 then 1 elseif mtc == 2 then 3 else 4 + else + motionType = if mtc == 1 then 2 elseif mtc == 2 then 1 else 4 + end + if mtc == 0 then + err = true + return false + end + if not fieldPic and pattern then + dctType = read(1) + end + end + end + else + motionType = 1 + end + if band(mt, 0x10) ~= 0 then + local code = read(5) + if code == 0 then + err = true + return false + end + qscale = getQscale(code) + end + if mbIntra then + if concealMv then + -- concealment vectors: parsed, kept as predictors + if fieldPic then + pos += 1 + end + local x = decodeMotion(fc00, PMV[1]) + local y = decodeMotion(fc01, PMV[2]) + PMV[1], PMV[3] = x, x + PMV[2], PMV[4] = y, y + pos += 1 -- marker + else + resetPmv() + end + else + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw = fw + motBw = bw + if fw then + motionVectors(0) + elseif ptype == 2 then + -- P without motion: a zero vector (field pictures: from the same parity) + resetPmv() + motFw = true + motionType = 1 + MV[1], MV[2] = 0, 0 + FSEL[1] = parity + end + if bw then + motionVectors(1) + end + if err then + return false + end + predictMb() + end + local nb = if chroma == 2 then 8 else 6 + local cbp + if pattern then + cbp = vlc(CBP, CBP_BITS) + if nb == 8 then + cbp = cbp * 4 + read(2) + end + if err then + return false + end + else + cbp = if mbIntra then lshift(1, nb) - 1 else 0 + end + if cbp ~= 0 then + for b = 0, nb - 1 do + if band(cbp, lshift(1, nb - 1 - b)) ~= 0 then + if not decodeBlock(b) then + return false + end + end + end + end + return pos <= endBits + end + + local function decodeSlice(row: number, endByte: number) + if mpeg2 and lumaH > 2800 then + row += lshift(read(3), 7) + end + if row > mbRows then + return + end + mbAddr = (row - 1) * mbW - 1 + resetPmv() + dcY, dcCb, dcCr = lshift(128, dcPrec), lshift(128, dcPrec), lshift(128, dcPrec) + motFw, motBw = false, false + local code = read(5) + local endBits = endByte * 8 + while read(1) == 1 and pos < endBits do + pos += 8 + end + if code == 0 then + return + end + qscale = getQscale(code) + local first = true + while true do + if not decodeMacroblock(first, endBits) then + state.errors += 1 + buffer.fill(blk, 0, 0, 256) -- a block may have stopped half decoded + break + end + first = false + -- the slice ends at a start code (byte aligned) or at the end of the picture data + local i = rshift(pos + 7, 3) + if i >= endByte then + break + end + if readu8(data, i) == 0 and readu8(data, i + 1) == 0 and readu8(data, i + 2) == 1 then + break + end + end + -- the motion state a gap after this slice repeats (B pictures) + if mbIntra then + gapFw, gapBw = false, false + else + gapFw, gapBw, gapType = motFw, motBw, motionType + table.move(MV, 1, 16, 1, GAP) + end + end + + -- ------------------------------------------------------------------------------------------------ pictures + -- the frame a picture completes becomes the newest reference (I / P) + local function finishFrame(s: Store) + if s.ptype ~= 3 then + state.refOld = state.refNew + state.refNew = s + end + end + + -- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice + -- start code (-1: none) and the temporal reference, or nil when the picture is skipped + local function pictureHeader(p: number, stop: number): (number?, number) + pos = p * 8 + local tref = read(10) + ptype = read(3) + pos += 16 -- vbv_delay + if ptype < 1 or ptype > 3 then + state.skipped += 1 -- D pictures and invalid types + return nil, 0 + end + fullPelFw, fullPelBw = false, false + if ptype >= 2 then + fullPelFw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc00, fc01 = c, c + end + if ptype == 3 then + fullPelBw = read(1) == 1 + local c = read(3) + if c == 0 then + state.skipped += 1 + return nil, 0 + end + fc10, fc11 = c, c + end + -- MPEG-1 semantics unless a picture coding extension follows + dcPrec, picStruct, fpfd, concealMv, qScaleType, intraVlc, scan = 0, 3, true, false, 0, false, ZZ + tff, rff, progFrame = true, false, true + err = false + local at = findStart(rshift(pos + 7, 3), stop) + while at >= 0 do + local code = readu8(data, at + 3) + if code == 0xB5 then + extension(at + 4) + elseif code ~= 0xB2 then + break + end + at = findStart(at + 4, stop) + end + if mpeg2 then + fullPelFw, fullPelBw = false, false + end + if err then + state.errors += 1 + err = false + end + return at, tref + end + + -- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped + local function selectTarget(tref: number, tag: any): boolean + fieldPic = picStruct ~= 3 + parity = if picStruct == 2 then 1 else 0 + secondField = false + local target: Store + if fieldPic and pending and pendingStruct ~= picStruct then + secondField = true + target = pending :: Store + fwS, bwS = pendingFw, pendingBw + if ptype == 3 and (fwS == nil or bwS == nil) then + state.skipped += 1 + return false + end + else + if pending then + -- an unpaired field: its frame is done as it is + finishFrame(pending :: Store) + pending = nil + end + local refOld, refNew = state.refOld, state.refNew + if ptype == 1 then + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + elseif ptype == 2 then + if refNew == nil and not fieldPic then + state.skipped += 1 + return false + end + target = if stores[1] == refNew then stores[2] else stores[1] + fwS, bwS = refNew, nil + else + if refOld == nil or refNew == nil or bStore == nil then + state.skipped += 1 + return false + end + target = bStore :: Store + fwS, bwS = refOld, refNew + end + target.ptype = ptype + target.tref = tref + target.tag = tag + target.mpeg2 = mpeg2 + target.progressive = progFrame + target.fields = fieldPic + target.tff = if fieldPic then picStruct == 1 else tff + target.rff = rff + target.clamped = 0 + target.concealed = {} + end + cur = target + return true + end + + -- plane addressing of the current picture + local function setAddressing() + local target = cur :: Store + curY, curCb, curCr = target.y, target.cb, target.cr + if fieldPic then + mbRows = mbH // 2 + lstride, lbase = 2 * cw, parity * cw + cstride, cbase = 2 * chw, parity * chw + else + mbRows = mbH + lstride, lbase = cw, 0 + cstride, cbase = chw, 0 + end + mbSize = mbW * mbRows + covered = 0 + hasRef = fwS ~= nil + gapFw, gapBw = false, false + mbIntra = false + end + + -- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil + -- (skipped, or the first field of a frame). + local function decodePicture(p: number, stop: number, tag: any): Store? + local first, tref = pictureHeader(p, stop) + if first == nil or not selectTarget(tref, tag) then + return nil + end + setAddressing() + -- slices + local at = first :: number + while at >= 0 do + local code = readu8(data, at + 3) + if code >= 0x01 and code <= 0xAF then + pos = (at + 4) * 8 + err = false + decodeSlice(code, stop) + local nb = rshift(pos + 7, 3) + if nb >= stop then + break + end + at = findStart(nb, stop) + elseif code == 0xB2 or code == 0xB5 then + at = findStart(at + 4, stop) + else + break + end + end + conceal(covered, mbSize - 1) + state.pictures += 1 + local target = cur :: Store + if fieldPic and not secondField then + pending = target + pendingStruct = picStruct + pendingFw, pendingBw = fwS, bwS + return nil + end + pending = nil + finishFrame(target) + return target + end + + local core = {} :: Core + core.state = state + + function core.write(src: buffer, off: number, n: number) + if n <= 0 then + return + end + -- drop consumed bytes, keeping the scan state relative + if readByte > 0 then + local keep = dataLen - readByte + if keep > 0 then + buffer.copy(data, 0, data, readByte, keep) + end + scanPos = math.max(0, scanPos - readByte) + dataLen = keep + readByte = 0 + end + local need = dataLen + n + PAD + if need > buffer.len(data) then + local cap = buffer.len(data) + while cap < need do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, data, 0, dataLen) + data = nb + end + buffer.copy(data, dataLen, src, off, n) + dataLen += n + buffer.fill(data, dataLen, 0, PAD) + end + + -- the sequence header unit at byte at (up to stop): the header, then its extensions + local function sequenceUnit(at: number, stop: number) + local ok = sequenceHeader(at + 4) + local s = findStart(at + 4, stop) + while s >= 0 do + if readu8(data, s + 3) == 0xB5 then + extension(s + 4) + end + s = findStart(s + 4, stop) + end + if not ok or not applySequence() then + state.errors += 1 + end + end + + function core.nextPicture(atEnd: boolean, tag: any): (Store?, boolean) + while true do + local at = findStart(readByte, dataLen) + if at < 0 then + -- keep the last 3 bytes: a start code may straddle the next write + readByte = math.max(readByte, dataLen - 3) + if atEnd then + readByte = dataLen + end + return nil, true + end + local code = readu8(data, at + 3) + if code == 0xB3 or code == 0x00 then + -- a unit is complete when the next unit start (or the end of the data) follows it + local stop = dataLen + do + local s = findStart(math.max(at + 4, scanPos), dataLen) + while s >= 0 do + local c = readu8(data, s + 3) + if c == 0x00 or c == 0xB3 or c == 0xB7 or c == 0xB8 then + break + end + s = findStart(s + 4, dataLen) + end + if s < 0 then + if not atEnd then + scanPos = math.max(at + 4, dataLen - 3) + readByte = at + return nil, true + end + else + stop = s + end + end + scanPos = 0 + readByte = stop + if code == 0xB3 then + sequenceUnit(at, stop) + elseif hasSeq then + local s = decodePicture(at + 4, stop, tag) + if s then + return s, false + end + else + state.skipped += 1 + end + else + readByte = at + 4 -- GOP header, sequence end, user data, stray slices + end + end + end + + function core.toRgba(s: Store, out: buffer) + if s.chroma == 2 then + toRgba422(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + else + toRgba(s.y, s.cb, s.cr, s.cw, s.w, s.h, out) + end + end + + function core.reset() + dataLen = 0 + readByte = 0 + scanPos = 0 + state.refOld = nil + state.refNew = nil + pending = nil + end + + return core +end + +return D diff --git a/src/Formats/codecs/video/Mpeg1/Tables.luau b/src/Formats/codecs/video/Mpeg2/Tables.luau similarity index 73% rename from src/Formats/codecs/video/Mpeg1/Tables.luau rename to src/Formats/codecs/video/Mpeg2/Tables.luau index 1cad194..86960c9 100644 --- a/src/Formats/codecs/video/Mpeg1/Tables.luau +++ b/src/Formats/codecs/video/Mpeg2/Tables.luau @@ -1,7 +1,8 @@ --!strict --- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, +-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg, -- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from --- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays. +-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the +-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7. local T = {} T.PICTURE_RATE = { [0] = 0.0, 23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, @@ -74,16 +75,6 @@ T.MOTION = { [0] = 3, 0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0, 0, -15, 0, 0, -11, 0, 0, -13, } -T.DCT_DC_SIZE_LUMINANCE = { [0] = 6, - 3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36, - 33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0, - 0, 7, 0, 0, 8, -} -T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6, - 3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0, - 0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0, - 0, 7, 0, 0, 8, -} T.DCT_COEFF = { [0] = 3, 6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0, 0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81, @@ -114,4 +105,34 @@ T.DCT_COEFF = { [0] = 3, 0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0, 0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842, } +-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size +T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } } +T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } } +-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows) +T.DCT_COEFF_B15 = { + 2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8, + 124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16, + 30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24, + 22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32, + 23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40, + 2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264, + 30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272, + 17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769, + 38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282, + 18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050, + 120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074, + 36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098, + 31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145, + 28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937, +} +-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code +T.NON_LINEAR_QSCALE = { [0] = 0, + 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112, +} +-- the alternate scan (Figure 7-3): scan index -> natural position +T.ALTERNATE_SCAN = { [0] = 0, + 8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58, + 35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46, + 54, 62, 39, 47, 55, 63, +} return T diff --git a/src/Formats/codecs/video/Mpeg1/Vlc.luau b/src/Formats/codecs/video/Mpeg2/Vlc.luau similarity index 68% rename from src/Formats/codecs/video/Mpeg1/Vlc.luau rename to src/Formats/codecs/video/Mpeg2/Vlc.luau index b4799aa..7ab0504 100644 --- a/src/Formats/codecs/video/Mpeg1/Vlc.luau +++ b/src/Formats/codecs/video/Mpeg2/Vlc.luau @@ -1,14 +1,15 @@ --!strict --- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau). +-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). -- -- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds -- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level -- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF, -- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the -- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one --- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but --- for this header and the require. -local T = require("@formats/codecs/video/Mpeg1/Tables") +-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA / +-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees); +-- the MPEG-2 tables are built from code lists. +local T = require("@formats/codecs/video/Mpeg2/Tables") local V = {} @@ -32,8 +33,7 @@ local function leaves(tree: { [number]: number }): { Leaf } return out end -local function flat(tree: { [number]: number }): (buffer, number) - local ls = leaves(tree) +local function flatLeaves(ls: { Leaf }): (buffer, number) local k = 0 for _, l in ls do k = math.max(k, l.len) @@ -49,6 +49,19 @@ local function flat(tree: { [number]: number }): (buffer, number) return lut, k end +local function flat(tree: { [number]: number }): (buffer, number) + return flatLeaves(leaves(tree)) +end + +-- { { code, length } } indexed from 1 -> leaves with value = index - 1 +local function codeLeaves(codes: { { number } }): { Leaf } + local out: { Leaf } = {} + for i, c in codes do + table.insert(out, { code = c[1], len = c[2], value = i - 1 }) + end + return out +end + V.SUB = 0x1000000 V.ESC = 0xFFFF V.EOB = 0xFFFE @@ -93,10 +106,16 @@ V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA) V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE) V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B) -V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN) +do + -- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma + -- pattern bits) + local ls = leaves(T.CODE_BLOCK_PATTERN) + table.insert(ls, { code = 1, len = 9, value = 0 }) + V.CBP, V.CBP_BITS = flatLeaves(ls) +end V.MOTION, V.MOTION_BITS = flat(T.MOTION) -V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE) -V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE) +V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA)) +V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA)) do local ls = leaves(T.DCT_COEFF) @@ -113,4 +132,13 @@ do V.DCT_NEXT = twoLevel(nextLs) end +do + local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } } + local b = T.DCT_COEFF_B15 + for i = 1, #b, 3 do + table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] }) + end + V.DCT_B15 = twoLevel(ls) +end + return V diff --git a/src/Formats/codecs/video/Mpeg2/init.luau b/src/Formats/codecs/video/Mpeg2/init.luau new file mode 100644 index 0000000..846cbf7 --- /dev/null +++ b/src/Formats/codecs/video/Mpeg2/init.luau @@ -0,0 +1,364 @@ +--!strict +-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). +-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I / +-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes +-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from +-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder +-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this +-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines); +-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded. +-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped). +-- +-- local dec = Mpeg2.new({ reorder = true, rgba = false }) +-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts +-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true)) +-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces +-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek +-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... } +-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2) +-- +-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local D = require("@formats/codecs/video/Mpeg2/Decoder") + +local Mpeg2 = {} + +Mpeg2.PICTURE_I = 1 +Mpeg2.PICTURE_P = 2 +Mpeg2.PICTURE_B = 3 + +export type Frame = { + width: number, + height: number, + pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false } + pictureType: number, -- 1 I, 2 P, 3 B + temporalReference: number, -- the picture's 10-bit display index within its GOP + index: number, -- frames returned so far (1-based) + tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) + -- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride + -- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2) + y: buffer, + cb: buffer, + cr: buffer, + codedWidth: number, + chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 + mpeg2: boolean, + progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) + fields: boolean, -- coded as two field pictures + topFieldFirst: boolean, + repeatFirstField: boolean, + clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) + concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) +} + +export type Options = { + reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the + -- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is + -- display order for streams without B-frames. + rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr) + maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304) +} + +local Decoder = {} +Decoder.__index = Decoder + +export type Decoder = typeof(setmetatable( + {} :: { + _core: D.Core, + _reorder: boolean, + _rgba: boolean, + _held: D.Store?, + _pixels: buffer?, + _count: number, + width: number, + height: number, + frameRate: number, + bitRate: number, + stats: { pictures: number, errors: number, skipped: number }, + }, + Decoder +)) + +function Mpeg2.new(opts: Options?): Decoder + local o: Options = if type(opts) == "table" then opts else {} + local core = D.new(o.maxPixels) + return setmetatable({ + _core = core, + _reorder = o.reorder == true, + _rgba = o.rgba ~= false, + _held = nil, + _pixels = nil, + _count = 0, + width = 0, + height = 0, + frameRate = 0, + bitRate = 0, + stats = { pictures = 0, errors = 0, skipped = 0 }, + }, Decoder) +end + +local function emit(self: Decoder, s: D.Store): Frame + local core = self._core + local pixels: buffer? = nil + if self._rgba then + local need = s.w * s.h * 4 + local px = self._pixels + if px == nil or buffer.len(px) ~= need then + px = buffer.create(need) + self._pixels = px + end + core.toRgba(s, px :: buffer) + pixels = px + end + self._count += 1 + return { + width = s.w, + height = s.h, + pixels = pixels, + pictureType = s.ptype, + temporalReference = s.tref, + index = self._count, + tag = s.tag, + y = s.y, + cb = s.cb, + cr = s.cr, + codedWidth = s.cw, + chroma = s.chroma, + mpeg2 = s.mpeg2, + progressive = s.progressive, + fields = s.fields, + topFieldFirst = s.tff, + repeatFirstField = s.rff, + clamped = s.clamped, + concealed = s.concealed, + } +end + +local function sync(self: Decoder) + local st = self._core.state + self.width = st.width + self.height = st.height + self.frameRate = st.frameRate + self.bitRate = st.bitRate + self.stats.pictures = st.pictures + self.stats.errors = st.errors + self.stats.skipped = st.skipped +end + +-- a decoded picture -> the frame to return now (nil while reordering holds it) +local function handle(self: Decoder, s: D.Store): Frame? + if not self._reorder or s.ptype == D.PICTURE_B then + return emit(self, s) + end + local prev = self._held + self._held = s + if prev then + return emit(self, prev) + end + return nil +end + +local function run(self: Decoder, atEnd: boolean, tag: any): Frame? + local core = self._core + while true do + local s, needData = core.nextPicture(atEnd, tag) + sync(self) + if s then + local f = handle(self, s) + if f then + return f + end + elseif needData then + return nil + end + end +end + +local function append(self: Decoder, data: any, offset: number?, len: number?): boolean + local src: buffer + if type(data) == "string" then + src = buffer.fromstring(data) + elseif type(data) == "buffer" then + src = data + else + return false + end + local total = buffer.len(src) + local off = math.floor(tonumber(offset) or 0) + if off < 0 or off > total then + return false + end + local n = math.floor(tonumber(len) or (total - off)) + if n < 0 or off + n > total then + return false + end + self._core.write(src, off, n) + return true +end + +-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument. +function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean + return append(self, data, offset, len) +end + +-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is +-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one). +function Decoder.decodeFrame(self: Decoder): Frame? + return run(self, false, nil) +end + +-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data). +-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag. +function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame? + if not append(self, data, offset, len) then + return nil + end + return run(self, true, tag) +end + +-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held +-- for reordering. Call until it returns nil. +function Decoder.flush(self: Decoder): Frame? + local f = run(self, true, nil) + if f then + return f + end + local held = self._held + if held then + self._held = nil + return emit(self, held) + end + return nil +end + +-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture). +function Decoder.reset(self: Decoder) + self._core.reset() + self._held = nil +end + +-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to +-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma +-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for +-- a value that is not a Frame. +function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image? + if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then + return nil + end + local w, h, cw = frame.width, frame.height, frame.codedWidth + if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then + return nil + end + local c422 = frame.chroma == 2 + local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 + local crows = if c422 then h else oh + if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then + return nil + end + local img + if rgba then + img = Types.Image.new(w, h) + if c422 then + D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + else + D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) + end + else + img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + for y = 0, h - 1 do + buffer.copy(px, y * w, frame.y, y * cw, w) + end + local o = w * h + if not c422 then + for y = 0, oh - 1 do + buffer.copy(px, o + y * ow, frame.cb, y * chw, ow) + buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow) + end + else + -- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field + -- (4k + j and 4k + j + 2), so the fields do not mix + local inter = not frame.progressive + for y = 0, oh - 1 do + local a, b + if inter then + local base = (y // 2) * 4 + y % 2 + a, b = base, base + 2 + else + a, b = 2 * y, 2 * y + 1 + end + if b >= h then + b = a + end + for x = 0, ow - 1 do + buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2) + buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2) + end + end + end + end + img.meta.source = { + format = if frame.mpeg2 then "mpeg2" else "mpeg1", + pictureType = frame.pictureType, + temporalReference = frame.temporalReference, + chroma = if c422 then "422" else "420", + interlaced = not frame.progressive, + topFieldFirst = frame.topFieldFirst, + range = if rgba then nil else "limited", + } + return img +end + +-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder +-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in +-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of +-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream). +function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) + local queue: { any } = {} + local function push(f: Frame) + local img = Mpeg2.frameImage(f) + if img then + img.meta.yuv = { range = "limited", matrix = "bt601" } + local tag = f.tag + table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) + end + end + local self = {} + function self.decode(_: any, packet: Types.Packet): Err.Err? + local tag = { packet.pts } + local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag) + if not ok then + return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) + end + while f do -- more pictures in the packet + push(f) + f = dec:decode(packet.data, 0, 0, tag) + end + return nil + end + function self.receive(_: any): (Types.Image?, number?, boolean?) + local q = table.remove(queue, 1) + if q then + return q[1], q[2], q[3] + end + return nil, nil, nil + end + function self.flush(_: any) + for _ = 1, 8 do + local f = dec:flush() + if not f then + break + end + push(f) + end + end + function self.reset(_: any) + dec:reset() + table.clear(queue) + end + return self :: any, nil +end + +return Mpeg2 diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 0960b9b..01f8218 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -240,51 +240,10 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end --- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) -local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) - local Mpeg1 = require("@formats/codecs/video/Mpeg1") - local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) - local queue: { any } = {} - local function push(f: any) - local img = Mpeg1.frameImage(f) - if img then - img.meta.yuv = { range = "limited", matrix = "bt601" } - local tag = f.tag - table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) - end - end - local self = {} - function self.decode(_: any, packet: Types.Packet): Err.Err? - local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts }) - if not ok then - return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) - end - if f then - push(f) - end - return nil - end - function self.receive(_: any): (Types.Image?, number?, boolean?) - local q = table.remove(queue, 1) - if q then - return q[1], q[2], q[3] - end - return nil, nil, nil - end - function self.flush(_: any) - for _ = 1, 4 do - local f = dec:flush() - if not f then - break - end - push(f) - end - end - function self.reset(_: any) - dec:reset() - table.clear(queue) - end - return self :: any, nil +-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display +local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) + local Mpeg2 = require("@formats/codecs/video/Mpeg2") + return Mpeg2.newVideoDecoder(track, opts) end -- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); @@ -299,9 +258,9 @@ end local BUILTIN: { Entry } = { { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, - { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder }, + { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg2Decoder }, { id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder }, - { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } }, + { id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder }, { id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } }, { id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, { id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } }, diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau index f84a0bf..704db06 100644 --- a/src/Formats/containers/MpegEs.luau +++ b/src/Formats/containers/MpegEs.luau @@ -35,6 +35,8 @@ export type Picture = { temporal: number, -- temporal_reference gop: boolean, -- a GOP header precedes the picture sequence: boolean, -- a sequence header precedes the picture + structure: number, -- MPEG-2 picture_structure: 1 top field, 2 bottom field, 3 frame (MPEG-1: 3) + fields: number?, -- 2: a frame coded as two field pictures (both in this unit) } export type Info = { width: number, height: number, frameRate: number, mpeg2: boolean } @@ -77,8 +79,30 @@ function MpegEs.pictureType(b: buffer, off: number, limit: number): (number, num return 0, 0 end +-- pictureStructure(b, p, limit) -> the picture_structure of the picture whose start code is at p, from its picture +-- coding extension (3 = frame when there is none: MPEG-1) +function MpegEs.pictureStructure(b: buffer, p: number, limit: number): number + local q = MpegEs.findStart(b, p + 4, limit) + local count = 0 + while q and count < 8 do + count += 1 + local code = if q + 6 < limit then readu8(b, q + 3) else -1 + if code == 0xB5 then + if readu8(b, q + 4) // 16 == 8 then + local st = readu8(b, q + 6) % 4 + return if st == 0 then 3 else st + end + elseif code ~= 0xB2 then + break + end + q = MpegEs.findStart(b, q + 4, limit) + end + return 3 +end + -- pictures(b, off, limit) -> access units of an MPEG-1 / 2 video elementary stream: each picture starts at its --- sequence / GOP header when one precedes it and runs to the next unit's start +-- sequence / GOP header when one precedes it and runs to the next unit's start; a frame coded as two field pictures +-- is one unit (fields = 2) function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local out: { Picture } = {} local unitStart: number? = nil @@ -87,7 +111,11 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local p = MpegEs.findStart(b, off, limit) while p do local code = if p + 3 < limit then readu8(b, p + 3) else -1 - if code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then + local st = if code == 0x00 then MpegEs.pictureStructure(b, p, limit) else 3 + if code == 0x00 and cur and cur.structure ~= 3 and cur.fields == nil and st ~= 3 and st ~= cur.structure then + -- the second field of the current frame: same unit + cur.fields = 2 + elseif code == 0xB3 or code == 0xB8 or code == 0x00 or code == 0xB7 then -- a sequence / GOP header or a picture after a picture closes it if cur and (code ~= 0xB7) then cur.size = p - cur.offset @@ -106,7 +134,7 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) t, tr = (x // 8) % 8, x // 64 end - cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq } + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } unitStart, seq, gop = nil, false, false elseif code == 0xB7 and cur then cur.size = p + 4 - cur.offset diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau new file mode 100644 index 0000000..fb3da3f --- /dev/null +++ b/tests/codecs/mpeg2.luau @@ -0,0 +1,302 @@ +-- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and +-- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan, +-- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd +-- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display +-- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive, +-- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted +-- streams never throw; the fuzz no-throw pass. +local T = require("@tests/T") +local Mpeg2 = require("@formats/codecs/video/Mpeg2") +local Video = require("@formats/codecs/video/Video") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Deflate = require("@formats/codecs/compress/Deflate") + +local STREAMS = { + require("@tests/gen/mpeg2_prog"), + require("@tests/gen/mpeg2_tff"), + require("@tests/gen/mpeg2_bff_alt"), + require("@tests/gen/mpeg2_tools"), + require("@tests/gen/mpeg2_dc9_matrix"), + require("@tests/gen/mpeg2_dc11_q1"), + require("@tests/gen/mpeg2_motion"), + require("@tests/gen/mpeg2_odd_ilace"), + require("@tests/gen/mpeg2_c422"), + require("@tests/gen/mpeg2_c422_ilace"), + require("@tests/gen/mpeg2_dualprime"), +} + +local t = T.suite("codecs/mpeg2") +local rand = T.rng(11) + +local function b64(s: string): buffer + return Base64.decode(s) :: buffer +end + +-- CRC-32 of a plane cropped to w x h from a buffer with stride +local function planeCrc(b: buffer, stride: number, w: number, h: number): number + local row = buffer.create(w * h) + for y = 0, h - 1 do + buffer.copy(row, y * w, b, y * stride, w) + end + return Crc32.of(row) +end + +-- the cropped planes of a frame, as ffmpeg writes them (w x h luma, ceil(w / 2) x (h or ceil(h / 2)) chroma) +local function crcs(f: any): (number, number, number) + local w, h = f.width, f.height + local cw = (w + 1) // 2 + local ch = if f.chroma == 2 then h else (h + 1) // 2 + local chw = f.codedWidth // 2 + return planeCrc(f.y, f.codedWidth, w, h), planeCrc(f.cb, chw, cw, ch), planeCrc(f.cr, chw, cw, ch) +end + +-- differing samples between a frame's luma and a reference yuv frame (debug detail on a mismatch) +local function lumaDiff(f: any, ref: buffer): (number, number) + local n, first = 0, -1 + for y = 0, f.height - 1 do + for x = 0, f.width - 1 do + if buffer.readu8(f.y, y * f.codedWidth + x) ~= buffer.readu8(ref, y * f.width + x) then + n += 1 + if first < 0 then + first = y * 65536 + x + end + end + end + end + return n, first +end + +local function decodeUnits(fx: any, file: buffer): { any } + local dec = Mpeg2.new({ reorder = true, rgba = false }) + local out = {} + local function take(f: any) + local y, u, v = crcs(f) + -- the 16-line luma bands now: the planes belong to the decoder + local bands = {} + for b = 0, (f.height + 15) // 16 - 1 do + local rows = math.min(16, f.height - b * 16) + local buf = buffer.create(f.width * rows) + for r = 0, rows - 1 do + buffer.copy(buf, r * f.width, f.y, (b * 16 + r) * f.codedWidth, f.width) + end + bands[b] = Crc32.of(buf) + end + table.insert(out, { y, u, v, f, bands }) + end + for i, u in fx.units do + local f = dec:decode(file, u[1], u[2], i) + while f do + take(f) + f = dec:decode(file, 0, 0, i) + end + end + while true do + local f = dec:flush() + if not f then + break + end + take(f) + end + return out +end + +-- 1. every stream against ffmpeg, bit-exact. ffmpeg's encoder sometimes ends a B-picture slice before the row's last +-- macroblock (invalid MPEG-2); both decoders conceal the gap, ffmpeg with its error-resilience guesses and deblocking. +-- Frames with concealed macroblocks compare every 16-line luma band but those and their neighbours. +local total, concealedFrames = 0, 0 +for _, fx in STREAMS do + local name = fx.name + local file = b64(fx.file) + local t0 = os.clock() + local got = decodeUnits(fx, file) + local dt = os.clock() - t0 + t:eq(#got, fx.frames, name .. ": frame count") + local bad, msg = 0, "" + for k, ref in fx.crcs do + local g = got[k] + if g and (g[1] ~= ref[1] or g[2] ~= ref[2] or g[3] ~= ref[3]) then + local f = g[4] + local ok = next(f.concealed) ~= nil + if ok then + concealedFrames += 1 + for band, crc in fx.bands[k] do + local b = band - 1 + if not (f.concealed[b] or f.concealed[b - 1] or f.concealed[b + 1]) then + ok = ok and g[5][b] == crc + end + end + end + if not ok then + bad += 1 + if bad == 1 then + local detail = "" + if k == 1 and #got == 1 then + local n, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer) + detail = string.format(" (%d luma samples differ, first at %d,%d)", n, first % 65536, first // 65536) + end + msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType, + tostring(g[1] == ref[1]), tostring(g[2] == ref[2]), tostring(g[3] == ref[3]), detail) + end + end + end + end + t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg) + local f1 = got[1] and got[1][4] + if f1 then + t:check(f1.mpeg2 == true, name .. ": mpeg2 flag") + t:eq(f1.chroma, fx.chroma, name .. ": chroma format") + end + total += #got + t:note(" %-12s %4dx%-4d %s %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height, + if fx.chroma == 2 then "4:2:2" else "4:2:0", #got, #got / dt) +end + +-- 2. interlace flags +do + local got = decodeUnits(STREAMS[2], b64(STREAMS[2].file)) + t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == true, "tff: interlaced, top field first") + got = decodeUnits(STREAMS[3], b64(STREAMS[3].file)) + t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == false, "bff_alt: bottom field first") + got = decodeUnits(STREAMS[1], b64(STREAMS[1].file)) + t:check(got[1][4].progressive == true, "prog: progressive") +end + +-- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit +for _, idx in { 2, 9 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local want = decodeUnits(fx, file) + local dec = Mpeg2.new({ reorder = true, rgba = false }) + local p, k, ok = 0, 0, true + local n = buffer.len(file) + local function check(f: any) + k += 1 + local y, u, v = crcs(f) + local ref = want[k] + ok = ok and ref ~= nil and y == ref[1] and u == ref[2] and v == ref[3] + end + while p < n do + local len = math.min(n - p, 1 + rand(5000)) + dec:write(file, p, len) + p += len + while true do + local f = dec:decodeFrame() + if not f then + break + end + check(f) + end + end + while true do + local f = dec:flush() + if not f then + break + end + check(f) + end + t:check(ok and k == fx.frames, string.format("%s: random pieces give the same %d frames (%d)", fx.name, fx.frames, k)) +end + +-- 4. frameImage: yuv420p (4:2:2 converted), rgba8 +do + local fx = STREAMS[9] + local dec = Mpeg2.new({ reorder = false, rgba = true }) + local file = b64(fx.file) + local f = dec:decode(file, fx.units[1][1], fx.units[1][2]) + t:check(f ~= nil and f.pixels ~= nil, "c422: rgba frame") + if f then + local img = Mpeg2.frameImage(f) + t:check(img ~= nil and img.format == "yuv420p" and img.width == fx.width, "c422: frameImage yuv420p") + if img then + local cw, ch = (fx.width + 1) // 2, (fx.height + 1) // 2 + t:eq(buffer.len(img.pixels), fx.width * fx.height + 2 * cw * ch, "c422: yuv420p size") + t:eq(img.meta.source.format, "mpeg2", "c422: meta.source.format") + t:eq(img.meta.source.chroma, "422", "c422: meta.source.chroma") + end + local rgba = Mpeg2.frameImage(f, true) + t:check(rgba ~= nil and rgba.format == "rgba8", "c422: frameImage rgba8") + end + t:check(Mpeg2.frameImage({} :: any) == nil, "frameImage of a non-frame is nil") +end + +-- 5. the registry's decoder (packets = access units), display order with pts +do + t:check(Video.fromFourcc("mpg2") == "mpeg2" and Video.fromMatroska("V_MPEG2") == "mpeg2", "registry names") + t:check(Video.canDecode("mpeg2") and Video.canDecode("mpeg1"), "registry decoders") + local fx = STREAMS[1] + local file = b64(fx.file) + local want = decodeUnits(fx, file) + local dec = assert(Video.decoder({ id = 1, kind = "video", codec = "mpeg2", timescale = 25 } :: any)) + local frames, order = 0, true + local last = -1 + for i, u in fx.units do + local d = buffer.create(u[2]) + buffer.copy(d, 0, file, u[1], u[2]) + dec:decode({ track = 1, pts = i, keyframe = false, data = d } :: any) + while true do + local img, pts = dec:receive() + if not img then + break + end + frames += 1 + local ref = want[frames] + local w, h = fx.width, fx.height + order = order and ref ~= nil and Crc32.of(img.pixels, 0, w * h) == ref[1] and img.meta.yuv ~= nil + last = pts or last + end + end + dec:flush() + while dec:receive() do + frames += 1 + end + t:eq(frames, fx.frames, "registry decoder: frame count") + t:check(order, "registry decoder: frames in display order, equal to the codec's") +end + +-- 6. robustness: truncated units, bit flips, garbage (never throws), and the fuzz pass +do + local samples = {} + for _, idx in { 1, 2, 9, 11 } do + local fx = STREAMS[idx] + local file = b64(fx.file) + local n = math.min(buffer.len(file), 60000) + local b = buffer.create(n) + buffer.copy(b, 0, file, 0, n) + table.insert(samples, b) + end + local threw = 0 + for round = 1, 12 do + local src = samples[1 + round % #samples] + local b = buffer.create(buffer.len(src)) + buffer.copy(b, 0, src) + for _ = 1, 20 do + local i = rand(buffer.len(b)) + buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8)))) + end + local ok = pcall(function() + local dec = Mpeg2.new({ reorder = true }) + dec:write(b) + while dec:decodeFrame() do + end + while dec:flush() do + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "corrupted streams never throw") + t:fuzz("decode", function(b: buffer) + local dec = Mpeg2.new({ reorder = true }) + dec:write(b) + local f = dec:decodeFrame() + while f do + f = dec:decodeFrame() + end + return dec:flush() + end, samples, { mutations = 60, garbage = 10 }) +end + +t:note(" %d frames bit-exact with ffmpeg -idct int (%d with concealed macroblocks: compared outside them)", total, concealedFrames) +t:done() diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py new file mode 100644 index 0000000..b9e1f00 --- /dev/null +++ b/tools/fixtures/mpeg2.py @@ -0,0 +1,178 @@ +# MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder +# (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the +# alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and +# chroma matrices, large motion (f_code > 1), odd sizes, B-frames) and from mjpegtools' mpeg2enc (dual-prime +# prediction in interlaced frame pictures), each with `ffmpeg -idct int` decoding as the reference: the IJG integer +# IDCT that codecs/video/Dsp reproduces, so the planes must match exactly. +# tests/gen/mpeg2_.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64), +# units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of +# every frame's cropped planes, display order), bands = { { crc } } (per frame, of +# each 16-line luma band), first / last = the yuv frame (base64 zlib) } +# tests/gen/mpeg2_containers.luau the prog stream in MPEG-TS (stream type 0x02, and patched to 0x80), MPEG-PS, +# Matroska and AVI, base64, with the stream's crcs +# tests/gen/mpeg2_bench.luau { { width, height, file, units } }: 720x576 interlaced (DVD-like) for tools/bench.luau +import base64, os, shutil, subprocess, tempfile, zlib + + +def b64(b): + return base64.b64encode(b).decode() + + +def z64(b): + return base64.b64encode(zlib.compress(b, 9)).decode() + + +FF = ["-hide_banner", "-loglevel", "error", "-y"] +ENC = ["-c:v", "mpeg2video", "-f", "mpeg2video"] +ILACE = ["-flags", "+ilme+ildct"] +CHROMA_INTRA = ",".join(str(8 + (i // 8) * 2 + (i % 8)) for i in range(64)) +INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64)) +INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64)) + + +def src(kind, w, h, t, rate=25, vf=None): + s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate) + if vf: + s += "," + vf + return ["-f", "lavfi", "-i", s, "-t", str(t)] + + +# name: (ffmpeg input + encoder args, chroma) +CASES = { + "prog": (src("testsrc2", 352, 288, 0.8) + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1), + "tff": (src("mandelbrot", 352, 288, 0.8, vf="setfield=tff") + ILACE + ["-b:v", "2M", "-bf", "2", "-g", "12"], 1), + "bff_alt": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.01:v=0.02,setfield=bff") + ILACE + ["-alternate_scan", "1", + "-b:v", "1500k", "-bf", "1", "-g", "9"], 1), + "tools": (src("mandelbrot", 320, 240, 0.6) + ["-intra_vlc", "1", "-non_linear_quant", "1", "-qmax", "28", "-dc", "10", "-b:v", "1500k", + "-bf", "2", "-g", "8"], 1), + "dc9_matrix": (src("testsrc2", 176, 144, 0.6) + ["-dc", "9", "-intra_matrix", INTRA, "-inter_matrix", INTER, + "-b:v", "800k", "-bf", "1", "-g", "6"], 1), + "dc11_q1": (src("mandelbrot", 176, 144, 0.32) + ["-dc", "11", "-q:v", "1", "-qmin", "1", "-bf", "0", "-g", "4"], 1), + "motion": (src("testsrc2", 352, 288, 0.6, vf="scroll=h=0.04:v=0.03") + ["-b:v", "3M", "-bf", "3", "-g", "15"], 1), + "odd_ilace": (src("testsrc2", 346, 258, 0.48) + ILACE + ["-b:v", "1500k", "-bf", "2", "-g", "6"], 1), + "c422": (src("mandelbrot", 352, 288, 0.48) + ["-pix_fmt", "yuv422p", "-b:v", "3M", "-bf", "2", "-g", "6", + "-chroma_intra_matrix", CHROMA_INTRA], 2), + "c422_ilace": (src("testsrc2", 320, 240, 0.48, vf="scroll=h=0.02,setfield=tff") + ["-pix_fmt", "yuv422p"] + ILACE + + ["-alternate_scan", "1", "-b:v", "3M", "-bf", "1", "-g", "6"], 2), +} + + +def access_units(es): + # one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start + starts = [] + i = 0 + pending = None + while True: + i = es.find(b"\x00\x00\x01", i) + if i < 0 or i + 3 >= len(es): + break + code = es[i + 3] + if code in (0xB3, 0xB8) and pending is None: + pending = i + elif code == 0x00: + starts.append(pending if pending is not None else i) + pending = None + i += 3 + return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)] + + +def generate(ctx): + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe") + + def ff(args): + subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True) + + def size(path): + r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", + "-of", "csv=p=0", path], check=True, capture_output=True) + return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2]) + + def reference(path, chroma): + out = path + ".yuv" + ff(["-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", + "-pix_fmt", "yuv422p" if chroma == 2 else "yuv420p", out]) + return open(out, "rb").read() + + def emit(name, es, path, chroma): + w, h = size(path) + yuv = reference(path, chroma) + cw, ch = (w + 1) // 2, (h if chroma == 2 else (h + 1) // 2) + fs = w * h + 2 * cw * ch + n = len(yuv) // fs + crcs, bands = [], [] + for k in range(n): + f = yuv[k * fs:(k + 1) * fs] + crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])]) + bands.append([zlib.crc32(f[y * w:min(h, y + 16) * w]) for y in range(0, h, 16)]) + ctx.emit("mpeg2_" + name, { + "name": name, "width": w, "height": h, "chroma": chroma, "frames": n, "file": b64(es), + "units": access_units(es), "crcs": crcs, "bands": bands, "first": z64(yuv[:fs]), "last": z64(yuv[(n - 1) * fs:n * fs]), + }) + return crcs + + with tempfile.TemporaryDirectory(prefix="formats-mpeg2-") as tmp: + crcs = {} + for name, (args, chroma) in CASES.items(): + path = os.path.join(tmp, name + ".m2v") + ff(args + ENC + [path]) + crcs[name] = emit(name, open(path, "rb").read(), path, chroma) + + # mjpegtools' mpeg2enc: interlaced frame pictures with dual-prime prediction (P only, as dual prime requires) + y4m = os.path.join(tmp, "src.y4m") + ff(src("mandelbrot", 352, 288, 0.6) + ["-vf", "setfield=tff", "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", y4m]) + dp = os.path.join(tmp, "dualprime.m2v") + ctx.nix("mjpegtools", ["sh", "-c", "mpeg2enc -v 0 -f 3 -I 1 --dualprime-mpeg2 -R 0 -b 2500 -g 9 -G 9 -o '%s' < '%s'" + % (dp, y4m)]) + emit("dualprime", open(dp, "rb").read(), dp, 1) + + # the prog stream in the containers (stream copy) + prog = os.path.join(tmp, "prog.m2v") + cont = {"crcs": crcs["prog"]} + for fmt, ext in (("mpegts", "ts"), ("vob", "mpg"), ("matroska", "mkv"), ("avi", "avi")): + out = os.path.join(tmp, "prog." + ext) + ff(["-fflags", "+genpts", "-r", "25", "-i", prog, "-c", "copy", "-f", fmt, out]) + cont[ext] = b64(open(out, "rb").read()) + # stream type 0x80 (private / DigiCipher II video): the PMT's 0x02 entry patched, its CRC redone + ts = bytearray(base64.b64decode(cont["ts"])) + patched = False + for p in range(0, len(ts), 188): + pkt = ts[p:p + 188] + if pkt[0] != 0x47 or not (pkt[1] & 0x40): + continue + pid = ((pkt[1] & 0x1F) << 8) | pkt[2] + if pid == 0 or pid == 0x11 or pkt[3] & 0x20: + continue + o = p + 5 + pkt[4] + if ts[o] != 0x02: # table_id of a PMT + continue + slen = ((ts[o + 1] & 0x0F) << 8) | ts[o + 2] + pinfo = ((ts[o + 10] & 0x0F) << 8) | ts[o + 11] + e = o + 12 + pinfo + while e < o + 3 + slen - 4: + if ts[e] == 0x02: + ts[e] = 0x80 + patched = True + e += 5 + (((ts[e + 3] & 0x0F) << 8) | ts[e + 4]) + crc = zlib_crc32_mpeg(bytes(ts[o:o + 3 + slen - 4])) + ts[o + 3 + slen - 4:o + 3 + slen] = crc.to_bytes(4, "big") + assert patched, "mpeg2: no PMT entry patched" + cont["ts80"] = b64(bytes(ts)) + ctx.emit("mpeg2_containers", cont) + + bench = [] + path = os.path.join(tmp, "bench.m2v") + ff(src("mandelbrot", 720, 576, 1.0) + ILACE + ["-b:v", "6M", "-bf", "2", "-g", "12"] + ENC + [path]) + es = open(path, "rb").read() + bench.append({"width": 720, "height": 576, "file": b64(es), "units": access_units(es)}) + ctx.emit("mpeg2_bench", bench) + + +def zlib_crc32_mpeg(data): + # CRC-32/MPEG-2: poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor + crc = 0xFFFFFFFF + for b in data: + crc ^= b << 24 + for _ in range(8): + crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF + return crc From 22db57f3489aa979f5419decff55ed24c5858c07 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:11 -0500 Subject: [PATCH 21/54] ws-video2: MPEG-2 in MPEG-TS (0x02 / private 0x80), MPEG-PS, MKV, AVI, MP4 caps; tests/video/mpeg2.luau --- docs/FORMATS.md | 10 ++-- src/Formats/Registry.luau | 10 ++-- src/Formats/video/avi/init.luau | 2 +- src/Formats/video/mkv/init.luau | 2 +- src/Formats/video/mp4/init.luau | 2 +- src/Formats/video/mpegps/init.luau | 11 ++-- src/Formats/video/mpegts/init.luau | 7 +-- tests/video/mpeg2.luau | 80 ++++++++++++++++++++++++++++++ 8 files changed, 103 insertions(+), 21 deletions(-) create mode 100644 tests/video/mpeg2.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d612dc3..c98a249 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -27,12 +27,12 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | voc | .voc | yes | yes | streaming: true, depths: 8, 16, lossy: false | `tests/audio/voc.luau` | | audio | vorbis | .ogg .oga | yes | yes | streaming: true, seek: true, lossy: true, channels: 255 | `tests/audio/vorbis.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | -| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | +| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, odml: true | `tests/video/avi.luau` | | video | h264 | .h264 .264 .avc .jsv .26l .jvt | yes | yes | streaming: true, video: "h264", depths: 8 | `tests/video/h264.luau` | -| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | -| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | -| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | -| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | +| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` | +| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "h264", audio: true | `tests/video/mpegts.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 429bc2a..7dfc437 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -285,7 +285,7 @@ local list: { Entry } = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, load = function() return require("@formats/video/avi") end, @@ -309,7 +309,7 @@ local list: { Entry } = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") end, @@ -321,7 +321,7 @@ local list: { Entry } = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, load = function() return require("@formats/video/mp4") end, @@ -333,7 +333,7 @@ local list: { Entry } = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, load = function() return require("@formats/video/mpegps") end, @@ -345,7 +345,7 @@ local list: { Entry } = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, load = function() return require("@formats/video/mpegts") end, diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index fc46a32..1f0fdf0 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -25,7 +25,7 @@ local AviFormat = { extensions = { "avi" }, mime = { "video/x-msvideo", "video/avi" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, odml = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 8e009e9..9e068c7 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -28,7 +28,7 @@ local Mkv = { extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/compress/Deflate", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "mpeg2", "rawvideo" }, audio = true, subtitles = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mp4/init.luau b/src/Formats/video/mp4/init.luau index 48b57c7..eb643df 100644 --- a/src/Formats/video/mp4/init.luau +++ b/src/Formats/video/mp4/init.luau @@ -30,7 +30,7 @@ local Mp4 = { extensions = { "mp4", "m4v", "mov", "qt", "3gp", "3g2", "mj2" }, mime = { "video/mp4", "video/quicktime", "video/3gpp" }, deps = { "core/Err", "core/Bytes", "Types", "containers/IsoBmff", "containers/Demux", "codecs/video/Video", "codecs/video/Video/Source" }, - caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "h264" }, audio = true, fragments = true }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "mjpeg", "mpeg1", "mpeg2", "h264" }, audio = true, fragments = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegps/init.luau b/src/Formats/video/mpegps/init.luau index 8708894..91ef418 100644 --- a/src/Formats/video/mpegps/init.luau +++ b/src/Formats/video/mpegps/init.luau @@ -1,10 +1,11 @@ --!strict -- video/mpegps: MPEG program streams (ISO/IEC 11172-1 system streams and 13818-1 program streams: .mpg / .mpeg / -- .vob / VCD .dat). New in formats-luau, on containers/MpegPs. Video PES payloads are joined into the elementary --- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers); a --- picture takes the PTS of the PES it starts in, pictures without one get theirs from the GOP's temporal references. --- Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). open() returns a VideoDecoder: MPEG-1 --- video through the codecs/video/Video registry (MPEG-2 detected and reported), audio through the api's opts.openAudio hook. +-- stream and cut into pictures (containers/MpegEs: one packet per picture with its sequence / GOP headers, both +-- fields of a field-coded frame in one); a picture takes the PTS of the PES it starts in, pictures without one get +-- theirs from the GOP's temporal references. Audio packets are the PES payloads (MP1 / MP2 / MP3 frames, AC-3, LPCM). +-- open() returns a VideoDecoder: MPEG-1 / MPEG-2 video through the codecs/video/Video registry (MPEG-2 told by its +-- sequence extension), audio through the api's opts.openAudio hook. -- Timescale 90 kHz. Not supported: writing, H.264 in PS (packets are whole PES payloads), DVD navigation packets. -- ------------------------------------------------------------------------------------------------ requires @@ -23,7 +24,7 @@ local Ps = { extensions = { "mpg", "mpeg", "vob", "m1v", "mpv", "dat" }, mime = { "video/mpeg" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegPs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/src/Formats/video/mpegts/init.luau b/src/Formats/video/mpegts/init.luau index 1cac2a4..4213838 100644 --- a/src/Formats/video/mpegts/init.luau +++ b/src/Formats/video/mpegts/init.luau @@ -2,8 +2,9 @@ -- video/mpegts: MPEG transport streams (ISO/IEC 13818-1: .ts / .m2ts segments, HLS). The demuxer is containers/MpegTs, -- absorbed from mpegts-luau (resync, PAT / PMT with CRC, continuity checks, PES reassembly, 33-bit PTS / DTS -- unwrapped); this format turns its units into a Demuxer (timescale 90 kHz; one PES = one packet: a picture as --- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 video through the codecs/video/Video --- registry (stream type 0x02 checked for an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / +-- muxed by ffmpeg, one or more audio frames) and returns a VideoDecoder: MPEG-1 / MPEG-2 video through the +-- codecs/video/Video registry (stream types 0x01 / 0x02, and private ones such as 0x80 with a video PES stream id, +-- told apart by an MPEG-2 sequence extension), H.264 when registered, audio (MP1 / MP2 / -- MP3, AAC in ADTS) through the api's opts.openAudio hook. Keyframes: MPEG-1 / 2 I-pictures, H.264 IDR access units. -- M2TS (192-byte packets with a 4-byte timestamp prefix) is read too. Not supported: writing, scrambled streams, -- PES without PTS for video before the first one (dropped). @@ -24,7 +25,7 @@ local Ts = { extensions = { "ts", "m2ts", "mts", "tsv" }, mime = { "video/mp2t" }, deps = { "core/Err", "core/Bytes", "Types", "containers/MpegTs", "containers/MpegEs", "containers/Demux", "codecs/video/Video" }, - caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "h264" }, audio = true }, + caps = { decode = true, encode = false, streaming = true, video = { "mpeg1", "mpeg2", "h264" }, audio = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/tests/video/mpeg2.luau b/tests/video/mpeg2.luau new file mode 100644 index 0000000..9fe1724 --- /dev/null +++ b/tests/video/mpeg2.luau @@ -0,0 +1,80 @@ +-- MPEG-2 video in the containers (tools/fixtures/mpeg2.py, "mpeg2_containers"): the same elementary stream copied by +-- ffmpeg into MPEG-TS (stream type 0x02, and the PMT patched to 0x80, private / DigiCipher II video), MPEG-PS (VOB), +-- Matroska (V_MPEG2) and AVI: each opens through F.video.open with codec "mpeg2", its frames equal ffmpeg's +-- `-idct int` decode (luma CRC per frame, display order), seeking lands on a frame; the raw .m2v opens too. +local T = require("@tests/T") +local F = require("@formats") +local Base64 = require("@formats/core/Base64") +local Crc32 = require("@formats/core/Crc32") +local Fx = require("@tests/gen/mpeg2_containers") +local Prog = require("@tests/gen/mpeg2_prog") + +local t = T.suite("video/mpeg2") + +local function lumaCrc(img: any): number + return Crc32.of(img.pixels, 0, img.width * img.height) +end + +local CASES = { + { "ts", "mpegts" }, + { "ts80", "mpegts" }, + { "mpg", "mpegps" }, + { "mkv", "mkv" }, + { "avi", "avi" }, +} +for _, c in CASES do + local key, format = c[1], c[2] + local data = Base64.decode(Fx[key]) :: buffer + local v, err = F.video.open(data) + t:check(v ~= nil, key .. ": opens: " .. tostring(err)) + if v then + t:eq(v.format, format, key .. ": format") + t:eq(v.codec, "mpeg2", key .. ": codec") + t:check(v.width == Prog.width and v.height == Prog.height, key .. ": size") + local frames, exact = 0, 0 + while true do + local f, ferr = v:nextFrame() + t:check(ferr == nil, key .. ": frame error " .. tostring(ferr)) + if not f then + break + end + frames += 1 + local ref = Fx.crcs[frames] + if ref and lumaCrc(f.image) == ref[1] then + exact += 1 + end + end + t:eq(frames, #Fx.crcs, key .. ": frame count") + -- the frames ffmpeg's encoder left with an uncoded macroblock are concealed differently (tests/codecs/mpeg2) + t:check(exact >= frames - 2, string.format("%s: %d of %d frames equal ffmpeg's", key, exact, frames)) + v:seek(0.4) + local f = v:nextFrame() + t:check(f ~= nil and math.abs(f.pts - 0.4) < 0.05, key .. ": seek") + t:note(" %-5s %-7s %d frames, %d bit-exact", key, format, frames, exact) + end +end + +-- the elementary stream itself +do + local v, err = F.video.open(Base64.decode(Prog.file) :: buffer) + t:check(v ~= nil and v.codec == "mpeg2", "m2v: opens as mpeg2: " .. tostring(err)) + if v then + local n = 0 + while v:nextFrame() do + n += 1 + end + t:eq(n, Prog.frames, "m2v: frame count") + end +end + +t:fuzz("open", function(b: buffer) + local v = F.video.open(b) + if v then + for _ = 1, 3 do + v:nextFrame() + end + end + return v +end, { Base64.decode(Fx.ts) :: buffer, Base64.decode(Fx.mpg) :: buffer }, { mutations = 30, garbage = 5 }) + +t:done() From e3ac2f8b366a6a5fa820135ac1f5168a079ecf9e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:56 -0500 Subject: [PATCH 22/54] ws-3d3-d: model/ldraw (LDR / DAT / MPD read: parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, library paths through files / resolve) Built-in colour table from LDConfig.ldr (CC BY 2.0 / 4.0, licenses/LDRAW_COLOURS.txt + NOTICE.md row). Tests: independent Python expansion + LeoCAD OBJ export of library parts / car.ldr / pyramid.ldr (read from the nix store). --- docs/FORMATS.md | 1 + docs/guide/scene.md | 60 +++ licenses/LDRAW_COLOURS.txt | 15 + licenses/NOTICE.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/model/ldraw/Colors.luau | 319 +++++++++++++++ src/Formats/model/ldraw/Read.luau | 580 ++++++++++++++++++++++++++++ src/Formats/model/ldraw/init.luau | 105 +++++ tests/model/ldraw.luau | 226 +++++++++++ tools/fixtures/ldraw.py | 417 ++++++++++++++++++++ 10 files changed, 1737 insertions(+) create mode 100644 licenses/LDRAW_COLOURS.txt create mode 100644 src/Formats/model/ldraw/Colors.luau create mode 100644 src/Formats/model/ldraw/Read.luau create mode 100644 src/Formats/model/ldraw/init.luau create mode 100644 tests/model/ldraw.luau create mode 100644 tools/fixtures/ldraw.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 4049798..a867468 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -39,6 +39,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index f8fb42d..2b233ff 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -391,6 +391,65 @@ Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records the origin, `meta.source.fps` / `frames` the `ANIM` chunk. +## LDraw + +LDraw files (`.ldr` models, `.dat` parts, `.mpd` multi-part files) load read-only. Every reference to a **part** +becomes a node with the reference's matrix, and each part is baked once per colour into a mesh those nodes share; +**sub-models** (`.ldr` / `.mpd` files, MPD sections that are not parts) become nodes with children. Colour 16 takes the +colour of the reference above it, 24 its edge colour; codes come from the LDConfig.ldr table built in (one material per +colour, `extras.ldraw.code` / `name`), `0x2RRGGBB` is a direct colour. BFC (`CERTIFY`, `CW` / `CCW`, `INVERTNEXT`, +`NOCLIP`) turns every face counter-clockwise; faces of uncertified parts get double-sided materials. Edge lines (type 2) +are `"lines"` primitives (`lines = false` drops them); optional lines only on request (`optionalLines = true`). + +```luau +local mpd = [[ +0 FILE house.ldr +1 4 0 0 0 1 0 0 0 1 0 0 0 1 wall.dat +1 4 50 0 0 1 0 0 0 1 0 0 0 1 wall.dat +1 1 0 -30 0 1 0 0 0 1 0 0 0 1 roof.dat +0 FILE wall.dat +0 !LDRAW_ORG Unofficial_Part +0 BFC CERTIFY CCW +4 16 -10 0 -10 10 0 -10 10 0 10 -10 0 10 +2 24 -10 0 -10 10 0 -10 +0 FILE roof.dat +0 BFC CERTIFY CCW +3 16 0 -10 0 10 0 0 -10 0 0 +]] +local scene = assert(F.model.load(mpd, { format = "ldraw" })) +print(#scene.meshes) -- 2: wall.dat in red (both walls share it), roof.dat in blue +local root = scene.nodes[scene.roots[1]] -- "LDraw": turns LDraw's -Y up into Y up +local a, b = scene.nodes[root.children[1]], scene.nodes[root.children[2]] +assert(a.mesh == b.mesh and b.matrix[13] == 50) +local red = scene.materials[scene.meshes[a.mesh].primitives[1].material] +print(red.name, red.extras.ldraw.code) -- Red 4 +assert(scene.meta.up == "y" and scene.meta.unit == 0.0004) -- 1 LDU = 0.4 mm +``` + +Parts and primitives that are not in the file come through `files` or `resolve`, asked for by their LDraw library +path: the name as written (backslashes turned into slashes), then in lower case, under `""`, `parts/`, `p/`, +`parts/s/` and `models/`. Point `resolve` at an LDraw library folder to load real models; missing files are skipped and +listed in `meta.source.missing`: + +```luau +local library = { + ["p/box.dat"] = "0 BFC CERTIFY CCW\n4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1\n4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1\n", + ["parts/plate.dat"] = "0 !LDRAW_ORG Part\n1 16 0 4 0 20 0 0 0 4 0 0 0 10 box.dat\n", +} +local model = "0 two plates\n1 14 0 0 0 1 0 0 0 1 0 0 0 1 plate.dat\n1 0x2FF8000 0 -8 0 1 0 0 0 1 0 0 0 1 plate.dat\n" + .. "1 4 0 -16 0 1 0 0 0 1 0 0 0 1 3001.dat\n" +local scene = assert(F.model.load(model, { format = "ldraw", files = library })) +assert(#scene.meshes == 2 and scene.meta.source.missing[1] == "3001.dat") +local same = assert(F.model.load(model, { format = "ldraw", resolve = function(path) + return library[path] -- or: read ldrawFolder .. "/" .. path +end })) +local flat = assert(F.model.load(model, { format = "ldraw", files = library, flatten = true })) +assert(#flat.meshes == 1) -- one mesh, one primitive per colour +``` + +`upright = false` leaves out the root node (LDraw's axes as stored, `meta.source.up = "-y"`); `ldconfig` takes the +text of another LDConfig.ldr, and `color` the colour of code 16 at the top (default 16, "Main_Colour"). + ## Formats | Format | Read | Write | Notes | @@ -406,6 +465,7 @@ the origin, `meta.source.fps` / `frames` the `ANIM` chunk. | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | | B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame | +| LDraw (LDR / DAT / MPD) | yes | | parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, `files` / `resolve` for the library | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/licenses/LDRAW_COLOURS.txt b/licenses/LDRAW_COLOURS.txt new file mode 100644 index 0000000..69ac6f7 --- /dev/null +++ b/licenses/LDRAW_COLOURS.txt @@ -0,0 +1,15 @@ +LDraw colour table (src/Formats/model/ldraw/Colors.luau) + +The built-in colour list of model/ldraw is the list of !COLOUR definitions of LDConfig.ldr from the LDraw.org Parts +Library ("0 !LDRAW_ORG Configuration UPDATE 2025-05-20", Author: LDraw.org), reformatted (one line per colour, the +"0 !COLOUR" prefix dropped, MATERIAL parameters cut after the material type). Modified from the original. + +Creator: LDraw.org (https://www.ldraw.org/) +Work: LDConfig.ldr, LDraw.org Parts Library, https://library.ldraw.org/library/updates/complete.zip +Licence: Creative Commons Attribution 2.0 (CC BY 2.0) and Creative Commons Attribution 4.0 International (CC BY 4.0), +as specified by the LDraw Contributor Agreement (see the library's CAreadme.txt): + https://creativecommons.org/licenses/by/2.0/ + https://creativecommons.org/licenses/by/4.0/ + +LDraw is a trademark of the Estate of James Jessiman. LEGO is a trademark of the LEGO Group, which does not sponsor, +authorize or endorse this software. diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index d61e1b4..f3ed9ba 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -38,6 +38,8 @@ | `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) | | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | +| `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) | +| `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 7d0229a..675db96 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -422,6 +422,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "ldraw", + category = "model", + path = "model/ldraw", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, + load = function() + return require("@formats/model/ldraw") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/model/ldraw/Colors.luau b/src/Formats/model/ldraw/Colors.luau new file mode 100644 index 0000000..d114066 --- /dev/null +++ b/src/Formats/model/ldraw/Colors.luau @@ -0,0 +1,319 @@ +--!strict +-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from +-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see +-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut +-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB. +local Colors = {} + +export type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? } +export type Table = { [number]: Colour } + +local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true } + +-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..." +function Colors.entry(rest: string): (number?, Colour?) + local words: { string } = {} + for w in string.gmatch(rest, "%S+") do + table.insert(words, w) + end + local name = words[1] + local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil + local i = 2 + while i <= #words do + local k, v = words[i], words[i + 1] + if k == "CODE" and v then + code = tonumber(v) + i += 1 + elseif k == "VALUE" and v and rgb == nil then + rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16) + i += 1 + elseif k == "EDGE" and v then + local hex = string.match(v, "^#(%x%x%x%x%x%x)$") + edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v) + i += 1 + elseif k == "ALPHA" and v then + alpha = math.clamp(tonumber(v) or 255, 0, 255) + i += 1 + elseif k == "LUMINANCE" and v then + lum = math.clamp(tonumber(v) or 0, 0, 255) + i += 1 + elseif FINISHES[k] then + finish = k + elseif k == "MATERIAL" and v then + finish = v + break + end + i += 1 + end + if not name or not code or not rgb or code % 1 ~= 0 then + return nil, nil + end + return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish } +end + +-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added +function Colors.parse(text: string, into: Table?): Table + local t: Table = into or {} + for line in string.gmatch(text, "[^\n]+") do + local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$") + if rest then + local code, c = Colors.entry(rest) + if code and c then + t[code] = c + end + end + end + return t +end + +local BUILTIN = [[ +Black CODE 0 VALUE #1B2A34 EDGE #808080 +Blue CODE 1 VALUE #1E5AA8 EDGE #333333 +Green CODE 2 VALUE #00852B EDGE #333333 +Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333 +Red CODE 4 VALUE #B40000 EDGE #333333 +Dark_Pink CODE 5 VALUE #D3359D EDGE #333333 +Brown CODE 6 VALUE #543324 EDGE #1E1E1E +Light_Grey CODE 7 VALUE #8A928D EDGE #333333 +Dark_Grey CODE 8 VALUE #545955 EDGE #333333 +Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333 +Bright_Green CODE 10 VALUE #58AB41 EDGE #333333 +Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333 +Salmon CODE 12 VALUE #F06D61 EDGE #333333 +Pink CODE 13 VALUE #F6A9BB EDGE #333333 +Yellow CODE 14 VALUE #FAC80A EDGE #333333 +White CODE 15 VALUE #F4F4F4 EDGE #333333 +Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333 +Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333 +Tan CODE 19 VALUE #D7BA8C EDGE #333333 +Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333 +Purple CODE 22 VALUE #671F81 EDGE #333333 +Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333 +Orange CODE 25 VALUE #D67923 EDGE #333333 +Magenta CODE 26 VALUE #901F76 EDGE #333333 +Lime CODE 27 VALUE #A5CA18 EDGE #333333 +Dark_Tan CODE 28 VALUE #897D62 EDGE #333333 +Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333 +Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333 +Lavender CODE 31 VALUE #CDA4DE EDGE #333333 +Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333 +Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333 +Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080 +Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333 +Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333 +Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333 +Medium_Green CODE 74 VALUE #7FC475 EDGE #333333 +Light_Pink CODE 77 VALUE #FECCCF EDGE #333333 +Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333 +Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333 +Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333 +Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333 +Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333 +Nougat CODE 92 VALUE #BB805A EDGE #333333 +Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333 +Violet CODE 110 VALUE #26469A EDGE #333333 +Medium_Violet CODE 112 VALUE #4861AC EDGE #333333 +Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333 +Aqua CODE 118 VALUE #9CD6CC EDGE #333333 +Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333 +Light_Orange CODE 125 VALUE #F9A777 EDGE #333333 +Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333 +Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333 +Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333 +Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333 +Rust CODE 216 VALUE #872B17 EDGE #333333 +Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333 +Lilac CODE 219 VALUE #564E9D EDGE #333333 +Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333 +Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333 +Dark_Blue CODE 272 VALUE #19325A EDGE #333333 +Dark_Green CODE 288 VALUE #00451A EDGE #808080 +Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333 +Dark_Brown CODE 308 VALUE #352100 EDGE #808080 +Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333 +Dark_Red CODE 320 VALUE #720012 EDGE #333333 +Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333 +Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333 +Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333 +Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333 +Olive_Green CODE 330 VALUE #77774E EDGE #333333 +Sand_Red CODE 335 VALUE #88605E EDGE #333333 +Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333 +Coral CODE 353 VALUE #FF6D77 EDGE #333333 +Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333 +Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333 +Medium_Brown CODE 370 VALUE #755945 EDGE #333333 +Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333 +Sand_Purple CODE 373 VALUE #75657D EDGE #333333 +Sand_Green CODE 378 VALUE #708E7C EDGE #333333 +Sand_Blue CODE 379 VALUE #70819A EDGE #333333 +Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333 +Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333 +Umber_Brown CODE 423 VALUE #543F33 EDGE #333333 +Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333 +Medium_Orange CODE 462 VALUE #F58624 EDGE #333333 +Dark_Orange CODE 484 VALUE #91501C EDGE #333333 +Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333 +Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333 +Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333 +Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333 +Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333 +Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128 +Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128 +Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128 +Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128 +Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128 +Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128 +Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128 +Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128 +Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128 +Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128 +Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 +Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128 +Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128 +Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128 +Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 +Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128 +Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128 +Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 +Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210 +Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128 +Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128 +Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128 +Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128 +Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128 +Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128 +Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128 +Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128 +Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME +Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME +Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME +Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME +Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME +Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME +Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME +Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT +Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT +Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT +Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT +Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT +Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT +Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT +Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT +Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT +Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT +Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT +Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT +Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT +Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT +Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT +Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT +Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT +Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT +Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT +Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL +Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL +Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL +Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL +Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL +Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL +Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL +Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL +Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240 +Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15 +Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15 +Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15 +Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER +Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER +Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER +Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER +Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE +Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE +Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE +Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER +Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER +Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER +Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER +Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER +Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER +Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER +Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER +Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER +Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER +Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER +Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER +Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER +Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER +Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER +Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER +Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER +Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER +Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER +Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER +Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER +Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER +Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER +Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER +Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER +Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER +Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER +Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER +Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER +Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER +Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER +Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER +Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER +Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER +Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER +Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER +Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC +Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC +Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC +Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC +Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC +Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC +Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC +Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC +Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC +Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC +Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC +Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333 +Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333 +Magnet CODE 493 VALUE #656761 EDGE #333333 METAL +Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL +Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL +Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16 +]] + +local cache: Table? = nil +-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it) +function Colors.builtin(): Table + if not cache then + local t: Table = {} + for line in string.gmatch(BUILTIN, "[^\n]+") do + local code, c = Colors.entry(line) + if code and c then + t[code] = c + end + end + cache = t + end + local copy: Table = {} + for k, v in cache :: Table do + copy[k] = v + end + return copy +end + +return Colors diff --git a/src/Formats/model/ldraw/Read.luau b/src/Formats/model/ldraw/Read.luau new file mode 100644 index 0000000..8aa58d9 --- /dev/null +++ b/src/Formats/model/ldraw/Read.luau @@ -0,0 +1,580 @@ +--!strict +-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command +-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into +-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes. +-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from). +local Types = require("@formats/Types") +local Colors = require("@formats/model/ldraw/Colors") + +local Read = {} + +export type Options = { + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + ldconfig: string?, + color: number?, + upright: boolean?, + flatten: boolean?, + lines: boolean?, + optionalLines: boolean?, + maxDepth: number?, + maxTriangles: number?, + maxNodes: number?, +} + +-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5 +type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? } +type File = { + name: string, + key: string, + cmds: { Cmd }, + certified: boolean, + org: string?, + refs: number, + library: boolean, + main: boolean, + title: string?, + author: string?, + model: boolean?, +} +type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? } + +local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" } +local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true } +local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 } +local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 } + +local function norm(name: string): string + return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/"))) +end + +local function srgbToLinear(v: number): number + return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4 +end + +-- parse(text, name) -> File (colour definitions go into colours as they are met) +local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File + local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false } + local cmds = f.cmds + local invert, step, first = false, 1, true + for line in string.gmatch(text, "[^\n]+") do + local t = string.match(line, "^%s*(%d)%s") + if t then + stats.lines += 1 + end + if t == "0" then + local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$") + if w1 == "BFC" and rest then + local u = string.upper(rest) + local cmd: Cmd? = nil + for word in string.gmatch(u, "%S+") do + if word == "CERTIFY" then + f.certified = true + elseif word == "NOCERTIFY" then + f.certified = false + elseif word == "INVERTNEXT" then + invert = true + elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then + local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 } + cmd = c + if word == "CW" or word == "CCW" then + c.cw = word == "CW" + else + c.clip = word == "CLIP" + end + end + end + if cmd then + table.insert(cmds, cmd) + end + elseif w1 == "!COLOUR" then + Colors.parse(line, colours) + elseif w1 == "!LDRAW_ORG" and rest then + f.org = string.match(rest, "^(%S+)") + elseif w1 == "STEP" then + step += 1 + elseif w1 == "Author:" then + f.author = rest + elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then + -- (headers) + elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then + f.title = (string.match(line, "^%s*0%s+(.-)%s*$")) + end + first = false + elseif t then + first = false + local k = tonumber(t) :: number + local inv = invert + invert = false + if k == 1 then + local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$") + local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) } + local code = tonumber(c) + local complete = true + for j = 1, 12 do + if v[j] == nil then + complete = false + end + end + if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then + table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step }) + f.refs += 1 + else + stats.bad += 1 + end + elseif k >= 2 and k <= 5 then + local need = if k == 2 then 6 elseif k == 3 then 9 else 12 + local v: { number } = {} + local code: number? = nil + local n = 0 + for w in string.gmatch(line, "%S+") do + n += 1 + if n == 2 then + code = tonumber(w) + elseif n > 2 and n <= need + 2 then + local num = tonumber(w) + if not num then + break + end + v[n - 2] = num + end + end + if code and code >= 0 and code % 1 == 0 and #v == need then + table.insert(cmds, { k = k, c = code, v = v }) + else + stats.bad += 1 + end + elseif k ~= 0 then + stats.bad += 1 + end + end + end + return f +end + +-- scene(text, opts) -> Scene | nil, message, kind +function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?) + local o: Options = opts or {} + local colours = Colors.builtin() + if type(o.ldconfig) == "string" then + Colors.parse(o.ldconfig, colours) + end + local maxDepth = o.maxDepth or 64 + local maxTriangles = o.maxTriangles or 2 ^ 24 + local maxNodes = o.maxNodes or 2 ^ 20 + local withLines = o.lines ~= false + local withOptional = o.optionalLines == true + local stats = { bad = 0, lines = 0 } + + -- ------------------------------------------------------------------------------------------ MPD sections + text = string.gsub(text, "\r", "") + local sections: { [string]: string } = {} + local mainName: string? = nil + local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil + local mainText = text + if mpd then + local cur: string? = nil + local buf: { string } = {} + local function close() + if cur and sections[cur] == nil then + sections[cur] = table.concat(buf, "\n") + end + cur, buf = nil, {} + end + for line in string.gmatch(text, "[^\n]+") do + local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$") + if fname then + close() + cur = norm(fname) + if not mainName then + mainName = fname + end + elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then + close() + elseif cur then + table.insert(buf, line) + end + end + close() + mainText = sections[norm(mainName or "")] or "" + end + + -- ------------------------------------------------------------------------------------------ files + local cache: { [string]: File | false } = {} + local missing: { [string]: boolean } = {} + local fetchFiles = o.files + local resolve = o.resolve + local function fetch(uri: string): string? + local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil + if v == nil and type(resolve) == "function" then + local ok, res = pcall(resolve, uri) + v = if ok then res else nil + end + return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil + end + local function lookup(name: string): File? + local key = norm(name) + local have = cache[key] + if have ~= nil then + return have or nil + end + local sec = sections[key] + if sec then + local f = parse(sec, name, colours, stats) + cache[key] = f + return f + end + local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/") + for _, prefix in PREFIXES do + for _, cand in { prefix .. slash, prefix .. key } do + local data = fetch(cand) + if data then + local f = parse((string.gsub(data, "\r", "")), name, colours, stats) + f.library = LIBRARY[prefix] == true + cache[key] = f + return f + end + end + end + missing[key] = true + cache[key] = false + return nil + end + local function isModel(f: File): boolean + local m = f.model + if m == nil then + local org = string.lower(f.org or "") + local orgPart = org ~= "" and not string.find(org, "model", 1, true) + if f.main then + m = not orgPart and f.refs > 0 + else + local ext = string.match(f.key, "%.(%w+)$") + m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd") + end + f.model = m + end + return m :: boolean + end + + -- ------------------------------------------------------------------------------------------ colours, materials + local scene = Types.Scene.new() + local function edgeOf(c: number): number + local e = colours[c] + if e then + return e.edge + end + return if c >= 0x2000000 then 0x2000000 else 0x2333333 + end + local function resolveColour(code: number, cur: number): number + if code == 16 then + return cur + elseif code == 24 then + return edgeOf(cur) + end + return code + end + local materialOf: { [string]: number } = {} + local function material(col: number, ds: boolean): number + local key = col .. (if ds then "d" else "") + local have = materialOf[key] + if have then + return have + end + local entry = colours[col] + local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil + if entry then + rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish + elseif col >= 0x2000000 and col < 0x4000000 then + rgb = col % 0x1000000 + alpha = if col >= 0x3000000 then 128 else 255 + name = string.format("#%06X", rgb) + elseif col >= 0x4000000 and col < 0x8000000 then + -- dithered: two 12-bit colours, shown as their mean + local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000 + local function ch(v: number, s: number): number + return ((v // s) % 16) * 17 + end + rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2 + alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255 + name = string.format("Dither_%X", col) + end + local m = Types.Scene.material(name) + m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 } + if alpha < 255 then + m.alphaMode = "blend" + end + m.doubleSided = ds + m.metallic = 0 + m.roughness = 0.35 + if finish == "CHROME" or finish == "METAL" then + m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4 + elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then + m.metallic, m.roughness = 0.6, 0.45 + elseif finish == "RUBBER" then + m.roughness = 0.9 + end + m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } } + table.insert(scene.materials, m) + materialOf[key] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ baking + local failure: string?, failKind: string? = nil, nil + local triangles = 0 + local cycles = 0 + local function fail(msg: string, kind: string?) + if not failure then + failure, failKind = msg, kind + end + end + + -- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct) + local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-files nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local model = isModel(f) + local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m) + local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9) + local cw, clip = false, true + local function group(mode: string, col: number, ds: boolean): Group + local key = mode .. col .. (if ds then "d" else "") + local g = groups[key] + if not g then + g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil } + groups[key] = g + table.insert(order, g) + end + return g + end + local function put(list: { number }, x: number, y: number, z: number) + local n = #list + list[n + 1] = m1 * x + m2 * y + m3 * z + m4 + list[n + 2] = m5 * x + m6 * y + m7 * z + m8 + list[n + 3] = m9 * x + m10 * y + m11 * z + m12 + end + for _, cmd in f.cmds do + if failure then + break + end + local k = cmd.k + local v = cmd.v + if k == 0 then + if cmd.cw ~= nil then + cw = cmd.cw :: boolean + end + if cmd.clip ~= nil then + clip = cmd.clip :: boolean + end + elseif k == 1 then + if not direct then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v) + local child = { + m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4, + m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8, + m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12, + } + local childCert = if model then true else certified and f.certified and clip + bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false) + end + end + elseif k == 3 or k == 4 then + local col = resolveColour(cmd.c, colour) + local one = certified and f.certified and clip + local g = group("triangles", col, not one) + local rev = cw ~= inv ~= (det < 0) + local p = g.pos + local nt = if k == 3 then 1 else 2 + triangles += nt + if triangles > maxTriangles then + return fail(string.format("limit: more than %d triangles", maxTriangles), "limit") + end + local function tri(a: number, b: number, c: number) + if rev then + a, c = c, a + end + put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3]) + put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3]) + put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3]) + end + tri(0, 1, 2) + if k == 4 then + tri(0, 2, 3) + end + elseif k == 2 and withLines then + local g = group("lines", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + elseif k == 5 and withOptional then + local g = group("optional", resolveColour(cmd.c, colour), false) + put(g.pos, v[1], v[2], v[3]) + put(g.pos, v[4], v[5], v[6]) + local ctrl = g.ctrl :: { number } + for _ = 1, 2 do + put(ctrl, v[7], v[8], v[9]) + put(ctrl, v[10], v[11], v[12]) + end + end + end + stack[f] = nil + end + + local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor + local b = buffer.create(count * 12) + for i = 0, count - 1 do + local s = from + i * step + buffer.writef32(b, i * 12, list[s]) + buffer.writef32(b, i * 12 + 4, list[s + 1]) + buffer.writef32(b, i * 12 + 8, list[s + 2]) + end + return Types.Scene.accessor(b, "f32", 3, count) + end + + -- the mesh of a file baked at the identity (nil when it has no geometry) + local meshOf: { [string]: number | false } = {} + local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number? + local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "") + local have = meshOf[key] + if have ~= nil then + return have or nil + end + local groups: { [string]: Group } = {} + local order: { Group } = {} + bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct) + local mesh: Types.Mesh = { name = f.name, primitives = {} } + for _, g in order do + local count = #g.pos // 3 + if count > 0 then + local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" } + prim.material = material(g.colour, g.ds) + if g.mode == "optional" then + local ctrl = g.ctrl :: { number } + prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count) + prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count) + prim.extras = { ldraw = { optional = true } } + end + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + meshOf[key] = false + return nil + end + table.insert(scene.meshes, mesh) + meshOf[key] = #scene.meshes + return #scene.meshes + end + + -- ------------------------------------------------------------------------------------------ the node tree + local mainFile = parse(mainText, mainName or "main", colours, stats) + mainFile.main = true + if stats.lines == 0 then + return nil, "no LDraw lines", nil + end + if mainName then + cache[norm(mainName)] = mainFile + end + local mainColour = o.color or 16 + local function newNode(node: Types.Node): number + table.insert(scene.nodes, node) + if #scene.nodes > maxNodes then + fail(string.format("limit: more than %d nodes", maxNodes), "limit") + end + return #scene.nodes + end + local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean }) + if failure then + return + end + if depth > maxDepth then + return fail("limit: sub-models nested deeper than " .. maxDepth, "limit") + end + stack[f] = true + local direct = meshFor(f, colour, inv, true) + if direct then + table.insert(out, newNode({ name = f.name, children = {}, mesh = direct })) + end + for _, cmd in f.cmds do + if failure then + break + end + if cmd.k == 1 then + local sub = lookup(cmd.name :: string) + if sub and stack[sub] then + cycles += 1 + elseif sub then + local v = cmd.v + local c = resolveColour(cmd.c, colour) + local subInv = inv ~= (cmd.inv == true) + local node: Types.Node = { + name = cmd.name, + children = {}, + matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 }, + extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } }, + } + local index = newNode(node) + if isModel(sub) then + expand(sub, c, subInv, node.children, depth + 1, stack) + else + node.mesh = meshFor(sub, c, subInv, false) + end + table.insert(out, index) + end + end + end + stack[f] = nil + end + local top: { number } = {} + if o.flatten or not isModel(mainFile) then + local mesh = meshFor(mainFile, mainColour, false, false) + table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh })) + else + expand(mainFile, mainColour, false, top, 0, {}) + end + if failure then + return nil, failure, failKind + end + if o.upright == false then + scene.roots = top + else + table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) }) + scene.roots = { #scene.nodes } + scene.meta.up = "y" + end + scene.meta.unit = 0.0004 + local missingList: { string } = {} + for k in missing do + table.insert(missingList, k) + end + table.sort(missingList) + local nfiles = 0 + for _, f in cache do + if f then + nfiles += 1 + end + end + scene.meta.source = { + format = "ldraw", + mpd = mpd, + name = mainName, + title = mainFile.title, + author = mainFile.author, + files = nfiles, + missing = missingList, + cycles = cycles, + badLines = stats.bad, + up = if o.upright == false then "-y" else nil, + } + return scene, nil, nil +end + +return Read diff --git a/src/Formats/model/ldraw/init.luau b/src/Formats/model/ldraw/init.luau new file mode 100644 index 0000000..b7ed74c --- /dev/null +++ b/src/Formats/model/ldraw/init.luau @@ -0,0 +1,105 @@ +--!strict +-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and +-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked +-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models. +-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour + +-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines +-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at +-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried +-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing +-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles). +-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without +-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main +-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw = +-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one +-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines +-- = false drops them); no normals, no indices (each triangle has its own three vertices). +-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise +-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or +-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place. +-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge +-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig +-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered +-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER -> +-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }). +-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node +-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright = +-- false leaves it out (meta.up = nil, meta.source.up = "-y"). +-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }. +-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta +-- commands (ignored); BFC in model files' references (models place parts as certified). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Read = require("@formats/model/ldraw/Read") +local Colors = require("@formats/model/ldraw/Colors") + +-- ------------------------------------------------------------------------------------------------ contract +local Ldraw = { + name = "ldraw", + category = "model", + extensions = { "ldr", "mpd", "dat" }, + mime = { "application/x-ldraw", "application/x-multi-part-ldraw" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = false, materials = true, lines = true, instancing = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths) + files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...) + ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours + color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour") + upright: boolean?, -- add the root node turning -Y up into Y up (default true) + flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false) + lines: boolean?, -- type 2 edge lines as "lines" primitives (default true) + optionalLines: boolean?, -- type 5 optional lines too (default false) + maxDepth: number?, -- sub-file nesting (default 64) + maxTriangles: number?, -- default 2^24 + maxNodes: number?, -- default 2^20 +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ldraw.sniff(r: Bytes.Reader): number + local head = Sniff.text(r, 2048, true) + if string.find(head, "^0%s+FILE%s") then + return 0.9 + end + if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then + return 0.8 + end + if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then + return 0.4 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, kind = pcall(Read.scene, text, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, nil, kind) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance, +-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added +function Ldraw.colors(ldconfig: string?): { [number]: any } + local t = Colors.builtin() + if ldconfig then + Colors.parse(ldconfig, t) + end + return t +end + +return Ldraw diff --git a/tests/model/ldraw.luau b/tests/model/ldraw.luau new file mode 100644 index 0000000..f72e535 --- /dev/null +++ b/tests/model/ldraw.luau @@ -0,0 +1,226 @@ +-- model/ldraw tests: hand-written LDraw files (a brick of primitives found through library paths, an MPD with +-- embedded parts and sub-models, BFC CW / CCW / INVERTNEXT / NOCLIP / uncertified files, mirrored references, colours +-- 16 / 24 / direct / local !COLOUR, optional lines, a missing part, a self-reference, bad lines, CRLF) and real library +-- parts and models (3001, 3062b, 4073, 3626c, car.ldr, pyramid.ldr) against an independent expansion in the generator +-- (world triangles per colour, double-sided faces, lines, area, signed volume of the one-sided faces, bounds, missing +-- files) and LeoCAD's OBJ export (bounds, area); node / flattened / un-flipped scenes agree; mesh sharing; the +-- built-in colour table against LDConfig.ldr; resolve; error codes; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/ldraw.py. +local T = require("@tests/T") +local Ldraw = require("@formats/model/ldraw") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/ldraw_cases") +local Config = require("@tests/gen/ldraw_config") + +local t = T.suite("ldraw") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ldraw.decode(Bytes.reader(b), opts) +end + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +t:eq(Ldraw.name, "ldraw", "name") +t:eq(Ldraw.category, "model", "category") +t:check(Ldraw.caps.decode and not Ldraw.caps.encode, "caps") +t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 FILE main.ldr\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 a.dat\n"))) >= 0.9, "sniff MPD") +t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 x\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 3001.dat\n"))) >= 0.8, "sniff LDR") +t:eq(Ldraw.sniff(Bytes.reader(buffer.fromstring("solid cube\n facet normal 0 0 1\n"))), 0, "sniff other") + +-- ------------------------------------------------------------------------------------------------ colour table +do + local tbl = Ldraw.colors() + local bad = 0 + for _, c in Config.colours do + local e = tbl[c[1]] + if not e or e.rgb ~= c[2] or e.edge ~= c[3] or e.alpha ~= c[4] then + bad += 1 + end + end + t:eq(bad, 0, "built-in colours = LDConfig.ldr (" .. #Config.colours .. " colours)") + local over = Ldraw.colors("0 !COLOUR Mine CODE 4 VALUE #010203 EDGE 0\n") + t:check(over[4].rgb == 0x010203 and over[4].edge == 0 and over[4].name == "Mine", "ldconfig overrides") +end + +-- ------------------------------------------------------------------------------------------------ measuring +type Stats = { triangles: number, lines: number, optional: number, ds: number, area: number, volume: number, colours: { [number]: number } } + +local function det3(m: { number }): number + return 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]) +end + +local function measure(scene: any): Stats + local s: Stats = { triangles = 0, lines = 0, optional = 0, ds = 0, area = 0, volume = 0, colours = {} } + for _, pl in Types.Scene.flatten(scene) do + local p = pl.primitive + local n = p.attributes.POSITION.count + if p.mode == "lines" then + if p.extras and p.extras.ldraw and p.extras.ldraw.optional then + s.optional += n // 2 + else + s.lines += n // 2 + end + else + local mat = scene.materials[p.material] + local code = mat.extras.ldraw.code + s.colours[code] = (s.colours[code] or 0) + n // 3 + s.triangles += n // 3 + if mat.doubleSided then + s.ds += n // 3 + end + local m = pl.matrix + local flip = det3(m) < 0 + local get = assert(Types.Scene.reader(p.attributes.POSITION)) + for tri = 0, n // 3 - 1 do + local q = {} + for k = 0, 2 do + local x, y, z = get(tri * 3 + k, 0), get(tri * 3 + k, 1), get(tri * 3 + k, 2) + q[k + 1] = { 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 + local a, b, c = q[1], q[2], q[3] + if flip then + a, c = c, a + end + local ux, uy, uz, vx, vy, vz = b[1] - a[1], b[2] - a[2], b[3] - a[3], c[1] - a[1], c[2] - a[2], c[3] - a[3] + local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + s.area += math.sqrt(x * x + y * y + z * z) / 2 + if not mat.doubleSided then + s.volume += (a[1] * (b[2] * c[3] - b[3] * c[2]) - a[2] * (b[1] * c[3] - b[3] * c[1]) + a[3] * (b[1] * c[2] - b[2] * c[1])) / 6 + end + end + end + end + return s +end + +local function compare(label: string, s: Stats, w: any) + t:eq(s.triangles, w.triangles, label .. ": triangles") + t:eq(s.ds, w.doubleSided, label .. ": double-sided triangles") + t:eq(s.lines, w.lines, label .. ": lines") + local bad = {} + for _, pair in w.colours do + if s.colours[pair[1]] ~= pair[2] then + table.insert(bad, string.format("%d: %s / %d", pair[1], tostring(s.colours[pair[1]]), pair[2])) + end + end + t:check(#bad == 0 and #w.colours == #(function() + local keys = {} + for k in s.colours do + table.insert(keys, k) + end + return keys + end)(), label .. ": triangles per colour " .. table.concat(bad, ", ")) + t:check(near(s.area, w.area, 1e-5), string.format("%s: area %.6f / %.6f", label, s.area, w.area)) + t:check(near(s.volume, w.volume, 1e-5), string.format("%s: signed volume %.6f / %.6f", label, s.volume, w.volume)) +end + +-- ------------------------------------------------------------------------------------------------ cases +local samples = {} +local lib: any = nil +for _, c in Cases do + local opts = table.clone(c.opts or {}) + opts.files = c.files + local scene, err = decode(c.data, opts) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + local w = c.want + compare(c.name, measure(scene), w) + local lo, hi = MeshOps.bounds(assert(MeshOps.merge(scene))) + local ok = lo ~= nil and w.min ~= nil + for k = 1, 3 do + ok = ok and near((lo :: any)[k], w.min[k], 1e-5) and near((hi :: any)[k], w.max[k], 1e-5) + end + t:check(ok, string.format("%s: bounds %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " "))) + t:eq(table.concat(scene.meta.source.missing, ","), table.concat(w.missing, ","), c.name .. ": missing files") + t:check(scene.meta.up == "y" and scene.meta.unit == 0.0004, c.name .. ": meta.up / unit") + -- LeoCAD: its axes are (x, -z, y) of ours, 2 decimals + local lc = c.leocad + if lc then + local lmin = { lo[1], -hi[3], lo[2] } + local lmax = { hi[1], -lo[3], hi[2] } + local good = true + for k = 1, 3 do + good = good and math.abs(lmin[k] - lc.min[k]) < 0.02 and math.abs(lmax[k] - lc.max[k]) < 0.02 + end + t:check(good, c.name .. ": bounds (LeoCAD)") + local s = measure(scene) + t:check(near(s.area, lc.area, 2e-4), string.format("%s: area %.3f (LeoCAD %.3f)", c.name, s.area, lc.area)) + end + -- the same model flattened into one mesh, and without the root flip + local flat = assert(decode(c.data, { files = c.files, flatten = true })) + t:eq(#flat.meshes <= 1, true, c.name .. ": flatten: one mesh") + compare(c.name .. " (flatten)", measure(flat), w) + local raw = assert(decode(c.data, { files = c.files, upright = false })) + local rlo, rhi = MeshOps.bounds(assert(MeshOps.merge(raw))) + t:check(rlo and near(rlo[2], -hi[2], 1e-6) and near(rhi[3], -lo[3], 1e-6) and raw.meta.source.up == "-y", c.name .. ": upright = false") + if #c.data < 4000 then + table.insert(samples, c.data) + end + if c.name == "two.ldr" then + lib = c.files + -- one mesh per (part, colour): four colours, the missing part has no node + t:eq(#scene.meshes, 4, "two.ldr: meshes per colour") + local root = scene.nodes[scene.roots[1]] + t:eq(#root.children, 4, "two.ldr: one node per placed part") + local steps = {} + for _, ci in root.children do + table.insert(steps, scene.nodes[ci].extras.ldraw.step) + end + t:eq(table.concat(steps, ","), "1,1,1,2", "two.ldr: steps") + -- through resolve instead of files + local viaResolve = assert(decode(c.data, { resolve = function(uri: string): any + return c.files[uri] + end })) + t:eq(measure(viaResolve).triangles, w.triangles, "two.ldr: resolve") + -- optional lines on request + local withOpt = assert(decode(c.data, { files = c.files, optionalLines = true, lines = false })) + local so = measure(withOpt) + t:check(so.optional == w.optional and so.lines == 0, "two.ldr: optional lines only") + elseif c.name == "model.mpd" then + t:check(scene.meta.source.mpd, "model.mpd: mpd") + local meshNodes = 0 + for _, n in scene.nodes do + if n.mesh then + meshNodes += 1 + end + end + t:check(#scene.meshes < meshNodes, string.format("model.mpd: meshes shared (%d meshes, %d mesh nodes)", #scene.meshes, meshNodes)) + local purple + for _, m in scene.materials do + if m.extras.ldraw.code == 1000 then + purple = m + end + end + t:check(purple and purple.name == "Test_Purple" and purple.alphaMode == "blend", "model.mpd: local !COLOUR") + elseif c.name == "badrefs.ldr" then + t:check(scene.meta.source.cycles > 0 and scene.meta.source.badLines == 2, "badrefs.ldr: cycle and bad lines counted") + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e = decode("") + t:check(e and e.code == Err.CORRUPT, "empty: CORRUPT") + _, e = decode("hello world\nthis is not ldraw\n") + t:check(e and e.code == Err.CORRUPT, "text: CORRUPT") + _, e = decode(Cases[1].data, { files = Cases[1].files, maxTriangles = 10 }) + t:check(e and e.code == Err.LIMIT, "maxTriangles: LIMIT") + _, e = decode(Cases[1].data, { files = Cases[1].files, maxDepth = 0 }) + t:check(e and e.code == Err.LIMIT, "maxDepth: LIMIT") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +t:fuzz("decode", function(b: buffer) + local s = Ldraw.decode(Bytes.reader(b), { files = lib, optionalLines = true }) + if s then + MeshOps.merge(s) + end + return s +end, samples, { mutations = 24 }) + +t:done() diff --git a/tools/fixtures/ldraw.py b/tools/fixtures/ldraw.py new file mode 100644 index 0000000..1808d79 --- /dev/null +++ b/tools/fixtures/ldraw.py @@ -0,0 +1,417 @@ +# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through +# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT, +# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions, +# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts +# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never +# committed: each case carries the files it needs). References: an independent expansion written here (world +# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and +# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in +# colour table. +# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} } +# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } } +import math, os, re, subprocess, zipfile + +INPUTS = [] + + +def nix_out(attr): + out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def library_zip(leocad): + # LeoCAD's wrapper points LEOCAD_LIB at the parts library zip + wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1") + m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper) + return m.group(1) if m else None + + +# ---------------------------------------------------------------------------------------------------- reference +def norm(name): + return name.strip().replace("\\", "/").lower() + + +class Ref: + """an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)""" + + PREFIXES = ("", "parts/", "p/", "parts/s/", "models/") + + def __init__(self, main, files, colours): + self.files = {norm(k): v for k, v in files.items()} + self.colours = colours # code -> (rgb, edge) + self.mpd = {} + self.missing = set() + self.tris = [] # (colour, ds, (v0, v1, v2)) + self.lines = 0 + self.optional = 0 + text = main + if re.search(r"^\s*0\s+FILE\s", text, re.M): + cur = None + first = None + for line in text.splitlines(): + m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line) + if m: + cur = norm(m.group(1)) + first = first or cur + self.mpd[cur] = [] + continue + if re.match(r"^\s*0\s+NOFILE\b", line): + cur = None + continue + if cur: + self.mpd[cur].append(line) + self.main = "\n".join(self.mpd[first]) + else: + self.main = text + org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M) + refs = re.search(r"^\s*1\s", self.main, re.M) + self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs + + def lookup(self, name): + n = norm(name) + if n in self.mpd: + return "\n".join(self.mpd[n]) + for p in self.PREFIXES: + if p + n in self.files: + return self.files[p + n] + self.missing.add(n) + return None + + def colour(self, code, cur): + if code == 16: + return cur + if code == 24: + return self.edge(cur) + return code + + def edge(self, c): + if c in self.colours: + e = self.colours[c][1] + return e + return 0x2333333 if c < 0x2000000 else 0x2000000 + + def walk(self, text, m, colour, inv, certified, depth, model, stack=()): + # model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place + if depth > 64: + return + st = {"cw": False, "cert": None, "clip": True, "invert": False} + for raw in text.splitlines(): + t = raw.split() + if not t: + continue + if t[0] == "0": + if len(t) >= 3 and t[1] == "!COLOUR": + self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()}) + if len(t) >= 3 and t[1] == "BFC": + words = [w.upper() for w in t[2:]] + if "NOCERTIFY" in words: + st["cert"] = False + elif "CERTIFY" in words: + st["cert"] = True + if "CW" in words: + st["cw"] = True + if "CCW" in words: + st["cw"] = False + if "NOCLIP" in words: + st["clip"] = False + elif "CLIP" in words: + st["clip"] = True + if "INVERTNEXT" in words: + st["invert"] = True + continue + invert_next = st["invert"] + st["invert"] = False + try: + kind = int(t[0]) + code = int(t[1], 0) + cert = certified and st["cert"] is True and st["clip"] + if kind == 1 and len(t) >= 15: + x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]] + loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]] + name = raw.split(None, 14)[14].strip() + if norm(name) in stack: + continue # a file that (indirectly) places itself + sub = self.lookup(name) + if sub is None: + continue + sub_model = norm(name).endswith((".ldr", ".mpd")) + self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next, + (True if model else cert), depth + 1, sub_model, stack + (norm(name),)) + elif kind in (3, 4) and len(t) >= 2 + 3 * kind: + pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)] + if st["cw"] ^ inv ^ (det(m) < 0): + pts = pts[::-1] + col = self.colour(code, colour) + one = cert and not model or (model and st["cert"] is True and st["clip"]) + self.tris.append((col, not one, (pts[0], pts[1], pts[2]))) + if kind == 4: + self.tris.append((col, not one, (pts[0], pts[2], pts[3]))) + elif kind == 2 and len(t) >= 8: + [float(v) for v in t[2:8]] + self.lines += 1 + elif kind == 5 and len(t) >= 14: + [float(v) for v in t[2:14]] + self.optional += 1 + except ValueError: + pass + + def run(self, main_colour=16): + flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]] + self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part) + return self + + def summary(self): + per = {} + area, vol = 0.0, 0.0 + lo, hi = [1e30] * 3, [-1e30] * 3 + for col, ds, (a, b, c) in self.tris: + per[col] = per.get(col, 0) + 1 + for p in (a, b, c): + lo = [min(u, v) for u, v in zip(lo, p)] + hi = [max(u, v) for u, v in zip(hi, p)] + area += tri_area(a, b, c) + if not ds: + vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6 + out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol, + "doubleSided": sum(1 for x in self.tris if x[1]), + "colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)} + if self.tris: + out["min"], out["max"] = lo, hi + return out + + +def mul(m, l): + # 3x4 affine product m * l + r = [[0.0] * 4 for _ in range(3)] + for i in range(3): + for j in range(4): + s = sum(m[i][k] * l[k][j] for k in range(3)) + r[i][j] = s + (m[i][3] if j == 3 else 0) + return r + + +def apply(m, p): + return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)] + + +def det(m): + return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])) + + +def tri_area(a, b, c): + e1 = [b[i] - a[i] for i in range(3)] + e2 = [c[i] - a[i] for i in range(3)] + x = e1[1] * e2[2] - e1[2] * e2[1] + y = e1[2] * e2[0] - e1[0] * e2[2] + z = e1[0] * e2[1] - e1[1] * e2[0] + return math.sqrt(x * x + y * y + z * z) / 2 + + +def parse_ldconfig(text): + out = {} + for line in text.splitlines(): + m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line) + if not m: + continue + t = m.group(2).split() + kv = {} + for i in range(0, len(t) - 1): + if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv: + kv[t[i]] = t[i + 1] + code = int(kv["CODE"]) + rgb = int(kv["VALUE"][1:], 16) + e = kv["EDGE"] + edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e) + out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1)) + return out + + +# ---------------------------------------------------------------------------------------------------- hand-written +BOX = """0 a unit box primitive (faces outward, CCW) +0 BFC CERTIFY CCW +4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1 +4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1 +4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 +4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1 +4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1 +4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1 +2 24 -1 -1 -1 1 -1 -1 +2 24 -1 -1 -1 -1 1 -1 +5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1 +""" + +BOX_CW = """0 the same box written clockwise +0 BFC CERTIFY CW +4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1 +4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1 +4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 +4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1 +4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1 +4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1 +""" + +TRI = """0 an uncertified triangle +3 16 0 0 0 1 0 0 0 0 1 +""" + +# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle +BRICK = """0 Test Brick 1 x 2 +0 Name: testbrick.dat +0 Author: formats-luau +0 !LDRAW_ORG Unofficial_Part +0 BFC CERTIFY CCW +1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat +0 BFC INVERTNEXT +1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat +1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat +1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat +1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat +""" + +PLAIN_LDR = """0 Two bricks +0 Name: two.ldr +1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat +1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat +1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat +0 STEP +1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat +1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat +""" + +MPD = """0 FILE main.ldr +0 MPD main +0 Name: main.ldr +0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200 +1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr +1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr +1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat +3 24 0 0 0 10 0 0 0 10 0 +0 NOFILE +0 FILE sub.ldr +0 a sub-model: two parts and a nested sub-model +1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat +1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat +1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr +0 NOFILE +0 FILE inner.ldr +1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat +0 FILE Embedded Part.dat +0 !LDRAW_ORG Unofficial_Part +0 BFC CERTIFY CCW +1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat +0 BFC NOCLIP +3 24 0 -5 0 5 -5 0 0 -5 5 +0 BFC CLIP +4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5 +""" + +BAD_REFS = """0 cycles and bad lines are survived +1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat +1 16 0 0 0 1 0 0 0 1 +3 16 0 0 0 1 x 0 0 0 1 +4 16 0 0 0 1 0 0 1 1 0 0 1 0 +""" +LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n" + +LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI, + "parts/testbrick.dat": BRICK, "loop.dat": LOOP} + + +def hand_cases(colours): + cases = [] + + def add(name, text, files, opts=None): + ref = Ref(text, files, colours).run() + c = {"name": name, "data": text, "files": files, "want": ref.summary()} + if opts: + c["opts"] = opts + cases.append(c) + + add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"}) + add("two.ldr", PLAIN_LDR, dict(LIB)) + add("model.mpd", MPD, {"parts/box.dat": BOX}) + add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP}) + add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB)) + return cases + + +# ---------------------------------------------------------------------------------------------------- real parts +def closure(z, names, text_of): + """the library files a set of references needs: { library path -> text }""" + have = {} + index = {} + for n in z.namelist(): + if n.startswith("ldraw/") and n.lower().endswith(".dat"): + index[n[6:].lower()] = n + todo = list(names) + while todo: + n = norm(todo.pop()) + for p in Ref.PREFIXES: + key = p + n + if key in index: + if key not in have: + t = z.read(index[key]).decode("utf-8", "replace") + have[key] = t + for line in t.splitlines(): + parts = line.split(None, 14) + if len(parts) == 15 and parts[0] == "1": + todo.append(parts[14].strip()) + break + return have + + +def leocad_obj(leocad, libzip, path, tmp): + out = os.path.join(tmp, "leocad.obj") + env = dict(os.environ, QT_QPA_PLATFORM="offscreen") + subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True) + vs, area = [], 0.0 + lo, hi = [1e30] * 3, [-1e30] * 3 + with open(out) as f: + for line in f: + p = line.split() + if not p: + continue + if p[0] == "v": + v = [float(x) for x in p[1:4]] + vs.append(v) + lo = [min(a, b) for a, b in zip(lo, v)] + hi = [max(a, b) for a, b in zip(hi, v)] + elif p[0] == "f": + idx = [int(x.split("/")[0]) - 1 for x in p[1:]] + for k in range(1, len(idx) - 1): + area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]) + return {"min": lo, "max": hi, "area": area} + + +def generate(ctx): + import tempfile + tmp = tempfile.mkdtemp(prefix="formats-ldraw-") + leocad = nix_out("nixpkgs#leocad") + libzip = library_zip(leocad) + z = zipfile.ZipFile(libzip) + config = z.read("ldraw/LDConfig.ldr").decode("utf-8") + colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()} + ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]}) + + cases = hand_cases(colours) + # real parts and the library's sample models, with LeoCAD's export + reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"), + ("pyramid.ldr", "ldraw/models/pyramid.ldr")] + for name, member in reals: + if member: + text = z.read(member).decode("utf-8", "replace") + else: + text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name + files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None) + ref = Ref(text, files, colours).run() + c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()} + p = os.path.join(tmp, "model.ldr") + with open(p, "w") as f: + f.write(text) + try: + c["leocad"] = leocad_obj(leocad, libzip, p, tmp) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError): + pass + cases.append(c) + ctx.emit("ldraw_cases", cases) From c3711a7ab1f766bf33d7f7947124f2f670a634e8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:29:54 -0500 Subject: [PATCH 23/54] ws-3d3: model/gltf: KHR_draco_mesh_compression through codecs/model/Draco Draco primitives decode on load (attributes as their accessors declare them, u32 indices), written back uncompressed without the extension; meshopt stays UNSUPPORTED. Tests: transcoded Khronos samples (two quantizations), Draco's and assimp's Draco glTF files, each Draco primitive byte for byte against libdraco, against the uncompressed sources, round trips. Draco bench line; scene.md section. --- docs/FORMATS.md | 2 +- docs/guide/scene.md | 21 +++- src/Formats/Registry.luau | 4 +- src/Formats/model/gltf/Read.luau | 94 +++++++++++++++++- src/Formats/model/gltf/init.luau | 11 ++- tests/model/gltf.luau | 4 +- tests/model/gltf_draco.luau | 164 +++++++++++++++++++++++++++++++ tools/bench.luau | 20 ++++ tools/fixtures/docs_draco.py | 17 ++++ tools/fixtures/gltf_draco.py | 132 +++++++++++++++++++++++++ 10 files changed, 455 insertions(+), 14 deletions(-) create mode 100644 tests/model/gltf_draco.luau create mode 100644 tools/fixtures/docs_draco.py create mode 100644 tools/fixtures/gltf_draco.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 05b81c3..575f9f7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -37,7 +37,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | -| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..5fdcd5f 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -218,6 +218,25 @@ assert(cube.materials[1].baseColor[1] == 0.8) -- from Kd 0.8 0.1 0.1 A missing **image** is not an error: the texture keeps its `uri` and no `data`. +### Compressed glTF (Draco) + +Primitives compressed with `KHR_draco_mesh_compression` decode on load (through `codecs/model/Draco`, a port of Google's +Draco decoder: Edgebreaker and sequential connectivity, every prediction scheme, quantized attributes, bit-exact with +libdraco). The attributes come out as their accessors declare them, and the indices as `u32`. Saving writes the +geometry back uncompressed, without the extension. `EXT_meshopt_compression` is not supported. + +```luau +local scene = assert(F.load(dracoGlbBytes)) -- Box.glb through draco_transcoder +local prim = scene.meshes[1].primitives[1] +assert(prim.indices.count == 36 and prim.attributes.POSITION.type == "f32") +local plain = assert(F.save(scene, nil, { format = "glb" })) +assert(not string.find(buffer.tostring(plain), "KHR_draco", 1, true)) +``` + +Raw `.drc` files (and Draco data inside other formats) go through the codec itself: +`require(Formats.codecs.model.Draco).decode(bytes)` returns `{ kind, numPoints, numFaces, indices, attributes }` with +each attribute's values per point (`name`, `uniqueId`, `components`, `type`, `normalized`, `data`). + ## Editing: `F.ops.mesh` Every function accepts any accessor type and writes `f32` attributes and `u32` indices. Bad arguments return @@ -382,7 +401,7 @@ assert(F.load(vox).voxels[1].size[1] == 4) | Format | Read | Write | Notes | |---|---|---|---| -| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`; no Draco / meshopt | +| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`, Draco (read); no meshopt | | OBJ + MTL | yes | yes | polygons, vertex colours, Phong + PBR MTL | | STL | yes | yes | ASCII / binary, colour conventions; a triangle soup | | PLY | yes | yes | ASCII / binary, point clouds, custom `_` attributes | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..78eec79 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -404,8 +404,8 @@ local list: { Entry } = { path = "model/gltf", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" }, - caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, load = function() return require("@formats/model/gltf") end, diff --git a/src/Formats/model/gltf/Read.luau b/src/Formats/model/gltf/Read.luau index 459a67f..0cba6eb 100644 --- a/src/Formats/model/gltf/Read.luau +++ b/src/Formats/model/gltf/Read.luau @@ -9,6 +9,7 @@ local Err = require("@formats/core/Err") local Types = require("@formats/Types") local Base64 = require("@formats/core/Base64") local Pack = require("@formats/model/gltf/Pack") +local Draco = require("@formats/codecs/model/Draco") local Read = {} @@ -50,6 +51,7 @@ local KNOWN = { EXT_texture_avif = true, KHR_node_visibility = true, KHR_xmp_json_ld = true, + KHR_draco_mesh_compression = true, } Read.KNOWN = KNOWN @@ -100,6 +102,57 @@ local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any return { gltf = { extras = extras, extensions = ext } } end +-- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value +-- by value: normalized integers <-> floats, ints widened or narrowed) +local DRACO_HANDLED = { KHR_draco_mesh_compression = true } +local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 } +local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" } +local DRACO_WRITE: { [string]: (buffer, number, number) -> () } = { i8 = buffer.writei8, u8 = buffer.writeu8, i16 = buffer.writei16, u16 = buffer.writeu16, i32 = buffer.writei32, u32 = buffer.writeu32, f32 = buffer.writef32 } +local NORM_MAX: { [string]: number } = { u8 = 255, i8 = 127, u16 = 65535, i16 = 32767, u32 = 4294967295, i32 = 2147483647 } +local function dracoAccessor(da: Draco.Attribute, acc: Types.Accessor, n: number): Types.Accessor? + if da.components ~= acc.components or not DRACO_SIZE[da.type] then + return nil + end + local out = Types.Scene.accessor(nil, acc.type, acc.components, n) + out.name = acc.name + if DRACO_SAME[acc.type] == da.type then + out.data = da.data + return out + end + local reader = Types.Scene.reader({ data = da.data, type = da.type :: any, components = da.components, count = n }) + local size = Types.COMPONENT_SIZE[acc.type] + local norm = string.match(acc.type, "^[us]norm") ~= nil + local base: string = DRACO_SAME[acc.type] or acc.type + local wr = DRACO_WRITE[base] + local dmax = NORM_MAX[base] or 1 + if not reader or not wr or not size then + return nil + end + local get = reader :: (number, number) -> number + local w = wr :: (buffer, number, number) -> () + local stride = size * acc.components + local function put(v: number, c: number, x: number) + if base ~= "f32" then + if norm then + x = math.clamp(x, if base == "u8" or base == "u16" then 0 else -1, 1) * dmax + end + x = math.floor(x + 0.5) + end + w(out.data, v * stride + c * size, x) + end + local srcMax = if da.normalized then NORM_MAX[da.type] else nil + for v = 0, n - 1 do + for c = 0, da.components - 1 do + local x = get(v, c) + if srcMax then + x = math.max(x / srcMax, -1) + end + put(v, c, x) + end + end + return out +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 @@ -422,13 +475,39 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc 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)") + local pext = if type(p.extensions) == "table" then p.extensions else nil + if pext and pext.EXT_meshopt_compression then + return nil, Err.new(Err.UNSUPPORTED, "meshopt compressed primitives (EXT_meshopt_compression)") + end + -- KHR_draco_mesh_compression: the attributes it lists and the indices come from the Draco data + local dext = pext and pext.KHR_draco_mesh_compression + local draco: Draco.Geometry? = nil + local dmap: { [string]: number } = {} + if dext ~= nil then + local view = type(dext) == "table" and int(dext.bufferView) and views[dext.bufferView + 1] + if not view then + return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: draco: bad bufferView", i - 1, k - 1)) + end + local g, derr = Draco.decode(view.buf, view.offset, view.length, { maxPoints = maxBytes // 4, maxFaces = maxBytes // 12 }) + if not g then + local e = derr :: Err.Err + return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - 1, e.message)) + end + draco = g + for name, id in (if type(dext.attributes) == "table" then dext.attributes else {}) do + if type(name) == "string" and int(id) then + dmap[name] = id + end + end end local attrs: { [string]: Types.Accessor } = {} local count = -1 for name, ai in p.attributes do local a = accessor(ai) + if a and draco and dmap[name] then + local da = Draco.attribute(draco, dmap[name]) + a = if da then dracoAccessor(da, a, draco.numPoints) else nil + end if not a then return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name))) end @@ -443,7 +522,14 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc 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 + if draco then + if draco.kind == "mesh" then + prim.indices = Types.Scene.accessor(draco.indices, "u32", 1, draco.numFaces * 3) + prim.mode = "triangles" + else + prim.mode = "points" + end + elseif 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") @@ -472,7 +558,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc end prim.targets = targets end - prim.extras = keep(p, nil) + prim.extras = keep(p, DRACO_HANDLED) table.insert(mesh.primitives, prim) end table.insert(scene.meshes, mesh) diff --git a/src/Formats/model/gltf/init.luau b/src/Formats/model/gltf/init.luau index 8af711c..f64bd11 100644 --- a/src/Formats/model/gltf/init.luau +++ b/src/Formats/model/gltf/init.luau @@ -12,8 +12,11 @@ -- 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 .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). +-- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the +-- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back +-- uncompressed (the extension is dropped). +-- Not supported: 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") @@ -31,8 +34,8 @@ local Gltf = { category = "model", extensions = { "gltf", "glb" }, mime = { "model/gltf+json", "model/gltf-binary" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" }, - caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" }, + caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true }, } -- ------------------------------------------------------------------------------------------------ types diff --git a/tests/model/gltf.luau b/tests/model/gltf.luau index b737320..1f6d070 100644 --- a/tests/model/gltf.luau +++ b/tests/model/gltf.luau @@ -313,8 +313,8 @@ do t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e)) local _, e2 = decode('{"asset": {"version": "1.0"}}') t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2)) - local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["KHR_draco_mesh_compression"]}') - t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3)) + local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["EXT_meshopt_compression"]}') + t:check(e3 and e3.code == Err.UNSUPPORTED, "meshopt: " .. tostring(e3)) local c = byName["Box/glTF"] local _, e4 = decode(c.data) t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4)) diff --git a/tests/model/gltf_draco.luau b/tests/model/gltf_draco.luau new file mode 100644 index 0000000..82057dd --- /dev/null +++ b/tests/model/gltf_draco.luau @@ -0,0 +1,164 @@ +-- model/gltf KHR_draco_mesh_compression tests: the Khronos samples compressed by draco_transcoder (two quantizations), +-- Draco's and assimp's Draco glTF files. Every Draco primitive against libdraco's decode of its buffer view (points, +-- faces, index and attribute CRCs); the transcoded files against their uncompressed sources (meshes, primitives, +-- nodes, materials, skins, animations, triangles, world bounds within the quantization step); the scene saved back +-- (uncompressed, without the extension) and reloaded; the fuzz no-throw pass. Fixtures: tools/fixtures/gltf_draco.py. +local T = require("@tests/T") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Cases = require("@tests/gen/gltf_draco") + +local t = T.suite("gltf_draco") + +local DT = { [1] = "i8", [2] = "u8", [3] = "i16", [4] = "u16", [5] = "i32", [6] = "u32", [9] = "f32" } +local SAME = { i8 = "i8", snorm8 = "i8", u8 = "u8", unorm8 = "u8", i16 = "i16", snorm16 = "i16", u16 = "u16", unorm16 = "u16", i32 = "i32", u32 = "u32", f32 = "f32" } + +local function decode(data: string, files: any): (any, any) + return Gltf.decode(Bytes.reader(buffer.fromstring(data)), { files = files }) +end + +local function triangles(scene: any): number + local n = 0 + for _, m in scene.meshes do + for _, p in m.primitives do + if p.mode == "triangles" then + n += if p.indices then p.indices.count // 3 else p.attributes.POSITION.count // 3 + end + end + end + return n +end + +local checked = { prims = 0, attrs = 0, converted = 0, originals = 0, roundTrips = 0 } +local samples = {} +for _, c in Cases do + local scene, err = decode(c.data, c.files) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if scene then + for _, ref in c.prims do + local label = string.format("%s: mesh %d primitive %d", c.name, ref.mesh, ref.prim) + local prim = scene.meshes[ref.mesh] and scene.meshes[ref.mesh].primitives[ref.prim] + t:check(prim, label .. ": present") + if prim then + t:eq(prim.attributes.POSITION.count, ref.points, label .. ": points") + if ref.faces then + t:eq(prim.indices.count, ref.faces * 3, label .. ": indices") + t:eq(Crc32.of(prim.indices.data), ref.indices, label .. ": index CRC") + end + for name, a in ref.attrs do + local acc = prim.attributes[name] + t:check(acc, label .. ": " .. name) + if acc then + if SAME[acc.type] == DT[a.dataType] then + t:eq(Crc32.of(acc.data), a.crc, label .. ": " .. name .. " values") + checked.attrs += 1 + else + checked.converted += 1 + end + end + end + checked.prims += 1 + end + end + -- against the uncompressed source + local o = c.original + if o then + local orig, oerr = decode(o.data, o.files) + t:check(orig, c.name .. ": original: " .. tostring(oerr)) + if orig then + t:eq(#scene.meshes, #orig.meshes, c.name .. ": meshes") + for i, m in orig.meshes do + t:eq(#scene.meshes[i].primitives, #m.primitives, c.name .. ": mesh " .. i .. " primitives") + end + t:eq(#scene.nodes, #orig.nodes, c.name .. ": nodes") + -- draco_transcoder adds a default material to files without one + t:check(#scene.materials == #orig.materials or (#orig.materials == 0 and #scene.materials == 1), c.name .. ": materials") + t:eq(#scene.skins, #orig.skins, c.name .. ": skins") + t:eq(#scene.animations, #orig.animations, c.name .. ": animations") + t:eq(triangles(scene), triangles(orig), c.name .. ": triangles") + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local olo, ohi = MeshOps.bounds(MeshOps.merge(orig)) + if lo and olo then + -- the quantization step relative to the scene: 11-bit positions by default, 16-bit for "fine" + local rel = if string.find(c.name, "fine", 1, true) then 1e-4 else 5e-3 + local ok = true + for k = 1, 3 do + local eps = math.max(ohi[k] - olo[k], 1e-6) * rel + if math.abs(lo[k] - olo[k]) > eps or math.abs(hi[k] - ohi[k]) > eps then + ok = false + end + end + t:check(ok, c.name .. ": world bounds within the quantization step") + end + checked.originals += 1 + end + end + -- saved back without the extension + local glb = Gltf.encode(scene, { binary = true }) + t:check(glb, c.name .. ": encode") + if glb then + t:check(not string.find(buffer.tostring(glb), "KHR_draco_mesh_compression", 1, true), c.name .. ": no Draco extension written") + local again = Gltf.decode(Bytes.reader(glb)) + t:check(again and triangles(again) == triangles(scene), c.name .. ": round trip") + checked.roundTrips += 1 + end + if #c.data < 6000 and next(c.files) == nil then + table.insert(samples, c.data) + end + end +end +t:note("%d Draco primitives like libdraco (%d attributes byte for byte, %d converted to their accessor type), %d against the uncompressed sources, %d round trips", checked.prims, checked.attrs, checked.converted, checked.originals, checked.roundTrips) + +-- an accessor type other than the Draco attribute's: u8 normalized colours declared as f32 +do + local Draco = require("@formats/codecs/model/Draco") + local Base64 = require("@formats/core/Base64") + local DracoCases = require("@tests/gen/draco_cases") + local drc + for _, dc in DracoCases do + if dc.name == "enc/test_generic.ply.cl7" then + drc = dc.data + end + end + local g = drc and Draco.decode(drc) + t:check(g, "colour .drc fixture") + if g then + local pos, col + for _, a in g.attributes do + if a.name == "POSITION" then + pos = a + elseif a.name == "COLOR" then + col = a + end + end + local n = g.numPoints + local doc = string.format( + '{"asset":{"version":"2.0"},"extensionsUsed":["KHR_draco_mesh_compression"],"extensionsRequired":["KHR_draco_mesh_compression"],' + .. '"buffers":[{"byteLength":%d,"uri":"data:application/octet-stream;base64,%s"}],"bufferViews":[{"buffer":0,"byteLength":%d}],' + .. '"accessors":[{"componentType":5126,"count":%d,"type":"VEC3"},{"componentType":5126,"count":%d,"type":"VEC%d"},{"componentType":5125,"count":%d,"type":"SCALAR"}],' + .. '"meshes":[{"primitives":[{"attributes":{"POSITION":0,"COLOR_0":1},"indices":2,"extensions":{"KHR_draco_mesh_compression":{"bufferView":0,"attributes":{"POSITION":%d,"COLOR_0":%d}}}}]}],' + .. '"nodes":[{"mesh":0}],"scenes":[{"nodes":[0]}]}', + #drc, Base64.encode(buffer.fromstring(drc)), #drc, n, n, col.components, g.numFaces * 3, pos.uniqueId, col.uniqueId) + local scene, err = decode(doc, {}) + t:check(scene, "converted accessor: " .. tostring(err)) + if scene then + local acc = scene.meshes[1].primitives[1].attributes.COLOR_0 + t:eq(acc.type, "f32", "colour accessor type") + local ok = true + for i = 0, n * col.components - 1 do + local want = buffer.readu8(col.data, i) / 255 + if math.abs(buffer.readf32(acc.data, i * 4) - want) > 1e-6 then + ok = false + end + end + t:check(ok, "u8 normalized colours -> f32 / 255") + end + end +end + +t:fuzz("decode", function(b: buffer) + return Gltf.decode(Bytes.reader(b)) +end, samples, { mutations = 6, garbage = 50 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..74181ef 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,23 @@ do jitTune(false) end end +do + -- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV + -- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second. + local Draco = require("@formats/codecs/model/Draco") + local DC = require("@tests/gen/draco_cases") + for _, c in DC do + if c.name == "enc/bunny_norm.obj.cl7" or c.name == "enc/uvsphere.obj.cl10" or c.name == "enc/uvsphere.obj.cl0" then + local data = buffer.fromstring(c.data) + local g = assert(Draco.decode(data)) + local n = g.numFaces * 12 + for _, a in g.attributes do + n += buffer.len(a.data) + end + local dt = bench("draco " .. string.sub(c.name, 5), 3, n, function() + Draco.decode(data) + end) + print(string.format("%-8s %-30s %8.0f triangles/s", runtime, " (" .. g.numFaces .. " faces)", g.numFaces / dt)) + end + end +end diff --git a/tools/fixtures/docs_draco.py b/tools/fixtures/docs_draco.py new file mode 100644 index 0000000..a8cf67d --- /dev/null +++ b/tools/fixtures/docs_draco.py @@ -0,0 +1,17 @@ +# Docs inputs for the Draco section of docs/guide/scene.md (tools/fixtures.py, tools/docs_check.py): the Khronos Box +# sample (tests/fixtures/gltf) compressed with KHR_draco_mesh_compression by draco_transcoder 1.5.7 (nix). +# tests/gen/docs_draco.luau { files = { [name] = bytes }, vars = { dracoGlbBytes = "Box_draco.glb" } } +import importlib.util, os, subprocess, tempfile + +INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf/Box"] + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + dc = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dc) + draco = subprocess.run(["nix", "build", "nixpkgs#draco", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip().split("\n")[-1] + out = os.path.join(tempfile.mkdtemp(prefix="formats-docs-draco-"), "Box_draco.glb") + subprocess.run([os.path.join(draco, "bin", "draco_transcoder"), "-i", os.path.join(ctx.root, "tests", "fixtures", "gltf", "Box", "glTF-Binary", "Box.glb"), "-o", out], + capture_output=True, check=True) + dc.emit_inputs(ctx, {"Box_draco.glb": open(out, "rb").read()}, {"dracoGlbBytes": "Box_draco.glb"}) diff --git a/tools/fixtures/gltf_draco.py b/tools/fixtures/gltf_draco.py new file mode 100644 index 0000000..2cc2b7c --- /dev/null +++ b/tools/fixtures/gltf_draco.py @@ -0,0 +1,132 @@ +# glTF + Draco fixtures (tools/fixtures.py): KHR_draco_mesh_compression files. The Khronos samples of +# tests/fixtures/gltf compressed by draco_transcoder 1.5.7 (nix) at its default and at a finer quantization, Draco's +# own glTF test files (Box_Draco.glb, BoxMetaDraco) and assimp's 2CylinderEngine (robot.glb: 12 MB, left out), read from the +# nixpkgs sources and never committed. Reference values: every Draco primitive's buffer view decoded by libdraco +# (tools/fixtures/_draco_dump.cc, compiled against nixpkgs#draco): points, faces, the index and per-attribute CRCs. +# tests/gen/gltf_draco.luau { { name, data, files = { uri -> bytes }, original? = { data, files } (the uncompressed +# source), prims = { { mesh, prim, points, faces, indices, attrs = { [name] = { uniqueId, +# dataType, crc } } } } } } +import json, os, struct, subprocess, tempfile, zlib + +INPUTS = ["tests/fixtures/gltf", "tools/fixtures/_draco_dump.cc"] + + +def store_path(attr): + out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def load(path): + # -> (doc, bin, files): the JSON, the GLB binary chunk, the sibling files a .gltf refers to + raw = open(path, "rb").read() + files, binchunk = {}, None + if raw[:4] == b"glTF": + off = 12 + doc = None + while off + 8 <= len(raw): + n, kind = struct.unpack_from(" 2 else "")) + elif parts[0] == "ATTR": + by_id[int(parts[5])] = {"dataType": int(parts[2]), "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))} + for name, uid in ext.get("attributes", {}).items(): + if uid in by_id: + a = dict(by_id[uid]) + a["uniqueId"] = uid + entry["attrs"][name] = a + prims.append(entry) + return prims + + +def generate(ctx): + draco = store_path("draco") + dsrc = store_path("draco.src") + asrc = store_path("assimp.src") + tmp = tempfile.mkdtemp(prefix="formats-gltfdraco-") + dump = os.path.join(tmp, "dump") + ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"), + "-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump]) + transcoder = os.path.join(draco, "bin", "draco_transcoder") + sources = [] # (name, path, original path?) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model in sorted(os.listdir(gl)): + d0 = os.path.join(gl, model) + for variant in sorted(os.listdir(d0)): + d = os.path.join(d0, variant) + if not os.path.isdir(d) or "Quantized" in variant: + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if not mains: + continue + src = os.path.join(d, mains[0]) + for q, args in (("default", []), ("fine", ["-qp", "16", "-qt", "14", "-qn", "12", "-qc", "10", "-qw", "12", "-qtg", "10"])): + out = os.path.join(tmp, "%s_%s.glb" % (model, q)) + r = subprocess.run([transcoder, "-i", src, "-o", out] + args, capture_output=True) + if r.returncode == 0 and os.path.exists(out): + sources.append(("transcoded/%s/%s" % (model, q), out, src)) + break + for name, rel in (("draco/Box_Draco.glb", os.path.join(dsrc, "testdata", "Box", "glTF_Binary", "Box_Draco.glb")), + ("draco/BoxMetaDraco.gltf", os.path.join(dsrc, "testdata", "BoxMetaDraco", "glTF", "BoxMetaDraco.gltf")), + ("assimp/2CylinderEngine.gltf", os.path.join(asrc, "test", "models", "glTF2", "draco", "2CylinderEngine.gltf"))): + if os.path.exists(rel): + sources.append((name, rel, None)) + cases = [] + for name, path, orig in sources: + doc, binchunk, files = load(path) + prims = references(doc, binchunk, files, dump, tmp) + if not prims: + continue + case = {"name": name, "data": open(path, "rb").read(), "files": files, "prims": prims} + if orig: + _, _, ofiles = load(orig) + case["original"] = {"data": open(orig, "rb").read(), "files": ofiles} + cases.append(case) + ctx.emit("gltf_draco", cases) From ef2cd93c880f665f5040c54268ad7308f84b06ff Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:30:30 -0500 Subject: [PATCH 24/54] ws-tex: image/ktx (KTX1 + KTX2 read: BCn / ETC2 / EAC / uncompressed, mips, cube, arrays, 3D, Zstd / ZLIB; Basis UNSUPPORTED; KTX2 write) KTX2 writer: rgba8 (UNORM / SRGB), rgba16, rgba16f / rgba32f with a full DFD, mips, cube / array frames, ZLIB. Tested against ktx create / deflate / extract, toktx, nvcompress -ktx and hand-written KTX1 (big-endian, packed, row padding, T=u); our files pass ktx validate. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/image/ktx/init.luau | 672 +++++++++++++++++++++++++++++++ tests/image/ktx.luau | 167 ++++++++ tools/fixtures/_tex_encode.luau | 20 + tools/fixtures/_tex_reference.py | 3 + tools/fixtures/ktx.py | 279 +++++++++++++ 7 files changed, 1154 insertions(+) create mode 100644 src/Formats/image/ktx/init.luau create mode 100644 tests/image/ktx.luau create mode 100644 tools/fixtures/ktx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dfcdb88..46d0547 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | +| image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` | | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 988b668..718bbaa 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/image/jpeg") end, }, + { + name = "ktx", + category = "image", + path = "image/ktx", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, + load = function() + return require("@formats/image/ktx") + end, + }, { name = "png", category = "image", diff --git a/src/Formats/image/ktx/init.luau b/src/Formats/image/ktx/init.luau new file mode 100644 index 0000000..2fd15bb --- /dev/null +++ b/src/Formats/image/ktx/init.luau @@ -0,0 +1,672 @@ +--!strict +-- image/ktx: Khronos texture containers (KTX 1.1 and KTX 2.0 specifications; new code). Decode: KTX1 (OpenGL +-- glInternalFormat / glFormat + glType: the S3TC / RGTC / BPTC / ETC1 / ETC2 / EAC compressed formats and the +-- uncompressed ones with 4-byte row alignment; big-endian files) and KTX2 (VkFormat: BCn, ETC2 / EAC and every +-- uncompressed format codecs/image/Texel knows; Zstandard (codecs/compress/Zstd) and ZLIB supercompression); mip +-- levels, cube maps, arrays and 3D textures, the key / value data (meta.keyValue) and KTXorientation (T=u rows are +-- flipped). Like image/dds: the first surface is the image, img.frames lists every face / layer / slice when there is +-- more than one (meta.layout), opts.mips decodes the smaller levels into img.meta.mipmaps; rgba8 unless opts.native. +-- Encode: KTX2, uncompressed: rgba8 (R8G8B8A8_UNORM, or _SRGB when meta.colorSpace is "srgb"), rgba16 +-- (R16G16B16A16_UNORM), rgbaf32 (R32G32B32A32_SFLOAT or R16G16B16A16_SFLOAT), with a full DFD, optional mip chain, +-- frames as layers or cube faces, optional ZLIB supercompression. Not supported: Basis Universal (BasisLZ / ETC1S and +-- UASTC: UNSUPPORTED), ASTC and PVRTC, writing KTX1 or Zstandard. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Zstd = require("@formats/codecs/compress/Zstd") +local Texel = require("@formats/codecs/image/Texel") +local Texture = require("@formats/codecs/image/Texture") + +-- ------------------------------------------------------------------------------------------------ contract +local Ktx = { + name = "ktx", + category = "image", + extensions = { "ktx2", "ktx" }, + mime = { "image/ktx2", "image/ktx" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/image/Texel", "codecs/image/Texture" }, + caps = { decode = true, encode = true, alpha = true, float = true, mipmaps = true, cubemap = true, compressed = { "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- keep rgbaf32 / rgba16 for float / 16-bit / BC6H / EAC sources (default false: rgba8) + mips: boolean?, -- decode the smaller mip levels of the first surface into img.meta.mipmaps (default false) + surfaces: boolean?, -- decode every face / layer / slice into img.frames (default true) + maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) +} +export type EncodeOptions = { + format: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) + srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") + mips: boolean?, -- a full mip chain (box filter; default false) + cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") + zlib: number?, -- ZLIB-supercompress every level at this level 1..9 (default none) + keyValue: { [string]: string }?, -- extra key / value pairs (KTXwriter is always written) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ID1 = "\171KTX 11\187\r\n\26\n" +local ID2 = "\171KTX 20\187\r\n\26\n" + +-- VkFormat -> texture format name +local VK: { [number]: string } = { + [2] = "a4b4g4r4", [3] = "a4r4g4b4", [4] = "b5g6r5", [5] = "r5g6b5", [6] = "a1b5g5r5", [7] = "a1r5g5b5", [8] = "b5g5r5a1", + [9] = "r8", [10] = "r8s", [13] = "r8ui", [14] = "r8i", [15] = "r8", + [16] = "rg8", [17] = "rg8s", [20] = "rg8ui", [21] = "rg8i", [22] = "rg8", + [23] = "rgb8", [24] = "rgb8s", [27] = "rgb8ui", [28] = "rgb8i", [29] = "rgb8", + [30] = "bgr8", [36] = "bgr8", + [37] = "rgba8", [38] = "rgba8s", [41] = "rgba8ui", [42] = "rgba8i", [43] = "rgba8", + [44] = "bgra8", [50] = "bgra8", + [58] = "bgr10a2", [64] = "rgb10a2", + [70] = "r16", [71] = "r16s", [74] = "r16ui", [75] = "r16i", [76] = "r16f", + [77] = "rg16", [78] = "rg16s", [81] = "rg16ui", [82] = "rg16i", [83] = "rg16f", + [84] = "rgb16", [85] = "rgb16s", [88] = "rgb16ui", [89] = "rgb16i", [90] = "rgb16f", + [91] = "rgba16", [92] = "rgba16s", [95] = "rgba16ui", [96] = "rgba16i", [97] = "rgba16f", + [98] = "r32ui", [99] = "r32i", [100] = "r32f", [101] = "rg32ui", [102] = "rg32i", [103] = "rg32f", + [104] = "rgb32ui", [105] = "rgb32i", [106] = "rgb32f", [107] = "rgba32ui", [108] = "rgba32i", [109] = "rgba32f", + [122] = "r11g11b10f", [123] = "rgb9e5", [124] = "r16", [126] = "r32f", + [131] = "bc1", [132] = "bc1", [133] = "bc1", [134] = "bc1", [135] = "bc2", [136] = "bc2", [137] = "bc3", [138] = "bc3", + [139] = "bc4", [140] = "bc4s", [141] = "bc5", [142] = "bc5s", [143] = "bc6h", [144] = "bc6hs", [145] = "bc7", [146] = "bc7", + [147] = "etc2_rgb", [148] = "etc2_rgb", [149] = "etc2_rgba1", [150] = "etc2_rgba1", [151] = "etc2_rgba", [152] = "etc2_rgba", + [153] = "eac_r11", [154] = "eac_r11s", [155] = "eac_rg11", [156] = "eac_rg11s", +} +local VK_SRGB = { [15] = true, [22] = true, [29] = true, [36] = true, [43] = true, [50] = true, [132] = true, [134] = true, [136] = true, [138] = true, [146] = true, [148] = true, [150] = true, [152] = true } +local VK_OPAQUE = { [131] = true, [132] = true } -- BC1 RGB: the 3-colour mode's index 3 is opaque black +-- OpenGL compressed internal formats +local GL_COMPRESSED: { [number]: string } = { + [0x83F0] = "bc1", [0x83F1] = "bc1", [0x83F2] = "bc2", [0x83F3] = "bc3", + [0x8C4C] = "bc1", [0x8C4D] = "bc1", [0x8C4E] = "bc2", [0x8C4F] = "bc3", + [0x8DBB] = "bc4", [0x8DBC] = "bc4s", [0x8DBD] = "bc5", [0x8DBE] = "bc5s", + [0x8E8C] = "bc7", [0x8E8D] = "bc7", [0x8E8E] = "bc6hs", [0x8E8F] = "bc6h", + [0x8D64] = "etc1", [0x9274] = "etc2_rgb", [0x9275] = "etc2_rgb", [0x9276] = "etc2_rgba1", [0x9277] = "etc2_rgba1", + [0x9278] = "etc2_rgba", [0x9279] = "etc2_rgba", [0x9270] = "eac_r11", [0x9271] = "eac_r11s", [0x9272] = "eac_rg11", [0x9273] = "eac_rg11s", +} +local GL_SRGB = { [0x8C4C] = true, [0x8C4D] = true, [0x8C4E] = true, [0x8C4F] = true, [0x8E8D] = true, [0x9275] = true, [0x9277] = true, [0x9279] = true, [0x8C41] = true, [0x8C43] = true } +local GL_OPAQUE = { [0x83F0] = true, [0x8C4C] = true } +-- glFormat -> channel order; glType -> bit size, Texel suffix +local GL_ORDER: { [number]: string } = { + [0x1903] = "r", [0x8227] = "rg", [0x1907] = "rgb", [0x1908] = "rgba", [0x80E0] = "bgr", [0x80E1] = "bgra", + [0x1909] = "l", [0x190A] = "la", [0x1906] = "a", + [0x8D94] = "r", [0x8228] = "rg", [0x8D98] = "rgb", [0x8D99] = "rgba", -- the _INTEGER formats +} +local GL_INTEGER = { [0x8D94] = true, [0x8228] = true, [0x8D98] = true, [0x8D99] = true } +local GL_PACKED: { [number]: string } = { + [0x8363] = "b5g6r5", [0x8033] = "a4b4g4r4", [0x8034] = "a1b5g5r5", [0x8368] = "rgb10a2", [0x8C3B] = "r11g11b10f", [0x8C3E] = "rgb9e5", +} +local GL_TYPES: { [number]: { any } } = { + [0x1401] = { 8, "", "ui" }, [0x1400] = { 8, "s", "i" }, [0x1403] = { 16, "", "ui" }, [0x1402] = { 16, "s", "i" }, + [0x1405] = { 32, "ui", "ui" }, [0x1404] = { 32, "i", "i" }, [0x140B] = { 16, "f", "f" }, [0x1406] = { 32, "f", "f" }, +} +local FACES = { "+x", "-x", "+y", "-y", "+z", "-z" } + +local readu32, readstring = buffer.readu32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Ktx.sniff(r: Bytes.Reader): number + return math.max(Sniff.magic(r, ID2), Sniff.magic(r, ID1)) +end + +-- ------------------------------------------------------------------------------------------------ decode +export type Info = { + version: number, -- 1 or 2 + width: number, + height: number, + depth: number, -- 1 for 2D + layers: number, + faces: number, + levels: number, + format: string?, -- the texture format name (nil when unsupported: see unsupported) + unsupported: string?, + srgb: boolean, + opaque: boolean, -- BC1 RGB + vkFormat: number?, + glInternalFormat: number?, + supercompression: number?, + keyValue: { [string]: string }, + bigEndian: boolean?, + typeSize: number, + dataOffset: number, -- KTX1: the first imageSize field (relative to the file) + levelIndex: { { offset: number, length: number, uncompressed: number } }?, -- KTX2 +} + +local function u64(b: buffer, o: number): number + return readu32(b, o) + readu32(b, o + 4) * 4294967296 +end + +-- key / value pairs from [p, stop): u32 length, key NUL value, padding to 4 +local function keyValues(b: buffer, p: number, stop: number, be: boolean): { [string]: string } + local kv: { [string]: string } = {} + while p + 4 <= stop do + local n = readu32(b, p) + if be then + n = bit32.byteswap(n) + end + p += 4 + if n > stop - p then + break + end + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + if z then + local v = string.sub(s, z + 1) + if string.sub(v, -1) == "\0" then + v = string.sub(v, 1, -2) + end + kv[string.sub(s, 1, z - 1)] = v + end + p += n + (3 - (n + 3) % 4) + end + return kv +end + +local function info1(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 64 then + return nil, Err.new(Err.TRUNCATED, "short KTX1 header", o) + end + local e = readu32(b, o + 12) + local be = e == 0x01020304 + if not be and e ~= 0x04030201 then + return nil, Err.new(Err.CORRUPT, "bad endianness field", o + 12) + end + local function f(i: number): number + local v = readu32(b, o + 16 + i * 4) + return if be then bit32.byteswap(v) else v + end + local glType, typeSize, glFormat, internal = f(0), f(1), f(2), f(3) + local w, h, d, arr, faces, levels, kvBytes = f(5), f(6), f(7), f(8), f(9), f(10), f(11) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or arr > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX1 header", o + 16) + end + if 64 + kvBytes > n then + return nil, Err.new(Err.TRUNCATED, "key / value data runs past the end", o + 64) + end + local info: Info = { + version = 1, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, arr), + faces = faces, + levels = math.max(1, levels), + srgb = GL_SRGB[internal] == true, + opaque = GL_OPAQUE[internal] == true, + glInternalFormat = internal, + keyValue = keyValues(b, o + 64, o + 64 + kvBytes, be), + bigEndian = be, + typeSize = typeSize, + dataOffset = 64 + kvBytes, + } + if glType == 0 then + info.format = GL_COMPRESSED[internal] + if not info.format then + info.unsupported = string.format("compressed glInternalFormat 0x%04X", internal) + end + else + local name = GL_PACKED[glType] + if not name then + local order = GL_ORDER[glFormat] + local int = GL_INTEGER[glFormat] == true + -- glType -> component bits, Texel suffix (normalized / integer) + local t = GL_TYPES[glType] + local size: number? = t and t[1] + local suffix: string = if t then (if int then t[3] else t[2]) else "" + if order and size then + name = order .. tostring(size) .. suffix + end + end + if name and Texel.FORMATS[name] then + info.format = name + else + info.unsupported = string.format("glFormat 0x%04X / glType 0x%04X", glFormat, glType) + end + end + return info, nil +end + +local function info2(r: Bytes.Reader): (Info?, Err.Err?) + local b, o, n = r.buf, r.base, r.limit - r.base + if n < 80 then + return nil, Err.new(Err.TRUNCATED, "short KTX2 header", o) + end + local vk, typeSize = readu32(b, o + 12), readu32(b, o + 16) + local w, h, d = readu32(b, o + 20), readu32(b, o + 24), readu32(b, o + 28) + local layers, faces, levels, scheme = readu32(b, o + 32), readu32(b, o + 36), readu32(b, o + 40), readu32(b, o + 44) + if w == 0 or w > 65536 or h > 65536 or d > 2048 or layers > 4096 or (faces ~= 1 and faces ~= 6) or levels > 32 then + return nil, Err.new(Err.CORRUPT, "bad KTX2 header", o + 20) + end + local nl = math.max(1, levels) + if 80 + nl * 24 > n then + return nil, Err.new(Err.TRUNCATED, "level index runs past the end", o + 80) + end + local dfdOff, dfdLen, kvOff, kvLen = readu32(b, o + 48), readu32(b, o + 52), readu32(b, o + 56), readu32(b, o + 60) + local info: Info = { + version = 2, + width = w, + height = math.max(1, h), + depth = math.max(1, d), + layers = math.max(1, layers), + faces = faces, + levels = nl, + srgb = VK_SRGB[vk] == true, + opaque = VK_OPAQUE[vk] == true, + vkFormat = vk, + supercompression = scheme, + keyValue = if kvLen > 0 and kvOff + kvLen <= n then keyValues(b, o + kvOff, o + kvOff + kvLen, false) else {}, + typeSize = typeSize, + dataOffset = 0, + levelIndex = {}, + } + for i = 0, nl - 1 do + local q = o + 80 + i * 24 + table.insert(info.levelIndex :: any, { offset = u64(b, q), length = u64(b, q + 8), uncompressed = u64(b, q + 16) }) + end + -- the colour model of the DFD tells Basis Universal apart + local model = -1 + if dfdLen >= 16 and dfdOff + dfdLen <= n then + model = buffer.readu8(b, o + dfdOff + 12) + if buffer.readu8(b, o + dfdOff + 14) == 2 then + info.srgb = true + end + end + if scheme == 1 or model == 163 then + info.unsupported = "Basis Universal ETC1S / BasisLZ" + elseif model == 166 then + info.unsupported = "Basis Universal UASTC" + elseif scheme > 3 then + info.unsupported = "supercompression scheme " .. scheme + elseif vk == 0 then + info.unsupported = "VK_FORMAT_UNDEFINED" + else + info.format = VK[vk] + if not info.format then + info.unsupported = "VkFormat " .. vk .. (if vk >= 157 and vk <= 184 or vk >= 1000066000 then " (ASTC)" else "") + end + end + return info, nil +end + +-- info(r) -> Info | nil, Err (the headers only) +function Ktx.info(r: Bytes.Reader): (Info?, Err.Err?) + local id = r:peek(12) + if id == ID2 then + return info2(r) + elseif id == ID1 then + return info1(r) + end + return nil, Err.new(Err.CORRUPT, "not a KTX file", r.base) +end + +-- reverses the bytes of every typeSize-wide element of a big-endian KTX1 image +local function swapped(b: buffer, p: number, n: number, size: number): buffer + local out = buffer.create(n) + buffer.copy(out, 0, b, p, n) + for i = 0, n - size, size do + if size == 2 then + buffer.writeu16(out, i, bit32.rshift(bit32.byteswap(buffer.readu16(out, i)), 16)) + else + buffer.writeu32(out, i, bit32.byteswap(buffer.readu32(out, i))) + end + end + return out +end + +-- flips the rows of a decoded surface (KTXorientation T=u) +local function flip(img: Types.Image) + local row = img.width * (Types.BPP[img.format] or 4) + local px = img.pixels + local tmp = buffer.create(row) + for y = 0, img.height // 2 - 1 do + local a, z = y * row, (img.height - 1 - y) * row + buffer.copy(tmp, 0, px, a, row) + buffer.copy(px, a, px, z, row) + buffer.copy(px, z, tmp, 0, row) + end +end + +function Ktx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, ierr = Ktx.info(r) + if not info then + return nil, ierr + end + local fmt = info.format + if not fmt then + return nil, Err.new(Err.UNSUPPORTED, info.unsupported or "format") + end + local native = opts and opts.native or false + local wantMips = opts and opts.mips or false + local wantAll = not (opts and opts.surfaces == false) + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + local b, base, limit = r.buf, r.base, r.limit + local bw, bh, bbytes = Texture.block(fmt) + local blockFmt = bw == 4 + local orient = info.keyValue.KTXorientation or "" + local up = string.find(orient, "T=u", 1, true) ~= nil or (info.version == 2 and string.sub(orient, 2, 2) == "u") + local list: { Texture.Surface } = {} + local pixels = 0 + local count = info.layers * info.faces + local p = base + info.dataOffset + local w, h, d = info.width, info.height, info.depth + for level = 0, info.levels - 1 do + local want = level == 0 or wantMips + -- the level's data: buf, offset, the image stride and row pitch + local lb, lp = b, 0 + local rowPitch: number? = nil + local imgSize = Texture.size(fmt, w, h) :: number + local stride = imgSize + if info.version == 1 then + if p + 4 > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "missing level 0", p) + end + break + end + local declared = readu32(b, p) + if info.bigEndian then + declared = bit32.byteswap(declared) + end + p += 4 + if not blockFmt then + local tight = (bbytes :: number) * w + rowPitch = tight + (3 - (tight + 3) % 4) + imgSize = (rowPitch :: number) * h + end + stride = imgSize + (3 - (imgSize + 3) % 4) -- cube padding + local total = stride * count * d + if declared < imgSize * (if info.faces == 6 and info.layers == 1 then 1 else count * d) and level == 0 then + return nil, Err.new(Err.CORRUPT, "imageSize too small for the format", p - 4) + end + if p + total > limit then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", p) + end + break + end + lp = p + p += total + p += 3 - (total + 3) % 4 + if info.bigEndian and info.typeSize > 1 and want then + lb, lp = swapped(b, lp, total, info.typeSize), 0 + end + else + local li = (info.levelIndex :: any)[level + 1] + local off, len = base + li.offset, li.length + if off + len > limit or li.offset < 80 then + if level == 0 then + return nil, Err.new(Err.TRUNCATED, "level 0 data runs past the end", off) + end + break + end + local expect = imgSize * count * d + if want then + local scheme = info.supercompression + if scheme == 2 or scheme == 3 then + if li.uncompressed < expect or li.uncompressed > 2 ^ 31 then + return nil, Err.new(Err.CORRUPT, "bad uncompressed level size", base + 80 + level * 24) + end + local out, zerr + if scheme == 2 then + out, zerr = Zstd.decompress(b, off, len, { maxBytes = li.uncompressed }) + else + out, zerr = Deflate.zlib(b, off, len, li.uncompressed) + end + if not out then + return nil, Err.wrap(zerr) + end + lb, lp = out, 0 + else + lb, lp = b, off + end + if lp + expect > buffer.len(lb) then + return nil, Err.new(Err.TRUNCATED, "level " .. level .. " is too small", off) + end + end + end + if want then + for layer = 0, count - 1 do + for slice = 0, d - 1 do + if level == 0 and not wantAll and (layer > 0 or slice > 0) then + continue + end + if level > 0 and (layer > 0 or slice > 0) then + continue + end + pixels += w * h + if pixels > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("over the %d pixel limit", maxPixels)) + end + local at = lp + (layer * d + slice) * stride + local px, pf + if rowPitch then + px, pf = Texel.decode(fmt, lb, at, w, h, native, rowPitch) + else + px, pf = Texture.decode(fmt, lb, at, w, h, native) + end + if not px then + return nil, Err.from(pf, at) + end + local im = Texture.image(px, pf, w, h) + if info.opaque then + for i = 0, w * h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + end + if up then + flip(im) + end + table.insert(list, { level = level, layer = layer, face = layer % info.faces, slice = slice, image = im }) + end + end + end + w, h, d = math.max(1, w // 2), math.max(1, h // 2), math.max(1, d // 2) + end + local layout = if info.depth > 1 then "volume" elseif info.faces == 6 then "cube" elseif info.layers > 1 then "array" else "2d" + local img = Texture.assemble(list, layout) + if not img then + return nil, Err.new(Err.TRUNCATED, "no image data") + end + if info.faces == 6 then + img.meta.faces = table.clone(FACES) + end + if info.srgb then + img.meta.colorSpace = "srgb" + elseif string.find(fmt, "f$") or fmt == "bc6h" or fmt == "bc6hs" or fmt == "rgb9e5" then + img.meta.colorSpace = "linear" + end + img.meta.keyValue = info.keyValue + img.meta.source = { + format = "ktx", + version = info.version, + pixelFormat = fmt, + vkFormat = info.vkFormat, + glInternalFormat = info.glInternalFormat, + supercompression = info.supercompression, + mips = info.levels, + layers = info.layers, + depth = info.depth, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- format -> VkFormat, bytes per texel, component bytes, kind +local OUT: { [string]: { number } } = { + rgba8 = { 37, 4, 1 }, + rgba16 = { 91, 8, 2 }, + rgba16f = { 97, 8, 2 }, + rgba32f = { 109, 16, 4 }, +} + +-- the DFD: one basic descriptor block with four samples (R G B A) +local function dfd(f: string, srgb: boolean): buffer + local spec = OUT[f] + local texel, comp = spec[2], spec[3] + local float = f == "rgba16f" or f == "rgba32f" + local w = Bytes.writer(92) + local blockSize = 24 + 16 * 4 + w:u32le(4 + blockSize) + w:u32le(0) -- vendor 0, descriptor type 0 + w:u32le(2 + blockSize * 65536) -- version 2, block size + w:u8(1) -- colour model RGBSDA + w:u8(1) -- primaries BT.709 + w:u8(if srgb then 2 else 1) -- transfer: sRGB / linear + w:u8(0) -- straight alpha + w:u32le(0) -- texel block 1 x 1 x 1 x 1 + w:u32le(texel) -- bytesPlane0 + w:u32le(0) + for c = 0, 3 do + local channel = if c == 3 then 15 else c + local qual = (if float then 0xC0 else 0) + (if srgb and c == 3 then 0x10 else 0) + w:u16le(c * comp * 8) + w:u8(comp * 8 - 1) + w:u8(channel + qual) + w:u32le(0) -- sample position + if float then + w:u32le(0xBF800000) + w:u32le(0x3F800000) + else + w:u32le(0) + w:u32le(if comp == 1 then 255 else 65535) + end + end + return w:finish() +end + +function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or type(img.width) ~= "number" or img.width < 1 or img.height < 1 then + return nil, Err.new(Err.ARG, "needs an Image") + end + local pf = img.format + if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then + return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") + end + local f: string = (opts and opts.format) or (if pf == "rgbaf32" then "rgba32f" else pf) + local spec = OUT[f] + if not spec then + return nil, Err.new(Err.ARG, "unknown format " .. tostring(f)) + end + local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f + if pf ~= needs then + return nil, Err.new(Err.ARG, string.format("format %s needs an %s Image", f, needs)) + end + local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb")) + local images: { Types.Image } = { img } + if img.frames and #img.frames > 1 then + images = {} + for i, fr in img.frames do + local fi = fr.image + if type(fi) ~= "table" or fi.width ~= img.width or fi.height ~= img.height or fi.format ~= pf then + return nil, Err.new(Err.ARG, "frame " .. i .. ": every surface needs the image's size and pixel format") + end + images[i] = fi + end + end + local cube = if opts and opts.cube ~= nil then opts.cube else (img.meta and img.meta.layout == "cube") + if cube and (#images % 6 ~= 0 or img.width ~= img.height) then + return nil, Err.new(Err.ARG, "a cube map needs 6 square faces per layer") + end + local faces = if cube then 6 else 1 + local layers = #images // faces + local levels = 1 + if opts and opts.mips then + local m = math.max(img.width, img.height) + while m > 1 do + m //= 2 + levels += 1 + end + end + local zl = opts and opts.zlib + if zl ~= nil and (type(zl) ~= "number" or zl < 1 or zl > 9) then + return nil, Err.new(Err.ARG, "zlib level must be 1..9") + end + -- level data: the images of every layer / face per level + local levelData: { buffer } = {} + local raw: { number } = {} + local cur = table.clone(images) + for lv = 1, levels do + local w = Bytes.writer() + for i, im in cur do + local data = if f == "rgba16f" then Texture.toHalf(im.pixels, im.width * im.height) else im.pixels + w:bytes(data, 0, im.width * im.height * spec[2]) + if lv < levels then + cur[i] = Texture.halve(im) + end + end + local lb = w:finish() + raw[lv] = buffer.len(lb) + if zl then + lb = Deflate.zlibCompress(lb, { level = zl }) :: buffer + end + levelData[lv] = lb + end + -- key / value data + local kvw = Bytes.writer() + local pairs_: { { string } } = { { "KTXwriter", "formats-luau" } } + if opts and opts.keyValue then + for k, v in opts.keyValue do + if k ~= "KTXwriter" then + table.insert(pairs_, { k, v }) + end + end + end + table.sort(pairs_, function(a: { string }, c: { string }): boolean + return a[1] < c[1] + end) + for _, kv in pairs_ do + local n = #kv[1] + 1 + #kv[2] + 1 + kvw:u32le(n) + kvw:string(kv[1]) + kvw:u8(0) + kvw:string(kv[2]) + kvw:u8(0) + kvw:fill(0, 3 - (n + 3) % 4) + end + local kvd = kvw:finish() + local d = dfd(f, srgb == true) + local dfdOff = 80 + levels * 24 + local kvOff = dfdOff + buffer.len(d) + local dataStart = kvOff + buffer.len(kvd) + local align = if zl then 1 else (if spec[2] % 4 == 0 then spec[2] else 4) + -- smallest level first + local offsets: { number } = {} + local p = dataStart + for lv = levels, 1, -1 do + p += (align - p % align) % align + offsets[lv] = p + p += buffer.len(levelData[lv]) + end + local out = Bytes.writer(p) + out:string(ID2) + out:u32le(if f == "rgba8" and srgb then 43 else spec[1]) + out:u32le(spec[3]) + out:u32le(img.width) + out:u32le(img.height) + out:u32le(0) + out:u32le(if layers > 1 then layers else 0) + out:u32le(faces) + out:u32le(levels) + out:u32le(if zl then 3 else 0) + out:u32le(dfdOff) + out:u32le(buffer.len(d)) + out:u32le(kvOff) + out:u32le(buffer.len(kvd)) + out:u64le(0) + out:u64le(0) + for lv = 1, levels do + out:u64le(offsets[lv]) + out:u64le(buffer.len(levelData[lv])) + out:u64le(raw[lv]) + end + out:bytes(d) + out:bytes(kvd) + for lv = levels, 1, -1 do + out:fill(0, offsets[lv] - out:tell()) + out:bytes(levelData[lv]) + end + return out:finish(), nil +end + +return Ktx diff --git a/tests/image/ktx.luau b/tests/image/ktx.luau new file mode 100644 index 0000000..1c24fbf --- /dev/null +++ b/tests/image/ktx.luau @@ -0,0 +1,167 @@ +-- image/ktx tests: KTX2 files from KTX-Software (`ktx create` from PNGs and raw data in uncompressed / packed / float / +-- BCn / ETC2 / EAC formats, mips, cube maps, arrays, 3D, Zstandard and ZLIB supercompression; Basis Universal is +-- UNSUPPORTED) and KTX1 files from toktx / nvcompress / hand-written ones (big-endian, packed types, row padding, +-- KTXorientation) against their sources or reference decodes; our KTX2 files through `ktx validate` / `ktx extract`; +-- round trips; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/ktx.py. +local T = require("@tests/T") +local Ktx = require("@formats/image/ktx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/ktx") + +local t = T.suite("ktx") + +t:eq(Ktx.name, "ktx", "name") +t:check(Ktx.caps.decode and Ktx.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Ktx.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +local function maxDiff(a: buffer, b: buffer, n: number): number + local worst = 0 + for i = 0, n * 4 - 1 do + worst = math.max(worst, math.abs(buffer.readu8(a, i) - buffer.readu8(b, i))) + end + return worst +end + +local nsurf = 0 +for _, c in Fx.cases do + if c.unsupported then + local img, e = dec(c.data) + t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")") + continue + end + local img, err = dec(c.data, { mips = true }) + t:check(img, c.name .. ": " .. tostring(err)) + if c.layout then + t:eq(img.meta.layout, c.layout, c.name .. ": layout") + end + if c.mips then + t:eq(img.meta.source.mips, c.mips, c.name .. ": mip count") + end + if c.srgb then + t:eq(img.meta.colorSpace, "srgb", c.name .. ": sRGB") + end + local native = nil + local frames = img.frames or { { image = img } } + for _, s in c.surfaces do + local label = string.format("%s: level %d layer %d slice %d", c.name, s.level, s.layer, s.slice) + local im + if s.level == 0 then + local f = frames[s.layer + s.slice + 1] + im = f and f.image + else + im = img.meta.mipmaps and img.meta.mipmaps[s.level] + end + t:check(im and im.width == s.w and im.height == s.h, label .. ": surface size") + if s.rgba then + local d = maxDiff(im.pixels, buffer.fromstring(s.rgba), s.w * s.h) + t:check(d <= s.tol, string.format("%s: %d off the reference", label, d)) + end + if s.floats and s.level == 0 and s.layer == 0 then + native = native or dec(c.data, { native = true }) + local f = buffer.fromstring(s.floats) + local worst = 0 + for i = 0, s.w * s.h * 4 - 1 do + local want = buffer.readf32(f, i * 4) + local got + if native.format == "rgbaf32" then + got = buffer.readf32(native.pixels, i * 4) + elseif native.format == "rgba16" then + got = buffer.readu16(native.pixels, i * 2) / 65535 + else + got = buffer.readu8(native.pixels, i) / 255 + end + if i % 4 ~= 3 or not string.find(c.name, "bc6h") then + worst = math.max(worst, math.abs(got - want) / math.max(1, math.abs(want))) + end + end + local tol = if native.format == "rgba8" then 1 / 255 elseif native.format == "rgba16" then 1 / 65535 else 1e-3 + t:check(worst <= tol + 1e-9, string.format("%s: native %s off by %g", label, native.format, worst)) + end + nsurf += 1 + end +end +t:note("%d files, %d surfaces match", #Fx.cases, nsurf) + +-- our files: ktx validate accepts them, ktx extract reads the first image +local function source(w: number, h: number): buffer + local px = buffer.create(w * h * 4) + for y = 0, h - 1 do + for x = 0, w - 1 do + local o = (y * w + x) * 4 + buffer.writeu8(px, o, math.floor(x / (w - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 1, math.floor(y / (h - 1) * 255 + 0.5)) + buffer.writeu8(px, o + 2, math.floor(((x * 7 + y * 13) % 64) / 63 * 255 + 0.5)) + buffer.writeu8(px, o + 3, math.floor(((x + y) % 5) / 4 * 255 + 0.5)) + end + end + return px +end +local src = source(37, 23) +for _, o in Fx.ours do + t:check(o.valid, o.name .. ": ktx validate: " .. tostring(o.report)) + local img, err = dec(o.data, { mips = true, native = true }) + t:check(img, o.name .. ": " .. tostring(err)) + if o.png and (string.find(o.name, "rgba8") or string.find(o.name, "srgb")) then + t:eq(o.png, buffer.tostring(src), o.name .. ": ktx extract gives the source") + end + if string.find(o.name, "mips") or string.find(o.name, "zlib") then + t:eq(#img.meta.mipmaps, 5, o.name .. ": mip chain") + end + if string.find(o.name, "cube") then + t:eq(img.meta.layout, "cube", o.name .. ": cube") + t:eq(#img.frames, 6, o.name .. ": faces") + end +end +t:note("%d of our files pass ktx validate", #Fx.ours) + +-- round trips +do + local img = Types.Image.new(37, 23) + img.pixels = src + for _, o in { {}, { mips = true }, { zlib = 9 }, { srgb = true } } do + local back = dec(Ktx.encode(img, o :: any) :: buffer) + t:eq(buffer.tostring(back.pixels), buffer.tostring(src), "rgba8 round trip") + end + local f = Types.Image.new(3, 2, "rgbaf32") + for i = 0, 23 do + buffer.writef32(f.pixels, i * 4, i * 0.37 - 2) + end + local back = dec(Ktx.encode(f) :: buffer, { native = true }) + t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip") + local _, e = Ktx.encode(f, { format = "rgba8" }) + t:check(e and e.code == Err.ARG, "format mismatch") + local _, e2 = Ktx.encode(img, { zlib = 12 }) + t:check(e2 and e2.code == Err.ARG, "zlib level") +end + +-- sniff, info, errors +do + local c = Fx.cases[1] + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff KTX2") + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("\171KTX 11\187\r\n\26\n"))), 1, "sniff KTX1") + t:eq(Ktx.sniff(Bytes.reader(buffer.fromstring("PNG"))), 0, "sniff other") + local info = Ktx.info(Bytes.reader(buffer.fromstring(c.data))) + t:check(info and info.version == 2 and info.vkFormat == 37, "info") + local _, e = dec(string.sub(c.data, 1, 60)) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = dec(string.sub(c.data, 1, #c.data - 100)) + t:check(e2 and e2.code == Err.TRUNCATED, "cut data: " .. tostring(e2)) + local _, e3 = dec(c.data, { maxPixels = 10 }) + t:check(e3 and e3.code == Err.LIMIT, "limit") +end + +local samples = {} +for i, c in Fx.cases do + if i % 2 == 0 or c.unsupported then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return dec(b, { mips = true }) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index cd0d87d..14a7df0 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -73,3 +73,23 @@ if which == "dds" then cube.meta.layout = "array" emit("ours_array_bc1.dds", Dds.encode(cube, { format = "bc1" })) end + +if which == "ktx" then + local Ktx = require("@formats/image/ktx") + local img = image(37, 23, "rgba8", 0) + emit("ours_rgba8.ktx2", Ktx.encode(img)) + emit("ours_rgba8_mips.ktx2", Ktx.encode(img, { mips = true })) + emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 })) + emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true })) + emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true })) + emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" })) + local cube = image(16, 16, "rgba8", 0) + cube.frames = {} + for i = 1, 6 do + cube.frames[i] = { image = image(16, 16, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + end + cube.meta.layout = "cube" + emit("ours_cube.ktx2", Ktx.encode(cube, { mips = true })) + cube.meta.layout = "array" + emit("ours_array.ktx2", Ktx.encode(cube)) +end diff --git a/tools/fixtures/_tex_reference.py b/tools/fixtures/_tex_reference.py index af25edf..52b51bd 100644 --- a/tools/fixtures/_tex_reference.py +++ b/tools/fixtures/_tex_reference.py @@ -99,6 +99,9 @@ def rgba_from(mode, raw): if mode == "L": for v in raw: out += bytes((v, v, v, 255)) + elif mode == "LA": + for i in range(0, len(raw), 2): + out += bytes((raw[i], raw[i], raw[i], raw[i + 1])) elif mode == "RGB": for i in range(0, len(raw), 3): out += raw[i:i + 3] + b"\xff" diff --git a/tools/fixtures/ktx.py b/tools/fixtures/ktx.py new file mode 100644 index 0000000..1e69fdb --- /dev/null +++ b/tools/fixtures/ktx.py @@ -0,0 +1,279 @@ +# KTX fixtures (tools/fixtures.py): +# - KTX2 from KTX-Software 4.4 (`ktx create`): PNG sources (mip chains, sRGB, cube maps, arrays), --raw data in +# uncompressed / packed / float / BCn / ETC2 / EAC VkFormats, a 3D texture, `ktx deflate` Zstandard and ZLIB +# supercompression, Basis Universal (ETC1S and UASTC: must give UNSUPPORTED); +# - KTX1 from toktx (PNG sources, mips, cube map, odd widths with row padding) and nvcompress -ktx (BC1 / BC3 / BC7), +# plus hand-written big-endian and packed-type KTX1 files; +# - our encoder's KTX2 files (tools/fixtures/_tex_encode.luau -a ktx): `ktx validate` and `ktx extract` read them. +# References: the PNG sources / raw values themselves, `ktx extract` PNGs for the generated mip levels, Pillow (BCn, +# through a one-surface DDS) and Godot (ETC / EAC) for block data. +# tests/gen/ktx.luau { cases = { { name, data, layout?, mips?, surfaces = { { level, layer, slice, w, h, rgba?, +# floats?, tol } }, unsupported? } }, ours = { { name, data, valid, extract = { rgba / floats } } } } +import importlib.util, os, random, shutil, struct, subprocess, tempfile + +_dir = os.path.dirname(os.path.abspath(__file__)) +_spec = importlib.util.spec_from_file_location("_tex_reference", os.path.join(_dir, "_tex_reference.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) +_spec2 = importlib.util.spec_from_file_location("_dds_fixture", os.path.join(_dir, "dds.py")) +D = importlib.util.module_from_spec(_spec2) +_spec2.loader.exec_module(D) + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ktx", "tools/fixtures/dds.py"] + + +def q8(v): + return 0 if v != v or v <= 0 else (255 if v >= 1 else int(v * 255 + 0.5)) + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-ktx-") + try: + cases = _cases(ctx, work, random.Random(9)) + ours = _ours(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + ctx.emit("ktx", {"cases": cases, "ours": ours}) + + +def read_png(ctx, paths): + return [R.rgba_from(m, raw) if m in ("RGB", "L", "LA", "RGBA") else raw for (m, w, h, raw) in + R.pillow(ctx, [open(p, "rb").read() for p in paths])] + + +def _cases(ctx, work, rng): + cases = [] + sh = [] + + def run(cmd): + sh.append(cmd) + + # sources + srcs = {} + for name, w, h, salt in (("a", 37, 23, 0), ("sq", 32, 32, 3)): + srcs[name] = (w, h, D.source(w, h, salt)) + open(os.path.join(work, name + ".png"), "wb").write(D.png(w, h, srcs[name][2])) + faces = [] + for i in range(6): + px = D.source(16, 16, i + 1) + faces.append(px) + open(os.path.join(work, "f%d.png" % i), "wb").write(D.png(16, 16, px)) + fl = " ".join("f%d.png" % i for i in range(6)) + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear a.png k2_rgba8.ktx2") + run("ktx create --format R8G8B8A8_SRGB --assign-tf srgb --generate-mipmap sq.png k2_srgb_mips.ktx2") + run("ktx extract --level all k2_srgb_mips.ktx2 k2mips") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --cubemap %s k2_cube.ktx2" % fl) + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --layers 3 f0.png f1.png f2.png k2_array.ktx2") + run("ktx create --format R8G8B8_UNORM --assign-tf linear a.png k2_rgb8.ktx2") + run("ktx deflate --zstd 12 k2_srgb_mips.ktx2 k2_zstd.ktx2") + run("ktx deflate --zlib 6 k2_cube.ktx2 k2_zlib.ktx2") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode basis-lz a.png k2_basis.ktx2") + run("ktx create --format R8G8B8A8_UNORM --assign-tf linear --encode uastc a.png k2_uastc.ktx2") + # raw formats with known values + W, H = 8, 4 + raws = [] + + def raw(name, vk, data, texels=None, block=None, w=W, h=H, extra="", parts=1): + n = len(data) // parts + files = [] + for i in range(parts): + open(os.path.join(work, "%s_%d.raw" % (name, i)), "wb").write(data[i * n:(i + 1) * n]) + files.append("%s_%d.raw" % (name, i)) + run("ktx create --raw --width %d --height %d --format %s %s %s %s.ktx2" % (w, h, vk, extra, " ".join(files), name)) + raws.append((name, texels, block, w, h, data)) + + u8 = bytes(rng.randrange(256) for _ in range(W * H * 4)) + raw("k2_raw_rgba8", "R8G8B8A8_UNORM", u8, [tuple(u8[i + k] / 255 for k in range(4)) for i in range(0, len(u8), 4)]) + raw("k2_raw_bgra8_srgb", "B8G8R8A8_SRGB", u8, [(u8[i + 2] / 255, u8[i + 1] / 255, u8[i] / 255, u8[i + 3] / 255) for i in range(0, len(u8), 4)]) + raw("k2_raw_rg8", "R8G8_UNORM", u8[:W * H * 2], [(u8[i] / 255, u8[i + 1] / 255, 0.0, 1.0) for i in range(0, W * H * 2, 2)]) + vals = [(rng.uniform(-1, 4), rng.uniform(0, 1), rng.uniform(0, 2), rng.uniform(0, 1)) for _ in range(W * H)] + hd = b"".join(struct.pack("<4e", *v) for v in vals) + raw("k2_raw_rgba16f", "R16G16B16A16_SFLOAT", hd, [struct.unpack("<4e", hd[i:i + 8]) for i in range(0, len(hd), 8)]) + fd = b"".join(struct.pack("<4f", *v) for v in vals) + raw("k2_raw_rgba32f", "R32G32B32A32_SFLOAT", fd, [struct.unpack("<4f", fd[i:i + 16]) for i in range(0, len(fd), 16)]) + u16 = [rng.randrange(65536) for _ in range(W * H)] + raw("k2_raw_r16", "R16_UNORM", b"".join(struct.pack("> 11) / 31, ((v >> 5) & 63) / 63, (v & 31) / 31, 1.0) for v in u16]) + p32 = [rng.getrandbits(32) for _ in range(W * H)] + raw("k2_raw_a2b10g10r10", "A2B10G10R10_UNORM_PACK32", b"".join(struct.pack("> 10) & 1023) / 1023, ((v >> 20) & 1023) / 1023, (v >> 30) / 3) for v in p32]) + raw("k2_raw_e5b9g9r9", "E5B9G9R9_UFLOAT_PACK32", b"".join(struct.pack("> (9 * k) & 511) * 2.0 ** ((v >> 27) - 24) for k in range(3)) + (1.0,) for v in p32]) + vol = bytes(rng.randrange(256) for _ in range(4 * 4 * 3 * 4)) + raw("k2_raw_3d", "R8G8B8A8_UNORM", vol, None, None, 4, 4, "--depth 3", 3) + for kind, vk in (("bc1", "BC1_RGB_UNORM_BLOCK"), ("bc1", "BC1_RGBA_UNORM_BLOCK"), ("bc3", "BC3_UNORM_BLOCK"), + ("bc7", "BC7_UNORM_BLOCK"), ("bc6h", "BC6H_UFLOAT_BLOCK"), ("etc2_rgba", "ETC2_R8G8B8A8_UNORM_BLOCK"), + ("etc2_rgb", "ETC2_R8G8B8_UNORM_BLOCK"), ("eac_rg11", "EAC_R11G11_UNORM_BLOCK")): + bb = {"bc1": 8, "bc3": 16, "bc7": 16, "bc6h": 16, "etc2_rgba": 16, "etc2_rgb": 8, "eac_rg11": 16}[kind] + data = bytes(rng.getrandbits(8) for _ in range(4 * 2 * bb)) + raw("k2_raw_" + vk.lower(), vk, data, None, kind, 13, 7) + # KTX1 + run("toktx --genmipmap k1_mips.ktx sq.png") + run("toktx k1_rgba.ktx a.png") + run("toktx --cubemap k1_cube.ktx %s" % fl) + run("ktx2ktx2 -o k1_mips_as2.ktx2 k1_mips.ktx") + run("ktx extract --level all k1_mips_as2.ktx2 k1mips") + ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))]) + ctx.nix("nvidia-texture-tools", ["sh", "-c", "cd %s && nvcompress -silent -ktx -bc1 a.png n_bc1.ktx && nvcompress -silent -ktx -bc3 a.png n_bc3.ktx && nvcompress -silent -ktx -bc7 -nomips a.png n_bc7.ktx" % work]) + + def rd(n): + return open(os.path.join(work, n), "rb").read() + + def surf(level, layer, s, w, h, rgba=None, floats=None, tol=0): + d = {"level": level, "layer": layer, "slice": s, "w": w, "h": h, "tol": tol} + if rgba is not None: + d["rgba"] = rgba + if floats is not None: + d["floats"] = floats + return d + + aw, ah, apx = srcs["a"] + sw, shh, spx = srcs["sq"] + cases.append({"name": "k2_rgba8.ktx2", "data": rd("k2_rgba8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]}) + mip_files = sorted(f for f in os.listdir(work) if f.startswith("k2mips") or f.startswith("output_level")) + mips = [] + lw = sw + level = 0 + while True: + p = os.path.join(work, "k2mips_level%d.png" % level) + if not os.path.exists(p): + p = os.path.join(work, "k2mips", "output_level%d.png" % level) + if not os.path.exists(p): + break + mips.append((level, p)) + level += 1 + if not mips: + raise RuntimeError("ktx extract wrote no mip levels: %r" % os.listdir(work)) + pngs = read_png(ctx, [p for _, p in mips]) + msurf = [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for (lv, _), px in zip(mips, pngs)] + cases.append({"name": "k2_srgb_mips.ktx2", "data": rd("k2_srgb_mips.ktx2"), "layout": "2d", "mips": len(mips), "srgb": True, "surfaces": msurf}) + cases.append({"name": "k2_zstd.ktx2", "data": rd("k2_zstd.ktx2"), "layout": "2d", "mips": len(mips), "surfaces": msurf}) + csurf = [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)] + cases.append({"name": "k2_cube.ktx2", "data": rd("k2_cube.ktx2"), "layout": "cube", "surfaces": csurf}) + cases.append({"name": "k2_zlib.ktx2", "data": rd("k2_zlib.ktx2"), "layout": "cube", "surfaces": csurf}) + cases.append({"name": "k2_array.ktx2", "data": rd("k2_array.ktx2"), "layout": "array", "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(3)]}) + opaque = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(apx)) + cases.append({"name": "k2_rgb8.ktx2", "data": rd("k2_rgb8.ktx2"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, opaque)]}) + cases.append({"name": "k2_basis.ktx2", "data": rd("k2_basis.ktx2"), "unsupported": True, "surfaces": []}) + cases.append({"name": "k2_uastc.ktx2", "data": rd("k2_uastc.ktx2"), "unsupported": True, "surfaces": []}) + pil, pil_t, gd, gd_t = [], [], [], [] + for (name, texels, block, w, h, data) in raws: + c = {"name": name + ".ktx2", "data": rd(name + ".ktx2"), "layout": "volume" if name.endswith("3d") else "2d"} + if texels is not None: + c["surfaces"] = [surf(0, 0, 0, w, h, bytes(q8(v) for t in texels for v in t), b"".join(struct.pack("<4f", *t) for t in texels), 1)] + elif block is None: + c["surfaces"] = [surf(0, 0, s, w, h, data[s * w * h * 4:(s + 1) * w * h * 4]) for s in range(3)] + else: + sd = surf(0, 0, 0, w, h) + c["surfaces"] = [sd] + if block.startswith("bc") and block != "bc6h": + dx = {"bc1": 71, "bc3": 77, "bc7": 98}[block] + pil.append(R.dds_dx10(w, h, dx, data)) + pil_t.append((sd, "RGB_UNORM" in name.upper())) + else: + gd.append((data, w, h, R.GODOT[block], block == "bc6h")) + gd_t.append((sd, block)) + cases.append(c) + for (sd, opaque_), (mode, w, h, rw) in zip(pil_t, R.pillow(ctx, pil)): + px = R.rgba_from(mode, rw) + if opaque_: + px = bytes(v if i % 4 != 3 else 255 for i, v in enumerate(px)) + sd["rgba"] = px + for (sd, block), out in zip(gd_t, R.godot(ctx, gd)): + if block == "bc6h": + sd["floats"] = out + elif block == "eac_rg11": + sd["rgba"] = bytes(v if i % 4 < 2 else (255 if i % 4 == 3 else 0) for i, v in enumerate(out)) + sd["tol"] = 1 + else: + sd["rgba"] = out + # KTX1 + k1 = [] + level = 0 + while True: + p = os.path.join(work, "k1mips_level%d.png" % level) + if not os.path.exists(p): + p = os.path.join(work, "k1mips", "output_level%d.png" % level) + if not os.path.exists(p): + break + k1.append(p) + level += 1 + k1png = read_png(ctx, k1) + cases.append({"name": "k1_mips.ktx", "data": rd("k1_mips.ktx"), "layout": "2d", "mips": len(k1), + "surfaces": [surf(lv, 0, 0, max(1, sw >> lv), max(1, shh >> lv), px) for lv, px in enumerate(k1png)]}) + cases.append({"name": "k1_rgba.ktx", "data": rd("k1_rgba.ktx"), "layout": "2d", "surfaces": [surf(0, 0, 0, aw, ah, apx)]}) + cases.append({"name": "k1_cube.ktx", "data": rd("k1_cube.ktx"), "layout": "cube", + "surfaces": [surf(0, i, 0, 16, 16, faces[i]) for i in range(6)]}) + # nvcompress KTX1: the level-0 blocks follow the 64-byte header + key / value data + imageSize + nv = [] + for n, dx in (("n_bc1.ktx", 71), ("n_bc3.ktx", 77), ("n_bc7.ktx", 98)): + d = rd(n) + kvb = struct.unpack("4H", *v) for v in v16) + b"\0" * 0 # rows of 40 bytes: already 4-aligned + cases.append({"name": "hand big-endian RGBA16", "data": ktx1(0x1403, 2, 0x1908, 0x805B, 0x1908, W2, H2, img, True), "layout": "2d", + "surfaces": [surf(0, 0, 0, W2, H2, bytes(q8(x / 65535) for v in v16 for x in v), b"".join(struct.pack("<4f", *(x / 65535 for x in v)) for v in v16), 1)]}) + p565 = [rng.getrandbits(16) for _ in range(W2 * H2)] + rows = b"".join(b"".join(struct.pack("> 11) / 31, ((p >> 5) & 63) / 63, (p & 31) / 31, 1.0)), None, 1)]}) + rgb = bytes(rng.randrange(256) for _ in range(W2 * H2 * 3)) + rows = b"".join(rgb[y * W2 * 3:(y + 1) * W2 * 3] + b"\0" for y in range(H2)) + kv = b"KTXorientation\0S=r,T=u\0" + kv = struct.pack(" %s.val 2>&1; echo $? > %s.rc)" % (n, base, base)) + sh.append("(ktx extract %s %s.x > /dev/null 2>&1 || true)" % (n, base)) + ctx.nix("ktx-tools", ["sh", "-c", "cd %s && %s" % (work, " ; ".join(sh))]) + out = [] + pngs, idx = [], [] + for i, n in enumerate(names): + base = n[:-5] + rc = open(os.path.join(work, base + ".rc")).read().strip() + e = {"name": n, "data": files[n], "valid": rc == "0", "report": open(os.path.join(work, base + ".val"), "rb").read()[:2000]} + for ext in (".x", ".x.png", ".x.exr"): + p = os.path.join(work, base + ext) + if os.path.exists(p) and os.path.isfile(p): + e["extracted"] = open(p, "rb").read()[:8] + if open(p, "rb").read(4) == b"\x89PNG": + pngs.append(p) + idx.append(i) + out.append(e) + for i, (mode, w, h, raw) in zip(idx, R.pillow(ctx, [open(p, "rb").read() for p in pngs])): + if mode in ("RGBA", "RGB", "L", "LA"): + out[i]["png"] = R.rgba_from(mode, raw) + return out From 5585ce53cef2d020ecb364fb70ea00c261831c10 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:30:45 -0500 Subject: [PATCH 25/54] ws-video2: MPEG-1 tests bit-exact against ffmpeg -idct int (308 of 312 frames; 4 with concealed macroblocks) --- tests/codecs/mpeg1.luau | 27 +++++++++++++++++++++++++-- tools/fixtures/mpeg1.py | 15 +++++++++++---- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/tests/codecs/mpeg1.luau b/tests/codecs/mpeg1.luau index 34cafb4..d5ca329 100644 --- a/tests/codecs/mpeg1.luau +++ b/tests/codecs/mpeg1.luau @@ -1,4 +1,5 @@ --- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Against ffmpeg +-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with +-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg -- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode, -- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per -- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p; @@ -11,6 +12,7 @@ local Mpeg1 = require("@formats/codecs/video/Mpeg1") local Base64 = require("@formats/core/Base64") local Deflate = require("@formats/codecs/compress/Deflate") local Types = require("@formats/Types") +local Crc32 = require("@formats/core/Crc32") local STREAMS = { require("@tests/gen/mpeg1_qcif_200k"), @@ -81,6 +83,7 @@ local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): nu end local MAE_LIMIT = 2 +local totalExact, totalConcealed = 0, 0 local MEAN_LIMIT = 1.5 -- 1. every stream against ffmpeg @@ -101,6 +104,7 @@ for _, fx in STREAMS do local hasB = string.find(name, "bframes") ~= nil local dec = Mpeg1.new({ reorder = hasB }) local frames = 0 + local exact, concealed = 0, 0 local maxMae, maxMeanErr = 0, 0 local sums = {} local function onFrame(f: any) @@ -136,6 +140,21 @@ for _, fx in STREAMS do end t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255") sums[frames] = buffer.tostring(px) + -- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal) + local ex = fx.exact[frames] + if ex then + local img = Mpeg1.frameImage(f) :: Types.Image + local yc = Crc32.of(img.pixels, 0, n) + local uc = Crc32.of(img.pixels, n, cw * ch) + local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch) + if yc == ex[1] and uc == ex[2] and vc == ex[3] then + exact += 1 + elseif next(f.concealed) ~= nil then + concealed += 1 + else + t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType)) + end + end end local t0 = os.clock() for _, u in fx.units do @@ -155,7 +174,10 @@ for _, fx in STREAMS do t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)") t:eq(dec.stats.errors, 0, name .. ": no bitstream errors") worst = math.max(worst, maxMae) - t:note("%-13s %4dx%-4d %3d frames worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, maxMae, maxMeanErr, frames / dt) + t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt) + t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)") + totalExact += exact + totalConcealed += concealed -- streamed: random pieces through write / decodeFrame, then flush local d2 = Mpeg1.new({ reorder = hasB }) @@ -187,6 +209,7 @@ for _, fx in STREAMS do t:eq(got, frames, name .. ": streamed frame count") end t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC) +t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed) -- 2. a size change mid-stream do diff --git a/tools/fixtures/mpeg1.py b/tools/fixtures/mpeg1.py index 0400555..3b5dfd8 100644 --- a/tools/fixtures/mpeg1.py +++ b/tools/fixtures/mpeg1.py @@ -4,7 +4,9 @@ # tests/gen/mpeg1_.luau { name, width, height, frames, file (base64), units = { { offset, length } }, # means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA), # rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib), -# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) } +# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib), +# exact = { { y, u, v } } (CRC-32 of every frame's planes from `ffmpeg -idct int`, the IDCT +# codecs/video/Dsp reproduces: the decode must equal it) } # tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } } # tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with # B-frames) for tools/bench.luau @@ -122,9 +124,9 @@ def generate(ctx): es = open(path, "rb").read() return (patch_size(es, *size) if size else es), path - def reference(path, fmt): - out = path + "." + fmt - ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) + def reference(path, fmt, idct=None): + out = path + "." + fmt + (idct or "") + ff((["-idct", idct] if idct else []) + ["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out]) r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "csv=p=0", path], check=True, capture_output=True) w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2]) @@ -134,10 +136,13 @@ def generate(ctx): es, path = encode(name, args, size) rgba, w, h = reference(path, "rgba") yuv, _, _ = reference(path, "yuv420p") + exact, _, _ = reference(path, "yuv420p", "int") if size: rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1]) + exact = crop_yuv(exact, w, h, size[0], size[1]) w, h = size fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + c = ((w + 1) // 2) * ((h + 1) // 2) n = len(rgba) // fs means = [] for k in range(n): @@ -151,6 +156,8 @@ def generate(ctx): "means": means, "rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks], "yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks], + "exact": [[zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + c]), zlib.crc32(f[w * h + c:ys])] + for f in (exact[k * ys:(k + 1) * ys] for k in range(n))], }) # a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own) From 730820d1f6f7d6befe0ac01b320f6b554e4efce2 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:33:46 -0500 Subject: [PATCH 26/54] ws-3d3: model/ms3d (MilkShape 3D) read + write Groups, materials (texture uri), joints -> nodes + skin + one animation, version 4 sub-versioned blocks (comments, vertex extras with up to four bones, joint colours, model extras). Writer: groups per placed primitive, the first skin plus animated nodes as joints (rigid meshes bound to them), weights in percent. Tested against assimp and through glTF skin models. --- docs/FORMATS.md | 1 + docs/guide/scene.md | 35 ++- src/Formats/Registry.luau | 12 + src/Formats/model/ms3d/Read.luau | 464 ++++++++++++++++++++++++++++ src/Formats/model/ms3d/Write.luau | 486 ++++++++++++++++++++++++++++++ src/Formats/model/ms3d/init.luau | 82 +++++ tests/model/ms3d.luau | 430 ++++++++++++++++++++++++++ tools/fixtures/_ms3d_encode.luau | 44 +++ tools/fixtures/ms3d.py | 68 +++++ 9 files changed, 1620 insertions(+), 2 deletions(-) create mode 100644 src/Formats/model/ms3d/Read.luau create mode 100644 src/Formats/model/ms3d/Write.luau create mode 100644 src/Formats/model/ms3d/init.luau create mode 100644 tests/model/ms3d.luau create mode 100644 tools/fixtures/_ms3d_encode.luau create mode 100644 tools/fixtures/ms3d.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index ce760a5..0af45e9 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -39,6 +39,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | ms3d | .ms3d | yes | yes | materials: true, skins: true, animation: true | `tests/model/ms3d.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 211ff7b..6dc5fb7 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -290,7 +290,7 @@ the binary container. | glTF | `external = true` writes `.bin` and the images into `opts.files` (default: embedded `data:` URIs) | `binary`, `external`, `name` | | OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | | STL | | `ascii = true` (default binary), `normals = "attribute"` | -| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS | see [FORMATS.md](../FORMATS.md) and the format's options | | +| PLY, OFF, FBX, DAE, 3MF, USDA, VOX, 3DS, MS3D | see [FORMATS.md](../FORMATS.md) and the format's options | | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -408,6 +408,36 @@ assert(back.materials[prim.material].baseColor[1] == 1) assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the node transform ``` +## MilkShape 3D (MS3D) + +Each group loads as a node with one mesh (per-corner normals and uvs, so vertices are split per corner); joints become +nodes with a skin (`JOINTS_0` / `WEIGHTS_0`, up to four bones from the 1.8 vertex extras) and their keys one +animation. Comments, joint colours and the other MilkShape fields stay in `extras.ms3d` / `meta.source`. The writer +puts every placed primitive in a group, the first skin's joints plus every node the first animation moves (meshes +under them are bound rigidly) into the skeleton, and the weights in percent. + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") +-- spin the node a quarter turn about z in one second +local times = S.accessor(nil, "f32", 1, 2) +buffer.writef32(times.data, 4, 1) +local turns = S.accessor(nil, "f32", 4, 2) +for i, v in { 0, 0, 0, 1, 0, 0, math.sqrt(0.5), math.sqrt(0.5) } do + buffer.writef32(turns.data, (i - 1) * 4, v) +end +scene.animations[1] = { channels = { { node = 1, path = "rotation", input = times, output = turns, interpolation = "LINEAR" } } } +local back = assert(F.load(assert(F.save(scene, nil, { format = "ms3d" })))) +assert(back.meta.source.format == "ms3d" and #back.skins == 1) -- the animated node became a joint +local prim = back.meshes[1].primitives[1] +assert(prim.attributes.JOINTS_0 and prim.attributes.NORMAL) +assert(back.animations[1].channels[1].path == "rotation") +``` + ## Formats | Format | Read | Write | Notes | @@ -423,6 +453,7 @@ assert(back.nodes[1].translation[3] == 2) -- the keyframer keeps the | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | | 3DS | yes | yes | keyframer hierarchy and animation, Phong materials, texture names, cameras, lights; Z up | +| MS3D (MilkShape 3D) | yes | yes | groups, materials, joints -> skin + animation, comments | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 8fbf340..3906190 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -422,6 +422,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "ms3d", + category = "model", + path = "model/ms3d", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, + load = function() + return require("@formats/model/ms3d") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/model/ms3d/Read.luau b/src/Formats/model/ms3d/Read.luau new file mode 100644 index 0000000..2470edd --- /dev/null +++ b/src/Formats/model/ms3d/Read.luau @@ -0,0 +1,464 @@ +--!strict +-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h +-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a +-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess +-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and +-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds +-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model), +-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3), +-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference). +-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices +-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest + +-- key positions). Never throws on bad data: returns nil, message, offset. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") + +local Read = {} + +local S = Types.Scene +local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring +local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32 + +Read.MAGIC = "MS3D000000" + +export type Options = { maxVertices: number? } + +-- ------------------------------------------------------------------------------------------------ helpers +local function fixed(b: buffer, p: number, n: number): string + local s = readstring(b, p, n) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +local function floats(values: { number }, comps: number): Types.Accessor + local n = #values // comps + local a = S.accessor(nil, "f32", comps, n) + for i = 1, n * comps do + writef32(a.data, (i - 1) * 4, values[i]) + end + return a +end + +local function color(b: buffer, p: number): { number } + return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) } +end + +-- the texture file name as a relative uri (MilkShape writes ".\name.jpg") +local function uri(s: string): string + local u = string.gsub(s, "\\", "/") + u = string.gsub(u, "^%./", "") + return u +end + +-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion +local function euler(x: number, y: number, z: number): { number } + return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z))) +end + +-- ------------------------------------------------------------------------------------------------ parse +type Vertex = { pos: { number }, bones: { number }, weights: { number } } +type Joint = { + name: string, parent: string, flags: number, rot: { number }, pos: { number }, + rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?, +} + +-- scene(b, base, limit, opts) -> Scene | nil, message, offset +function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?) + local p = base + local function need(n: number): boolean + return p + n <= limit + end + if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then + return nil, "not a MilkShape 3D file", base + end + local version = readi32(b, p + 10) + if version ~= 3 and version ~= 4 then + return nil, "unsupported: version " .. version, p + 10 + end + p += 14 + local maxV = opts and opts.maxVertices or 2 ^ 20 + -- vertices + if not need(2) then + return nil, "truncated vertex count", p + end + local nv = readu16(b, p) + p += 2 + if not need(nv * 15) then + return nil, "truncated vertices", p + end + local verts: { Vertex } = {} + for i = 1, nv do + local q = p + (i - 1) * 15 + verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } } + end + p += nv * 15 + -- triangles + if not need(2) then + return nil, "truncated triangle count", p + end + local nt = readu16(b, p) + p += 2 + if not need(nt * 70) then + return nil, "truncated triangles", p + end + if nt * 3 > maxV then + return nil, "limit: more than " .. maxV .. " triangle corners", p + end + local triAt = p + p += nt * 70 + -- groups + if not need(2) then + return nil, "truncated group count", p + end + local ng = readu16(b, p) + p += 2 + local groups = {} + for _ = 1, ng do + if not need(35) then + return nil, "truncated group", p + end + local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? } + local n = readu16(b, p + 33) + p += 35 + if not need(n * 2 + 1) then + return nil, "truncated group triangles", p + end + for k = 0, n - 1 do + local ti = readu16(b, p + k * 2) + if ti >= nt then + return nil, "group triangle " .. ti .. " out of range", p + k * 2 + end + table.insert(g.tris, ti) + end + p += n * 2 + g.material = readi8(b, p) + p += 1 + table.insert(groups, g) + end + -- materials + if not need(2) then + return nil, "truncated material count", p + end + local nm = readu16(b, p) + p += 2 + if not need(nm * 361) then + return nil, "truncated materials", p + end + local mats = {} + for i = 0, nm - 1 do + local q = p + i * 361 + table.insert(mats, { + name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64), + emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100), + mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?, + }) + end + p += nm * 361 + -- animation header and joints (version 3 files may end here) + local fps, current, frames = 24, 0, 0 + local joints: { Joint } = {} + if need(12) then + fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8) + p += 12 + if not need(2) then + return nil, "truncated joint count", p + end + local nj = readu16(b, p) + p += 2 + for _ = 1, nj do + if not need(93) then + return nil, "truncated joint", p + end + local j: Joint = { + flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32), + rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) }, + pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) }, + rotKeys = {}, posKeys = {}, + } + local nr, np = readu16(b, p + 89), readu16(b, p + 91) + p += 93 + if not need((nr + np) * 16) then + return nil, "truncated joint keys", p + end + for k = 0, nr + np - 1 do + local q = p + k * 16 + local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) } + table.insert(if k < nr then j.rotKeys else j.posKeys, key) + end + p += (nr + np) * 16 + table.insert(joints, j) + end + end + -- sub-versioned blocks + local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames } + local function comments(list: { any }): string? + if not need(4) then + return "truncated comments" + end + local n = readi32(b, p) + p += 4 + for _ = 1, math.max(n, 0) do + if not need(8) then + return "truncated comment" + end + local index, len = readi32(b, p), readi32(b, p + 4) + p += 8 + if len < 0 or not need(len) then + return "comment runs past the end" + end + if list[index + 1] then + list[index + 1].comment = readstring(b, p, len) + end + p += len + end + return nil + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.commentVersion = sub + if sub == 1 then + for _, list in { groups, mats, joints } :: { { any } } do + local e = comments(list) + if e then + return nil, e, p + end + end + if not need(4) then + return nil, "truncated model comment", p + end + local has = readi32(b, p) + p += 4 + if has ~= 0 then + if not need(4) then + return nil, "truncated model comment", p + end + local len = readi32(b, p) + p += 4 + if len < 0 or not need(len) then + return nil, "model comment runs past the end", p + end + source.comment = readstring(b, p, len) + p += len + end + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + source.vertexVersion = sub + local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0 + if size > 0 and need(nv * size) then + for i = 1, nv do + local q = p + (i - 1) * size + local v = verts[i] + local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5) + if w0 + w1 + w2 > 0 then + local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100 + v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) } + v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) } + end + end + p += nv * size + end + end + if need(4) then + local sub = readi32(b, p) + p += 4 + if (sub == 1 or sub == 2) and need(#joints * 12) then + for _, j in joints do + j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) } + p += 12 + end + end + end + if need(16) and readi32(b, p) >= 1 then + source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12) + end + return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil +end + +-- ------------------------------------------------------------------------------------------------ build +function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene + local scene = S.new() + scene.meta.up = "y" + scene.meta.source = source :: any + -- materials, textures + for _, m in mats do + local mat = S.material(m.name) + local d = m.diffuse + mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) } + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1) + mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] } + mat.alphaMode = if m.transparency < 1 then "blend" else "opaque" + if m.texture ~= "" then + local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) } + table.insert(scene.textures, tex) + mat.baseColorTexture = { texture = #scene.textures } + end + mat.extras = { + ms3d = { + ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess, + transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment, + }, + } + table.insert(scene.materials, mat) + end + -- joints: nodes, rest pose, skin + local nj = #joints + local jointNode: { [number]: number } = {} + local byName: { [string]: number } = {} + local abs: { { number } } = {} + for i, j in joints do + local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) } + node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } } + table.insert(scene.nodes, node) + jointNode[i] = #scene.nodes + if byName[j.name] == nil then + byName[j.name] = i + end + end + for i, j in joints do + local pi = byName[j.parent] + -- parents must come first (MilkShape writes them in that order); others become roots + local local_ = S.nodeMatrix(scene.nodes[jointNode[i]]) + if pi and pi < i then + table.insert(scene.nodes[jointNode[pi]].children, jointNode[i]) + abs[i] = S.mul(abs[pi], local_) + else + table.insert(scene.roots, jointNode[i]) + abs[i] = local_ + end + end + local skinned = false + for _, v in verts do + for k = 1, 4 do + if v.bones[k] >= nj then + v.bones[k] = -1 + end + end + skinned = skinned or (nj > 0 and v.bones[1] >= 0) + end + if nj > 0 then + local ibm = S.accessor(nil, "f32", 16, nj) + ibm.matrix = true + for i = 1, nj do + local inv = Mat4.inverse(abs[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local list = table.create(nj, 0) + for i = 1, nj do + list[i] = jointNode[i] + end + scene.skins[1] = { joints = list, inverseBindMatrices = ibm } + end + -- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner + local nv = #verts + for gi, g in groups do + local remap: { [string]: number } = {} + local P, N, U, J, W = {}, {}, {}, {}, {} + local idx: { number } = {} + local sgs: { number } = {} + local count = 0 + for _, ti in g.tris do + local q = triAt + ti * 70 + -- a triangle with an out-of-range vertex is dropped + if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then + continue + end + table.insert(sgs, readu8(b, q + 68)) + for k = 0, 2 do + local vi = readu16(b, q + 2 + k * 2) + local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4) + local o = remap[key] + if o == nil then + o = count + count += 1 + remap[key] = o + local v = verts[vi + 1] + table.move(v.pos, 1, 3, o * 3 + 1, P) + N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12) + U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4) + -- influences: the valid bones, weights normalized + local sum = 0 + for c = 1, 4 do + if v.bones[c] >= 0 then + sum += v.weights[c] + end + end + for c = 1, 4 do + local ok = v.bones[c] >= 0 and sum > 0 + J[o * 4 + c] = if ok then v.bones[c] else 0 + W[o * 4 + c] = if ok then v.weights[c] / sum else 0 + end + end + table.insert(idx, o :: number) + end + end + local prim: Types.Primitive = { + attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) }, + mode = "triangles", + material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil, + extras = { ms3d = { smoothing = sgs } }, + } + local ind = S.accessor(nil, "u32", 1, #idx) + for i, v in idx do + writeu32(ind.data, (i - 1) * 4, v) + end + prim.indices = ind + local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } } + if skinned then + local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count) + for i = 1, count * 4 do + if nj > 255 then + writeu16(ja.data, (i - 1) * 2, J[i]) + else + writeu8(ja.data, i - 1, J[i]) + end + end + prim.attributes.JOINTS_0 = ja + prim.attributes.WEIGHTS_0 = floats(W, 4) + node.skin = 1 + end + local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } } + scene.meshes[gi] = mesh + node.mesh = gi + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- the animation: rest * key rotations, rest + key positions + local channels: { Types.Channel } = {} + for i, j in joints do + if #j.rotKeys > 0 then + local times, vals = {}, {} + local rest = scene.nodes[jointNode[i]].rotation :: { number } + for _, k in j.rotKeys do + table.insert(times, k[1]) + local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4])))) + table.move(q, 1, 4, #vals + 1, vals) + end + local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" } + table.insert(channels, ch) + end + if #j.posKeys > 0 then + local times, vals = {}, {} + for _, k in j.posKeys do + table.insert(times, k[1]) + table.insert(vals, j.pos[1] + k[2]) + table.insert(vals, j.pos[2] + k[3]) + table.insert(vals, j.pos[3] + k[4]) + end + local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" } + table.insert(channels, ch) + end + end + if #channels > 0 then + table.insert(scene.animations, { name = "ms3d", channels = channels }) + end + return scene +end + +return Read diff --git a/src/Formats/model/ms3d/Write.luau b/src/Formats/model/ms3d/Write.luau new file mode 100644 index 0000000..3cef5bd --- /dev/null +++ b/src/Formats/model/ms3d/Write.luau @@ -0,0 +1,486 @@ +--!strict +-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped, +-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first +-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2); +-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each +-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's +-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials: +-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and +-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment), +-- joint colours and model extras are written in their sub-versioned blocks. +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") + +local Write = {} + +local S = Types.Scene +local sqrt = math.sqrt + +export type Options = { fps: number?, name: string?, files: { [string]: any }? } + +local function fixedString(w: Bytes.Writer, s: string, n: number) + local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1) + w:string(v) + for _ = #v + 1, n do + w:u8(0) + end +end + +local function msg(s: any): string + return if type(s) == "string" then s else "" +end + +-- ------------------------------------------------------------------------------------------------ tree +type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } } +local function tree(scene: Types.Scene): Tree + local t: Tree = { world = {}, parent = {}, order = {} } + local function visit(i: number, p: number, pm: { number }, depth: number) + local n = scene.nodes[i] + if type(n) ~= "table" or t.world[i] or depth > 256 then + return + end + t.world[i] = S.mul(pm, S.nodeMatrix(n)) + t.parent[i] = p + table.insert(t.order, i) + for _, c in n.children or {} do + visit(c, i, t.world[i], depth + 1) + end + end + for _, r in scene.roots do + visit(r, 0, S.IDENTITY, 0) + end + return t +end + +-- ------------------------------------------------------------------------------------------------ joints +type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } } + +-- the rigid part (rotation and translation) of a matrix +local function rigid(m: { number }): { number } + local t, r = Mat4.decompose(m) + return Mat4.compose(t, r, nil) +end + +-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order; +-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices +local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number }) + local skin = scene.skins[1] + local anim = scene.animations[1] + local out: { Joint } = {} + local bySkin: { [number]: number } = {} + local byNode: { [number]: number } = {} + local skinIndex: { [number]: number } = {} + local isJoint: { [number]: boolean } = {} + for k, ni in (if skin then skin.joints else {}) :: { number } do + skinIndex[ni] = k - 1 + isJoint[ni] = true + end + local chans: { [number]: { Types.Channel } } = {} + for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do + if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then + isJoint[ch.node] = true + chans[ch.node] = chans[ch.node] or {} + table.insert(chans[ch.node], ch) + end + end + -- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix + local B = S.IDENTITY + local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil + if skin and IBM and tr.world[skin.joints[1]] then + local m = table.create(16, 0) + for c = 1, 16 do + m[c] = (IBM :: any)(0, c - 1) + end + B = S.mul(tr.world[skin.joints[1]], m) + end + local names: { [string]: boolean } = {} + for _, ni in tr.order do + if not isJoint[ni] or #out >= 127 then + continue + end + local p = tr.parent[ni] + while p ~= 0 and byNode[p] == nil do + p = tr.parent[p] + end + -- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the + -- joint and its joint parent (C) carry over to the keys + local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity() + local gp = tr.parent[ni] + local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY) + local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni]))) + local e = Mat4.eulerXYZ(r) + local base = string.sub(msg(scene.nodes[ni].name), 1, 27) + local name = if base ~= "" then base else "joint" .. #out + local n = 1 + while names[name] do + n += 1 + name = base .. "_" .. n + end + names[name] = true + local j: Joint = { + node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t, + rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {}, + } + table.insert(out, j) + byNode[ni] = #out - 1 + if skinIndex[ni] then + bySkin[skinIndex[ni]] = #out - 1 + end + -- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest + local _, rc = Mat4.decompose(C) + local inv = Mat4.transpose3(Mat4.fromQuat(r)) + for _, ch in chans[ni] or {} do + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local cubic = ch.interpolation == "CUBICSPLINE" + for k = 0, ch.input.count - 1 do + local v = if cubic then k * 3 + 1 else k + local time = IN(k, 0) + if ch.path == "rotation" then + local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) } + local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 } + local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q))))) + table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) }) + else + local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2)) + table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] }) + end + end + end + end + return out, bySkin, byNode, B +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } } +type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number } +type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? } + +-- every placed primitive as a group: vertices, triangles; or nil, message +local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?) + local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {} + for _, pl in S.flatten(scene) do + local prim: any = pl.primitive + local node = scene.nodes[pl.node] + local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean + return false + end, { triangulate = true }) + if not merged then + return verts, tris, groups, err + end + local corners = merged.corners + if #corners == 0 then + continue + end + local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil + -- a rigid mesh follows its nearest joint + local rigid = -1 + if not skinned then + local p = pl.node + while p and p ~= 0 do + if byNode[p] then + rigid = byNode[p] + break + end + p = tr.parent[p] + end + end + local M = if skinned then B else pl.matrix + local NM = Mat4.normalMatrix(M) + local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0 + local A = prim.attributes + local POS = S.reader(A.POSITION) :: any + local zero = function(_: number, _: number): number + return 0 + end + type Get = (number, number) -> number + local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil + local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero + local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero + local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero + local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero + local base = #verts + local nv = A.POSITION.count + if base + nv > 65535 then + return verts, tris, groups, "more than 65535 vertices" + end + for v = 0, nv - 1 do + local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2)) + local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 } + if skinned then + local inf = {} + for c = 0, 3 do + local w = WE(v, c) + local j = bySkin[JO(v, c)] + if w > 0 and j then + table.insert(inf, { j, w }) + end + end + table.sort(inf, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, e in inf do + sum += e[2] + end + for c = 1, 4 do + local e = inf[c] + bones[c] = if e then e[1] else -1 + weights[c] = if e and sum > 0 then e[2] / sum else 0 + end + end + table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights }) + end + local gi = #groups + if gi >= 255 then + return verts, tris, groups, "more than 255 groups" + end + local name = msg(node.name) + if name == "" then + name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name) + end + local x = node.extras and node.extras.ms3d + local g: Group = { + name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0, + material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1, + comment = x and x.comment, + } + local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing + if type(saved) ~= "table" or #saved ~= #corners // 3 then + saved = nil + end + for f = 0, #corners // 3 - 1 do + local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3] + if mirror then + b, c = c, b + end + local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi } + -- the face normal for primitives without normals + local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1] + local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z + local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z + local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x + for _, v in { a, b, c } do + local nx, ny, nz = fx, fy, fz + if hasN then + local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2) + nx = NM[1] * ox + NM[5] * oy + NM[9] * oz + ny = NM[2] * ox + NM[6] * oy + NM[10] * oz + nz = NM[3] * ox + NM[7] * oy + NM[11] * oz + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n) + table.insert(t.uv, UV(v, 0)) + table.insert(t.uv, UV(v, 1)) + end + table.insert(tris, t) + table.insert(g.tris, #tris - 1) + end + if #tris > 65535 then + return verts, tris, groups, "more than 65535 triangles" + end + table.insert(groups, g) + end + return verts, tris, groups, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local tr = tree(scene) + local js, bySkin, byNode, B = joints(scene, tr) + local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B) + if gerr then + return nil, gerr + end + if #scene.materials > 127 then + return nil, "more than 127 materials" + end + local src: any = scene.meta.source + local fromMs3d = src ~= nil and src.format == "ms3d" + local w = Bytes.writer(65536) + w:string("MS3D000000") + w:u32le(4) + w:u16le(#verts) + for _, v in verts do + w:u8(0) + w:f32le(v.x) + w:f32le(v.y) + w:f32le(v.z) + w:i8(v.bones[1] % 256) + w:u8(1) + end + w:u16le(#tris) + for _, t in tris do + w:u16le(0) + for k = 1, 3 do + w:u16le(t.v[k]) + end + for k = 1, 9 do + w:f32le(t.n[k]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2 - 1]) + end + for k = 1, 3 do + w:f32le(t.uv[k * 2]) + end + w:u8(math.clamp(t.sg, 0, 255)) + w:u8(t.group) + end + w:u16le(#groups) + for _, g in groups do + w:u8(g.flags % 256) + fixedString(w, g.name, 32) + w:u16le(#g.tris) + for _, ti in g.tris do + w:u16le(ti) + end + w:i8(g.material % 256) + end + -- materials + w:u16le(#scene.materials) + local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture" + for i, m in scene.materials do + local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any } + local bc = m.baseColor or { 1, 1, 1, 1 } + fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32) + local e = m.emissive or { 0, 0, 0 } + for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do + for k = 1, 4 do + w:f32le(c[k] or 1) + end + end + local r = math.max(m.roughness or 1, 0.1) + w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128)) + w:f32le(bc[4] or 1) + w:i8((tonumber(x.mode) or 0) % 256) + local file = "" + local ref: any = m.baseColorTexture + local tex: any = ref and scene.textures[ref.texture] + if tex then + file = tex.uri or "" + if file == "" or string.sub(file, 1, 5) == "data:" then + file = base .. "_" .. ref.texture .. ".png" + if o.files and tex.data then + o.files[file] = tex.data + end + end + end + fixedString(w, file, 128) + fixedString(w, msg(x.alphamap), 128) + end + -- the animation header and joints + local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24) + local last = 0 + for _, j in js do + for _, k in j.rotKeys do + last = math.max(last, k[1]) + end + for _, k in j.posKeys do + last = math.max(last, k[1]) + end + end + w:f32le(fps) + w:f32le(0) + w:u32le(math.max(1, math.ceil(last * fps))) + w:u16le(#js) + for _, j in js do + local x = scene.nodes[j.node].extras + local jx = x and x.ms3d + w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0) + fixedString(w, j.name, 32) + fixedString(w, j.parent, 32) + for k = 1, 3 do + w:f32le(j.rot[k]) + end + for k = 1, 3 do + w:f32le(j.pos[k]) + end + w:u16le(#j.rotKeys) + w:u16le(#j.posKeys) + for _, list in { j.rotKeys, j.posKeys } do + for _, k in list do + for c = 1, 4 do + w:f32le(k[c]) + end + end + end + end + -- comments + w:u32le(1) + local function comments(list: { any }, get: (any) -> string?) + local found = {} + for i, item in list do + local c = get(item) + if type(c) == "string" and c ~= "" then + table.insert(found, { i - 1, c }) + end + end + w:u32le(#found) + for _, f in found do + w:u32le(f[1]) + w:u32le(#f[2]) + w:string(f[2]) + end + end + comments(groups, function(g: any): string? + return g.comment + end) + comments(scene.materials, function(m: any): string? + return m.extras and m.extras.ms3d and m.extras.ms3d.comment + end) + comments(js, function(j: any): string? + local x: any = scene.nodes[j.node].extras + return x and x.ms3d and x.ms3d.comment + end) + local mc = if fromMs3d then msg(src.comment) else "" + w:u32le(if mc ~= "" then 1 else 0) + if mc ~= "" then + w:u32le(#mc) + w:string(mc) + end + -- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32 + w:u32le(2) + for _, v in verts do + local p = table.create(3, 0) + local left = 100 + for c = 1, 3 do + p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left) + left -= p[c] + end + if v.bones[2] < 0 and v.bones[1] >= 0 then + p = { 100, 0, 0 } + end + for c = 2, 4 do + w:i8(v.bones[c] % 256) + end + for c = 1, 3 do + w:u8(p[c]) + end + w:u32le(0) + end + -- joint colours, model extras + w:u32le(1) + for _, j in js do + local x: any = scene.nodes[j.node].extras + local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 } + for k = 1, 3 do + w:f32le(c[k] or 1) + end + end + w:u32le(1) + w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1) + w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0) + w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5) + local out = buffer.create(w.pos) + buffer.copy(out, 0, w.buf, 0, w.pos) + return out, nil +end + +return Write diff --git a/src/Formats/model/ms3d/init.luau b/src/Formats/model/ms3d/init.luau new file mode 100644 index 0000000..e9db7b7 --- /dev/null +++ b/src/Formats/model/ms3d/init.luau @@ -0,0 +1,82 @@ +--!strict +-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of +-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested +-- against (no code ported). +-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and +-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in +-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive; +-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use +-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse +-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes +-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d, +-- the model comment / fps / frames / joint size in meta.source. meta.up = "y". +-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex), +-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127 +-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/ms3d/Read") +local Write = require("@formats/model/ms3d/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Ms3d = { + name = "ms3d", + category = "model", + extensions = { "ms3d" }, + mime = { "application/x-ms3d" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more triangle corners (default 2^20) +} +export type EncodeOptions = { + fps: number?, -- the animation's frames per second (default: the source's, else 24) + name: string?, -- the destination's file name (names textures that have no uri) + files: { [string]: any }?, -- receives the bytes of textures that have data but no uri +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ms3d.sniff(r: Bytes.Reader): number + local h = r:peek(14) + if string.sub(h, 1, 10) ~= Read.MAGIC then + return 0 + end + local v = string.byte(h, 11) + return if v == 3 or v == 4 then 1 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg, at) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ms3d.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 ok, out, err = pcall(Write.encode, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + return nil, Err.new(Err.ARG, tostring(err)) + end + return out, nil +end + +return Ms3d diff --git a/tests/model/ms3d.luau b/tests/model/ms3d.luau new file mode 100644 index 0000000..fc2b59c --- /dev/null +++ b/tests/model/ms3d.luau @@ -0,0 +1,430 @@ +-- model/ms3d tests: assimp's MilkShape 3D test models (groups, materials, textures, version 4 with and without the +-- sub-versioned blocks) against assimp (meshes, faces, corners, materials, world bounds); round trips through our +-- writer, of those files and of glTF sample models (world triangles, materials, textures, skins: joints, inverse bind +-- matrices, skinned vertices; animation sampled through the skeleton); assimp reading our files (meshes, faces, +-- bones, animations, bounds: ms3d_xcheck); comments and extras; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/ms3d.py. +local T = require("@tests/T") +local F = require("@formats") +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") +local Xcheck = require("@tests/gen/ms3d_xcheck") + +local t = T.suite("ms3d") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Ms3d.decode(Bytes.reader(b), opts) +end + +t:eq(Ms3d.name, "ms3d", "name") +t:eq(Ms3d.category, "model", "category") +t:check(Ms3d.caps.decode and Ms3d.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function counts(scene: any): (number, number, number) + local prims, faces, corners = 0, 0, 0 + for _, pl in S.flatten(scene) do + prims += 1 + faces += pl.primitive.indices.count // 3 + corners += pl.primitive.indices.count + end + return prims, faces, corners +end + +local function bstr(lo: any, hi: any): string + if not lo then + return "-" + end + return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +local function boundsEq(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end + +-- the bones assimp makes: per group, the distinct strongest joints of its vertices +local function bones(scene: any): number + local n = 0 + for _, pl in S.flatten(scene) do + local A = pl.primitive.attributes + if A.JOINTS_0 then + local J, W = S.reader(A.JOINTS_0) :: any, S.reader(A.WEIGHTS_0) :: any + local seen = {} + for v = 0, A.JOINTS_0.count - 1 do + local best, bw = -1, 0 + for c = 0, 3 do + if W(v, c) > bw then + best, bw = J(v, c), W(v, c) + end + end + if best >= 0 and not seen[best] then + seen[best] = true + n += 1 + end + end + end + end + return n +end + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes = {} +for i, c in Cases do + local scene, err = decode(c.data) + local a = c.assimp + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + if scene and not a.failed then + local prims, faces, corners = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": faces (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + t:eq(bones(scene), a.bones, c.name .. ": bones (assimp)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + end +end +t:note("%d files against assimp", #Cases) + +-- ------------------------------------------------------------------------------------------------ round trips +-- skinned world positions at a time: the skeleton posed by animations[1], vertices blended by their joints +local function skinnedPositions(s: any, time: number): { number } + local byNode: { [number]: { [string]: any } } = {} + for _, ch in (if s.animations[1] then s.animations[1].channels else {}) :: { any } do + byNode[ch.node] = byNode[ch.node] or {} + byNode[ch.node][ch.path] = ch + end + local function eval(ch: any, comps: number): { number } + local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + local u = if t1 > t0 then (time - t0) / (t1 - t0) else 1 + local a0, a1 = v(k), v(k + 1) + if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + if comps == 4 then + local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4]) + r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l } + end + return r + end + end + return v(n - 1) + end + local world: { [number]: { number } } = {} + local function visit(i: number, parent: { number }) + local n = s.nodes[i] + local chs = byNode[i] + local m = S.nodeMatrix(n) + if chs then + m = Mat4.compose(if chs.translation then eval(chs.translation, 3) else n.translation, + if chs.rotation then eval(chs.rotation, 4) else n.rotation, n.scale) + end + world[i] = S.mul(parent, m) + for _, c in n.children do + visit(c, world[i]) + end + end + for _, r in s.roots do + visit(r, S.IDENTITY) + end + local out = {} + for _, pl in S.flatten(s) do + local prim = pl.primitive + local P = S.reader(prim.attributes.POSITION) :: any + local I = S.reader(prim.indices) :: any + local node = s.nodes[pl.node] + local skin = node.skin and s.skins[node.skin] + local J = prim.attributes.JOINTS_0 and S.reader(prim.attributes.JOINTS_0) :: any + local W = prim.attributes.WEIGHTS_0 and S.reader(prim.attributes.WEIGHTS_0) :: any + local IBM = skin and skin.inverseBindMatrices and S.reader(skin.inverseBindMatrices) :: any + local tri = {} + for k = 0, prim.indices.count - 1 do + local v = I(k, 0) + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + local wx, wy, wz = 0, 0, 0 + if skin and J and W then + for c = 0, 3 do + local w = W(v, c) + if w > 0 then + local j = J(v, c) + local ibm = {} + for q = 1, 16 do + ibm[q] = IBM(j, q - 1) + end + local m = S.mul(world[skin.joints[j + 1]], ibm) + local px, py, pz = Mat4.point(m, x, y, z) + wx, wy, wz = wx + px * w, wy + py * w, wz + pz * w + end + end + else + wx, wy, wz = Mat4.point(world[pl.node] or pl.matrix, x, y, z) + end + table.insert(tri, { wx, wy, wz }) + if #tri == 3 then + -- each triangle's corners in a fixed order (a mirrored node's winding is flipped on write) + local function r(x: number): number + return math.floor(x * 100 + 0.5) + end + table.sort(tri, function(p: { number }, q: { number }): boolean + if r(p[1]) ~= r(q[1]) then + return r(p[1]) < r(q[1]) + elseif r(p[2]) ~= r(q[2]) then + return r(p[2]) < r(q[2]) + end + return r(p[3]) < r(q[3]) + end) + for _, c in tri do + table.move(c, 1, 3, #out + 1, out) + end + tri = {} + end + end + end + return out +end + +local function compare(a: any, b: any, label: string, eps: number) + local _, fa = counts(a) + local _, fb = counts(b) + t:eq(fb, fa, label .. ": triangles") + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + local ta = m.baseColorTexture and a.textures[m.baseColorTexture.texture] + local tb = m2.baseColorTexture and b.textures[m2.baseColorTexture.texture] + t:check((ta == nil) == (tb == nil) and (ta == nil or ta.uri == nil or ta.uri == tb.uri), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.skins, if #a.skins > 0 or #a.animations > 0 then 1 else 0, label .. ": skins (animated nodes become joints)") + if a.skins[1] then + t:eq(#b.skins[1].joints, #a.skins[1].joints, label .. ": joints") + end + -- the same posed triangles (the corners in order) at a few times + for _, time in { 0, 0.3, 0.75, 1.2, 2.5, 4 } do + local pa, pb = skinnedPositions(a, time), skinnedPositions(b, time) + local ok = #pa == #pb + local worst = 0 + if ok then + for k = 1, #pa do + local d = math.abs(pa[k] - pb[k]) / math.max(1, math.abs(pa[k])) + worst = math.max(worst, d) + end + end + t:check(ok and worst <= eps, string.format("%s: posed vertices at %.2f s (worst %.3g)", label, time, worst)) + if #a.animations == 0 then + break + end + end +end + +for i, c in Cases do + local scene = scenes[i] + if scene then + local out, err = Ms3d.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name, 1e-6) + t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes") + local same = true + for mi, m in scene.meshes do + same = same and back.meshes[mi].primitives[1].attributes.POSITION.count == m.primitives[1].attributes.POSITION.count + end + t:check(same, c.name .. ": vertices kept") + end + end +end + +local gltfScenes = {} +local ng = 0 +for gi, g in Picks do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + gltfScenes[gi] = scene + local out, err = Ms3d.encode(scene) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + local lines = false + for _, m in scene.meshes do + for _, p in m.primitives do + lines = lines or p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" + end + end + if not lines then + -- weights are stored in percent + compare(scene, back, "glTF " .. g.name, if #scene.skins > 0 then 1e-2 else 1e-4) + end + ng += 1 + end + end +end +t:note("%d reference files and %d glTF models through our writer and back", #Cases, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +local nx = 0 +for _, x in Xcheck do + local a = x.assimp + t:check(not a.failed, x.name .. ": assimp reads our file") + local scene = if x.case then scenes[x.case] else gltfScenes[x.gltf] + if scene and not a.failed then + local back = decode(Ms3d.encode(scene) :: buffer) + local prims, faces, corners = counts(back) + t:eq(a.meshes, prims, x.name .. ": assimp meshes of our file") + t:eq(a.faces, faces, x.name .. ": assimp faces of our file") + t:eq(a.vertices, corners, x.name .. ": assimp corners of our file") + t:eq(a.bones, bones(back), x.name .. ": assimp bones of our file") + t:eq(a.animations, if #back.nodes > #back.meshes then 1 else 0, x.name .. ": assimp animations of our file (it makes one for any joint)") + t:eq(a.materials, math.max(#back.materials, 1), x.name .. ": assimp materials of our file") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(back)) + t:check(lo and boundsEq(lo, hi, a, 1e-4), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max)) + end + nx += 1 + end +end +t:note("%d of our files read back by assimp", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local jeep = byName["assimp/jeep1.ms3d"] + if jeep then + local m = jeep.materials[1] + t:check(m.baseColorTexture and jeep.textures[1].uri ~= nil and jeep.textures[1].data == nil, "texture -> uri, not loaded: " .. tostring(jeep.textures[1].uri)) + t:eq(#jeep.meshes, 7, "jeep: 7 groups") + t:eq(jeep.meta.up, "y", "MilkShape is Y up") + t:check(jeep.meta.source.vertexVersion == nil, "jeep: no sub-versioned blocks") + end + local mats = byName["assimp/twospheres_withmats.ms3d"] + if mats then + t:eq(mats.meta.source.commentVersion, 1, "comment block") + t:eq(mats.meta.source.vertexVersion, 3, "vertex extras subversion 3") + t:check(mats.materials[2].extras.ms3d.shininess > 0, "shininess in extras") + end + -- a skinned scene by hand: two joints, comments, weights split between them + local gl = gltfScenes[3] + if gl then + local out = Ms3d.encode(gl) :: buffer + local back = decode(out) + t:check(back.skins[1] and #back.skins[1].joints == #gl.skins[1].joints, "joints written") + local W = back.meshes[1].primitives[1].attributes.WEIGHTS_0 + local R = S.reader(W) :: any + local split = false + for v = 0, W.count - 1 do + split = split or (R(v, 1) > 0.05) + t:check(math.abs(R(v, 0) + R(v, 1) + R(v, 2) + R(v, 3) - 1) < 1e-6, "weights sum to 1") + end + t:check(split, "vertex extras: second bone weights") + back.nodes[1].extras.ms3d.comment = "the root" + back.materials[1] = F.Types.Scene.material("m") + back.materials[1].extras = { ms3d = { comment = "a material" } } + back.meta.source.comment = "made by a test" + local again = decode(Ms3d.encode(back) :: buffer) + t:eq(again.nodes[1].extras.ms3d.comment, "the root", "joint comment") + t:eq(again.materials[1].extras.ms3d.comment, "a material", "material comment") + t:eq(again.meta.source.comment, "made by a test", "model comment") + end + local s = F.load(Cases[1].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "ms3d", "F.load detects MS3D") + local viaApi = F.save(s, nil, { format = "ms3d" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 10) == "MS3D000000", "F.save format ms3d") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local data = Cases[2].data + local _, e1 = decode(string.sub(data, 1, 100)) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local _, e2 = decode("MS3D000000\9\0\0\0") + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 9: " .. tostring(e2)) + local _, e3 = decode("MS3D000001") + t:check(e3 and e3.code == Err.CORRUPT, "bad magic: " .. tostring(e3)) + local _, e4 = decode(data, { maxVertices = 10 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Ms3d.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + t:eq(Ms3d.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + for gi, g in gltfScenes do + if gi <= 4 then + table.insert(samples, buffer.tostring(Ms3d.encode(g) :: buffer)) + end + end + t:fuzz("decode", function(b: buffer) + local s = Ms3d.decode(Bytes.reader(b)) + if s then + Ms3d.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 14 }) +end + +t:done() diff --git a/tools/fixtures/_ms3d_encode.luau b/tools/fixtures/_ms3d_encode.luau new file mode 100644 index 0000000..15977f6 --- /dev/null +++ b/tools/fixtures/_ms3d_encode.luau @@ -0,0 +1,44 @@ +-- tools/fixtures/_ms3d_encode: run by tools/fixtures/ms3d.py (luau CLI, repo root): decodes every MS3D case and every +-- glTF sample model with our readers and writes them with our MS3D writer, printing "\t" lines for assimp +-- to read back. Files: case_.ms3d, gltf_.ms3d. +local Ms3d = require("@formats/model/ms3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/ms3d_cases") +local Picks = require("@tests/gen/ms3d_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function emit(name: string, scene: any) + local out, err = Ms3d.encode(scene) + if out then + print(name .. "\t" .. hex(out)) + else + print("encode failed " .. name .. ": " .. tostring(err)) + end +end + +for i, c in Cases do + local scene, err = Ms3d.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + emit(string.format("case_%d.ms3d", i), scene) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end +for i, g in Picks do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + if scene then + emit(string.format("gltf_%d.ms3d", i), scene) + end +end diff --git a/tools/fixtures/ms3d.py b/tools/fixtures/ms3d.py new file mode 100644 index 0000000..611a48a --- /dev/null +++ b/tools/fixtures/ms3d.py @@ -0,0 +1,68 @@ +# MS3D fixtures (tools/fixtures.py): assimp's MilkShape 3D test models (test/models/MS3D: groups, materials, textures, +# version 4 with and without the sub-versioned blocks; read from the nixpkgs assimp source, never committed), with +# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, bones; world bounds +# from its PreTransformVertices export). No tool writes MS3D with joints, so skins and animation are checked through +# our writer: glTF sample models (skins, animation, textures) written by tools/fixtures/_ms3d_encode.luau and read +# back by assimp. +# tests/gen/ms3d_cases.luau { name, data, assimp } +# tests/gen/ms3d_gltf.luau glTF sample models: { name, data, files } +# tests/gen/ms3d_xcheck.luau { name, case? | gltf?, assimp } +import importlib.util, os + +INPUTS = ["src/Formats/model/ms3d", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/3ds.py", "tools/fixtures/_ms3d_encode.luau"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +GLTF = ("Box", "BoxTextured", "SimpleSkin", "RiggedSimple", "SimpleMeshes", "MultiUVTest", "NegativeScaleTest", + "AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes") + + +def generate(ctx): + M = load(ctx, "_model_ref") + X = load(ctx, "fbx") + R = load(ctx, "3ds") + tmp = M.tempdir() + d = os.path.join(X.assimp_src(ctx), "test", "models", "MS3D") + cases = [{"name": "assimp/" + f, "path": os.path.join(d, f)} for f in sorted(os.listdir(d)) if f.lower().endswith(".ms3d")] + for c, a in zip(cases, R.reference(ctx, M, X, [c["path"] for c in cases], tmp)): + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("ms3d_cases", cases) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + dd = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(dd)) if f.endswith(".gltf") or f.endswith(".glb")] if os.path.isdir(dd) else [] + if mains: + picks.append({"name": model + "/" + variant, "data": open(os.path.join(dd, mains[0]), "rb").read(), + "files": {f: open(os.path.join(dd, f), "rb").read() for f in sorted(os.listdir(dd)) if f != mains[0]}}) + break + ctx.emit("ms3d_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_ms3d_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".ms3d")) + paths = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + paths.append(p) + xs = [] + for n, a in zip(names, R.reference(ctx, M, X, paths, xtmp)): + kind, idx = n[:-5].split("_") + e = {"name": n, "assimp": a} + e["case" if kind == "case" else "gltf"] = int(idx) + xs.append(e) + ctx.emit("ms3d_xcheck", xs) From 4f2a388a6de2a6b3fc60be0842e3a75ababff9fc Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:34:06 -0500 Subject: [PATCH 27/54] ws-3d3: codecs/model/Draco: kd-tree point clouds (bitstream 2.3, levels 0 - 6) Byte-exact against libdraco on all 206 test files, kd-tree point clouds included. --- .../codecs/model/Draco/Attributes.luau | 12 +- src/Formats/codecs/model/Draco/KdTree.luau | 363 ++++++++++++++++++ src/Formats/codecs/model/Draco/init.luau | 19 +- tests/codecs/draco.luau | 13 +- 4 files changed, 388 insertions(+), 19 deletions(-) create mode 100644 src/Formats/codecs/model/Draco/KdTree.luau diff --git a/src/Formats/codecs/model/Draco/Attributes.luau b/src/Formats/codecs/model/Draco/Attributes.luau index 5b5b11f..ac5111f 100644 --- a/src/Formats/codecs/model/Draco/Attributes.luau +++ b/src/Formats/codecs/model/Draco/Attributes.luau @@ -9,6 +9,7 @@ local Reader = require("@formats/codecs/model/Draco/Reader") local Connectivity = require("@formats/codecs/model/Draco/Connectivity") local Predict = require("@formats/codecs/model/Draco/Predict") +local KdTree = require("@formats/codecs/model/Draco/KdTree") local Attributes = {} @@ -285,8 +286,6 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) -- prediction data: the attribute's own corner table when its seams are in use local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e } - elseif g.kdTree then - return nil, "unsupported: kd-tree point clouds" end decoders[i + 1] = dec end @@ -323,7 +322,7 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) table.insert(all, a) table.insert(dec.attrs, a) end - for _, a in dec.attrs do + for _, a in (if g.kdTree then {} else dec.attrs) do local t = Reader.u8(d) if d.bad then return nil, d.bad @@ -353,6 +352,13 @@ function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?) end -- decode for _, dec in decoders do + if g.kdTree then + local ok, err = KdTree.decode(d, dec.attrs, g.numPoints) + if not ok then + return nil, err + end + continue + end local points: { number } local trav = dec.traversal if trav then diff --git a/src/Formats/codecs/model/Draco/KdTree.luau b/src/Formats/codecs/model/Draco/KdTree.luau new file mode 100644 index 0000000..9091e3e --- /dev/null +++ b/src/Formats/codecs/model/Draco/KdTree.luau @@ -0,0 +1,363 @@ +--!strict +-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder +-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the +-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from +-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/ +-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0, +-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported. +local Reader = require("@formats/codecs/model/Draco/Reader") +local Predict = require("@formats/codecs/model/Draco/Predict") + +local KdTree = {} + +type D = Reader.D + +-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out +type Src = { next: () -> number, bits: (n: number) -> number? } + +local function direct(d: D): Src? + local size = Reader.u32(d) + if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then + Reader.fail(d, "kd-tree: bad direct bits") + return nil + end + local b, base, words = d.b, d.pos, size // 4 + d.pos += size + local pos, used = 0, 0 + return { + next = function(): number + if pos >= words then + return 0 + end + local w = buffer.readu32(b, base + pos * 4) + local bit = bit32.extract(w, 31 - used) + used += 1 + if used == 32 then + pos += 1 + used = 0 + end + return bit + end, + bits = function(n: number): number? + local remaining = 32 - used + if n <= remaining then + if pos >= words then + return nil + end + local w = buffer.readu32(b, base + pos * 4) + local v = bit32.extract(w, 32 - used - n, n) + used += n + if used == 32 then + pos += 1 + used = 0 + end + return v + end + if pos + 1 >= words then + return nil + end + local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining) + local lo = n - remaining + pos += 1 + used = lo + local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo) + return hiBits * 2 ^ lo + loBits + end, + } +end + +local function rans(d: D): Src? + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + local function nextBit(): number + return if Reader.bit(bd) then 1 else 0 + end + return { + next = nextBit, + bits = function(n: number): number? + local v = 0 + for _ = 1, n do + v = v * 2 + nextBit() + end + return v + end, + } +end + +local function folded(d: D): Src? + local parts: { Reader.Bits } = {} + for i = 1, 32 do + local bd = Reader.bitDecoder(d) + if not bd then + return nil + end + parts[i] = bd + end + local main = Reader.bitDecoder(d) + if not main then + return nil + end + return { + next = function(): number + return if Reader.bit(main :: Reader.Bits) then 1 else 0 + end, + bits = function(n: number): number? + local v = 0 + for i = 1, n do + v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0) + end + return v + end, + } +end + +local function msb(n: number): number + local k = -1 + while n >= 1 do + n = n // 2 + k += 1 + end + return k +end + +-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil +local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?) + local bitLength = Reader.u32(d) + local numPoints = Reader.u32(d) + if d.bad then + return nil, d.bad + end + if bitLength > 32 then + return nil, "kd-tree: bad bit length" + end + if numPoints ~= expected then + return nil, "kd-tree: point count mismatch" + end + local out: { { number } } = {} + if numPoints == 0 then + return out, nil + end + local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d) + local remainingBits = numbers and direct(d) + local axisDec = remainingBits and direct(d) + local half = axisDec and direct(d) + if not numbers or not remainingBits or not axisDec or not half then + return nil, d.bad or "kd-tree: bad bit decoders" + end + local selectAxis = level >= 6 + local zero = table.create(dim, 0) + local baseStack: { { number } } = { table.clone(zero) } + local levelStack: { { number } } = { table.clone(zero) } + local stack = { { numPoints, 0, 0 } } + local decoded = 0 + local p = table.create(dim, 0) + while #stack > 0 do + local st = stack[#stack] + stack[#stack] = nil + local n, lastAxis, sp = st[1], st[2], st[3] + local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1] + if n > numPoints then + return nil, "kd-tree: bad point count" + end + local axis + if not selectAxis then + axis = if lastAxis == dim - 1 then 0 else lastAxis + 1 + elseif n < 64 then + axis = 0 + for a = 1, dim - 1 do + if levels[axis + 1] > levels[a + 1] then + axis = a + end + end + else + axis = (axisDec :: Src).bits(4) or 0 + end + if axis >= dim then + return nil, "kd-tree: bad axis" + end + local lvl = levels[axis + 1] + if bitLength - lvl == 0 then + for _ = 1, n do + table.insert(out, table.clone(oldBase)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if n <= 2 then + for _ = 1, n do + local a = axis + for _ = 1, dim do + local rb = bitLength - levels[a + 1] + local v = 0 + if rb > 0 then + local got = remainingBits.bits(rb) + if got == nil then + return nil, "kd-tree: remaining bits run out" + end + v = got + end + p[a + 1] = bit32.bor(oldBase[a + 1], v) + a = if a == dim - 1 then 0 else a + 1 + end + table.insert(out, table.clone(p)) + decoded += 1 + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + continue + end + if decoded > numPoints then + return nil, "kd-tree: too many points" + end + local rbits = bitLength - lvl + local modifier = 2 ^ (rbits - 1) + local nb = table.clone(oldBase) + nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296 + baseStack[sp + 2] = nb + local number = numbers.bits(msb(n)) or 0 + local first = n // 2 + if first < number then + return nil, "kd-tree: bad split" + end + first -= number + local second = n - first + if first ~= second and half.next() == 0 then + first, second = second, first + end + levels[axis + 1] += 1 + levelStack[sp + 2] = table.clone(levels) + if sp + 2 > 32 * dim + 1 then + return nil, "kd-tree: too deep" + end + if first > 0 then + table.insert(stack, { first, axis, sp }) + end + if second > 0 then + table.insert(stack, { second, axis, sp + 1 }) + end + end + if decoded ~= expected then + return nil, "kd-tree: point count mismatch" + end + return out, nil +end + +local SIGNED = { [1] = 8, [3] = 16, [5] = 32 } + +-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues) +function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?) + if d.ver < 0x0203 then + return false, "unsupported: kd-tree point clouds before bitstream 2.3" + end + local level = Reader.u8(d) + if d.bad then + return false, d.bad + end + if level > 6 then + return false, "kd-tree: bad compression level" + end + local dim = 0 + for _, a in attrs do + local dt = a.dataType + if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then + return false, "unsupported: kd-tree attribute of data type " .. dt + end + dim += a.comps + end + local points, err = decodePoints(d, level, dim, numPoints) + if not points then + return false, err + end + -- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types + local off = 0 + for _, a in attrs do + local comps = a.comps + local vals = table.create(numPoints * comps, 0) + local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296 + local raw = a.dataType == 9 + for i, pt in points do + for c = 1, comps do + local v = pt[off + c] + vals[(i - 1) * comps + c] = if raw then v else v % mod + end + end + a.portable = vals + a.values = vals + a.numValues = numPoints + a.map = nil + off += comps + end + -- the data needed by the transforms: f32 quantization, then the signed minima + for _, a in attrs do + if a.dataType == 9 then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + mins[c] = Reader.f32(d) + end + local range = Reader.f32(d) + local bits = Reader.u8(d) + if d.bad or bits < 1 or bits > 30 then + return false, d.bad or "kd-tree: bad quantization" + end + a.quant = { min = mins, range = range, bits = bits } + end + end + for _, a in attrs do + if SIGNED[a.dataType] then + local mins = table.create(a.comps, 0) + for c = 1, a.comps do + local v = Reader.varint(d) + mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2 + end + if d.bad then + return false, d.bad + end + a.signedMin = mins + end + end + -- back to the original values + local fround = Predict.fround + for _, a in attrs do + local vals = a.portable :: { number } + local comps = a.comps + if a.dataType == 9 then + local q = a.quant + local delta = fround(q.range / fround(2 ^ q.bits - 1)) + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local v = vals[i] + if v >= 2147483648 then + v -= 4294967296 + end + out[i] = fround(fround(fround(v) * delta) + q.min[c]) + end + a.values = out + elseif SIGNED[a.dataType] then + -- the C++ reads the stored (already narrowed) unsigned values back + local bits = SIGNED[a.dataType] + local mins = a.signedMin + local out = table.create(#vals, 0) + for i = 1, #vals do + local c = (i - 1) % comps + 1 + local u = vals[i] + if u > 2147483647 then + return false, "kd-tree: signed value out of range" + end + local s = Predict.i32(u + mins[c]) + local m = 2 ^ bits + out[i] = (s + m / 2) % m - m / 2 + end + a.values = out + end + end + return true, nil +end + +return KdTree diff --git a/src/Formats/codecs/model/Draco/init.luau b/src/Formats/codecs/model/Draco/init.luau index fd994e2..1e54287 100644 --- a/src/Formats/codecs/model/Draco/init.luau +++ b/src/Formats/codecs/model/Draco/init.luau @@ -3,11 +3,12 @@ -- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range. -- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions -- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology --- splits, attribute seams) and sequential point clouds; attribute decoders generic / integer / quantization / --- octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, constrained --- multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal octahedron --- transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the dequantization). --- Not supported: kd-tree point clouds (Err.UNSUPPORTED). +-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic / +-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram, +-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal +-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the +-- dequantization). +-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED). -- -- local Draco = require("@formats/codecs/model/Draco") -- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string @@ -262,12 +263,10 @@ local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, end numPoints = m.numPoints else - if h.method == 1 then - return nil, "unsupported: kd-tree point clouds", nil - elseif h.method ~= 0 then + if h.method > 1 then return nil, "unsupported: point cloud encoding method " .. h.method, nil end - method = "sequential" + method = if h.method == 1 then "kdtree" else "sequential" numPoints = Reader.i32(d) if d.bad then return nil, d.bad, nil @@ -279,7 +278,7 @@ local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, if numPoints > maxPoints then return nil, "too many points", "limit" end - local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = false }) + local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" }) if not attrs then return nil, aerr, nil end diff --git a/tests/codecs/draco.luau b/tests/codecs/draco.luau index d7098a7..de172ea 100644 --- a/tests/codecs/draco.luau +++ b/tests/codecs/draco.luau @@ -1,7 +1,7 @@ -- codecs/model/Draco tests: Google's Draco test data (bitstreams 0.9 - 2.2) and files encoded by draco_encoder 1.5.7 -- at every compression level, quantization and as point clouds, decoded and compared byte for byte (points, faces, --- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc); kd-tree --- point clouds report UNSUPPORTED; argument errors; the fuzz no-throw pass (which also fails on any internal error the +-- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc), kd-tree +-- point clouds included; argument errors; the fuzz no-throw pass (which also fails on any internal error the -- decoder's safety net caught). Fixtures: tools/fixtures/draco.py. local T = require("@tests/T") local Draco = require("@formats/codecs/model/Draco") @@ -11,15 +11,13 @@ local Cases = require("@tests/gen/draco_cases") local t = T.suite("draco") -local counts = { exact = 0, unsupported = 0, rejected = 0 } +local counts = { exact = 0, rejected = 0, kd = 0 } local samples = {} for _, c in Cases do local g, err = Draco.decode(c.data) if c.error then t:check(g == nil and err ~= nil, c.name .. ": libdraco rejects it, so do we") counts.rejected += 1 - elseif not g and err and err.code == Err.UNSUPPORTED and string.find(err.message, "kd-tree", 1, true) then - counts.unsupported += 1 else t:check(g, c.name .. ": decode: " .. tostring(err)) if g then @@ -41,13 +39,16 @@ for _, c in Cases do end end counts.exact += 1 + if g.method == "kdtree" then + counts.kd += 1 + end if #c.data < 4000 then table.insert(samples, c.data) end end end end -t:note("%d files decoded exactly like libdraco, %d kd-tree point clouds unsupported, %d rejected by both", counts.exact, counts.unsupported, counts.rejected) +t:note("%d files decoded exactly like libdraco (%d kd-tree point clouds), %d rejected by both", counts.exact, counts.kd, counts.rejected) -- the attribute lookup and the header local first = Cases[1] From bf639260e4cbb2dca13967c06fdecdab8a487b73 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:39 -0500 Subject: [PATCH 28/54] video/smk: Smacker (SMK2 / SMK4) with its video codec and audio containers into containers/Demux (palette updates ride on each video packet as packet.palette); the Smacker video codec (header Huffman trees with the escape cache, MONO / FULL (+ SMK4 doubled modes) / SKIP / FILL blocks) lives in codecs/video/Legacy/Smacker and registers as 'smackvid'; Smacker's packed DPCM-Huffman audio (8 / 16-bit, mono / stereo) and raw PCM tracks decode in video/smk/Audio, the Decoder built by the format over codecs/audio/Stream (Smk.openAudio; open() installs it as the openAudio hook). Fixtures encoded by tools/fixtures/smk.py: video and audio bit-exact with ffmpeg. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Legacy/Smacker.luau | 363 ++++++++++++++ src/Formats/codecs/video/Legacy/init.luau | 33 +- src/Formats/video/smk/Audio.luau | 123 +++++ src/Formats/video/smk/init.luau | 320 ++++++++++++ tests/video/smk.luau | 180 +++++++ tools/fixtures/smk.py | 493 +++++++++++++++++++ 8 files changed, 1522 insertions(+), 3 deletions(-) create mode 100644 src/Formats/codecs/video/Legacy/Smacker.luau create mode 100644 src/Formats/video/smk/Audio.luau create mode 100644 src/Formats/video/smk/init.luau create mode 100644 tests/video/smk.luau create mode 100644 tools/fixtures/smk.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 13d1e91..8b27918 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -34,6 +34,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | smk | .smk | yes | - | streaming: true, video: "smackvid", audio: "smackaudio", "pcm_u8", "pcm_s16le" | `tests/video/smk.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d26e1e1..ad48ba9 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -362,6 +362,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "smk", + category = "video", + path = "video/smk", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, + load = function() + return require("@formats/video/smk") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau new file mode 100644 index 0000000..c5923ec --- /dev/null +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -0,0 +1,363 @@ +--!strict +--!native +--!optimize 2 +-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and +-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are +-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); +-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte +-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a +-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; +-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a +-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give +-- zero bits, a frame whose codes run out of bits gives no picture. +local Picture = require("@formats/codecs/video/Legacy/Picture") + +local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local band, rshift = bit32.band, bit32.rshift + +local Smacker = {} + +local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder) +local MAX_DEPTH16 = 500 + +-- block runs (TYPE code bits 2..7) +local RUNS = table.create(64, 0) +for i = 1, 59 do + RUNS[i] = i +end +RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 + +-- a bit position over buf[0, nbits / 8) +export type Bits = { buf: buffer, pos: number, nbits: number } + +function Smacker.bits(buf: buffer, offset: number, length: number): Bits + return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 } +end + +local function bit(br: Bits): number + local p = br.pos + br.pos = p + 1 + if p >= br.nbits then + return 0 + end + return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1) +end +Smacker.bit = bit + +-- read(br, n) -> n bits (LSB first; zeros past the end) +function Smacker.read(br: Bits, n: number): number + local v, m = 0, 1 + for _ = 1, n do + v += bit(br) * m + m *= 2 + end + return v +end +local readBits = Smacker.read + +-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) +local function walk(tree: { number }, br: Bits): number + local i = 1 + local e = tree[1] + while e < 0 do + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = tree[i] + end + return e +end +Smacker.walk = walk + +-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based) +local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) + local vals: { number } = {} + local n = 0 + local stack: { number } = {} + local state: { number } = {} + local sp = 0 + while true do + if sp > maxDepth then + return nil, "tree too deep" + end + if n >= maxEntries then + return nil, "tree too big" + end + if bigChecks and br.pos >= br.nbits then + return nil, "truncated tree" + end + if bit(br) == 1 then + n += 1 + vals[n] = -1 + sp += 1 + stack[sp], state[sp] = n, 0 + else + local v, msg = leaf(n) + if not v then + return nil, msg + end + n += 1 + vals[n] = v + local more = false + while sp > 0 do + if state[sp] == 0 then + local at = stack[sp] + vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries + state[sp] = 1 + more = true + break + end + sp -= 1 + end + if not more then + return vals, nil + end + end + end +end + +-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message +function Smacker.tree8(br: Bits): ({ number }?, string?) + local leaves = 0 + return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) + if leaves >= 256 then + return nil, "tree too big" + end + leaves += 1 + if br.nbits - br.pos < 8 then + return nil, "truncated tree" + end + return readBits(br, 8), nil + end, false) +end +local tree8 = Smacker.tree8 + +export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) + +-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) +local function bigTree(br: Bits, size: number): (BigTree?, string?) + if bit(br) == 0 then + return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 + end + local lohi: { { number } } = {} + for k = 1, 2 do + if bit(br) == 0 then + lohi[k] = { 0 } + else + local t, msg = tree8(br) + if not t then + return nil, msg + end + bit(br) + lohi[k] = t + end + end + local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) } + local last = { -1, -1, -1 } + local lo, hi = lohi[1], lohi[2] + local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?) + local v = walk(lo, br) + walk(hi, br) * 256 + for k = 1, 3 do + if v == esc[k] then + last[k] = index + 1 + return 0, nil + end + end + return v, nil + end, true) + if not vals then + return nil, msg + end + bit(br) + for k = 1, 3 do + if last[k] == -1 then + table.insert(vals, 0) + last[k] = #vals + end + end + return { vals = vals, last = last }, nil +end + +export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } + +-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits +function Smacker.trees(config: buffer): (Trees?, string?) + local n = buffer.len(config) + if n <= 16 then + return nil, "no trees" + end + local br = Smacker.bits(config, 16, n - 16) + local out: { BigTree } = {} + local present = 0 + for k = 1, 4 do + local size = buffer.readu32(config, (k - 1) * 4) + if size >= 2 ^ 28 then + return nil, "tree size too large" + end + local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1 + local t, msg = bigTree(br, size) + if not t then + return nil, msg + end + if here then + present += 1 + end + out[k] = t + end + if present == 0 or br.pos > br.nbits then + return nil, "bad trees" + end + return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil +end + +-- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree +local function code(t: BigTree, br: Bits): number? + local vals = t.vals + local i = 1 + local e = vals[1] + while e < 0 do + if br.pos >= br.nbits then + return nil + end + if bit(br) == 1 then + i += -e - 1 + end + i += 1 + e = vals[i] + end + local last = t.last + local l0, l1, l2 = last[1], last[2], last[3] + if e ~= vals[l0] then + vals[l2] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e +end + +local function reset(t: BigTree) + local vals, last = t.vals, t.last + vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 +end + +-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4 +function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) + local px = pic.idx :: buffer + local stride = pic.stride + local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type + reset(mmap) + reset(mclr) + reset(full) + reset(typ) + local br = Smacker.bits(d, 0, buffer.len(d)) + local bw, bh = pic.w // 4, pic.h // 4 + local blocks = bw * bh + local blk = 0 + while blk < blocks do + local ty = code(typ, br) + if not ty then + return false, "truncated frame" + end + local run = RUNS[band(rshift(ty, 2), 63) + 1] + local kind = band(ty, 3) + if kind == 2 then + blk = math.min(blocks, blk + run) + elseif kind == 3 then + local v = rshift(ty, 8) * 0x01010101 + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + writeu32(px, o, v) + writeu32(px, o + stride, v) + writeu32(px, o + 2 * stride, v) + writeu32(px, o + 3 * stride, v) + blk += 1 + end + elseif kind == 0 then + for _ = 1, run do + if blk >= blocks then + break + end + local clr = code(mclr, br) + local map = code(mmap, br) + if not clr or not map then + return false, "truncated frame" + end + local hi, lo = rshift(clr, 8), band(clr, 255) + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + for r = 0, 3 do + local q = o + r * stride + writeu8(px, q, if band(map, 1) ~= 0 then hi else lo) + writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo) + writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo) + writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo) + map = rshift(map, 4) + end + blk += 1 + end + else + local mode = 0 + if v4 then + if br.pos >= br.nbits then + return false, "truncated frame" + end + if bit(br) == 1 then + mode = 1 + elseif bit(br) == 1 then + mode = 2 + end + end + for _ = 1, run do + if blk >= blocks then + break + end + local o = (blk // bw) * stride * 4 + (blk % bw) * 4 + if mode == 0 then + for r = 0, 3 do + local a = code(full, br) + local b = code(full, br) + if not a or not b then + return false, "truncated frame" + end + local q = o + r * stride + writeu8(px, q + 2, band(a, 255)) + writeu8(px, q + 3, rshift(a, 8)) + writeu8(px, q, band(b, 255)) + writeu8(px, q + 1, rshift(b, 8)) + end + elseif mode == 1 then + for half = 0, 1 do + local a = code(full, br) + if not a then + return false, "truncated frame" + end + local lo, hi = band(a, 255), rshift(a, 8) + local v = lo * 0x0101 + hi * 0x01010000 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + else + for half = 0, 1 do + local p2 = code(full, br) + local p1 = code(full, br) + if not p1 or not p2 then + return false, "truncated frame" + end + local v = p1 + p2 * 65536 + writeu32(px, o + half * 2 * stride, v) + writeu32(px, o + (half * 2 + 1) * stride, v) + end + end + blk += 1 + end + end + end + return true, nil +end + +return Smacker diff --git a/src/Formats/codecs/video/Legacy/init.luau b/src/Formats/codecs/video/Legacy/init.luau index 51729a4..f73885d 100644 --- a/src/Formats/codecs/video/Legacy/init.luau +++ b/src/Formats/codecs/video/Legacy/init.luau @@ -3,7 +3,8 @@ -- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk -- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", -- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation --- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey) and QuickTime Graphics ("smc", 'smc '). +-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker +-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4). -- New in formats-luau, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's -- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns -- a fresh copy. @@ -13,7 +14,7 @@ -- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth). -- -- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder --- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } -- -- Never throws: bad tracks return nil, Err; bad packets return Err from decode(). local Err = require("@formats/core/Err") @@ -24,6 +25,7 @@ local Cinepak = require("@formats/codecs/video/Legacy/Cinepak") local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1") local QtRle = require("@formats/codecs/video/Legacy/QtRle") local Smc = require("@formats/codecs/video/Legacy/Smc") +local Smacker = require("@formats/codecs/video/Legacy/Smacker") local Legacy = {} @@ -33,7 +35,8 @@ Legacy.Cinepak = Cinepak Legacy.Msvideo1 = Msvideo1 Legacy.QtRle = QtRle Legacy.Smc = Smc -Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc" } +Legacy.Smacker = Smacker +Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } export type Options = { maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) @@ -124,6 +127,30 @@ local CODECS: { [string]: Codec } = { return Picture.image(st.pic), nil end, }, + smackvid = { + make = function(t) + local cfg = t.config + if type(cfg) ~= "buffer" then + return nil, "no Smacker trees" + end + local trees, msg = Smacker.trees(cfg) + if not trees then + return nil, msg + end + return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil + end, + step = function(st, data, packet) + packetPalette(st.pic, packet) + if buffer.len(data) == 0 then + return nil, fail("empty frame") + end + local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4) + if not ok then + return nil, fail(msg) + end + return Picture.image(st.pic), nil + end, + }, flic = { make = function(t) return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8) diff --git a/src/Formats/video/smk/Audio.luau b/src/Formats/video/smk/Audio.luau new file mode 100644 index 0000000..2da8993 --- /dev/null +++ b/src/Formats/video/smk/Audio.luau @@ -0,0 +1,123 @@ +--!strict +--!native +--!optimize 2 +-- video/smk/Audio: Smacker's packed audio (SMKA: DPCM with Huffman-coded deltas), the one audio codec only Smacker +-- files carry. Written from the format description (MultimediaWiki "Smacker"). A packet: the unpacked size (u32), +-- then LSB-first bits: data flag, stereo, 16-bit, one 8-bit Huffman tree per channel and byte (codecs/video/Legacy/ +-- Smacker trees: 1, 2 or 4), the first sample(s) raw (16-bit ones byte-swapped, the right channel first), then per +-- sample a delta added with wraparound (the low byte's tree, and the high byte's for 16 bits). Raw PCM tracks (u8 / +-- s16le) are converted here too. Output: interleaved floats (u8: (v - 128) / 128, s16: v / 32768), as ffmpeg gives +-- them. Never throws: trees are bounded and every read past the packet gives zero bits. +local Smacker = require("@formats/codecs/video/Legacy/Smacker") + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +local Audio = {} + +-- decode(data, channels, bits, packed) -> frames, floats (1-based interleaved) | nil, message +function Audio.decode(d: buffer, channels: number, bits: number, packed: boolean): (number?, { number } | string) + local n = buffer.len(d) + if not packed then + local bps = bits // 8 + local frames = n // (bps * channels) + local count = frames * channels + local out = table.create(count, 0) + if bps == 1 then + for i = 0, count - 1 do + out[i + 1] = (readu8(d, i) - 128) / 128 + end + else + for i = 0, count - 1 do + out[i + 1] = readi16(d, i * 2) / 32768 + end + end + return frames, out + end + if n <= 4 then + return nil, "packet too small" + end + local size = buffer.readu32(d, 0) + if size > 2 ^ 24 then + return nil, "packet too big" + end + local br = Smacker.bits(d, 4, n - 4) + local bit, read, walk = Smacker.bit, Smacker.read, Smacker.walk + if bit(br) == 0 then + return 0, {} -- no data + end + local stereo = bit(br) + local wide = bit(br) + if (stereo == 1) ~= (channels == 2) or (wide == 1) ~= (bits == 16) then + return nil, "packet does not match the track's format" + end + local bytes = wide + 1 + local ch = stereo + 1 + if size % (ch * bytes) ~= 0 then + return nil, "unpacked size is not a whole number of samples" + end + local trees: { { number } } = {} + for k = 1, 2 ^ (wide + stereo) do + bit(br) + local t, msg = Smacker.tree8(br) + if not t then + return nil, msg or "bad tree" + end + bit(br) + trees[k] = t + end + if br.nbits - br.pos < ch * bytes * 8 then + return nil, "truncated packet" + end + -- whether any tree needs bits (else every delta is a constant and no end check applies) + local coded = false + for _, t in trees do + if #t > 1 then + coded = true + end + end + local frames = size // (ch * bytes) + local total = frames * ch + local out = table.create(total, 0) + if wide == 1 then + local pred = { 0, 0 } + for c = ch, 1, -1 do + local v = read(br, 16) + pred[c] = (v // 256) + (v % 256) * 256 + end + for c = 1, math.min(ch, total) do + local v = pred[c] + out[c] = (if v >= 32768 then v - 65536 else v) / 32768 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if coded and br.pos > br.nbits then + return nil, "truncated packet" + end + local lo = walk(trees[2 * c + 1], br) + local hi = walk(trees[2 * c + 2], br) + local v = (pred[c + 1] + lo + hi * 256) % 65536 + pred[c + 1] = v + out[i + 1] = (if v >= 32768 then v - 65536 else v) / 32768 + end + else + local pred = { 0, 0 } + for c = ch, 1, -1 do + pred[c] = read(br, 8) + end + for c = 1, math.min(ch, total) do + out[c] = (pred[c] - 128) / 128 + end + for i = ch, total - 1 do + local c = if ch == 2 then i % 2 else 0 + if br.pos > br.nbits then + return nil, "truncated packet" + end + local v = (pred[c + 1] + walk(trees[c + 1], br)) % 256 + pred[c + 1] = v + out[i + 1] = (v - 128) / 128 + end + end + return frames, out +end + +return Audio diff --git a/src/Formats/video/smk/init.luau b/src/Formats/video/smk/init.luau new file mode 100644 index 0000000..11c4c45 --- /dev/null +++ b/src/Formats/video/smk/init.luau @@ -0,0 +1,320 @@ +--!strict +-- video/smk: RAD Game Tools' Smacker video (SMK2 and SMK4). New in formats-luau, written from the format description +-- (MultimediaWiki "Smacker"). +-- Read: the header (size, frame count, frame time: > 0 ms, < 0 units of 10 us; the ring-frame flag), up to 7 audio +-- tracks (rate, packed / 16-bit / stereo flags), the frame sizes and flags, the four Huffman trees; per frame a palette +-- update (skip / copy-from-old / new 6-bit entries), the audio chunks and the video data, into a Demuxer. open() +-- returns a VideoDecoder: rgba8 frames from the Smacker video codec (codecs/video/Legacy/Smacker, through the +-- codecs/video/Video registry: the frame's palette rides on each packet as packet.palette), and the first audio +-- track as an audio Decoder built here (Smacker's packed DPCM audio has no audio format, so the format decodes it +-- itself: video/smk/Audio over codecs/audio/Stream; raw u8 / s16le tracks too). The ring frame (the extra frame that +-- leads back to the first) is not shown unless opts.ringFrame. Smk.demux(r) gives the Demuxer; Smk.openAudio(dmx, +-- track) the Decoder of any of its audio tracks. +-- Not supported: writing, Bink audio tracks (flags 0x08 / 0x04: reported as "binkaudio", no decoder). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/video/Video") +local Stream = require("@formats/codecs/audio/Stream") +local Audio = require("@formats/video/smk/Audio") + +-- ------------------------------------------------------------------------------------------------ contract +local Smk = { + name = "smk", + category = "video", + extensions = { "smk" }, + mime = { "video/vnd.radgamettools.smacker" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/video/Video", "codecs/audio/Stream", "codecs/video/Legacy/Smacker" }, + caps = { decode = true, encode = false, streaming = true, video = { "smackvid" }, audio = { "smackaudio", "pcm_u8", "pcm_s16le" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- (frames are rgba8 already) + maxPixels: number?, -- default 2^26 + audio: boolean?, -- false: do not open the audio track + ringFrame: boolean?, -- true: also show the ring frame at the end (as ffmpeg does) + openAudio: any?, -- the api's hook: used only for tracks this format cannot decode (Bink audio) +} + +-- ------------------------------------------------------------------------------------------------ constants +local HEADER = 104 +local RING = 1 +-- 6-bit palette components -> 8 bits (bit replication: v << 2 | v >> 4) +local PAL6 = table.create(64, 0) +for i = 0, 63 do + PAL6[i + 1] = i * 4 + i // 16 +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Smk.sniff(r: Bytes.Reader): number + local s = r:peek(4) + if s ~= "SMK2" and s ~= "SMK4" then + return 0 + end + return 1 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- a frame's palette update over the previous palette (pal: 256 u32 R, G, B, A); false when malformed +local function palette(b: buffer, p: number, stop: number, old: buffer): (buffer?) + local pal = buffer.create(1024) + buffer.copy(pal, 0, old, 0, 1024) + local function u8(): number + local v = if p < stop then buffer.readu8(b, p) else 0 + p += 1 + return v + end + local sz = 0 + while sz < 256 do + local t = u8() + if t >= 0x80 then + sz += t - 0x80 + 1 + elseif t >= 0x40 then + local off = u8() + local j = t - 0x40 + 1 + if off + j > 256 then + return nil + end + while j > 0 and sz < 256 do + buffer.writeu32(pal, sz * 4, buffer.readu32(old, off * 4)) + sz += 1 + off += 1 + j -= 1 + end + else + local r = PAL6[t + 1] + local g = PAL6[u8() % 64 + 1] + local bl = PAL6[u8() % 64 + 1] + buffer.writeu32(pal, sz * 4, r + g * 256 + bl * 65536 + 0xFF000000) + sz += 1 + end + end + return pal +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function Smk.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < HEADER then + return nil, Err.new(Err.TRUNCATED, "file shorter than the header") + end + local hr = Bytes.reader(b, base, HEADER) + local magic = hr:string(4) + local w, h, frames = hr:u32le(), hr:u32le(), hr:u32le() + local ptsInc = hr:i32le() + local flags = hr:u32le() + hr:skip(28) + local treeSize = hr:u32le() + local sizes = { hr:u32le(), hr:u32le(), hr:u32le(), hr:u32le() } + local rates, aflags = {}, {} + for k = 1, 7 do + rates[k] = hr:u24le() + aflags[k] = hr:u8() + end + if hr.err then + return nil, hr.err + end + if magic ~= "SMK2" and magic ~= "SMK4" then + return nil, Err.new(Err.CORRUPT, "not a Smacker file") + end + if w == 0 or h == 0 or w > 32768 or h > 32768 then + return nil, Err.new(Err.CORRUPT, "bad picture size") + end + local max = (opts and opts.maxPixels) or 2 ^ 26 + if w * h > max then + return nil, Err.new(Err.LIMIT, w .. " x " .. h .. " over maxPixels") + end + local shown = frames + if bit32.band(flags, RING) ~= 0 then + frames += 1 + end + local p = base + HEADER + if frames > 0xFFFFFF or p + frames * 5 + treeSize > limit then + return nil, Err.new(Err.TRUNCATED, "frame tables or trees past the end of the file") + end + -- the trees (with the four sizes in front, as the video codec takes them) + local config = buffer.create(16 + treeSize) + for k = 1, 4 do + buffer.writeu32(config, (k - 1) * 4, sizes[k]) + end + buffer.copy(config, 16, b, p + frames * 5, treeSize) + -- frame time: > 0 ms, < 0 units of 10 us (ticks of 1/100000 s) + local tick = if ptsInc < 0 then -ptsInc elseif ptsInc > 0 then ptsInc * 100 else 10000 + local tracks: { Types.Track } = { + { + id = 1, + kind = "video", + codec = "smackvid", + codecTag = magic, + timescale = 100000, + width = w, + height = h, + frameRate = 100000 / tick, + default = true, + config = config, + flags = flags, + } :: Types.Track, + } + local audio: { [number]: Types.Track } = {} + for k = 1, 7 do + if rates[k] > 0 then + local f = aflags[k] + local bits = if bit32.band(f, 0x20) ~= 0 then 16 else 8 + local codec = if bit32.band(f, 0x0C) ~= 0 then "binkaudio" + elseif bit32.band(f, 0x80) ~= 0 then "smackaudio" + elseif bits == 16 then "pcm_s16le" + else "pcm_u8" + local t: Types.Track = { + id = k + 1, + kind = "audio", + codec = codec, + codecTag = string.format("0x%02X", f), + timescale = rates[k], + sampleRate = rates[k], + channels = if bit32.band(f, 0x10) ~= 0 then 2 else 1, + bitsPerSample = bits, + default = #tracks == 1, + } + audio[k] = t + table.insert(tracks, t) + end + end + local dmx = Demux.new("smk", tracks, b, { version = magic, flags = flags, frames = shown, ringFrame = frames > shown }) + local count = if opts and opts.ringFrame then frames else shown + local pal = buffer.create(1024) + local apts = { 0, 0, 0, 0, 0, 0, 0 } + local at = p + frames * 5 + treeSize + for i = 0, frames - 1 do + local fsize = buffer.readu32(b, p + i * 4) + local fflags = buffer.readu8(b, p + frames * 4 + i) + local size = fsize - fsize % 4 + local q, stop = at, math.min(limit, at + size) + at += size + local ok = true + if fflags % 2 == 1 and q < stop then + local psize = buffer.readu8(b, q) * 4 + if psize > size then + ok = false + else + local np = palette(b, q + 1, math.min(stop, q + psize), pal) + if np then + pal = np + else + ok = false + end + q += psize + end + end + for k = 1, 7 do + if not ok then + break + end + if bit32.band(fflags, 2 ^ k) ~= 0 then + if q + 4 > stop then + ok = false + break + end + local asize = buffer.readu32(b, q) + local t = audio[k] + local min = if t and t.codec ~= "pcm_s16le" then 8 else 4 + if asize < min or q + asize > stop then + ok = false + break + end + if t then + local len = asize - 4 + local frameBytes = (t.channels :: number) * (t.bitsPerSample :: number) // 8 + local n = if t.codec == "smackaudio" then buffer.readu32(b, q + 4) // frameBytes + elseif t.codec == "binkaudio" then 0 + else len // frameBytes + dmx:add(t.id, apts[k], nil, n, true, q + 4, len) + apts[k] += n + end + q += asize + end + end + if ok and i < count then + dmx:add(1, i * tick, nil, tick, i == 0 or fsize % 2 == 1, q, math.max(0, stop - q)) + dmx:setExtra("palette", pal) + end + end + dmx:finish() + return dmx, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- openAudio(dmx, track) -> an audio Decoder for one of the demuxer's audio tracks | nil, Err +function Smk.openAudio(dmx: any, track: Types.Track): (Types.Decoder?, Err.Err?) + local codec = track.codec + if codec ~= "smackaudio" and codec ~= "pcm_u8" and codec ~= "pcm_s16le" then + return nil, Err.new(Err.UNSUPPORTED, "audio codec " .. codec) + end + local id = track.id + local count = dmx:count(id) + local starts: { number } = {} + local total = 0 + for k = 1, count do + local pts, _, dur = dmx:info(id, k) + starts[k] = pts or total + total = (pts or total) + (dur or 0) + end + starts[count + 1] = total + local rate, ch, bits = track.sampleRate :: number, track.channels :: number, track.bitsPerSample :: number + local packed = codec == "smackaudio" + local floats: { number } = {} + local dec: any = { + sampleRate = rate, + channels = ch, + frames = total, + duration = total / rate, + bitrate = rate * ch * bits, + tags = {}, + } + return Stream.packets(dec, { + count = count, + start = function(i: number): number + return starts[math.clamp(i, 1, count + 1)] + end, + decode = function(i: number): (number?, Err.Err?) + local pkt = dmx:get(id, i) + if not pkt then + return nil, Err.new(Err.TRUNCATED, "no audio packet " .. i) + end + local n, out = Audio.decode(pkt.data, ch, bits, packed) + if not n then + return nil, Err.from(out :: string) + end + floats = out :: { number } + return n, nil + end, + pcm = function(): { number } + return floats + end, + reset = function() end, + cumulative = true, + }) +end + +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Smk.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Smk.demux(r, opts) + if not dmx then + return nil, err + end + local o: any = table.clone(opts or {}) + type Hook = (any, Types.Track) -> (Types.Decoder?, Err.Err?) + local hook = o.openAudio :: Hook? + o.openAudio = function(d: any, track: Types.Track): (Types.Decoder?, Err.Err?) + if track.codec == "binkaudio" and hook then + return hook(d, track) + end + return Smk.openAudio(d, track) + end + return Video.open(dmx, o) +end + +return Smk diff --git a/tests/video/smk.luau b/tests/video/smk.luau new file mode 100644 index 0000000..6969cde --- /dev/null +++ b/tests/video/smk.luau @@ -0,0 +1,180 @@ +-- video/smk tests: Smacker files encoded by the fixture script (SMK2 and SMK4, every block type and run, the trees' +-- escape cache, palette updates, a ring frame, ms and 10 us frame times; packed 16-bit stereo / 8-bit mono / 16-bit +-- mono / 8-bit stereo audio and raw s16le / u8 tracks): every video frame and every audio track equal ffmpeg's +-- decode (CRC-32 of rgba / f32le), audio seeking, errors, and the fuzz pass on the container, the video codec and the +-- audio codec. Fixtures: tools/fixtures/smk.py. +local T = require("@tests/T") +local F = require("@formats") +local Smk = require("@formats/video/smk") +local SmkAudio = require("@formats/video/smk/Audio") +local Legacy = require("@formats/codecs/video/Legacy") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/smk_cases") + +local t = T.suite("smk") +t:eq(Smk.name, "smk", "name") +t:eq(Smk.category, "video", "category") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- every frame of an audio Decoder -> f32 buffer, frames +local function drain(dec: any): (buffer, number) + local chunks, total = {}, 0 + while true do + local b, n = dec:read(1000) + if n == 0 then + break + end + table.insert(chunks, { b, n }) + total += n + end + local out = buffer.create(total * dec.channels * 4) + local at = 0 + for _, c in chunks do + buffer.copy(out, at, c[1], 0, c[2] * dec.channels * 4) + at += c[2] * dec.channels * 4 + end + return out, total +end + +for _, c in Fx do + local label = c.name + t:check(Smk.sniff(reader(c.data)) == 1, label .. ": sniff") + t:eq(F.detect(buffer.fromstring(c.data)), "smk", label .. ": detect") + local v, err = F.video.open(buffer.fromstring(c.data)) + t:check(v ~= nil, label .. ": open " .. tostring(err)) + if v then + t:eq(v.codec, "smackvid", label .. ": codec") + t:check(v.width == c.width and v.height == c.height, label .. ": size") + t:check(math.abs(v.frameRate - c.rate) < 1e-6, label .. ": frame rate " .. v.frameRate) + local want = if c.ring then #c.frames - 1 else #c.frames + local n, bad = 0, 0 + while true do + local f, ferr = v:nextFrame() + if not f then + t:check(ferr == nil, label .. ": " .. tostring(ferr)) + break + end + n += 1 + if f.image.format ~= "rgba8" or Crc32.of(f.image.pixels) ~= c.frames[n] then + bad += 1 + end + end + t:check(n == want and bad == 0, string.format("%s: %d of %d frames equal ffmpeg's (%d differ)", label, n - bad, want, bad)) + v:seek(0.2) + local f = v:nextFrame() + local k = math.floor(0.2 * c.rate - 1e-9) + 2 + t:check(f ~= nil and Crc32.of(f.image.pixels) == c.frames[k], label .. ": seek to frame " .. k) + -- audio: the first track through the VideoDecoder, every track through Smk.openAudio + if #c.audio > 0 then + t:check(v.audio ~= nil, label .. ": audio " .. tostring(v.audioError)) + end + local tracks = {} + for _, tr in v.demuxer.tracks do + if tr.kind == "audio" then + table.insert(tracks, tr) + end + end + t:eq(#tracks, #c.audio, label .. ": audio tracks") + for i, a in c.audio do + local tr = tracks[i] + t:eq(tr.codec, a.codec, label .. ": audio " .. i .. " codec") + local dec, aerr = Smk.openAudio(v.demuxer, tr) + t:check(dec ~= nil, label .. ": audio " .. i .. ": " .. tostring(aerr)) + if dec then + t:check(dec.sampleRate == a.rate and dec.channels == a.channels, label .. ": audio " .. i .. " format") + local pcm, frames = drain(dec) + t:eq(frames, a.frames, label .. ": audio " .. i .. " frames") + t:eq(Crc32.of(pcm), a.crc, label .. ": audio " .. i .. " equals ffmpeg's") + dec:seek(0) + local again = drain(dec) + t:eq(Crc32.of(again), a.crc, label .. ": audio " .. i .. " after seek(0)") + dec:seek(0.3) + local tail, rest = drain(dec) + local skip = a.frames - rest + t:check(math.abs(skip - 0.3 * a.rate) <= 1, label .. ": audio " .. i .. " seek(0.3) at frame " .. skip) + local same = buffer.len(tail) > 0 + for q = 0, math.min(buffer.len(tail), 4000) - 4, 4 do + if buffer.readu32(tail, q) ~= buffer.readu32(pcm, skip * a.channels * 4 + q) then + same = false + break + end + end + t:check(same, label .. ": audio " .. i .. " seek(0.3) samples") + end + end + if c.ring then + local v2 = Smk.open(reader(c.data), { ringFrame = true }) + local m = 0 + while v2 and v2:nextFrame() do + m += 1 + end + t:eq(m, #c.frames, label .. ": with the ring frame") + end + end +end + +-- errors +do + local _, e = Smk.open(reader(string.sub(Fx[1].data, 1, 60))) + t:check(e ~= nil and e.code == Err.TRUNCATED, "short header: TRUNCATED") + local _, e2 = Smk.open(reader("SMK3" .. string.sub(Fx[1].data, 5))) + t:check(e2 ~= nil and e2.code == Err.CORRUPT, "bad magic: CORRUPT") + t:eq(Smk.sniff(reader("SMK3" .. string.sub(Fx[1].data, 5))), 0, "bad magic: no sniff") + local _, e3 = Smk.open(reader(Fx[1].data), { maxPixels = 100 }) + t:check(e3 ~= nil and e3.code == Err.LIMIT, "maxPixels: LIMIT") + local _, e4 = Smk.open(reader(string.sub(Fx[1].data, 1, 200))) + t:check(e4 ~= nil and e4.code == Err.TRUNCATED, "trees past the end: TRUNCATED") +end + +-- fuzz: the container, the video codec (native, no pcall in between) and the audio codec +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("open", function(b: buffer) + local v = Smk.open(Bytes.reader(b)) + if v then + for _ = 1, 4 do + if not v:nextFrame() then + break + end + end + if v.audio then + v.audio:read(500) + end + end + return v +end, samples, { mutations = 16, garbage = 40, keepHeader = 4 }) +local S, P = Legacy.Smacker, Legacy.Picture +for _, c in { Fx[1], Fx[2] } do + local d = Smk.demux(reader(c.data)) + local tr = d.tracks[1] + local packets = {} + for k = 1, math.min(3, d:count(1)) do + table.insert(packets, d:get(1, k).data) + end + t:fuzz(c.name .. " trees", function(b: buffer) + return S.trees(b) + end, { tr.config }, { mutations = 30, garbage = 30, keepHeader = 16 }) + local trees = assert(S.trees(tr.config)) + t:fuzz(c.name .. " frames", function(b: buffer) + return S.decode(P.new(c.width, c.height, true, 4, 4), b, trees, tr.codecTag == "SMK4") + end, packets, { mutations = 30, garbage = 30 }) + for _, at in d.tracks do + if at.kind == "audio" then + local ap = {} + for k = 1, math.min(2, d:count(at.id)) do + table.insert(ap, d:get(at.id, k).data) + end + t:fuzz(c.name .. " audio " .. at.codec, function(b: buffer) + return SmkAudio.decode(b, at.channels, at.bitsPerSample, at.codec == "smackaudio") + end, ap, { mutations = 20, garbage = 20 }) + end + end +end +t:done() diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py new file mode 100644 index 0000000..0d9ee5a --- /dev/null +++ b/tools/fixtures/smk.py @@ -0,0 +1,493 @@ +# Smacker fixtures (tools/fixtures.py): ffmpeg cannot write Smacker, so this encodes SMK2 / SMK4 files: the four +# header trees (8-bit low / high byte trees, escape leaves used through the recent-value cache, absent trees), every +# block type (MONO, FULL with the SMK4 doubled modes, SKIP, FILL) with block runs, palette updates (new entries, skips, +# copies from the old palette), a ring frame, both frame-time units, and audio tracks: packed DPCM 16-bit stereo and +# 8-bit mono, raw s16le and u8. The reference is ffmpeg's decode: the CRC-32 of each video frame as rgba and of each +# audio track as f32le. +# tests/gen/smk_cases.luau { { name, data, width, height, rate, frames = { crc }, audio = { { rate, channels, +# bits, codec, frames, crc } } } } +import heapq, importlib.util, math, os, random, struct, tempfile, zlib + +_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py")) +V = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(V) + +INPUTS = ["tools/fixtures/_video.py"] + +RUNS = list(range(1, 60)) + [128, 256, 512, 1024, 2048] + + +# ---------------------------------------------------------------------------------------------------- bits / trees +class Bits: + def __init__(self): + self.bits = [] + + def put(self, v, n): + for i in range(n): + self.bits.append((v >> i) & 1) + + def code(self, c): + self.bits.extend(c) + + def bytes(self): + out = bytearray((len(self.bits) + 7) // 8) + for i, b in enumerate(self.bits): + out[i >> 3] |= b << (i & 7) + return bytes(out) + + +def huffman(freqs, maxdepth): + """a Huffman tree over freqs {value: count}: nested (left, right) tuples / ('leaf', value)""" + f = dict(freqs) + while True: + heap = [(c, i, ("leaf", v)) for i, (v, c) in enumerate(sorted(f.items()))] + heapq.heapify(heap) + k = len(heap) + while len(heap) > 1: + a = heapq.heappop(heap) + b = heapq.heappop(heap) + heapq.heappush(heap, (a[0] + b[0], k, (a[2], b[2]))) + k += 1 + tree = heap[0][2] + if depth(tree) <= maxdepth: + return tree + f = {v: c // 2 + 1 for v, c in f.items()} + + +def depth(t): + return 0 if t[0] == "leaf" else 1 + max(depth(t[0]), depth(t[1])) + + +def codes(t, prefix=(), out=None): + out = {} if out is None else out + if t[0] == "leaf": + out[t[1]] = list(prefix) + else: + codes(t[0], prefix + (0,), out) + codes(t[1], prefix + (1,), out) + return out + + +def write_tree8(bw, t): + if t[0] == "leaf": + bw.put(0, 1) + bw.put(t[1], 8) + else: + bw.put(1, 1) + write_tree8(bw, t[0]) + write_tree8(bw, t[1]) + + +class BigTree: + """a header tree: values (16-bit) with three escape leaves for the recent-value cache""" + + def __init__(self, freqs, rnd, absent_ok=True): + self.absent = not freqs + if self.absent: + return + lo = {} + hi = {} + for v, c in freqs.items(): + lo[v & 255] = lo.get(v & 255, 0) + c + hi[v >> 8] = hi.get(v >> 8, 0) + c + # three escape values made of bytes the byte trees have, not used as values (a high-byte tree of only 0 is + # left out: absent byte trees decode as 0) + esc = [] + for l in sorted(lo): + for h in sorted(hi): + v = l | h << 8 + if v not in freqs and len(esc) < 3: + esc.append(v) + while len(esc) < 3: # every combination used: widen the low byte tree + nl = next(x for x in range(256) if x not in lo) + lo[nl] = 1 + esc.append(nl | sorted(hi)[0] << 8) + self.esc = esc + self.lo = huffman(lo, 27) + self.hi = huffman(hi, 27) + allv = dict(freqs) + for i, e in enumerate(esc): + allv[e] = max(1, sum(freqs.values()) // (8 + i)) + self.tree = huffman(allv, 200) + self.lcodes, self.hcodes, self.vcodes = codes(self.lo), codes(self.hi), codes(self.tree) + self.entries = count_entries(self.tree) + self.hi_absent = len(hi) == 1 and 0 in hi + self.rnd = rnd + + def write(self, bw): + if self.absent: + bw.put(0, 1) + return + bw.put(1, 1) + bw.put(1, 1) + write_tree8(bw, self.lo) + bw.put(0, 1) + if self.hi_absent: + bw.put(0, 1) + else: + bw.put(1, 1) + write_tree8(bw, self.hi) + bw.put(0, 1) + for e in self.esc: + bw.put(e, 16) + self._write_big(bw, self.tree) + bw.put(0, 1) + + def _write_big(self, bw, t): + if t[0] == "leaf": + bw.put(0, 1) + v = t[1] + bw.code(self.lcodes[v & 255]) + if not self.hi_absent: + bw.code(self.hcodes[v >> 8]) + else: + bw.put(1, 1) + self._write_big(bw, t[0]) + self._write_big(bw, t[1]) + + def size(self): + return 0 if self.absent else (self.entries + 3) * 4 + + def reset(self): + self.cache = [0, 0, 0] + + def emit(self, bw, v): + if self.absent: + assert v == 0 + return + hit = [k for k in range(3) if self.cache[k] == v] + if hit and self.rnd.random() < 0.7: + bw.code(self.vcodes[self.esc[hit[0]]]) + else: + bw.code(self.vcodes[v]) + if v != self.cache[0]: + self.cache[2] = self.cache[1] + self.cache[1] = self.cache[0] + self.cache[0] = v + + +def count_entries(t): + return 1 if t[0] == "leaf" else 1 + count_entries(t[0]) + count_entries(t[1]) + + +# ---------------------------------------------------------------------------------------------------- video +def blocks_of(img, w, h): + return [[[img[by * 4 + r][bx * 4 + x] for x in range(4)] for r in range(4)] for by in range(h // 4) for bx in range(w // 4)] + + +def classify(b, prev, v4): + if prev is not None and b == prev: + return ("skip",) + flat = [p for r in b for p in r] + cols = sorted(set(flat)) + if len(cols) == 1: + return ("fill", cols[0]) + if len(cols) == 2: + lo, hi = cols + m = 0 + for i, p in enumerate(flat): + if p == hi: + m |= 1 << i + return ("mono", hi << 8 | lo, m) + if v4 and b[0] == b[1] and b[2] == b[3] and b[0][0] == b[0][1] and b[0][2] == b[0][3] and b[2][0] == b[2][1] and b[2][2] == b[2][3]: + return ("full", 1) + if v4 and b[0] == b[1] and b[2] == b[3]: + return ("full", 2) + return ("full", 0) + + +def full_codes(b, mode): + if mode == 0: + out = [] + for r in b: + out += [r[2] | r[3] << 8, r[0] | r[1] << 8] + return out + if mode == 1: + return [b[0][0] | b[0][2] << 8, b[2][0] | b[2][2] << 8] + return [b[0][2] | b[0][3] << 8, b[0][0] | b[0][1] << 8, b[2][2] | b[2][3] << 8, b[2][0] | b[2][1] << 8] + + +def plan(frames, w, h, v4): + """per frame the list of runs: (kind, extra, [blocks])""" + out = [] + prev = None + for img in frames: + bl = blocks_of(img, w, h) + cls = [classify(b, prev[i] if prev else None, v4) for i, b in enumerate(bl)] + runs = [] + i = 0 + while i < len(bl): + c = cls[i] + key = c[:2] if c[0] in ("fill", "full") else c[:1] + j = i + while j + 1 < len(bl) and (cls[j + 1][:2] if cls[j + 1][0] in ("fill", "full") else cls[j + 1][:1]) == key: + j += 1 + n = j - i + 1 + # the largest run length of the table that fits + k = max(r for r in RUNS if r <= n) + runs.append((c, [bl[x] for x in range(i, i + k)], [cls[x] for x in range(i, i + k)], RUNS.index(k))) + i += k + out.append(runs) + prev = bl + return out + + +def type_value(c, ri): + kind = {"mono": 0, "full": 1, "skip": 2, "fill": 3}[c[0]] + v = kind | ri << 2 + if c[0] == "fill": + v |= c[1] << 8 + return v + + +def stats(plans, v4): + f = {"type": {}, "mclr": {}, "mmap": {}, "full": {}} + + def add(t, v): + f[t][v] = f[t].get(v, 0) + 1 + + for runs in plans: + for c, bl, cl, ri in runs: + add("type", type_value(c, ri)) + if c[0] == "mono": + for x in cl: + add("mclr", x[1]) + add("mmap", x[2]) + elif c[0] == "full": + for b in bl: + for v in full_codes(b, c[1]): + add("full", v) + return f + + +def encode_video(frames, w, h, v4, rnd): + plans = plan(frames, w, h, v4) + f = stats(plans, v4) + trees = {k: BigTree(f[k], rnd) for k in ("mmap", "mclr", "full", "type")} + tb = Bits() + for k in ("mmap", "mclr", "full", "type"): + trees[k].write(tb) + treebytes = tb.bytes() + out = [] + for runs in plans: + for t in trees.values(): + t.reset() + bw = Bits() + for c, bl, cl, ri in runs: + trees["type"].emit(bw, type_value(c, ri)) + if c[0] == "mono": + for x in cl: + trees["mclr"].emit(bw, x[1]) + trees["mmap"].emit(bw, x[2]) + elif c[0] == "full": + if v4: + bw.code([1] if c[1] == 1 else [0, 1] if c[1] == 2 else [0, 0]) + for b in bl: + for v in full_codes(b, c[1]): + trees["full"].emit(bw, v) + out.append(bw.bytes() or b"\0") + return treebytes, [trees[k].size() for k in ("mmap", "mclr", "full", "type")], out + + +# ---------------------------------------------------------------------------------------------------- palettes +def pal_chunk(new, old, first): + """a palette update: new / old are lists of 256 6-bit (r, g, b)""" + body = bytearray() + i = 0 + while i < 256: + if not first and new[i] == old[i]: + j = i + while j < 256 and j - i < 128 and new[j] == old[j]: + j += 1 + body.append(0x80 | (j - i - 1)) + i = j + continue + # a copy from the old palette when the next entries appear there in a row + if not first: + for off in range(256): + n = 0 + while i + n < 256 and off + n < 256 and n < 64 and new[i + n] == old[off + n]: + n += 1 + if n >= 2: + body += bytes([0x40 | (n - 1), off]) + i += n + break + else: + off = None + if off is not None: + continue + body += bytes(new[i]) + i += 1 + size = 1 + len(body) + size = (size + 3) // 4 * 4 + return bytes([size // 4]) + bytes(body) + bytes(size - 1 - len(body)) + + +# ---------------------------------------------------------------------------------------------------- audio +def pack_audio(samples, ch, bits): + """one packed (SMKA) chunk body: samples interleaved (s16 or u8)""" + nb = bits // 8 + bw = Bits() + bw.put(1, 1) + bw.put(1 if ch == 2 else 0, 1) + bw.put(1 if bits == 16 else 0, 1) + mod = 65536 if bits == 16 else 256 + pred = list(samples[:ch]) + deltas = [] + for i in range(ch, len(samples)): + c = i % ch + d = (samples[i] - pred[c]) % mod + pred[c] = samples[i] + deltas.append((c, d)) + ntrees = (2 if bits == 16 else 1) * ch + freqs = [dict() for _ in range(ntrees)] + for c, d in deltas: + if bits == 16: + freqs[2 * c][d & 255] = freqs[2 * c].get(d & 255, 0) + 1 + freqs[2 * c + 1][d >> 8] = freqs[2 * c + 1].get(d >> 8, 0) + 1 + else: + freqs[c][d] = freqs[c].get(d, 0) + 1 + trees = [huffman(f or {0: 1}, 27) for f in freqs] + cds = [codes(t) for t in trees] + for t in trees: + bw.put(1, 1) + write_tree8(bw, t) + bw.put(0, 1) + for c in range(ch - 1, -1, -1): + v = samples[c] % mod + if bits == 16: + v = ((v & 255) << 8) | (v >> 8) # stored byte-swapped + bw.put(v, bits) + for c, d in deltas: + if bits == 16: + bw.code(cds[2 * c][d & 255]) + bw.code(cds[2 * c + 1][d >> 8]) + else: + bw.code(cds[c][d]) + return struct.pack(" 0 else -pts_inc / 100000.0) + achunks = [] + for ti, (kind, rate, ch, bits) in enumerate(tracks): + per = [] + done = 0 + for t in range(total): + n = int(round((t + 1) * seconds * rate)) - done + done += n + s = tone(n, ch, bits, rate, seed * 10 + ti * 100 + t, 440 + 110 * ti) + if kind == "packed": + per.append(pack_audio(s, ch, bits)) + else: + per.append(b"".join(struct.pack(" 0 else 100000 / -pts + cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio, + "ring": ring}) + ctx.emit("smk_cases", cases) From 51daa00a67c5041bf9caf64634e908d20dbe57de Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:39:22 -0500 Subject: [PATCH 29/54] ws-3d3-b: model/iqm (Inter-Quake Model v2 read + write: meshes, every vertex array format, joints -> skin, poses / frames / anims -> channels, bounds; writer merges skins, samples and quantizes animations); new codecs/model/Sampler (channel evaluation STEP / LINEAR + slerp / CUBICSPLINE, animation poses at a time) with tests mrfixit.iqm matches assimp and an independent Python IQM reader (its skinning reproduces the bounds the IQM tool stored; ours matches it to 1e-4); round trips and glTF skinned models written by us are skinned identically by the Python reader. --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/model/Sampler.luau | 173 +++++++ src/Formats/model/iqm/Read.luau | 359 +++++++++++++ src/Formats/model/iqm/Write.luau | 706 ++++++++++++++++++++++++++ src/Formats/model/iqm/init.luau | 82 +++ tests/codecs/sampler.luau | 92 ++++ tests/model/iqm.luau | 319 ++++++++++++ tools/fixtures/_iqm_encode.luau | 38 ++ tools/fixtures/_iqm_reference.py | 113 +++++ tools/fixtures/iqm.py | 57 +++ 11 files changed, 1953 insertions(+) create mode 100644 src/Formats/codecs/model/Sampler.luau create mode 100644 src/Formats/model/iqm/Read.luau create mode 100644 src/Formats/model/iqm/Write.luau create mode 100644 src/Formats/model/iqm/init.luau create mode 100644 tests/codecs/sampler.luau create mode 100644 tests/model/iqm.luau create mode 100644 tools/fixtures/_iqm_encode.luau create mode 100644 tools/fixtures/_iqm_reference.py create mode 100644 tools/fixtures/iqm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 998e47b..a352671 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | +| model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | @@ -130,6 +131,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each + - codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d44f2b4..397a3f7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return require("@formats/model/iqm") + end, + }, { name = "lwo", category = "model", diff --git a/src/Formats/codecs/model/Sampler.luau b/src/Formats/codecs/model/Sampler.luau new file mode 100644 index 0000000..df866b9 --- /dev/null +++ b/src/Formats/codecs/model/Sampler.luau @@ -0,0 +1,173 @@ +--!strict +-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for +-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold +-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames +-- (IQM, MD5, BVH, ...). New in formats-luau. +-- +-- local sample = Sampler.channel(ch) -- nil for an unreadable channel +-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights +-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique +-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } +-- +-- Never throws on bad data: unreadable channels are skipped. +local Types = require("@formats/Types") + +local Sampler = {} + +export type Sample = (t: number) -> { number } +export type Pose = { [number]: { [string]: { number } } } + +local function normalize(q: { number }): { number } + local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a: { number }, b: { number }, s: number): { number } + local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +-- channel(ch) -> sample(t) | nil +function Sampler.channel(ch: Types.Channel): Sample? + local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = if cubic then 3 else 1 + local comps: number + if ch.path == "weights" then + comps = (out.count * out.components) // (n * per) + else + comps = if ch.path == "rotation" then 4 else 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = table.create(n) :: { number } + for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + -- element e (0-based, of comps values) of the flat output + local function get(e: number): { number } + local v = table.create(comps) :: { number } + for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(flat // oc, flat % oc) + end + return v + end + local function value(k: number): { number } -- key k (1-based) + return get(if cubic then (k - 1) * 3 + 1 else k - 1) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t: number): { number } + if t <= times[1] or n == 1 then + return if rot then normalize(value(1)) else value(1) + end + if t >= times[n] then + return if rot then normalize(value(n)) else value(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = if dt > 0 then (t - times[lo]) / dt else 0 + if step then + return if rot then normalize(value(lo)) else value(lo) + end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return if rot then normalize(v) else v + end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +-- times(anim) -> every key time, sorted and unique +function Sampler.times(anim: Types.Animation): { number } + local seen: { [number]: boolean } = {} + local out: { number } = {} + for _, ch in anim.channels do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table +-- (reuse it across calls for the same animation) +function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose + local cache: { [any]: any } = samplers or {} + local pose: Pose = {} + for _, ch in anim.channels do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s: Sample? = cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler diff --git a/src/Formats/model/iqm/Read.luau b/src/Formats/model/iqm/Read.luau new file mode 100644 index 0000000..599091a --- /dev/null +++ b/src/Formats/model/iqm/Read.luau @@ -0,0 +1,359 @@ +--!strict +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and +-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). +-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h: number): number + local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } + local out = table.create(n) :: { number } + local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v: number + if format == 0 then + v = readi8(b, p) + v = if normalized then math.max(v / 127, -1) else v + elseif format == 1 then + v = readu8(b, p) + v = if normalized then v / 255 else v + elseif format == 2 then + v = readi16(b, p) + v = if normalized then math.max(v / 32767, -1) else v + elseif format == 3 then + v = readu16(b, p) + v = if normalized then v / 65535 else v + elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals: { number }, comps: number): Types.Accessor + local d = buffer.create(#vals * 4) + for i, v in vals do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, #vals // comps) +end + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +-- scene(b, base, limit, opts) -> Scene | nil, message +function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) + local size = limit - base + local H: { [string]: number } = {} + for i, name in Read.HEADER do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs: number, count: number, each: number, what: string): string? + if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" + local function str(ofs: number): string + if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + -- vertex arrays (the whole model's vertices; meshes are ranges of them) + local nv = H.num_vertexes + type Array = { kind: string, name: string, format: number, comps: number, offset: number } + local arrays: { Array } = {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) + table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + -- joints -> nodes + a skin + local jointNodes: { number } = {} + local skin: number? = nil + if H.num_joints > 0 then + local joints: { Rig.Joint } = {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = table.create(10) :: { number } + for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM names its texture there) + local matOf: { [string]: number } = {} + local function material(name: string): number? + if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + -- meshes + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes: { [string]: Types.Accessor } = {} + for _, a in arrays do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (if big then 2 else 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 + x = math.clamp(math.floor(x), 0, if big then 65535 else 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 + writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name + local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps + if want ~= a.comps then + local fixed = table.create(cv * want, 0) :: { number } + for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 + end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses: { { mask: number, offset: { number }, scale: { number } } } = {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = table.create(10) :: { number }, table.create(10) :: { number } + for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels += 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes: number = H.num_framechannels * 2 + local framesAt: number = base + H.ofs_frames + local function frame(f: number): { { number } } + local out = table.create(np) :: { { number } } + local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = table.create(10) :: { number } + for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k: number = ps.scale[c + 1] + x += readu16(b, q) * k + q += 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims: { any } = {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = if rate > 0 and rate == rate then rate else 30 + local times = table.create(count) :: { number } + local tracks: { [number]: Rig.Track } = {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in tracks do + local v = fr[j] + local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } + table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = if ql > 0 then ql else 1 + table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read diff --git a/src/Formats/model/iqm/Write.luau b/src/Formats/model/iqm/Write.luau new file mode 100644 index 0000000..df6eaf9 --- /dev/null +++ b/src/Formats/model/iqm/Write.luau @@ -0,0 +1,706 @@ +--!strict +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines +-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights +-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins +-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse +-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world +-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are +-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), +-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. +-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). +-- Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Mat4 = require("@formats/codecs/model/Mat4") +local Sampler = require("@formats/codecs/model/Sampler") +local Read = require("@formats/model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene +type M4 = { number } + +-- ------------------------------------------------------------------------------------------------ scene walk +-- world matrices (rest pose, or with a pose's overrides) and the parent of every node +local function parents(scene: Types.Scene): { [number]: number } + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4 + if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 } + local world: { [number]: M4 } = {} + local function get(i: number, depth: number): M4 + local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in scene.nodes do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points +local function triangles(prim: Types.Primitive): { number }? + local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = if fget then fget(f, 0) else 0 + for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at += n + end + else + return nil + end + for _, v in out do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }? + if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = table.create(nv * comps) :: { number } + for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1] + end + end + return out +end + +-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } + local pairs_: { { number } } = {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, pr in pairs_ do + sum += pr[2] + end + local q: { number } = {} + local left = 255 + for k, pr in pairs_ do + q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0 + left -= q[k] + end + if #pairs_ > 0 then + q[1] += left + end + local list: { number } = {} + for k, pr in pairs_ do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +-- appends a flat influence list to the blend index / weight arrays (4 slots) +local function push4(bi: { number }, bw: { number }, list: { number }) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end + +-- ------------------------------------------------------------------------------------------------ writer +type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number } + +function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) + local parent = parents(scene) + local rest = worlds(scene, parent, nil) + -- the skeleton: every skin joint, parents first + local isJoint: { [number]: boolean } = {} + local ibmOf: { [number]: M4 } = {} + for _, skin in scene.skins do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in skin.joints do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = table.create(16) :: M4 + for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + local jointList: { number } = {} + local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local function add(n: number, depth: number) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard += 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in scene.skins do + for _, n in skin.joints do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n: number): number + local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard += 1 + end + return -1 + end + local bindWorld: { [number]: M4 } = {} + for _, n in jointList do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number }) + local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1]]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + -- the meshes + local nodeOfMesh: { [number]: number } = {} + local placed: { { node: number, mesh: number } } = {} + local seen: { [number]: boolean } = {} + local function visit(i: number, depth: number) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in node.children or {} do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in scene.nodes do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in roots do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in scene.meshes do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris: { number } = {} + local meshes: { MeshOut } = {} + -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds + local skinOf: { { number } } = {} + local nvTotal = 0 + for _, pl in placed do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY + local nrmM = Mat4.normalMatrix(world) + for pi, prim in mesh.primitives do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number } + local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = if pl.node > 0 then pl.node else nil + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard += 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + local list: { number } + if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- triangles back to IQM's clockwise order + local tfirst = #tris // 3 + for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else "" + end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name ..= "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 }) + nvTotal += nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + -- animation frames + local frames: { { { number } } } = {} -- frames[f][joint] = 10 values + local anims: { { name: string, first: number, count: number, rate: number } } = {} + local frameWorld: { { [number]: M4 } } = {} + if hasJoints then + for ai, anim in scene.animations do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second + local dt = if #keys > 1 then keys[2] - keys[1] else 0 + local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = if uniform then 1 / dt else 30 + end + local fps: number = math.clamp(rate :: number, 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ: { [number]: { number } } = {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = table.create(#jointList) :: { { number } } + for j, n in jointList do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + -- quantization per pose channel + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in frames do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels += 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + -- text + local text = { "\0" } + local textLen = 1 + local textAt: { [string]: number } = { [""] = 0 } + local function str(s: string): number + local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen += #s + 1 + textAt[s] = at + return at + end + for _, m in meshes do + str(m.name) + str(m.material) + end + for _, n in jointList do + str(scene.nodes[n].name or "") + end + for _, a in anims do + str(a.name) + end + local comment = opts and opts.comment + -- layout + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H: { [string]: number } = {} + local function at(): number + return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text += 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in meshes do + for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do + w:u32le(v) + end + end + -- vertex arrays: headers, then data + type Arr = { typ: number, format: number, comps: number, data: { number } } + local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt: { number } = {} + for i, a in arrs do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in a.data do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in a.data do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in a.data do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in a.data do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), #tris // 3 + for _, v in tris do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in jointList do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le(if p < 0 then p + 2 ^ 32 else p) + for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in jointList do + local jp = jointParent(n) + w:u32le(if jp < 0 then jp + 2 ^ 32 else jp) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in anims do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in frames do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + -- bounds of the skinned vertices per frame + H.ofs_bounds = at() + local skinM = table.create(#jointList) :: { M4 } + for f, world in frameWorld do + for j, n in jointList do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in Read.HEADER do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in arrs do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write diff --git a/src/Formats/model/iqm/init.luau b/src/Formats/model/iqm/init.luau new file mode 100644 index 0000000..c46a61b --- /dev/null +++ b/src/Formats/model/iqm/init.luau @@ -0,0 +1,82 @@ +--!strict +-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / +-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). +-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as +-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as +-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints +-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels +-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in +-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's +-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). +-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and +-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/iqm/Read") +local Write = require("@formats/model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more vertices or triangles (default 2^25) +} +export type EncodeOptions = { + framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) + comment: string?, -- stored in the comment block +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r: Bytes.Reader): number + return if r:peek(16) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.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 ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message) + end + return out, nil +end + +return Iqm diff --git a/tests/codecs/sampler.luau b/tests/codecs/sampler.luau new file mode 100644 index 0000000..bfdb746 --- /dev/null +++ b/tests/codecs/sampler.luau @@ -0,0 +1,92 @@ +-- codecs/model/Sampler tests: STEP / LINEAR / CUBICSPLINE channels (glTF's Hermite definition), quaternion slerp +-- (shortest path, unit length), clamping outside the keys, weights channels, Sampler.times and Sampler.pose; glTF's +-- InterpolationTest sample model (every interpolation) sampled at its keys gives the key values; bad channels. +local T = require("@tests/T") +local Sampler = require("@formats/codecs/model/Sampler") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Picks = require("@tests/gen/iqm_gltf") + +local t = T.suite("codecs/sampler") +local S = Types.Scene + +local function acc(list: { number }, comps: number): Types.Accessor + local b = buffer.create(#list * 4) + for i, v in list do + buffer.writef32(b, (i - 1) * 4, v) + end + return S.accessor(b, "f32", comps, #list // comps) +end +local function near(a: number, b: number, eps: number?): boolean + return math.abs(a - b) < (eps or 1e-5) +end + +do + local ch: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 1, 3 }, 1), output = acc({ 0, 0, 0, 2, 4, 6, 2, 0, 0 }, 3), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(0.5)[1], 1) and near(s(0.5)[2], 2), "linear: halfway") + t:check(near(s(2)[1], 2) and near(s(2)[2], 2), "linear: second span") + t:check(near(s(-1)[2], 0) and near(s(9)[1], 2), "linear: clamped outside the keys") + ch.interpolation = "STEP" + local st = assert(Sampler.channel(ch)) + t:check(near(st(0.99)[1], 0) and near(st(1)[1], 2), "step") +end +do + -- rotation: 0 -> 90 degrees about z, and a key stored with the opposite sign (shortest path) + local h = math.sqrt(0.5) + local ch: Types.Channel = { node = 1, path = "rotation", input = acc({ 0, 1, 2 }, 1), output = acc({ 0, 0, 0, 1, 0, 0, h, h, 0, 0, -h, -h }, 4), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local q = s(0.5) + local a = 2 * math.acos(q[4]) + t:check(near(a, math.pi / 4, 1e-4) and near(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2, 1), "slerp: 45 degrees, unit length") + local q2 = s(1.5) + t:check(near(math.abs(q2[3]), h, 1e-4), "slerp: the same orientation stored negated stays put") +end +do + -- cubic spline: in-tangent, value, out-tangent per key; p(t) for p0 = 0, p1 = 1, m0 = m1 = 0 is smoothstep + local ch: Types.Channel = { node = 1, path = "scale", input = acc({ 0, 2 }, 1), output = acc({ 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 9, 9, 9 }, 3), interpolation = "CUBICSPLINE" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(1)[1], 0.5) and near(s(0.5)[1], 3 * 0.25 ^ 2 - 2 * 0.25 ^ 3), "cubic: smoothstep") + t:check(near(s(2)[2], 1), "cubic: the last value") + -- tangents scale with the key spacing + local ch2: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 2 }, 1), output = acc({ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 3), interpolation = "CUBICSPLINE" } + local s2 = assert(Sampler.channel(ch2)) + -- h10(0.5) * dt * m0 = 0.125 * 2 * 1 + t:check(near(s2(1)[1], 0.25), "cubic: tangents times the key spacing") +end +do + local ch: Types.Channel = { node = 2, path = "weights", input = acc({ 0, 1 }, 1), output = acc({ 1, 0, 0, 1 }, 1), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local w = s(0.25) + t:check(#w == 2 and near(w[1], 0.75) and near(w[2], 0.25), "weights") + local anim: Types.Animation = { name = "a", channels = { ch, { node = 1, path = "translation", input = acc({ 0.5, 1 }, 1), output = acc({ 0, 0, 0, 1, 1, 1 }, 3), interpolation = "STEP" } } } + local times = Sampler.times(anim) + t:eq(table.concat(times, " "), "0 0.5 1", "times: sorted, unique") + local pose = Sampler.pose(S.new(), anim, 1) + t:check(pose[2].weights and pose[1].translation and near(pose[1].translation[1], 1), "pose") + t:check(Sampler.channel({ node = 1, path = "translation", input = acc({ 0, 1 }, 1), output = acc({ 1, 2 }, 1), interpolation = "LINEAR" }) == nil, "short output: nil") + t:check(Sampler.channel({ node = 1, path = "translation", input = {} :: any, output = {} :: any, interpolation = "LINEAR" }) == nil, "junk: nil") +end +do + -- a real file: sampling a glTF sample model's skin animation at its own keys returns the key values + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[1].data)), { files = Picks[1].files })) + local ok, total = true, 0 + for _, anim in g.animations do + for _, ch in anim.channels do + local s = assert(Sampler.channel(ch)) + local IN, OUT = assert(S.reader(ch.input)), assert(S.reader(ch.output)) + local comps = if ch.path == "rotation" then 4 else 3 + for k = 0, ch.input.count - 1 do + local v = s(IN(k, 0)) + for c = 1, comps do + ok = ok and near(v[c], OUT(k, c - 1), 1e-4) + end + total += 1 + end + end + end + t:check(ok and total > 0, Picks[1].name .. ": samples at the keys are the keys (" .. total .. ")") +end + +t:done() diff --git a/tests/model/iqm.luau b/tests/model/iqm.luau new file mode 100644 index 0000000..588320e --- /dev/null +++ b/tests/model/iqm.luau @@ -0,0 +1,319 @@ +-- model/iqm tests: assimp's mrfixit.iqm against assimp (meshes, triangles, vertices, materials, bind pose bounds), an +-- independent Python reader (joints, anims) and the bounds the IQM tool stored per frame (our decoded skeleton and +-- animation, skinned here, must reproduce them); writer round trips (mrfixit, glTF sample models with and without +-- skins) read back by our reader, by assimp and by the Python reader, whose skinning of our files must match ours; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/iqm.py. +local T = require("@tests/T") +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Sampler = require("@formats/codecs/model/Sampler") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") +local Xcheck = require("@tests/gen/iqm_xcheck") + +local t = T.suite("iqm") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Iqm.decode(Bytes.reader(b), opts) +end + +t:eq(Iqm.name, "iqm", "name") +t:eq(Iqm.category, "model", "category") +t:check(Iqm.caps.decode and Iqm.caps.encode, "caps") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end +-- the largest coordinate difference between two boxes +local function boxDiff(lo: { number }, hi: { number }, want: any): number + local d = 0 + for k = 1, 3 do + d = math.max(d, math.abs(lo[k] - want.min[k]), math.abs(hi[k] - want.max[k])) + end + return d +end +local function boxNear(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end +-- assimp's IQM root turns z-up into y-up: (x, y, z) -> (x, z, -y) +local function zUpToY(lo: { number }, hi: { number }): ({ number }, { number }) + return { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] } +end + +local function counts(scene: any): (number, number, number) + local prims, tris, verts = 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + prims += 1 + tris += p.indices.count // 3 + verts += p.attributes.POSITION.count + end + end + return prims, tris, verts +end + +-- the bounding box of every mesh vertex, skinned with the scene's skins at time t of anim (nil: the rest pose) +local function skinnedBounds(scene: any, anim: any?, time: number): ({ number }, { number }) + local pose = if anim then Sampler.pose(scene, anim, time) else nil + local parent = {} + for i, n in scene.nodes do + for _, c in n.children do + parent[c] = i + end + end + local world = {} + local function W(i: number): { number } + if world[i] then + return world[i] + end + local node = scene.nodes[i] + local over = pose and pose[i] + local m + if over then + m = Mat4.compose(over.translation or node.translation, over.rotation or node.rotation, over.scale or node.scale) + else + m = S.nodeMatrix(node) + end + if parent[i] then + m = S.mul(W(parent[i]), m) + end + world[i] = m + return m + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for ni, node in scene.nodes do + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + local skin = node.skin and scene.skins[node.skin] + local mats = {} + if skin then + local ibm = assert(S.reader(skin.inverseBindMatrices)) + for j, jn in skin.joints do + local inv = {} + for k = 1, 16 do + inv[k] = ibm(j - 1, k - 1) + end + mats[j - 1] = S.mul(W(jn), inv) + end + end + local LINES = { points = true, lines = true, line_strip = true, line_loop = true } + for _, p in mesh.primitives do + if LINES[p.mode] then + continue + end + local P = assert(S.reader(p.attributes.POSITION)) + local J = p.attributes.JOINTS_0 and S.reader(p.attributes.JOINTS_0) + local Wt = p.attributes.WEIGHTS_0 and S.reader(p.attributes.WEIGHTS_0) + for v = 0, p.attributes.POSITION.count - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if skin and J and Wt then + local sx, sy, sz = 0, 0, 0 + for c = 0, 3 do + local w = Wt(v, c) + if w > 0 then + local qx, qy, qz = Mat4.point(mats[J(v, c)], x, y, z) + sx, sy, sz = sx + w * qx, sy + w * qy, sz + w * qz + end + end + x, y, z = sx, sy, sz + else + x, y, z = Mat4.point(W(ni), x, y, z) + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + end + end + end + end + return lo, hi +end + +local function xcheck(name: string): any + for _, x in Xcheck do + if x.name == name then + return x + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ mrfixit +local fixit = Cases[1] +local scene, err = decode(fixit.data) +t:check(scene, "mrfixit: decode " .. tostring(err)) +do + local a, ref = fixit.assimp, fixit.ref + local prims, tris, verts = counts(scene) + t:eq(prims, a.meshes, "mrfixit: meshes (assimp)") + t:eq(tris, a.faces, "mrfixit: triangles (assimp)") + t:eq(verts, a.vertices, "mrfixit: vertices (assimp)") + t:eq(#scene.materials, a.materials, "mrfixit: materials (assimp)") + t:eq(scene.textures[scene.materials[1].baseColorTexture.texture].uri, "Body.jpg", "mrfixit: material string -> texture uri") + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local ylo, yhi = zUpToY(lo, hi) + t:check(boxNear(ylo, yhi, a, 1e-4), string.format("mrfixit: bind pose bounds (assimp) %s / %s", table.concat(ylo, " "), table.concat(yhi, " "))) + t:eq(#scene.skins, 1, "mrfixit: one skin") + t:eq(#scene.skins[1].joints, ref.joints, "mrfixit: joints (Python reader)") + for j, n in scene.skins[1].joints do + t:eq(scene.nodes[n].name, ref.jointNames[j], "mrfixit: joint name " .. j) + end + t:eq(#scene.animations, #ref.anims, "mrfixit: animations") + t:eq(scene.animations[1].name, ref.anims[1].name, "mrfixit: animation name") + t:eq(scene.meta.source.animations[1].frames, ref.anims[1].frames, "mrfixit: frames") + local prim = scene.meshes[1].primitives[1] + t:check(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0.type == "unorm8", "mrfixit: blend indexes / weights") + t:check(prim.attributes.TANGENT and prim.attributes.TANGENT.components == 4, "mrfixit: tangents") + -- the bounds the IQM tool stored, from our skeleton + animation (and the Python reader's skinning agrees) + local fps = ref.anims[1].framerate + -- (the tool computed its bounds before quantizing the frames: up to 0.1% off the quantized animation) + local worst, worstPy = 0, 0 + for f = 1, ref.frames, 5 do + local l, h = skinnedBounds(scene, scene.animations[1], (f - 1) / fps) + worst = math.max(worst, boxDiff(l, h, ref.stored[f])) + worstPy = math.max(worstPy, boxDiff(l, h, ref.skinned[f])) + t:check(boxDiff(ref.skinned[f].min, ref.skinned[f].max, ref.stored[f]) < 1e-2, "mrfixit: the Python reader reproduces the stored bounds, frame " .. f) + end + t:check(worst < 1e-2, "mrfixit: skinned bounds per frame match the IQM tool's (worst " .. worst .. ")") + t:check(worstPy < 1e-4, "mrfixit: skinned bounds per frame match the Python reader's (worst " .. worstPy .. ")") + t:check(scene.meta.source.bounds and #scene.meta.source.bounds == ref.frames, "mrfixit: bounds block read") +end + +-- ------------------------------------------------------------------------------------------------ round trips +do + local out = assert(Iqm.encode(scene)) + local back = assert(decode(out)) + local p1, t1, v1 = counts(scene) + local p2, t2, v2 = counts(back) + t:check(p1 == p2 and t1 == t2 and v1 == v2, "round trip: counts") + -- positions and indices exact + local same = true + for mi, m in scene.meshes do + local a, b = m.primitives[1], back.meshes[mi].primitives[1] + t:check(buffer.tostring(a.attributes.POSITION.data) == buffer.tostring(b.attributes.POSITION.data), "round trip: positions exact, mesh " .. mi) + t:check(buffer.tostring(a.indices.data) == buffer.tostring(b.indices.data), "round trip: triangles exact, mesh " .. mi) + -- influences: the same (joint, weight) pairs (unused slots and their order may differ) + local ja, wa, jb, wb = S.reader(a.attributes.JOINTS_0), S.reader(a.attributes.WEIGHTS_0), S.reader(b.attributes.JOINTS_0), S.reader(b.attributes.WEIGHTS_0) + for v = 0, a.attributes.POSITION.count - 1 do + local inf = {} + for c = 0, 3 do + if (wa :: any)(v, c) > 0 then + inf[(ja :: any)(v, c)] = (inf[(ja :: any)(v, c)] or 0) + (wa :: any)(v, c) + end + end + for c = 0, 3 do + local w = (wb :: any)(v, c) + if w > 0 then + local j = (jb :: any)(v, c) + same = same and inf[j] ~= nil and math.abs(inf[j] - w) < 1.5 / 255 + inf[j] = nil + end + end + same = same and next(inf) == nil + end + end + t:check(same, "round trip: the same influences") + t:eq(#back.skins[1].joints, #scene.skins[1].joints, "round trip: joints") + t:eq(back.meta.source.animations[1].frames, scene.meta.source.animations[1].frames, "round trip: frames") + local worst = 0 + for _, time in { 0, 0.5, 1.5, 3 } do + local l1, h1 = skinnedBounds(scene, scene.animations[1], time) + local l2, h2 = skinnedBounds(back, back.animations[1], time) + for k = 1, 3 do + worst = math.max(worst, math.abs(l1[k] - l2[k]), math.abs(h1[k] - h2[k])) + end + end + t:check(worst < 2e-3, "round trip: the animation skins the same (worst " .. worst .. ")") + -- assimp and the Python reader on our file + local x = assert(xcheck("rt_mrfixit.iqm"), "xcheck rt_mrfixit") + t:eq(x.assimp.faces, fixit.assimp.faces, "round trip: assimp triangles") + t:eq(x.assimp.vertices, fixit.assimp.vertices, "round trip: assimp vertices") + t:check(boxNear(x.assimp.min, x.assimp.max, fixit.assimp, 1e-4), "round trip: assimp bounds") + local w2, w3 = 0, 0 + for f, box in fixit.ref.skinned do + local mine = x.ref.skinned[f] + w2 = math.max(w2, boxDiff(mine.min, mine.max, box)) + w3 = math.max(w3, boxDiff(x.ref.stored[f].min, x.ref.stored[f].max, mine)) + end + t:check(w2 < 2e-3, "round trip: the Python reader skins our file like the original (worst " .. w2 .. ")") + t:check(w3 < 1e-4, "round trip: our bounds block matches the Python skinning (worst " .. w3 .. ")") +end + +-- glTF sample models through the writer +for _, p in Picks do + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })) + local out, e = Iqm.encode(g) + t:check(out, p.name .. ": encode " .. tostring(e)) + local back = assert(decode(out)) + local x = assert(xcheck("gltf_" .. p.name .. ".iqm"), "xcheck " .. p.name) + local _, tris, verts = counts(back) + t:eq(x.assimp.faces, tris, p.name .. ": assimp reads our triangles") + t:eq(x.assimp.vertices, verts, p.name .. ": assimp reads our vertices") + -- unskinned: the glTF scene's world bounds (skinned: IQM's rest pose is the bind pose, checked by the frames below) + local l2, h2 = skinnedBounds(back, nil, 0) + if #g.skins == 0 then + local lo, hi = skinnedBounds(g, nil, 0) + t:check(boxNear(l2, h2, { min = lo, max = hi }, 1e-4), p.name .. ": world bounds kept") + end + local yl, yh = zUpToY(l2, h2) + t:check(boxNear(yl, yh, x.assimp, 1e-3), p.name .. ": assimp bounds of our file") + if #g.skins > 0 and #g.animations > 0 then + local anim = x.ref.anims[1] + local worst = 0 + for f = 1, x.ref.frames do + local l, h = skinnedBounds(g, g.animations[1], (f - 1) / anim.framerate) + local py = x.ref.skinned[f] + for k = 1, 3 do + worst = math.max(worst, math.abs(l[k] - py.min[k]), math.abs(h[k] - py.max[k])) + end + end + t:check(worst < 5e-3, p.name .. ": the Python reader skins our file like the glTF animation (worst " .. worst .. ")") + t:eq(#back.skins[1].joints, #g.skins[1].joints, p.name .. ": joints") + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("INTERQUAKEMODEL\0") + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local bad = buffer.fromstring(fixit.data) + buffer.writeu32(bad, 16, 1) + local _, e2 = decode(bad) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 1: " .. tostring(e2)) + local cut = buffer.fromstring(string.sub(fixit.data, 1, 5000)) + local _, e3 = decode(cut) + t:check(e3 and e3.code == Err.TRUNCATED, "cut: " .. tostring(e3)) + local _, e4 = decode(fixit.data, { maxVertices = 100 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Iqm.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + local _, e6 = Iqm.encode(S.new()) + t:check(e6 and e6.code == Err.ARG, "encode an empty scene: " .. tostring(e6)) + t:eq(Iqm.sniff(Bytes.reader(buffer.fromstring(fixit.data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local small = assert(Iqm.encode(assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[2].data)), { files = Picks[2].files })))) + local samples = { small, string.sub(fixit.data, 1, 20000) } + t:fuzz("decode", function(b: buffer) + local s = Iqm.decode(Bytes.reader(b)) + if s then + Iqm.encode(s) + end + return s + end, samples, { mutations = 24, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/_iqm_encode.luau b/tools/fixtures/_iqm_encode.luau new file mode 100644 index 0000000..388e77f --- /dev/null +++ b/tools/fixtures/_iqm_encode.luau @@ -0,0 +1,38 @@ +-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our +-- reader and writer, and every glTF pick through our writer, printing "\t" lines for assimp and the +-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_.iqm. +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +for _, c in Cases do + local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data)))) + print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene)))) +end +for _, p in Picks do + local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files }) + if scene then + local out, e2 = Iqm.encode(scene) + if out then + print("gltf_" .. p.name .. ".iqm\t" .. hex(out)) + else + print("encode failed " .. p.name .. ": " .. tostring(e2)) + end + else + print("skipped " .. p.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/_iqm_reference.py b/tools/fixtures/_iqm_reference.py new file mode 100644 index 0000000..b2525a6 --- /dev/null +++ b/tools/fixtures/_iqm_reference.py @@ -0,0 +1,113 @@ +# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its +# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the +# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds +# block, which it returns too for comparison). +import math, struct + +HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays " + "num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames " + "num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split() +FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)} + + +def mat(t, q, s): + x, y, z, w = q + n = math.sqrt(x * x + y * y + z * z + w * w) or 1 + x, y, z, w = x / n, y / n, z / n, w / n + r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], + [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], + [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]] + return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]] + + +def mul(a, b): + return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)] + + +def inv(m): + # general 4x4 inverse (Gauss-Jordan) + a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)] + for c in range(4): + p = max(range(c, 4), key=lambda r: abs(a[r][c])) + a[c], a[p] = a[p], a[c] + d = a[c][c] or 1e-30 + a[c] = [v / d for v in a[c]] + for r in range(4): + if r != c: + f = a[r][c] + a[r] = [v - f * w for v, w in zip(a[r], a[c])] + return [row[4:] for row in a] + + +def read(data): + h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16))) + text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]] + + def s(o): + return text[o:text.index(b"\0", o)].decode("latin1") + arrays = {} + for i in range(h["num_vertexarrays"]): + typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20) + c, n = FMT[fmt] + vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs) + arrays[typ] = (fmt, size, vals) + joints = [] + for j in range(h["num_joints"]): + v = struct.unpack_from("= 0 else m) + invbind = [inv(m) for m in bind] + poses = [] + for p in range(h["num_poses"]): + v = struct.unpack_from("= 0 else m) + skin = [mul(world[j], invbind[j]) for j in range(len(world))] + lo, hi = [1e30] * 3, [-1e30] * 3 + for v in range(h["num_vertexes"]): + x, y, z = pos[v * 3:v * 3 + 3] + if bi and bw: + sx = sy = sz = 0.0 + tot = 0.0 + for c in range(4): + w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c] + if w > 0: + m = skin[bi[2][v * 4 + c]] + sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3]) + sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3]) + sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3]) + tot += w + if tot > 0: + x, y, z = sx, sy, sz + lo = [min(a, b) for a, b in zip(lo, (x, y, z))] + hi = [max(a, b) for a, b in zip(hi, (x, y, z))] + boxes.append({"min": lo, "max": hi}) + stored = [] + if h["ofs_bounds"]: + for f in range(h["num_frames"]): + v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32) + stored.append({"min": list(v[0:3]), "max": list(v[3:6])}) + return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"], + "jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored} diff --git a/tools/fixtures/iqm.py b/tools/fixtures/iqm.py new file mode 100644 index 0000000..ae2559d --- /dev/null +++ b/tools/fixtures/iqm.py @@ -0,0 +1,57 @@ +# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp +# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent +# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed +# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf) +# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader. +# tests/gen/iqm_cases.luau { name, data, assimp, ref } +# tests/gen/iqm_gltf.luau { name, data, files } +# tests/gen/iqm_xcheck.luau { name, assimp, ref } +import importlib.util, os + +INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"] + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def info(ctx, M, fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + for k in ("min", "max", "perMesh"): + a.pop(k, None) + if not a.get("failed"): + a.update(fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = module(ctx, "_model_ref") + fbx = module(ctx, "fbx") + R = module(ctx, "_iqm_reference") + tmp = M.tempdir() + p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm") + data = open(p, "rb").read() + ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}]) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"): + d0 = os.path.join(gl, model) + for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []: + d = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else [] + if mains: + picks.append({"name": model, "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + ctx.emit("iqm_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau") + out = [] + for name in sorted(ours): + q = os.path.join(tmp, name) + open(q, "wb").write(ours[name]) + out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])}) + ctx.emit("iqm_xcheck", out) From d99b026b0711e60a59317e432a3703f74a8dbd9f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:29 -0500 Subject: [PATCH 30/54] legacy video: bench lines (320x240 / 320x200 fixtures), Smacker frame decoder through 10-bit lookup tables --- src/Formats/codecs/video/Legacy/Smacker.luau | 146 ++++++++++++------- tools/bench.luau | 39 +++++ tools/fixtures/fli.py | 6 + tools/fixtures/legacy.py | 8 + tools/fixtures/smk.py | 14 +- 5 files changed, 157 insertions(+), 56 deletions(-) diff --git a/src/Formats/codecs/video/Legacy/Smacker.luau b/src/Formats/codecs/video/Legacy/Smacker.luau index c5923ec..eab6650 100644 --- a/src/Formats/codecs/video/Legacy/Smacker.luau +++ b/src/Formats/codecs/video/Legacy/Smacker.luau @@ -9,12 +9,13 @@ -- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; -- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a -- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour). --- Trees are flat arrays (a node stores the size of its left subtree, as a negative number) walked bit by bit. +-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads +-- 10 bits at a time through a lookup table into them. -- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give -- zero bits, a frame whose codes run out of bits gives no picture. local Picture = require("@formats/codecs/video/Legacy/Picture") -local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 +local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local band, rshift = bit32.band, bit32.rshift local Smacker = {} @@ -135,7 +136,7 @@ function Smacker.tree8(br: Bits): ({ number }?, string?) end local tree8 = Smacker.tree8 -export type BigTree = { vals: { number }, last: { number } } -- last: the escape leaves' indexes (1-based) +export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) -- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries) local function bigTree(br: Bits, size: number): (BigTree?, string?) @@ -213,29 +214,26 @@ function Smacker.trees(config: buffer): (Trees?, string?) return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil end --- code(tree, br) -> the next value (updating the recent-value cache) | nil when the bits run out inside the tree -local function code(t: BigTree, br: Bits): number? - local vals = t.vals - local i = 1 - local e = vals[1] - while e < 0 do - if br.pos >= br.nbits then - return nil +local LUT_BITS = 10 + +-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits +local function lut(vals: { number }): buffer + local size = 2 ^ LUT_BITS + local t = buffer.create(size * 4) + for pat = 0, size - 1 do + local i, len = 1, 0 + local e = vals[1] + while e < 0 and len < LUT_BITS do + if band(rshift(pat, len), 1) == 1 then + i += -e - 1 + end + i += 1 + len += 1 + e = vals[i] end - if bit(br) == 1 then - i += -e - 1 - end - i += 1 - e = vals[i] + writeu32(t, pat * 4, i * 32 + len) end - local last = t.last - local l0, l1, l2 = last[1], last[2], last[3] - if e ~= vals[l0] then - vals[l2] = vals[l1] - vals[l1] = vals[l0] - vals[l0] = e - end - return e + return t end local function reset(t: BigTree) @@ -248,17 +246,65 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local px = pic.idx :: buffer local stride = pic.stride local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type - reset(mmap) - reset(mclr) - reset(full) - reset(typ) - local br = Smacker.bits(d, 0, buffer.len(d)) + for _, t in { mmap, mclr, full, typ } do + reset(t) + if not t.lut then + t.lut = lut(t.vals) + end + end + local n = buffer.len(d) + local nbits = n * 8 + local pos = 0 + -- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree + local function code(t: BigTree): number + local vals = t.vals + local i, p + local byte = rshift(pos, 3) + if byte + 3 <= n then + local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023) + local ent = readu32(t.lut :: buffer, v * 4) + i = rshift(ent, 5) + p = pos + band(ent, 31) + else + i, p = 1, pos + end + local e = vals[i] + while e < 0 do + if p >= nbits then + return -1 + end + if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then + i += -e - 1 + end + p += 1 + i += 1 + e = vals[i] + end + pos = p + local last = t.last + local l0 = last[1] + if e ~= vals[l0] then + local l1 = last[2] + vals[last[3]] = vals[l1] + vals[l1] = vals[l0] + vals[l0] = e + end + return e + end + local function bit(): number + local p = pos + pos = p + 1 + if p >= nbits then + return 0 + end + return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) + end local bw, bh = pic.w // 4, pic.h // 4 local blocks = bw * bh local blk = 0 while blk < blocks do - local ty = code(typ, br) - if not ty then + local ty = code(typ) + if ty < 0 then return false, "truncated frame" end local run = RUNS[band(rshift(ty, 2), 63) + 1] @@ -283,9 +329,9 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole if blk >= blocks then break end - local clr = code(mclr, br) - local map = code(mmap, br) - if not clr or not map then + local clr = code(mclr) + local map = code(mmap) + if clr < 0 or map < 0 then return false, "truncated frame" end local hi, lo = rshift(clr, 8), band(clr, 255) @@ -303,12 +349,12 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole else local mode = 0 if v4 then - if br.pos >= br.nbits then + if pos >= nbits then return false, "truncated frame" end - if bit(br) == 1 then + if bit() == 1 then mode = 1 - elseif bit(br) == 1 then + elseif bit() == 1 then mode = 2 end end @@ -319,33 +365,29 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole local o = (blk // bw) * stride * 4 + (blk % bw) * 4 if mode == 0 then for r = 0, 3 do - local a = code(full, br) - local b = code(full, br) - if not a or not b then + local a = code(full) + local b = code(full) + if a < 0 or b < 0 then return false, "truncated frame" end - local q = o + r * stride - writeu8(px, q + 2, band(a, 255)) - writeu8(px, q + 3, rshift(a, 8)) - writeu8(px, q, band(b, 255)) - writeu8(px, q + 1, rshift(b, 8)) + -- the first code is the right pixel pair, the second the left one + writeu32(px, o + r * stride, b + a * 65536) end elseif mode == 1 then for half = 0, 1 do - local a = code(full, br) - if not a then + local a = code(full) + if a < 0 then return false, "truncated frame" end - local lo, hi = band(a, 255), rshift(a, 8) - local v = lo * 0x0101 + hi * 0x01010000 + local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000 writeu32(px, o + half * 2 * stride, v) writeu32(px, o + (half * 2 + 1) * stride, v) end else for half = 0, 1 do - local p2 = code(full, br) - local p1 = code(full, br) - if not p1 or not p2 then + local p2 = code(full) + local p1 = code(full) + if p1 < 0 or p2 < 0 then return false, "truncated frame" end local v = p1 + p2 * 65536 diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..f593634 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do jitTune(false) end end +-- ------------------------------------------------------------------------------------------- ws-video2-legacy: fps +do + -- the legacy codecs (codecs/video/Legacy) through F.video.open, rgba8 frames out: ffmpeg's encoders at 320x240 + -- (tools/fixtures/legacy.py), a 320x200 FLC (fli.py) and a 320x200 SMK4 (smk.py, textured: mostly FULL blocks); + -- frames per second of the whole decode (and the Smacker audio track, seconds of audio per second) + local F = require("@formats") + local LB = require("@tests/gen/legacy_bench") + local cases = table.clone(LB) + table.insert(cases, { name = "fli.flc", data = require("@tests/gen/fli_bench").data, width = 320, height = 200 }) + table.insert(cases, { name = "smk4.smk", data = require("@tests/gen/smk_bench").data, width = 320, height = 200 }) + for _, c in cases do + local data = buffer.fromstring(c.data) + local frames = 0 + local dt = math.huge + for _ = 1, 3 do + local t0 = os.clock() + local v = assert(F.video.open(data, { audio = false })) + frames = 0 + while v:nextFrame() do + frames += 1 + end + dt = math.min(dt, os.clock() - t0) + end + print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, string.format("legacy %s %dx%d", c.name, c.width, c.height), dt * 1000 / frames, frames / dt)) + end + local v = assert(F.video.open(buffer.fromstring(require("@tests/gen/smk_bench").data))) + local a = assert(v.audio) + local t0 = os.clock() + local n = 0 + while true do + local _, got = a:read(4096) + if got == 0 then + break + end + n += got + end + local dt = os.clock() - t0 + print(string.format("%-8s %-30s %8.2f ms %7.1fx real time", runtime, "smacker audio 22 kHz stereo", dt * 1000, n / a.sampleRate / dt)) +end diff --git a/tools/fixtures/fli.py b/tools/fixtures/fli.py index 0428f02..e7ad3d6 100644 --- a/tools/fixtures/fli.py +++ b/tools/fixtures/fli.py @@ -393,3 +393,9 @@ def generate(ctx): assert crcs, name cases.append({"name": name, "data": data, "width": w, "height": h, "depth": depth, "rate": rate, "frames": crcs}) ctx.emit("fli_cases", cases) + # tools/bench.luau: a 320x200 FLC, 10 frames (BRUN then SS2 deltas) + w, h, n = 320, 200, 10 + imgs = idx_frames(w, h, n, 256, 9) + frames = [frame([color([(0, pal(256, 9, False))], False), brun([[bytes([v]) for v in r] for r in imgs[0]], 1, True)])] + frames += [frame([ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)] + ctx.emit("fli_bench", {"data": file(0xAF12, w, h, 8, 66, frames), "width": w, "height": h, "frames": n}) diff --git a/tools/fixtures/legacy.py b/tools/fixtures/legacy.py index 863b866..76353ce 100644 --- a/tools/fixtures/legacy.py +++ b/tools/fixtures/legacy.py @@ -98,3 +98,11 @@ def generate(ctx): for c in cases: assert c["frames"], c["name"] + ": ffmpeg decoded no frame" ctx.emit("legacy_cases", cases) + # tools/bench.luau: 320x240, 10 frames of each codec + bench = [] + big = ["-f", "lavfi", "-i", "testsrc2=size=320x240:rate=10", "-t", "1"] + for name, args in [("cinepak.avi", ["-c:v", "cinepak"]), ("msvideo1.avi", ["-c:v", "msvideo1"]), + ("qtrle.mov", ["-c:v", "qtrle", "-pix_fmt", "rgb24"]), ("smc.mov", ["-c:v", "smc"])]: + ff(*big, *args, "bench_" + name) + bench.append({"name": name, "data": open(os.path.join(tmp, "bench_" + name), "rb").read(), "width": 320, "height": 240}) + ctx.emit("legacy_bench", bench) diff --git a/tools/fixtures/smk.py b/tools/fixtures/smk.py index 0d9ee5a..0bfba7a 100644 --- a/tools/fixtures/smk.py +++ b/tools/fixtures/smk.py @@ -381,11 +381,14 @@ def tone(n, ch, bits, rate, seed, f0): # ---------------------------------------------------------------------------------------------------- files -def idx_frames(w, h, n, seed): +def idx_frames(w, h, n, seed, busy=False): rnd = random.Random(seed) out = [] for t in range(n): - img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)] + if busy: # textured, moving: mostly FULL blocks (the bench) + img = [[(x * 3 + y * 5 + ((x + t * 4) * (y + t)) // 7) % 251 for x in range(w)] for y in range(h)] + else: + img = [[(x // 8 + y // 8 * 3) % 40 for x in range(w)] for y in range(h)] for y in range(8, 24): for x in range(8 + t * 4, 24 + t * 4): img[y][x] = 100 + (x + y) % 2 # two colours: MONO blocks @@ -399,10 +402,10 @@ def idx_frames(w, h, n, seed): return out -def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed): +def smk_file(version, w, h, nframes, pts_inc, tracks, ring, seed, busy=False): """version 2 / 4; tracks = [(kind, rate, ch, bits)] kind "packed" / "raw"; returns bytes, track info""" rnd = random.Random(seed) - frames = idx_frames(w, h, nframes, seed) + frames = idx_frames(w, h, nframes, seed, busy) if ring: frames = frames + [frames[0]] treebytes, sizes, video = encode_video(frames, w, h, version == 4, rnd) @@ -491,3 +494,6 @@ def generate(ctx): cases.append({"name": name, "data": data, "width": w, "height": h, "rate": rate, "frames": crcs, "audio": audio, "ring": ring}) ctx.emit("smk_cases", cases) + # tools/bench.luau: a 320x200 SMK4 with 22.05 kHz packed stereo audio, 10 frames + ctx.emit("smk_bench", {"data": smk_file(4, 320, 200, 10, 100, [("packed", 22050, 2, 16)], False, 9, True), "width": 320, + "height": 200, "frames": 10}) From 1d45c661082bf194aae38190ef01b01f0bbc5c92 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:36 -0500 Subject: [PATCH 31/54] ws-3d3-b: docs/guide/scene.md: LWO, .x and IQM (sections with tested snippets, Formats table, intro list) --- docs/guide/scene.md | 82 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..c714ee3 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, LightWave LWO, DirectX .x, IQM) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -378,6 +378,83 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves assert(F.load(vox).voxels[1].size[1] == 4) ``` +## LightWave, DirectX and Inter-Quake models + +**LightWave objects** (`.lwo`: LWO2 and the older LWOB; Modo's `.lxo`) give one node per layer (its pivot as the +translation, parents by layer index), one mesh per layer and one primitive per surface. LightWave is left-handed: z is +negated and the winding reversed on load, so the scene is glTF's right-handed y up. UV maps become `TEXCOORD_n` (one +set per map name), the colour map a surface names becomes `COLOR_0`, weight maps `_WEIGHT_n` and morph maps morph +targets (names in `prim.extras.lwo.maps` / `mesh.extras.targetNames`). Surface values and texture blocks are in +`material.extras.lwo`; image textures keep only the file name as `uri` (`F.model.loadTextures` reads them). Subdivision +cages (`PTCH` / `SUBD`) stay polygons with `prim.extras.lwo.subdivision = true`. + +```luau +-- a one-triangle LWO2 file, built by hand (IFF chunks, big-endian) +local function be(n, bytes) + local s = "" + for i = bytes - 1, 0, -1 do + s ..= string.char(bit32.band(bit32.rshift(n, i * 8), 255)) + end + return s +end +local function f4(x) + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return be(buffer.readu32(b, 0), 4) +end +local function chunk(id, body) + return id .. be(#body, 4) .. body +end +local body = "LWO2" .. chunk("TAGS", "Red\0") .. chunk("LAYR", be(0, 4) .. f4(0) .. f4(0) .. f4(0) .. "Body\0\0") + .. chunk("PNTS", f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0)) + .. chunk("POLS", "FACE" .. be(3, 2) .. be(0, 2) .. be(1, 2) .. be(2, 2)) + .. chunk("PTAG", "SURF" .. be(0, 4)) + .. chunk("SURF", "Red\0\0\0" .. "COLR" .. be(14, 2) .. f4(1) .. f4(0) .. f4(0) .. be(0, 2)) +local scene = assert(F.load("FORM" .. be(#body, 4) .. body)) +assert(scene.nodes[1].name == "Body" and scene.meta.source.version == "LWO2") +assert(scene.materials[1].name == "Red" and scene.materials[1].baseColor[1] == 1) +assert(scene.meshes[1].primitives[1].indices.count == 3) +``` + +**DirectX `.x`** files (text, binary and MSZIP-compressed, 32- or 64-bit floats) give the frame hierarchy, one primitive +per material, materials with their texture file names, skins (`SkinWeights`) and animation sets. Direct3D is +left-handed too: z is negated and the winding reversed. Key times are in seconds (`AnimTicksPerSecond`, default 4800). + +```luau +local text = [[xof 0303txt 0032 +Material Wood { 0.8; 0.6; 0.4; 1.0;; 20.0; 0.1; 0.1; 0.1;; 0.0; 0.0; 0.0;; TextureFilename { "wood.png"; } } +Frame Root { + FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,5,1;; } + Mesh Tri { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3;0,1,2;; MeshMaterialList { 1; 1; 0;; { Wood } } } +} +]] +local scene = assert(F.load(text, { format = "x" })) +local root = scene.nodes[1] +assert(root.name == "Root" and root.translation[3] == -5) -- z negated +assert(scene.materials[1].name == "Wood") +assert(scene.textures[scene.materials[1].baseColorTexture.texture].uri == "wood.png") +local glb = assert(F.save(scene, nil, { format = "glb" })) +``` + +**IQM** (Inter-Quake Model, version 2) reads and writes meshes, every vertex array, the skeleton (a node per joint and +one skin), animations (dequantized frames as translation / rotation / scale channels, loop flags and frame ranges in +`meta.source.animations`) and per-frame bounds. IQM is z-up (`meta.up = "z"`); nothing is rotated either way. The +writer turns any Scene's triangles into IQM meshes, merges the skins into one skeleton and samples each animation at +its key spacing when uniform (else `opts.framerate`, default 30 frames per second). + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") +local iqm = assert(F.save(scene, nil, { format = "iqm" })) +local back = assert(F.load(iqm)) +assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri") +assert(back.meshes[1].primitives[1].indices.count == 3) +``` + ## Formats | Format | Read | Write | Notes | @@ -392,6 +469,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| LightWave LWO (LWO2, LWOB, Modo LXOB) | yes | | layers, vertex maps, surfaces; see below | +| DirectX .x (text, binary, MSZIP) | yes | | frames, materials, skins, animation | +| IQM (Inter-Quake Model) | yes | yes | skeleton, skin, sampled animations, bounds | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). From abd01270f0bc4be99076bd5aa08ce770cdba7f5c Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:02 -0500 Subject: [PATCH 32/54] ws-tex: image/exr (read NONE/RLE/ZIPS/ZIP/PIZ, half/float/uint, scanline + tiled + multipart, mips; write NONE/ZIPS/ZIP) Tested against the OpenEXR 3.5 python bindings, exrmaketiled (one level / mipmap / ripmap / round up), exrmultipart, a hand-written subsampled file; PXR24 / B44 / DWAA give UNSUPPORTED; our files read back by the bindings and exrheader. Broken / zeroed offset tables are rebuilt (exrmultipart writes them zeroed). --- docs/FORMATS.md | 1 + licenses/NOTICE.md | 1 + licenses/openexr-LICENSE.md | 11 + src/Formats/Registry.luau | 12 + src/Formats/image/exr/Codec.luau | 117 +++++ src/Formats/image/exr/Piz.luau | 367 +++++++++++++++ src/Formats/image/exr/init.luau | 782 +++++++++++++++++++++++++++++++ tests/image/exr.luau | 143 ++++++ tools/bench.luau | 17 + tools/fixtures/_tex_encode.luau | 15 + tools/fixtures/exr.py | 195 ++++++++ 11 files changed, 1661 insertions(+) create mode 100644 licenses/openexr-LICENSE.md create mode 100644 src/Formats/image/exr/Codec.luau create mode 100644 src/Formats/image/exr/Piz.luau create mode 100644 src/Formats/image/exr/init.luau create mode 100644 tests/image/exr.luau create mode 100644 tools/fixtures/exr.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 46d0547..48b6db4 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -7,6 +7,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build |---|---|---|---|---|---|---| | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | +| image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` | | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | diff --git a/licenses/NOTICE.md b/licenses/NOTICE.md index 1fa543c..23e52ba 100644 --- a/licenses/NOTICE.md +++ b/licenses/NOTICE.md @@ -39,6 +39,7 @@ | `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) | | `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data | | `src/Formats/codecs/image/Bcn/Decode.luau` (the BC1..BC7 block decoders and the BPTC tables; changed to follow the D3D11 rules) | Pillow 12 `src/libImaging/BcnDecode.c` | CC0 1.0: [pillow-bcn-CC0.txt](pillow-bcn-CC0.txt) | +| `src/Formats/image/exr/Piz.luau`, `src/Formats/image/exr/Codec.luau` (the PIZ Huffman / wavelet / LUT steps and the ZIP / RLE byte predictor, re-implemented in Luau after the OpenEXR algorithms) | OpenEXR 3.x (ImfPizCompressor, ImfHuf, ImfWav, ImfZip, ImfRle) | BSD-3-Clause: [openexr-LICENSE.md](openexr-LICENSE.md) | Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this folder (see docs/STYLE.md, "Absorbing an existing repo"). diff --git a/licenses/openexr-LICENSE.md b/licenses/openexr-LICENSE.md new file mode 100644 index 0000000..b2a016e --- /dev/null +++ b/licenses/openexr-LICENSE.md @@ -0,0 +1,11 @@ +Copyright (c) Contributors to the OpenEXR Project. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 718bbaa..beaefc8 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -38,6 +38,18 @@ local list: { Entry } = { return require("@formats/image/dds") end, }, + { + name = "exr", + category = "image", + path = "image/exr", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, + load = function() + return require("@formats/image/exr") + end, + }, { name = "gif", category = "image", diff --git a/src/Formats/image/exr/Codec.luau b/src/Formats/image/exr/Codec.luau new file mode 100644 index 0000000..a369338 --- /dev/null +++ b/src/Formats/image/exr/Codec.luau @@ -0,0 +1,117 @@ +--!strict +--!native +--!optimize 2 +-- image/exr/Codec: the OpenEXR byte-level codecs (from the OpenEXR file layout document and ImfZip / ImfRle, BSD-3- +-- Clause): RLE and ZIP / ZIPS decode (run lengths or zlib, then the delta predictor and the two-half byte interleave), +-- ZIP encode, and the per-line channel sample conversion to floats. Never throws. +local Deflate = require("@formats/codecs/compress/Deflate") +local Half = require("@formats/codecs/image/Half") + +local Codec = {} + +local readu8, writeu8, readi8, readu16, readu32, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readi8, buffer.readu16, buffer.readu32, buffer.readf32, buffer.writef32 +local HALF = Half.TABLE + +-- undoes the predictor and the interleave of t (n bytes) -> a new buffer +local function reconstruct(t: buffer, n: number): buffer + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + prev = (prev + readu8(t, i) - 128) % 256 + writeu8(t, i, prev) + end + local out = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, half - 1 do + writeu8(out, i * 2, readu8(t, i)) + end + for i = 0, n - half - 1 do + writeu8(out, i * 2 + 1, readu8(t, half + i)) + end + return out +end + +-- rle(src, p, n, outSize) -> the raw block | nil, message +function Codec.rle(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t = buffer.create(outSize) + local o, stop = 0, p + n + while p < stop do + local c = readi8(src, p) + p += 1 + if c < 0 then + local cnt = -c + if p + cnt > stop or o + cnt > outSize then + return nil, "bad RLE run" + end + buffer.copy(t, o, src, p, cnt) + p += cnt + o += cnt + else + if p >= stop or o + c + 1 > outSize then + return nil, "bad RLE run" + end + buffer.fill(t, o, readu8(src, p), c + 1) + p += 1 + o += c + 1 + end + end + if o ~= outSize then + return nil, "RLE data too short" + end + return reconstruct(t, outSize), nil +end + +-- zip(src, p, n, outSize) -> the raw block | nil, message (ZIP and ZIPS) +function Codec.unzip(src: buffer, p: number, n: number, outSize: number): (buffer?, string?) + local t, err = Deflate.zlib(src, p, n, outSize) + if not t then + return nil, tostring(err) + end + if buffer.len(t) ~= outSize then + return nil, "zlib block has the wrong size" + end + return reconstruct(t, outSize), nil +end + +-- zipEncode(raw, level) -> the compressed block (interleave, predictor, zlib) +function Codec.zip(raw: buffer, level: number): buffer + local n = buffer.len(raw) + local t = buffer.create(n) + local half = (n + 1) // 2 + for i = 0, n - 1 do + local v = readu8(raw, i) + if i % 2 == 0 then + writeu8(t, i // 2, v) + else + writeu8(t, half + i // 2, v) + end + end + local prev = if n > 0 then readu8(t, 0) else 0 + for i = 1, n - 1 do + local v = readu8(t, i) + writeu8(t, i, (v - prev + 384) % 256) + prev = v + end + return Deflate.zlibCompress(t, { level = level }) :: buffer +end + +-- samples(src, p, count, kind, dst, d, step) -> reads count samples of kind (0 uint, 1 half, 2 float) at p into +-- dst (f32) at byte offset d, step bytes apart; returns the source offset after them +function Codec.samples(src: buffer, p: number, count: number, kind: number, dst: buffer, d: number, step: number): number + if kind == 1 then + for i = 0, count - 1 do + writef32(dst, d + i * step, HALF[readu16(src, p + i * 2)]) + end + return p + count * 2 + elseif kind == 2 then + for i = 0, count - 1 do + writef32(dst, d + i * step, readf32(src, p + i * 4)) + end + else + for i = 0, count - 1 do + writef32(dst, d + i * step, readu32(src, p + i * 4)) + end + end + return p + count * 4 +end + +return Codec diff --git a/src/Formats/image/exr/Piz.luau b/src/Formats/image/exr/Piz.luau new file mode 100644 index 0000000..3016030 --- /dev/null +++ b/src/Formats/image/exr/Piz.luau @@ -0,0 +1,367 @@ +--!strict +--!native +--!optimize 2 +-- image/exr/Piz: OpenEXR's PIZ decompressor (written from the OpenEXR 3.x sources' algorithm description: ImfPizCompressor +-- / ImfHuf / ImfWav, BSD-3-Clause, licenses/openexr-LICENSE.md): the range bitmap and its reverse LUT, the Huffman +-- stream (packed code lengths, canonical codes, the run-length symbol), the 2-D Haar wavelet (14- and 16-bit +-- variants) per channel plane, then the planes rearranged into scanlines. Never throws: nil, message on bad data. +local Piz = {} + +local readu8, readu16, writeu16, readu32 = buffer.readu8, buffer.readu16, buffer.writeu16, buffer.readu32 +local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift + +local USHORT_RANGE, BITMAP_SIZE = 65536, 8192 +local HUF_ENCSIZE = 65537 +local DECBITS = 14 +local SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN = 59, 63, 6 + +-- ------------------------------------------------------------------------------------------------ Huffman +-- the canonical code table: lengths[i] and codes[i] for symbols im..iM (1-based tables: symbol s at s + 1) +local function unpackTable(src: buffer, p: number, limit: number, im: number, iM: number, len: { number }): number? + local c, lc = 0, 0 + local function bits(n: number): number? + while lc < n do + if p >= limit then + return nil + end + c = c * 256 + readu8(src, p) + p += 1 + lc += 8 + end + lc -= n + local v = c // 2 ^ lc + c -= v * 2 ^ lc + return v + end + local i = im + while i <= iM do + local l = bits(6) + if not l then + return nil + end + if l == LONG_ZEROCODE_RUN then + local z = bits(8) + if not z then + return nil + end + z += SHORTEST_LONG_RUN + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + elseif l >= SHORT_ZEROCODE_RUN then + local z = l - SHORT_ZEROCODE_RUN + 2 + if i + z > iM + 1 then + return nil + end + for k = i, i + z - 1 do + len[k + 1] = 0 + end + i += z + else + len[i + 1] = l + i += 1 + end + end + return p +end + +-- hufUncompress: nRaw u16 values from [p, p + n) into out (a buffer of u16) | nil, message +local function huffman(src: buffer, p: number, n: number, out: buffer, nRaw: number): string? + if n == 0 then + return if nRaw == 0 then nil else "empty Huffman data" + end + if n < 20 then + return "truncated Huffman header" + end + local im, iM, nBits = readu32(src, p), readu32(src, p + 4), readu32(src, p + 12) + if im >= HUF_ENCSIZE or iM >= HUF_ENCSIZE or im > iM then + return "bad Huffman symbol range" + end + local limit = p + n + local len = table.create(HUF_ENCSIZE, 0) + local q = unpackTable(src, p + 20, limit, im, iM, len) + if not q then + return "bad Huffman table" + end + if q + (nBits + 7) // 8 > limit then + return "truncated Huffman data" + end + -- canonical codes (OpenEXR's order: longest codes get the smallest values) + local count = table.create(59, 0) + for s = im, iM do + local l = len[s + 1] + if l > 58 then + return "bad Huffman code length" + end + count[l + 1] += 1 + end + local start = table.create(59, 0) + local c = 0 + for l = 58, 1, -1 do + local nc = (c + count[l + 1]) // 2 + start[l + 1] = c + c = nc + end + local fast = buffer.create(lshift(1, DECBITS) * 4) -- (symbol + 1) * 64 + length; 0 = long or invalid + local long: { [number]: { [number]: number } } = {} + local maxLong = 0 + for s = im, iM do + local l = len[s + 1] + if l > 0 then + local code = start[l + 1] + start[l + 1] = code + 1 + if l <= DECBITS then + local base = code * 2 ^ (DECBITS - l) + local v = (s + 1) * 64 + l + for k = base, base + 2 ^ (DECBITS - l) - 1 do + if k < lshift(1, DECBITS) then + buffer.writeu32(fast, k * 4, v) + end + end + else + if l > 52 then + return "unsupported: Huffman code longer than 52 bits" + end + local t = long[l] + if not t then + t = {} + long[l] = t + end + t[code] = s + maxLong = math.max(maxLong, l) + end + end + end + -- decode MSB-first from a zero-padded copy + local nbytes = (nBits + 7) // 8 + local data = buffer.create(nbytes + 8) + buffer.copy(data, 0, src, q, nbytes) + local bp = 0 + local o = 0 + local rlc = iM + local mask = lshift(1, DECBITS) - 1 + while bp < nBits do + local byte = rshift(bp, 3) + local w = bit32.byteswap(readu32(data, byte)) + local peek = band(rshift(w, 32 - DECBITS - band(bp, 7)), mask) + local e = readu32(fast, peek * 4) + local sym: number, l: number = 0, 0 + if e ~= 0 then + sym = e // 64 - 1 + l = band(e, 63) + else + -- a long code: bit by bit from length 15 + sym = -1 + local code = 0 + for k = 0, maxLong - 1 do + local bitAt = bp + k + code = code * 2 + band(rshift(readu8(data, rshift(bitAt, 3)), 7 - band(bitAt, 7)), 1) + if k + 1 > DECBITS then + local t = long[k + 1] + local found: number? = if t then t[code] else nil + if found then + sym = found + l = k + 1 + break + end + end + end + if sym < 0 then + return "invalid Huffman code" + end + end + bp += l + if bp > nBits then + return "Huffman code past the end of the data" + end + if sym == rlc then + if bp + 8 > nBits then + return "truncated run length" + end + local b2 = bit32.byteswap(readu32(data, rshift(bp, 3))) + local cs = band(rshift(b2, 24 - band(bp, 7)), 255) + bp += 8 + if o + cs > nRaw then + return "too much Huffman data" + end + if o == 0 then + return "run length at the start" + end + local s = readu16(out, (o - 1) * 2) + for _ = 1, cs do + writeu16(out, o * 2, s) + o += 1 + end + else + if o >= nRaw then + return "too much Huffman data" + end + writeu16(out, o * 2, sym) + o += 1 + end + end + if o ~= nRaw then + return "not enough Huffman data" + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ wavelet +-- the inverse 2-D Haar wavelet over n x ny u16 values at element offset base, strides ox / oy (in elements) +local function wav2Decode(t: buffer, base: number, nx: number, ox: number, ny: number, oy: number, mx: number) + local w14 = mx < 16384 + local n = math.min(nx, ny) + local p = 1 + while p <= n do + p *= 2 + end + p //= 2 + local p2 = p + p //= 2 + local function dec(l: number, h: number): (number, number) + if w14 then + local ls = if l >= 32768 then l - 65536 else l + local hs = if h >= 32768 then h - 65536 else h + local ai = ls + hs % 2 + hs // 2 + return ai % 65536, (ai - hs) % 65536 + end + local bb = (l - rshift(h, 1)) % 65536 + return (h + bb - 32768) % 65536, bb + end + while p >= 1 do + local oy1, oy2, ox1, ox2 = oy * p, oy * p2, ox * p, ox * p2 + local py = base + local ey = base + oy * (ny - p2) + while py <= ey do + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local p10 = px + oy1 + local p11 = p10 + ox1 + local i00, i10 = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + local i01, i11 = dec(readu16(t, p01 * 2), readu16(t, p11 * 2)) + local a, b = dec(i00, i01) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + local c, d = dec(i10, i11) + writeu16(t, p10 * 2, c) + writeu16(t, p11 * 2, d) + px += ox2 + end + if band(nx, p) ~= 0 then + local p10 = px + oy1 + local a, b = dec(readu16(t, px * 2), readu16(t, p10 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p10 * 2, b) + end + py += oy2 + end + if band(ny, p) ~= 0 then + local px = py + local ex = py + ox * (nx - p2) + while px <= ex do + local p01 = px + ox1 + local a, b = dec(readu16(t, px * 2), readu16(t, p01 * 2)) + writeu16(t, px * 2, a) + writeu16(t, p01 * 2, b) + px += ox2 + end + end + p2 = p + p //= 2 + end +end + +-- ------------------------------------------------------------------------------------------------ decode +export type Chan = { nx: number, ny: number, size: number, ys: number } + +-- decode(src, p, n, chans, minY, maxY, outSize) -> the uncompressed block (scanline order) | nil, message. +-- chans: per channel (sorted order) its sample counts nx / ny in the block, size (1 = half, 2 = float / uint) and +-- ySampling. +function Piz.decode(src: buffer, p: number, n: number, chans: { Chan }, minY: number, maxY: number, outSize: number): (buffer?, string?) + local total = 0 + for _, c in chans do + total += c.nx * c.ny * c.size + end + if total * 2 ~= outSize then + return nil, "PIZ block size mismatch" + end + local out = buffer.create(outSize) + if total == 0 then + return out, nil + end + local limit = p + n + if p + 4 > limit then + return nil, "truncated PIZ header" + end + local minNZ, maxNZ = readu16(src, p), readu16(src, p + 2) + p += 4 + if maxNZ >= BITMAP_SIZE then + return nil, "bad PIZ bitmap range" + end + local bitmap = buffer.create(BITMAP_SIZE) + if minNZ <= maxNZ then + local cnt = maxNZ - minNZ + 1 + if p + cnt > limit then + return nil, "truncated PIZ bitmap" + end + buffer.copy(bitmap, minNZ, src, p, cnt) + p += cnt + end + -- reverse LUT + local lut = buffer.create(USHORT_RANGE * 2) + local k = 0 + for i = 0, USHORT_RANGE - 1 do + if i == 0 or band(readu8(bitmap, rshift(i, 3)), lshift(1, band(i, 7))) ~= 0 then + writeu16(lut, k * 2, i) + k += 1 + end + end + local maxValue = k - 1 + if p + 4 > limit then + return nil, "truncated PIZ length" + end + local length = readu32(src, p) + p += 4 + if length > limit - p then + return nil, "truncated PIZ data" + end + local tmp = buffer.create(total * 2) + local herr = huffman(src, p, length, tmp, total) + if herr then + return nil, herr + end + local starts = table.create(#chans, 0) + local at = 0 + for i, c in chans do + starts[i] = at + for j = 0, c.size - 1 do + wav2Decode(tmp, at + j, c.nx, c.size, c.ny, c.nx * c.size, maxValue) + end + at += c.nx * c.ny * c.size + end + for i = 0, total - 1 do + writeu16(tmp, i * 2, readu16(lut, readu16(tmp, i * 2) * 2)) + end + -- planes -> scanlines + local o = 0 + local cursor = table.clone(starts) + for y = minY, maxY do + for i, c in chans do + if y % c.ys == 0 then + local cnt = c.nx * c.size + buffer.copy(out, o, tmp, cursor[i] * 2, cnt * 2) + cursor[i] += cnt + o += cnt * 2 + end + end + end + return out, nil +end + +return Piz diff --git a/src/Formats/image/exr/init.luau b/src/Formats/image/exr/init.luau new file mode 100644 index 0000000..58e4922 --- /dev/null +++ b/src/Formats/image/exr/init.luau @@ -0,0 +1,782 @@ +--!strict +-- image/exr: OpenEXR (the OpenEXR file layout and technical introduction documents, openexr.com; new code, the PIZ +-- decoder written after OpenEXR's algorithm, BSD-3-Clause: licenses/openexr-LICENSE.md). Decode: single-part and +-- multipart files (opts.part: 1-based index or part name; meta.source.parts lists them), scanline and tiled parts +-- (one level, mip-map and rip-map levels: level 0, plus the mip-map levels into img.meta.mipmaps with opts.mips), +-- compression NONE / RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, x / y subsampled channels (nearest), any +-- line order, broken offset tables (rebuilt from the chunks of single-part files). R / G / B / A map to the image +-- (opts.layer = "diffuse" reads diffuse.R ...); a Y-only image is grey; every channel name is in meta.source.channels. +-- The image is the data window (meta.dataWindow / meta.displayWindow keep both boxes). opts.native gives the linear +-- rgbaf32 values; the default rgba8 is a display conversion like image/hdr's: round(clamp(v, 0, 1) ^ (1 / 2.2) * 255) +-- for colour, round(clamp(a, 0, 1) * 255) for alpha. +-- Encode: rgbaf32 (or rgba8 through the inverse curve) as a scanline file, HALF (default) or FLOAT channels, A only +-- when some alpha is not 1, compression NONE, ZIPS or ZIP (default). Not supported: deep data, PXR24 / B44 / B44A / +-- DWAA / DWAB / HTJ2K / ZSTD compression (UNSUPPORTED naming the method), RY / BY chroma (the Y channel is used). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Half = require("@formats/codecs/image/Half") +local Codec = require("@formats/image/exr/Codec") +local Piz = require("@formats/image/exr/Piz") + +-- ------------------------------------------------------------------------------------------------ contract +local Exr = { + name = "exr", + category = "image", + extensions = { "exr" }, + mime = { "image/x-exr", "image/aces" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Half", "codecs/compress/Deflate" }, + caps = { decode = true, encode = true, alpha = true, float = true, hdr = true, depths = { 16, 32 }, multipart = true, tiled = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- linear rgbaf32 (default false: rgba8 through a 1 / 2.2 display gamma) + part: (number | string)?, -- multipart files: the part to read (1-based index or name; default 1) + layer: string?, -- read .R / .G / .B / .A instead of R / G / B / A + mips: boolean?, -- tiled mip-map parts: decode the smaller levels into img.meta.mipmaps (default false) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + compression: ("none" | "zips" | "zip")?, -- default "zip" + pixelType: ("half" | "float")?, -- default "half" + alpha: boolean?, -- write A (default: when some alpha is not 1) + level: number?, -- zlib level 1..9 (default 6) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "\118\47\49\1" +local COMPRESSION: { [number]: string } = { [0] = "none", "rle", "zips", "zip", "piz", "pxr24", "b44", "b44a", "dwaa", "dwab", "htj2k256", "htj2k32", "zstd" } +local LINES: { [number]: number } = { [0] = 1, 1, 1, 16, 32, 16, 32, 32, 32, 256 } +local GAMMA = 1 / 2.2 + +local readu8, readu32, readi32, readf32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ sniff +function Exr.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +type Channel = { name: string, kind: number, linear: boolean, xs: number, ys: number } +type Part = { + attrs: { [string]: any }, + channels: { Channel }, + compression: number, + box: { number }, -- data window xMin, yMin, xMax, yMax + display: { number }, + tiled: boolean, + tiles: { number }?, -- xSize, ySize, mode, rounding + name: string?, + type: string?, + chunks: number, + offsets: { number }, +} + +local function cstr(b: buffer, p: number, limit: number, max: number): (string?, number) + local q = p + while q < limit and q - p <= max do + if readu8(b, q) == 0 then + return readstring(b, p, q - p), q + 1 + end + q += 1 + end + return nil, q +end + +local function f32(b: buffer, o: number): number + return readf32(b, o) +end + +-- one attribute value of a known type +local function value(b: buffer, p: number, size: number, typ: string): any + if typ == "chlist" then + local list: { Channel } = {} + local q, stop = p, p + size + while q < stop and readu8(b, q) ~= 0 do + local name, nq = cstr(b, q, stop, 255) + if not name or nq + 16 > stop then + return nil + end + table.insert(list, { name = name, kind = readi32(b, nq), linear = readu8(b, nq + 4) ~= 0, xs = readi32(b, nq + 8), ys = readi32(b, nq + 12) }) + q = nq + 16 + end + return list + elseif typ == "compression" or typ == "lineOrder" or typ == "envmap" or typ == "deepImageState" then + return if size >= 1 then readu8(b, p) else nil + elseif typ == "box2i" then + return if size >= 16 then { readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12) } else nil + elseif typ == "box2f" then + return if size >= 16 then { f32(b, p), f32(b, p + 4), f32(b, p + 8), f32(b, p + 12) } else nil + elseif typ == "v2i" then + return if size >= 8 then { readi32(b, p), readi32(b, p + 4) } else nil + elseif typ == "v2f" then + return if size >= 8 then { f32(b, p), f32(b, p + 4) } else nil + elseif typ == "v3f" then + return if size >= 12 then { f32(b, p), f32(b, p + 4), f32(b, p + 8) } else nil + elseif typ == "float" then + return if size >= 4 then f32(b, p) else nil + elseif typ == "double" then + return if size >= 8 then buffer.readf64(b, p) else nil + elseif typ == "int" then + return if size >= 4 then readi32(b, p) else nil + elseif typ == "string" then + return readstring(b, p, size) + elseif typ == "tiledesc" then + if size < 9 then + return nil + end + local m = readu8(b, p + 8) + return { readu32(b, p), readu32(b, p + 4), m % 16, m // 16 } + elseif typ == "chromaticities" then + if size < 32 then + return nil + end + local t = {} + for i = 0, 7 do + t[i + 1] = f32(b, p + i * 4) + end + return t + end + local raw = buffer.create(size) + buffer.copy(raw, 0, b, p, size) + return raw +end + +-- the attributes of one header from p -> attrs, the offset after its terminating NUL | nil, Err +local function header(b: buffer, p: number, limit: number): ({ [string]: any }?, number, Err.Err?) + local attrs: { [string]: any } = {} + local types: { [string]: string } = {} + while true do + if p >= limit then + return nil, p, Err.new(Err.TRUNCATED, "header runs past the end", p) + end + if readu8(b, p) == 0 then + attrs._types = types + return attrs, p + 1, nil + end + local name, q = cstr(b, p, limit, 255) + if not name then + return nil, p, Err.new(Err.CORRUPT, "bad attribute name", p) + end + local typ, q2 = cstr(b, q, limit, 255) + if not typ then + return nil, p, Err.new(Err.CORRUPT, "bad attribute type", q) + end + if q2 + 4 > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute size runs past the end", q2) + end + local size = readi32(b, q2) + if size < 0 or q2 + 4 + size > limit then + return nil, p, Err.new(Err.TRUNCATED, "attribute " .. name .. " runs past the end", q2) + end + attrs[name] = value(b, q2 + 4, size, typ) + types[name] = typ + p = q2 + 4 + size + end +end + +-- level sizes of a tiled part +local function levelSize(n: number, l: number, roundUp: boolean): number + local d = 2 ^ l + return math.max(1, if roundUp then math.ceil(n / d) else n // d) +end +local function levelCount(w: number, h: number, mode: number, roundUp: boolean): (number, number) + local function count(n: number): number + local c = 1 + while levelSize(n, c - 1, roundUp) > 1 do + c += 1 + end + return c + end + if mode == 0 then + return 1, 1 + elseif mode == 1 then + local c = count(math.max(w, h)) + return c, c + end + return count(w), count(h) +end + +-- chunk count of a part (single-part files: computed) +local function chunkCount(pt: Part): number + local w, h = pt.box[3] - pt.box[1] + 1, pt.box[4] - pt.box[2] + 1 + if not pt.tiled then + return (h + LINES[pt.compression] - 1) // LINES[pt.compression] + end + local t = pt.tiles :: { number } + local tx, ty, mode, roundUp = t[1], t[2], t[3], t[4] == 1 + local lx, ly = levelCount(w, h, mode, roundUp) + local n = 0 + if mode == 2 then + for y = 0, ly - 1 do + for x = 0, lx - 1 do + n += math.ceil(levelSize(w, x, roundUp) / tx) * math.ceil(levelSize(h, y, roundUp) / ty) + end + end + else + for l = 0, lx - 1 do + n += math.ceil(levelSize(w, l, roundUp) / tx) * math.ceil(levelSize(h, l, roundUp) / ty) + end + end + return n +end + +export type Info = { multipart: boolean, tiled: boolean, deep: boolean, parts: { Part }, dataStart: number } + +local function parse(r: Bytes.Reader): (Info?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 8 or readstring(b, base, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not an OpenEXR file", base) + end + local ver = readu32(b, base + 4) + if ver % 256 ~= 2 then + return nil, Err.new(Err.UNSUPPORTED, "version " .. ver % 256, base + 4) + end + local flags = ver // 256 + local tiledFlag, deep, multi = bit32.band(flags, 2) ~= 0, bit32.band(flags, 8) ~= 0, bit32.band(flags, 16) ~= 0 + local info: Info = { multipart = multi, tiled = tiledFlag, deep = deep, parts = {}, dataStart = 0 } + local p = base + 8 + repeat + local attrs, q, herr = header(b, p, limit) + if not attrs then + return nil, herr + end + p = q + local chans = attrs.channels + local box = attrs.dataWindow + if type(chans) ~= "table" or type(box) ~= "table" or type(attrs.compression) ~= "number" then + return nil, Err.new(Err.CORRUPT, "missing channels / dataWindow / compression", p) + end + local typ = attrs.type + local pt: Part = { + attrs = attrs, + channels = chans, + compression = attrs.compression, + box = box, + display = attrs.displayWindow or box, + tiled = if typ then (typ == "tiledimage" or typ == "deeptile") else tiledFlag, + tiles = attrs.tiles, + name = attrs.name, + type = typ, + chunks = 0, + offsets = {}, + } + if pt.tiled and type(pt.tiles) ~= "table" then + return nil, Err.new(Err.CORRUPT, "tiled part without tiles", p) + end + if box[3] < box[1] or box[4] < box[2] or box[3] - box[1] >= 2 ^ 24 or box[4] - box[2] >= 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad data window", p) + end + if pt.tiled and ((pt.tiles :: any)[1] < 1 or (pt.tiles :: any)[2] < 1) then + return nil, Err.new(Err.CORRUPT, "bad tile size", p) + end + for _, c in chans do + if c.xs < 1 or c.ys < 1 or c.kind < 0 or c.kind > 2 then + return nil, Err.new(Err.CORRUPT, "bad channel " .. c.name, p) + end + end + table.insert(info.parts, pt) + if #info.parts > 4096 then + return nil, Err.new(Err.LIMIT, "too many parts", p) + end + until not multi or (p < limit and readu8(b, p) == 0) + if multi then + p += 1 + end + -- offset tables + for _, pt in info.parts do + local n = if type(pt.attrs.chunkCount) == "number" then pt.attrs.chunkCount else (if LINES[pt.compression] then chunkCount(pt) else 0) + if n < 0 or n > 2 ^ 24 then + return nil, Err.new(Err.CORRUPT, "bad chunk count", p) + end + pt.chunks = n + if p + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "offset table runs past the end", p) + end + for i = 0, n - 1 do + pt.offsets[i + 1] = readu32(b, p + i * 8) + readu32(b, p + i * 8 + 4) * 4294967296 + end + p += n * 8 + end + info.dataStart = p - base + return info, nil +end + +-- info(r) -> { multipart, tiled, deep, parts = { { name, type, attrs, channels, compression, box, ... } } } | nil, Err +function Exr.info(r: Bytes.Reader): (Info?, Err.Err?) + return parse(r) +end + +-- bytes of a sample kind +local SIZE = { [0] = 4, 2, 4 } + +-- number of multiples of s in [a, b] +local function samples(a: number, b: number, s: number): number + return b // s - (a - 1) // s +end + +type Target = { [number]: number } -- channel index -> output component (0..3, 4 = grey) + +local function newPlane(pw: number, ph: number): buffer + local px = buffer.create(pw * ph * 16) + for i = 0, pw * ph - 1 do + buffer.writef32(px, i * 16 + 12, 1) + end + return px +end +-- one decompressed block: the lines y0..y1 (absolute), columns x0..x0 + bw - 1 of plane (pw wide, origin ox, oy) +local function block(part: Part, target: Target, data: buffer, dp: number, y0: number, y1: number, x0: number, bw: number, plane: buffer, pw: number, ph: number, ox: number, oy: number): Err.Err? + local p = dp + for y = y0, y1 do + for i, c in part.channels do + if y % c.ys == 0 then + local nx = if c.xs == 1 then bw else samples(x0, x0 + bw - 1, c.xs) + local sz = SIZE[c.kind] + if p + nx * sz > buffer.len(data) then + return Err.new(Err.CORRUPT, "block too short") + end + local k = target[i] + if k ~= nil then + local row = y - oy + if c.xs == 1 and c.ys == 1 and k < 4 then + Codec.samples(data, p, nx, c.kind, plane, (row * pw + (x0 - ox)) * 16 + k * 4, 16) + else + local tmp = buffer.create(nx * 4) + Codec.samples(data, p, nx, c.kind, tmp, 0, 4) + local first = (x0 + c.xs - 1) // c.xs * c.xs + for s = 0, nx - 1 do + local v = buffer.readf32(tmp, s * 4) + local sx = first + s * c.xs + for yy = row, math.min(row + c.ys - 1, ph - 1) do + for xx = sx - ox, math.min(sx - ox + c.xs - 1, pw - 1) do + local o = (yy * pw + xx) * 16 + if k == 4 then + buffer.writef32(plane, o, v) + buffer.writef32(plane, o + 4, v) + buffer.writef32(plane, o + 8, v) + else + buffer.writef32(plane, o + k * 4, v) + end + end + end + end + end + end + p += nx * sz + end + end + end + return nil +end + +-- the raw bytes of a block (uncompressed size raw) +local function unpack(b: buffer, comp: number, part: Part, p: number, size: number, raw: number, y0: number, y1: number, x0: number, bw: number): (buffer?, number, Err.Err?) + if size == raw or comp == 0 then + if size < raw then + return nil, 0, Err.new(Err.CORRUPT, "short uncompressed block", p) + end + return b, p, nil + end + local out, err + if comp == 1 then + out, err = Codec.rle(b, p, size, raw) + elseif comp == 2 or comp == 3 then + out, err = Codec.unzip(b, p, size, raw) + else + local chans: { Piz.Chan } = {} + for i, c in part.channels do + chans[i] = { nx = samples(x0, x0 + bw - 1, c.xs), ny = samples(y0, y1, c.ys), size = SIZE[c.kind] // 2, ys = c.ys } + end + out, err = Piz.decode(b, p, size, chans, y0, y1, raw) + end + if not out then + return nil, 0, Err.from(err, p) + end + return out, 0, nil +end + +local function rawSize(part: Part, y0: number, y1: number, x0: number, bw: number): number + local n = 0 + for y = y0, y1 do + for _, c in part.channels do + if y % c.ys == 0 then + n += samples(x0, x0 + bw - 1, c.xs) * SIZE[c.kind] + end + end + end + return n +end + +function Exr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local info, perr = parse(r) + if not info then + return nil, perr + end + local b, base, limit = r.buf, r.base, r.limit + local want = opts and opts.part or 1 + local pt: Part? = nil + local partIndex = 0 + for i, p in info.parts do + if (type(want) == "number" and i == want) or (type(want) == "string" and p.name == want) then + pt, partIndex = p, i + end + end + if not pt then + return nil, Err.new(Err.ARG, "no part " .. tostring(want)) + end + local part = pt :: Part + if info.deep or (part.type and string.find(part.type, "deep")) then + return nil, Err.new(Err.UNSUPPORTED, "deep data") + end + local comp: number = part.compression + if comp > 4 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. (COMPRESSION[comp] or tostring(comp))) + end + local box = part.box + local xMin, yMin, xMax, yMax = box[1], box[2], box[3], box[4] + local w, h = xMax - xMin + 1, yMax - yMin + 1 + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel -> output component + local prefix = if opts and opts.layer then opts.layer .. "." else "" + local target: Target = {} + local hasRgb = false + for i, c in part.channels do + local n = c.name + if string.sub(n, 1, #prefix) == prefix then + local s = string.sub(n, #prefix + 1) + local k = if s == "R" or s == "r" then 0 elseif s == "G" or s == "g" then 1 elseif s == "B" or s == "b" then 2 elseif s == "A" or s == "a" then 3 else nil + if k then + target[i] = k + hasRgb = hasRgb or k < 3 + end + end + end + if not hasRgb then + for i, c in part.channels do + if c.name == prefix .. "Y" then + target[i] = 4 + end + end + end + local multi = info.multipart + -- offsets: single-part tables with holes are rebuilt from the chunk sequence + local offsets = part.offsets + local bad = false + for _, o in offsets do + if o < info.dataStart or base + o + 8 > limit then + bad = true + break + end + end + if bad then + -- rebuild from the chunk sequence (every part's chunks follow the tables; multipart chunks name their part) + offsets = {} + local p = base + info.dataStart + local total = 0 + for _, q in info.parts do + total += q.chunks + end + for _ = 1, total do + local pi = 1 + local at = p + if multi then + if p + 4 > limit then + break + end + pi = readi32(b, p) + 1 + p += 4 + end + local q = info.parts[pi] + if not q then + break + end + local head = if q.tiled then 20 else 8 + if p + head > limit then + break + end + local size = readi32(b, p + head - 4) + if size < 0 then + break + end + if pi == partIndex then + table.insert(offsets, at - base) + end + p += head + size + end + end + + local planes: { [number]: buffer } = { [0] = newPlane(w, h) } -- level -> rgbaf32 pixels + local tiles = part.tiles + local roundUp = tiles ~= nil and tiles[4] == 1 + local wantMips = opts and opts.mips and tiles ~= nil and tiles[3] == 1 + + local lpb = LINES[comp] + for ci, off in offsets do + local p = base + off + if multi then + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk past the end", p) + end + if readi32(b, p) ~= partIndex - 1 then + return nil, Err.new(Err.CORRUPT, "chunk of another part in this part's table", p) + end + p += 4 + end + if part.tiled then + if p + 20 > limit then + return nil, Err.new(Err.TRUNCATED, "tile header past the end", p) + end + local tx, ty, lx, ly, size = readi32(b, p), readi32(b, p + 4), readi32(b, p + 8), readi32(b, p + 12), readi32(b, p + 16) + p += 20 + local t = tiles :: { number } + local level = if lx == 0 and ly == 0 then 0 elseif wantMips and lx == ly then lx else -1 + if level >= 0 then + local lw, lh = levelSize(w, level, roundUp), levelSize(h, level, roundUp) + local x0, y0 = tx * t[1], ty * t[2] + if tx < 0 or ty < 0 or x0 >= lw or y0 >= lh then + return nil, Err.new(Err.CORRUPT, "tile outside the image", p) + end + if size < 0 or p + size > limit then + return nil, Err.new(Err.TRUNCATED, "tile data past the end", p) + end + local bw, bh = math.min(t[1], lw - x0), math.min(t[2], lh - y0) + local plane = planes[level] + if not plane then + plane = newPlane(lw, lh) + planes[level] = plane + end + -- tile coordinates are relative to the level's data window origin + local ax, ay = xMin + x0, yMin + y0 + local raw = rawSize(part, ay, ay + bh - 1, ax, bw) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, ay, ay + bh - 1, ax, bw) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, ay, ay + bh - 1, ax, bw, plane, lw, lh, xMin, yMin) + if berr then + return nil, berr + end + end + else + if p + 8 > limit then + return nil, Err.new(Err.TRUNCATED, "chunk header past the end", p) + end + local y, size = readi32(b, p), readi32(b, p + 4) + p += 8 + if y < yMin or y > yMax or (y - yMin) % lpb ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad scanline block y " .. y, p - 8) + end + if size < 0 or p + size > limit then + if ci > 1 then + break -- a cut file: keep the lines that decoded (meta.truncated) + end + return nil, Err.new(Err.TRUNCATED, "block data past the end", p) + end + local y1 = math.min(y + lpb - 1, yMax) + local raw = rawSize(part, y, y1, xMin, w) + local data, dp, uerr = unpack(b, comp, part, p, size, raw, y, y1, xMin, w) + if not data then + return nil, uerr + end + local berr = block(part, target, data, dp, y, y1, xMin, w, planes[0], w, h, xMin, yMin) + if berr then + return nil, berr + end + end + end + + local native = opts and opts.native + local function finish(px: buffer, pw: number, ph: number): Types.Image + if native then + local img = Types.Image.new(0, 0, "rgbaf32") + img.width, img.height, img.pixels = pw, ph, px + return img + end + local img = Types.Image.new(pw, ph, "rgba8") + local o = img.pixels + for i = 0, pw * ph - 1 do + for c = 0, 3 do + local v = buffer.readf32(px, i * 16 + c * 4) + v = if v ~= v or v <= 0 then 0 elseif v >= 1 then 1 else v + buffer.writeu8(o, i * 4 + c, math.floor((if c < 3 then v ^ GAMMA else v) * 255 + 0.5)) + end + end + return img + end + local img = finish(planes[0], w, h) + if wantMips then + local mips = {} + local l = 1 + while planes[l] do + mips[l] = finish(planes[l], levelSize(w, l, roundUp), levelSize(h, l, roundUp)) + l += 1 + end + if #mips > 0 then + img.meta.mipmaps = mips + end + end + local names, parts = {}, {} + for i, c in part.channels do + names[i] = c.name + end + for i, p in info.parts do + parts[i] = { name = p.name or "", type = p.type or (if p.tiled then "tiledimage" else "scanlineimage") } + end + img.meta.colorSpace = "linear" + img.meta.dataWindow = { x = xMin, y = yMin, width = w, height = h } + local dw = part.display + img.meta.displayWindow = { x = dw[1], y = dw[2], width = dw[3] - dw[1] + 1, height = dw[4] - dw[2] + 1 } + local attrs = {} + for k, v in part.attrs do + if k ~= "_types" and (type(v) == "string" or type(v) == "number") then + attrs[k] = v + end + end + img.meta.attributes = attrs + local kinds = {} + for i, c in part.channels do + kinds[i] = ({ [0] = "uint", "half", "float" })[c.kind] + end + img.meta.source = { + format = "exr", + compression = COMPRESSION[comp], + channels = names, + pixelTypes = kinds, + part = partIndex, + parts = parts, + tiled = part.tiled, + lineOrder = part.attrs.lineOrder, + bitDepth = if kinds[1] == "half" then 16 else 32, + } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function attr(w: Bytes.Writer, name: string, typ: string, data: buffer) + w:cstring(name) + w:cstring(typ) + w:u32le(buffer.len(data)) + w:bytes(data) +end + +function Exr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" or (img.format ~= "rgbaf32" and img.format ~= "rgba8") then + return nil, Err.new(Err.ARG, "needs an rgbaf32 or rgba8 Image") + end + local w, h = img.width, img.height + if type(w) ~= "number" or w < 1 or h < 1 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.ARG, "bad image size") + end + local compName = opts and opts.compression or "zip" + local comp = if compName == "none" then 0 elseif compName == "zips" then 2 elseif compName == "zip" then 3 else nil + if not comp then + return nil, Err.new(Err.ARG, "compression must be none, zips or zip") + end + local ptype = opts and opts.pixelType or "half" + if ptype ~= "half" and ptype ~= "float" then + return nil, Err.new(Err.ARG, "pixelType must be half or float") + end + local level = opts and opts.level or 6 + -- the float values + local n = w * h + local fl = buffer.create(n * 16) + if img.format == "rgbaf32" then + buffer.copy(fl, 0, img.pixels, 0, n * 16) + else + for i = 0, n * 4 - 1 do + local v = buffer.readu8(img.pixels, i) / 255 + buffer.writef32(fl, i * 4, if i % 4 < 3 then v ^ 2.2 else v) + end + end + local alpha = opts and opts.alpha + if alpha == nil then + alpha = false + for i = 0, n - 1 do + if buffer.readf32(fl, i * 16 + 12) ~= 1 then + alpha = true + break + end + end + end + local chans = if alpha then { { "A", 3 }, { "B", 2 }, { "G", 1 }, { "R", 0 } } else { { "B", 2 }, { "G", 1 }, { "R", 0 } } + local kind = if ptype == "half" then 1 else 2 + local sz = if kind == 1 then 2 else 4 + local lpb = LINES[comp] + local nblocks = (h + lpb - 1) // lpb + -- header + local hw = Bytes.writer(512) + hw:string(MAGIC) + hw:u32le(2) + local cl = Bytes.writer() + for _, c in chans do + cl:cstring(c[1]) + cl:u32le(kind) + cl:u8(0) + cl:fill(0, 3) + cl:u32le(1) + cl:u32le(1) + end + cl:u8(0) + attr(hw, "channels", "chlist", cl:finish()) + attr(hw, "compression", "compression", buffer.fromstring(string.char(comp))) + local bw = Bytes.writer(16) + bw:u32le(0) + bw:u32le(0) + bw:u32le(w - 1) + bw:u32le(h - 1) + local boxb = bw:finish() + attr(hw, "dataWindow", "box2i", boxb) + attr(hw, "displayWindow", "box2i", boxb) + attr(hw, "lineOrder", "lineOrder", buffer.fromstring("\0")) + local fw = Bytes.writer(4) + fw:f32le(1) + attr(hw, "pixelAspectRatio", "float", fw:finish()) + attr(hw, "screenWindowCenter", "v2f", buffer.create(8)) + attr(hw, "screenWindowWidth", "float", fw:finish()) + hw:u8(0) + local tableAt = hw:tell() + hw:fill(0, nblocks * 8) + local from = Half.fromFloat + for bi = 0, nblocks - 1 do + local y0 = bi * lpb + local y1 = math.min(y0 + lpb - 1, h - 1) + local raw = buffer.create((y1 - y0 + 1) * #chans * w * sz) + local o = 0 + for y = y0, y1 do + for _, c in chans do + local k = c[2] + for x = 0, w - 1 do + local v = buffer.readf32(fl, ((y * w + x) * 4 + k) * 4) + if kind == 1 then + buffer.writeu16(raw, o, from(v)) + else + buffer.writef32(raw, o, v) + end + o += sz + end + end + end + local data = raw + if comp ~= 0 then + local z = Codec.zip(raw, level) + if buffer.len(z) < buffer.len(raw) then + data = z + end + end + local at = hw:tell() + hw:setU32le(tableAt + bi * 8, at) + hw:u32le(y0) + hw:u32le(buffer.len(data)) + hw:bytes(data) + end + return hw:finish(), nil +end + +return Exr diff --git a/tests/image/exr.luau b/tests/image/exr.luau new file mode 100644 index 0000000..64078a5 --- /dev/null +++ b/tests/image/exr.luau @@ -0,0 +1,143 @@ +-- image/exr tests: files from the OpenEXR 3.5 bindings (NONE / RLE / ZIPS / ZIP / PIZ; HALF / FLOAT / UINT; offset +-- data window; decreasing lines; Y-only; a layer), a hand-written subsampled file, exrmaketiled tiles (one level, +-- mip-map, rip-map, round up) and exrmultipart parts against the bindings' reads; PXR24 / B44 / DWAA UNSUPPORTED; our +-- files read back by the bindings and exrheader; round trips; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/exr.py. +local T = require("@tests/T") +local Exr = require("@formats/image/exr") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/exr") + +local t = T.suite("exr") + +t:eq(Exr.name, "exr", "name") +t:check(Exr.caps.decode and Exr.caps.encode, "caps") + +local function dec(data: any, opts: any?): (any, any) + return Exr.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data), opts) +end + +-- the largest difference between two rgbaf32 buffers (exact for HALF / FLOAT, UINT as their values) +local function worst(a: buffer, b: buffer, n: number): number + local m = 0 + for i = 0, n * 4 - 1 do + local x, y = buffer.readf32(a, i * 4), buffer.readf32(b, i * 4) + if x ~= y then + m = math.max(m, math.abs(x - y) / math.max(1, math.abs(y))) + end + end + return m +end + +for _, c in Fx.cases do + if c.unsupported then + local img, e = dec(c.data) + t:check(img == nil and e and e.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED (" .. tostring(e) .. ")") + continue + end + local opts = { native = true, layer = c.layer, part = c.part, mips = c.mips } + local img, err = dec(c.data, opts) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.w and img.height == c.h and img.format == "rgbaf32", c.name .. ": size") + local d = worst(img.pixels, buffer.fromstring(c.floats), c.w * c.h) + t:check(d < 1e-6, string.format("%s: off by %g", c.name, d)) + if c.partName then + local byName = dec(c.data, { native = true, part = c.partName }) + t:check(byName and buffer.tostring(byName.pixels) == buffer.tostring(img.pixels), c.name .. ": part by name") + t:eq(img.meta.source.parts[c.part].name, c.partName, c.name .. ": part names") + end + if c.mips and string.find(c.name, "mip") then + local mm = img.meta.mipmaps + t:check(mm and #mm >= 5, c.name .. ": mip levels") + local up = string.find(c.name, "up") ~= nil + t:eq(mm[1].width, if up then math.ceil(c.w / 2) else c.w // 2, c.name .. ": level 1 width") + end + -- the rgba8 display conversion + local d8 = dec(c.data, { layer = c.layer, part = c.part }) + t:eq(d8.format, "rgba8", c.name .. ": rgba8 by default") +end +t:note("%d files match the OpenEXR bindings", #Fx.cases) + +-- the window, the attributes +do + for _, c in Fx.cases do + if c.name == "window_zip.exr" then + local img = dec(c.data) + t:check(img.meta.dataWindow.x == 5 and img.meta.dataWindow.y == -3, "data window origin") + t:check(img.meta.displayWindow.width == 40 and img.meta.displayWindow.height == 20, "display window") + t:eq(img.meta.source.compression, "zip", "compression name") + end + end +end + +-- our files: the bindings read our values back, exrheader accepts them +for _, o in Fx.ours do + t:check(o.headerOk, o.name .. ": exrheader") + local img = dec(o.data, { native = true }) + local n = img.width * img.height + local d = worst(img.pixels, buffer.fromstring(o.floats), n) + t:check(d == 0, string.format("%s: the bindings read %g off our decode", o.name, d)) +end +t:note("%d of our files read back by the OpenEXR bindings", #Fx.ours) + +-- round trips: FLOAT exactly, HALF to half precision +do + local f = Types.Image.new(13, 9, "rgbaf32") + local rand = T.rng(5) + for i = 0, 13 * 9 * 4 - 1 do + buffer.writef32(f.pixels, i * 4, (rand(20000) - 5000) / 997) + end + for _, comp in { "none", "zips", "zip" } do + local back = dec(Exr.encode(f, { compression = comp :: any, pixelType = "float" }) :: buffer, { native = true }) + t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), comp .. ": float round trip") + local hb = dec(Exr.encode(f, { compression = comp :: any }) :: buffer, { native = true }) + t:check(worst(hb.pixels, f.pixels, 13 * 9) < 1e-3, comp .. ": half round trip") + end + local img8 = Types.Image.new(4, 4) + for i = 0, 63 do + buffer.writeu8(img8.pixels, i, (i * 37) % 256) + end + local back8 = dec(Exr.encode(img8, { pixelType = "float" }) :: buffer) + local ok = true + for i = 0, 63 do + ok = ok and math.abs(buffer.readu8(back8.pixels, i) - buffer.readu8(img8.pixels, i)) <= 1 + end + t:check(ok, "rgba8 through the display curve and back") + local _, e = Exr.encode(f, { compression = "piz" :: any }) + t:check(e and e.code == Err.ARG, "no PIZ encoder") +end + +-- sniff, info, errors +do + local c = Fx.cases[1] + t:eq(Exr.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Exr.sniff(Bytes.reader(buffer.fromstring("v/1\0"))), 0, "sniff other") + local info = Exr.info(Bytes.reader(buffer.fromstring(c.data))) + t:check(info and #info.parts == 1 and #info.parts[1].channels == 4, "info") + local _, e = dec(string.sub(c.data, 1, 40)) + t:check(e and e.code == Err.TRUNCATED, "short header: " .. tostring(e)) + local _, e2 = dec(c.data, { maxPixels = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + local _, e3 = dec(c.data, { part = 3 }) + t:check(e3 and e3.code == Err.ARG, "no such part") + -- a zeroed offset table is rebuilt + local b = buffer.fromstring(c.data) + local info2 = Exr.info(Bytes.reader(b)) :: any + local tab = info2.dataStart - 8 * info2.parts[1].chunks + buffer.fill(b, tab, 0, 8 * info2.parts[1].chunks) + local img = dec(b, { native = true }) + t:check(img and buffer.tostring(img.pixels) == buffer.tostring(dec(c.data, { native = true }).pixels), "rebuilt offset table") +end + +local samples = {} +for i, c in Fx.cases do + if i % 3 == 0 or c.unsupported then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + return dec(b, { mips = true }) +end, samples, { mutations = 6 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 5486408..6f108fd 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1102,3 +1102,20 @@ do Bcn.decode("bc6h", b6, 0, w, h) end) end +do + -- OpenEXR (ws-tex): a 512 x 256 half RGBA image from the OpenEXR bindings (tools/fixtures/exr.py), ZIP and PIZ; + -- MB/s of rgbaf32 output; our ZIP encoder on the decoded floats + local Exr = require("@formats/image/exr") + local EB = require("@tests/gen/exr_bench") + local n = 512 * 256 * 16 + for _, k in { "zip", "piz" } do + local data = buffer.fromstring(EB[k]) + bench("exr decode " .. k .. " 512x256 half", 3, n, function() + Exr.decode(Bytes.reader(data), { native = true }) + end) + end + local img = Exr.decode(Bytes.reader(buffer.fromstring(EB.zip)), { native = true }) :: any + bench("exr encode zip 512x256 half", 2, n, function() + Exr.encode(img) + end) +end diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 14a7df0..4c21f24 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -93,3 +93,18 @@ if which == "ktx" then cube.meta.layout = "array" emit("ours_array.ktx2", Ktx.encode(cube)) end + +if which == "exr" then + local Exr = require("@formats/image/exr") + local f = image(37, 23, "rgbaf32", 0, 4) + for _, c in { "none", "zips", "zip" } do + emit("ours_half_" .. c .. ".exr", Exr.encode(f, { compression = c :: any })) + emit("ours_float_" .. c .. ".exr", Exr.encode(f, { compression = c :: any, pixelType = "float" })) + end + local opaque = image(20, 40, "rgbaf32", 1, 2) + for i = 0, 20 * 40 - 1 do + buffer.writef32(opaque.pixels, i * 16 + 12, 1) + end + emit("ours_rgb_zip.exr", Exr.encode(opaque)) + emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2))) +end diff --git a/tools/fixtures/exr.py b/tools/fixtures/exr.py new file mode 100644 index 0000000..1281c4d --- /dev/null +++ b/tools/fixtures/exr.py @@ -0,0 +1,195 @@ +# OpenEXR fixtures (tools/fixtures.py): files written by the OpenEXR 3.5 python bindings (every compression NONE / +# RLE / ZIPS / ZIP / PIZ, HALF / FLOAT / UINT channels, odd sizes, an offset data window, decreasing line order, a +# Y-only image, a layer (diffuse.R ...), subsampled channels, PXR24 / B44 / DWAA for the UNSUPPORTED path), tiled +# versions by exrmaketiled (one level, mip-map with unfiltered levels, rip-map, round up, several compressions), +# multipart files by exrmultipart; our encoder's files (tools/fixtures/_tex_encode.luau -a exr) read back by the +# bindings and exrheader. References: the bindings' read of each file (RGBA as little-endian f32; Y as grey). +# tests/gen/exr.luau { cases = { { name, data, w, h, floats?, unsupported?, opts?, mips? } }, ours = { { name, +# data, floats, compression, header_ok } } } +# tests/gen/exr_bench.luau a 512 x 256 half RGBA image in ZIP and PIZ +import os, shutil, subprocess, tempfile + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/exr"] + +WRITE = r''' +import OpenEXR, numpy as np, os, sys, json +w = sys.argv[1] +rng = np.random.default_rng(3) +def win(x0, y0, x1, y1): + return (np.array([x0, y0], dtype=np.int32), np.array([x1, y1], dtype=np.int32)) +def img(h, wd, kind="f2"): + y, x = np.mgrid[0:h, 0:wd] + r = (x / max(1, wd - 1)) * 3 - 0.5 + g = np.sin(y * 0.7) * 0.5 + 0.5 + b = rng.random((h, wd)) * 0.01 + (x * y % 7) * 0.2 + a = ((x + y) % 4) / 3.0 + return [c.astype(kind) for c in (r, g, b, a)] +def save(name, header, channels): + h = {"type": OpenEXR.scanlineimage} + h.update(header) + OpenEXR.File(h, channels).write(os.path.join(w, name)) +C = {"none": OpenEXR.NO_COMPRESSION, "rle": OpenEXR.RLE_COMPRESSION, "zips": OpenEXR.ZIPS_COMPRESSION, + "zip": OpenEXR.ZIP_COMPRESSION, "piz": OpenEXR.PIZ_COMPRESSION} +names = [] +for cn, c in C.items(): + r, g, b, a = img(23, 37) + save("half_rgba_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b, "A": a}) + r, g, b, a = img(19, 41, "f4") + save("float_rgb_%s.exr" % cn, {"compression": c}, {"R": r, "G": g, "B": b}) + r, g, b, a = img(37, 70) + u = (rng.random((37, 70)) * 100000).astype("uint32") + save("mixed_%s.exr" % cn, {"compression": c, "lineOrder": OpenEXR.DECREASING_Y}, {"R": r, "G": g.astype("f4"), "B": u}) + names += ["half_rgba_%s.exr" % cn, "float_rgb_%s.exr" % cn, "mixed_%s.exr" % cn] +r, g, b, a = img(20, 30) +save("window_zip.exr", {"compression": C["zip"], "dataWindow": win(5, -3, 34, 16), "displayWindow": win(0, 0, 39, 19)}, {"R": r, "G": g, "B": b, "A": a}) +save("grey_piz.exr", {"compression": C["piz"]}, {"Y": r}) +save("layer_zips.exr", {"compression": C["zips"]}, {"diffuse.R": r, "diffuse.G": g, "diffuse.B": b, "R": a, "G": a, "B": a}) +r, g, b, a = img(64, 96) +save("big_piz.exr", {"compression": C["piz"]}, {"R": r, "G": g, "B": b, "A": a}) +save("big_zip.exr", {"compression": C["zip"]}, {"R": r, "G": g, "B": b, "A": a}) +names += ["window_zip.exr", "grey_piz.exr", "layer_zips.exr", "big_piz.exr", "big_zip.exr"] +y, x = np.mgrid[0:16, 0:24] +Y = (x / 23.0).astype("f2") +sub = (np.mgrid[0:8, 0:12][1] / 11.0).astype("f2") +# subsampled: hand-written (the bindings only write full-resolution channels): NONE, A at 2 x 2, R / G / B full +import struct +def attr(n, t, d): + return n.encode() + b"\0" + t.encode() + b"\0" + struct.pack(" 3 and name.startswith("layer") else "" + px = np.zeros((H, W, 4), dtype="f4") + px[:, :, 3] = 1 + def get(n): + c = ch.get(layer + n) + if c is None: + return None + p = c.pixels.astype("f4") + if p.shape != (H, W): + p = np.repeat(np.repeat(p, c.ySampling, axis=0), c.xSampling, axis=1)[:H, :W] + return p + if get("R") is None and get("Y") is not None: + for k in range(3): + px[:, :, k] = get("Y") + for k, n in enumerate("RGBA"): + p = get(n) + if p is not None: + px[:, :, k] = p + out[name] = {"w": W, "h": H, "floats": px.tobytes().hex(), "compression": str(hdr["compression"]).split(".")[-1]} +print(json.dumps(out)) +''' + + +def generate(ctx): + work = tempfile.mkdtemp(prefix="formats-exr-") + try: + _generate(ctx, work) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def py(ctx, code, *args): + expr = "with import {}; python3.withPackages (p: [p.openexr p.numpy])" + res = subprocess.run(["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code] + list(args), capture_output=True) + if res.returncode: + raise RuntimeError("OpenEXR bindings failed: " + res.stderr.decode()[-2000:]) + return res.stdout + + +def _generate(ctx, work): + import json + names = json.loads(py(ctx, WRITE, work)) + tiled = [] + sh = [] + for cn in ("none", "rle", "zip", "piz"): + sh.append("exrmaketiled -o -t 16 8 -z %s half_rgba_zip.exr tiled_%s.exr" % (cn, cn)) + tiled.append("tiled_%s.exr" % cn) + sh.append("exrmaketiled -m -t 8 8 -z zip -f R -f G -f B -f A half_rgba_zip.exr tiled_mip.exr") + sh.append("exrmaketiled -m -u -t 8 8 -z piz half_rgba_zip.exr tiled_mip_up.exr") + sh.append("exrmaketiled -r -t 16 16 -z zips half_rgba_zip.exr tiled_rip.exr") + sh.append("exrmaketiled -o -t 8 8 -z zip float_rgb_none.exr tiled_float.exr") + sh.append("exrmaketiled -o -t 7 5 -z zip window_zip.exr tiled_window.exr") + tiled += ["tiled_mip.exr", "tiled_mip_up.exr", "tiled_rip.exr", "tiled_float.exr", "tiled_window.exr"] + sh.append("exrmultipart -combine -i half_rgba_piz.exr::left half_rgba_rle.exr::right tiled_zip.exr::tiles -o multipart.exr") + ctx.nix("openexr", ["sh", "-c", "cd %s && %s" % (work, " && ".join(sh))]) + ref = json.loads(py(ctx, READ, work, json.dumps(names + tiled), "diffuse.")) + cases = [] + for n in names + tiled: + r = ref[n] + c = {"name": n, "data": open(os.path.join(work, n), "rb").read(), "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])} + if n.startswith("layer"): + c["layer"] = "diffuse" + if n.startswith("tiled_mip") or n.startswith("tiled_rip"): + c["mips"] = True + cases.append(c) + # multipart: every part against the file it came from + mp = open(os.path.join(work, "multipart.exr"), "rb").read() + for i, (src, pname) in enumerate((("half_rgba_piz.exr", "left"), ("half_rgba_rle.exr", "right"), ("tiled_zip.exr", "tiles"))): + r = ref[src] + cases.append({"name": "multipart part %d (%s)" % (i + 1, pname), "data": mp, "part": i + 1, "partName": pname, + "w": r["w"], "h": r["h"], "floats": bytes.fromhex(r["floats"])}) + for cn in ("pxr24", "b44", "dwaa"): + cases.append({"name": "unsupported_%s.exr" % cn, "data": open(os.path.join(work, "unsupported_%s.exr" % cn), "rb").read(), "unsupported": True}) + ours = _ours(ctx, work) + ctx.emit("exr", {"cases": cases, "ours": ours}) + ctx.emit("exr_bench", {"zip": open(os.path.join(work, "bench_zip.exr"), "rb").read(), "piz": open(os.path.join(work, "bench_piz.exr"), "rb").read()}) + + +def _ours(ctx, work): + import json + exe = shutil.which("luau") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", "exr"], cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + n, hx = line.split("\t", 1) + files[n] = bytes.fromhex(hx.strip()) + names = sorted(files) + for n in names: + open(os.path.join(work, n), "wb").write(files[n]) + ref = json.loads(py(ctx, READ, work, json.dumps(names))) + rc = ctx.nix("openexr", ["sh", "-c", "cd %s && for f in %s; do exrheader $f > /dev/null 2>&1; echo $f $?; done" % (work, " ".join(names))]).decode() + ok = {line.split()[0]: line.split()[1] == "0" for line in rc.strip().split("\n")} + return [{"name": n, "data": files[n], "floats": bytes.fromhex(ref[n]["floats"]), "compression": ref[n]["compression"], "headerOk": ok.get(n, False)} for n in names] From 1013925a85fe3c3435cac17823f60a58e0907b1d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:22 -0500 Subject: [PATCH 33/54] ws-video2-theora: Theora speed (fused prediction + IDCT add, inlined token decode, table-driven tokens), bench lines, guide section tools/bench.luau: a ws-video2-theora block (320x240 testsrc2 / mandelbrot, decode and decode + image()). docs/guide/video.md: an Ogg Theora section (tested snippet; inputs from the new tools/fixtures/docs_theora.py) and the formats / writers tables. --- docs/guide/video.md | 28 +- src/Formats/codecs/video/Theora/Decoder.luau | 462 ++++++++++--------- src/Formats/codecs/video/Theora/Header.luau | 2 +- tools/bench.luau | 39 ++ tools/fixtures/docs_theora.py | 20 + tools/fixtures/theora.py | 13 +- 6 files changed, 342 insertions(+), 222 deletions(-) create mode 100644 tools/fixtures/docs_theora.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..6d2ed39 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -179,6 +179,7 @@ Images and animated images save as videos too. | Destination | Video | Audio | |---|---|---| | webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied | +| ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied | | mkv | any codec copied, else MJPEG | copied, else PCM s16 | | mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only | | avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 | @@ -235,6 +236,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## Ogg Theora + +Ogg video (`.ogv`, or `.ogg` with a Theora stream) opens like any other container: the `ogv` format demuxes every +Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4 +chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes `v.audio`. Plain Ogg Vorbis / Opus / +FLAC files stay audio. Theora in Matroska (`V_THEORA`) decodes too, and an Ogg Theora video remuxes to ogv or mkv +(there is no Theora encoder). + +```luau +local v = assert(F.video.open(ogvBytes)) -- Theora + Vorbis +assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48) +assert(v.frameRate == 10 and v.audio ~= nil) +local n = 0 +while v:nextFrame() do n += 1 end -- dropped frames repeat the previous picture +assert(n == 10) +local Theora = F.format("ogv") -- the format module: sniff / demux / open / encode +local d = assert(Theora.demux(F.Bytes.reader(ogvBytes))) +local vt = d:track("video") +assert(vt.codec == "theora" and vt.timescale == 10) -- packet times are frame numbers here +v:reset() +local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copied into Matroska +assert(F.video.open(mkv).codec == "theora") +``` + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -279,7 +304,8 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| | mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw, Theora (+ H.264) | +| ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora | | avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | | mpegts, mpegps | yes | - | MPEG-1, H.264 | | y4m | yes | yes | raw | diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index d29b8cf..aad8f1c 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -24,9 +24,10 @@ local writeu8 = buffer.writeu8 local readu16 = buffer.readu16 local readi16 = buffer.readi16 local writei16 = buffer.writei16 -local readi32 = buffer.readi32 -local writei32 = buffer.writei32 local readu32 = buffer.readu32 +local writeu32 = buffer.writeu32 +local band = bit32.band +local bxor = bit32.bxor local bcopy = buffer.copy local bfill = buffer.fill local lshift = bit32.lshift @@ -93,10 +94,56 @@ do end -- DCT tokens: extra bits per token -local TOKEN_EXTRA = { - [0] = 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, +local TOKEN_EXTRA = { -- [token + 1] + 0, 0, 0, 2, 3, 4, 12, 3, 6, 0, 0, 0, 0, 1, 1, 1, 1, 2, 3, 4, 5, 6, 10, 1, 1, 1, 1, 1, 3, 4, 2, 3, } +-- the zero-run / coefficient tokens (7..31) by token * 1024 + extra bits + 1: run * 4096 + value + 2048, where run is +-- the zeros before the value (value 0: a pure zero run of run + 1) +local TOKEN_VALUE = table.create(32 * 1024, 2048) +for tok = 7, 31 do + local ex = TOKEN_EXTRA[tok + 1] + for eb = 0, 2 ^ ex - 1 do + local v, r = 0, 0 + if tok < 9 then + r = eb -- zero runs: eb + 1 zeros + elseif tok < 13 then + v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 + elseif tok < 17 then + v = if eb == 1 then -(tok - 10) else tok - 10 + elseif tok < 23 then + local half = 2 ^ (ex - 1) -- the top extra bit is the sign + local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 + v = base + eb % half + if eb >= half then + v = -v + end + elseif tok < 28 then + r = tok - 22 + v = if eb == 1 then -1 else 1 + elseif tok == 28 then + r = 6 + eb % 4 + v = if eb >= 4 then -1 else 1 + elseif tok == 29 then + r = 10 + eb % 8 + v = if eb >= 8 then -1 else 1 + elseif tok == 30 then + r = 1 + v = 2 + eb % 2 + if eb >= 2 then + v = -v + end + else + r = 2 + eb % 2 + v = 2 + (eb // 2) % 2 + if eb >= 4 then + v = -v + end + end + TOKEN_VALUE[tok * 1024 + eb + 1] = r * 4096 + v + 2048 + end +end + -- natural index of zig-zag position (1-based by position + 1) local ZIGZAG = Header.ZIGZAG @@ -158,9 +205,8 @@ export type State = { lflim: { number }, huff: { number }, roots: { number }, - blk: buffer, -- i32 x 64 work blocks + blk: buffer, -- i16 x 64 work blocks tmp: buffer, - res: buffer, bv: { number }, -- the loop filter's bounding values for the frame, [(f + 4) >> 3 + 129] keyframes: number, } @@ -191,9 +237,8 @@ function D.new(info: Header.Info, setup: Header.Setup): State lflim = setup.lflim, huff = setup.huff, roots = setup.roots, - blk = buffer.create(256), - tmp = buffer.create(256), - res = buffer.create(256), + blk = buffer.create(128), + tmp = buffer.create(128), bv = table.create(257, 0), keyframes = 0, } @@ -366,23 +411,24 @@ local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, return t0 + t7, t1 + t6, t2 + t5, t3 + t4, t3 - t4, t2 - t5, t1 - t6, t0 - t7 end --- 2-D IDCT of blk (i16, natural order) into res (i32 residuals). Like libtheora, the dequantised coefficients and --- the first pass's outputs are 16-bit (the i16 buffers wrap them), which also bounds every residual to +-24000. -local function idct(blk: buffer, tmp: buffer, res: buffer) +-- the first IDCT pass: the rows of blk (i16, natural order) into the columns of tmp (i16: like libtheora, the +-- dequantised coefficients and these intermediate values are 16-bit, which also bounds every residual) +local function idctRows(blk: buffer, tmp: buffer) for i = 0, 7 do local o = i * 16 local x0, x1, x2, x3 = readi16(blk, o), readi16(blk, o + 2), readi16(blk, o + 4), readi16(blk, o + 6) local x4, x5, x6, x7 = readi16(blk, o + 8), readi16(blk, o + 10), readi16(blk, o + 12), readi16(blk, o + 14) local c = i * 2 - if x0 == 0 and x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then - writei16(tmp, c, 0) - writei16(tmp, c + 16, 0) - writei16(tmp, c + 32, 0) - writei16(tmp, c + 48, 0) - writei16(tmp, c + 64, 0) - writei16(tmp, c + 80, 0) - writei16(tmp, c + 96, 0) - writei16(tmp, c + 112, 0) + if x1 == 0 and x2 == 0 and x3 == 0 and x4 == 0 and x5 == 0 and x6 == 0 and x7 == 0 then + local y = (C4 * x0) // 65536 + writei16(tmp, c, y) + writei16(tmp, c + 16, y) + writei16(tmp, c + 32, y) + writei16(tmp, c + 48, y) + writei16(tmp, c + 64, y) + writei16(tmp, c + 80, y) + writei16(tmp, c + 96, y) + writei16(tmp, c + 112, y) else local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) writei16(tmp, c, y0) @@ -395,20 +441,29 @@ local function idct(blk: buffer, tmp: buffer, res: buffer) writei16(tmp, c + 112, y7) end end - for i = 0, 7 do - local o = i * 16 - local x0, x1, x2, x3 = readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6) - local x4, x5, x6, x7 = readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14) - local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(x0, x1, x2, x3, x4, x5, x6, x7) - local c = i * 4 - writei32(res, c, (y0 + 8) // 16) - writei32(res, c + 32, (y1 + 8) // 16) - writei32(res, c + 64, (y2 + 8) // 16) - writei32(res, c + 96, (y3 + 8) // 16) - writei32(res, c + 128, (y4 + 8) // 16) - writei32(res, c + 160, (y5 + 8) // 16) - writei32(res, c + 192, (y6 + 8) // 16) - writei32(res, c + 224, (y7 + 8) // 16) +end + +-- the second pass, added to the prediction already in dst: column c of the block is row c of tmp +local function idctAdd(tmp: buffer, dst: buffer, pos: number, stride: number) + for c = 0, 7 do + local o = c * 16 + local y0, y1, y2, y3, y4, y5, y6, y7 = idct8(readi16(tmp, o), readi16(tmp, o + 2), readi16(tmp, o + 4), readi16(tmp, o + 6), readi16(tmp, o + 8), readi16(tmp, o + 10), readi16(tmp, o + 12), readi16(tmp, o + 14)) + local p = pos + c + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y0 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y1 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y2 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y3 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y4 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y5 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y6 + 8) // 16 + COFF)) + p += stride + writeu8(dst, p, readu8(CLAMP, readu8(dst, p) + (y7 + 8) // 16 + COFF)) end end @@ -426,7 +481,8 @@ local function mvSplit(d: number, q: boolean): (number, number) return a, b end --- reconstruct one coded fragment into dst (the SELF reference planes) +-- reconstruct one coded fragment into dst (the SELF reference planes): the prediction (128 for intra blocks, the +-- reference block or the average of two for inter ones) goes to dst first, then the residual is added local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { buffer }) local pli = st.fpl[fi] local mode = st.fmode[fi] @@ -435,12 +491,20 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local dcq = readu16(dq, (((qis[1] * 3 + pli) * 2 + qti) * 64) * 2) local dc = st.dcv[fi] local last = st.last[fi] - local res = st.res - local flat = false + local stride = st.stride[pli + 1] + local dst = dstPlanes[pli + 1] + local pos = st.fpos[fi] + local ri = st.refi[fi] local fv = 0 if last == 0 then - flat = true fv = wrap16((dc * dcq + 15) // 32) + if ri == SELF then + local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, v, 8) + end + return + end else local blk = st.blk bfill(blk, 0, 0, 128) @@ -456,50 +520,44 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu end end st.last[fi] = 0 - idct(blk, st.tmp, res) + idctRows(blk, st.tmp) end - local stride = st.stride[pli + 1] - local dst = dstPlanes[pli + 1] - local pos = st.fpos[fi] - local ri = st.refi[fi] + -- the prediction if ri == SELF then - if flat then - local v = readu8(CLAMP, fv + 128 + COFF) + for y = 0, 7 do + bfill(dst, pos + y * stride, 128, 8) + end + else + local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] + local mx, mx2 = mvSplit(st.mvx[fi], pli > 0 and st.hdec == 1) + local my, my2 = mvSplit(st.mvy[fi], pli > 0 and st.vdec == 1) + local s1 = pos + my * stride + mx + if mx2 ~= 0 or my2 ~= 0 then + -- (a + b) >> 1 per byte, four at a time + local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do - bfill(dst, pos + y * stride, v, 8) + local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride + local u, v = readu32(ref, a), readu32(ref, b) + writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + u, v = readu32(ref, a + 4), readu32(ref, b + 4) + writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) end else for y = 0, 7 do - local d, s = pos + y * stride, y * 32 - for x = 0, 7 do - writeu8(dst, d + x, readu8(CLAMP, readi32(res, s + x * 4) + 128 + COFF)) - end + local d, a = pos + y * stride, s1 + y * stride + writeu32(dst, d, readu32(ref, a)) + writeu32(dst, d + 4, readu32(ref, a + 4)) end end - return end - local ref = st.refs[if ri == GOLD then st.gold else st.prev][pli + 1] - local qx = pli > 0 and st.hdec == 1 - local qy = pli > 0 and st.vdec == 1 - local mx, mx2 = mvSplit(st.mvx[fi], qx) - local my, my2 = mvSplit(st.mvy[fi], qy) - local s1 = pos + my * stride + mx - if mx2 ~= 0 or my2 ~= 0 then - local s2 = s1 + my2 * stride + mx2 + -- the residual + if last ~= 0 then + idctAdd(st.tmp, dst, pos, stride) + elseif fv ~= 0 then for y = 0, 7 do - local d, a, b, r = pos + y * stride, s1 + y * stride, s2 + y * stride, y * 32 - for x = 0, 7 do - local p = (readu8(ref, a + x) + readu8(ref, b + x)) // 2 - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, p + v + COFF)) - end - end - else - for y = 0, 7 do - local d, a, r = pos + y * stride, s1 + y * stride, y * 32 - for x = 0, 7 do - local v = if flat then fv else readi32(res, r + x * 4) - writeu8(dst, d + x, readu8(CLAMP, readu8(ref, a + x) + v + COFF)) + local d = pos + y * stride + for x = d, d + 7 do + writeu8(dst, x, readu8(CLAMP, readu8(dst, x) + fv + COFF)) end end end @@ -593,6 +651,88 @@ local function borders(st: State, planes: { buffer }) end end +-- DC prediction (raster order per plane): each coded block's DC adds a prediction from its left / upper neighbours +-- coded from the same reference frame (or the last such DC in the plane) +local function dcPredict(st: State) + local coded, refi, dcv = st.coded, st.refi, st.dcv + for pli = 0, 2 do + local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] + local base = st.foff[pli + 1] + local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) + for fy = 0, nv - 1 do + local row = base + fy * nh + local lref, ulref, uref = -1, -1, -1 + if fy > 0 then + uref = refi[row - nh + 1] + end + for fx = 0, nh - 1 do + local fi = row + fx + 1 + local urref = -1 + if fy > 0 and fx + 1 < nh then + urref = refi[fi - nh + 1] + end + if coded[fi] ~= 0 then + local r = refi[fi] + local pred: number + if fy == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + else + local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) + if m == 0 then + pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 + elseif m == 1 or m == 3 then + pred = dcv[fi - 1] + elseif m == 2 then + pred = dcv[fi - nh - 1] + elseif m == 4 or m == 6 or m == 12 then + pred = dcv[fi - nh] + elseif m == 5 then + local s = dcv[fi - 1] + dcv[fi - nh] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 8 then + pred = dcv[fi - nh + 1] + elseif m == 9 or m == 11 or m == 13 then + local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 128) else s // 128 + elseif m == 10 then + local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] + pred = if s < 0 then -((-s) // 2) else s // 2 + elseif m == 14 then + local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] + pred = if s < 0 then -((-s) // 16) else s // 16 + else + local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] + local s = 29 * (p0 + p2) - 26 * p1 + pred = if s < 0 then -((-s) // 32) else s // 32 + if math.abs(pred - p2) > 128 then + pred = p2 + elseif math.abs(pred - p0) > 128 then + pred = p0 + elseif math.abs(pred - p1) > 128 then + pred = p1 + end + end + end + local v = wrap16(dcv[fi] + pred) + dcv[fi] = v + if r == 0 then + pl0 = v + elseif r == 1 then + pl1 = v + else + pl2 = v + end + lref = r + else + lref = -1 + end + ulref = uref + uref = urref + end + end + end +end + -- ------------------------------------------------------------------------------------------------ frame decode -- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in -- st.refs[st.shown]. @@ -609,31 +749,11 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, if pos > maxp then pos = maxp end - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) + local w = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - n) pos += n return w end local huff = st.huff - local function token(root: number): number - if pos > maxp then - pos = maxp - end - local o = root - while true do - local n = huff[o] - local w = rshift(lshift(bswap(readu32(bb, pos // 8)), pos % 8), 32 - n) - local e = huff[o + 1 + w] - if e >= 0 then - pos += e // 64 - return e % 64 - end - pos += n - o = -e - if pos > maxp then - pos = maxp - end - end - end local function sbRun(): number if bits(1) == 0 then return 1 @@ -1028,9 +1148,28 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, eobs -= 1 t = 64 else - local tok = token(root) - local ex = TOKEN_EXTRA[tok] - local eb = if ex > 0 then bits(ex) else 0 + -- the token (inlined: the hottest loop), then its extra bits + if pos > maxp then + pos = maxp + end + local o, tok = root, 0 + while true do + local nb = huff[o] + local e = huff[o + 1 + rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - nb)] + if e >= 0 then + pos += rshift(e, 6) + tok = band(e, 63) + break + end + pos += nb + o = -e + end + local ex = TOKEN_EXTRA[tok + 1] + local eb = 0 + if ex > 0 then + eb = rshift(lshift(bswap(readu32(bb, rshift(pos, 3))), band(pos, 7)), 32 - ex) + pos += ex + end if tok < 7 then local run: number if tok < 3 then @@ -1046,49 +1185,18 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end eobs = run - 1 t = 64 - elseif tok < 9 then - t = zzi + eb + 1 else - local v, r = 0, 0 - if tok < 13 then - v = if tok == 9 then 1 elseif tok == 10 then -1 elseif tok == 11 then 2 else -2 - elseif tok < 17 then - v = if eb == 1 then -(tok - 10) else tok - 10 - elseif tok < 23 then - local half = 2 ^ (ex - 1) - local base = if tok == 17 then 7 elseif tok == 18 then 9 elseif tok == 19 then 13 elseif tok == 20 then 21 elseif tok == 21 then 37 else 69 - v = base + eb % half - if eb >= half then - v = -v + -- zero runs and coefficients: run * 4096 + value + 2048 (value 0: a zero run) + local e = TOKEN_VALUE[tok * 1024 + eb + 1] + local p = zzi + rshift(e, 12) + local v = band(e, 4095) - 2048 + if v ~= 0 then + if p == 0 then + dcv[fi] = v + elseif p < 64 then + writei16(coef, (fi - 1) * 128 + p * 2, v) + last[fi] = p end - elseif tok < 28 then - r = tok - 22 - v = if eb == 1 then -1 else 1 - elseif tok == 28 then - r = 6 + eb % 4 - v = if eb >= 4 then -1 else 1 - elseif tok == 29 then - r = 10 + eb % 8 - v = if eb >= 8 then -1 else 1 - elseif tok == 30 then - r = 1 - v = 2 + eb % 2 - if eb >= 2 then - v = -v - end - else - r = 2 + eb % 2 - v = 2 + (eb // 2) % 2 - if eb >= 4 then - v = -v - end - end - local p = zzi + r - if p == 0 then - dcv[fi] = v - elseif p < 64 then - writei16(coef, (fi - 1) * 128 + p * 2, v) - last[fi] = p end t = p + 1 end @@ -1104,83 +1212,7 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?, end end - -- DC prediction (raster order per plane) - for pli = 0, 2 do - local nh, nv = st.nhf[pli + 1], st.nvf[pli + 1] - local base = st.foff[pli + 1] - local pl0, pl1, pl2 = 0, 0, 0 -- the last DC of each reference frame (GOLD, PREV, SELF) - for fy = 0, nv - 1 do - local row = base + fy * nh - local lref, ulref, uref = -1, -1, -1 - if fy > 0 then - uref = refi[row - nh + 1] - end - for fx = 0, nh - 1 do - local fi = row + fx + 1 - local urref = -1 - if fy > 0 and fx + 1 < nh then - urref = refi[fi - nh + 1] - end - if coded[fi] ~= 0 then - local r = refi[fi] - local pred: number - if fy == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - else - local m = (if lref == r then 1 else 0) + (if ulref == r then 2 else 0) + (if uref == r then 4 else 0) + (if urref == r then 8 else 0) - if m == 0 then - pred = if r == 0 then pl0 elseif r == 1 then pl1 else pl2 - elseif m == 1 or m == 3 then - pred = dcv[fi - 1] - elseif m == 2 then - pred = dcv[fi - nh - 1] - elseif m == 4 or m == 6 or m == 12 then - pred = dcv[fi - nh] - elseif m == 5 then - local s = dcv[fi - 1] + dcv[fi - nh] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 8 then - pred = dcv[fi - nh + 1] - elseif m == 9 or m == 11 or m == 13 then - local s = 75 * dcv[fi - 1] + 53 * dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 128) else s // 128 - elseif m == 10 then - local s = dcv[fi - nh - 1] + dcv[fi - nh + 1] - pred = if s < 0 then -((-s) // 2) else s // 2 - elseif m == 14 then - local s = 3 * (dcv[fi - nh - 1] + dcv[fi - nh + 1]) + 10 * dcv[fi - nh] - pred = if s < 0 then -((-s) // 16) else s // 16 - else - local p0, p1, p2 = dcv[fi - 1], dcv[fi - nh - 1], dcv[fi - nh] - local s = 29 * (p0 + p2) - 26 * p1 - pred = if s < 0 then -((-s) // 32) else s // 32 - if math.abs(pred - p2) > 128 then - pred = p2 - elseif math.abs(pred - p0) > 128 then - pred = p0 - elseif math.abs(pred - p1) > 128 then - pred = p1 - end - end - end - local v = wrap16(dcv[fi] + pred) - dcv[fi] = v - if r == 0 then - pl0 = v - elseif r == 1 then - pl1 = v - else - pl2 = v - end - lref = r - else - lref = -1 - end - ulref = uref - uref = urref - end - end - end + dcPredict(st) -- reconstruction into a free reference buffer local self = 1 diff --git a/src/Formats/codecs/video/Theora/Header.luau b/src/Formats/codecs/video/Theora/Header.luau index 2d88abd..2259c19 100644 --- a/src/Formats/codecs/video/Theora/Header.luau +++ b/src/Formats/codecs/video/Theora/Header.luau @@ -226,7 +226,7 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t for i = 0, size - 1 do local cur, d = n, 0 while d < nb and tok[cur] < 0 do - local bit = (i // 2 ^ (nb - 1 - d)) % 2 + local bit = bit32.extract(i, nb - 1 - d, 1) local nx = if bit == 0 then kid0[cur] else kid1[cur] d += 1 cur = nx diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..afd0966 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1078,3 +1078,42 @@ do jitTune(false) end end +do + -- ------------------------------------------------------------------------------------- ws-video2-theora: fps + -- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static: + -- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode + + -- image() (the yuv420p copy every VideoDecoder frame makes) + local Theora = require("@formats/codecs/video/Theora") + local Ogg = require("@formats/containers/Ogg") + local Base64 = require("@formats/core/Base64") + local TB = require("@tests/gen/theora_bench") + local function run(tag: string) + for _, c in TB do + local d = Ogg.open(Base64.decode(c.file) :: buffer) + local hdrs, data = {}, {} + for p in d:packets(d:find("theora")) do + table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p)) + end + for _, image in { false, true } do + local n = c.width * c.height * 3 // 2 * #data + local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function() + local dec = Theora.new(hdrs) :: any + for _, p in data do + dec:decode(p) + if image then + dec:image() + end + end + end) + print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt)) + end + end + end + jitTune(false) + run("") + if runtime == "luajit" then + jitTune(true) + run(" (jit tuned)") + jitTune(false) + end +end diff --git a/tools/fixtures/docs_theora.py b/tools/fixtures/docs_theora.py new file mode 100644 index 0000000..1b85b57 --- /dev/null +++ b/tools/fixtures/docs_theora.py @@ -0,0 +1,20 @@ +# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a +# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video. +# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } } +import importlib.util, os, shutil, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py")) + dc = importlib.util.module_from_spec(spec) + spec.loader.exec_module(dc) + ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip() + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "clip.ogv") + subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", + "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora", + "-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True) + files = {"clip.ogv": open(out, "rb").read()} + dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"}) diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 7d05299..6bcfd6a 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -10,7 +10,7 @@ # rate, channels } # tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio # tests/gen/theora_mkv.luau { file (base64 .mkv), frames } -# tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau +# tests/gen/theora_bench.luau { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib FF = ["-hide_banner", "-loglevel", "error", "-y"] @@ -199,7 +199,10 @@ def generate(ctx): ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv]) ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"), "width": 174, "height": 98}) - # the bench stream - bench = os.path.join(tmp, "bench.ogv") - ff(src("testsrc2", 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", "600k", "-g", "25", bench]) - ctx.emit("theora_bench", {"file": b64(open(bench, "rb").read()), "width": 320, "height": 240}) + # the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves) + bench = [] + for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")): + path = os.path.join(tmp, "bench_" + kind + ".ogv") + ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path]) + bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240}) + ctx.emit("theora_bench", bench) From 3e336392728f51f6bd0856697405e648b4a3867b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:43:48 -0500 Subject: [PATCH 34/54] docs: legacy video (guide section, formats table rows, docs/video.md layers row); docs_legacy inputs --- docs/guide/video.md | 71 +++++++++++++++++++++++++++++++++++ docs/video.md | 1 + tools/fixtures/docs_legacy.py | 33 ++++++++++++++++ 3 files changed, 105 insertions(+) create mode 100644 tools/fixtures/docs_legacy.py diff --git a/docs/guide/video.md b/docs/guide/video.md index 99e0395..28e87c7 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -288,6 +288,77 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`. + +| fli / flc / flx | yes | - | FLIC (8-bit palettised, 15 / 16 / 24-bit) | +| smk | yes | - | Smacker video (SMK2 / SMK4) + Smacker audio / PCM | + +AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1, +QuickTime Animation (RLE) and QuickTime Graphics (SMC). See [Legacy video](#legacy-video). + + +## Legacy video + +The 1990s formats and codecs decode to **rgba8** frames (they are palettised or RGB, not YUV), each frame painted +over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's. + +| Codec id | Name | Containers | Depths | +|---|---|---|---| +| `flic` | Autodesk FLI / FLC | fli | 8-bit palettised, 15 / 16 / 24-bit | +| `smackvid` | Smacker video | smk | 8-bit palettised | +| `cinepak` | Cinepak (`cvid`) | avi, mov, mkv | 24-bit, grey, 8-bit palettised | +| `msvideo1` | Microsoft Video 1 (`CRAM`, `MSVC`, `WHAM`) | avi, mov, mkv | 16-bit (5-5-5), 8-bit palettised | +| `qtrle` | QuickTime Animation (`rle `) | mov, mkv | 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha) | +| `smc` | QuickTime Graphics (`smc `) | mov, mkv | 8-bit palettised | + +Palettes come from the container: `track.palette` (256 entries, 4 bytes each: R, G, B, A) holds the AVI +BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker +frames carry their own palette changes. + +```luau +local v = assert(F.video.open(cinepakBytes)) -- Cinepak in a QuickTime movie +assert(v.format == "mov" and v.codec == "cinepak") +local frames = 0 +while true do + local f = v:nextFrame() + if not f then break end + assert(f.image.format == "rgba8" and f.image.width == 64) + frames += 1 +end +assert(frames == v.frames) +``` + +FLIC files (`.fli` at 70 Hz ticks, `.flc` / `.flx` in milliseconds) open as videos; the ring frame (an extra frame +leading back to the first, for looping) is not shown unless you ask for it. + +```luau +local v = assert(F.video.open(flcBytes)) +print(v.format, v.codec, v.width, v.height, v.frameRate) -- fli flic 64 48 10 +assert(v.track.bitsPerPixel == 8 and v.frames == 10) +local f = assert(v:nextFrame()) +local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0) -- palette colours, opaque +assert(r and g and b and a == 255) +local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true })) +assert(all.codec == "flic") +``` + +Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself: +`v.audio` is the first track, `F.format("smk").openAudio(demuxer, track)` opens any of them. + +```luau +local v = assert(F.video.open(smkBytes)) +assert(v.format == "smk" and v.codec == "smackvid") +local a = assert(v.audio, tostring(v.audioError)) -- packed 16-bit stereo, 22050 Hz +assert(a.sampleRate == 22050 and a.channels == 2) +local Smk = F.format("smk") +for _, t in v.demuxer.tracks do + if t.kind == "audio" then + local dec = assert(Smk.openAudio(v.demuxer, t)) -- smackaudio, pcm_u8 or pcm_s16le + local pcm, n = dec:read(1000) + assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4) + end +end +``` + ## Gotchas - Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with `tools/bench.luau` diff --git a/docs/video.md b/docs/video.md index 184ca45..f2469d6 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,7 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Legacy` | FLIC, Smacker, Cinepak, Microsoft Video 1, QuickTime RLE / SMC: rgba8, palettes from `track.palette` | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_legacy.py b/tools/fixtures/docs_legacy.py new file mode 100644 index 0000000..719f8fd --- /dev/null +++ b/tools/fixtures/docs_legacy.py @@ -0,0 +1,33 @@ +# Docs inputs for the legacy video sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): +# a 64x48 FLC (tools/fixtures/fli.py's encoder), a 64x48 SMK4 with a packed stereo and a raw mono audio track +# (tools/fixtures/smk.py's encoder) and a 64x48 Cinepak MOV from ffmpeg. +# tests/gen/docs_legacy.luau { files = { [name] = bytes }, vars = { flcBytes = "anim.flc", ... } } +import importlib.util, os, tempfile + +INPUTS = ["tools/docs_check.py", "tools/fixtures/fli.py", "tools/fixtures/smk.py", "tools/fixtures/_video.py"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_legacy_" + name.replace("/", "_"), os.path.join(ctx.root, "tools", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + dc = load(ctx, "docs_check") + fli = load(ctx, "fixtures/fli") + smk = load(ctx, "fixtures/smk") + v = load(ctx, "fixtures/_video") + files = {} + w, h, n = 64, 48, 10 + imgs = fli.idx_frames(w, h, n, 256, 5) + frames = [fli.frame([fli.color([(0, fli.pal(256, 5, False))], False), fli.brun([[bytes([x]) for x in r] for r in imgs[0]], 1, True)])] + frames += [fli.frame([fli.ss2(imgs[t], imgs[t - 1])]) for t in range(1, n)] + files["anim.flc"] = fli.file(0xAF12, w, h, 8, 100, frames) + files["intro.smk"] = smk.smk_file(4, 64, 48, 10, 100, [("packed", 22050, 2, 16), ("raw", 11025, 1, 8)], False, 7) + with tempfile.TemporaryDirectory() as d: + out = os.path.join(d, "cinepak.mov") + v.ffmpeg(["-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1", "-c:v", "cinepak", out]) + files["cinepak.mov"] = open(out, "rb").read() + dc.emit_inputs(ctx, files, {"flcBytes": "anim.flc", "smkBytes": "intro.smk", "cinepakBytes": "cinepak.mov"}) From d294c211f9aa9af0eff5e68cc6658c9b62040168 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:48:46 -0500 Subject: [PATCH 35/54] ws-tex: image/pcx (read 1/2/4/8-bit, planes, palettes; write 8-bit palette / 24 / 32-bit RLE) Tested against netpbm ppmtopcx / ImageMagick / Pillow files decoded by pcxtoppm; our files read by ImageMagick. Shared test helper tests/image/_raster.luau and fixture helper tools/fixtures/_raster_ref.py. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/image/pcx/init.luau | 266 ++++++++++++++++++++++++++++++++ tests/image/_raster.luau | 78 ++++++++++ tests/image/pcx.luau | 39 +++++ tools/fixtures/_raster_ref.py | 122 +++++++++++++++ tools/fixtures/_tex_encode.luau | 38 +++++ tools/fixtures/pcx.py | 58 +++++++ 8 files changed, 614 insertions(+) create mode 100644 src/Formats/image/pcx/init.luau create mode 100644 tests/image/_raster.luau create mode 100644 tests/image/pcx.luau create mode 100644 tools/fixtures/_raster_ref.py create mode 100644 tools/fixtures/pcx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 48b6db4..d8f80cb 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -13,6 +13,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | | image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` | +| image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` | | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index beaefc8..636a18b 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -110,6 +110,18 @@ local list: { Entry } = { return require("@formats/image/ktx") end, }, + { + name = "pcx", + category = "image", + path = "image/pcx", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, + load = function() + return require("@formats/image/pcx") + end, + }, { name = "png", category = "image", diff --git a/src/Formats/image/pcx/init.luau b/src/Formats/image/pcx/init.luau new file mode 100644 index 0000000..200af75 --- /dev/null +++ b/src/Formats/image/pcx/init.luau @@ -0,0 +1,266 @@ +--!strict +-- image/pcx: ZSoft PC Paintbrush (the ZSoft "Technical Reference Manual" PCX header and RLE; new code). Decode: 1-bit +-- monochrome, 1-bit x 2..4 planes (EGA, the header palette), 2 / 4-bit packed (the header palette), 8-bit with the +-- 256-colour palette at the end (grey when it is missing), 8-bit x 3 / 4 planes (RGB / RGBA); RLE (runs may cross +-- scan lines) and the rare uncompressed encoding; the window (xMin / yMin) and DPI (meta.dpi). Encode: rgba8 as +-- 8-bit palette (up to 256 opaque colours), 24-bit (3 planes) or 32-bit (4 planes, when there is alpha), RLE. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Pcx = { + name = "pcx", + category = "image", + extensions = { "pcx", "pcc", "dcx" }, + mime = { "image/vnd.zbrush.pcx", "image/x-pcx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 4, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + palette: boolean?, -- 8-bit palette when possible (default true); false: always 24 / 32-bit planes +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 + +-- ------------------------------------------------------------------------------------------------ sniff +function Pcx.sniff(r: Bytes.Reader): number + if r:size() < 128 then + return 0 + end + local m, v, e, bpp = r:peekU8(0), r:peekU8(1), r:peekU8(2), r:peekU8(3) + if m ~= 10 or (v ~= 0 and v ~= 2 and v ~= 3 and v ~= 4 and v ~= 5) or e > 1 then + return 0 + end + return if bpp == 1 or bpp == 2 or bpp == 4 or bpp == 8 then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Pcx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 128 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if readu8(b, o) ~= 10 then + return nil, Err.new(Err.CORRUPT, "not a PCX file", o) + end + local version, enc, bpp = readu8(b, o + 1), readu8(b, o + 2), readu8(b, o + 3) + local x0, y0, x1, y1 = readu16(b, o + 4), readu16(b, o + 6), readu16(b, o + 8), readu16(b, o + 10) + local planes, bpl = readu8(b, o + 65), readu16(b, o + 66) + local w, h = x1 - x0 + 1, y1 - y0 + 1 + if x1 < x0 or y1 < y0 then + return nil, Err.new(Err.CORRUPT, "bad window", o + 4) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local kind + if bpp == 8 and planes == 1 then + kind = "pal8" + elseif bpp == 8 and (planes == 3 or planes == 4) then + kind = "rgb" + elseif bpp == 1 and planes >= 1 and planes <= 4 then + kind = "planar" + elseif (bpp == 2 or bpp == 4) and planes == 1 then + kind = "packed" + else + return nil, Err.new(Err.UNSUPPORTED, string.format("%d bits x %d planes", bpp, planes), o + 3) + end + if bpl * 8 < w * bpp then + return nil, Err.new(Err.CORRUPT, "bytes per line too small", o + 66) + end + -- the scan lines (planes after each other per line), RLE across lines + local total = bpl * planes * h + local raw = buffer.create(total) + local p, q = o + 128, 0 + local truncated = false + if enc == 1 then + while q < total do + if p >= limit then + truncated = true + break + end + local c = readu8(b, p) + p += 1 + if c >= 0xC0 then + if p >= limit then + truncated = true + break + end + local n = math.min(c - 0xC0, total - q) + buffer.fill(raw, q, readu8(b, p), n) + p += 1 + q += n + else + buffer.writeu8(raw, q, c) + q += 1 + end + end + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + p += n + truncated = n < total + end + -- palettes + local pal = buffer.create(1024) + local function setPal(i: number, rr: number, gg: number, bb: number) + buffer.writeu32(pal, i * 4, rr + gg * 256 + bb * 65536 + 0xFF000000) + end + if kind == "pal8" then + local at = limit - 769 + if at >= p and readu8(b, at) == 12 then + for i = 0, 255 do + setPal(i, readu8(b, at + 1 + i * 3), readu8(b, at + 2 + i * 3), readu8(b, at + 3 + i * 3)) + end + else + for i = 0, 255 do + setPal(i, i, i, i) + end + end + elseif kind == "planar" and planes == 1 then + setPal(0, 0, 0, 0) + setPal(1, 255, 255, 255) + else + for i = 0, 15 do + setPal(i, readu8(b, o + 16 + i * 3), readu8(b, o + 17 + i * 3), readu8(b, o + 18 + i * 3)) + end + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if kind == "pal8" or kind == "packed" then + Pixels.indexed(raw, 0, bpl, bpp, px, w, h, true, pal) + elseif kind == "planar" then + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local idx = 0 + for pl = 0, planes - 1 do + local byte = readu8(raw, row + pl * bpl + bit32.rshift(x, 3)) + idx += bit32.band(bit32.rshift(byte, 7 - bit32.band(x, 7)), 1) * bit32.lshift(1, pl) + end + buffer.writeu32(px, (y * w + x) * 4, buffer.readu32(pal, idx * 4)) + end + end + else + for y = 0, h - 1 do + local row = y * bpl * planes + for x = 0, w - 1 do + local d = (y * w + x) * 4 + buffer.writeu8(px, d, readu8(raw, row + x)) + buffer.writeu8(px, d + 1, readu8(raw, row + bpl + x)) + buffer.writeu8(px, d + 2, readu8(raw, row + 2 * bpl + x)) + buffer.writeu8(px, d + 3, if planes == 4 then readu8(raw, row + 3 * bpl + x) else 255) + end + end + end + if kind == "pal8" or kind == "packed" or (kind == "planar" and planes > 1) then + local list: { { number } } = {} + for i = 0, (if kind == "pal8" then 256 else bit32.lshift(1, bpp * planes)) - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + local hd, vd = readu16(b, o + 12), readu16(b, o + 14) + if hd > 0 and vd > 0 then + img.meta.dpi = { x = hd, y = vd } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "pcx", version = version, bitDepth = bpp * planes, planes = planes, x = x0, y = y0, rle = enc == 1 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- RLE of one plane row into w +local function rleRow(out: Bytes.Writer, src: buffer, p: number, n: number) + local i = 0 + while i < n do + local v = readu8(src, p + i) + local run = 1 + while i + run < n and run < 63 and readu8(src, p + i + run) == v do + run += 1 + end + if run > 1 or v >= 0xC0 then + out:u8(0xC0 + run) + end + out:u8(v) + i += run + end +end + +function Pcx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 and not (opts and opts.palette == false) + local planes = if usePal then 1 elseif alpha then 4 else 3 + local bpl = w + w % 2 + local out = Bytes.writer(128 + w * h * planes + 800) + out:u8(10) + out:u8(5) + out:u8(1) + out:u8(8) + out:u16le(0) + out:u16le(0) + out:u16le(w - 1) + out:u16le(h - 1) + local dpi = img.meta and img.meta.dpi + out:u16le(if dpi then math.floor(dpi.x + 0.5) else 72) + out:u16le(if dpi then math.floor(dpi.y + 0.5) else 72) + out:fill(0, 48) + out:u8(0) + out:u8(planes) + out:u16le(bpl) + out:u16le(1) + out:fill(0, 58) + local row = buffer.create(bpl) + local index: { [number]: number } = {} + for i, c in cols do + index[c] = i - 1 + end + for y = 0, h - 1 do + for pl = 0, planes - 1 do + for x = 0, w - 1 do + local s = (y * w + x) * 4 + local v + if usePal then + v = index[bit32.band(buffer.readu32(px, s), 0xFFFFFF)] or 0 + else + v = readu8(px, s + pl) + end + buffer.writeu8(row, x, v) + end + rleRow(out, row, 0, bpl) + end + end + if usePal then + out:u8(12) + for i = 0, 255 do + local c = cols[i + 1] or 0 + out:u8(bit32.band(c, 255)) + out:u8(bit32.band(bit32.rshift(c, 8), 255)) + out:u8(bit32.rshift(c, 16)) + end + end + return out:finish(), nil +end + +return Pcx diff --git a/tests/image/_raster.luau b/tests/image/_raster.luau new file mode 100644 index 0000000..98e16e9 --- /dev/null +++ b/tests/image/_raster.luau @@ -0,0 +1,78 @@ +-- tests/image/_raster: the shared checks of the simple raster formats' tests (pcx, sgi, sunras, xbm, xpm, ilbm, icns, +-- ani): decode every case against its reference rgba8 pixels, round-trip images through the encoder, fuzz samples. +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +local R = {} + +local function maxDiff(a: buffer, b: buffer, n: number): (number, number) + local worst, at = 0, -1 + for i = 0, n * 4 - 1 do + local d = math.abs(buffer.readu8(a, i) - buffer.readu8(b, i)) + if d > worst then + worst, at = d, i // 4 + end + end + return worst, at +end +R.maxDiff = maxDiff + +-- cases: { { name, data, w, h, rgba, tol? } } (rgba: the reference decode) +function R.decodes(t: any, Fmt: any, cases: { any }, opts: any?): number + local n = 0 + for _, c in cases do + local img, err = Fmt.decode(Bytes.reader(buffer.fromstring(c.data)), opts) + t:check(img, c.name .. ": " .. tostring(err)) + if img then + t:check(img.width == c.w and img.height == c.h and img.format == "rgba8", string.format("%s: %d x %d %s", c.name, img.width, img.height, img.format)) + if img.width == c.w and img.height == c.h then + local d, at = maxDiff(img.pixels, buffer.fromstring(c.rgba), c.w * c.h) + t:check(d <= (c.tol or 0), string.format("%s: %d off the reference at pixel %d", c.name, d, at)) + end + n += 1 + end + -- from inside a bigger buffer + local big = buffer.create(#c.data + 9) + buffer.writestring(big, 5, c.data) + local img2 = Fmt.decode(Bytes.reader(big, 5, #c.data), opts) + t:check(img2 and img and buffer.tostring(img2.pixels) == buffer.tostring(img.pixels), c.name .. ": from a sub-range") + end + return n +end + +-- image(w, h, rgba string) -> Types.Image +function R.image(w: number, h: number, rgba: string): Types.Image + local img = Types.Image.new(w, h) + img.pixels = buffer.fromstring(rgba) + return img +end + +-- roundTrip(t, Fmt, img, encodeOpts?, label, tol?) -> the encoded buffer +function R.roundTrip(t: any, Fmt: any, img: Types.Image, eopts: any?, label: string, tol: number?): buffer? + local enc, err = Fmt.encode(img, eopts) + t:check(enc, label .. ": encode " .. tostring(err)) + if not enc then + return nil + end + local back, derr = Fmt.decode(Bytes.reader(enc)) + t:check(back, label .. ": decode " .. tostring(derr)) + if back then + t:check(back.width == img.width and back.height == img.height, label .. ": size") + local d = maxDiff(back.pixels, img.pixels, img.width * img.height) + t:check(d <= (tol or 0), string.format("%s: round trip %d off", label, d)) + end + return enc +end + +-- samples(cases, every?) -> the fuzz samples (every n-th case's data) +function R.samples(cases: { any }, every: number?): { string } + local samples = {} + for i, c in cases do + if i % (every or 1) == 0 then + table.insert(samples, c.data) + end + end + return samples +end + +return R diff --git a/tests/image/pcx.luau b/tests/image/pcx.luau new file mode 100644 index 0000000..2386c54 --- /dev/null +++ b/tests/image/pcx.luau @@ -0,0 +1,39 @@ +-- image/pcx tests: files from netpbm (24-bit, 8-bit, packed 2 / 4-bit, 3 / 4 planes, mono), ImageMagick and Pillow +-- against pcxtoppm's decode; our files read by ImageMagick; round trips (palette, 24-bit, 32-bit alpha); errors; the +-- fuzz no-throw pass. Fixtures: tools/fixtures/pcx.py. +local T = require("@tests/T") +local Pcx = require("@formats/image/pcx") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/pcx") + +local t = T.suite("pcx") +t:eq(Pcx.name, "pcx", "name") +t:check(Pcx.caps.decode and Pcx.caps.encode, "caps") + +t:note("%d files match pcxtoppm", R.decodes(t, Pcx, Fx.cases)) +-- our files: ImageMagick reads what we decode +for _, o in Fx.ours do + local img = Pcx.decode(Bytes.reader(buffer.fromstring(o.data))) :: any + t:eq(R.maxDiff(img.pixels, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": ImageMagick reads our file") +end +for _, c in Fx.cases do + R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + R.roundTrip(t, Pcx, R.image(c.w, c.h, c.rgba), { palette = false }, c.name .. " re-encoded 24-bit") +end +do + local img = R.image(3, 2, string.rep("\1\2\3\128", 6)) + local enc = R.roundTrip(t, Pcx, img, nil, "alpha: 4 planes") :: buffer + t:eq(buffer.readu8(enc, 65), 4, "alpha -> 4 planes") + t:eq(Pcx.sniff(Bytes.reader(enc)), 0.8, "sniff") + t:eq(Pcx.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other") + local _, e = Pcx.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 60)))) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = Pcx.decode(Bytes.reader(enc), { maxPixels = 2 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") +end +t:fuzz("decode", function(b: buffer) + return Pcx.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_raster_ref.py b/tools/fixtures/_raster_ref.py new file mode 100644 index 0000000..da5970b --- /dev/null +++ b/tools/fixtures/_raster_ref.py @@ -0,0 +1,122 @@ +# Shared by the simple raster fixture generators (pcx, sgi, sunras, xbm, xpm, ilbm, icns, ani): source images, a PNG +# writer, netpbm / ImageMagick runs in one temp dir, and a PNM / PAM reader for their output. +# work = Work(ctx) a temp dir; work.png(name, w, h, rgba); work.sh("netpbm", ["cmd", ...]); work.read(n) +# pnm_rgba(data) -> (w, h, rgba) for P1..P7 (PBM 1 = black; PAM GRAYSCALE[_ALPHA] / RGB[_ALPHA]) +import os, random, shutil, struct, subprocess, tempfile, zlib + + +def png(w, h, rgba): + raw = b"".join(b"\0" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d)) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")) + + +def photo(w, h, seed=1, alpha=False): + rng = random.Random(seed) + out = bytearray() + for y in range(h): + for x in range(w): + r = (x * 255) // max(1, w - 1) + g = (y * 255) // max(1, h - 1) + b = ((x * 7 + y * 3) * 4 + rng.randrange(8)) % 256 + a = 255 if not alpha else ((x * 37 + y * 11) % 256) + out += bytes((r, g, b, a)) + return bytes(out) + + +def palette_image(w, h, ncolours, seed=2): + rng = random.Random(seed) + cols = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(ncolours)] + out = bytearray() + for y in range(h): + for x in range(w): + out += bytes(cols[(x // 3 + y // 2 + (x * y) % 3) % ncolours]) + b"\xff" + return bytes(out) + + +class Work: + def __init__(self, ctx): + self.ctx = ctx + self.dir = tempfile.mkdtemp(prefix="formats-raster-") + + def close(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def path(self, n): + return os.path.join(self.dir, n) + + def write(self, n, data): + with open(self.path(n), "wb") as f: + f.write(data) + + def read(self, n): + with open(self.path(n), "rb") as f: + return f.read() + + def png(self, n, w, h, rgba): + self.write(n, png(w, h, rgba)) + + def sh(self, pkg, cmds): + script = " && ".join(cmds) + res = subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", "cd %s && %s" % (self.dir, script)], capture_output=True) + if res.returncode: + raise RuntimeError("%s failed: %s" % (pkg, res.stderr.decode()[-1500:])) + return res.stdout + + +def _tokens(data, n, pos): + out = [] + while len(out) < n: + while data[pos:pos + 1].isspace(): + pos += 1 + if data[pos:pos + 1] == b"#": + while data[pos:pos + 1] not in (b"\n", b""): + pos += 1 + continue + s = pos + while not data[pos:pos + 1].isspace(): + pos += 1 + out.append(int(data[s:pos])) + return out, pos + 1 + + +def pnm_rgba(data): + kind = data[:2] + if kind == b"P7": + end = data.index(b"ENDHDR\n") + 7 + hdr = dict(l.split(None, 1) for l in data[3:end - 7].decode().strip().split("\n") if l and not l.startswith("#")) + w, h, d, mx = int(hdr["WIDTH"]), int(hdr["HEIGHT"]), int(hdr["DEPTH"]), int(hdr["MAXVAL"]) + raw, pos = data[end:], 0 + elif kind in (b"P4",): + (w, h), pos = _tokens(data, 2, 2) + bits = data[pos:] + stride = (w + 7) // 8 + out = bytearray() + for y in range(h): + for x in range(w): + v = 0 if (bits[y * stride + x // 8] >> (7 - x % 8)) & 1 else 255 + out += bytes((v, v, v, 255)) + return w, h, bytes(out) + else: + (w, h, mx), pos = _tokens(data, 3, 2) + d = 1 if kind == b"P5" else 3 + raw = data[pos:] + bps = 2 if mx > 255 else 1 + out = bytearray() + for i in range(w * h): + vals = [] + for k in range(d): + o = (i * d + k) * bps + v = raw[o] if bps == 1 else (raw[o] << 8 | raw[o + 1]) + vals.append((v * 255 + mx // 2) // mx) + if d == 1: + out += bytes((vals[0],) * 3 + (255,)) + elif d == 2: + out += bytes((vals[0],) * 3 + (vals[1],)) + elif d == 3: + out += bytes(vals) + b"\xff" + else: + out += bytes(vals) + return w, h, bytes(out) diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 4c21f24..12d8cf6 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -108,3 +108,41 @@ if which == "exr" then emit("ours_rgb_zip.exr", Exr.encode(opaque)) emit("ours_from_rgba8.exr", Exr.encode(image(16, 16, "rgba8", 2))) end + +-- the simple raster writers: a 37 x 23 photo-like image (opaque and with alpha) and a 12-colour one +local function photo(alpha: boolean): Types.Image + local img = image(37, 23, "rgba8", 0) + if not alpha then + for i = 0, 37 * 23 - 1 do + buffer.writeu8(img.pixels, i * 4 + 3, 255) + end + end + return img +end +local function few(): Types.Image + local img = Types.Image.new(30, 20) + for y = 0, 19 do + for x = 0, 29 do + local k = (x // 3 + y // 2) % 12 + buffer.writeu32(img.pixels, (y * 30 + x) * 4, (k * 20) + (255 - k * 20) * 256 + ((k * 77) % 256) * 65536 + 0xFF000000) + end + end + return img +end +local function simple(): any + if which == "pcx" then + return require("@formats/image/pcx") + end + return nil +end +local Fmt = simple() +if Fmt then + for name, img in { opaque = photo(false), alpha = photo(true), few = few() } do + local out, err = Fmt.encode(img) + if out then + emit("ours_" .. name .. "." .. which, out) + else + print("skip\t" .. name .. "\t" .. tostring(err)) + end + end +end diff --git a/tools/fixtures/pcx.py b/tools/fixtures/pcx.py new file mode 100644 index 0000000..1b31968 --- /dev/null +++ b/tools/fixtures/pcx.py @@ -0,0 +1,58 @@ +# PCX fixtures (tools/fixtures.py): files from netpbm's ppmtopcx (24-bit planes, 8-bit palette, packed 1 / 2 / 4-bit, +# 4-plane EGA, 1-bit mono), ImageMagick (24-bit, palette) and Pillow (RGB, P, L, 1), decoded by pcxtoppm (netpbm) as +# the reference; our encoder's files (tools/fixtures/_tex_encode.luau -a pcx) decoded by ImageMagick (it reads 4-plane alpha). +# tests/gen/pcx.luau { cases = { { name, data, w, h, rgba } }, ours = { { name, data, w, h, rgba } } } +import importlib.util, os, shutil, subprocess + +_spec = importlib.util.spec_from_file_location("_raster_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_raster_ref.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/pcx"] + + +def ours(ctx, which): + exe = shutil.which("luau") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if line.startswith("ours_") and "\t" in line: + n, hx = line.split("\t", 1) + files[n] = bytes.fromhex(hx.strip()) + return files + + +def generate(ctx): + w = R.Work(ctx) + try: + w.png("photo.png", 37, 23, R.photo(37, 23)) + w.png("pal.png", 40, 30, R.palette_image(40, 30, 200)) + w.png("c16.png", 33, 17, R.palette_image(33, 17, 16, 5)) + w.png("c4.png", 21, 9, R.palette_image(21, 9, 4, 6)) + w.png("mono.png", 29, 13, bytes(v for i in range(29 * 13) for v in ((255,) * 3 if (i * 7) % 5 < 2 else (0,) * 3) + (255,))) + nb = ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam c16.png | pamtopnm > c16.ppm", + "pngtopam c4.png | pamtopnm > c4.ppm", "pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm > mono.pbm", + "ppmtopcx -24bit photo.ppm > nb_24bit.pcx", "ppmtopcx -8bit pal.ppm > nb_8bit.pcx", "ppmtopcx -packed c16.ppm > nb_packed4.pcx", + "ppmtopcx -packed c4.ppm > nb_packed2.pcx", "ppmtopcx -planes 4 c16.ppm > nb_planes4.pcx", "ppmtopcx mono.pbm > nb_mono.pcx", + "ppmtopcx -planes 3 c4.ppm > nb_planes3.pcx"] + w.sh("netpbm", nb) + w.sh("imagemagick", ["magick photo.png -alpha off im_24bit.pcx", "magick pal.png -alpha off -type palette im_palette.pcx"]) + code = ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('photo.png').convert('RGB')\nim.save('pil_rgb.pcx')\n" + "Image.open('pal.png').convert('RGB').quantize(256).save('pil_p.pcx')\nim.convert('L').save('pil_l.pcx')\n" + "Image.open('mono.png').convert('1').save('pil_1.pcx')\n") % w.dir + ctx.python(["pillow"], code) + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".pcx")) + mine = ours(ctx, "pcx") + for n, d in mine.items(): + w.write(n, d) + allnames = names + sorted(mine) + w.sh("netpbm", ["pcxtoppm %s > %s.ppm" % (n, n) for n in names]) + w.sh("imagemagick", ["magick %s -depth 8 pam:%s.ppm" % (n, n) for n in sorted(mine)]) + cases, our = [], [] + for n in allnames: + ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm")) + (our if n.startswith("ours_") else cases).append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}) + ctx.emit("pcx", {"cases": cases, "ours": our}) + finally: + w.close() From d22c72c1bc967dc4ff2a0628e50c4298e40e91dd Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:50:27 -0500 Subject: [PATCH 36/54] ws-video2: MPEG-2 field-picture / concealment-vector fixtures (a syntax-level writer in tools/fixtures/mpeg2.py), bit-exact; LuaJIT-friendlier hot paths; mpeg2 bench line --- src/Formats/codecs/video/Mpeg2/Decoder.luau | 67 ++++-- tests/codecs/mpeg2.luau | 4 +- tools/bench.luau | 17 ++ tools/fixtures/mpeg2.py | 252 +++++++++++++++++++- 4 files changed, 322 insertions(+), 18 deletions(-) diff --git a/src/Formats/codecs/video/Mpeg2/Decoder.luau b/src/Formats/codecs/video/Mpeg2/Decoder.luau index 4cd982c..e25801d 100644 --- a/src/Formats/codecs/video/Mpeg2/Decoder.luau +++ b/src/Formats/codecs/video/Mpeg2/Decoder.luau @@ -31,6 +31,7 @@ local readi32 = buffer.readi32 local writei32 = buffer.writei32 local band = bit32.band local bor = bit32.bor +local bxor = bit32.bxor local lshift = bit32.lshift local rshift = bit32.rshift local bswap = bit32.byteswap @@ -549,12 +550,18 @@ function D.new(maxPixels: number?): Core mc(rY, stride, sb + sy * stride + sx, curY, stride, dOff, 16, h, hx, hy, avg) end -- chroma: horizontal vector / 2 truncated toward zero; vertical too in 4:2:0 - local mx = if mvx < 0 then -((-mvx) // 2) else mvx // 2 + local mx = mvx // 2 + if mvx < 0 then + mx = -((-mvx) // 2) + end local cx, cy, chh, cph, chx, chy chx = band(mx, 1) cx = mbCol * 8 + (mx - chx) // 2 if chroma == 1 then - local my = if mvy < 0 then -((-mvy) // 2) else mvy // 2 + local my = mvy // 2 + if mvy < 0 then + my = -((-mvy) // 2) + end chy = band(my, 1) cy = rowY // 2 + (my - chy) // 2 chh, cph = h // 2, ph // 2 @@ -563,7 +570,11 @@ function D.new(maxPixels: number?): Core cy = rowY + (mvy - chy) // 2 chh, cph = h, ph end - local cdOff = cdb + (if chroma == 1 then rowY // 2 else rowY) * cs + mbCol * 8 + local crow = rowY + if chroma == 1 then + crow = rowY // 2 + end + local cdOff = cdb + crow * cs + mbCol * 8 if cx < 0 or cy < 0 or cx + 8 + chx > chw or cy + chh + chy > cph then Dsp.edge(rCb, cs, csb, cx, cy, 8, chh, chw, cph, EDGE) mc(EDGE, 32, 0, curCb, cs, cdOff, 8, chh, chx, chy, avg) @@ -592,8 +603,15 @@ function D.new(maxPixels: number?): Core local function predictDir(d: number, avg: boolean) local o = d * 8 if not fieldPic then - local r = (if d == 0 then fwS else bwS) or cur :: Store - local ry, rcb, rcr = r.y, r.cb, r.cr + local r = bwS + if d == 0 then + r = fwS + end + if r == nil then + r = cur + end + local ref = r :: Store + local ry, rcb, rcr = ref.y, ref.cb, ref.cr if motionType == 1 then mcPart(ry, rcb, rcr, -1, -1, mbRow * 16, 16, MV[o + 1], MV[o + 2], avg) elseif motionType == 2 then @@ -736,7 +754,10 @@ function D.new(maxPixels: number?): Core dc = dcY else size = vlc(DC_CHROMA, DC_CHROMA_BITS) - dc = if b % 2 == 0 then dcCb else dcCr + dc = dcCr + if b % 2 == 0 then + dc = dcCb + end end if size > 0 then local diff = read(size) @@ -761,14 +782,24 @@ function D.new(maxPixels: number?): Core end local v = lshift(dc, 3 - dcPrec) writei32(blk, 0, v) - parityOdd = bit32.bxor(1, band(v, 1)) - q = if luma then intraQ else chromaIntraQ + parityOdd = bxor(1, band(v, 1)) + q = chromaIntraQ + if luma then + q = intraQ + end n = 1 else - q = if luma then nonIntraQ else chromaNonIntraQ + q = chromaNonIntraQ + if luma then + q = nonIntraQ + end + end + local lut, nextLut = DCT_NEXT, DCT_NEXT + if mbIntra and intraVlc then + lut, nextLut = DCT_B15, DCT_B15 + elseif n == 0 then + lut = DCT_FIRST end - local lut = if mbIntra and intraVlc then DCT_B15 elseif n == 0 then DCT_FIRST else DCT_NEXT - local nextLut = if mbIntra and intraVlc then DCT_B15 else DCT_NEXT local intra = mbIntra local qs = qscale local m2 = mpeg2 @@ -853,7 +884,9 @@ function D.new(maxPixels: number?): Core if neg then m = -m end - parityOdd = bit32.bxor(parityOdd, band(m, 1)) + if m2 then + parityOdd = bxor(parityOdd, band(m, 1)) + end -- saturate if m > 2047 then m = 2047 @@ -887,7 +920,10 @@ function D.new(maxPixels: number?): Core off = (mbRow * 16 + (if b >= 2 then 8 else 0)) * cw + mbCol * 16 + (if b % 2 == 1 then 8 else 0) end else - dst = if b % 2 == 0 then curCb else curCr + dst = curCr + if b % 2 == 0 then + dst = curCb + end local k = (b - 4) // 2 -- the vertical chroma block of a 4:2:2 macroblock if chroma == 1 then stride = cstride @@ -923,7 +959,10 @@ function D.new(maxPixels: number?): Core -- motion vectors of direction d (13818-2 7.6.3; MPEG-1: frame vectors, full_pel doubled) local function motionVectors(d: number) - local fh, fv = if d == 0 then fc00 else fc10, if d == 0 then fc01 else fc11 + local fh, fv = fc10, fc11 + if d == 0 then + fh, fv = fc00, fc01 + end local o, p, f = d * 8, d * 4, d * 2 if motionType == 1 and not fieldPic then local x = decodeMotion(fh, PMV[p + 1]) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index fb3da3f..cd88a82 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -1,7 +1,7 @@ -- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and -- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan, -- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd --- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display +-- size, B-frames, dual prime, field pictures, concealment vectors) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display -- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive, -- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted -- streams never throw; the fuzz no-throw pass. @@ -24,6 +24,8 @@ local STREAMS = { require("@tests/gen/mpeg2_c422"), require("@tests/gen/mpeg2_c422_ilace"), require("@tests/gen/mpeg2_dualprime"), + require("@tests/gen/mpeg2_fields"), + require("@tests/gen/mpeg2_fields_conceal"), } local t = T.suite("codecs/mpeg2") diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..4712a7c 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -964,11 +964,28 @@ do end end end + -- MPEG-2: 720x576 interlaced (field prediction / field DCT, B-frames), as on a DVD (ws-video2) + local M2 = require("@tests/gen/mpeg2_bench") + local function mpeg2(tag: string) + for _, s in M2 do + local file = Base64.decode(s.file) :: buffer + fps(string.format("mpeg2 decode yuv %dx%d interlaced%s", s.width, s.height, tag), 3, #s.units, function() + local dec = Mpeg1.new({ reorder = true, rgba = false }) + for i, u in s.units do + dec:decode(file, u[1], u[2], i) + end + while dec:flush() do + end + end) + end + end jitTune(false) mpeg1("") + mpeg2("") if runtime == "luajit" then jitTune(true) mpeg1(" (jit tuned)") + mpeg2(" (jit tuned)") jitTune(false) end end diff --git a/tools/fixtures/mpeg2.py b/tools/fixtures/mpeg2.py index b9e1f00..17a931b 100644 --- a/tools/fixtures/mpeg2.py +++ b/tools/fixtures/mpeg2.py @@ -1,9 +1,11 @@ # MPEG-2 video fixtures for codecs/video/Mpeg2 (tools/fixtures.py): elementary streams from ffmpeg's mpeg2video encoder # (progressive and interlaced frame pictures with field prediction / field DCT, top and bottom field first, 4:2:2, the # alternate scan, Table B-15 intra VLCs, the non-linear quantiser scale, intra DC precision 9..11, custom luma and -# chroma matrices, large motion (f_code > 1), odd sizes, B-frames) and from mjpegtools' mpeg2enc (dual-prime -# prediction in interlaced frame pictures), each with `ffmpeg -idct int` decoding as the reference: the IJG integer -# IDCT that codecs/video/Dsp reproduces, so the planes must match exactly. +# chroma matrices, large motion (f_code > 1), odd sizes, B-frames), from mjpegtools' mpeg2enc (dual-prime +# prediction in interlaced frame pictures) and from field_stream below (field pictures: I / P / B fields, the second +# field predicted from the first, field / 16x8 / dual-prime prediction, skipped macroblocks; concealment vectors), +# each with `ffmpeg -idct int` decoding as the reference: the IJG integer IDCT that codecs/video/Dsp reproduces, so +# the planes must match exactly. # tests/gen/mpeg2_.luau { name, width, height, chroma (1 4:2:0 / 2 4:2:2), frames, file (base64), # units = { { offset, length } } (one per picture), crcs = { { y, u, v } } (CRC-32 of # every frame's cropped planes, display order), bands = { { crc } } (per frame, of @@ -126,6 +128,14 @@ def generate(ctx): % (dp, y4m)]) emit("dualprime", open(dp, "rb").read(), dp, 1) + # field pictures and concealment vectors (field_stream below: no encoder at hand writes them) + seq = [("I", "P"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B"), ("P", "P"), ("B", "B")] + for name, seed, dims, conceal in (("fields", 5, (320, 240), False), ("fields_conceal", 6, (176, 144), True)): + path = os.path.join(tmp, name + ".m2v") + es = field_stream(ctx.rng(seed), dims[0], dims[1], seq, conceal) + open(path, "wb").write(es) + emit(name, es, path, 1) + # the prog stream in the containers (stream copy) prog = os.path.join(tmp, "prog.m2v") cont = {"crcs": crcs["prog"]} @@ -176,3 +186,239 @@ def zlib_crc32_mpeg(data): for _ in range(8): crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF if crc & 0x80000000 else (crc << 1) & 0xFFFFFFFF return crc + + +# --------------------------------------------------------------------------------------------------------------------- +# A syntax-level MPEG-2 writer for what no encoder at hand produces: field pictures (I + P fields, the P field +# predicted from the first field of its own frame, P / B field pictures, field and 16x8 prediction, dual prime in +# field pictures, skipped macroblocks) and concealment motion vectors. The content is random (DC levels, sparse +# escape-coded coefficients, motion vectors kept inside the picture): any valid stream will do, ffmpeg's decode is +# the reference. The tables are those of ISO/IEC 13818-2 annex B (only the entries used here). +MBAI = {1: "1", 2: "011", 3: "010"} +DC_LUMA = ["100", "00", "01", "101", "110", "1110", "11110", "111110", "1111110"] +DC_CHROMA = ["00", "01", "10", "110", "1110", "11110", "111110", "1111110", "11111110"] +# |motion_code| 0..16 (Table B-10), then the sign bit +MOTION = ["1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010", "000001001", + "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100"] +CBP = {60: "111", 4: "1101", 8: "1100", 16: "1011", 32: "1010"} +MBTYPE_P = {"mc_coded": "1", "nomc_coded": "01", "mc": "001", "intra": "00011"} +MBTYPE_B = {"interp": "10", "interp_coded": "11", "bwd": "010", "bwd_coded": "011", "fwd": "0010", "fwd_coded": "0011", + "intra": "00011"} + + +class Bits: + def __init__(self): + self.s = [] + + def put(self, v, n): + self.s.append(format(v & ((1 << n) - 1), "0%db" % n) if n else "") + + def code(self, c): + self.s.append(c) + + def start(self, code): + # next_start_code: zero stuffing to a byte boundary, then 00 00 01 code + n = len("".join(self.s)) + if n % 8: + self.s.append("0" * (8 - n % 8)) + self.put(0x000001, 24) + self.put(code, 8) + + def bytes(self): + s = "".join(self.s) + s += "0" * (-len(s) % 8) + return bytes(int(s[i:i + 8], 2) for i in range(0, len(s), 8)) + + +def field_stream(rng, w, h, frames, conceal=False): + """frames: [(picture type per field, ...)] in decode order, e.g. [("I", "P"), ("P", "P"), ("B", "B")]""" + b = Bits() + mbw, mbh = (w + 15) // 16, 2 * ((h + 31) // 32) + fh = mbh * 8 # field height in lines (coded) + b.start(0xB3) + b.put(w, 12), b.put(h, 12), b.put(1, 4), b.put(3, 4), b.put(5000, 18), b.put(1, 1), b.put(112, 10), b.put(0, 1) + b.put(0, 1), b.put(0, 1) + b.start(0xB5) + b.put(1, 4), b.put(0x48, 8), b.put(0, 1), b.put(1, 2), b.put(0, 2), b.put(0, 2), b.put(0, 12), b.put(1, 1) + b.put(0, 8), b.put(0, 1), b.put(0, 2), b.put(0, 5) + b.start(0xB8) + b.put(0, 25), b.put(1, 1), b.put(0, 1) + # temporal references: decode order I P B P B ... is display order I B P B P (each B before the reference decoded + # just before it) + tr, d, last_ref = {}, 0, None + for k, f in enumerate(frames): + if f[0] != "B": + if last_ref is not None: + tr[last_ref] = d + d += 1 + last_ref = k + else: + tr[k] = d + d += 1 + tr[last_ref] = d + for k, (t0, t1) in enumerate(frames): + for fi, ptype in enumerate((t0, t1)): + parity = fi # top field first + pt = {"I": 1, "P": 2, "B": 3}[ptype] + b.start(0x00) + b.put(tr[k], 10), b.put(pt, 3), b.put(0xFFFF, 16) + if pt >= 2: + b.put(0, 1), b.put(7, 3) + if pt == 3: + b.put(0, 1), b.put(7, 3) + b.put(0, 1) + b.start(0xB5) + fc = (1, 1, 15, 15) if pt == 2 else (1, 1, 1, 1) if pt == 3 else (15, 15, 15, 15) + if pt == 1 and conceal: + fc = (1, 1, 15, 15) + b.put(8, 4) + for f in fc: + b.put(f, 4) + b.put(0, 2), b.put(1 + parity, 2), b.put(0, 1), b.put(0, 1), b.put(1 if conceal else 0, 1), b.put(0, 1) + b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1), b.put(0, 1) + # the second field of the first frame has one reference: the first field (no skips, zero-vector or + # dual-prime prediction from its own parity) + only_first = k == 0 and fi == 1 + for row in range(mbh // 2): + b.start(row + 1) + b.put(rng.choice((2, 4, 8)), 5), b.put(0, 1) + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] # [dir][r * 2 + c] + dc = [128, 128, 128] + col = 0 + prev_dirs = None + while col < mbw: + # B skips repeat the previous vectors: only after zero ones (they stay inside the picture) + skip = (pt != 1 and not only_first and col > 0 and col < mbw - 1 and rng.random() < 0.15 and + prev_dirs is not None and (pt == 2 or not any(pmv[0] + pmv[1]))) + if skip: + b.code(MBAI[2]) + col += 1 # the skipped one + dc = [128, 128, 128] + if pt == 2: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + else: + b.code(MBAI[1]) + if pt == 1 or rng.random() < 0.08: + b.code("1" if pt == 1 else (MBTYPE_P if pt == 2 else MBTYPE_B)["intra"]) + if conceal: + # field_select, a concealment vector (the predictor again: motion codes 0), marker + b.put(0, 1), b.code(MOTION[0]), b.code(MOTION[0]), b.put(1, 1) + pmv[0][2:] = pmv[0][:2] + else: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + for blk in range(6): + comp = 0 if blk < 4 else blk - 3 + target = rng.randrange(40, 216) + diff = target - dc[comp] + dc[comp] = target + size = abs(diff).bit_length() + b.code((DC_LUMA if comp == 0 else DC_CHROMA)[size]) + if size: + b.put(diff if diff > 0 else diff + (1 << size) - 1, size) + ac_block(b, rng, 1, 0.5) + prev_dirs = None + col += 1 + continue + dc = [128, 128, 128] + if pt == 2: + kind = rng.choice(("mc", "mc_coded", "mc_coded", "mc") if only_first else + ("mc", "mc_coded", "mc_coded", "nomc_coded", "mc")) + dirs = (0,) if kind != "nomc_coded" else () + b.code(MBTYPE_P[kind]) + coded = kind != "mc" + else: + kind = rng.choice(("interp", "interp_coded", "bwd", "bwd_coded", "fwd", "fwd_coded")) + dirs = (0, 1) if kind.startswith("interp") else (1,) if kind.startswith("bwd") else (0,) + b.code(MBTYPE_B[kind]) + coded = kind.endswith("coded") + if dirs: + choices = ["field", "16x8"] + (["dmv"] if pt == 2 and not only_first else []) + mt = rng.choice(choices) + b.put({"field": 1, "16x8": 2, "dmv": 3}[mt], 2) + for d in dirs: + motion(b, rng, pmv[d], mt, col, row, mbw, fh, parity, 0 if only_first else None) + else: + pmv = [[0, 0, 0, 0], [0, 0, 0, 0]] + if coded: + cbp = rng.choice(list(CBP)) + b.code(CBP[cbp]) + for blk in range(6): + if cbp & (32 >> blk): + ac_block(b, rng, 0, 0.6) + prev_dirs = dirs + col += 1 + b.start(0xB7) + return b.bytes() + + +def ac_block(b, rng, first, more): + # escape-coded coefficients (6-bit run, 12-bit level), then end_of_block ("10"); a non-intra block needs one + n = first + count = 0 + while n < 64 and (count == 0 and first == 0 or rng.random() < more): + run = rng.randrange(0, 6) + if n + run > 63: + break + level = rng.choice((-1, 1)) * rng.randrange(1, 24) + b.code("000001"), b.put(run, 6), b.put(level, 12) + n += run + 1 + count += 1 + b.code("10") + + +def put_motion(b, delta): + b.code(MOTION[abs(delta)]) + if delta: + b.put(1 if delta < 0 else 0, 1) + + +def wrap(v): + return (v + 16) % 32 - 16 + + +def motion(b, rng, pmv, mt, col, row, mbw, fh, parity, force_sel): + """one direction's vectors for a field-picture macroblock, kept inside the reference field""" + def ok(mx, my, rows, y0): + sx, sy = col * 16 + (mx >> 1), y0 + (my >> 1) + return sx >= 0 and sx + 16 + (mx & 1) <= mbw * 16 and sy >= 0 and sy + rows + (my & 1) <= fh + + def pick(px, py, rows, y0, extra=None): + for _ in range(50): + mx, my = rng.randrange(-12, 13), rng.randrange(-10, 11) + dx, dy = wrap(mx - px), wrap(my - py) + if ok(mx, my, rows, y0) and (extra is None or extra(mx, my)): + return dx, dy, mx, my + return None + + if mt == "field": + sel = rng.randrange(2) if force_sel is None else force_sel + r = pick(pmv[0], pmv[1], 16, row * 16) or (wrap(-pmv[0]), wrap(-pmv[1]), 0, 0) + b.put(sel, 1) + put_motion(b, r[0]), put_motion(b, r[1]) + mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1]) + pmv[:] = [mx, my, mx, my] + elif mt == "16x8": + for half in range(2): + sel = rng.randrange(2) if force_sel is None else force_sel + px, py = pmv[half * 2], pmv[half * 2 + 1] + r = pick(px, py, 8, row * 16 + half * 8) or (wrap(-px), wrap(-py), 0, 0) + b.put(sel, 1) + put_motion(b, r[0]), put_motion(b, r[1]) + pmv[half * 2], pmv[half * 2 + 1] = wrap(px + r[0]), wrap(py + r[1]) + else: + # dual prime: the vector, its differential (0, +1, -1) and the derived opposite-parity vector + def dmv_ok(dmx, dmy): + def f(mx, my): + ox = ((mx + (mx > 0)) >> 1) + dmx + oy = ((my + (my > 0)) >> 1) + dmy + (-1 if parity == 0 else 1) + return ok(ox, oy, 16, row * 16) + return f + for dmx, dmy in rng.sample([(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1)], 7): + r = pick(pmv[0], pmv[1], 16, row * 16, dmv_ok(dmx, dmy)) + if r: + break + assert r, "dual prime: no vector fits" + put_motion(b, r[0]), b.code({0: "0", 1: "10", -1: "11"}[dmx]) + put_motion(b, r[1]), b.code({0: "0", 1: "10", -1: "11"}[dmy]) + mx, my = wrap(pmv[0] + r[0]), wrap(pmv[1] + r[1]) + pmv[:] = [mx, my, mx, my] From 6e0b80a7f2078685e0e64466659799b203e75451 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:51:14 -0500 Subject: [PATCH 37/54] ws-video2: MpegEs Picture type annotation (type baseline) --- src/Formats/containers/MpegEs.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/containers/MpegEs.luau b/src/Formats/containers/MpegEs.luau index 704db06..77be2ef 100644 --- a/src/Formats/containers/MpegEs.luau +++ b/src/Formats/containers/MpegEs.luau @@ -134,7 +134,7 @@ function MpegEs.pictures(b: buffer, off: number, limit: number): { Picture } local x = readu8(b, p + 4) * 256 + readu8(b, p + 5) t, tr = (x // 8) % 8, x // 64 end - cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } + cur = { offset = unitStart or p, size = 0, type = t, temporal = tr, gop = gop, sequence = seq, structure = st } :: Picture unitStart, seq, gop = nil, false, false elseif code == 0xB7 and cur then cur.size = p + 4 - cur.offset From 403a4d6f31c94382d5fb12a0a643791d3a220abc Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:52:47 -0500 Subject: [PATCH 38/54] ws-tex: image/sgi + image/sunras (read + write) SGI: verbatim / RLE, 1-2 bytes per channel, 1-4 channels (rgba16 native); write RGB(A) RLE / verbatim. Sun Raster: 1 / 8 / 24 / 32-bit, standard / byte-encoded / RGB types, colour maps; write 24 / 32-bit. References: ImageMagick, netpbm (sgitopnm-era writers, rasttopnm), Pillow. --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 24 +++ src/Formats/image/sgi/init.luau | 286 +++++++++++++++++++++++++++++ src/Formats/image/sunras/init.luau | 247 +++++++++++++++++++++++++ tests/image/sgi.luau | 34 ++++ tests/image/sunras.luau | 42 +++++ tools/fixtures/_simple.py | 22 +++ tools/fixtures/_tex_encode.luau | 4 + tools/fixtures/sgi.py | 39 ++++ tools/fixtures/sunras.py | 45 +++++ 10 files changed, 745 insertions(+) create mode 100644 src/Formats/image/sgi/init.luau create mode 100644 src/Formats/image/sunras/init.luau create mode 100644 tests/image/sgi.luau create mode 100644 tests/image/sunras.luau create mode 100644 tools/fixtures/_simple.py create mode 100644 tools/fixtures/sgi.py create mode 100644 tools/fixtures/sunras.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index d8f80cb..79f098e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,6 +17,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | +| image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` | +| image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` | | image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 636a18b..2619353 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -158,6 +158,30 @@ local list: { Entry } = { return require("@formats/image/qoi") end, }, + { + name = "sgi", + category = "image", + path = "image/sgi", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, + load = function() + return require("@formats/image/sgi") + end, + }, + { + name = "sunras", + category = "image", + path = "image/sunras", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, + load = function() + return require("@formats/image/sunras") + end, + }, { name = "tga", category = "image", diff --git a/src/Formats/image/sgi/init.luau b/src/Formats/image/sgi/init.luau new file mode 100644 index 0000000..7699632 --- /dev/null +++ b/src/Formats/image/sgi/init.luau @@ -0,0 +1,286 @@ +--!strict +-- image/sgi: Silicon Graphics image files (.rgb / .sgi / .bw / .rgba; Paul Haeberli's "The SGI Image File Format" +-- 1.00; new code). Decode: verbatim and RLE storage, 1 and 2 bytes per channel, 1 (grey), 2 (grey + alpha), 3 (RGB) +-- and 4 (RGBA) channels, dimension 1 / 2 / 3, rows bottom-up; rgba8 (2-byte channels keep their high byte), or rgba16 +-- with opts.native for 2-byte files; the image name (meta.text.name). Encode: rgba8 as RGB (or RGBA when there is +-- alpha), RLE (default) or verbatim; rgba16 as 2-byte channels. Not supported: the obsolete dithered / screen / +-- colour-map files (colormap field 1..3: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Sgi = { + name = "sgi", + category = "image", + extensions = { "sgi", "rgb", "rgba", "bw", "int", "inta" }, + mime = { "image/sgi", "image/x-rgb" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + native: boolean?, -- rgba16 for 2-byte files (default false: rgba8) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + rle: boolean?, -- RLE storage (default true) + name: string?, -- the image name (up to 79 bytes; default meta.text.name) +} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sgi.sniff(r: Bytes.Reader): number + if Sniff.magic(r, "\1\218") == 0 or r:size() < 512 then + return 0 + end + local st, bpc = r:peekU8(2), r:peekU8(3) + return if st <= 1 and (bpc == 1 or bpc == 2) then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sgi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 512 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if be16(b, o) ~= 474 then + return nil, Err.new(Err.CORRUPT, "not an SGI image", o) + end + local rle, bpc, dim = readu8(b, o + 2), readu8(b, o + 3), be16(b, o + 4) + local w, h, z = be16(b, o + 6), be16(b, o + 8), be16(b, o + 10) + if dim == 1 then + h, z = 1, 1 + elseif dim == 2 then + z = 1 + end + if rle > 1 or (bpc ~= 1 and bpc ~= 2) or dim < 1 or dim > 3 or w == 0 or h == 0 or z == 0 then + return nil, Err.new(Err.CORRUPT, "bad header", o + 2) + end + if z > 4 then + return nil, Err.new(Err.UNSUPPORTED, z .. " channels", o + 10) + end + local cmap = be32(b, o + 104) + if cmap ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "colormap type " .. cmap, o + 104) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + -- channel planes as 16-bit samples (8-bit values scaled * 257) + local plane = buffer.create(w * h * z * 2) + local truncated = false + local function put(c: number, row: number, x: number, v: number) + buffer.writeu16(plane, ((c * h + row) * w + x) * 2, if bpc == 1 then v * 257 else v) + end + if rle == 0 then + local need = w * h * z * bpc + local p = o + 512 + local avail = math.min(need, limit - p) + truncated = avail < need + for i = 0, avail // bpc - 1 do + local v = if bpc == 1 then readu8(b, p + i) else be16(b, p + i * 2) + buffer.writeu16(plane, i * 2, if bpc == 1 then v * 257 else v) + end + else + local n = h * z + if o + 512 + n * 8 > limit then + return nil, Err.new(Err.TRUNCATED, "RLE tables run past the end", o + 512) + end + for c = 0, z - 1 do + for row = 0, h - 1 do + local i = c * h + row + local start, len = be32(b, o + 512 + i * 4), be32(b, o + 512 + n * 4 + i * 4) + local p = o + start + local stop = math.min(limit, p + len) + local x = 0 + while x < w and p + bpc <= stop do + local cnt = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + local count = bit32.band(cnt, 0x7F) + if count == 0 then + break + end + if bit32.band(cnt, 0x80) ~= 0 then + for _ = 1, count do + if x >= w or p + bpc > stop then + break + end + put(c, row, x, if bpc == 1 then readu8(b, p) else be16(b, p)) + p += bpc + x += 1 + end + else + if p + bpc > stop then + break + end + local v = if bpc == 1 then readu8(b, p) else be16(b, p) + p += bpc + for _ = 1, count do + if x >= w then + break + end + put(c, row, x, v) + x += 1 + end + end + end + if x < w then + truncated = true + end + end + end + end + local wide = opts and opts.native and bpc == 2 + local img = Types.Image.new(w, h, if wide then "rgba16" else "rgba8") + local px = img.pixels + for y = 0, h - 1 do + local row = h - 1 - y + for x = 0, w - 1 do + local function s(c: number): number + return buffer.readu16(plane, ((c * h + row) * w + x) * 2) + end + local rr: number = s(0) + local gg: number = if z >= 3 then s(1) else rr + local bb: number = if z >= 3 then s(2) else rr + local aa: number = if z == 2 then s(1) elseif z == 4 then s(3) else 65535 + local d = (y * w + x) + if wide then + buffer.writeu16(px, d * 8, rr) + buffer.writeu16(px, d * 8 + 2, gg) + buffer.writeu16(px, d * 8 + 4, bb) + buffer.writeu16(px, d * 8 + 6, aa) + else + buffer.writeu32(px, d * 4, bit32.rshift(rr, 8) + bit32.rshift(gg, 8) * 256 + bit32.rshift(bb, 8) * 65536 + bit32.rshift(aa, 8) * 16777216) + end + end + end + local name = buffer.readstring(b, o + 24, 80) + local zpos = string.find(name, "\0", 1, true) + name = if zpos then string.sub(name, 1, zpos - 1) else name + if name ~= "" then + img.meta.text = { name = name } + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sgi", bitDepth = bpc * 8, channels = z, rle = rle == 1, dimension = dim } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sgi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or (img.format ~= "rgba8" and img.format ~= "rgba16") or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 or rgba16 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local wide = img.format == "rgba16" + local bpc = if wide then 2 else 1 + local px = img.pixels + local function sample(x: number, y: number, c: number): number + local i = (y * w + x) * 4 + c + return if wide then buffer.readu16(px, i * 2) else readu8(px, i) + end + local z = 3 + for i = 0, w * h - 1 do + if (if wide then buffer.readu16(px, i * 8 + 6) < 65535 else readu8(px, i * 4 + 3) < 255) then + z = 4 + break + end + end + local rle = not (opts and opts.rle == false) + local out = Bytes.writer(512 + w * h * z * bpc + h * z * 8) + out:u16be(474) + out:u8(if rle then 1 else 0) + out:u8(bpc) + out:u16be(3) + out:u16be(w) + out:u16be(h) + out:u16be(z) + out:u32be(0) + out:u32be(if wide then 65535 else 255) + out:u32be(0) + local name = (opts and opts.name) or (img.meta and img.meta.text and img.meta.text.name) or "" + name = string.sub(name, 1, 79) + out:string(name) + out:fill(0, 80 - #name) + out:u32be(0) + out:fill(0, 404) + local function put(v: number) + if wide then + out:u16be(v) + else + out:u8(v) + end + end + if not rle then + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + for x = 0, w - 1 do + put(sample(x, y, c)) + end + end + end + return out:finish(), nil + end + local tables = out:tell() + out:fill(0, h * z * 8) + for c = 0, z - 1 do + for row = 0, h - 1 do + local y = h - 1 - row + local start = out:tell() + local x = 0 + while x < w do + -- a run of equal samples (>= 3) or literals up to the next run + local v = sample(x, y, c) + local run = 1 + while x + run < w and run < 127 and sample(x + run, y, c) == v do + run += 1 + end + if run >= 3 then + put(run) + put(v) + x += run + else + local lit = 0 + while x + lit < w and lit < 127 do + local a = sample(x + lit, y, c) + if x + lit + 2 < w and sample(x + lit + 1, y, c) == a and sample(x + lit + 2, y, c) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + put(0x80 + lit) + for k = 0, lit - 1 do + put(sample(x + k, y, c)) + end + x += lit + end + end + put(0) + local i = c * h + row + out:setU32be(tables + i * 4, start) + out:setU32be(tables + h * z * 4 + i * 4, out:tell() - start) + end + end + return out:finish(), nil +end + +return Sgi diff --git a/src/Formats/image/sunras/init.luau b/src/Formats/image/sunras/init.luau new file mode 100644 index 0000000..36ad35a --- /dev/null +++ b/src/Formats/image/sunras/init.luau @@ -0,0 +1,247 @@ +--!strict +-- image/sunras: Sun Raster (rasterfile(5), SunOS ; new code). Decode: 1-bit (0 = white without a colour +-- map), 8-bit (grey or the RGB colour map), 24-bit and 32-bit pixels in BGR / XBGR order (RT_STANDARD, RT_OLD, +-- RT_BYTE_ENCODED) or RGB / XRGB order (RT_FORMAT_RGB), the byte-encoded RLE (0x80 escapes), 16-bit row padding; in +-- 32-bit files the X byte is alpha when it is not all zero. Encode: rgba8 as 24-bit (opaque) or 32-bit (alpha in the +-- X byte) BGR, RT_BYTE_ENCODED (default) or RT_STANDARD. Not supported: RT_FORMAT_TIFF / RT_FORMAT_IFF (UNSUPPORTED), +-- raw colour maps (RMT_RAW is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Pixels = require("@formats/codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Sunras = { + name = "sunras", + category = "image", + extensions = { "ras", "sun", "rs", "im1", "im8", "im24", "im32" }, + mime = { "image/x-sun-raster", "image/x-cmu-raster" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + rle: boolean?, -- RT_BYTE_ENCODED (default true); false: RT_STANDARD +} + +local MAGIC = "\89\166\106\149" +local readu8, readu32 = buffer.readu8, buffer.readu32 +local function be32(b: buffer, o: number): number + return bit32.byteswap(readu32(b, o)) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Sunras.sniff(r: Bytes.Reader): number + return Sniff.magic(r, MAGIC) +end + +-- ------------------------------------------------------------------------------------------------ decode +function Sunras.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 32 then + return nil, Err.new(Err.TRUNCATED, "short header", o) + end + if buffer.readstring(b, o, 4) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a Sun raster", o) + end + local w, h, depth, typ, maptype, maplen = be32(b, o + 4), be32(b, o + 8), be32(b, o + 12), be32(b, o + 20), be32(b, o + 24), be32(b, o + 28) + if w == 0 or h == 0 or w > 65536 or h > 65536 then + return nil, Err.new(Err.CORRUPT, "bad size", o + 4) + end + if depth ~= 1 and depth ~= 8 and depth ~= 24 and depth ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, depth .. "-bit pixels", o + 12) + end + if typ == 4 or typ == 5 or typ > 5 and typ ~= 0xFFFF then + return nil, Err.new(Err.UNSUPPORTED, "raster type " .. typ, o + 20) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local p = o + 32 + if p + maplen > limit then + return nil, Err.new(Err.TRUNCATED, "colour map runs past the end", p) + end + local pal = buffer.create(1024) + local ncol = 0 + if maptype == 1 and maplen > 0 then + ncol = math.min(256, maplen // 3) + for i = 0, ncol - 1 do + buffer.writeu32(pal, i * 4, readu8(b, p + i) + readu8(b, p + ncol + i) * 256 + readu8(b, p + 2 * ncol + i) * 65536 + 0xFF000000) + end + elseif depth == 1 then + buffer.writeu32(pal, 0, 0xFFFFFFFF) + buffer.writeu32(pal, 4, 0xFF000000) + else + for i = 0, 255 do + buffer.writeu32(pal, i * 4, i * 0x10101 + 0xFF000000) + end + end + p += maplen + local stride = ((w * depth + 15) // 16) * 2 + local total = stride * h + local raw = buffer.create(total + 4) + local truncated = false + if typ == 2 then + local q = 0 + while q < total and p < limit do + local c = readu8(b, p) + p += 1 + if c ~= 0x80 then + buffer.writeu8(raw, q, c) + q += 1 + else + if p >= limit then + break + end + local n = readu8(b, p) + p += 1 + if n == 0 then + buffer.writeu8(raw, q, 0x80) + q += 1 + else + if p >= limit then + break + end + local cnt = math.min(n + 1, total - q) + buffer.fill(raw, q, readu8(b, p), cnt) + p += 1 + q += cnt + end + end + end + truncated = q < total + else + local n = math.min(total, limit - p) + buffer.copy(raw, 0, b, p, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if depth <= 8 then + Pixels.indexed(raw, 0, stride, depth, px, w, h, true, pal) + else + local rgb = typ == 3 + local bytes = depth // 8 + local alpha = false + if bytes == 4 then + for y = 0, h - 1 do + for x = 0, w - 1 do + if readu8(raw, y * stride + x * 4) ~= 0 then + alpha = true + end + end + end + end + for y = 0, h - 1 do + for x = 0, w - 1 do + local s = y * stride + x * bytes + local a = 255 + if bytes == 4 then + a = if alpha then readu8(raw, s) else 255 + s += 1 + end + local c0, c1, c2 = readu8(raw, s), readu8(raw, s + 1), readu8(raw, s + 2) + local rr, bb = if rgb then c0 else c2, if rgb then c2 else c0 + buffer.writeu32(px, (y * w + x) * 4, rr + c1 * 256 + bb * 65536 + a * 16777216) + end + end + end + if ncol > 0 then + local list: { { number } } = {} + for i = 0, ncol - 1 do + local v = buffer.readu32(pal, i * 4) + list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = list + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "sunras", bitDepth = depth, type = typ, rle = typ == 2 } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Sunras.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local px = img.pixels + local alpha = false + for i = 0, w * h - 1 do + if readu8(px, i * 4 + 3) < 255 then + alpha = true + break + end + end + local depth = if alpha then 32 else 24 + local bytes = depth // 8 + local stride = ((w * depth + 15) // 16) * 2 + local raw = buffer.create(stride * h) + for y = 0, h - 1 do + for x = 0, w - 1 do + local s, d = (y * w + x) * 4, y * stride + x * bytes + if alpha then + buffer.writeu8(raw, d, readu8(px, s + 3)) + d += 1 + end + buffer.writeu8(raw, d, readu8(px, s + 2)) + buffer.writeu8(raw, d + 1, readu8(px, s + 1)) + buffer.writeu8(raw, d + 2, readu8(px, s)) + end + end + local rle = not (opts and opts.rle == false) + local body = raw + if rle then + local wr = Bytes.writer(stride * h) + local i, n = 0, stride * h + while i < n do + local v = readu8(raw, i) + local run = 1 + while i + run < n and run < 256 and readu8(raw, i + run) == v do + run += 1 + end + if run >= 3 or v == 0x80 then + if run == 1 then + wr:u8(0x80) + wr:u8(0) + else + wr:u8(0x80) + wr:u8(run - 1) + wr:u8(v) + end + else + for _ = 1, run do + wr:u8(v) + end + end + i += run + end + body = wr:finish() + end + local out = Bytes.writer(32 + buffer.len(body)) + out:string(MAGIC) + out:u32be(w) + out:u32be(h) + out:u32be(depth) + out:u32be(buffer.len(body)) + out:u32be(if rle then 2 else 1) + out:u32be(0) + out:u32be(0) + out:bytes(body) + return out:finish(), nil +end + +return Sunras diff --git a/tests/image/sgi.luau b/tests/image/sgi.luau new file mode 100644 index 0000000..4890eca --- /dev/null +++ b/tests/image/sgi.luau @@ -0,0 +1,34 @@ +-- image/sgi tests: files from netpbm / ImageMagick / Pillow against ImageMagick's decode, our encoder's files read +-- by ImageMagick, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sgi.py. +local T = require("@tests/T") +local Sgi = require("@formats/image/sgi") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/sgi") + +local t = T.suite("sgi") +t:eq(Sgi.name, "sgi", "name") +t:check(Sgi.caps.decode and Sgi.caps.encode, "caps") + +t:note("%d files match ImageMagick", R.decodes(t, Sgi, Fx.cases)) +t:note("%d of our files read by ImageMagick", R.decodes(t, Sgi, Fx.ours)) +for _, c in Fx.cases do + R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + R.roundTrip(t, Sgi, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE") +end +do + local enc = Sgi.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer + t:eq(Sgi.sniff(Bytes.reader(enc)), 1, "sniff") + t:eq(Sgi.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other") + local _, e = Sgi.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20)))) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = Sgi.decode(Bytes.reader(enc), { maxPixels = 2 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + local _, e3 = Sgi.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "bad image") +end +t:fuzz("decode", function(b: buffer) + return Sgi.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tests/image/sunras.luau b/tests/image/sunras.luau new file mode 100644 index 0000000..4b336c7 --- /dev/null +++ b/tests/image/sunras.luau @@ -0,0 +1,42 @@ +-- image/sunras tests: files from netpbm / ImageMagick against ImageMagick's decode, our encoder's files read +-- by rasttopnm, round trips through every option, errors, the fuzz no-throw pass. Fixtures: tools/fixtures/sunras.py. +local T = require("@tests/T") +local Sunras = require("@formats/image/sunras") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/sunras") + +local t = T.suite("sunras") +t:eq(Sunras.name, "sunras", "name") +t:check(Sunras.caps.decode and Sunras.caps.encode, "caps") + +t:note("%d files match rasttopnm / ImageMagick", R.decodes(t, Sunras, Fx.cases)) +-- our files: rasttopnm reads the colours (it drops alpha) +for _, o in Fx.ours do + local img = Sunras.decode(Bytes.reader(buffer.fromstring(o.data))) :: any + local px = buffer.fromstring(buffer.tostring(img.pixels)) + for i = 0, o.w * o.h - 1 do + buffer.writeu8(px, i * 4 + 3, 255) + end + t:eq(R.maxDiff(px, buffer.fromstring(o.rgba), o.w * o.h), 0, o.name .. ": rasttopnm reads our file") +end +for _, c in Fx.cases do + R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + R.roundTrip(t, Sunras, R.image(c.w, c.h, c.rgba), { rle = false }, c.name .. " re-encoded without RLE") +end +do + local enc = Sunras.encode(R.image(2, 2, string.rep("\1\2\3\4", 4))) :: buffer + t:eq(Sunras.sniff(Bytes.reader(enc)), 1, "sniff") + t:eq(Sunras.sniff(Bytes.reader(buffer.fromstring("GIF89a"))), 0, "sniff other") + local _, e = Sunras.decode(Bytes.reader(buffer.fromstring(string.sub(buffer.tostring(enc), 1, 20)))) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = Sunras.decode(Bytes.reader(enc), { maxPixels = 2 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + local _, e3 = Sunras.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "bad image") +end +t:fuzz("decode", function(b: buffer) + return Sunras.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_simple.py b/tools/fixtures/_simple.py new file mode 100644 index 0000000..f9dea1d --- /dev/null +++ b/tools/fixtures/_simple.py @@ -0,0 +1,22 @@ +# Shared by the simple raster fixture generators: run our encoder (tools/fixtures/_tex_encode.luau -a ) and +# decode files with ImageMagick into rgba8 (through PAM). +import os, shutil, subprocess + + +def ours(ctx, which): + exe = shutil.which("luau") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"] + res = subprocess.run(cmd + ["tools/fixtures/_tex_encode.luau", "-a", which], cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if line.startswith("ours_") and "\t" in line: + n, hx = line.split("\t", 1) + files[n] = bytes.fromhex(hx.strip()) + return files + + +def magick_cases(R, w, names, fmt=None): + """ImageMagick decodes of the named files in the work dir -> { name: (w, h, rgba) }""" + pre = (fmt + ":") if fmt else "" + w.sh("imagemagick", ["magick %s%s -depth 8 -alpha on pam:%s.pam" % (pre, n, n) for n in names]) + return {n: R.pnm_rgba(w.read(n + ".pam")) for n in names} diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 12d8cf6..8e7887f 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -132,6 +132,10 @@ end local function simple(): any if which == "pcx" then return require("@formats/image/pcx") + elseif which == "sgi" then + return require("@formats/image/sgi") + elseif which == "sunras" then + return require("@formats/image/sunras") end return nil end diff --git a/tools/fixtures/sgi.py b/tools/fixtures/sgi.py new file mode 100644 index 0000000..956a4f7 --- /dev/null +++ b/tools/fixtures/sgi.py @@ -0,0 +1,39 @@ +# SGI fixtures (tools/fixtures.py): files from netpbm (pnmtosgi: RLE and verbatim, RGB and grey), ImageMagick (RGB, +# RGBA, 16-bit) and Pillow (L, RGB, RGBA), plus our encoder's files (tools/fixtures/_tex_encode.luau -a sgi); the +# reference is ImageMagick's decode of each file (16-bit within 1: it rounds where we keep the high byte). +# tests/gen/sgi.luau { cases = { { name, data, w, h, rgba, tol } }, ours = { ... } } +import importlib.util, os + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S = _load("_raster_ref"), _load("_simple") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sgi"] + + +def generate(ctx): + w = R.Work(ctx) + try: + w.png("photo.png", 37, 23, R.photo(37, 23)) + w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True)) + w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pnmtosgi -rle photo.ppm > nb_rle.sgi", "pnmtosgi -verbatim photo.ppm > nb_verbatim.sgi", + "ppmtopgm photo.ppm | pnmtosgi -rle > nb_grey.sgi"]) + w.sh("imagemagick", ["magick photo.png -alpha off im_rgb.sgi", "magick alpha.png im_rgba.sgi", "magick photo.png -alpha off -depth 16 im_rgb16.sgi", + "magick alpha.png -compress none im_rgba_verbatim.sgi"]) + ctx.python(["pillow"], ("from PIL import Image\nimport os\nos.chdir(%r)\nim=Image.open('alpha.png')\nim.save('pil_rgba.sgi')\n" + "im.convert('RGB').save('pil_rgb.sgi')\nim.convert('L').save('pil_l.sgi')\n") % w.dir) + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".sgi")) + mine = S.ours(ctx, "sgi") + for n, d in mine.items(): + w.write(n, d) + ref = S.magick_cases(R, w, names + sorted(mine)) + out = {"cases": [], "ours": []} + for n in names + sorted(mine): + ww, hh, rgba = ref[n] + out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba, "tol": 1 if "16" in n else 0}) + ctx.emit("sgi", out) + finally: + w.close() diff --git a/tools/fixtures/sunras.py b/tools/fixtures/sunras.py new file mode 100644 index 0000000..c67965f --- /dev/null +++ b/tools/fixtures/sunras.py @@ -0,0 +1,45 @@ +# Sun Raster fixtures (tools/fixtures.py): files from netpbm (pnmtorast: standard and byte-encoded, 1 / 8 / 24-bit) and +# ImageMagick (24-bit, 32-bit with alpha, 8-bit palette, 1-bit), plus our encoder's files (tools/fixtures/_tex_encode +# .luau -a sunras); the reference is rasttopnm for netpbm's and our files (RGB only) and ImageMagick's decode for the others. +# tests/gen/sunras.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } } +import importlib.util, os + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S = _load("_raster_ref"), _load("_simple") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/sunras"] + + +def generate(ctx): + w = R.Work(ctx) + try: + w.png("photo.png", 37, 23, R.photo(37, 23)) + w.png("pal.png", 31, 19, R.palette_image(31, 19, 40)) + w.png("alpha.png", 30, 17, R.photo(30, 17, 3, True)) + w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", + "pnmtorast -standard photo.ppm > nb_24_standard.ras", "pnmtorast -rle photo.ppm > nb_24_rle.ras", + "pnmtorast -rle pal.ppm > nb_8_rle.ras", "ppmtopgm photo.ppm | pnmtorast -standard > nb_grey.ras", + "ppmtopgm photo.ppm | pgmtopbm | pnmtorast -rle > nb_1.ras"]) + w.sh("imagemagick", ["magick photo.png -alpha off im_24.ras", "magick alpha.png im_32.ras", "magick pal.png -alpha off -type palette im_8.ras", + "magick photo.png -monochrome im_1.ras"]) + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".ras")) + mine = S.ours(ctx, "sunras") + for n, d in mine.items(): + w.write(n, d) + # netpbm's own files through rasttopnm (ImageMagick cuts the last row of nb_8_rle short), the rest through ImageMagick + nb = [n for n in names if n.startswith("nb_")] + sorted(mine) + w.sh("netpbm", ["rasttopnm %s > %s.pnm" % (n, n) for n in nb]) + ref = S.magick_cases(R, w, [n for n in names if not n.startswith("nb_")], "sun") + for n in nb: + ref[n] = R.pnm_rgba(w.read(n + ".pnm")) + out = {"cases": [], "ours": []} + for n in names + sorted(mine): + ww, hh, rgba = ref[n] + out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}) + ctx.emit("sunras", out) + finally: + w.close() From 36770d7a8bf7822e5d1c02385d6b6527edbdbbd9 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:53:04 -0500 Subject: [PATCH 39/54] ws-video2: docs/guide/video.md MPEG-2 section (tested snippet, tsBytes clip), formats table; docs/video.md layers --- docs/guide/video.md | 34 +++++++++++++++++++++++++++++----- docs/video.md | 2 ++ tools/fixtures/docs_av.py | 10 +++++++--- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/docs/guide/video.md b/docs/guide/video.md index cbabe27..996da6f 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -2,7 +2,7 @@ A video file opens as a **VideoDecoder**: frames come out one at a time, as Images, with their presentation time. Underneath sits a **Demuxer**: the container's tracks and their compressed packets. Video tracks decode through a -codec registry (H.264, VP8, MPEG-1, Motion-JPEG, raw), and the first audio track opens as an audio +codec registry (H.264, VP8, MPEG-1, MPEG-2, Motion-JPEG, raw), and the first audio track opens as an audio [Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the internals and how to add a codec. @@ -263,6 +263,30 @@ assert(C.register({ assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid")) ``` +## MPEG-2 (DVD, broadcast TS) + +MPEG-1 and MPEG-2 video decode through one decoder (`codecs/video/Mpeg2`; `codecs/video/Mpeg1` is the same module): +Main profile, progressive and interlaced, frame and field pictures, 4:2:0 and 4:2:2. It reads `.mpg` / `.vob` +program streams, transport streams (stream type 0x02, or a private type such as 0x80 carrying a video PES), raw +`.m2v` elementary streams, and MPEG-2 tracks of MP4 / MOV, Matroska and AVI. The output equals `ffmpeg -idct int` +sample for sample (the integer IDCT of the IJG; ffmpeg's default IDCT differs from it by at most a level or two). + +```luau +local v = assert(F.video.open(tsBytes)) -- MPEG-TS: interlaced MPEG-2 + MP2 +assert(v.format == "mpegts" and v.codec == "mpeg2") +local f = assert(v:nextFrame()) +local src = f.image.meta.source +assert(src.format == "mpeg2" and src.interlaced and src.topFieldFirst) +assert(f.image.format == "yuv420p") -- both fields woven: the top field on the even lines +local a = assert(v.audio, tostring(v.audioError)) -- the MP2 track through the audio hook +assert(a.sampleRate == 44100) +``` + +Interlaced frames come out woven, as they were coded: deinterlace them yourself if needed (`src.interlaced`, +`src.topFieldFirst`). 4:2:2 streams (studio / XDCAM) are converted to 4:2:0 for the frame Image, averaging chroma +lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop +core (`tools/bench.luau`): real time with room to spare on a PC, less so on phones. + ## Playing in a game loop Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes @@ -306,10 +330,10 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels) | Format | Read | Write | Video codecs (decode) | |---|---|---|---| -| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1 | -| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | -| avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | -| mpegts, mpegps | yes | - | MPEG-1, H.264 | +| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 | +| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) | +| mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 | | y4m | yes | yes | raw | | h264 (Annex B) | yes | yes (copy) | H.264 | | gif, png (APNG), webp | as video | as video via the image writers | frames | diff --git a/docs/video.md b/docs/video.md index 184ca45..8f5b6f5 100644 --- a/docs/video.md +++ b/docs/video.md @@ -28,6 +28,8 @@ F.convert(gif, "avi") -- animated images become videos (un | `codecs/video/Video/Source` | what writers write: copied packets or frames encoded by a registry encoder, PCM from the audio | | `codecs/image/Yuv` | yuv420p <-> rgba8 (BT.601 / 709, limited / full range from `image.meta.yuv`), range remap | | `codecs/image/Vp8`, `Jpeg`, `Mpeg1` | the decoders (and the JPEG encoder) | +| `codecs/video/Mpeg2` (`Mpeg1` is the same module), `H264` | MPEG-1 / MPEG-2 and H.264 video decoders | +| `codecs/video/Dsp` | 8x8 IDCT (bit-exact with `ffmpeg -idct int`) and half-pel motion compensation for the MPEG-style codecs | | `video/` | the formats: demux into `containers/Demux`, `open` = `Video.open(demuxer, opts)`, `encode` via Source | Audio tracks reach the audio formats through the api hook `opts.openAudio(demuxer, track)` (a format never requires diff --git a/tools/fixtures/docs_av.py b/tools/fixtures/docs_av.py index 8019408..9beb3a2 100644 --- a/tools/fixtures/docs_av.py +++ b/tools/fixtures/docs_av.py @@ -1,8 +1,8 @@ # Docs inputs for the audio / music / video / subtitle guide pages (tools/fixtures.py; tools/docs_check.py reads them): # tiny ffmpeg test clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): MP4 (H.264 + AAC), AVI (MJPEG + -# PCM), WebM (VP8 + Vorbis); a MIDI file written here (SMF 1: a tempo track and a melody), the SoundFont of -# tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py (song_basic), and SRT / WebVTT / -# ASS subtitles. +# PCM), WebM (VP8 + Vorbis), MPEG-TS (interlaced MPEG-2 + MP2); a MIDI file written here (SMF 1: a tempo track and a +# melody), the SoundFont of tools/fixtures/sf2.py (build_sf2), a ProTracker module from tools/fixtures/mod.py +# (song_basic), and SRT / WebVTT / ASS subtitles. # tests/gen/docs_av.luau { files = { [name] = bytes }, vars = { mp4Bytes = "clip.mp4", ... } } import importlib.util, os, struct, tempfile @@ -91,6 +91,9 @@ def generate(ctx): "-c:a", "aac", "-b:a", "64k"]), ("clip.avi", ["-c:v", "mjpeg", "-q:v", "4", "-pix_fmt", "yuvj420p", "-c:a", "pcm_s16le"]), ("clip.webm", ["-c:v", "libvpx", "-b:v", "200k", "-g", "5", "-c:a", "libvorbis", "-q:a", "2"]), + ("clip.ts", ["-c:v", "mpeg2video", "-b:v", "300k", "-g", "5", "-bf", "2", "-vf", "setfield=tff", + "-flags", "+ilme+ildct", + "-c:a", "mp2", "-b:a", "64k"]), ): out = os.path.join(d, name) ctx.nix("ffmpeg", ["ffmpeg", "-v", "error", "-y"] + src + codec + ["-shortest", out]) @@ -107,6 +110,7 @@ def generate(ctx): "mp4Bytes": "clip.mp4", "aviBytes": "clip.avi", "webmBytes": "clip.webm", + "tsBytes": "clip.ts", "midiBytes": "tune.mid", "sf2Bytes": "bank.sf2", "modBytes": "song.mod", From 48c0366528e67854d8b7c1e6549513f6bc5483e4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:03 -0500 Subject: [PATCH 40/54] ws-video2: mpeg2 test: field pictures written in random pieces --- tests/codecs/mpeg2.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/codecs/mpeg2.luau b/tests/codecs/mpeg2.luau index cd88a82..b111d68 100644 --- a/tests/codecs/mpeg2.luau +++ b/tests/codecs/mpeg2.luau @@ -165,7 +165,7 @@ do end -- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit -for _, idx in { 2, 9 } do +for _, idx in { 2, 9, 12 } do local fx = STREAMS[idx] local file = b64(fx.file) local want = decodeUnits(fx, file) From f3df37012e7a3392a4f5d47420d2eb85b5fbbf01 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:21 -0500 Subject: [PATCH 41/54] ws-3d3: model/3ds/Write: drop an unused local --- src/Formats/model/3ds/Write.luau | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Formats/model/3ds/Write.luau b/src/Formats/model/3ds/Write.luau index c094afd..8718a7b 100644 --- a/src/Formats/model/3ds/Write.luau +++ b/src/Formats/model/3ds/Write.luau @@ -670,7 +670,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) local pk = if p ~= 0 then kfOf[p] else nil local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light]) local dist = 100 - local x3ds = n.extras and n.extras["3ds"] local function placeCamLight(kind: number, objName: string, tgtChunk: number?) local pos, tgt, roll = aim(W[i], dist) local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } } @@ -751,7 +750,6 @@ function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?) end return idx end - local _ = x3ds if n.mesh == nil and camOrLight then camLight(true) continue From 76128bf381bed4161e6159f0d23130db9433fbc8 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:56 -0500 Subject: [PATCH 42/54] ws-3d3: codecs/model/Vrml (VRML97 / X3D classic parser, X3D XML adapter, node graph -> Scene builder, writer) + model/vrml (.wrl read / write) + model/x3d (.x3d / .x3dv read / write; .x3db UNSUPPORTED); tests against VTK and assimp --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 24 + src/Formats/codecs/model/Vrml/Build.luau | 590 +++++++++++++++ src/Formats/codecs/model/Vrml/Fields.luau | 168 +++++ src/Formats/codecs/model/Vrml/Geometry.luau | 770 ++++++++++++++++++++ src/Formats/codecs/model/Vrml/Parse.luau | 536 ++++++++++++++ src/Formats/codecs/model/Vrml/Write.luau | 750 +++++++++++++++++++ src/Formats/codecs/model/Vrml/Xml.luau | 238 ++++++ src/Formats/codecs/model/Vrml/init.luau | 160 ++++ src/Formats/model/vrml/init.luau | 77 ++ src/Formats/model/x3d/init.luau | 85 +++ tests/codecs/vrml.luau | 148 ++++ tests/model/_vrml_common.luau | 109 +++ tests/model/pmx.luau | 2 +- tests/model/vrml.luau | 410 +++++++++++ tests/model/x3d.luau | 308 ++++++++ tools/fixtures/_vrml_encode.luau | 54 ++ tools/fixtures/_vrml_ref.py | 241 ++++++ tools/fixtures/vrml.py | 99 +++ tools/fixtures/x3d.py | 135 ++++ 20 files changed, 4906 insertions(+), 1 deletion(-) create mode 100644 src/Formats/codecs/model/Vrml/Build.luau create mode 100644 src/Formats/codecs/model/Vrml/Fields.luau create mode 100644 src/Formats/codecs/model/Vrml/Geometry.luau create mode 100644 src/Formats/codecs/model/Vrml/Parse.luau create mode 100644 src/Formats/codecs/model/Vrml/Write.luau create mode 100644 src/Formats/codecs/model/Vrml/Xml.luau create mode 100644 src/Formats/codecs/model/Vrml/init.luau create mode 100644 src/Formats/model/vrml/init.luau create mode 100644 src/Formats/model/x3d/init.luau create mode 100644 tests/codecs/vrml.luau create mode 100644 tests/model/_vrml_common.luau create mode 100644 tests/model/vrml.luau create mode 100644 tests/model/x3d.luau create mode 100644 tools/fixtures/_vrml_encode.luau create mode 100644 tools/fixtures/_vrml_ref.py create mode 100644 tools/fixtures/vrml.py create mode 100644 tools/fixtures/x3d.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f3846c1..83ae02a 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -45,6 +45,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| model | vrml | .wrl .wrz .vrml | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true | `tests/model/vrml.luau` | +| model | x3d | .x3d .x3dv .x3dz .x3dvz .x3db | yes | yes | materials: true, polygons: true, animation: true, cameras: true, lights: true, lines: true, points: true, xml: true, classic: true | `tests/model/x3d.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | @@ -127,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index a414daf..be89cbf 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -494,6 +494,30 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "vrml", + category = "model", + path = "model/vrml", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, + load = function() + return require("@formats/model/vrml") + end, + }, + { + name = "x3d", + category = "model", + path = "model/x3d", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, + load = function() + return require("@formats/model/x3d") + end, + }, { name = "step", category = "cad", diff --git a/src/Formats/codecs/model/Vrml/Build.luau b/src/Formats/codecs/model/Vrml/Build.luau new file mode 100644 index 0000000..8ddc054 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Build.luau @@ -0,0 +1,590 @@ +--!strict +-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene. +-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation, +-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through +-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when +-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children. +-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial +-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture +-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform: +-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight / +-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a +-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in +-- meta.source.skipped. Never throws: bad data returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Fields = require("@formats/codecs/model/Vrml/Fields") +local Geometry = require("@formats/codecs/model/Vrml/Geometry") + +local Build = {} + +local S = Types.Scene +local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes +local deg = math.deg + +export type Options = Geometry.Options & { + fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files + load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph + format: string?, -- meta.source.format + maxInline: number?, -- Inline nesting (default 8) +} + +local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true } +local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true } +local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" } +-- nodes with nothing to show (not counted as skipped) +local QUIET = { + WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true, + PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true, + CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true, + VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true, + AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true, + MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true, + BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true, + StringSensor = true, LoadSensor = true, +} +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" } + +local function quat(r: { number }): { number } + return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4])) +end +local function qmul(a: { number }, b: { number }): { number } + return { + a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2], + a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1], + a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4], + a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], + } +end +local function qrot(q: { number }, v: { number }): { number } + local m = Mat4.fromQuat(q) + local x, y, z = Mat4.point(m, v[1], v[2], v[3]) + return { x, y, z } +end +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +local function isIdentityQ(q: { number }): boolean + return q[1] == 0 and q[2] == 0 and q[3] == 0 +end +-- the rotation taking unit vector a onto b +local function between(a: { number }, b: { number }): { number } + local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3]) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local bx, by, bz = b[1] / l, b[2] / l, b[3] / l + local d = a[1] * bx + a[2] * by + a[3] * bz + if d < -0.999999 then + -- opposite: half a turn about any perpendicular axis + return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 } + end + local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx + local w = 1 + d + local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w) + return { cx / n, cy / n, cz / n, w / n } +end + +type Ctx = { + scene: Types.Scene, + opts: Options, + meshes: { [any]: any }, + materials: { [any]: any }, + textures: { [any]: number }, + instances: { [any]: { { node: number, center: { number }, so: { number } } } }, + skipped: { [string]: number }, + depth: number, + inline: number, + failure: string?, +} + +local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number + local nodes_ = ctx.scene.nodes + table.insert(nodes_, n) + local i = #nodes_ + if parent then + table.insert(nodes_[parent].children, i) + else + table.insert(ctx.scene.roots, i) + end + return i +end + +-- ------------------------------------------------------------------------------------------------ materials +local function texture(ctx: Ctx, t: any): number? + if not t then + return nil + end + if t.type == "MultiTexture" then + return texture(ctx, nodes(t, "texture")[1]) + end + local cached = ctx.textures[t] + if cached then + return cached + end + local tex: Types.Texture = { name = t.def } + if t.type == "ImageTexture" or t.type == "MovieTexture" then + local urls = strs(t, "url") + local fetch = ctx.opts.fetch + for _, u in urls do + local clean = string.match(u, "^([^#?]*)") or u + if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then + tex.uri = clean + end + local data = fetch and fetch(clean) + if data then + tex.uri, tex.data = clean, data + break + end + end + tex.uri = tex.uri or urls[1] + local ext = tex.uri and string.match(tex.uri, "%.(%w+)$") + tex.mime = if ext then MIME[string.lower(ext)] else nil + elseif t.type == "PixelTexture" then + -- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first) + local v = nums(t, "image") or {} + local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0) + if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then + local img = Types.Image.new(w, h) + for i = 0, w * h - 1 do + local px = math.floor(v[4 + i]) % 2 ^ (8 * c) + local b = table.create(4, 0) + for k = c, 1, -1 do + b[k] = px % 256 + px //= 256 + end + local r, g, bl, a + if c <= 2 then + r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255 + else + r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255 + end + -- the image's first row is the bottom one + local row = h - 1 - i // w + local o = (row * w + i % w) * 4 + buffer.writeu8(img.pixels, o, r) + buffer.writeu8(img.pixels, o + 1, g) + buffer.writeu8(img.pixels, o + 2, bl) + buffer.writeu8(img.pixels, o + 3, a) + end + tex.image = img + end + else + ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1 + return nil + end + local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true) + if not rs or not rt then + tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" } + end + table.insert(ctx.scene.textures, tex) + ctx.textures[t] = #ctx.scene.textures + return #ctx.scene.textures +end + +local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef? + local i = texture(ctx, t) + if not i then + return nil + end + local ref: Types.TextureRef = { texture = i } + if xf and xf.type == "TextureTransform" then + local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then + ref.transform = { offset = tr, scale = sc, rotation = rot } + end + end + return ref +end + +local function material(ctx: Ctx, app: any, solid: boolean): number? + if not app and solid then + return nil + end + local key = app or "default" + local cache = ctx.materials[key] + if type(cache) ~= "table" then + cache = {} + ctx.materials[key] = cache + end + local hit = (cache :: any)[solid] + if hit then + return hit + end + local m = S.material(app and app.def) + m.metallic = 0 + local x: { [string]: any } = {} + local mat = app and node(app, "material") + local tex = app and node(app, "texture") + local xf = app and node(app, "textureTransform") + if mat and mat.type == "TwoSidedMaterial" then + m.doubleSided = true + x.twoSided = true + end + if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then + local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 }) + local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2) + m.name = mat.def or m.name + m.baseColor = { d[1], d[2], d[3], 1 - tr } + m.emissive = e + m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1) + x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb + if tr > 0 then + m.alphaMode = "blend" + end + -- X3D 4 texture fields + local dt = node(mat, "diffuseTexture") + if dt then + m.baseColorTexture = textureRef(ctx, dt, nil) + end + local nt = node(mat, "normalTexture") + if nt then + m.normalTexture = textureRef(ctx, nt, nil) + end + elseif mat and mat.type == "PhysicalMaterial" then + local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 }) + local tr = num(mat, "transparency", 0) + m.name = mat.def or m.name + m.baseColor = { b[1], b[2], b[3], 1 - tr } + m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1) + if tr > 0 then + m.alphaMode = "blend" + end + local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" } + for field, slot in slots do + local t = node(mat, field) + if t then + (m :: any)[slot] = textureRef(ctx, t, nil) + end + end + elseif mat and mat.type == "UnlitMaterial" then + local e = vec(mat, "emissiveColor", { 1, 1, 1 }) + m.name = mat.def or m.name + m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) } + m.extensions = { KHR_materials_unlit = {} } + else + -- no material: unlit white (the specifications' default) + m.extensions = { KHR_materials_unlit = {} } + end + if tex and not m.baseColorTexture then + m.baseColorTexture = textureRef(ctx, tex, xf) + if m.baseColorTexture and xf then + x.textureCenter = vec(xf, "center", { 0, 0 }) + end + end + if not solid then + m.doubleSided = true + end + m.extras = { vrml = x } + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + ;(cache :: any)[solid] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ nodes +local walk: (ctx: Ctx, n: any, parent: number?) -> () + +local function shape(ctx: Ctx, n: any, parent: number?) + local geo = node(n, "geometry") + if not geo then + return + end + local mi = ctx.meshes[n] + if mi == nil then + local prim, solidOrErr = Geometry.primitive(geo, ctx.opts) + if not prim then + if solidOrErr then + ctx.failure = ctx.failure or solidOrErr + else + ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1 + end + ctx.meshes[n] = false :: any + return + end + local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count + if count == 0 then + -- nothing to draw (no valid faces / points) + ctx.meshes[n] = false + return + end + prim.material = material(ctx, node(n, "appearance"), solidOrErr == true) + table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } }) + mi = #ctx.scene.meshes + ctx.meshes[n] = mi + elseif mi == false then + return + end + addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent) +end + +local function viewpoint(ctx: Ctx, n: any, parent: number?) + local cam: any + if n.type == "OrthoViewpoint" then + local f = vec(n, "fieldOfView", { -1, -1, 1, 1 }) + cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 } + else + cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 } + end + cam.name = n.def or str(n, "description") + table.insert(ctx.scene.cameras, cam) + local o = vec(n, "orientation", { 0, 0, 1, 0 }) + local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) } + if o[4] ~= 0 then + nd.rotation = quat(o) + end + addNode(ctx, nd, parent) +end + +local function light(ctx: Ctx, n: any, parent: number?) + local t = n.type + local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) } + local nd: Types.Node = { name = n.def, children = {} } + local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") } + if t == "DirectionalLight" then + l.type = "directional" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + else + nd.translation = vec(n, "location", { 0, 0, 0 }) + l.range = num(n, "radius", 100) + x.attenuation = vec(n, "attenuation", { 1, 0, 0 }) + if t == "SpotLight" then + l.type = "spot" + nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 })) + local cut = num(n, "cutOffAngle", 0.785398) + l.outerCone = cut + l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut) + end + end + ;(l :: any).extras = { vrml = x } + table.insert(ctx.scene.lights, l) + nd.light = #ctx.scene.lights + addNode(ctx, nd, parent) +end + +local function children(ctx: Ctx, n: any, parent: number?) + if n.type == "Switch" then + local which = math.floor(num(n, "whichChoice", -1)) + local list = nodes(n, "choice") + if #list == 0 then + list = nodes(n, "children") + end + local c = list[which + 1] + if which >= 0 and c then + walk(ctx, c, parent) + end + return + elseif n.type == "LOD" then + local list = nodes(n, "level") + if #list == 0 then + list = nodes(n, "children") + end + if list[1] then + walk(ctx, list[1], parent) + end + return + end + for _, f in CHILDREN do + for _, c in nodes(n, f) do + walk(ctx, c, parent) + end + end +end + +local function transform(ctx: Ctx, n: any, parent: number?) + local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 }) + local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 }) + local qr, qs = quat(r), quat(so) + local outer: Types.Node = { name = n.def, children = {} } + local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] } + if not isZero(tt) then + outer.translation = tt + end + local q = if isIdentityQ(qs) then qr else qmul(qr, qs) + if not isIdentityQ(q) then + outer.rotation = q + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + outer.scale = s + end + local oi = addNode(ctx, outer, parent) + local list = ctx.instances[n] + if not list then + list = {} + ctx.instances[n] = list + end + table.insert(list, { node = oi, center = c, so = qs }) + local holder = oi + if not isZero(c) or not isIdentityQ(qs) then + local inv = { -qs[1], -qs[2], -qs[3], qs[4] } + local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) } + if not isIdentityQ(inv) then + inner.rotation = inv + end + holder = addNode(ctx, inner, oi) + end + children(ctx, n, holder) +end + +local function inline(ctx: Ctx, n: any, parent: number?) + local fetch, load = ctx.opts.fetch, ctx.opts.load + if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 + return + end + for _, u in strs(n, "url") do + local data = fetch(string.match(u, "^([^#?]*)") or u) + if data then + local g = load(data) + if g then + local holder = addNode(ctx, { name = n.def, children = {} }, parent) + ctx.inline += 1 + for _, root in g.roots do + walk(ctx, root, holder) + end + ctx.inline -= 1 + return + end + end + end + ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1 +end + +function walk(ctx: Ctx, n: any, parent: number?) + if ctx.failure or type(n) ~= "table" then + return + end + ctx.depth += 1 + if ctx.depth > 200 then + ctx.failure = "limit: scene nested deeper than 200" + return + end + local t = n.type + if TRANSFORM[t] then + transform(ctx, n, parent) + elseif GROUP[t] then + local holder = parent + if n.def or parent == nil then + holder = addNode(ctx, { name = n.def, children = {} }, parent) + end + children(ctx, n, holder) + elseif t == "Shape" then + shape(ctx, n, parent) + elseif t == "CADFace" then + for _, s in nodes(n, "shape") do + walk(ctx, s, parent) + end + elseif t == "Viewpoint" or t == "OrthoViewpoint" then + viewpoint(ctx, n, parent) + elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then + light(ctx, n, parent) + elseif t == "Inline" then + inline(ctx, n, parent) + elseif t == "WorldInfo" then + local src = ctx.scene.meta.source :: any + src.title = str(n, "title") + local info = strs(n, "info") + src.info = if #info > 0 then info else nil + elseif not QUIET[t] then + ctx.skipped[t] = (ctx.skipped[t] or 0) + 1 + end + ctx.depth -= 1 +end + +-- ------------------------------------------------------------------------------------------------ animation +local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" } + +local function animations(ctx: Ctx, routes: { any }) + -- interpolator -> its TimeSensor + local timer: { [any]: any } = {} + for _, r in routes do + if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then + timer[r.to] = r.from + end + end + local anims: { [any]: Types.Animation } = {} + local order: { any } = {} + for _, r in routes do + local path = TARGET[r.toField] + local it = r.from + local inst = ctx.instances[r.to] + if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then + continue + end + if (path == "rotation") ~= (it.type == "OrientationInterpolator") then + continue + end + local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {} + local comps = if path == "rotation" then 4 else 3 + local n = math.min(#key, #kv // comps) + if n == 0 then + continue + end + local ts = timer[it] + local cycle = if ts then num(ts, "cycleInterval", 1) else 1 + local input = S.accessor(nil, "f32", 1, n) + for i = 0, n - 1 do + buffer.writef32(input.data, i * 4, key[i + 1] * cycle) + end + local id = ts or "routes" + local anim = anims[id] + if not anim then + anim = { name = if ts then ts.def else nil, channels = {} } + anims[id] = anim + table.insert(order, id) + end + for _, at in inst do + local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n) + local prev: { number }? = nil + for i = 0, n - 1 do + local v: { number } + if path == "rotation" then + v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] }) + if not isIdentityQ(at.so) then + v = qmul(v, at.so) + end + if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then + v = { -v[1], -v[2], -v[3], -v[4] } + end + prev = v + elseif path == "translation" then + v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] } + else + v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] } + end + for c = 1, #v do + buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c]) + end + end + table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any }) + end + end + for _, id in order do + table.insert(ctx.scene.animations, anims[id]) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(graph: any, opts: Options): (Types.Scene?, string?) + local scene = S.new() + scene.meta.up = "y" + local units = graph.units or {} + scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1 + local h = graph.header or {} + local skipped: { [string]: number } = {} + scene.meta.source = { + format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d, + xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped, + } + local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil } + for _, n in graph.roots do + walk(ctx, n, nil) + end + if ctx.failure then + return nil, ctx.failure + end + animations(ctx, graph.routes or {}) + return scene, nil +end + +return Build diff --git a/src/Formats/codecs/model/Vrml/Fields.luau b/src/Formats/codecs/model/Vrml/Fields.luau new file mode 100644 index 0000000..c9ec1e2 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Fields.luau @@ -0,0 +1,168 @@ +--!strict +-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding +-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here +-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans +-- true / false). Never throws. +local Fields = {} + +local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte + +-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted +local function mfString(s: string): { string } + local out = {} + local p = find(s, "[^%s,]") + if not p or byte(s, p) ~= 34 then + return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {} + end + local n = #s + while p and p <= n do + if byte(s, p) ~= 34 then + break + end + local q = p + 1 + local parts = {} + while true do + local e = find(s, '["\\]', q) + if not e then + table.insert(parts, sub(s, q)) + table.insert(out, table.concat(parts)) + return out + end + table.insert(parts, sub(s, q, e - 1)) + if byte(s, e) == 92 then + table.insert(parts, sub(s, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + break + end + end + table.insert(out, table.concat(parts)) + p = find(s, "[^%s,]", p) + end + return out +end + +-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent +function Fields.nums(node: any, name: string): { number }? + local v = node.fields[name] + if v == nil then + return nil + end + if type(v) == "string" then + local out = {} + for w in gmatch(v, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "true" or w == "TRUE" then + table.insert(out, 1) + elseif w == "false" or w == "FALSE" then + table.insert(out, 0) + end + end + node.fields[name] = out + return out + end + if type(v) ~= "table" then + return nil + end + local ok = true + for _, x in v do + if type(x) ~= "number" then + ok = false + break + end + end + if ok then + return v + end + local out = {} + for _, x in v do + if type(x) == "number" then + table.insert(out, x) + elseif type(x) == "boolean" then + table.insert(out, if x then 1 else 0) + end + end + return out +end + +function Fields.num(node: any, name: string, default: number): number + local v = Fields.nums(node, name) + return if v and type(v[1]) == "number" then v[1] else default +end + +-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter) +function Fields.vec(node: any, name: string, default: { number }): { number } + local v = Fields.nums(node, name) + if not v or #v < #default then + return default + end + local out: { number } = {} + for i = 1, #default do + out[i] = v[i] + end + return out +end + +function Fields.bool(node: any, name: string, default: boolean): boolean + local v = node.fields[name] + if type(v) == "string" then + local w = string.lower(string.match(v, "^%s*(%S*)") :: string) + return if w == "true" then true elseif w == "false" then false else default + end + if type(v) == "table" and type(v[1]) == "boolean" then + return v[1] + end + return default +end + +function Fields.strs(node: any, name: string): { string } + local v = node.fields[name] + if type(v) == "string" then + local out = mfString(v) + node.fields[name] = out + return out + end + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.str(node: any, name: string, default: string?): string? + local v = node.fields[name] + if type(v) == "string" then + return v + end + if type(v) == "table" and type(v[1]) == "string" then + return v[1] + end + return default +end + +-- nodes(node, name) -> the nodes of an SFNode / MFNode field +function Fields.nodes(node: any, name: string): { any } + local v = node.fields[name] + local out = {} + if type(v) == "table" then + for _, x in v do + if type(x) == "table" and type(x.type) == "string" then + table.insert(out, x) + end + end + end + return out +end + +function Fields.node(node: any, name: string): any + return Fields.nodes(node, name)[1] +end + +return Fields diff --git a/src/Formats/codecs/model/Vrml/Geometry.luau b/src/Formats/codecs/model/Vrml/Geometry.luau new file mode 100644 index 0000000..306562d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Geometry.luau @@ -0,0 +1,770 @@ +--!strict +-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no +-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face +-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets +-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet, +-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale, +-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone, +-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to +-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data. +local Types = require("@formats/Types") +local Fields = require("@formats/codecs/model/Vrml/Fields") + +local Geometry = {} + +local S = Types.Scene +local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node +local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi + +export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? } + +local function f32(list: { number }, comps: number, count: number): Types.Accessor + local a = S.accessor(nil, "f32", comps, count) + local d = a.data + for i = 1, math.min(#list, comps * count) do + buffer.writef32(d, (i - 1) * 4, list[i]) + end + return a +end + +local function u32(list: { number }): Types.Accessor + local a = S.accessor(nil, "u32", 1, #list) + for i, v in list do + buffer.writeu32(a.data, (i - 1) * 4, v) + end + return a +end + +-- the colour node's values and component count (Color: 3, ColorRGBA: 4) +local function colors(n: any): ({ number }?, number) + local c = node(n, "color") + if not c then + return nil, 3 + end + local comps = if c.type == "ColorRGBA" then 4 else 3 + return nums(c, "color") or {}, comps +end + +local function points(n: any, field: string, sub: string): { number }? + local c = node(n, field) + return if c then nums(c, sub) or {} else nil +end + +-- ------------------------------------------------------------------------------------------------ polygon meshes +-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil: +-- the coordinate index) or per-face indices. +type PolyIn = { + P: { number }, -- coordinates, 3 per point + corners: { number }, -- coordinate index per corner, face after face + sizes: { number }, -- corners per face + N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity) + C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?, + T: { number }?, tIdx: { number }?, + ccw: boolean, +} + +local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?) + local P, corners, sizes = m.P, m.corners, m.sizes + local np = #P // 3 + local N, C, T = m.N, m.C, m.T + local cc = m.cComps or 3 + -- the attribute index of corner k (1-based) in face f (1-based) + local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number + if perFace then + return if list and #list > 0 then (list[f] or 0) else f - 1 + end + return if list and #list > 0 then (list[k] or c) else c + end + local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0) + local vkey: { [string]: number } = {} + local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices + local out: { number } = {} + local outSizes: { number } = {} + local k = 0 + for f, size in sizes do + local face: { number } = {} + local valid = size >= 3 + for q = 1, size do + k += 1 + local c = corners[k] + if c == nil or c < 0 or c >= np then + valid = false + end + face[q] = k + end + if valid then + local verts: { number } = {} + for q, kk in face do + local c = corners[kk] + if simple then + verts[q] = c + else + local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1 + local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1 + local ti = if T then idx(m.tIdx, false, f, kk, c) else -1 + local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti + local v = vkey[key] + if not v then + v = #vsrc + vsrc[v + 1] = { c, ni, ci, ti } + vkey[key] = v + if v >= maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + end + verts[q] = v + end + end + if not m.ccw then + for a = 2, (size + 1) // 2 do + verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a] + end + end + if o.triangulate == false then + table.insert(outSizes, size) + for _, v in verts do + table.insert(out, v) + end + else + for a = 2, size - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[a]) + table.insert(out, verts[a + 1]) + end + end + end + end + local nv = if simple then np else #vsrc + if nv > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local flipV = o.flipV ~= false + local pos = S.accessor(nil, "f32", 3, nv) + local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil + local col = if C then S.accessor(nil, "f32", cc, nv) else nil + local tex = if T then S.accessor(nil, "f32", 2, nv) else nil + local wf = buffer.writef32 + for v = 0, nv - 1 do + local s = if simple then nil else vsrc[v + 1] + local c = if s then s[1] else v + for q = 0, 2 do + wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0) + end + if nrm and N then + local ni = if s then s[2] else v + for q = 0, 2 do + wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0) + end + end + if col and C then + local ci = if s then s[3] else v + for q = 0, cc - 1 do + wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1) + end + end + if tex and T then + local ti = if s then s[4] else v + local tt = T[ti * 2 + 2] or 0 + wf(tex.data, v * 8, T[ti * 2 + 1] or 0) + wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex + local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" } + if o.triangulate == false then + prim.mode = "polygons" + prim.faces = u32(outSizes) + end + return prim +end + +-- split a -1 separated index list into corners + sizes +local function split(list: { number }): ({ number }, { number }) + local corners, sizes = {}, {} + local run = 0 + for _, x in list do + if x < 0 then + if run > 0 then + table.insert(sizes, run) + end + run = 0 + else + table.insert(corners, x) + run += 1 + end + end + if run > 0 then + table.insert(sizes, run) + end + return corners, sizes +end + +-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners) +local function cornerList(list: { number }?): { number }? + if not list or #list == 0 then + return nil + end + local out = {} + for _, x in list do + if x >= 0 then + table.insert(out, x) + end + end + return out +end + +local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local P = points(n, "coord", "point") or {} + local corners, sizes = split(nums(n, "coordIndex") or {}) + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"), + C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"), + T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil, + tIdx = cornerList(nums(n, "texCoordIndex")), + } + return polyMesh(m, o, maxV) +end + +-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts +local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local t = n.type + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local index = nums(n, "index") + local seq: { number } + if string.sub(t, 1, 7) == "Indexed" then + seq = index or {} + else + seq = {} + for i = 0, np - 1 do + seq[i + 1] = i + end + end + local corners, sizes = {}, {} + local function tri(a: number, b: number, c: number) + table.insert(corners, a) + table.insert(corners, b) + table.insert(corners, c) + table.insert(sizes, 3) + end + -- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips) + local function runs(): { { number } } + local out = {} + local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount") + if string.sub(t, 1, 7) == "Indexed" or not counts then + local cur = {} + for _, x in seq do + if x < 0 then + table.insert(out, cur) + cur = {} + else + table.insert(cur, x) + end + end + table.insert(out, cur) + else + local at = 1 + for _, c in counts do + local cur = {} + for q = 0, c - 1 do + cur[q + 1] = seq[at + q] + end + at += c + table.insert(out, cur) + end + end + return out + end + if t == "IndexedTriangleSet" or t == "TriangleSet" then + for i = 1, #seq - 2, 3 do + tri(seq[i], seq[i + 1], seq[i + 2]) + end + elseif t == "IndexedQuadSet" or t == "QuadSet" then + for i = 1, #seq - 3, 4 do + for q = 0, 3 do + table.insert(corners, seq[i + q]) + end + table.insert(sizes, 4) + end + elseif string.find(t, "Fan", 1, true) then + for _, r in runs() do + for i = 2, #r - 1 do + tri(r[1], r[i], r[i + 1]) + end + end + else + for _, r in runs() do + for i = 1, #r - 2 do + if i % 2 == 1 then + tri(r[i], r[i + 1], r[i + 2]) + else + tri(r[i + 1], r[i], r[i + 2]) + end + end + end + end + local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true) + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer, + T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil, + } + return polyMesh(m, o, maxV) +end + +local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0)) + local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1) + local h: { number } = nums(n, "height") or {} + if nx < 2 or nz < 2 then + return nil, nil + end + if nx * nz > maxV then + return nil, "limit: elevation grid of " .. nx .. " x " .. nz + end + local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {} + for z = 0, nz - 1 do + for x = 0, nx - 1 do + table.insert(P, x * dx) + table.insert(P, h[z * nx + x + 1] or 0) + table.insert(P, z * dz) + table.insert(T, x / (nx - 1)) + table.insert(T, z / (nz - 1)) + end + end + for z = 0, nz - 2 do + for x = 0, nx - 2 do + local a = z * nx + x + -- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1 + for _, c in { a, a + nx, a + nx + 1, a + 1 } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + local C, cc = colors(n) + local tc = node(n, "texCoord") + local m: PolyIn = { + P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true), + N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc, + cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T, + } + return polyMesh(m, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ Extrusion +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function sub3(a: { number }, b: { number }): { number } + return { a[1] - b[1], a[2] - b[2], a[3] - b[3] } +end +local function norm(a: { number }): ({ number }, number) + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l +end +-- rotate v about the unit axis k by angle a (Rodrigues) +local function rotate(v: { number }, k: { number }, a: number): { number } + local c, s = cos(a), sin(a) + local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c) + local kv = cross(k, v) + return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d } +end + +local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?) + local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 } + local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 } + local sc = nums(n, "scale") or { 1, 1 } + local ori = nums(n, "orientation") or { 0, 0, 1, 0 } + local ns, nc = #sp // 3, #cs // 2 + if ns < 2 or nc < 2 then + return nil, nil + end + if ns * nc > maxV then + return nil, "limit: extrusion of " .. ns .. " x " .. nc + end + local spine = {} + for i = 1, ns do + spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] } + end + local function same(a: { number }, b: { number }): boolean + return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9 + end + local closedSpine = same(spine[1], spine[ns]) + local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9 + -- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z + local Ys: { { number } }, Zs: { [number]: { number } } = {}, {} + for i = 1, ns do + local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil + local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil + local y = sub3(nxt or spine[i], prev or spine[i]) + Ys[i] = norm(y) + if prev and nxt then + local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i]))) + Zs[i] = if l > 1e-12 then z else nil + end + end + -- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction + local firstZ = nil + for i = 1, ns do + if Zs[i] then + firstZ = Zs[i] + break + end + end + for i = 1, ns do + if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then + Ys[i] = Ys[i - 1] or { 0, 1, 0 } + end + end + for i = 1, ns do + if not Zs[i] then + if firstZ then + Zs[i] = Zs[i - 1] or firstZ + else + local y = Ys[i] + local axis, l = norm(cross({ 0, 1, 0 }, y)) + local ang = math.acos(math.clamp(y[2], -1, 1)) + Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 } + end + end + if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then + Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] } + end + end + local nr = if closedSpine then ns - 1 else ns + local nring = if closedCs then nc - 1 else nc + local P = {} + for i = 1, nr do + local y, z = Ys[i], Zs[i] + local x = cross(y, z) + local si = if #sc >= i * 2 then i else 1 + local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1 + local oi = if #ori >= i * 4 then i else 1 + local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0 + for j = 1, nring do + local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz } + if ang ~= 0 then + v = rotate(v, ax, ang) + end + local s = spine[i] + table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3]) + table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3]) + table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3]) + end + end + local corners, sizes = {}, {} + local function at(i: number, j: number): number + return ((i - 1) % nr) * nring + (j - 1) % nring + end + for i = 1, ns - 1 do + for j = 1, nc - 1 do + for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do + table.insert(corners, c) + end + table.insert(sizes, 4) + end + end + if not closedSpine then + if bool(n, "beginCap", true) then + for j = 1, nring do + table.insert(corners, at(1, j)) + end + table.insert(sizes, nring) + end + if bool(n, "endCap", true) then + for j = nring, 1, -1 do + table.insert(corners, at(ns, j)) + end + table.insert(sizes, nring) + end + end + return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV) +end + +-- ------------------------------------------------------------------------------------------------ lines, points +local function lines(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + local C, cc = colors(n) + local perVertex = bool(n, "colorPerVertex", true) + local runs: { { number } } = {} + if n.type == "LineSet" then + local at = 0 + for _, c in nums(n, "vertexCount") or {} do + local r = {} + for q = 0, c - 1 do + r[q + 1] = at + q + end + at += c + table.insert(runs, r) + end + else + local corners, sizes = split(nums(n, "coordIndex") or {}) + local k = 0 + for _, s in sizes do + local r = {} + for q = 1, s do + r[q] = corners[k + q] + end + k += s + table.insert(runs, r) + end + end + local cIdx = nums(n, "colorIndex") or {} + local cList = if perVertex then cornerList(cIdx) else nil + local vkey: { [string]: number } = {} + local src: { { number } } = {} + local out: { number } = {} + local k = 0 + for li, r in runs do + local prev: number? = nil + for _, c in r do + k += 1 + if c == nil or c < 0 or c >= np then + prev = nil + continue + end + local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1) + local key = c .. ":" .. ci + local v = vkey[key] + if not v then + v = #src + src[v + 1] = { c, ci } + vkey[key] = v + end + if prev then + table.insert(out, prev) + table.insert(out, v) + end + prev = v + end + end + if #src > maxV then + return nil, "limit: more than " .. maxV .. " vertices" + end + local pos = S.accessor(nil, "f32", 3, #src) + local col = if C then S.accessor(nil, "f32", cc, #src) else nil + for v, s in src do + for q = 0, 2 do + buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1]) + end + if col and C then + for q = 0, cc - 1 do + buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1) + end + end + end + return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" } +end + +local function pointSet(n: any, maxV: number): (any, string?) + local P = points(n, "coord", "point") or {} + local np = #P // 3 + if np > maxV then + return nil, "limit: more than " .. maxV .. " points" + end + local C, cc = colors(n) + local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) } + if C then + local col = S.accessor(nil, "f32", cc, np) + for i = 0, np * cc - 1 do + buffer.writef32(col.data, i * 4, C[i + 1] or 1) + end + attrs.COLOR_0 = col + end + return { attributes = attrs, mode = "points" } +end + +-- ------------------------------------------------------------------------------------------------ primitives +-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles) +local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive + local nv = #P // 3 + if o.flipV ~= false then + for i = 2, #T, 2 do + T[i] = 1 - T[i] + end + end + return { + attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) }, + indices = u32(I), + mode = "triangles", + } +end + +local function box(n: any, o: Options): Types.Primitive + local s = vec(n, "size", { 2, 2, 2 }) + local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2 + local P, N, T, I = {}, {}, {}, {} + -- faces: normal, u axis, v axis (the specification's texture orientation) + local FACES = { + { { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } }, + { { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } }, + { { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } }, + } + for f, face in FACES do + local nn, u, v = face[1], face[2], face[3] + for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do + for q = 1, 3 do + local h = if q == 1 then hx elseif q == 2 then hy else hz + table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h) + table.insert(N, nn[q]) + end + table.insert(T, (c[1] + 1) / 2) + table.insert(T, (c[2] + 1) / 2) + end + local b = (f - 1) * 4 + for _, x in { 0, 1, 2, 0, 2, 3 } do + table.insert(I, b + x) + end + end + return direct(P, N, T, I, o) +end + +-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z) +-- and runs counter-clockwise seen from +y +local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?) + for i = 0, segs do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + if N then + table.insert(N, x * (nr or 1)) + table.insert(N, ny or 0) + table.insert(N, z * (nr or 1)) + end + if T then + table.insert(T, i / segs) + table.insert(T, t) + end + end +end + +-- a cap disc at height y facing ny (+1 / -1) +local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number) + local b = #P // 3 + for i = 0, segs - 1 do + local a = 2 * pi * i / segs + local x, z = -sin(a), -cos(a) + table.insert(P, x * r) + table.insert(P, y) + table.insert(P, z * r) + table.insert(N, 0) + table.insert(N, ny) + table.insert(N, 0) + -- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom) + table.insert(T, x / 2 + 0.5) + table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5) + end + for i = 1, segs - 2 do + -- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom + if ny > 0 then + table.insert(I, b) + table.insert(I, b + i) + table.insert(I, b + i + 1) + else + table.insert(I, b) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end + end +end + +-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper) +local function band(I: { number }, a: number, b: number, segs: number) + for i = 0, segs - 1 do + table.insert(I, a + i) + table.insert(I, a + i + 1) + table.insert(I, b + i + 1) + table.insert(I, a + i) + table.insert(I, b + i + 1) + table.insert(I, b + i) + end +end + +local function sphere(n: any, o: Options, segs: number): Types.Primitive + local r = num(n, "radius", 1) + local rings = math.max(2, segs // 2) + local P, N, T, I = {}, {}, {}, {} + for j = 0, rings do + local phi = pi * j / rings -- from the bottom + local y, rr = -cos(phi), sin(phi) + ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr) + end + for j = 0, rings - 1 do + band(I, j * (segs + 1), (j + 1) * (segs + 1), segs) + end + return direct(P, N, T, I, o) +end + +local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive + local r = num(n, if cone then "bottomRadius" else "radius", 1) + local h = num(n, "height", 2) + local P, N, T, I = {}, {}, {}, {} + if bool(n, "side", true) then + -- side normals: a cone's lean outwards by its slope + local l = sqrt(r * r + h * h) + local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1 + ring(P, N, T, segs, -h / 2, r, 0, ny, nr) + ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr) + band(I, 0, segs + 1, segs) + end + if not cone and bool(n, "top", true) then + cap(P, N, T, I, segs, h / 2, r, 1) + end + if bool(n, "bottom", true) then + cap(P, N, T, I, segs, -h / 2, r, -1) + end + return direct(P, N, T, I, o) +end + +-- ------------------------------------------------------------------------------------------------ dispatch +-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here); +-- the second value of a success is the node's solid flag +function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any) + local t = n.type + local maxV = o.maxVertices or 2 ^ 24 + local segs = math.clamp(math.floor(o.segments or 32), 3, 1024) + local solid = bool(n, "solid", true) + local prim: Types.Primitive?, err: string? = nil, nil + if t == "IndexedFaceSet" then + prim, err = faceSet(n, o, maxV) + elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then + prim, err = triSet(n, o, maxV) + elseif t == "ElevationGrid" then + prim, err = elevationGrid(n, o, maxV) + elseif t == "Extrusion" then + prim, err = extrusion(n, o, maxV) + elseif t == "IndexedLineSet" or t == "LineSet" then + prim, err = lines(n, maxV) + solid = false + elseif t == "PointSet" then + prim, err = pointSet(n, maxV) + solid = false + elseif t == "Box" then + prim = box(n, o) + elseif t == "Sphere" then + prim = sphere(n, o, segs) + elseif t == "Cylinder" then + prim = cylinder(n, o, segs, false) + elseif t == "Cone" then + prim = cylinder(n, o, segs, true) + else + return nil, nil + end + if not prim then + return nil, err + end + return prim, solid +end + +return Geometry diff --git a/src/Formats/codecs/model/Vrml/Parse.luau b/src/Formats/codecs/model/Vrml/Parse.luau new file mode 100644 index 0000000..8dd2ac5 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Parse.luau @@ -0,0 +1,536 @@ +--!strict +-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into +-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are +-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers, +-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO +-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside +-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations, +-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are +-- returned as nil, message ("line N: ..."). +local Parse = {} + +export type Node = { type: string, def: string?, fields: { [string]: any } } +export type Route = { from: Node, fromField: string, to: Node, toField: string } +export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? } +export type Graph = { + roots: { Node }, + routes: { Route }, + header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile + meta: { [string]: string }, -- META / WorldInfo statements + components: { string }, + units: { [string]: { name: string, factor: number } }, + protos: { [string]: Proto }, +} +-- an IS reference in a PROTO body: fields[name] = { is = "protoField" } +export type IsRef = { is: string } + +local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*" +local MAX_DEPTH = 200 +local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true } +local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true } + +-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared) +local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node + local done = memo[node] + if done then + return done + end + local out: Node = { type = node.type, def = node.def, fields = {} } + memo[node] = out + for k, v in node.fields do + if type(v) == "table" and type((v :: any).is) == "string" then + local name = (v :: any).is + local val = values[name] + if val == nil then + val = defaults[name] + end + out.fields[k] = val + elseif type(v) == "table" then + local arr = table.create(#v) + for i, x in v do + arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x + end + out.fields[k] = arr + else + out.fields[k] = v + end + end + return out +end + +-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO +function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node? + if proto.extern or #proto.body == 0 then + return nil + end + local memo = {} + local first: Node? = nil + for _, n in proto.body do + local c = copy(n, values, proto.fields, memo) + first = first or c + end + if routes then + for _, r in proto.routes do + local from, to = memo[r.from], memo[r.to] + if from and to then + table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField }) + end + end + end + local f = first :: Node + if def then + -- the instance gets its own copy of the node so its DEF name is its own + local out: Node = { type = f.type, def = def, fields = f.fields } + return out + end + return f +end + +function Parse.parse(text: string): (Graph?, string?) + local n = #text + local p = 1 + local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} } + local defs: { [string]: Node } = {} + local protos: { [string]: Proto } = graph.protos + local routes: { Route } = graph.routes + local failure: string? = nil + local depth = 0 + + local function line(at: number): number + local l = 1 + for _ in gmatch(sub(text, 1, at), "\n") do + l += 1 + end + return l + end + local function fail(msg: string) + if not failure then + failure = "line " .. line(p) .. ": " .. msg + end + end + + -- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8 + local v, enc = match(text, "^#VRML V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding = v, enc + if v ~= "2.0" then + return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)" + end + else + v, enc = match(text, "^#X3D V(%S+) (%S+)") + if v then + graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true + end + end + + -- the lexer: skip blanks, commas and comments; returns the next token kind and value + -- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof" + local function skip() + while true do + local q = find(text, "[^%s,]", p) + if not q then + p = n + 1 + return + end + p = q + if byte(text, p) == 35 then -- '#' + local e = find(text, "[\r\n]", p) + p = if e then e else n + 1 + else + return + end + end + end + local function token(): (string, any) + skip() + if p > n then + return "eof", nil + end + local c = byte(text, p) + if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ] + p += 1 + return string.char(c), nil + elseif c == 34 then -- a string: \" and \\ escapes + local q = p + 1 + local parts = {} + while true do + local e = find(text, '["\\]', q) + if not e then + fail("unterminated string") + p = n + 1 + return "eof", nil + end + table.insert(parts, sub(text, q, e - 1)) + if byte(text, e) == 92 then + table.insert(parts, sub(text, e + 1, e + 1)) + q = e + 2 + else + p = e + 1 + return "str", table.concat(parts) + end + end + end + if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then + local s, e = find(text, "^[+-]?0[xX]%x+", p) + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p) + end + if not s then + s, e = find(text, "^[+-]?%d*%.?%d*", p) + end + local num = tonumber(sub(text, p, e)) + if num then + p = (e :: number) + 1 + return "num", num + end + if c == 46 then + p += 1 + return ".", nil + end + -- +inf / -nan style words: read the word + local _, we = find(text, "^[^%s,%[%]{}#\"]+", p) + local w = sub(text, p, we) + p = (we :: number) + 1 + local wl = string.lower(w) + local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil + if val == nil then + fail("bad number " .. w) + return "eof", nil + end + return "num", val + end + local s, e = find(text, ID1, p) + if s then + p = (e :: number) + 1 + return "id", sub(text, s, e) + end + fail("unexpected character " .. sub(text, p, p)) + p = n + 1 + return "eof", nil + end + local function peek(): (string, any) + local save = p + local k, val = token() + p = save + return k, val + end + + local parseNode: (first: string) -> (Node?, boolean) + local parseProto: (extern: boolean) -> () + local parseRoute: () -> () + + -- a field value (after its name): an array of numbers / strings / booleans / nodes + local function value(): any + local k, val = token() + if k == "[" then + local out = {} + -- fast path: a bracket of plain numbers (big coordinate arrays) + local close = find(text, "]", p, true) + if close then + local seg = sub(text, p, close - 1) + if not find(seg, "[{}\"#]") then + local ok = true + for w in gmatch(seg, "[^%s,]+") do + local x = tonumber(w) + if x then + table.insert(out, x) + elseif w == "TRUE" or w == "FALSE" then + table.insert(out, w == "TRUE") + else + ok = false + break + end + end + if ok then + p = close + 1 + return out + end + table.clear(out) + end + end + while not failure do + k, val = token() + if k == "]" then + return out + elseif k == "num" or k == "str" then + table.insert(out, val) + elseif k == "id" and (val == "TRUE" or val == "FALSE") then + table.insert(out, val == "TRUE") + elseif k == "id" and val == "NULL" then + continue + elseif k == "id" then + local node = parseNode(val) + if node then + table.insert(out, node) + end + else + fail("unexpected " .. k .. " in a [ ] value") + return out + end + end + return out + elseif k == "num" then + local out = { val } + while true do + local save = p + local k2, v2 = token() + if k2 ~= "num" then + p = save + break + end + table.insert(out, v2) + end + return out + elseif k == "str" then + return { val } + elseif k == "id" then + if val == "TRUE" or val == "FALSE" then + return { val == "TRUE" } + elseif val == "NULL" then + return {} + end + local node = parseNode(val) + return if node then { node } else {} + end + fail("missing field value") + return {} + end + + -- the fields of a node body, up to its "}" + local function body(node: Node) + while not failure do + local k, name = token() + if k == "}" then + return + elseif k ~= "id" then + fail("expected a field name in " .. node.type .. ", got " .. k) + return + end + if name == "ROUTE" then + parseRoute() + elseif name == "PROTO" or name == "EXTERNPROTO" then + parseProto(name == "EXTERNPROTO") + elseif DECL[name] then + -- Script / shader interface: [ | IS ] + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad interface declaration in " .. node.type) + return + end + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[fname] = { is = ref } + elseif HAS_VALUE[name] then + node.fields[fname] = value() + end + else + local pk, pv = peek() + if pk == "id" and pv == "IS" then + token() + local _, ref = token() + node.fields[name] = { is = ref } + else + node.fields[name] = value() + end + end + end + end + + -- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { }) + function parseNode(first: string): (Node?, boolean) + if first == "USE" then + local k, name = token() + if k ~= "id" then + fail("USE without a name") + return nil, false + end + local node = defs[name] + if not node then + fail("USE of an undefined name " .. tostring(name)) + end + return node, true + end + local def: string? = nil + local typ = first + if first == "DEF" then + local k, name = token() + local k2, t2 = token() + if k ~= "id" or k2 ~= "id" then + fail("bad DEF") + return nil, false + end + def, typ = name, t2 + end + local k = token() + if k ~= "{" then + fail("expected { after " .. typ) + return nil, false + end + depth += 1 + if depth > MAX_DEPTH then + fail("limit: nodes nested deeper than " .. MAX_DEPTH) + return nil, false + end + local node: Node = { type = typ, def = def, fields = {} } + body(node) + depth -= 1 + local proto = protos[typ] + if proto and not proto.extern then + local inst = Parse.expand(proto, node.fields, def, routes) + if inst then + node = inst + end + elseif proto then + (node :: any).extern = true + end + if def then + defs[def] = node + end + return node, false + end + + -- ROUTE from.field TO to.field + function parseRoute() + local function path(): (string?, string?) + local k1, a = token() + local k2 = token() + local k3, b = token() + if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then + return nil, nil + end + return a, b + end + local a, af = path() + local k, to = token() + local b, bf = path() + if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then + fail("bad ROUTE") + return + end + local from, dst = defs[a :: string], defs[b :: string] + if from and dst then + table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string }) + end + end + + -- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url + function parseProto(extern: boolean) + local k, name = token() + if k ~= "id" or token() ~= "[" then + fail("bad PROTO") + return + end + local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + while not failure do + local k2, access = token() + if k2 == "]" then + break + elseif k2 ~= "id" or not DECL[access] then + fail("bad PROTO interface") + return + end + local _, _t = token() + local fk, fname = token() + if fk ~= "id" then + fail("bad PROTO interface") + return + end + if HAS_VALUE[access] and not extern then + proto.fields[fname] = value() + end + end + if extern then + value() -- the url list + protos[name] = proto + return + end + if token() ~= "{" then + fail("PROTO " .. tostring(name) .. " without a body") + return + end + -- the body has its own DEF names and its own routes + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + while not failure do + local k3, w = token() + if k3 == "}" then + break + elseif k3 ~= "id" then + fail("bad PROTO body") + break + elseif w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + else + local node = parseNode(w) + if node then + table.insert(proto.body, node) + end + end + end + defs, routes = outerDefs, outerRoutes + protos[name] = proto + end + + -- statements + while not failure do + local k, w = token() + if k == "eof" then + break + elseif k ~= "id" then + fail("unexpected " .. k) + break + end + if w == "ROUTE" then + parseRoute() + elseif w == "PROTO" or w == "EXTERNPROTO" then + parseProto(w == "EXTERNPROTO") + elseif w == "PROFILE" then + local _, prof = token() + graph.header.profile = prof + elseif w == "COMPONENT" then + local _, comp = token() -- name:level is one id + table.insert(graph.components, tostring(comp)) + elseif w == "META" then + local _, key = token() + local _, val = token() + graph.meta[tostring(key)] = tostring(val) + elseif w == "UNIT" then + local _, cat = token() + local _, uname = token() + local _, factor = token() + if type(cat) == "string" and type(factor) == "number" then + graph.units[cat] = { name = tostring(uname), factor = factor } + end + elseif w == "IMPORT" or w == "EXPORT" then + -- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene + local _, _a = token() + if peek() == "." then + token() + token() + end + local pk, pv = peek() + if pk == "id" and pv == "AS" then + token() + token() + end + else + local node = parseNode(w) + if node then + table.insert(graph.roots, node) + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return Parse diff --git a/src/Formats/codecs/model/Vrml/Write.luau b/src/Formats/codecs/model/Vrml/Write.luau new file mode 100644 index 0000000..8c0ad97 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Write.luau @@ -0,0 +1,750 @@ +--!strict +-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text, +-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS; +-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal, +-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines -> +-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material +-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of +-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or +-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights -> +-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and +-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped). +-- Never throws: returns nil, message. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Flatten = require("@formats/codecs/model/MeshFlatten") +local Xml = require("@formats/codecs/text/Xml") + +local Write = {} + +export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? } + +-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers +-- per line), "bool", "str", "mstr" (MFString), "node", "nodes" +type WNode = { type: string, def: string?, use: string?, fields: { { any } } } + +local format, concat = string.format, table.concat + +local function fmt(v: number): string + if v ~= v then + return "0" + elseif v == math.huge then + return "1e38" + elseif v == -math.huge then + return "-1e38" + elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then + return format("%d", v) + end + return format("%.9g", v) +end + +local function W(t: string, def: string?): WNode + return { type = t, def = def, fields = {} } +end +local function F(n: WNode, name: string, kind: string, value: any, per: number?) + table.insert(n.fields, { name, kind, value, per }) +end + +-- names: valid, unique DEF names +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local s = string.gsub(name or "", "[^%w_]", "_") + if s == "" or string.find(s, "^%d") then + s = fallback .. (if s ~= "" then "_" .. s else "") + end + local base, k = s, 1 + while used[s] do + k += 1 + s = base .. "_" .. k + end + used[s] = true + return s + end +end + +-- axis-angle of a quaternion (x, y, z, w) +local function axisAngle(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + local s = math.sqrt(math.max(0, 1 - w * w)) + if s < 1e-9 then + return { 0, 0, 1, 0 } + end + return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) } +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function values(acc: any): { number }? + return (Flatten.numbers(acc)) +end + +local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?) + local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } } + local keep = function(n: string): boolean + return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0" + end + local m, err = Flatten.merge(tmp, keep, { triangulate = false }) + if not m then + return nil, err + end + if not m.sizes or #m.sizes == 0 then + return nil, nil + end + local g = W("IndexedFaceSet") + local coord = W("Coordinate") + F(coord, "point", "mf", m.attrs.POSITION.values, 3) + F(g, "coord", "node", coord) + local idx = {} + local p = 0 + for _, s in m.sizes do + for k = 1, s do + table.insert(idx, m.corners[p + k]) + end + table.insert(idx, -1) + p += s + end + F(g, "coordIndex", "mf", idx, 0) + local nrm = m.attrs.NORMAL + if nrm then + local nn = W("Normal") + F(nn, "vector", "mf", nrm.values, 3) + F(g, "normal", "node", nn) + end + local tc = m.attrs.TEXCOORD_0 + if tc then + local t = W("TextureCoordinate") + local vals, c = {}, tc.components + for i = 0, m.count - 1 do + local s, tt = tc.values[i * c + 1], tc.values[i * c + 2] + table.insert(vals, s) + table.insert(vals, if o.flipV ~= false then 1 - tt else tt) + end + F(t, "point", "mf", vals, 2) + F(g, "texCoord", "node", t) + end + local col = m.attrs.COLOR_0 + if col then + local c = col.components + local rgba = c >= 4 and x3d + local cn = W(if rgba then "ColorRGBA" else "Color") + local vals = {} + local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1 + for i = 0, m.count - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, (col.values[i * c + k] or 1) / scale) + end + end + F(cn, "color", "mf", vals, if rgba then 4 else 3) + F(g, "color", "node", cn) + end + F(g, "solid", "bool", not doubleSided) + return g, nil +end + +-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points) +local function coordNode(prim: any): (WNode?, number) + local pos = values(prim.attributes.POSITION) + if not pos then + return nil, 0 + end + local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components + local p3 = {} + for i = 0, nv - 1 do + for k = 1, 3 do + table.insert(p3, pos[i * pc + k] or 0) + end + end + local coord = W("Coordinate") + F(coord, "point", "mf", p3, 3) + return coord, nv +end +local function colorNode(prim: any, nv: number, x3d: boolean): WNode? + local acc = prim.attributes.COLOR_0 + local col = acc and values(acc) + if not col then + return nil + end + local c = acc.components + local rgba = c >= 4 and x3d + local vals = {} + for i = 0, nv - 1 do + for k = 1, if rgba then 4 else 3 do + table.insert(vals, col[i * c + k] or 1) + end + end + local cn = W(if rgba then "ColorRGBA" else "Color") + F(cn, "color", "mf", vals, if rgba then 4 else 3) + return cn +end + +local function lineSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "lines without POSITION" + end + local ind: { number } + if prim.indices then + ind = values(prim.indices) or {} + else + ind = {} + for i = 0, nv - 1 do + ind[i + 1] = i + end + end + local idx = {} + local mode = prim.mode + if mode == "lines" then + for i = 1, #ind - 1, 2 do + table.insert(idx, ind[i]) + table.insert(idx, ind[i + 1]) + table.insert(idx, -1) + end + else + for _, v in ind do + table.insert(idx, v) + end + if mode == "line_loop" and #ind > 0 then + table.insert(idx, ind[1]) + end + table.insert(idx, -1) + end + for _, v in idx do + if v >= nv then + return nil, "line index out of range" + end + end + local g = W("IndexedLineSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + F(g, "coordIndex", "mf", idx, 0) + return g, nil +end + +local function pointSet(prim: any, x3d: boolean): (WNode?, string?) + local coord, nv = coordNode(prim) + if not coord then + return nil, "points without POSITION" + end + local g = W("PointSet") + F(g, "coord", "node", coord) + local cn = colorNode(prim, nv, x3d) + if cn then + F(g, "color", "node", cn) + end + return g, nil +end + +-- ------------------------------------------------------------------------------------------------ materials +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" } + +local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string? + if written[i] then + return written[i] + end + local tex = scene.textures[i] + if not tex then + return nil + end + local url = tex.uri + if tex.data and type(o.files) == "table" then + local base = string.match(o.name or "model", "([^/\\]+)$") or "model" + base = string.gsub(base, "%.[^.]*$", "") + local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png" + local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext) + o.files[file] = tex.data + url = file + end + if url then + written[i] = url + end + return url +end + +local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode + local m = scene.materials[mi] + local app = W("Appearance") + local mat = W("Material") + local x = m.extras and m.extras.vrml or {} + local c = m.baseColor or { 1, 1, 1, 1 } + F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] }) + local e = m.emissive or { 0, 0, 0 } + if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then + F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] }) + end + if type(x.specularColor) == "table" then + F(mat, "specularColor", "sf", x.specularColor) + end + local sh = x.shininess + if type(sh) ~= "number" then + local r = math.max(m.roughness or 1, 1e-3) + sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1) + end + F(mat, "shininess", "sf", { sh }) + if type(x.ambientIntensity) == "number" then + F(mat, "ambientIntensity", "sf", { x.ambientIntensity }) + end + if (c[4] or 1) < 1 then + F(mat, "transparency", "sf", { 1 - c[4] }) + end + F(app, "material", "node", mat) + local ref = m.baseColorTexture + if ref and type(ref.texture) == "number" then + local url = textureUrl(scene, ref.texture, o, written) + local img = scene.textures[ref.texture] and scene.textures[ref.texture].image + if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then + local it + if url then + it = W("ImageTexture") + F(it, "url", "mstr", { url }) + else + -- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up) + it = W("PixelTexture") + local w, h = img.width, img.height + local v = { w, h, 4 } + for row = h - 1, 0, -1 do + for x = 0, w - 1 do + table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4)) + end + end + -- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA + for i = 4, #v do + local p = v[i] + v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216 + end + F(it, "image", "sf", v) + end + local s = scene.textures[ref.texture].sampler + if s and s.wrapS == "clamp" then + F(it, "repeatS", "bool", false) + end + if s and s.wrapT == "clamp" then + F(it, "repeatT", "bool", false) + end + F(app, "texture", "node", it) + local tf = ref.transform + if tf then + local tt = W("TextureTransform") + if tf.offset then + F(tt, "translation", "sf", tf.offset) + end + if tf.scale then + F(tt, "scale", "sf", tf.scale) + end + if tf.rotation then + F(tt, "rotation", "sf", { tf.rotation }) + end + F(app, "textureTransform", "node", tt) + end + end + end + return app +end + +-- ------------------------------------------------------------------------------------------------ the tree +function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?) + local x3d = o.encoding == "x3dv" or o.encoding == "xml" + local name = namer() + local nodeDef: { [number]: string } = {} + local meshShapes: { [number]: { WNode } } = {} + local appDef: { [any]: string } = {} + local written: { [number]: string } = {} + local failure: string? = nil + + local function shapes(mi: number): { WNode } + local done = meshShapes[mi] + if done then + -- USE the shapes written before + local out = {} + for _, s in done do + table.insert(out, { type = "Shape", use = s.def, fields = {} }) + end + return out + end + local mesh = scene.meshes[mi] + local out = {} + for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do + local mode = prim.mode or "triangles" + local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil + local geo, err + if mode == "lines" or mode == "line_strip" or mode == "line_loop" then + geo, err = lineSet(prim, x3d) + elseif mode == "points" then + geo, err = pointSet(prim, x3d) + else + geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d) + end + if err then + failure = failure or err + end + if geo then + local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape")) + if mat then + local key = prim.material + if appDef[key] then + F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} }) + else + local app = appearance(scene, prim.material, o, written) + app.def = name(mat.name, "Material") + appDef[key] = app.def + F(sh, "appearance", "node", app) + end + end + F(sh, "geometry", "node", geo) + table.insert(out, sh) + end + end + meshShapes[mi] = out + return out + end + + local visiting: { [number]: boolean } = {} + local function transform(ni: number): WNode? + local n = scene.nodes[ni] + if type(n) ~= "table" or visiting[ni] then + return nil + end + visiting[ni] = true + local def = name(n.name, "Node") + nodeDef[ni] = def + local t = W("Transform", def) + local tr, rot, sc = n.translation, n.rotation, n.scale + if n.matrix then + tr, rot, sc = Mat4.decompose(n.matrix) + end + if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then + F(t, "translation", "sf", { tr[1], tr[2], tr[3] }) + end + if rot then + local aa = axisAngle(rot) + if aa[4] ~= 0 then + F(t, "rotation", "sf", aa) + end + end + if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then + F(t, "scale", "sf", { sc[1], sc[2], sc[3] }) + end + local kids: { WNode } = {} + if type(n.mesh) == "number" then + for _, s in shapes(n.mesh) do + table.insert(kids, s) + end + end + local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil + if cam then + local v + if cam.type == "orthographic" and x3d then + v = W("OrthoViewpoint") + local xm, ym = cam.xmag or 1, cam.ymag or 1 + F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym }) + else + v = W("Viewpoint") + F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 }) + end + F(v, "position", "sf", { 0, 0, 0 }) + if cam.name then + F(v, "description", "str", cam.name) + end + table.insert(kids, v) + end + local l = if type(n.light) == "number" then scene.lights[n.light] else nil + if l then + local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight" + local ln = W(typ) + local c = l.color or { 1, 1, 1 } + F(ln, "color", "sf", { c[1], c[2], c[3] }) + F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) }) + if typ ~= "PointLight" then + F(ln, "direction", "sf", { 0, 0, -1 }) + end + if typ ~= "DirectionalLight" then + F(ln, "location", "sf", { 0, 0, 0 }) + F(ln, "radius", "sf", { l.range or 100 }) + end + if typ == "SpotLight" then + F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 }) + F(ln, "beamWidth", "sf", { l.innerCone or 0 }) + end + table.insert(kids, ln) + end + for _, c in n.children or {} do + local ct = transform(c) + if ct then + table.insert(kids, ct) + end + end + if #kids > 0 then + F(t, "children", "nodes", kids) + end + visiting[ni] = nil + return t + end + + local roots: { WNode } = {} + local list = scene.roots + if type(list) ~= "table" or #list == 0 then + -- no roots: every node without a parent + local child = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + child[c] = true + end + end + list = {} + for i = 1, #scene.nodes do + if not child[i] then + table.insert(list, i) + end + end + end + for _, ri in list do + local t = transform(ri) + if t then + table.insert(roots, t) + end + end + if #scene.nodes == 0 then + for mi = 1, #scene.meshes do + for _, s in shapes(mi) do + table.insert(roots, s) + end + end + end + + -- animations: a TimeSensor per animation, an interpolator per channel + local routes: { { string } } = {} + for ai, anim in scene.animations or {} do + local tmax = 0 + local chans = {} + for _, ch in anim.channels or {} do + local target = nodeDef[ch.node] + if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then + local input, output = values(ch.input), values(ch.output) + if input and output and #input > 0 then + tmax = math.max(tmax, input[#input]) + table.insert(chans, { ch, target, input, output }) + end + end + end + if #chans > 0 then + local cycle = if tmax > 0 then tmax else 1 + local ts = W("TimeSensor", name(anim.name, "Animation" .. ai)) + F(ts, "cycleInterval", "sf", { cycle }) + F(ts, "loop", "bool", true) + table.insert(roots, ts) + for k, c in chans do + local ch, target, input, output = c[1], c[2], c[3], c[4] + local rot = ch.path == "rotation" + local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator")) + local keys = {} + for i, tv in input do + keys[i] = tv / cycle + end + local comps = if rot then 4 else 3 + local stride = #output // #input + -- CUBICSPLINE stores in-tangent, value, out-tangent per key + local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0 + local kv = {} + for i = 0, #input - 1 do + local v = {} + for q = 1, comps do + v[q] = output[i * stride + off + q] or 0 + end + if rot then + v = axisAngle(v) + end + for _, x in v do + table.insert(kv, x) + end + end + F(it, "key", "mf", keys, 0) + F(it, "keyValue", "mf", kv, comps) + table.insert(roots, it) + table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" }) + table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path }) + end + end + end + if failure then + return nil, nil, failure + end + return roots, routes, nil +end + +-- ------------------------------------------------------------------------------------------------ serializers +local function numbers(vals: { number }, per: number?, indent: string): string + local out = table.create(#vals) + for i, v in vals do + out[i] = fmt(v) + end + if per == 0 then + -- index lists: one face per line + local lines, cur = {}, {} + for i, v in vals do + table.insert(cur, out[i]) + if v == -1 then + table.insert(lines, concat(cur, " ")) + cur = {} + end + end + if #cur > 0 then + table.insert(lines, concat(cur, " ")) + end + return concat(lines, "\n" .. indent) + end + if per and per > 0 then + local lines = {} + for i = 1, #out, per do + table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out))) + end + return concat(lines, ",\n" .. indent) + end + return concat(out, " ") +end + +local function quote(s: string): string + return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"' +end + +local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string + local out = {} + if x3d then + table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by formats-luau\n") + else + table.insert(out, "#VRML V2.0 utf8\n# written by formats-luau\n") + end + local function emit(n: WNode, ind: string): string + if n.use then + return "USE " .. n.use + end + local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" } + local ind2 = ind .. " " + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + local s + if kind == "sf" then + s = numbers(v, nil, ind2) + elseif kind == "mf" then + s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]" + elseif kind == "bool" then + s = if v then "TRUE" else "FALSE" + elseif kind == "str" then + s = quote(v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + s = "[ " .. concat(q, " ") .. " ]" + elseif kind == "node" then + s = emit(v, ind2) + else + local q = {} + for i, x in v do + q[i] = ind2 .. " " .. emit(x, ind2 .. " ") + end + s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]" + end + table.insert(parts, ind2 .. fname .. " " .. s) + end + table.insert(parts, ind .. "}") + return concat(parts, "\n") + end + for _, r in roots do + table.insert(out, emit(r, "")) + end + for _, r in routes do + table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4])) + end + return concat(out, "\n") .. "\n" +end + +-- the containerField a child element needs when it is not its type's default +local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" } + +local function xml(roots: { WNode }, routes: { { string } }): (string?, string?) + local function element(n: WNode, field: string): any + local attrs = Types.object() + local kids = {} + if (DEFAULT[n.type] or "children") ~= field then + Types.set(attrs, "containerField", field) + end + if n.use then + Types.set(attrs, "USE", n.use) + return Xml.element(n.type, attrs :: any) + end + if n.def then + Types.set(attrs, "DEF", n.def) + end + for _, f in n.fields do + local fname, kind, v, per = f[1], f[2], f[3], f[4] + if kind == "sf" then + Types.set(attrs, fname, numbers(v, nil, "")) + elseif kind == "mf" then + local s = numbers(v, per, "") + Types.set(attrs, fname, (string.gsub(s, "\n", " "))) + elseif kind == "bool" then + Types.set(attrs, fname, if v then "true" else "false") + elseif kind == "str" then + Types.set(attrs, fname, v) + elseif kind == "mstr" then + local q = {} + for i, x in v do + q[i] = quote(x) + end + Types.set(attrs, fname, concat(q, " ")) + elseif kind == "node" then + table.insert(kids, element(v, fname)) + else + for _, x in v do + table.insert(kids, element(x, fname)) + end + end + end + return Xml.element(n.type, attrs :: any, kids) + end + local sceneKids = {} + for _, r in roots do + table.insert(sceneKids, element(r, "children")) + end + for _, r in routes do + local a = Types.object() + Types.set(a, "fromNode", r[1]) + Types.set(a, "fromField", r[2]) + Types.set(a, "toNode", r[3]) + Types.set(a, "toField", r[4]) + table.insert(sceneKids, Xml.element("ROUTE", a :: any)) + end + local ra = Types.object() + Types.set(ra, "profile", "Interchange") + Types.set(ra, "version", "3.3") + local meta = Types.object() + Types.set(meta, "name", "generator") + Types.set(meta, "content", "formats-luau") + local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) }) + local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 }) + if not s then + return nil, if err then err.message else "xml" + end + return s, nil +end + +-- text(scene, opts) -> the file text +function Write.text(scene: any, o: Options): (string?, string?) + local roots, routes, err = Write.graph(scene, o) + if not roots or not routes then + return nil, err + end + if o.encoding == "xml" then + return xml(roots, routes) + end + return classic(roots, routes, o.encoding == "x3dv"), nil +end + +return Write diff --git a/src/Formats/codecs/model/Vrml/Xml.luau b/src/Formats/codecs/model/Vrml/Xml.luau new file mode 100644 index 0000000..93066e8 --- /dev/null +++ b/src/Formats/codecs/model/Vrml/Xml.luau @@ -0,0 +1,238 @@ +--!strict +-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one +-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes; +-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their +-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE; +-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and +-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head / +-- meta, UNIT, component and the profile go into the graph header. Never throws. +local Xml = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") + +local VXml = {} + +local GEOMETRY = { + "Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid", + "Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet", + "IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D", + "Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface", +} +local CONTAINER: { [string]: string } = { + Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material", + UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture", + MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform", + Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", + TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord", + FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties", + LineProperties = "lineProperties", +} +for _, g in GEOMETRY do + CONTAINER[g] = "geometry" +end + +local function container(el: Xml.Node, typ: string): string + local c = el.attrs.containerField + if type(c) == "string" and c ~= "" then + return c + end + if string.sub(typ, 1, 8) == "Metadata" then + return "metadata" + end + return CONTAINER[typ] or "children" +end + +function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?) + local root = doc.root or doc + if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then + return nil, "no root element" + end + local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} } + graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile + local defs: { [string]: Parse.Node } = {} + local protos = graph.protos + local routes = graph.routes + local depth = 0 + local failure: string? = nil + + local convert: (el: Xml.Node) -> Parse.Node? + local function route(el: Xml.Node) + local a = el.attrs + local from, to = defs[a.fromNode or ""], defs[a.toNode or ""] + local ff, tf = a.fromField, a.toField + if from and to and type(ff) == "string" and type(tf) == "string" then + table.insert(routes, { from = from, fromField = ff, to = to, toField = tf }) + end + end + local declare: (el: Xml.Node, extern: boolean) -> () + + -- the child elements of a node into its fields + local function children(el: Xml.Node, node: Parse.Node) + for _, ch in el.children do + if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then + continue + end + local name = Xml.localName(ch.name) + if name == "ROUTE" then + route(ch) + elseif name == "IS" then + for _, c in Xml.children(ch, "connect") do + local nf, pf = c.attrs.nodeField, c.attrs.protoField + if nf and pf then + node.fields[nf] = { is = pf } + end + end + elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then + declare(ch, name == "ExternProtoDeclare") + elseif name == "field" or name == "fieldValue" then + continue -- Script / shader interfaces + else + local c = convert(ch) + if c then + local f = container(ch, if name == "ProtoInstance" then "" else name) + local list = node.fields[f] + if type(list) ~= "table" or (list :: any).is then + list = {} + node.fields[f] = list + end + table.insert(list, c) + end + end + end + end + + -- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes + local function fieldValue(el: Xml.Node): any + if el.attrs.value ~= nil then + return el.attrs.value + end + local list = {} + for _, ch in el.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local c = convert(ch) + if c then + table.insert(list, c) + end + end + end + return list + end + + function declare(el: Xml.Node, extern: boolean) + local name = el.attrs.name + if not name then + return + end + local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil } + local iface = if extern then el else Xml.child(el, "ProtoInterface") + if iface then + for _, f in Xml.children(iface, "field") do + if f.attrs.name then + proto.fields[f.attrs.name] = fieldValue(f) + end + end + end + local bodyEl = Xml.child(el, "ProtoBody") + if bodyEl and not extern then + local outerDefs, outerRoutes = defs, routes + defs, routes = {}, proto.routes + for _, ch in bodyEl.children do + if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then + local nm = Xml.localName(ch.name) + if nm == "ROUTE" then + route(ch) + elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then + declare(ch, nm == "ExternProtoDeclare") + else + local c = convert(ch) + if c then + table.insert(proto.body, c) + end + end + end + end + defs, routes = outerDefs, outerRoutes + end + protos[name] = proto + end + + function convert(el: Xml.Node): Parse.Node? + local a = el.attrs + if a.USE then + return defs[a.USE] + end + depth += 1 + if depth > 200 then + failure = failure or "limit: nodes nested deeper than 200" + depth -= 1 + return nil + end + local typ = Xml.localName(el.name) + local node: any + if typ == "ProtoInstance" then + local proto = protos[a.name or ""] + local values = {} + for _, fv in Xml.children(el, "fieldValue") do + if fv.attrs.name then + values[fv.attrs.name] = fieldValue(fv) + end + end + local inst = proto and Parse.expand(proto, values, a.DEF, routes) + node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values } + else + node = { type = typ, def = a.DEF, fields = {} } + for k, v in a do + if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then + node.fields[k] = v + end + end + children(el, node) + end + depth -= 1 + if a.DEF then + defs[a.DEF] = node + end + return node + end + + for _, ch in root.children do + if type(ch) ~= "table" then + continue + end + local name = Xml.localName(ch.name) + if name == "head" then + for _, h in ch.children do + if type(h) == "table" then + local hn = Xml.localName(h.name) + if hn == "meta" and h.attrs.name then + graph.meta[h.attrs.name] = h.attrs.content or "" + elseif hn == "component" and h.attrs.name then + table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1")) + elseif hn == "unit" and h.attrs.category then + graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 } + end + end + end + elseif name == "Scene" then + local scene: Parse.Node = { type = "Scene", fields = {} } + children(ch, scene) + local list = scene.fields.children + if type(list) == "table" then + graph.roots = list + end + for f, v in scene.fields do + -- a top-level node with another containerField still shows + if f ~= "children" and type(v) == "table" then + for _, x in v do + table.insert(graph.roots, x) + end + end + end + end + end + if failure then + return nil, failure + end + return graph, nil +end + +return VXml diff --git a/src/Formats/codecs/model/Vrml/init.luau b/src/Formats/codecs/model/Vrml/init.luau new file mode 100644 index 0000000..6e37e4d --- /dev/null +++ b/src/Formats/codecs/model/Vrml/init.luau @@ -0,0 +1,160 @@ +--!strict +-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML, +-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding +-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a +-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated +-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2. +-- +-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content +-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } }) +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local XmlCodec = require("@formats/codecs/text/Xml") +local Parse = require("@formats/codecs/model/Vrml/Parse") +local VXml = require("@formats/codecs/model/Vrml/Xml") +local Build = require("@formats/codecs/model/Vrml/Build") +local Write = require("@formats/codecs/model/Vrml/Write") + +local Vrml = {} + +export type Graph = Parse.Graph +export type Node = Parse.Node +export type Options = Build.Options & { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + maxBytes: number?, -- the inflated size of a gzipped file (default 2^28) +} + +-- the bytes as text: gzip inflated, UTF-8 BOM dropped +local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?) + local b = if type(data) == "string" then buffer.fromstring(data) else data + if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then + local out, err = Deflate.gunzip(b) + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflated file over maxBytes") + end + b = out + end + local s = buffer.tostring(b) + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + end + return s, nil +end + +local function code(msg: string): string + if string.find(msg, "unsupported", 1, true) then + return Err.UNSUPPORTED + elseif string.find(msg, "limit", 1, true) then + return Err.LIMIT + elseif string.find(msg, "unterminated", 1, true) then + return Err.TRUNCATED + end + return Err.CORRUPT +end + +-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv) +function Vrml.parse(s: string): (Graph?, Err.Err?) + local g, msg = Parse.parse(s) + if not g then + return nil, Err.new(code(msg or "parse error"), msg or "parse error") + end + return g, nil +end + +-- parseXml(text | XML document) -> the graph of an X3D XML file +function Vrml.parseXml(src: any): (Graph?, Err.Err?) + local doc = src + if type(src) == "string" then + local d, err = XmlCodec.decode(src) + if not d and err and err.code == Err.TRUNCATED and not string.find(src, "", 1, true) then + -- VTK's X3D exporter leaves the root element open + d = XmlCodec.decode(src .. "\n\n") + end + if not d then + return nil, err + end + doc = d + end + local g, msg = VXml.graph(doc) + if not g then + return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D") + end + return g, nil +end + +-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED +function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?) + local s, err = text(data, opts and opts.maxBytes) + if not s then + return nil, err + end + local head = string.match(s, "^%s*(.?)") + if head == "<" then + return Vrml.parseXml(s) + end + if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then + return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)") + end + return Vrml.parse(s) +end + +-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve +function Vrml.fetcher(opts: Options?): (uri: string) -> buffer? + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil + end +end + +-- build(graph, opts?) -> Scene +function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.fetch = o.fetch or Vrml.fetcher(opts) + o.load = o.load or function(data: buffer): (any, string?) + local g, err = Vrml.graph(data, opts) + return g, if err then err.message else nil + end + local scene, msg = Build.scene(graph, o) + if not scene then + return nil, Err.new(code(msg or "build failed"), msg or "build failed") + end + return scene, nil +end + +-- decode(bytes, opts?) -> Scene: graph + build +function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?) + local g, err = Vrml.graph(data, opts) + if not g then + return nil, err + end + return Vrml.build(g, opts) +end + +-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files +function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + local s, msg = Write.text(scene, opts or {}) + if not s then + return nil, Err.new(Err.ARG, msg or "the scene could not be written") + end + return s, nil +end + +return Vrml diff --git a/src/Formats/model/vrml/init.luau b/src/Formats/model/vrml/init.luau new file mode 100644 index 0000000..c9192c1 --- /dev/null +++ b/src/Formats/model/vrml/init.luau @@ -0,0 +1,77 @@ +--!strict +-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over +-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code. +-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD, +-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and +-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord, +-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided), +-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated +-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor -> +-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons +-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless +-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres). +-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet / +-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights, +-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials). +-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and +-- skins on write (the rest pose is written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local Wrl = { + name = "vrml", + category = "model", + extensions = { "wrl", "wrz", "vrml" }, + mime = { "model/vrml", "x-world/x-vrml" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Wrl.sniff(r: Bytes.Reader): number + local head = r:peek(16) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: any = table.clone(opts or {}) + o.format = "vrml" + return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o) +end + +-- ------------------------------------------------------------------------------------------------ encode +function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = table.clone(opts or {}) + o.encoding = "vrml97" + local text, err = Vrml.encode(scene, o) + if not text then + return nil, err + end + return buffer.fromstring(text), nil +end + +return Wrl diff --git a/src/Formats/model/x3d/init.luau b/src/Formats/model/x3d/init.luau new file mode 100644 index 0000000..860efa7 --- /dev/null +++ b/src/Formats/model/x3d/init.luau @@ -0,0 +1,85 @@ +--!strict +-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv, +-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares). +-- New code. +-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, +-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA, +-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial / +-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField; +-- head meta, components and UNIT length (-> meta.unit). +-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the +-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras). +-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders, +-- H-Anim skinning, scripts. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Vrml = require("@formats/codecs/model/Vrml") + +-- ------------------------------------------------------------------------------------------------ contract +local X3d = { + name = "x3d", + category = "model", + extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" }, + mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" }, + caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string) + resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths) + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention) + segments: number?, -- Sphere / Cone / Cylinder segments around (default 32) + maxVertices: number?, -- per geometry (default 2^24) +} +export type EncodeOptions = { + encoding: ("xml" | "x3dv")?, -- default "xml" + format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding + files: { [string]: any }?, -- receives the texture images (else url = texture.uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function X3d.sniff(r: Bytes.Reader): number + local head = r:peek(1024) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + if string.sub(head, 1, 5) == "#X3D " then + return 1 + end + if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then + return 0.9 + end + if string.find(head, "]") or string.find(head, " meta.unit") +end + +-- ------------------------------------------------------------------------------------------------ XML adapter +do + local g = assert(Vrml.graph([[ + + + + + + + +]])) + t:check(g.header.xml and g.header.version == "4.0", "XML header") + t:eq(g.components[1], "Shaders:1", "head component") + local grp = g.roots[1] + local kids = Fields.nodes(grp, "children") + t:eq(#kids, 2, "ProtoInstances in children") + t:eq(Fields.num(Fields.node(kids[1], "geometry"), "radius", -1), 5, "fieldValue") + t:eq(Fields.num(Fields.node(kids[2], "geometry"), "radius", -1), 2, "ProtoInterface default") + local shape = g.roots[2] + local box = Fields.node(shape, "geometry") + t:eq(table.concat(Fields.vec(box, "size", { 9, 9, 9 }), " "), "1 2 3", "numbers with commas") + t:eq(Fields.bool(box, "solid", true), false, "XML booleans (any case)") + local tex = Fields.node(Fields.node(shape, "appearance"), "texture") + local urls = Fields.strs(tex, "url") + t:check(#urls == 2 and urls[2] == "b.png", "quoted MFString") + t:eq(g.roots[3], grp, "USE in XML") + local single = { type = "ImageTexture", fields = { url = "plain name.png" } } + t:eq(Fields.strs(single, "url")[1], "plain name.png", "unquoted single MFString") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local function code(text: string): string? + local _, e = Vrml.graph(text) + return e and e.code + end + t:eq(code("#VRML V2.0 utf8\nShape { geometry Box { }"), Err.CORRUPT, "unclosed node") + t:eq(code("#VRML V2.0 utf8\nShape { geometry USE X }"), Err.CORRUPT, "undefined USE") + t:eq(code("#VRML V2.0 utf8\nROUTE A.b TO"), Err.CORRUPT, "bad ROUTE") + t:eq(code("#VRML V2.0 utf8\nWorldInfo { title \"x }"), Err.TRUNCATED, "unterminated string") + t:eq(code("#VRML V1.0 ascii\n"), Err.UNSUPPORTED, "VRML 1.0") + t:eq(code("\224\0\0\1rest"), Err.UNSUPPORTED, "Fast Infoset X3D") + t:eq(code("#VRML V2.0 utf8\n" .. string.rep("Group { children ", 250)), Err.LIMIT, "nesting limit") + t:eq(code(""), Err.CORRUPT, "bad XML") + local _, e = Vrml.encode({} :: any) + t:eq(e and e.code, Err.ARG, "encode junk") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { + "#VRML V2.0 utf8\nPROTO P [ field SFFloat a 1 ] { Box { size IS a IS a } }\nDEF X P { a 2 } USE X ROUTE X.a TO X.b\n", + "#X3D V3.3 utf8\nPROFILE Full\nShape { geometry Extrusion { spine [ 0 0 0 0 1 0 1 1 1 ] crossSection [ 0 0 1 0 1 1 0 0 ] } }\n", + "", + } + t:fuzz("graph + build", function(b: buffer) + local g = Vrml.graph(b) + if g then + return Vrml.build(g) + end + return nil + end, samples, { mutations = 400 }) +end + +t:done() diff --git a/tests/model/_vrml_common.luau b/tests/model/_vrml_common.luau new file mode 100644 index 0000000..8ac98a0 --- /dev/null +++ b/tests/model/_vrml_common.luau @@ -0,0 +1,109 @@ +-- tests/model/_vrml_common: helpers shared by the VRML and X3D tests (tests/model/vrml.luau, x3d.luau): counts over +-- placed primitives (instances count, as the reference readers count them) and world bounds that include lines and +-- points (MeshOps.merge skips them). +local Types = require("@formats/Types") + +local C = {} + +export type Stats = { prims: number, unique: number, polys: number, lines: number, points: number, lo: { number }, hi: { number }, area: number } + +function C.near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +function C.stats(scene: any): Stats + local s: Stats = { prims = 0, unique = 0, polys = 0, lines = 0, points = 0, lo = { math.huge, math.huge, math.huge }, hi = { -math.huge, -math.huge, -math.huge }, area = 0 } + local seen = {} + for _, pl in Types.Scene.flatten(scene) do + local p = pl.primitive + s.prims += 1 + if not seen[p] then + seen[p] = true + s.unique += 1 + end + local P = p.attributes.POSITION + local nf = 0 + if p.mode == "polygons" then + nf = p.faces.count + elseif p.mode == "lines" then + s.lines += (if p.indices then p.indices.count else P.count) // 2 + elseif p.mode == "points" then + s.points += P.count + elseif p.mode == "triangle_strip" or p.mode == "triangle_fan" then + nf = math.max(0, (if p.indices then p.indices.count else P.count) - 2) + elseif p.mode == "line_strip" or p.mode == "line_loop" then + local n = if p.indices then p.indices.count else P.count + s.lines += if p.mode == "line_loop" then n else math.max(0, n - 1) + else + nf = (if p.indices then p.indices.count else P.count) // 3 + end + s.polys += nf + local m = pl.matrix + local get = assert(Types.Scene.reader(P)) + local w = {} + for v = 0, P.count - 1 do + local x, y, z = get(v, 0), get(v, 1), get(v, 2) + local wx, wy, wz = 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] + w[v] = { wx, wy, wz } + s.lo[1], s.lo[2], s.lo[3] = math.min(s.lo[1], wx), math.min(s.lo[2], wy), math.min(s.lo[3], wz) + s.hi[1], s.hi[2], s.hi[3] = math.max(s.hi[1], wx), math.max(s.hi[2], wy), math.max(s.hi[3], wz) + end + -- world area of the faces (fan-triangulated polygons) + local mode = p.mode + if mode == "triangles" or mode == "polygons" or mode == "triangle_strip" or mode == "triangle_fan" then + local ir = if p.indices then Types.Scene.reader(p.indices) else nil + local ind = function(i: number, _c: number): number + return if ir then ir(i, 0) else i + end + local count = if p.indices then p.indices.count else P.count + local function tri(a: number, b: number, c: number) + local A, B, Cc = w[a], w[b], w[c] + if A and B and Cc then + local e1 = { B[1] - A[1], B[2] - A[2], B[3] - A[3] } + local e2 = { Cc[1] - A[1], Cc[2] - A[2], Cc[3] - A[3] } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + s.area += math.sqrt(x * x + y * y + z * z) / 2 + end + end + if mode == "triangles" then + for t = 0, count // 3 - 1 do + tri(ind(t * 3, 0), ind(t * 3 + 1, 0), ind(t * 3 + 2, 0)) + end + elseif mode == "triangle_strip" then + for t = 0, count - 3 do + tri(ind(t, 0), ind(t + 1, 0), ind(t + 2, 0)) + end + elseif mode == "triangle_fan" then + for t = 1, count - 2 do + tri(ind(0, 0), ind(t, 0), ind(t + 1, 0)) + end + else + local at = 0 + local sizes = assert(Types.Scene.reader(p.faces)) + for f = 0, p.faces.count - 1 do + local n = sizes(f, 0) + for k = 1, n - 2 do + tri(ind(at, 0), ind(at + k, 0), ind(at + k + 1, 0)) + end + at += n + end + end + end + end + return s +end + +function C.boundsNear(lo: { number }, hi: { number }, wlo: { number }, whi: { number }, eps: number): boolean + for k = 1, 3 do + if not C.near(lo[k], wlo[k], eps) or not C.near(hi[k], whi[k], eps) then + return false + end + end + return true +end + +function C.fmt(lo: { number }, hi: { number }): string + return string.format("%.5g %.5g %.5g / %.5g %.5g %.5g", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3]) +end + +return C diff --git a/tests/model/pmx.luau b/tests/model/pmx.luau index e685dcf..6612131 100644 --- a/tests/model/pmx.luau +++ b/tests/model/pmx.luau @@ -257,7 +257,7 @@ do MeshOps.merge(s) end return s - end, samples, { mutations = 16, keepHeader = 17 }) + end, samples, { mutations = 16, keepHeader = 16 }) end t:done() diff --git a/tests/model/vrml.luau b/tests/model/vrml.luau new file mode 100644 index 0000000..5638328 --- /dev/null +++ b/tests/model/vrml.luau @@ -0,0 +1,410 @@ +-- model/vrml tests: assimp's WRL test models (HelloWorld, Wuson, the MotionCaptureROM animation), scenes and glTF +-- samples written by VTK's VRML exporter, and hand-written feature files (PROTO, DEF / USE, per-face colours and +-- separate indices, primitives, ElevationGrid, Extrusion, Switch, LOD, lights, viewpoints, ROUTE animations, +-- PixelTexture, Inline), against VTK's vtkVRMLImporter (polygons, points, world bounds where VTK's transforms are +-- right) and exact expectations; the writer: round trips of every case and of glTF sample models (world triangles, +-- materials, textures, cameras, lights, animation samples), VTK reading our files like the originals; errors; the +-- fuzz no-throw pass. Fixtures: tools/fixtures/vrml.py. +local T = require("@tests/T") +local F = require("@formats") +local Vrml = require("@formats/model/vrml") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Deflate = require("@formats/codecs/compress/Deflate") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/vrml_xcheck") + +local t = T.suite("vrml") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Vrml.decode(Bytes.reader(b), opts) +end + +t:eq(Vrml.name, "vrml", "name") +t:eq(Vrml.category, "model", "category") +t:check(Vrml.caps.decode and Vrml.caps.encode, "contract") + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { vtk = 0, bounds = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local s = C.stats(scene) + local v = c.vtk + if v.failed or v.actors == 0 then + checked.none += 1 + continue + end + checked.vtk += 1 + if not c.primitives then + t:eq(s.polys, v.polys, c.name .. ": polygons (VTK)") + end + t:eq(s.points, v.verts, c.name .. ": points (VTK)") + t:check((s.lines > 0) == (v.lines > 0), c.name .. ": lines (VTK)") + if c.vtkTransforms and v.min then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, if c.primitives then 2e-2 else 1e-5), c.name .. ": world bounds (VTK) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + checked.bounds += 1 + end +end +t:note("%d files: %d against VTK (%d with bounds), %d VTK cannot read", #Cases, checked.vtk, checked.bounds, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +local function prims(scene: any): { any } + local out = {} + for _, pl in Types.Scene.flatten(scene) do + table.insert(out, pl) + end + return out +end + +do + local hw = byName["assimp/HelloWorld.wrl"] + if hw then + t:eq(#hw.cameras, 1, "HelloWorld: viewpoint") + t:eq(hw.cameras[1].name, "ViewUpClose", "HelloWorld: viewpoint DEF name") + t:eq(hw.meta.source.title, "Hello World!", "HelloWorld: WorldInfo title") + t:eq(hw.meta.source.skipped.Text, 1, "HelloWorld: Text skipped") + local tex = hw.textures[1] + t:check(tex and tex.uri == "earth-topo.png" and tex.data and tex.mime == "image/png", "HelloWorld: texture from files") + t:eq(hw.materials[1].name, "MaterialOffWhite", "HelloWorld: material DEF name") + t:check(near(hw.materials[1].baseColor[1], 0.980392, 1e-6), "HelloWorld: diffuseColor") + end + local mc = byName["assimp/MotionCaptureROM.WRL"] + if mc then + t:eq(#mc.animations, 1, "MotionCaptureROM: one TimeSensor animation") + local a = mc.animations[1] + t:check(#a.channels >= 20, "MotionCaptureROM: channels " .. #a.channels) + local tmax = 0 + for _, ch in a.channels do + tmax = math.max(tmax, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4)) + end + t:check(near(tmax, 45.27, 1e-4), "MotionCaptureROM: key times x cycleInterval " .. tmax) + end + + -- PROTO expansion, DEF / USE of a Shape (one mesh, two nodes) + local pu = byName["feature/feat_proto_use.wrl"] + if pu then + local s = C.stats(pu) + t:eq(#pu.meshes, 3, "proto: meshes (two instances + a shared shape)") + t:eq(s.prims, 4, "proto: placed primitives") + t:check(C.boundsNear(s.lo, s.hi, { -1, -0.5, -0.5 }, { 3.5, 6, 0.5 }, 1e-4), "proto: bounds " .. C.fmt(s.lo, s.hi)) + local cols = {} + for _, m in pu.materials do + table.insert(cols, string.format("%g %g %g", m.baseColor[1], m.baseColor[2], m.baseColor[3])) + end + table.sort(cols) + t:eq(table.concat(cols, ", "), "0 1 0, 1 0 0", "proto: IS fields (instance value, default)") + end + + -- separate indices, per-face normals / colours, ccw FALSE, solid FALSE + local ix = byName["feature/feat_indices.wrl"] + if ix then + local p1 = ix.meshes[1].primitives[1] + t:eq(p1.attributes.POSITION.count, 8, "indices: corners split by normal / colour / texture index") + t:eq(p1.faces.count, 2, "indices: two quads") + local N, Col, Tx = p1.attributes.NORMAL, p1.attributes.COLOR_0, p1.attributes.TEXCOORD_0 + t:check(buffer.readf32(N.data, 8) == 1 and buffer.readf32(Col.data, 0) == 1 and buffer.readf32(Col.data, 8) == 0, "indices: face 1 normal / colour") + t:check(buffer.readf32(Tx.data, 4) == 1, "indices: t flipped (0 -> 1)") + -- ccw FALSE: the first face is written reversed (0 3 2 1) + t:eq(buffer.readu32(p1.indices.data, 4), 3, "indices: ccw FALSE reverses the winding") + local m = ix.materials[p1.material] + t:check(m.doubleSided and m.alphaMode == "blend" and near(m.baseColor[4], 0.75, 1e-6), "indices: solid FALSE, transparency") + t:check(m.extras.vrml.shininess == 0.5 and m.extras.vrml.specularColor[1] == 1, "indices: Phong terms in extras") + local p2 = ix.meshes[2].primitives[1] + t:eq(p2.attributes.POSITION.count, 5, "indices: per-vertex colour indices") + t:check(p2.material == nil, "indices: no appearance, no material") + end + + -- primitives: exact bounds, unit normals + local pr = byName["feature/feat_primitives.wrl"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -4.5, -2, -1.5 }, { 9, 2, 1.5 }, 1e-6), "primitives: bounds " .. C.fmt(s.lo, s.hi)) + local box = pr.meshes[1].primitives[1] + t:eq(box.attributes.POSITION.count, 24, "Box: 24 vertices") + t:eq(box.indices.count, 36, "Box: 12 triangles") + local sph = pr.meshes[2].primitives[1] + local ok = true + local P, N = sph.attributes.POSITION, sph.attributes.NORMAL + for v = 0, P.count - 1 do + for k = 0, 2 do + ok = ok and near(buffer.readf32(P.data, (v * 3 + k) * 4) / 1.5, buffer.readf32(N.data, (v * 3 + k) * 4), 1e-5) + end + end + t:check(ok, "Sphere: normals = position / radius") + -- outward winding: the Box's first triangle faces +z + local function faceNormal(prim: any, tri: number): { number } + local function p(i: number): { number } + local v = buffer.readu32(prim.indices.data, (tri * 3 + i) * 4) + return { buffer.readf32(prim.attributes.POSITION.data, v * 12), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 4), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 8) } + end + local a, b, c = p(0), p(1), p(2) + local e1, e2 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }, { c[1] - a[1], c[2] - a[2], c[3] - a[3] } + return { e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] } + end + t:check(faceNormal(box, 0)[3] > 0, "Box: counter-clockwise front faces") + local cyl = pr.meshes[4].primitives[1] + local last = cyl.indices.count // 3 - 1 + t:check(faceNormal(cyl, last)[2] < 0, "Cylinder: bottom cap faces down") + t:check(faceNormal(cyl, 0)[3] < 0 or faceNormal(cyl, 0)[1] ~= 0, "Cylinder: side faces outwards") + end + + local ge = byName["feature/feat_grid_extrusion.wrl"] + if ge then + local grid, ex = ge.meshes[1].primitives[1], ge.meshes[2].primitives[1] + t:eq(grid.attributes.POSITION.count, 12, "ElevationGrid: vertices") + t:eq(grid.faces.count, 6, "ElevationGrid: quads") + t:eq(ex.attributes.POSITION.count, 16, "Extrusion: closed cross section shares its seam") + t:eq(ex.faces.count, 14, "Extrusion: sides + caps") + local s = C.stats(ge) + t:check(near(s.hi[2], 3, 1e-6) and near(s.hi[3], 4, 1e-6), "ElevationGrid: heights and spacing") + end + + local sc = byName["feature/feat_scene.wrl"] + if sc then + t:eq(sc.meta.source.title, "feature scene", "scene: title") + t:eq(#sc.cameras, 1, "scene: viewpoint") + t:check(near(sc.cameras[1].yfov, 0.9, 1e-9) and sc.cameras[1].name == "Cam", "scene: fieldOfView") + local types = {} + for _, l in sc.lights do + types[l.type] = l + end + t:check(types.directional and types.point and types.spot, "scene: three light types") + t:check(types.point.range == 10 and near(types.spot.outerCone, 0.6, 1e-9) and near(types.spot.innerCone, 0.4, 1e-9), "scene: radius, cones") + -- the directional light's node turns -z onto its direction (0, -1, -1) + for _, n in sc.nodes do + if n.light and sc.lights[n.light].type == "directional" then + local m = Mat4.fromQuat(n.rotation) + local x, y, z = Mat4.point(m, 0, 0, -1) + t:check(near(x, 0, 1e-6) and near(y, -math.sqrt(0.5), 1e-6) and near(z, -math.sqrt(0.5), 1e-6), "scene: light direction") + end + end + t:eq(#sc.animations, 1, "scene: animation") + local a = sc.animations[1] + t:eq(a.name, "Clock", "scene: animation named after its TimeSensor") + t:eq(#a.channels, 2, "scene: translation + rotation channels") + local tr = a.channels[1].path == "translation" and a.channels[1] or a.channels[2] + t:check(near(buffer.readf32(tr.input.data, 8), 4, 1e-6), "scene: key 1 x cycleInterval 4") + -- translation keys move the outer node: key + center + t:check(near(buffer.readf32(tr.output.data, 12), 1, 1e-6) and near(buffer.readf32(tr.output.data, 16), 2, 1e-6), "scene: translation key + center") + -- PixelTexture: the first row of the file is the bottom one + local img + for _, tex in sc.textures do + img = img or tex.image + end + t:check(img and img.width == 2 and buffer.readu8(img.pixels, 2) == 255 and buffer.readu8(img.pixels, 8) == 255 and buffer.readu8(img.pixels, 9) == 0, "scene: PixelTexture pixels") + -- Switch whichChoice 1: the sphere only; LOD: the first level; Inline: part.wrl + local s = C.stats(sc) + t:check(near(s.lo[2], -3.1, 1e-6), "scene: Inline file placed") + -- center / scaleOrientation: the line set's first point (0, 0, 0) under T C R SR S -SR -C + local mover = nil + for _, pl in prims(sc) do + if pl.primitive.mode == "lines" then + mover = pl + end + end + if mover then + local sr = Mat4.axisAngle(0, 0, 1, math.deg(0.5)) + local m = Mat4.mul(Mat4.translation(1, 0, 0), Mat4.mul(Mat4.fromQuat(sr), Mat4.mul(Mat4.scaling(1, 2, 1), Mat4.mul(Mat4.fromQuat({ -sr[1], -sr[2], -sr[3], sr[4] }), Mat4.translation(-1, 0, 0))))) + local ok = true + for k = 1, 16 do + ok = ok and near(mover.matrix[k], m[k], 1e-6) + end + t:check(ok, "scene: Transform center / scaleOrientation") + end + t:eq(sc.meta.unit, 1, "scene: metres") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds " .. C.fmt(sa.lo, sa.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(sa.area, sb.area, 1e-4), string.format("%s: area %.6g / %.6g", label, sa.area, sb.area)) + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") +end + +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + local files = {} + local out, err = Vrml.encode(a, { files = files, name = "rt.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if out then + local b, e2 = decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": re-decode: " .. tostring(e2)) + if b then + compare(a, b, c.name .. " (round trip)") + t:eq(#b.animations, #a.animations, c.name .. " (round trip): animations") + rt += 1 + end + end + end +end + +-- glTF samples through VRML: world triangles, materials, textures, cameras, lights, animation samples +local gltfScenes = {} +for i, c in GltfCases do + local g = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if not g then + continue + end + gltfScenes[i] = g + local files = {} + local out, err = Vrml.encode(g, { files = files, name = "model.wrl" }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + if not out then + continue + end + local b = decode(out, { files = files }) + t:check(b, c.name .. ": decode our VRML") + if not b then + continue + end + local ga = C.stats(g) + local sb = C.stats(b) + t:check(C.boundsNear(ga.lo, ga.hi, sb.lo, sb.hi, 1e-5), c.name .. ": bounds through VRML " .. C.fmt(ga.lo, ga.hi) .. " vs " .. C.fmt(sb.lo, sb.hi)) + t:check(near(ga.area, sb.area, 1e-4), c.name .. ": area through VRML") + t:eq(sb.points, ga.points, c.name .. ": points through VRML") + t:eq(#b.cameras, #g.cameras, c.name .. ": cameras through VRML") + for k, tex in g.textures do + local t2 = b.textures[k] + if tex.data and t2 then + t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), c.name .. ": texture " .. k .. " bytes") + end + end + -- animations: the translation / rotation / scale channels, sampled at their keys + local want = 0 + for _, a in g.animations do + for _, ch in a.channels do + if ch.path ~= "weights" then + want += 1 + end + end + end + local got = 0 + for _, a in b.animations do + got += #a.channels + end + t:eq(got, want, c.name .. ": animation channels through VRML") + rt += 1 +end +t:note("%d round trips", rt) + +-- VTK reads our files like the originals +local xc = 0 +for _, x in Xcheck do + local v = x.vtk + local src = if x.case then scenes[x.case] else (if x.gltf then gltfScenes[x.gltf] else nil) + local srcCase = if x.case then Cases[x.case] else nil + if src and not v.failed and v.actors > 0 then + local s = C.stats(src) + if not (srcCase and srcCase.primitives) then + -- our IndexedFaceSets keep polygons; VTK counts them + t:eq(v.polys, s.polys, x.name .. ": polygons (VTK reads our file)") + end + t:eq(v.verts, s.points, x.name .. ": points (VTK reads our file)") + if x.vtkTransforms and v.min and s.lo[1] <= s.hi[1] then + t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, 1e-4), x.name .. ": bounds (VTK reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max)) + end + xc += 1 + end +end +t:note("%d of our files read by VTK", xc) + +-- ------------------------------------------------------------------------------------------------ api, options, errors +do + local text = Cases[1].data + t:eq(F.detect(text), "vrml", "F.detect") + local s = F.load(text, { files = Cases[1].files }) + t:check(s and s.meta.source.format == "vrml", "F.load") + local gz = Deflate.gzip(text) + local sg = decode(gz :: buffer) + t:check(sg and #sg.meshes == #s.meshes, "gzipped .wrz") + local tri = decode(Cases[1].data) + t:check(tri and tri.meshes[1].primitives[1].mode == "triangles", "triangulated by default") + local seg = decode(Cases[1].data, { segments = 8 }) + t:check(seg and seg.meshes[1].primitives[1].attributes.POSITION.count < s.meshes[1].primitives[1].attributes.POSITION.count, "segments option") + local _, e1 = decode("#VRML V1.0 ascii\nSeparator { }") + t:check(e1 and e1.code == Err.UNSUPPORTED, "VRML 1.0: " .. tostring(e1)) + local _, e2 = decode("#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 }") + t:check(e2 and e2.code == Err.CORRUPT, "unclosed node: " .. tostring(e2)) + local _, e3 = decode("#VRML V2.0 utf8\nShape { appearance USE Nothing }") + t:check(e3 and e3.code == Err.CORRUPT, "USE of an undefined name: " .. tostring(e3)) + local _, e4 = decode('#VRML V2.0 utf8\nWorldInfo { title "open') + t:check(e4 and e4.code == Err.TRUNCATED, "unterminated string: " .. tostring(e4)) + local deep = "#VRML V2.0 utf8\n" .. string.rep("Group { children [ ", 300) .. string.rep("] } ", 300) + local _, e5 = decode(deep) + t:check(e5 and e5.code == Err.LIMIT, "nesting limit: " .. tostring(e5)) + local _, e6 = decode("#VRML V2.0 utf8\nShape { geometry ElevationGrid { xDimension 5000 zDimension 5000 } }", { maxVertices = 1000 }) + t:check(e6 and e6.code == Err.LIMIT, "maxVertices: " .. tostring(e6)) + local _, e7 = Vrml.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + -- a quad written as one polygon and read back as one + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local q = decode(Vrml.encode(quad) :: buffer, { triangulate = false }) + t:check(q and q.meshes[1].primitives[1].faces.count == 1 and q.nodes[1].name == "quad", "a quad stays one polygon, names kept") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Vrml.decode(Bytes.reader(b), { files = {} }) + if s then + Vrml.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tests/model/x3d.luau b/tests/model/x3d.luau new file mode 100644 index 0000000..6a04f64 --- /dev/null +++ b/tests/model/x3d.luau @@ -0,0 +1,308 @@ +-- model/x3d tests: assimp's X3D / X3DV / X3DB test models, scenes and glTF samples written by VTK's X3D exporter and +-- by assimp's X3D exporter, and hand-written feature files (the X3D triangle / quad / line sets, ColorRGBA, +-- ProtoDeclare / ProtoInstance with SFNode defaults, PhysicalMaterial, UnlitMaterial, OrthoViewpoint, ROUTE +-- animation, UNIT, the classic encoding's header statements), against assimp's X3D reader (meshes, faces, materials, +-- world bounds) and exact expectations; .x3dv against the same model as .x3d; the writer (XML and classic): round +-- trips, and assimp reading our X3D like the originals; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x3d.py. +local T = require("@tests/T") +local F = require("@formats") +local X3d = require("@formats/model/x3d") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local C = require("@tests/model/_vrml_common") +local Cases = require("@tests/gen/x3d_cases") +local VrmlCases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local Xcheck = require("@tests/gen/x3d_xcheck") +local Gltf = require("@formats/model/gltf") +local Vrml = require("@formats/model/vrml") + +local t = T.suite("x3d") +local near = C.near + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return X3d.decode(Bytes.reader(b), opts) +end + +t:eq(X3d.name, "x3d", "name") +t:eq(X3d.category, "model", "category") +t:check(X3d.caps.decode and X3d.caps.encode, "contract") + +-- assimp's own quirks (its reading is not the specification's): USE'd groups lose their parents' transforms; its X3D +-- exporter writes points and lines as 1- / 2-vertex faces (not valid IndexedFaceSet faces, dropped here) +local QUIRK = { ["assimp/X3D/ComputerKeyboard.x3d"] = "all", ["assimp-export/assimp_MeshPrimitiveModes.x3d"] = "all" } + +-- ------------------------------------------------------------------------------------------------ reference files +local scenes, byName = {}, {} +local checked = { assimp = 0, none = 0 } +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + if string.find(c.name, "%.x3db$") then + t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": binary X3D is UNSUPPORTED: " .. tostring(err)) + continue + end + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + scenes[i], byName[c.name] = scene, scene + local a = c.assimp + -- (VTK's exporter leaves out: assimp then reads nothing) + local unclosed = a.meshes == 0 and not string.find(c.data, "", 1, true) + if a.skip or a.failed or unclosed or string.find(c.name, "^feature/") then + checked.none += 1 + continue + end + local s = C.stats(scene) + local quirk = QUIRK[c.name] + if quirk ~= "all" then + if quirk ~= "counts" then + t:eq(s.prims, a.meshes, c.name .. ": meshes (assimp: one per placed shape)") + end + if not c.primitives and quirk ~= "counts" then + t:eq(s.polys + s.lines + s.points, a.faces, c.name .. ": faces (assimp)") + end + t:check(#scene.materials <= a.materials, c.name .. ": materials (assimp counts one per use)") + if a.min then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, if c.primitives then 5e-3 else 1e-5), c.name .. ": world bounds (assimp) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + end + checked.assimp += 1 +end +t:note("%d files: %d against assimp, %d without a reference", #Cases, checked.assimp, checked.none) + +-- ------------------------------------------------------------------------------------------------ exact expectations +do + local kb = byName["assimp/X3D/ComputerKeyboard.x3d"] + if kb then + local s = C.stats(kb) + t:eq(#kb.meshes, 3, "keyboard: three extrusions (the keys are USE'd)") + t:check(s.prims > 50, "keyboard: every USE placed: " .. s.prims) + t:eq(#kb.animations, 1, "keyboard: the push animation") + t:check(#kb.animations[1].channels == s.prims - 2, "keyboard: one channel per escape-button instance") + t:check(near(s.hi[3], 0.980018, 1e-5) and near(s.lo[2], -0.0002, 1e-3), "keyboard: the base under its rotation") + end + local hw, hv = byName["assimp/X3D/HelloWorld.x3d"], byName["assimp/X3DV/HelloWorld.x3dv"] + if hw and hv then + local a, b = C.stats(hw), C.stats(hv) + t:check(a.polys == b.polys and C.boundsNear(a.lo, a.hi, b.lo, b.hi, 1e-9), ".x3dv = .x3d: geometry") + t:eq(hv.materials[1].baseColor[2], hw.materials[1].baseColor[2], ".x3dv = .x3d: material") + t:check(hv.textures[1].data and hw.textures[1].data, ".x3dv / .x3d: texture from files") + t:eq(hv.meta.source.profile, "Immersive", ".x3dv: PROFILE") + t:eq(hw.meta.source.profile, "Immersive", ".x3d: profile") + t:eq(hv.meta.source.meta.title, "HelloWorld.x3d", ".x3dv: META") + t:eq(hw.meta.source.meta.creator, "Don Brutzman", ".x3d: head meta") + end + local ls = byName["assimp/X3D/IndexedLineSet.x3d"] + if ls then + local p = ls.meshes[1].primitives[1] + t:check(p.mode == "lines" and p.indices.count == 8, "IndexedLineSet: a closed polyline as 4 segments") + t:check(ls.materials[1].emissive[1] == 1, "IndexedLineSet: emissive colour") + end + + local sets = byName["feature/feat_sets.x3d"] + if sets then + local m = sets.meshes + local function tris(k: number): number + local p = m[k].primitives[1] + return if p.mode == "polygons" then p.faces.count else p.indices.count // 3 + end + t:eq(tris(1), 2, "IndexedTriangleSet") + local col = m[1].primitives[1].attributes.COLOR_0 + t:check(col and col.components == 4 and buffer.readf32(col.data, (2 * 4 + 3) * 4) == 0.5, "ColorRGBA alpha") + t:check(sets.materials[m[1].primitives[1].material].doubleSided, "solid false") + t:eq(tris(2), 3, "TriangleFanSet fanCount") + t:eq(tris(3), 3, "IndexedTriangleStripSet runs") + t:check(m[4].primitives[1].faces.count == 1 and m[4].primitives[1].indices.count == 4, "IndexedQuadSet: one quad") + t:eq(tris(5), 2, "TriangleSet") + t:check(m[6].primitives[1].mode == "lines" and m[6].primitives[1].indices.count == 6, "LineSet vertexCount") + -- strips alternate their winding: every triangle of the strip faces +z + local p = m[3].primitives[1] + local ok = true + local P = p.attributes.POSITION + local function v(i: number): (number, number) + local k = buffer.readu32(p.indices.data, i * 4) + return buffer.readf32(P.data, k * 12), buffer.readf32(P.data, k * 12 + 4) + end + local at = 0 + for f = 0, p.faces.count - 1 do + local ax, ay = v(at) + local bx, by = v(at + 1) + local cx, cy = v(at + 2) + ok = ok and (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > 0 + at += buffer.readu32(p.faces.data, f * 4) + end + t:check(ok, "IndexedTriangleStripSet: counter-clockwise triangles") + end + + local pr = byName["feature/feat_proto.x3d"] + if pr then + local s = C.stats(pr) + t:check(C.boundsNear(s.lo, s.hi, { -1.1, -2, -0.5 }, { 1.1, 5, 0.5 }, 1e-6), "protos: instances placed and sized " .. C.fmt(s.lo, s.hi)) + t:eq(pr.meta.unit, 0.01, "UNIT length") + t:eq(pr.meta.source.meta.title, "protos", "head meta") + local kinds = {} + for _, m in pr.materials do + if m.extensions and m.extensions.KHR_materials_unlit then + kinds.unlit = m + elseif m.metallic == 0.25 then + kinds.physical = m + elseif m.baseColor[3] == 1 and m.baseColor[1] == 0 then + kinds.default = m + end + end + t:check(kinds.physical and kinds.physical.roughness == 0.75, "PhysicalMaterial") + t:check(kinds.unlit and kinds.unlit.baseColor[2] == 1, "UnlitMaterial") + t:check(kinds.default ~= nil, "SFNode field default (the proto's appearance)") + t:eq(#pr.materials, 3, "the default appearance is shared by both instances") + local cam = pr.cameras[1] + t:check(cam and cam.type == "orthographic" and cam.xmag == 2 and cam.ymag == 1, "OrthoViewpoint") + local a = pr.animations[1] + t:check(a and a.name == "Clock" and #a.channels == 1 and a.channels[1].path == "rotation", "ROUTE elements -> animation") + t:check(a and near(buffer.readf32(a.channels[1].input.data, 8), 2, 1e-6), "key times x cycleInterval") + -- quaternion keys stay on one hemisphere (0, pi, 2 pi about y) + local q = a and a.channels[1].output + t:check(q and buffer.readf32(q.data, 2 * 16 + 12) < 0, "rotation keys continuous") + end + local cl = byName["feature/feat_classic.x3dv"] + if cl then + local s = C.stats(cl) + t:check(C.boundsNear(s.lo, s.hi, { 1, 2, 3 }, { 2, 3, 4 }, 1e-6), "classic: DEF Transform") + t:eq(cl.meta.unit, 0.001, "classic: UNIT") + t:eq(cl.meta.source.components[1], "Geometry2D:1", "classic: COMPONENT") + t:eq(cl.meta.source.meta.title, "classic", "classic: META") + t:eq(cl.meshes[1].primitives[1].attributes.COLOR_0.components, 4, "classic: ColorRGBA") + end +end + +-- ------------------------------------------------------------------------------------------------ writer +local function compare(a: any, b: any, label: string) + local sa, sb = C.stats(a), C.stats(b) + t:eq(sb.prims, sa.prims, label .. ": placed primitives") + t:eq(sb.polys, sa.polys, label .. ": faces") + t:eq(sb.lines, sa.lines, label .. ": line segments") + t:eq(sb.points, sa.points, label .. ": points") + if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then + t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds") + t:check(near(sa.area, sb.area, 1e-4), label .. ": area") + end + t:eq(#b.materials, #a.materials, label .. ": materials") + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") + t:eq(#b.animations, #a.animations, label .. ": animations") + for k, cam in a.cameras do + t:eq(b.cameras[k].type, cam.type, label .. ": camera type") + end +end +local rt = 0 +for i, c in Cases do + local a = scenes[i] + if a then + for _, enc in { "xml", "x3dv" } do + local files = {} + local out, err = X3d.encode(a, { files = files, encoding = enc :: any }) + t:check(out, c.name .. ": encode " .. enc .. ": " .. tostring(err)) + local b = out and decode(out, { files = files, triangulate = false }) + t:check(b, c.name .. ": decode our " .. enc) + if b then + compare(a, b, c.name .. " (" .. enc .. ")") + rt += 1 + end + end + end +end +t:note("%d round trips", rt) + +-- assimp reads our X3D like the source +local sources: { [string]: { any } } = { xcase = {}, wcase = {}, xgltf = {} } +for i, c in Cases do + sources.xcase[i] = { scenes[i], c } +end +for i, c in VrmlCases do + sources.wcase[i] = { Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }), c } +end +for i, c in GltfCases do + sources.xgltf[i] = { Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }), c } +end +-- assimp loses its place in the tree after an empty (a leaf node: an empty, a locator) +local function hasEmpty(scene: any): boolean + for _, n in scene.nodes do + if #n.children == 0 and not n.mesh and not n.camera and not n.light then + return true + end + end + return false +end +local xc, skipped = 0, 0 +for _, x in Xcheck do + local a = x.assimp + local kind = if x.xcase then "xcase" elseif x.wcase then "wcase" else "xgltf" + local src = sources[kind][x[kind]] + if src and src[1] and (a.failed or a.meshes == 0) and hasEmpty(src[1]) then + skipped += 1 + elseif src and src[1] and not a.failed then + local s = C.stats(src[1]) + t:eq(a.meshes, s.prims, x.name .. ": meshes (assimp reads our file)") + t:eq(a.faces, s.polys + s.lines + s.points, x.name .. ": faces (assimp reads our file)") + -- (shared meshes are written once and USE'd: assimp places USE'd nodes without their parents' transforms) + -- (MotionCaptureROM: assimp misplaces this deep hierarchy; an independent evaluation of our file's transforms + -- agrees with ours) + local deep = src[2].name == "assimp/MotionCaptureROM.WRL" + if a.min and s.lo[1] <= s.hi[1] and s.prims == s.unique and not deep then + t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, 1e-4), x.name .. ": bounds (assimp reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max)) + end + xc += 1 + elseif src and src[1] then + t:check(false, x.name .. ": assimp cannot read our file (" .. src[2].name .. ")") + end +end +t:note("%d of our files read by assimp (%d skipped: empty nodes)", xc, skipped) + +-- ------------------------------------------------------------------------------------------------ api, errors +do + local hw = Cases[2] + t:eq(F.detect(hw.data), "x3d", "F.detect .x3d") + t:eq(F.detect(Cases[5].data), "x3d", "F.detect .x3dv") + local s = F.load(hw.data, { files = hw.files }) + t:check(s and s.meta.source.format == "x3d", "F.load") + local x3dv = F.save(s, nil, { format = "x3dv" }) + t:check(x3dv and buffer.readstring(x3dv, 0, 5) == "#X3D ", "F.save format x3dv: the classic encoding") + local xml = F.save(s, nil, { format = "x3d" }) + t:check(xml and string.find(buffer.tostring(xml), "") + t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "mismatched XML: " .. tostring(e1)) + local _, e2 = decode("") + t:check(e2 and e2.code == Err.CORRUPT, "not X3D: " .. tostring(e2)) + -- VTK leaves the root element open: read anyway + local open = decode("\n") + t:check(open and #open.meshes == 1, "an unclosed root (VTK's exporter)") + local _, e3 = X3d.encode({} :: any) + t:check(e3 and e3.code == Err.ARG, "encode junk") + -- containerField and USE in XML + local u = decode([[ + + ]]) + local us = u and C.stats(u) + t:check(us and #u.meshes == 2 and us.prims == 3 and near(us.hi[1], 6, 1e-9) and near(us.hi[2], 2, 1e-6), "USE / containerField / Switch in XML") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = X3d.decode(Bytes.reader(b), { files = {} }) + if s then + X3d.encode(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/_vrml_encode.luau b/tools/fixtures/_vrml_encode.luau new file mode 100644 index 0000000..f3cabba --- /dev/null +++ b/tools/fixtures/_vrml_encode.luau @@ -0,0 +1,54 @@ +-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML / +-- X3D case and glTF sample with our readers and writes it back with our writers, printing "\t" lines for +-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_.wrl, gltf_.wrl, xcase_.x3d, xgltf_.x3d. +local Vrml = require("@formats/model/vrml") +local X3d = require("@formats/model/x3d") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/vrml_cases") +local GltfCases = require("@tests/gen/vrml_gltf") +local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +local function both(scene: any, wrl: string, x3d: string) + local a = Vrml.encode(scene) + if a then + print(wrl .. "\t" .. hex(a)) + end + local b = X3d.encode(scene) + if b then + print(x3d .. "\t" .. hex(b)) + end +end + +for i, c in Cases do + local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i)) + end +end +for i, c in GltfCases do + local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i)) + end +end +if ok and type(X3dCases) == "table" then + for i, c in X3dCases do + local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i)) + end + end +end diff --git a/tools/fixtures/_vrml_ref.py b/tools/fixtures/_vrml_ref.py new file mode 100644 index 0000000..2a0b137 --- /dev/null +++ b/tools/fixtures/_vrml_ref.py @@ -0,0 +1,241 @@ +# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and +# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files. +# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter) +# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes) +# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate +# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture +import json + +VTK_READ = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() + +def read(p): + imp = vtk.vtkVRMLImporter(); imp.SetFileName(p) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw) + imp.Update() + acts = imp.GetRenderer().GetActors(); acts.InitTraversal() + out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0} + lo, hi = [1e30] * 3, [-1e30] * 3 + for i in range(acts.GetNumberOfItems()): + a = acts.GetNextActor() + m = a.GetMapper() + if not m: + continue + m.Update() + d = m.GetInput() + if d is None or d.GetNumberOfPoints() == 0: + continue + out["actors"] += 1 + out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips() + out["lines"] += d.GetNumberOfLines() + out["verts"] += d.GetNumberOfVerts() + out["points"] += d.GetNumberOfPoints() + # tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds) + mat = a.GetMatrix() + pts = d.GetPoints() + for j in range(d.GetNumberOfPoints()): + p = pts.GetPoint(j) + w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0)) + for k in range(3): + lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k]) + if out["actors"]: + out["min"], out["max"] = lo, hi + return out + +# one child process per file: vtkVRMLImporter crashes on some valid files +res = [] +for p in json.loads(sys.stdin.read()): + r, w = os.pipe() + pid = os.fork() + if pid == 0: + os.close(r) + try: + data = json.dumps(read(p)) + except Exception: + data = json.dumps({"failed": True}) + os.write(w, data.encode()) + os._exit(0) + os.close(w) + chunks = [] + while True: + b = os.read(r, 65536) + if not b: + break + chunks.append(b) + os.close(r) + _, status = os.waitpid(pid, 0) + try: + res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True}) + except ValueError: + res.append({"failed": True}) +print("RESULT " + json.dumps(res)) +""" + +VTK_EXPORT = r""" +import json, os, sys, vtk +vtk.vtkObject.GlobalWarningDisplayOff() +args = json.loads(sys.stdin.read()) +out, gltfs = args["out"], args["gltf"] +made = [] + +def export(ren, name): + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren) + ren.ResetCamera() + w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write() + x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write() + made.append(name) + +def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False): + m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort()) + if not scalars: + m.ScalarVisibilityOff() + a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale) + a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2]) + if color: + a.GetProperty().SetColor(*color) + return a + +# 1. primitives as polygon meshes, transformed, coloured, one with point scalars +ren = vtk.vtkRenderer() +s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8) +ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1))) +c = vtk.vtkConeSource(); c.SetResolution(12) +ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3))) +cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5) +ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9))) +keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()] +el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0) +ren.AddActor(actor(el, (4, 4, 0), scalars=True)) +light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8) +ren.AddLight(light) +export(ren, "vtk_shapes") + +# 2. lines and points +ren = vtk.vtkRenderer() +ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5) +ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0))) +pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0) +ren.AddActor(actor(pts)) +ren.AddActor(actor(keep[2], (0, 0, -4))) +export(ren, "vtk_lines_points") + +# 3. a textured plane (PixelTexture) and a strip mesh +ren = vtk.vtkRenderer() +pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2) +img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0) +img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update() +tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort()) +a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex) +ren.AddActor(a) +strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort()) +ren.AddActor(actor(strip, (0, 3, 0))) +export(ren, "vtk_texture_strips") + +# 4. glTF sample models through VTK's glTF importer +for g in gltfs: + try: + imp = vtk.vtkGLTFImporter(); imp.SetFileName(g) + rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update() + name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0] + export(imp.GetRenderer(), name) + except Exception: + pass +print("RESULT " + json.dumps(made)) +""" + + +def vtk_xform_ok(data): + """False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation""" + import re + return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data) + + +def _run(ctx, code, arg): + out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace") + for line in out.split("\n"): + if line.startswith("RESULT "): + return json.loads(line[7:]) + raise RuntimeError("vtk script printed no result") + + +def vtk_read(ctx, paths): + return _run(ctx, VTK_READ, paths) if paths else [] + + +def vtk_export(ctx, outdir, gltfs): + return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs}) + + +FEATURES = { + "feat_proto_use.wrl": """#VRML V2.0 utf8 +PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] { + Transform { translation IS where children Shape { + appearance Appearance { material Material { diffuseColor IS col } } + geometry Box { size IS size } } } +} +DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 } +Brick { where 3 0 0 } +Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet { + coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] } +Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S } +""", + "feat_indices.wrl": """#VRML V2.0 utf8 +# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE +Shape { + appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } } + geometry IndexedFaceSet { + solid FALSE ccw FALSE + coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] } + coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ] + normal Normal { vector [ 0 0 1, 0 -1 0 ] } + normalPerVertex FALSE normalIndex [ 0 1 ] + color Color { color [ 1 0 0, 0 0 1 ] } + colorPerVertex FALSE + texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] } + texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ] + } +} +Shape { geometry IndexedFaceSet { + coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] } + coordIndex [ 0 1 2 -1 0 2 3 ] + color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } } +""", + "feat_primitives.wrl": """#VRML V2.0 utf8 +Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } } +Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } } +Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } } +Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } } +""", + "feat_grid_extrusion.wrl": """#VRML V2.0 utf8 +Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2 + height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } } +Transform { translation 6 0 0 children Shape { geometry Extrusion { + crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } } +""", + "feat_scene.wrl": """#VRML V2.0 utf8 +WorldInfo { title "feature scene" info [ "made for formats-luau" ] } +DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" } +DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 } +DEF Bulb PointLight { location 1 2 3 radius 10 } +DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 } +DEF Sw Switch { whichChoice 1 choice [ + Shape { geometry Box { } } + Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] } +LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] } +DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [ + Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } } + Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] } +DEF Clock TimeSensor { cycleInterval 4 loop TRUE } +DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] } +DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] } +ROUTE Clock.fraction_changed TO Path.set_fraction +ROUTE Clock.fraction_changed TO Turn.set_fraction +ROUTE Path.value_changed TO Mover.set_translation +ROUTE Turn.value_changed TO Mover.set_rotation +Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } } +Inline { url [ "part.wrl" ] } +""", +} +# the Inline target of feat_scene.wrl +INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"} diff --git a/tools/fixtures/vrml.py b/tools/fixtures/vrml.py new file mode 100644 index 0000000..c5673a2 --- /dev/null +++ b/tools/fixtures/vrml.py @@ -0,0 +1,99 @@ +# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source, +# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's +# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as +# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back +# by VTK. +# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) } +# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files } +# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk } +import importlib.util, os, re + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py", + "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"] + +GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest", + "NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def primitives(data): + return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data)) + + +def gltf_picks(ctx): + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in GLTF: + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in ("glTF", "glTF-Embedded", "glTF-Binary"): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if mains: + picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + return picks + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + tmp = M.tempdir() + cases = [] + src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL") + for f in sorted(os.listdir(src)): + if f.lower().endswith(".wrl"): + files = {} + if f == "HelloWorld.wrl": + files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files}) + picks = gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]): + cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}}) + for name, text in sorted(R.FEATURES.items()): + p = os.path.join(tmp, name) + with open(p, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)}) + for name, text in R.INLINE.items(): + with open(os.path.join(tmp, name), "w") as f: + f.write(text) + refs = R.vtk_read(ctx, [c["path"] for c in cases]) + for c, v in zip(cases, refs): + c["data"] = open(c["path"], "rb").read() + c["vtk"] = v + c["primitives"] = primitives(c["data"]) + c["vtkTransforms"] = R.vtk_xform_ok(c["data"]) + del c["path"] + ctx.emit("vrml_cases", cases) + for p in picks: + del p["path"] + ctx.emit("vrml_gltf", picks) + + # VTK reads our output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".wrl")) + for name, data in ours.items(): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names]) + out = [] + for n, v in zip(names, refs): + e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])} + m = re.match(r"(case|gltf)_(\d+)\.wrl$", n) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("vrml_xcheck", out) diff --git a/tools/fixtures/x3d.py b/tools/fixtures/x3d.py new file mode 100644 index 0000000..0826081 --- /dev/null +++ b/tools/fixtures/x3d.py @@ -0,0 +1,135 @@ +# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs +# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models +# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference +# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's +# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp. +# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) } +# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp } +import importlib.util, os, re, subprocess + +INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf", + "tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py", + "tools/fixtures/_vrml_encode.luau"] + +FEATURES = { + "feat_sets.x3d": """ + + + + + + + + + + +""", + "feat_proto.x3d": """ + + + + + + + + + + + + + + + + + + + + + + +""", + "feat_classic.x3dv": """#X3D V3.3 utf8 +PROFILE Interchange +COMPONENT Geometry2D:1 +META "title" "classic" +UNIT length millimetre 0.001 +DEF Root Transform { translation 1 2 3 children [ + Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } } + geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] + color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } } + Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } } +] } +""", +} + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def reference(ctx, M, Fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + if not a.get("failed"): + a.pop("min", None) + a.pop("max", None) + a.update(Fbx.assimp_extra(ctx, path)) + a.update(Fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = load(ctx, "_model_ref") + Fbx = load(ctx, "fbx") + R = load(ctx, "_vrml_ref") + V = load(ctx, "vrml") + tmp = M.tempdir() + cases = [] + root = os.path.join(Fbx.assimp_src(ctx), "test", "models") + for sub in ("X3D", "X3DV", "X3DB"): + d = os.path.join(root, sub) + for f in sorted(os.listdir(d)): + if f.lower().endswith((".x3d", ".x3dv", ".x3db")): + files = {} + if f.startswith("HelloWorld"): + files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read() + cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files}) + picks = V.gltf_picks(ctx) + for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]): + cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}}) + for p in picks: + out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d") + try: + ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"]) + except subprocess.CalledProcessError: + continue + cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])}) + for name, text in sorted(FEATURES.items()): + path = os.path.join(tmp, name) + with open(path, "w") as f: + f.write(text) + cases.append({"name": "feature/" + name, "path": path, "files": {}}) + for c in cases: + c["data"] = open(c["path"], "rb").read() + c["primitives"] = V.primitives(c["data"]) + c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True} + del c["path"] + ctx.emit("x3d_cases", cases) + + # assimp reads our X3D output + ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau") + xtmp = M.tempdir() + out = [] + for name in sorted(n for n in ours if n.endswith(".x3d")): + path = os.path.join(xtmp, name) + with open(path, "wb") as f: + # assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires) + f.write(re.sub(rb'url=""([^&"]*)""', rb'url="\1"', ours[name])) + e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)} + m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name) + if m: + e[m.group(1)] = int(m.group(2)) + out.append(e) + ctx.emit("x3d_xcheck", out) From ef460955d4a792af02a4d49552102a07213d8882 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:58:20 -0500 Subject: [PATCH 43/54] ws-tex: image/xbm + image/xpm (read + write) XBM: X11 / X10 arrays, hex / decimal / octal, hotspot; xbmtopbm reference (netpbm, ImageMagick, Pillow files). XPM: XPM 3 + XPM 2, c / g / g4 / m keys, hex depths, None, CSS / X11 names + grey0..100 (image/xpm/Names); ImageMagick reference. --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 24 +++ src/Formats/image/xbm/init.luau | 161 ++++++++++++++++++ src/Formats/image/xpm/Names.luau | 57 +++++++ src/Formats/image/xpm/init.luau | 271 +++++++++++++++++++++++++++++++ tests/image/xbm.luau | 43 +++++ tests/image/xpm.luau | 44 +++++ tools/fixtures/_tex_encode.luau | 4 + tools/fixtures/xbm.py | 43 +++++ tools/fixtures/xpm.py | 58 +++++++ 10 files changed, 707 insertions(+) create mode 100644 src/Formats/image/xbm/init.luau create mode 100644 src/Formats/image/xpm/Names.luau create mode 100644 src/Formats/image/xpm/init.luau create mode 100644 tests/image/xbm.luau create mode 100644 tests/image/xpm.luau create mode 100644 tools/fixtures/xbm.py create mode 100644 tools/fixtures/xpm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 79f098e..465515e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -22,6 +22,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | | image | webp | .webp | yes | yes | animation: true, alpha: true, lossy: true, lossless: true, depths: 8 | `tests/image/webp.luau` | +| image | xbm | .xbm .bm | yes | yes | depths: 1 | `tests/image/xbm.luau` | +| image | xpm | .xpm .pm | yes | yes | alpha: true, palette: true, depths: 8 | `tests/image/xpm.luau` | | audio | aac | .aac .adts | yes | - | codecs: "aac", streaming: true | `tests/audio/aac.luau` | | audio | aiff | .aiff .aif .aifc .afc | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/aiff.luau` | | audio | au | .au .snd | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, lossy: false | `tests/audio/au.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2619353..c954492 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -218,6 +218,30 @@ local list: { Entry } = { return require("@formats/image/webp") end, }, + { + name = "xbm", + category = "image", + path = "image/xbm", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, + load = function() + return require("@formats/image/xbm") + end, + }, + { + name = "xpm", + category = "image", + path = "image/xpm", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, + load = function() + return require("@formats/image/xpm") + end, + }, { name = "aac", category = "audio", diff --git a/src/Formats/image/xbm/init.luau b/src/Formats/image/xbm/init.luau new file mode 100644 index 0000000..7e1273a --- /dev/null +++ b/src/Formats/image/xbm/init.luau @@ -0,0 +1,161 @@ +--!strict +-- image/xbm: X BitMap (X11 bitmap(1) C source; X10 16-bit variant; new code). Decode: the #define _width / _height +-- (and _x_hot / _y_hot: meta.hotspot), the char / short bits array in hex, decimal or octal, LSB first, set bits black, +-- clear bits white (opts.transparent: clear bits transparent instead). Encode: rgba8 thresholded (luminance below +-- opts.threshold, default 128, and alpha >= 128 is black), X11 format, opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Xbm = { + name = "xbm", + category = "image", + extensions = { "xbm", "bm" }, + mime = { "image/x-xbitmap", "image/x-xbm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, depths = { 1 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + transparent: boolean?, -- clear bits transparent (default false: white) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + name: string?, -- the C identifier prefix (default "image") + threshold: number?, -- luminance below this is black (default 128) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Xbm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 256, true) + if string.match(s, "^#define%s+[%w_]*_?width%s+%d+") or string.match(s, "^/%*.-%*/%s*#define%s+[%w_]*width%s+%d+") then + return 0.9 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Xbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 26 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local s = buffer.readstring(r.buf, r.base, n) + local w = tonumber(string.match(s, "#define%s+[%w_]-_?width%s+(%d+)")) + local h = tonumber(string.match(s, "#define%s+[%w_]-_?height%s+(%d+)")) + if not w or not h or w < 1 or h < 1 then + return nil, Err.new(Err.CORRUPT, "missing width / height defines") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local brace = string.find(s, "{", 1, true) + if not brace then + return nil, Err.new(Err.CORRUPT, "missing bits array") + end + local decl = string.sub(s, 1, brace) + local short = string.find(decl, "short", 1, true) ~= nil + local unit = if short then 16 else 8 + local per = (w + unit - 1) // unit + local want = per * h + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local clear = if opts and opts.transparent then 0x00FFFFFF else 0xFFFFFFFF + local got = 0 + local body = string.gsub(string.sub(s, brace + 1), "/%*.-%*/", " ") + for tok in string.gmatch(body, "[%w]+") do + if got >= want then + break + end + local v + if string.match(tok, "^0[xX]%x+$") then + v = tonumber(string.sub(tok, 3), 16) + elseif string.match(tok, "^0%d+$") then + v = tonumber(tok, 8) + elseif string.match(tok, "^%d+$") then + v = tonumber(tok) + end + if v then + local y, cx = got // per, (got % per) * unit + for k = 0, unit - 1 do + local x = cx + k + if x < w then + buffer.writeu32(px, (y * w + x) * 4, if bit32.band(bit32.rshift(v, k), 1) == 1 then 0xFF000000 else clear) + end + end + got += 1 + end + end + if got < want then + for i = got * unit, want * unit - 1 do + local y, x = i // (per * unit), i % (per * unit) + if x < w then + buffer.writeu32(px, (y * w + x) * 4, clear) + end + end + img.meta.truncated = true + end + local hx = tonumber(string.match(s, "#define%s+[%w_]-_?x_hot%s+(%d+)")) + local hy = tonumber(string.match(s, "#define%s+[%w_]-_?y_hot%s+(%d+)")) + if hx and hy then + img.meta.hotspot = { x = hx, y = hy } + end + local name = string.match(s, "#define%s+([%w_]-)_?width%s") + img.meta.source = { format = "xbm", bitDepth = 1, name = name, x10 = short } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local name = opts and opts.name or "image" + if not string.match(name, "^[%a_][%w_]*$") then + return nil, Err.new(Err.ARG, "name must be a C identifier") + end + local th = opts and opts.threshold or 128 + local px = img.pixels + local parts = { + string.format("#define %s_width %d\n#define %s_height %d\n", name, w, name, h), + } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format("#define %s_x_hot %d\n#define %s_y_hot %d\n", name, hs.x, name, hs.y)) + end + table.insert(parts, string.format("static unsigned char %s_bits[] = {\n", name)) + local per = (w + 7) // 8 + local bytes = {} + for y = 0, h - 1 do + for bx = 0, per - 1 do + local v = 0 + for k = 0, 7 do + local x = bx * 8 + k + if x < w then + local o = (y * w + x) * 4 + local lum = 0.299 * buffer.readu8(px, o) + 0.587 * buffer.readu8(px, o + 1) + 0.114 * buffer.readu8(px, o + 2) + if lum < th and buffer.readu8(px, o + 3) >= 128 then + v += bit32.lshift(1, k) + end + end + end + table.insert(bytes, string.format("0x%02x", v)) + end + end + for i = 1, #bytes, 12 do + table.insert(parts, " " .. table.concat(bytes, ", ", i, math.min(i + 11, #bytes)) .. (if i + 11 < #bytes then ",\n" else " };\n")) + end + return buffer.fromstring(table.concat(parts)), nil +end + +return Xbm diff --git a/src/Formats/image/xpm/Names.luau b/src/Formats/image/xpm/Names.luau new file mode 100644 index 0000000..6291a2d --- /dev/null +++ b/src/Formats/image/xpm/Names.luau @@ -0,0 +1,57 @@ +--!strict +-- image/xpm/Names: colour names for XPM colour tables: the CSS Color 4 named colours (which come from X11), with X11's +-- own values where the two differ (gray / grey, green, maroon, purple), and X11's grey0 .. grey100 / gray0 .. gray100. +-- lookup(name) takes a lower-case name without spaces and returns R + G * 256 + B * 65536, or nil. +local Names = {} + +local HEX: { [string]: number } = { + aliceblue = 0xF0F8FF, antiquewhite = 0xFAEBD7, aqua = 0x00FFFF, aquamarine = 0x7FFFD4, azure = 0xF0FFFF, + beige = 0xF5F5DC, bisque = 0xFFE4C4, black = 0x000000, blanchedalmond = 0xFFEBCD, blue = 0x0000FF, + blueviolet = 0x8A2BE2, brown = 0xA52A2A, burlywood = 0xDEB887, cadetblue = 0x5F9EA0, chartreuse = 0x7FFF00, + chocolate = 0xD2691E, coral = 0xFF7F50, cornflowerblue = 0x6495ED, cornsilk = 0xFFF8DC, crimson = 0xDC143C, + cyan = 0x00FFFF, darkblue = 0x00008B, darkcyan = 0x008B8B, darkgoldenrod = 0xB8860B, darkgray = 0xA9A9A9, + darkgreen = 0x006400, darkgrey = 0xA9A9A9, darkkhaki = 0xBDB76B, darkmagenta = 0x8B008B, darkolivegreen = 0x556B2F, + darkorange = 0xFF8C00, darkorchid = 0x9932CC, darkred = 0x8B0000, darksalmon = 0xE9967A, darkseagreen = 0x8FBC8F, + darkslateblue = 0x483D8B, darkslategray = 0x2F4F4F, darkslategrey = 0x2F4F4F, darkturquoise = 0x00CED1, + darkviolet = 0x9400D3, deeppink = 0xFF1493, deepskyblue = 0x00BFFF, dimgray = 0x696969, dimgrey = 0x696969, + dodgerblue = 0x1E90FF, firebrick = 0xB22222, floralwhite = 0xFFFAF0, forestgreen = 0x228B22, fuchsia = 0xFF00FF, + gainsboro = 0xDCDCDC, ghostwhite = 0xF8F8FF, gold = 0xFFD700, goldenrod = 0xDAA520, gray = 0xBEBEBE, + green = 0x00FF00, greenyellow = 0xADFF2F, grey = 0xBEBEBE, honeydew = 0xF0FFF0, hotpink = 0xFF69B4, + indianred = 0xCD5C5C, indigo = 0x4B0082, ivory = 0xFFFFF0, khaki = 0xF0E68C, lavender = 0xE6E6FA, + lavenderblush = 0xFFF0F5, lawngreen = 0x7CFC00, lemonchiffon = 0xFFFACD, lightblue = 0xADD8E6, lightcoral = 0xF08080, + lightcyan = 0xE0FFFF, lightgoldenrodyellow = 0xFAFAD2, lightgray = 0xD3D3D3, lightgreen = 0x90EE90, + lightgrey = 0xD3D3D3, lightpink = 0xFFB6C1, lightsalmon = 0xFFA07A, lightseagreen = 0x20B2AA, lightskyblue = 0x87CEFA, + lightslategray = 0x778899, lightslategrey = 0x778899, lightsteelblue = 0xB0C4DE, lightyellow = 0xFFFFE0, + lime = 0x00FF00, limegreen = 0x32CD32, linen = 0xFAF0E6, magenta = 0xFF00FF, maroon = 0xB03060, + mediumaquamarine = 0x66CDAA, mediumblue = 0x0000CD, mediumorchid = 0xBA55D3, mediumpurple = 0x9370DB, + mediumseagreen = 0x3CB371, mediumslateblue = 0x7B68EE, mediumspringgreen = 0x00FA9A, mediumturquoise = 0x48D1CC, + mediumvioletred = 0xC71585, midnightblue = 0x191970, mintcream = 0xF5FFFA, mistyrose = 0xFFE4E1, moccasin = 0xFFE4B5, + navajowhite = 0xFFDEAD, navy = 0x000080, navyblue = 0x000080, oldlace = 0xFDF5E6, olive = 0x808000, olivedrab = 0x6B8E23, + orange = 0xFFA500, orangered = 0xFF4500, orchid = 0xDA70D6, palegoldenrod = 0xEEE8AA, palegreen = 0x98FB98, + paleturquoise = 0xAFEEEE, palevioletred = 0xDB7093, papayawhip = 0xFFEFD5, peachpuff = 0xFFDAB9, peru = 0xCD853F, + pink = 0xFFC0CB, plum = 0xDDA0DD, powderblue = 0xB0E0E6, purple = 0xA020F0, rebeccapurple = 0x663399, red = 0xFF0000, + rosybrown = 0xBC8F8F, royalblue = 0x4169E1, saddlebrown = 0x8B4513, salmon = 0xFA8072, sandybrown = 0xF4A460, + seagreen = 0x2E8B57, seashell = 0xFFF5EE, sienna = 0xA0522D, silver = 0xC0C0C0, skyblue = 0x87CEEB, + slateblue = 0x6A5ACD, slategray = 0x708090, slategrey = 0x708090, snow = 0xFFFAFA, springgreen = 0x00FF7F, + steelblue = 0x4682B4, tan = 0xD2B48C, teal = 0x008080, thistle = 0xD8BFD8, tomato = 0xFF6347, turquoise = 0x40E0D0, + violet = 0xEE82EE, wheat = 0xF5DEB3, white = 0xFFFFFF, whitesmoke = 0xF5F5F5, yellow = 0xFFFF00, yellowgreen = 0x9ACD32, +} + +-- lookup(name) -> R + G * 256 + B * 65536 | nil (name: lower case, no spaces) +function Names.lookup(name: string): number? + local v = HEX[name] + if v then + return bit32.rshift(v, 16) + bit32.band(v, 0xFF00) + bit32.band(v, 0xFF) * 65536 + end + local n = string.match(name, "^gr[ae]y(%d+)$") + if n then + local k = tonumber(n) :: number + if k <= 100 then + local g = math.floor(k * 255 / 100 + 0.49) + return g * 0x10101 + end + end + return nil +end + +return Names diff --git a/src/Formats/image/xpm/init.luau b/src/Formats/image/xpm/init.luau new file mode 100644 index 0000000..0be8459 --- /dev/null +++ b/src/Formats/image/xpm/init.luau @@ -0,0 +1,271 @@ +--!strict +-- image/xpm: X PixMap (XPM 3 C source and the XPM 2 plain form; the "XPM Manual" by Arnaud Le Hors; new code). Decode: +-- the values line (width, height, colours, chars per pixel, hotspot: meta.hotspot), colour lines with the c / g / g4 / +-- m / s keys (c preferred, then g, g4, m), #RGB / #RRGGBB / #RRRGGGBBB / #RRRRGGGGBBBB, None (transparent) and colour +-- names (image/xpm/Names: the CSS / X11 names and grey0..100; an unknown name is black and listed in +-- meta.unknownColours), the extensions section skipped. Encode: rgba8 as XPM 3 with hex colours, alpha < 128 as None, +-- the fewest chars per pixel; opts.name (default "image"). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Names = require("@formats/image/xpm/Names") + +-- ------------------------------------------------------------------------------------------------ contract +local Xpm = { + name = "xpm", + category = "image", + extensions = { "xpm", "pm" }, + mime = { "image/x-xpixmap", "image/x-xpm" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + name: string?, -- the C identifier (default "image") +} + +-- the characters of pixel codes (printable ASCII without '"' and '\') +local CODE_CHARS = " .XoO+@#$%&*=-;:>,<1234567890qwertyuipasdfghjklzxcvbnmMNBVCZASDFGHJKLPIUYTREWQ!~^/()_`'][{}|" + +-- ------------------------------------------------------------------------------------------------ sniff +function Xpm.sniff(r: Bytes.Reader): number + local s = Sniff.text(r, 64, true) + if string.sub(s, 1, 9) == "/* XPM */" or string.sub(s, 1, 6) == "! XPM2" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- colour value -> rgba8 u32, or nil for an unknown name +local function colour(v: string): number? + local l = string.lower(v) + if l == "none" or l == "transparent" then + return 0 + end + if string.sub(v, 1, 1) == "#" then + local hex = string.sub(v, 2) + local n = #hex + if n % 3 ~= 0 or n == 0 or n > 12 or not string.match(hex, "^%x+$") then + return nil + end + local k = n // 3 + local mx = 16 ^ k - 1 + local c = 0 + for i = 0, 2 do + local x = tonumber(string.sub(hex, i * k + 1, i * k + k), 16) :: number + c += math.floor(x * 255 / mx + 0.5) * 256 ^ i + end + return c + 0xFF000000 + end + local rgb = Names.lookup(l) + return if rgb then rgb + 0xFF000000 else nil +end + +-- the strings of the file: C string literals (XPM 3) or plain lines (XPM 2) +local function strings(s: string): { string } + local out = {} + if string.sub(Sniff.dropBom(s), 1, 6) == "! XPM2" then + local first = true + for line in string.gmatch(s, "[^\n]+") do + if first then + first = false + else + table.insert(out, (string.gsub(line, "\r$", ""))) + end + end + return out + end + local i, n = 1, #s + while i <= n do + local c = string.sub(s, i, i) + if c == "/" and string.sub(s, i + 1, i + 1) == "*" then + local e = string.find(s, "*/", i + 2, true) + i = if e then e + 2 else n + 1 + elseif c == '"' then + local parts = {} + local j = i + 1 + while j <= n do + local d = string.sub(s, j, j) + if d == "\\" then + table.insert(parts, string.sub(s, j + 1, j + 1)) + j += 2 + elseif d == '"' then + break + else + local e = string.find(s, '["\\]', j) + local stop = (e or n + 1) - 1 + table.insert(parts, string.sub(s, j, stop)) + j = stop + 1 + end + end + table.insert(out, table.concat(parts)) + i = j + 1 + else + i += 1 + end + end + return out +end + +local KEYS = { c = true, m = true, g4 = true, g = true, s = true } + +function Xpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local n = r.limit - r.base + if n > 2 ^ 27 then + return nil, Err.new(Err.LIMIT, "file too large") + end + local list = strings(buffer.readstring(r.buf, r.base, n)) + if #list == 0 then + return nil, Err.new(Err.CORRUPT, "no XPM strings") + end + local vals: { number } = {} + for tok in string.gmatch(list[1], "%S+") do + table.insert(vals, tonumber(tok) or -1) + end + local w: number, h: number, nc: number, cpp: number = vals[1] or -1, vals[2] or -1, vals[3] or -1, vals[4] or -1 + if w < 1 or h < 1 or nc < 1 or cpp < 1 or cpp > 8 or w % 1 ~= 0 or h % 1 ~= 0 then + return nil, Err.new(Err.CORRUPT, "bad values line") + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels or nc > 2 ^ 24 then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + if #list < 1 + nc then + return nil, Err.new(Err.TRUNCATED, "colour table runs past the end") + end + local map: { [string]: number } = {} + local unknown: { string } = {} + local palette: { { number } } = {} + for i = 1, nc do + local line = list[1 + i] + local code = string.sub(line, 1, cpp) + local rest = string.sub(line, cpp + 1) + local found: { [string]: string } = {} + local key: string? = nil + local acc = {} + for tok in string.gmatch(rest, "%S+") do + if KEYS[tok] and (key == nil or #acc > 0) then + if key then + found[key] = table.concat(acc, " ") + end + key, acc = tok, {} + else + table.insert(acc, tok) + end + end + if key then + found[key] = table.concat(acc, " ") + end + local v = found.c or found.g or found.g4 or found.m + local c = if v then colour(v) else nil + if v and not c then + c = colour((string.gsub(v, " ", ""))) + end + local cv: number = c or 0xFF000000 + if not c then + table.insert(unknown, v or "") + end + c = cv + map[code] = cv + palette[i] = { bit32.band(cv, 255), bit32.band(bit32.rshift(cv, 8), 255), bit32.band(bit32.rshift(cv, 16), 255), bit32.rshift(cv, 24) } + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + local truncated = false + for y = 0, h - 1 do + local row = list[2 + nc + y] + if not row then + truncated = true + break + end + for x = 0, w - 1 do + local c = map[string.sub(row, x * cpp + 1, x * cpp + cpp)] + buffer.writeu32(px, (y * w + x) * 4, c or 0) + end + end + if #vals >= 6 and vals[5] >= 0 and vals[6] >= 0 then + img.meta.hotspot = { x = vals[5], y = vals[6] } + end + if #unknown > 0 then + img.meta.unknownColours = unknown + end + if truncated then + img.meta.truncated = true + end + img.meta.palette = palette + img.meta.source = { format = "xpm", colours = nc, charsPerPixel = cpp } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 then + return nil, Err.new(Err.ARG, "bad size") + end + local name = opts and opts.name or "image" + if not string.match(name, "^[%a_][%w_]*$") then + return nil, Err.new(Err.ARG, "name must be a C identifier") + end + local px = img.pixels + local index: { [number]: number } = {} + local order: { number } = {} + local keys = table.create(w * h, 0) + for i = 0, w * h - 1 do + local v = buffer.readu32(px, i * 4) + local k = if v < 0x80000000 then -1 else bit32.band(v, 0xFFFFFF) + if not index[k] then + table.insert(order, k) + index[k] = #order + end + keys[i + 1] = index[k] + end + local nchars = #CODE_CHARS + local cpp = 1 + while nchars ^ cpp < #order do + cpp += 1 + end + local codes: { string } = {} + for i = 1, #order do + local v, s = i - 1, "" + for _ = 1, cpp do + local d = v % nchars + s ..= string.sub(CODE_CHARS, d + 1, d + 1) + v //= nchars + end + codes[i] = s + end + local parts = { "/* XPM */\n", string.format("static char *%s[] = {\n", name) } + local hs: { x: number, y: number }? = img.meta and img.meta.hotspot + if hs then + table.insert(parts, string.format('"%d %d %d %d %d %d",\n', w, h, #order, cpp, hs.x, hs.y)) + else + table.insert(parts, string.format('"%d %d %d %d",\n', w, h, #order, cpp)) + end + for i, k in order do + local col = if k < 0 then "None" else string.format("#%02X%02X%02X", bit32.band(k, 255), bit32.band(bit32.rshift(k, 8), 255), bit32.rshift(k, 16)) + table.insert(parts, string.format('"%s c %s",\n', codes[i], col)) + end + for y = 0, h - 1 do + local row = table.create(w, "") + for x = 0, w - 1 do + row[x + 1] = codes[keys[y * w + x + 1]] + end + table.insert(parts, '"' .. table.concat(row) .. '"' .. (if y < h - 1 then ",\n" else "\n")) + end + table.insert(parts, "};\n") + return buffer.fromstring(table.concat(parts)), nil +end + +return Xpm diff --git a/tests/image/xbm.luau b/tests/image/xbm.luau new file mode 100644 index 0000000..b1066aa --- /dev/null +++ b/tests/image/xbm.luau @@ -0,0 +1,43 @@ +-- image/xbm tests: files from netpbm / ImageMagick / Pillow and hand-written ones against the reference decode +-- (xbmtopbm), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass. +-- Fixtures: tools/fixtures/xbm.py. +local T = require("@tests/T") +local Xbm = require("@formats/image/xbm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/xbm") + +local t = T.suite("xbm") +t:eq(Xbm.name, "xbm", "name") +t:check(Xbm.caps.decode and Xbm.caps.encode, "caps") + +t:note("%d files match the reference", R.decodes(t, Xbm, Fx.cases)) +t:note("%d of our files read back by it", R.decodes(t, Xbm, Fx.ours)) +for _, c in Fx.cases do + R.roundTrip(t, Xbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + if c.hotspot then + local img = Xbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot") + end +end +do + -- decimal and octal values, the X10 short arrays + local img = Xbm.decode(Bytes.reader(buffer.fromstring("#define a_width 9\n#define a_height 1\nstatic char a_bits[] = { 1, 0400 };"))) :: any + t:eq(buffer.readu32(img.pixels, 0), 0xFF000000, "decimal: pixel 0 black") + t:eq(buffer.readu32(img.pixels, 4), 0xFFFFFFFF, "decimal: pixel 1 white") + local x10 = Xbm.decode(Bytes.reader(buffer.fromstring("#define b_width 17\n#define b_height 1\nstatic short b_bits[] = { 0x8001, 0x0001 };"))) :: any + t:eq(buffer.readu32(x10.pixels, 15 * 4), 0xFF000000, "x10: bit 15") + t:eq(buffer.readu32(x10.pixels, 16 * 4), 0xFF000000, "x10: second short") + local tr = Xbm.decode(Bytes.reader(buffer.fromstring("#define c_width 2\n#define c_height 1\nstatic char c_bits[] = { 0x01 };")), { transparent = true }) :: any + t:eq(buffer.readu32(tr.pixels, 4), 0x00FFFFFF, "transparent clear bits") + t:eq(Xbm.sniff(Bytes.reader(buffer.fromstring("#define c_width 2\n"))), 0.9, "sniff") + local _, e = Xbm.decode(Bytes.reader(buffer.fromstring("static char x[] = {};"))) + t:check(e and e.code == Err.CORRUPT, "no defines") + local _, e2 = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1bad" }) + t:check(e2 and e2.code == Err.ARG, "bad name") +end +t:fuzz("decode", function(b: buffer) + return Xbm.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tests/image/xpm.luau b/tests/image/xpm.luau new file mode 100644 index 0000000..fd525f3 --- /dev/null +++ b/tests/image/xpm.luau @@ -0,0 +1,44 @@ +-- image/xpm tests: files from netpbm / ImageMagick and hand-written ones against the reference decode +-- (ImageMagick), our encoder's files read back by it, round trips, errors, the fuzz no-throw pass. +-- Fixtures: tools/fixtures/xpm.py. +local T = require("@tests/T") +local Xpm = require("@formats/image/xpm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/xpm") + +local t = T.suite("xpm") +t:eq(Xpm.name, "xpm", "name") +t:check(Xpm.caps.decode and Xpm.caps.encode, "caps") + +t:note("%d files match the reference", R.decodes(t, Xpm, Fx.cases)) +t:note("%d of our files read back by it", R.decodes(t, Xpm, Fx.ours)) +for _, c in Fx.cases do + R.roundTrip(t, Xpm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + if c.hotspot then + local img = Xpm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot") + end +end +do + local img = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */\nstatic char *x[] = {"2 1 2 1 0 0", "a c gray50", "b c Unknownish", "ab"};'))) :: any + t:eq(buffer.readu32(img.pixels, 0), 0xFF7F7F7F, "gray50") + t:check(img.meta.unknownColours and img.meta.unknownColours[1] == "Unknownish", "unknown colour listed") + t:check(img.meta.hotspot and img.meta.hotspot.x == 0, "hotspot") + t:eq(Xpm.sniff(Bytes.reader(buffer.fromstring("/* XPM */\n"))), 1, "sniff") + local _, e = Xpm.decode(Bytes.reader(buffer.fromstring('/* XPM */ static char *x[] = {"2 1 5 1", "a c red"};'))) + t:check(e and e.code == Err.TRUNCATED, "short colour table") + -- many colours: two chars per pixel + local big = R.image(300, 1, "") + big.pixels = buffer.create(1200) + for i = 0, 299 do + buffer.writeu32(big.pixels, i * 4, i * 997 + 0xFF000000) + end + local enc = R.roundTrip(t, Xpm, big, nil, "300 colours") :: buffer + t:check(string.find(buffer.tostring(enc), '"300 1 300 2"', 1, true) ~= nil, "two chars per pixel") +end +t:fuzz("decode", function(b: buffer) + return Xpm.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 8e7887f..c15bf20 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -136,6 +136,10 @@ local function simple(): any return require("@formats/image/sgi") elseif which == "sunras" then return require("@formats/image/sunras") + elseif which == "xbm" then + return require("@formats/image/xbm") + elseif which == "xpm" then + return require("@formats/image/xpm") end return nil end diff --git a/tools/fixtures/xbm.py b/tools/fixtures/xbm.py new file mode 100644 index 0000000..f9c3792 --- /dev/null +++ b/tools/fixtures/xbm.py @@ -0,0 +1,43 @@ +# XBM fixtures (tools/fixtures.py): files from netpbm (pbmtoxbm X11 and -x10), ImageMagick and Pillow (with a hotspot), +# a hand-written one (comments, odd spacing); the reference is xbmtopbm (netpbm); our encoder's files +# (tools/fixtures/_tex_encode.luau -a xbm) read by xbmtopbm. +# tests/gen/xbm.luau { cases = { { name, data, w, h, rgba, hotspot? } }, ours = { ... } } +import importlib.util, os + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S = _load("_raster_ref"), _load("_simple") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xbm"] + + +def generate(ctx): + w = R.Work(ctx) + try: + mono = bytes(v for i in range(29 * 13) for v in ((0,) * 3 if (i * 7 + i // 29) % 5 < 2 else (255,) * 3) + (255,)) + w.png("mono.png", 29, 13, mono) + w.png("mono2.png", 16, 9, bytes(v for i in range(16 * 9) for v in ((0,) * 3 if (i % 3 == 0) else (255,) * 3) + (255,))) + w.sh("netpbm", ["pngtopam mono.png | pamtopnm | ppmtopgm | pgmtopbm -threshold > mono.pbm", "pbmtoxbm mono.pbm > nb_x11.xbm", + "pbmtoxbm -x10 mono.pbm > nb_x10.xbm"]) + w.sh("imagemagick", ["magick mono2.png im.xbm"]) + ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('mono.png').convert('1').save('pil.xbm', hotspot=(3, 4))\n" % w.dir) + w.write("hand.xbm", b"/* a comment */\n#define hand_width 10\n#define hand_height 2\nstatic unsigned char hand_bits[] = {\n 0xff,0x03, /* row 0 */\n 0x00, 0x01 };\n") + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xbm")) + mine = S.ours(ctx, "xbm") + for n, d in mine.items(): + w.write(n, d) + allnames = names + sorted(mine) + w.sh("netpbm", ["xbmtopbm %s > %s.pbm" % (n, n) for n in allnames]) + out = {"cases": [], "ours": []} + for n in allnames: + ww, hh, rgba = R.pnm_rgba(w.read(n + ".pbm")) + c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba} + if n == "pil.xbm": + c["hotspot"] = [3, 4] + out["ours" if n.startswith("ours_") else "cases"].append(c) + ctx.emit("xbm", out) + finally: + w.close() diff --git a/tools/fixtures/xpm.py b/tools/fixtures/xpm.py new file mode 100644 index 0000000..b086347 --- /dev/null +++ b/tools/fixtures/xpm.py @@ -0,0 +1,58 @@ +# XPM fixtures (tools/fixtures.py): files from netpbm (ppmtoxpm -hexonly), ImageMagick (with alpha: None) and +# hand-written ones (colour names, #RGB / #RRRRGGGGBBBB, g / m keys, two chars per pixel, XPM 2); the reference is +# ImageMagick's decode (the XPM 2 file's values are written here: ImageMagick does not read XPM 2); our encoder's files (tools/fixtures/_tex_encode.luau -a xpm) read by ImageMagick. +# tests/gen/xpm.luau { cases = { { name, data, w, h, rgba } }, ours = { ... } } +import importlib.util, os + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S = _load("_raster_ref"), _load("_simple") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/xpm"] + +HAND = b'''/* XPM */ +static char * hand_xpm[] = { +/* width height ncolors cpp */ +"6 4 6 2", +" c None", +".. c red", +"XX g4 #888 c LightBlue m white", +"oo c #FFFF00000000", +"++ s mine c navy", +"@@ c Gold", +" ..XXoo++@@", +"..XXoo++@@ ", +"XXoo++@@ ..", +"oo++@@ ..XX"}; +''' +XPM2 = b"! XPM2\n3 2 2 1\na c #102030\nb c white\nabb\nbab\n" + + +def generate(ctx): + w = R.Work(ctx) + try: + w.png("pal.png", 31, 19, R.palette_image(31, 19, 40)) + w.png("alpha.png", 20, 11, bytes(v for i in range(20 * 11) for v in (((i * 40) % 256, 80, 200, 255 if i % 3 else 0)))) + w.sh("netpbm", ["pngtopam pal.png | pamtopnm > pal.ppm", "ppmtoxpm -hexonly pal.ppm > nb.xpm"]) + w.sh("imagemagick", ["magick pal.png -alpha off im.xpm", "magick alpha.png im_alpha.xpm"]) + w.write("hand.xpm", HAND) + w.write("hand2.xpm", XPM2) + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".xpm") and f != "hand2.xpm") + mine = S.ours(ctx, "xpm") + for n, d in mine.items(): + w.write(n, d) + ref = S.magick_cases(R, w, names + sorted(mine), "xpm") + out = {"cases": [], "ours": []} + for n in names + sorted(mine): + ww, hh, rgba = ref[n] + # ImageMagick keeps the colour of transparent pixels; we decode None as transparent black + rgba = bytes(0 if rgba[i - i % 4 + 3] == 0 else v for i, v in enumerate(rgba)) + out["ours" if n.startswith("ours_") else "cases"].append({"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba}) + a, b = bytes((0x10, 0x20, 0x30, 255)), b"\xff" * 4 + out["cases"].append({"name": "hand2.xpm (XPM 2)", "data": XPM2, "w": 3, "h": 2, "rgba": a + b + b + b + a + b}) + ctx.emit("xpm", out) + finally: + w.close() From 4b9d8e3069c0bc539fda2bebf949358f7c75346d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:09 -0500 Subject: [PATCH 44/54] ws-3d3-b: model/x: counts past the data are refused before allocating (TRUNCATED) --- src/Formats/model/x/Build.luau | 26 ++++++++++++++++++++------ tests/model/x.luau | 2 ++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/Formats/model/x/Build.luau b/src/Formats/model/x/Build.luau index 2acb8f3..16d41e6 100644 --- a/src/Formats/model/x/Build.luau +++ b/src/Formats/model/x/Build.luau @@ -34,11 +34,25 @@ local function str(c: Vals): string end return x end +-- a non-negative integer (an index) +local function index(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad index " .. n, 0) + end + return n +end + +-- a count of items that follow (each takes at least one value: a count past the data is refused before anything +-- is allocated for it) local function count(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then error("bad count " .. n, 0) end + if n > #c.v - c.i + 1 then + error("truncated: a count of " .. n .. " runs past the data", 0) + end return n end @@ -146,7 +160,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end local face = table.create(n) :: { number } for k = 1, n do - local idx = count(c, 2 ^ 32) + local idx = index(c, 2 ^ 32) if idx >= nv then error("face index " .. idx .. " out of range", 0) end @@ -176,7 +190,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local face = table.create(n) :: { number } for q = 1, n do - face[q] = count(kc, 2 ^ 32) + face[q] = index(kc, 2 ^ 32) end nfs[f] = face end @@ -194,7 +208,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local col = table.create(nv * 4, 1) :: { number } for _ = 1, n do - local idx = count(kc, 2 ^ 32) + local idx = index(kc, 2 ^ 32) local r, g, b, a = num(kc), num(kc), num(kc), num(kc) if idx < nv then col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a @@ -202,10 +216,10 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end table.insert(colors, col) elseif k.type == "MeshMaterialList" then - count(kc, 2 ^ 20) -- material count (the objects below are authoritative) + num(kc) -- material count (the objects below are authoritative) local ni = count(kc, ctx.maxVertices) for q = 1, ni do - faceMat[q] = count(kc, 2 ^ 20) + faceMat[q] = index(kc, 2 ^ 20) end for _, mk in k.kids do if mk.type == "@ref" then @@ -220,7 +234,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local verts = table.create(n) :: { number } for q = 1, n do - verts[q] = count(kc, 2 ^ 32) + verts[q] = index(kc, 2 ^ 32) end local weights = table.create(n) :: { number } for q = 1, n do diff --git a/tests/model/x.luau b/tests/model/x.luau index 119cbdc..8cc3524 100644 --- a/tests/model/x.luau +++ b/tests/model/x.luau @@ -287,6 +287,8 @@ do t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) local _, e5 = decode("xof 0303txt 0032 Frame A { ") t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5)) + local _, e7 = decode("xof 0303txt 0032 Mesh { 33554431; 1; }") + t:check(e7 and e7.code == Err.TRUNCATED, "a vertex count past the data is refused before allocating: " .. tostring(e7)) local _, e6 = decode(CUBE, { maxValues = 10 }) t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6)) t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff") From 88d5fe7d2f05379a4e297fd3f36311026d145d37 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:19 -0500 Subject: [PATCH 45/54] ws-video2-theora: Theora MC average without type diagnostics (lint TYPES back to the baseline) --- src/Formats/codecs/video/Theora/Decoder.luau | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Formats/codecs/video/Theora/Decoder.luau b/src/Formats/codecs/video/Theora/Decoder.luau index aad8f1c..d7a7afc 100644 --- a/src/Formats/codecs/video/Theora/Decoder.luau +++ b/src/Formats/codecs/video/Theora/Decoder.luau @@ -537,10 +537,12 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu local s2 = s1 + my2 * stride + mx2 for y = 0, 7 do local d, a, b = pos + y * stride, s1 + y * stride, s2 + y * stride - local u, v = readu32(ref, a), readu32(ref, b) + local u: number = readu32(ref, a) + local v: number = readu32(ref, b) writeu32(dst, d, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) - u, v = readu32(ref, a + 4), readu32(ref, b + 4) - writeu32(dst, d + 4, band(u, v) + rshift(band(bxor(u, v), 0xFEFEFEFE), 1)) + local u2: number = readu32(ref, a + 4) + local v2: number = readu32(ref, b + 4) + writeu32(dst, d + 4, band(u2, v2) + rshift(band(bxor(u2, v2), 0xFEFEFEFE), 1)) end else for y = 0, 7 do From ce4845ae133d9e20341ed59df78389036f09f87e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:03:24 -0500 Subject: [PATCH 46/54] ws-tex: image/ilbm (IFF ILBM / PBM read: planar, EHB, HAM6/8, deep 24/32, masks; write palette / 24 / 32 planes) Chunks through containers/Chunks, ByteRun1 through codecs/compress/PackBits. Tested against ppmtoilbm files and hand-written EHB / PBM / mask / transparent-colour files decoded by ilbmtoppm; our files read by ilbmtoppm. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/image/ilbm/init.luau | 324 +++++++++++++++++++++++++++++++ tests/image/ilbm.luau | 72 +++++++ tools/fixtures/_tex_encode.luau | 2 + tools/fixtures/ilbm.py | 121 ++++++++++++ 6 files changed, 532 insertions(+) create mode 100644 src/Formats/image/ilbm/init.luau create mode 100644 tests/image/ilbm.luau create mode 100644 tools/fixtures/ilbm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 465515e..1fc6262 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -11,6 +11,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | +| image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | | image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` | | image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index c954492..7a27212 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -86,6 +86,18 @@ local list: { Entry } = { return require("@formats/image/ico") end, }, + { + name = "ilbm", + category = "image", + path = "image/ilbm", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, + load = function() + return require("@formats/image/ilbm") + end, + }, { name = "jpeg", category = "image", diff --git a/src/Formats/image/ilbm/init.luau b/src/Formats/image/ilbm/init.luau new file mode 100644 index 0000000..aaa4bd8 --- /dev/null +++ b/src/Formats/image/ilbm/init.luau @@ -0,0 +1,324 @@ +--!strict +-- image/ilbm: IFF ILBM and PBM pictures (EA IFF 85 "ILBM" standard, the Amiga ROM Kernel Manual; new code; chunks +-- through containers/Chunks, ByteRun1 through codecs/compress/PackBits). Decode: planar ILBM with 1..8 planes and a +-- CMAP (grey without one), EHB (extra half-brite, CAMG 0x80), HAM6 / HAM8 (CAMG 0x800), deep 24 / 32-plane RGB(A), +-- chunky PBM (8-bit, Deluxe Paint), masking 1 (a mask plane) and 2 (a transparent colour index), uncompressed or +-- ByteRun1 bodies; opts.adjustColors scales 4-bit OCS palettes (all low nibbles zero) to 8 bits; NAME / ANNO / AUTH +-- text (meta.text). HAM channel values replicate their bits (4-bit v -> v * 17; ilbmtoppm shifts: v * 16). Encode: rgba8 as a planar ILBM: up to 256 opaque colours with a CMAP and the fewest planes, else +-- 24 planes (32 with alpha), ByteRun1 (default) or uncompressed. Not supported: animations (ANIM), the rarer +-- encodings (RGBN / RGB8 / ACBM / DEEP chunks: UNSUPPORTED), SHAM / PCHG palette changes (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") +local PackBits = require("@formats/codecs/compress/PackBits") +local Pixels = require("@formats/codecs/image/Pixels") + +-- ------------------------------------------------------------------------------------------------ contract +local Ilbm = { + name = "ilbm", + category = "image", + extensions = { "iff", "ilbm", "lbm", "pbm" }, + mime = { "image/x-ilbm", "image/x-iff" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/compress/PackBits", "codecs/image/Pixels" }, + caps = { decode = true, encode = true, alpha = true, palette = true, depths = { 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + adjustColors: boolean?, -- scale 4-bit OCS palettes (every low nibble 0) to 8 bits (default false) + maxPixels: number?, -- refuse larger images (default 2^26) +} +export type EncodeOptions = { + compress: boolean?, -- ByteRun1 (default true) +} + +local readu8, readu16 = buffer.readu8, buffer.readu16 +local function be16(b: buffer, o: number): number + return bit32.rshift(bit32.byteswap(readu16(b, o)), 16) +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ilbm.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local t = r:peek(4, 8) + return if t == "ILBM" or t == "PBM " then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ilbm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 12 or buffer.readstring(b, o, 4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", o) + end + local form = buffer.readstring(b, o + 8, 4) + if form ~= "ILBM" and form ~= "PBM " then + return nil, Err.new(Err.UNSUPPORTED, "FORM " .. form, o + 8) + end + local chunky = form == "PBM " + local list = Chunks.walk(b, o + 12, math.min(limit, o + 8 + bit32.byteswap(buffer.readu32(b, o + 4))), Chunks.IFF) + local bmhd, cmap, body = Chunks.find(list, "BMHD"), Chunks.find(list, "CMAP"), Chunks.find(list, "BODY") + if not bmhd or bmhd.avail < 20 then + return nil, Err.new(Err.CORRUPT, "missing BMHD", o + 12) + end + if not body then + return nil, Err.new(Err.TRUNCATED, "missing BODY", o + 12) + end + local q = bmhd.offset + local w, h = be16(b, q), be16(b, q + 2) + local planes, masking, comp = readu8(b, q + 8), readu8(b, q + 9), readu8(b, q + 10) + local trans = be16(b, q + 12) + if w == 0 or h == 0 then + return nil, Err.new(Err.CORRUPT, "bad size", q) + end + if comp > 1 then + return nil, Err.new(Err.UNSUPPORTED, "compression " .. comp, q + 10) + end + if not (planes >= 1 and planes <= 8 or planes == 24 or planes == 32) or (chunky and planes ~= 8) then + return nil, Err.new(Err.UNSUPPORTED, planes .. " planes", q + 8) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, maxPixels)) + end + local camg = 0 + local c = Chunks.find(list, "CAMG") + if c and c.avail >= 4 then + camg = bit32.byteswap(buffer.readu32(b, c.offset)) + end + local ham = bit32.band(camg, 0x800) ~= 0 and (planes == 6 or planes == 8) + local ehb = bit32.band(camg, 0x80) ~= 0 and planes == 6 and not ham + -- palette + local pal = buffer.create(1024) + local ncol = 0 + if cmap then + ncol = math.min(256, cmap.avail // 3) + local low = true + for i = 0, ncol * 3 - 1 do + low = low and bit32.band(readu8(b, cmap.offset + i), 15) == 0 + end + local adjust = low and opts and opts.adjustColors + for i = 0, ncol - 1 do + local function ch(k: number): number + local v = readu8(b, cmap.offset + i * 3 + k) + return if adjust then v + bit32.rshift(v, 4) else v + end + buffer.writeu32(pal, i * 4, ch(0) + ch(1) * 256 + ch(2) * 65536 + 0xFF000000) + end + end + if ncol == 0 and planes <= 8 then + local n = bit32.lshift(1, planes) + for i = 0, n - 1 do + local g = (i * 255) // math.max(1, n - 1) + buffer.writeu32(pal, i * 4, g * 0x10101 + 0xFF000000) + end + ncol = n + end + if ehb then + for i = 0, 31 do + local v = buffer.readu32(pal, i * 4) + local rr, gg, bb = bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255) + buffer.writeu32(pal, (32 + i) * 4, bit32.rshift(rr, 1) + bit32.rshift(gg, 1) * 256 + bit32.rshift(bb, 1) * 65536 + 0xFF000000) + end + end + -- the body, decompressed + local rowBytes = if chunky then w + w % 2 else ((w + 15) // 16) * 2 + local total = if chunky then rowBytes * h else rowBytes * (planes + (if masking == 1 then 1 else 0)) * h + local raw = buffer.create(total) + local truncated + if comp == 1 then + local written = PackBits.decode(b, body.offset, body.offset + body.avail, raw, 0, total) + truncated = written < total + else + local n = math.min(total, body.avail) + buffer.copy(raw, 0, b, body.offset, n) + truncated = n < total + end + local img = Types.Image.new(w, h, "rgba8") + local px = img.pixels + if chunky then + Pixels.indexed(raw, 0, rowBytes, 8, px, w, h, true, pal) + if masking == 2 then + for i = 0, w * h - 1 do + local y, x = i // w, i % w + if readu8(raw, y * rowBytes + x) == trans then + buffer.writeu32(px, i * 4, 0) + end + end + end + else + local stride = rowBytes * (planes + (if masking == 1 then 1 else 0)) + local deep = planes >= 24 + local bits = planes - 2 + for y = 0, h - 1 do + local row = y * stride + local pr: number, pg: number, pb: number = 0, 0, 0 + if ham then + local v = buffer.readu32(pal, 0) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + end + for x = 0, w - 1 do + local byteAt, shift = bit32.rshift(x, 3), 7 - bit32.band(x, 7) + local idx = 0 + for k = 0, planes - 1 do + idx += bit32.band(bit32.rshift(readu8(raw, row + k * rowBytes + byteAt), shift), 1) * 2 ^ k + end + local out: number + if deep then + local a = if planes == 32 then bit32.rshift(idx, 24) % 256 else 255 + out = bit32.band(idx, 0xFFFFFF) + a * 16777216 + elseif ham then + local ctl = bit32.rshift(idx, bits) + local val = bit32.band(idx, bit32.lshift(1, bits) - 1) + local v8 = if bits == 4 then val * 17 else val * 4 + bit32.rshift(val, 4) + if ctl == 0 then + local v = buffer.readu32(pal, val * 4) + pr = bit32.band(v, 255) + pg = bit32.band(bit32.rshift(v, 8), 255) + pb = bit32.band(bit32.rshift(v, 16), 255) + elseif ctl == 1 then + pb = v8 + elseif ctl == 2 then + pr = v8 + else + pg = v8 + end + out = pr + pg * 256 + pb * 65536 + 0xFF000000 + else + out = buffer.readu32(pal, bit32.band(idx, 255) * 4) + if masking == 2 and idx == trans then + out = 0 + end + end + if masking == 1 then + local m = bit32.band(bit32.rshift(readu8(raw, row + planes * rowBytes + byteAt), shift), 1) + if m == 0 then + out = 0 + end + end + buffer.writeu32(px, (y * w + x) * 4, out) + end + end + end + if ncol > 0 and planes <= 8 and not ham then + local plist: { { number } } = {} + for i = 0, (if ehb then 64 else ncol) - 1 do + local v = buffer.readu32(pal, i * 4) + plist[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 } + end + img.meta.palette = plist + end + local text: { [string]: string } = {} + for _, ch in list do + if ch.id == "NAME" or ch.id == "ANNO" or ch.id == "AUTH" or ch.id == "(c) " then + local s = buffer.readstring(b, ch.offset, ch.avail) + local key = string.gsub(ch.id, "[^%w]", "") + text[string.lower(key)] = (string.gsub(s, "%z+$", "")) + end + end + if next(text) then + img.meta.text = text + end + if truncated then + img.meta.truncated = true + end + img.meta.source = { format = "ilbm", form = form, planes = planes, bitDepth = planes, ham = ham, ehb = ehb, masking = masking, compression = comp, camg = camg } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ilbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an rgba8 Image") + end + local w, h = img.width, img.height + if w < 1 or h < 1 or w > 65535 or h > 65535 then + return nil, Err.new(Err.ARG, "size must be 1..65535") + end + local px = img.pixels + local cols, alpha = Pixels.colours(px, w * h, 256) + local usePal = not alpha and #cols <= 256 + local planes = if usePal then 1 elseif alpha then 32 else 24 + if usePal then + while bit32.lshift(1, planes) < #cols do + planes += 1 + end + end + local compress = not (opts and opts.compress == false) + local index: { [number]: number } = {} + for i, cv in cols do + index[cv] = i - 1 + end + local rowBytes = ((w + 15) // 16) * 2 + local body = Bytes.writer(rowBytes * planes * h) + local row = buffer.create(rowBytes) + for y = 0, h - 1 do + for k = 0, planes - 1 do + buffer.fill(row, 0, 0, rowBytes) + for x = 0, w - 1 do + local v = buffer.readu32(px, (y * w + x) * 4) + local idx = if usePal then (index[bit32.band(v, 0xFFFFFF)] or 0) else v + if bit32.band(bit32.rshift(idx, k), 1) == 1 then + local at = bit32.rshift(x, 3) + buffer.writeu8(row, at, bit32.bor(readu8(row, at), bit32.rshift(0x80, bit32.band(x, 7)))) + end + end + if compress then + body:bytes(PackBits.encode(row, 0, rowBytes)) + else + body:bytes(row) + end + end + end + local bodyData = body:finish() + local out = Bytes.writer(buffer.len(bodyData) + 900) + out:string("FORM") + out:u32be(0) + out:string("ILBM") + out:string("BMHD") + out:u32be(20) + out:u16be(w) + out:u16be(h) + out:u16be(0) + out:u16be(0) + out:u8(planes) + out:u8(0) + out:u8(if compress then 1 else 0) + out:u8(0) + out:u16be(0) + out:u8(1) + out:u8(1) + out:u16be(w) + out:u16be(h) + if usePal then + local n = bit32.lshift(1, planes) + out:string("CMAP") + out:u32be(n * 3) + for i = 1, n do + local cv = cols[i] or 0 + out:u8(bit32.band(cv, 255)) + out:u8(bit32.band(bit32.rshift(cv, 8), 255)) + out:u8(bit32.rshift(cv, 16)) + end + if (n * 3) % 2 == 1 then + out:u8(0) + end + end + out:string("BODY") + out:u32be(buffer.len(bodyData)) + out:bytes(bodyData) + if buffer.len(bodyData) % 2 == 1 then + out:u8(0) + end + local res = out:finish() + buffer.writeu32(res, 4, bit32.byteswap(buffer.len(res) - 8)) + return res, nil +end + +return Ilbm diff --git a/tests/image/ilbm.luau b/tests/image/ilbm.luau new file mode 100644 index 0000000..5577d6b --- /dev/null +++ b/tests/image/ilbm.luau @@ -0,0 +1,72 @@ +-- image/ilbm tests: files from netpbm's ppmtoilbm (palette, uncompressed, HAM6, HAM8, 24-bit) and hand-written ones +-- (EHB, chunky PBM, a mask plane, a transparent colour) against ilbmtoppm (colours) and the written masks (alpha); our +-- encoder's files read by ilbmtoppm; round trips (palette, 24 and 32 planes, uncompressed); errors; the fuzz no-throw +-- pass. Fixtures: tools/fixtures/ilbm.py. +local T = require("@tests/T") +local Ilbm = require("@formats/image/ilbm") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/ilbm") + +local t = T.suite("ilbm") +t:eq(Ilbm.name, "ilbm", "name") +t:check(Ilbm.caps.decode and Ilbm.caps.encode, "caps") + +local function check(c: any) + local img, err = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.w and img.height == c.h, c.name .. ": size") + local ref = buffer.fromstring(c.rgba) + local bad, badA = 0, 0 + for i = 0, c.w * c.h - 1 do + local transparent = c.transparent and c.transparent[i + 1] + local v = buffer.readu32(img.pixels, i * 4) + if transparent then + badA += if v == 0 then 0 else 1 + else + for k = 0, 3 do + if math.abs(buffer.readu8(img.pixels, i * 4 + k) - buffer.readu8(ref, i * 4 + k)) > (c.tol or 0) then + bad += 1 + break + end + end + end + end + t:eq(bad, 0, c.name .. ": colours against ilbmtoppm") + t:eq(badA, 0, c.name .. ": transparent pixels") + return img +end +for _, c in Fx.cases do + check(c) + if not c.transparent and not c.tol then + R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), nil, c.name .. " re-encoded") + R.roundTrip(t, Ilbm, R.image(c.w, c.h, c.rgba), { compress = false }, c.name .. " re-encoded uncompressed") + end +end +for _, o in Fx.ours do + check(o) +end +t:note("%d files and %d of ours match ilbmtoppm", #Fx.cases, #Fx.ours) +do + local img = R.image(3, 2, string.rep("\1\2\3\128", 6)) + local enc = R.roundTrip(t, Ilbm, img, nil, "alpha: 32 planes") :: buffer + t:eq(Ilbm.sniff(Bytes.reader(enc)), 1, "sniff") + t:eq(Ilbm.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF") + local back = Ilbm.decode(Bytes.reader(enc)) :: any + t:eq(back.meta.source.planes, 32, "32 planes") + local _, e = Ilbm.decode(Bytes.reader(buffer.fromstring("FORM\0\0\0\4ILBM"))) + t:check(e and e.code == Err.CORRUPT, "no BMHD") + local _, e2 = Ilbm.decode(Bytes.reader(enc), { maxPixels = 2 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + for _, c in Fx.cases do + if c.name == "hand_transparent.iff" then + local im = Ilbm.decode(Bytes.reader(buffer.fromstring(c.data))) :: any + t:eq(im.meta.text and im.meta.text.name, "tiny", "NAME chunk") + end + end +end +t:fuzz("decode", function(b: buffer) + return Ilbm.decode(Bytes.reader(b)) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index c15bf20..d46124f 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -140,6 +140,8 @@ local function simple(): any return require("@formats/image/xbm") elseif which == "xpm" then return require("@formats/image/xpm") + elseif which == "ilbm" then + return require("@formats/image/ilbm") end return nil end diff --git a/tools/fixtures/ilbm.py b/tools/fixtures/ilbm.py new file mode 100644 index 0000000..1b830da --- /dev/null +++ b/tools/fixtures/ilbm.py @@ -0,0 +1,121 @@ +# IFF ILBM fixtures (tools/fixtures.py): files from netpbm's ppmtoilbm (palette ByteRun1 / uncompressed, few planes, +# HAM6, HAM8, 24-bit deep) and hand-written ones (EHB, chunky PBM, a mask plane, a transparent colour index, an odd +# CMAP), decoded by ilbmtoppm as the reference (alpha separately: ilbmtoppm writes PPM; HAM values within the scaling +# difference: ilbmtoppm shifts, we replicate bits); our encoder's files +# (tools/fixtures/_tex_encode.luau -a ilbm) read by ilbmtoppm. +# tests/gen/ilbm.luau { cases = { { name, data, w, h, rgba, transparent? } }, ours = { ... } } +import importlib.util, os, random, struct + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S = _load("_raster_ref"), _load("_simple") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/ilbm"] + + +def chunk(cid, data): + return cid + struct.pack(">I", len(data)) + data + (b"\0" if len(data) % 2 else b"") + + +def byterun1(row): + out = bytearray() + i = 0 + while i < len(row): + run = 1 + while i + run < len(row) and run < 128 and row[i + run] == row[i]: + run += 1 + if run >= 2: + out += bytes((257 - run, row[i])) + i += run + else: + j = i + while j < len(row) and j - i < 128 and not (j + 1 < len(row) and row[j + 1] == row[j]): + j += 1 + j = max(j, i + 1) + out += bytes((j - i - 1,)) + row[i:j] + i = j + return bytes(out) + + +def planar(w, h, idx, planes, mask=None, comp=True): + rb = ((w + 15) // 16) * 2 + body = bytearray() + for y in range(h): + rows = [] + for k in range(planes): + row = bytearray(rb) + for x in range(w): + if (idx[y * w + x] >> k) & 1: + row[x // 8] |= 0x80 >> (x % 8) + rows.append(bytes(row)) + if mask is not None: + row = bytearray(rb) + for x in range(w): + if mask[y * w + x]: + row[x // 8] |= 0x80 >> (x % 8) + rows.append(bytes(row)) + for row in rows: + body += byterun1(row) if comp else row + return bytes(body) + + +def ilbm(w, h, planes, body, cmap=b"", camg=None, masking=0, trans=0, comp=1, form=b"ILBM", extra=b""): + bmhd = struct.pack(">HHhhBBBxHBBhh", w, h, 0, 0, planes, masking, comp, trans, 10, 11, w, h) + data = form + chunk(b"BMHD", bmhd) + (chunk(b"CMAP", cmap) if cmap else b"") + (chunk(b"CAMG", struct.pack(">I", camg)) if camg is not None else b"") + extra + chunk(b"BODY", body) + return b"FORM" + struct.pack(">I", len(data)) + data + + +def generate(ctx): + rng = random.Random(8) + w = R.Work(ctx) + try: + w.png("photo.png", 37, 23, R.photo(37, 23)) + w.png("pal.png", 31, 19, R.palette_image(31, 19, 60)) + w.png("pal8.png", 26, 11, R.palette_image(26, 11, 7)) + w.sh("netpbm", ["pngtopam photo.png | pamtopnm > photo.ppm", "pngtopam pal.png | pamtopnm > pal.ppm", "pngtopam pal8.png | pamtopnm > pal8.ppm", + "ppmtoilbm pal.ppm > nb_pal.iff", "ppmtoilbm -nocompress pal.ppm > nb_pal_raw.iff", "ppmtoilbm pal8.ppm > nb_3planes.iff", + "ppmtoilbm -ham6 photo.ppm > nb_ham6.iff", "ppmtoilbm -ham8 photo.ppm > nb_ham8.iff", "ppmtoilbm -24force photo.ppm > nb_24.iff"]) + hand = [] + # EHB: 6 planes, 32 colours + W, H = 20, 7 + cm = bytes(rng.randrange(256) for _ in range(32 * 3)) + idx = [rng.randrange(64) for _ in range(W * H)] + hand.append(("hand_ehb.iff", ilbm(W, H, 6, planar(W, H, idx, 6), cm, 0x80), None)) + # chunky PBM (rows padded to even), 256 colours + cm2 = bytes(rng.randrange(256) for _ in range(256 * 3)) + W2 = 14 + idx2 = [rng.randrange(256) for _ in range(W2 * H)] + hand.append(("hand_pbm.lbm", ilbm(W2, H, 8, b"".join(byterun1(bytes(idx2[y * W2:(y + 1) * W2])) for y in range(H)), cm2, form=b"PBM "), None)) + # a mask plane and a transparent colour index + cm3 = bytes(rng.randrange(256) for _ in range(16 * 3)) + idx3 = [rng.randrange(16) for _ in range(W * H)] + mask = [rng.random() < 0.7 for _ in range(W * H)] + hand.append(("hand_mask.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, mask), cm3, masking=1), [not m for m in mask])) + hand.append(("hand_transparent.iff", ilbm(W, H, 4, planar(W, H, idx3, 4, comp=False), cm3, masking=2, trans=5, comp=0, + extra=chunk(b"NAME", b"tiny\0")), [i == 5 for i in idx3])) + for n, data, _ in hand: + w.write(n, data) + names = sorted(f for f in os.listdir(w.dir) if f.endswith(".iff") or f.endswith(".lbm")) + mine = S.ours(ctx, "ilbm") + for n, d in mine.items(): + w.write(n, d) + allnames = names + sorted(mine) + allnames = [n for n in allnames if n != "ours_alpha.ilbm"] # ilbmtoppm reads no 32-plane files + w.sh("netpbm", ["ilbmtoppm %s > %s.ppm" % (n, n) for n in allnames]) + tmap = {n: t for n, _, t in hand} + out = {"cases": [], "ours": []} + for n in allnames: + ww, hh, rgba = R.pnm_rgba(w.read(n + ".ppm")) + c = {"name": n, "data": w.read(n), "w": ww, "h": hh, "rgba": rgba} + if "ham" in n: + # ilbmtoppm scales HAM values by shifting (4-bit v -> v << 4); we replicate the bits (v * 17) + c["tol"] = 15 if "ham6" in n else 3 + if tmap.get(n): + c["transparent"] = [bool(v) for v in tmap[n]] + out["ours" if n.startswith("ours_") else "cases"].append(c) + ctx.emit("ilbm", out) + finally: + w.close() From 406b894635bc9e60d421aed19dccd17e5b0bf931 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:03:40 -0500 Subject: [PATCH 47/54] ws-3d3: model/3ds writer samples camera / light channels through codecs/model/Sampler (drops its local sampler); scene.md intro wrap --- docs/guide/scene.md | 3 ++- src/Formats/Registry.luau | 2 +- src/Formats/model/3ds/Write.luau | 42 +++++--------------------------- src/Formats/model/3ds/init.luau | 2 +- 4 files changed, 10 insertions(+), 39 deletions(-) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 99be4f5..9f51b27 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -3,7 +3,8 @@ Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave LWO, DirectX .x, IQM) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats -(STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. +(STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through +`F.ops.mesh`. ```luau local scene = assert(F.model.load(texturedGltfText)) diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 75e78bb..d152f91 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -368,7 +368,7 @@ local list: { Entry } = { path = "model/3ds", extensions = { "3ds" }, mime = { "application/x-3ds", "image/x-3ds" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, load = function() return require("@formats/model/3ds") diff --git a/src/Formats/model/3ds/Write.luau b/src/Formats/model/3ds/Write.luau index 8718a7b..4781560 100644 --- a/src/Formats/model/3ds/Write.luau +++ b/src/Formats/model/3ds/Write.luau @@ -10,6 +10,7 @@ -- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix). local Bytes = require("@formats/core/Bytes") local Types = require("@formats/Types") +local Sampler = require("@formats/codecs/model/Sampler") local Mat4 = require("@formats/codecs/model/Mat4") local Flatten = require("@formats/codecs/model/MeshFlatten") local Read = require("@formats/model/3ds/Read") @@ -127,44 +128,13 @@ local function conj(q: { number }): { number } return { -q[1], -q[2], -q[3], q[4] } end --- a channel's value at a time (linear; rotations normalized lerp along the short way) +-- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE) local function sample(ch: Types.Channel, t: number): { number } - local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any - local n = ch.input.count - local comps = if ch.path == "rotation" then 4 else 3 - local cubic = ch.interpolation == "CUBICSPLINE" - local function v(k: number): { number } - local e = if cubic then k * 3 + 1 else k - local r = table.create(comps, 0) - for c = 1, comps do - r[c] = OUT(e, c - 1) - end - return r + local f = Sampler.channel(ch) + if not f then + return if ch.path == "rotation" then { 0, 0, 0, 1 } else { 0, 0, 0 } end - if n == 0 then - return if comps == 4 then { 0, 0, 0, 1 } else { 0, 0, 0 } - end - if t <= IN(0, 0) then - return v(0) - end - for k = 0, n - 2 do - local t0, t1 = IN(k, 0), IN(k + 1, 0) - if t <= t1 then - if ch.interpolation == "STEP" or t1 <= t0 then - return if t >= t1 then v(k + 1) else v(k) - end - local u = (t - t0) / (t1 - t0) - local a, b = v(k), v(k + 1) - if comps == 4 and a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] < 0 then - b = { -b[1], -b[2], -b[3], -b[4] } - end - for c = 1, comps do - a[c] += (b[c] - a[c]) * u - end - return a - end - end - return v(n - 1) + return f(t) end -- ------------------------------------------------------------------------------------------------ materials diff --git a/src/Formats/model/3ds/init.luau b/src/Formats/model/3ds/init.luau index 2e7b581..acf355e 100644 --- a/src/Formats/model/3ds/init.luau +++ b/src/Formats/model/3ds/init.luau @@ -35,7 +35,7 @@ local ThreeDs = { category = "model", extensions = { "3ds" }, mime = { "application/x-3ds", "image/x-3ds" }, - deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" }, caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true }, } From 9e114fba8ba0161dd727ee471e8923adeb08710b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:07:07 -0500 Subject: [PATCH 48/54] ws-tex: image/icns (read RLE / ARGB / 1-bit / PNG-hook entries, JP2 skipped; write PNG via encodeImage or RLE) Tested against libicns (png2icns / icns2png -x), Pillow's writer and a hand-written file. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/image/icns/init.luau | 337 +++++++++++++++++++++++++++++++ tests/image/icns.luau | 84 ++++++++ tools/fixtures/_tex_encode.luau | 12 ++ tools/fixtures/icns.py | 73 +++++++ 6 files changed, 519 insertions(+) create mode 100644 src/Formats/image/icns/init.luau create mode 100644 tests/image/icns.luau create mode 100644 tools/fixtures/icns.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 1fc6262..3c6c4b8 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -10,6 +10,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` | | image | gif | .gif | yes | yes | animation: true, alpha: true, palette: true, depths: 1, 2, 4, 8 | `tests/image/gif.luau` | | image | hdr | .hdr .pic .rgbe | yes | yes | alpha: false, float: true, depths: 32 | `tests/image/hdr.luau` | +| image | icns | .icns | yes | yes | alpha: true, frames: true, depths: 1, 24, 32 | `tests/image/icns.luau` | | image | ico | .ico .cur | yes | yes | alpha: true, frames: true, depths: 1, 4, 8, 16, 24, 32 | `tests/image/ico.luau` | | image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 7a27212..e82c9d8 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -74,6 +74,18 @@ local list: { Entry } = { return require("@formats/image/hdr") end, }, + { + name = "icns", + category = "image", + path = "image/icns", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, + load = function() + return require("@formats/image/icns") + end, + }, { name = "ico", category = "image", diff --git a/src/Formats/image/icns/init.luau b/src/Formats/image/icns/init.luau new file mode 100644 index 0000000..4124dc8 --- /dev/null +++ b/src/Formats/image/icns/init.luau @@ -0,0 +1,337 @@ +--!strict +-- image/icns: Apple Icon Image files (the icns resource type; new code; chunks through containers/Chunks). Decode: +-- the legacy RGB entries is32 / il32 / ih32 / it32 (the icns RLE, or raw) with their s8mk / l8mk / h8mk / t8mk alpha +-- masks, ic04 / ic05 ARGB entries, the 1-bit ics# / ICN# / ich# / icm# icons with their masks, and PNG entries in any +-- type (icp4 .. ic14) through the api hook opts.decodeImage. JPEG 2000 entries are skipped (meta.skipped lists them), +-- like 4 / 8-bit palette entries and nested dark-mode / TOC chunks. The image is the largest entry; img.frames lists +-- every decoded entry (each with meta.source = { type = "ic07", ... }); a file of JPEG 2000 entries only returns +-- UNSUPPORTED. Encode: the image and every img.frames image (square, 16 .. 1024): PNG entries through opts.encodeImage +-- (icp4 / icp5 / icp6 / ic07 / ic08 / ic09 / ic10), or without the hook (or opts.legacy) the RLE entries for 16 / 32 / +-- 48 / 128 with masks. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Types = require("@formats/Types") +local Chunks = require("@formats/containers/Chunks") + +-- ------------------------------------------------------------------------------------------------ contract +local Icns = { + name = "icns", + category = "image", + extensions = { "icns" }, + mime = { "image/icns", "image/x-icns" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "containers/Chunks" }, + caps = { decode = true, encode = true, alpha = true, frames = true, depths = { 1, 24, 32 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes PNG entries (the api passes one) + maxPixels: number?, -- refuse entries larger than this (default 2^22) +} +export type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes PNG entries (the api passes one) + legacy: boolean?, -- RLE entries (16 / 32 / 48 / 128) even when encodeImage is there (default false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local RGB: { [string]: { any } } = { is32 = { 16, "s8mk" }, il32 = { 32, "l8mk" }, ih32 = { 48, "h8mk" }, it32 = { 128, "t8mk" } } +local MASKS: { [string]: boolean } = { s8mk = true, l8mk = true, h8mk = true, t8mk = true } +local ARGB: { [string]: number } = { ic04 = 16, ic05 = 32 } +local MONO: { [string]: { number } } = { ["ics#"] = { 16, 16 }, ["ICN#"] = { 32, 32 }, ["ich#"] = { 48, 48 }, ["icm#"] = { 16, 12 } } +local PNG_TYPES: { [number]: string } = { [16] = "icp4", [32] = "icp5", [64] = "icp6", [128] = "ic07", [256] = "ic08", [512] = "ic09", [1024] = "ic10" } +local LEGACY: { [number]: { string } } = { [16] = { "is32", "s8mk" }, [32] = { "il32", "l8mk" }, [48] = { "ih32", "h8mk" }, [128] = { "it32", "t8mk" } } +local LAYOUT: Chunks.Layout = { + bigEndian = true, + resize = function(_id: string, declared: number): number? + return math.max(0, declared - 8) + end, +} + +local readu8 = buffer.readu8 + +-- ------------------------------------------------------------------------------------------------ sniff +function Icns.sniff(r: Bytes.Reader): number + return Sniff.magic(r, "icns") +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the icns RLE of n channels of count bytes each from [p, stop) into out at channel offsets (interleaved, step 4) +local function unrle(b: buffer, p: number, stop: number, out: buffer, channels: { number }, count: number): boolean + for _, ch in channels do + local i = 0 + while i < count do + if p >= stop then + return false + end + local c = readu8(b, p) + p += 1 + if c >= 128 then + local n = c - 125 + if p >= stop then + return false + end + local v = readu8(b, p) + p += 1 + for _ = 1, math.min(n, count - i) do + buffer.writeu8(out, i * 4 + ch, v) + i += 1 + end + else + local n = c + 1 + if p + n > stop then + return false + end + for k = 0, math.min(n, count - i) - 1 do + buffer.writeu8(out, (i + k) * 4 + ch, readu8(b, p + k)) + end + i += math.min(n, count - i) + p += n + end + end + end + return true +end + +local function isPng(b: buffer, p: number, n: number): boolean + return n >= 8 and buffer.readstring(b, p, 8) == "\137PNG\r\n\26\n" +end +local function isJp2(b: buffer, p: number, n: number): boolean + return n >= 12 and (buffer.readstring(b, p, 12) == "\0\0\0\12jP \r\n\135\n" or buffer.readstring(b, p, 4) == "\255\79\255\81") +end + +function Icns.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local b, o, limit = r.buf, r.base, r.limit + if limit - o < 8 or buffer.readstring(b, o, 4) ~= "icns" then + return nil, Err.new(Err.CORRUPT, "not an icns file", o) + end + local total = bit32.byteswap(buffer.readu32(b, o + 4)) + local stop = math.min(limit, o + math.max(total, 8)) + local list = Chunks.walk(b, o + 8, stop, LAYOUT) + local decodeImage = opts and opts.decodeImage + local maxPixels = opts and opts.maxPixels or 2 ^ 22 + local masks: { [string]: Chunks.Chunk } = {} + for _, c in list do + if MASKS[c.id] then + masks[c.id] = c + end + end + local frames: { Types.Frame } = {} + local skipped: { string } = {} + local function add(im: Types.Image, typ: string, extra: { [string]: any }?) + local src: { [string]: any } = { format = "icns", type = typ } + if extra then + for k, v in extra do + src[k] = v + end + end + im.meta.source = src :: any + table.insert(frames, { image = im, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame) + end + for _, c in list do + local id, p, n = c.id, c.offset, c.avail + if c.truncated then + table.insert(skipped, id .. " (truncated)") + elseif RGB[id] then + local size = RGB[id][1] + local im = Types.Image.new(size, size, "rgba8") + local px = im.pixels + local q = if id == "it32" then p + 4 else p + local count = size * size + local ok + if n == count * 3 then + for i = 0, count - 1 do + for k = 0, 2 do + buffer.writeu8(px, i * 4 + k, readu8(b, p + k * count + i)) + end + end + ok = true + else + ok = unrle(b, q, p + n, px, { 0, 1, 2 }, count) + end + local m = masks[RGB[id][2]] + for i = 0, count - 1 do + buffer.writeu8(px, i * 4 + 3, if m and m.avail >= count then readu8(b, m.offset + i) else 255) + end + if ok then + add(im, id, { bitDepth = 24, mask = m ~= nil }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif ARGB[id] and n >= 4 and buffer.readstring(b, p, 4) == "ARGB" then + local size = ARGB[id] + local im = Types.Image.new(size, size, "rgba8") + if unrle(b, p + 4, p + n, im.pixels, { 3, 0, 1, 2 }, size * size) then + add(im, id, { bitDepth = 32 }) + else + table.insert(skipped, id .. " (bad RLE)") + end + elseif MONO[id] then + local w, h = MONO[id][1], MONO[id][2] + local bytes = w * h // 8 + if n >= bytes * 2 then + local im = Types.Image.new(w, h, "rgba8") + for i = 0, w * h - 1 do + local bit = bit32.band(bit32.rshift(readu8(b, p + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + local mbit = bit32.band(bit32.rshift(readu8(b, p + bytes + bit32.rshift(i, 3)), 7 - bit32.band(i, 7)), 1) + buffer.writeu32(im.pixels, i * 4, (if bit == 1 then 0 else 0xFFFFFF) + mbit * 0xFF000000) + end + add(im, id, { bitDepth = 1 }) + end + elseif isPng(b, p, n) then + if decodeImage then + local sub = buffer.create(n) + buffer.copy(sub, 0, b, p, n) + local okc, im, ierr = pcall(decodeImage, sub) + if okc and im then + if im.width * im.height <= maxPixels then + add(im :: Types.Image, id, { png = true }) + else + table.insert(skipped, id .. " (over maxPixels)") + end + else + table.insert(skipped, id .. " (PNG: " .. tostring(if okc then ierr else im) .. ")") + end + else + table.insert(skipped, id .. " (PNG: no decodeImage hook)") + end + elseif isJp2(b, p, n) then + table.insert(skipped, id .. " (JPEG 2000)") + elseif not MASKS[id] and id ~= "TOC " and id ~= "icnV" and id ~= "name" and id ~= "info" then + table.insert(skipped, id) + end + end + if #frames == 0 then + if #skipped > 0 then + return nil, Err.new(Err.UNSUPPORTED, "no decodable entry (" .. table.concat(skipped, ", ") .. ")") + end + return nil, Err.new(Err.CORRUPT, "no icon entries", o + 8) + end + local main = frames[1].image + for _, f in frames do + if f.image.width * f.image.height > main.width * main.height then + main = f.image + end + end + local img = Types.Image.new(0, 0, "rgba8") + img.width, img.height, img.pixels = main.width, main.height, main.pixels + if #frames > 1 then + img.frames = frames + end + if #skipped > 0 then + img.meta.skipped = skipped + end + img.meta.source = { format = "icns", type = main.meta.source and main.meta.source.type, entries = #frames } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the icns RLE of one channel (count bytes, step 4 from ch) into w +local function rle(w: Bytes.Writer, px: buffer, ch: number, count: number) + local i = 0 + while i < count do + local v = readu8(px, i * 4 + ch) + local run = 1 + while i + run < count and run < 130 and readu8(px, (i + run) * 4 + ch) == v do + run += 1 + end + if run >= 3 then + w:u8(run + 125) + w:u8(v) + i += run + else + local lit = 0 + while i + lit < count and lit < 128 do + local a = readu8(px, (i + lit) * 4 + ch) + if i + lit + 2 < count and readu8(px, (i + lit + 1) * 4 + ch) == a and readu8(px, (i + lit + 2) * 4 + ch) == a then + break + end + lit += 1 + end + lit = math.max(lit, 1) + w:u8(lit - 1) + for k = 0, lit - 1 do + w:u8(readu8(px, (i + k) * 4 + ch)) + end + i += lit + end + end +end + +function Icns.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local images: { Types.Image } = {} + local seen: { [number]: boolean } = {} + local function take(im: Types.Image): Err.Err? + if type(im) ~= "table" or im.format ~= "rgba8" or im.width ~= im.height then + return Err.new(Err.ARG, "icons are square rgba8 images") + end + if not seen[im.width] then + seen[im.width] = true + table.insert(images, im) + end + return nil + end + local e = take(img) + if e then + return nil, e + end + if type(img.frames) == "table" then + for _, f in img.frames do + local fe = take(f.image) + if fe then + return nil, fe + end + end + end + table.sort(images, function(a: Types.Image, c: Types.Image): boolean + return a.width < c.width + end) + local encodeImage = opts and opts.encodeImage + local legacy = (opts and opts.legacy) or encodeImage == nil + local body = Bytes.writer() + local function chunk(id: string, data: buffer) + body:string(id) + body:u32be(buffer.len(data) + 8) + body:bytes(data) + end + for _, im in images do + local s = im.width + if legacy and LEGACY[s] then + local types = LEGACY[s] + local w = Bytes.writer() + if s == 128 then + w:u32be(0) + end + for ch = 0, 2 do + rle(w, im.pixels, ch, s * s) + end + chunk(types[1], w:finish()) + local m = buffer.create(s * s) + for i = 0, s * s - 1 do + buffer.writeu8(m, i, readu8(im.pixels, i * 4 + 3)) + end + chunk(types[2], m) + elseif encodeImage and PNG_TYPES[s] then + local ok, png, perr = pcall(encodeImage, im, "png") + if not ok or not png then + return nil, Err.new(Err.ARG, "PNG entry " .. s .. ": " .. tostring(if ok then perr else png)) + end + chunk(PNG_TYPES[s], png :: buffer) + else + return nil, Err.new(Err.ARG, string.format("no icns entry for %d x %d%s", s, s, if encodeImage then "" else " without an encodeImage hook (16 / 32 / 48 / 128 only)")) + end + end + local data = body:finish() + local out = Bytes.writer(buffer.len(data) + 8) + out:string("icns") + out:u32be(buffer.len(data) + 8) + out:bytes(data) + return out:finish(), nil +end + +return Icns diff --git a/tests/image/icns.luau b/tests/image/icns.luau new file mode 100644 index 0000000..9e0a663 --- /dev/null +++ b/tests/image/icns.luau @@ -0,0 +1,84 @@ +-- image/icns tests: a libicns file (RLE entries + masks, JPEG 2000 entries skipped), a Pillow file (PNG entries through +-- the decodeImage hook) and a hand-written one (ics#, raw is32, ic04 ARGB) against icns2png's / the written pixels; +-- our RLE file read back by icns2png; PNG entries through encodeImage; errors; the fuzz no-throw pass. Fixtures: +-- tools/fixtures/icns.py. +local T = require("@tests/T") +local Icns = require("@formats/image/icns") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/icns") + +local t = T.suite("icns") +t:eq(Icns.name, "icns", "name") +t:check(Icns.caps.decode and Icns.caps.encode, "caps") + +local hooks = { + decodeImage = function(b: buffer): (any, any) + return Png.decode(Bytes.reader(b)) + end, + encodeImage = function(img: any, _fmt: string): (any, any) + return Png.encode(img) + end, +} + +local function check(c: any) + local img, err = Icns.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) + t:check(img, c.name .. ": " .. tostring(err)) + local frames = img.frames or { { image = img } } + t:check(#frames >= #c.entries, c.name .. ": entries") -- icns2png writes one file per size (@2x entries collide) + for _, e in c.entries do + local found = nil + for _, f in frames do + local im = f.image + if im.width == e.w and im.height == e.h and (e.type == "" or im.meta.source.type == e.type) then + found = im + end + end + t:check(found, c.name .. ": entry " .. e.type .. " " .. e.w) + if found then + local d = R.maxDiff(found.pixels, buffer.fromstring(e.rgba), e.w * e.h) + t:eq(d, 0, string.format("%s: %s %dx%d pixels", c.name, e.type, e.w, e.h)) + end + end + t:eq(if img.meta.skipped then #img.meta.skipped else 0, c.skipped or 0, c.name .. ": skipped entries") + return img +end +for _, c in Fx.cases do + check(c) +end +for _, o in Fx.ours do + check(o) +end +t:note("%d files and our encoder's file match", #Fx.cases) + +do + -- PNG entries through the hooks, legacy entries without them + local img = Types.Image.new(64, 64) + for i = 0, 64 * 64 - 1 do + buffer.writeu32(img.pixels, i * 4, i * 2654435761 % 4294967296) + end + local small = Types.Image.new(16, 16) + buffer.fill(small.pixels, 0, 200) + img.frames = { { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" }, { image = small, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } } + local enc = Icns.encode(img, hooks) :: buffer + local back = Icns.decode(Bytes.reader(enc), hooks) :: any + t:check(back and back.width == 64 and buffer.tostring(back.pixels) == buffer.tostring(img.pixels), "PNG entries round trip") + t:eq(#back.frames, 2, "two sizes") + local _, e = Icns.encode(img) + t:check(e and e.code == Err.ARG, "64 x 64 needs the PNG hook") + local leg = Icns.encode(small) :: buffer + local lb = Icns.decode(Bytes.reader(leg)) :: any + t:eq(buffer.tostring(lb.pixels), buffer.tostring(small.pixels), "legacy round trip") + local _, e2 = Icns.decode(Bytes.reader(enc)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "PNG entries without the hook: UNSUPPORTED") + t:eq(Icns.sniff(Bytes.reader(enc)), 1, "sniff") + local _, e3 = Icns.encode(Types.Image.new(10, 12)) + t:check(e3 and e3.code == Err.ARG, "not square") +end +t:fuzz("decode", function(b: buffer) + return Icns.decode(Bytes.reader(b), hooks) +end, R.samples(Fx.cases), { mutations = 6 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index d46124f..89a285e 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -156,3 +156,15 @@ if Fmt then end end end + +if which == "icns" then + -- square icons 16 / 32 / 48 / 128 as RLE entries (no encodeImage hook here) + local Icns = require("@formats/image/icns") + local base = image(128, 128, "rgba8", 1) + base.frames = {} + for i, s in { 16, 32, 48, 128 } do + base.frames[i] = { image = image(s, s, "rgba8", i), delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } + end + base.pixels = base.frames[4].image.pixels + emit("ours_legacy.icns", Icns.encode(base)) +end diff --git a/tools/fixtures/icns.py b/tools/fixtures/icns.py new file mode 100644 index 0000000..7602a7d --- /dev/null +++ b/tools/fixtures/icns.py @@ -0,0 +1,73 @@ +# ICNS fixtures (tools/fixtures.py): a libicns png2icns file (is32 / il32 / ih32 RLE entries with their masks, ic07 / +# ic08 PNG entries), a JPEG 2000 entry that must be skipped (hand-written into hand.icns), a Pillow file (PNG entries), a hand-written one (ics# / ICN# +# 1-bit icons, an ic04 ARGB entry, an uncompressed is32); every entry's reference pixels from icns2png -x (libicns) +# or written here; our encoder's RLE file (tools/fixtures/_tex_encode.luau -a icns) read back by icns2png. +# tests/gen/icns.luau { cases = { { name, data, entries = { { type, w, h, rgba } }, skipped } }, ours = { ... } } +import importlib.util, os, re, struct + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/image/icns"] + + +def extract(ctx, w, name): + """icns2png -x name -> { 'WxH': rgba } (one per extracted entry)""" + log = w.sh("libicns", ["mkdir -p x_%s && cd x_%s && icns2png -x ../%s" % (name, name, name)]).decode() + files = sorted(f for f in os.listdir(w.path("x_" + name)) if f.endswith(".png")) + out = {} + for f, (mode, ww, hh, raw) in zip(files, T.pillow(ctx, [w.read(os.path.join("x_" + name, f)) for f in files])): + out["%dx%d" % (ww, hh)] = T.rgba_from(mode, raw) + return out + + +def generate(ctx): + w = R.Work(ctx) + try: + for s in (16, 32, 48, 128, 256): + w.png("i%d.png" % s, s, s, R.photo(s, s, s, True)) + w.sh("libicns", ["png2icns libicns.icns i16.png i32.png i48.png i128.png i256.png"]) + w.png("p64.png", 64, 64, R.photo(64, 64, 9, True)) + ctx.python(["pillow"], "from PIL import Image\nimport os\nos.chdir(%r)\nImage.open('p64.png').save('pillow.icns')\n" % w.dir) + cases = [] + lib = extract(ctx, w, "libicns.icns") + cases.append({"name": "libicns.icns", "data": w.read("libicns.icns"), "skipped": 0, + "entries": [{"type": t, "w": s, "h": s, "rgba": lib["%dx%d" % (s, s)]} for t, s in (("is32", 16), ("il32", 32), ("ih32", 48), ("ic07", 128), ("ic08", 256))]}) + pil = extract(ctx, w, "pillow.icns") + cases.append({"name": "pillow.icns", "data": w.read("pillow.icns"), "skipped": 0, + "entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(pil.items())]}) + # hand-written: ics# (16x16 1-bit + mask), an uncompressed is32 + s8mk, an ic04 ARGB with RLE runs + bits = bytes((0xF0 if (i // 2) % 2 else 0x0F) for i in range(32)) + mask = bytes((0xFF if i < 24 else 0x00) for i in range(32)) + mono = [] + for i in range(256): + b = (bits[i // 8] >> (7 - i % 8)) & 1 + m = (mask[i // 8] >> (7 - i % 8)) & 1 + mono += [0, 0, 0] if b else [255, 255, 255] + mono.append(255 if m else 0) + raw = bytes((i * 3 + k * 50) % 256 for k in range(3) for i in range(256)) + alpha = bytes((i * 7) % 256 for i in range(256)) + rgb = bytes(v for i in range(256) for v in (raw[i], raw[256 + i], raw[512 + i], alpha[i])) + def ch(t, d): + return t + struct.pack(">I", len(d) + 8) + d + # ARGB channels: A = 256 x 77 (two runs of 128), then R / G / B as runs + argb = b"ARGB" + bytes((253, 77, 253, 77)) + bytes((253, 10, 253, 10)) + bytes((253, 20, 253, 20)) + bytes((253, 30, 253, 30)) + jp2 = b"\0\0\0\x0cjP \r\n\x87\n" + b"\0" * 20 + body = ch(b"ics#", bits + mask) + ch(b"is32", raw) + ch(b"s8mk", alpha) + ch(b"ic04", argb) + ch(b"ic09", jp2) + hand = b"icns" + struct.pack(">I", len(body) + 8) + body + cases.append({"name": "hand.icns", "data": hand, "skipped": 1, "entries": [ + {"type": "ics#", "w": 16, "h": 16, "rgba": bytes(mono)}, {"type": "is32", "w": 16, "h": 16, "rgba": rgb}, + {"type": "ic04", "w": 16, "h": 16, "rgba": bytes((10, 20, 30, 77)) * 256}]}) + mine = S.ours(ctx, "icns") + ours = [] + for n, d in mine.items(): + w.write(n, d) + ex = extract(ctx, w, n) + ours.append({"name": n, "data": d, "entries": [{"type": "", "w": int(k.split("x")[0]), "h": int(k.split("x")[1]), "rgba": v} for k, v in sorted(ex.items())]}) + ctx.emit("icns", {"cases": cases, "ours": ours}) + finally: + w.close() From 00d47096ed88e21897b8c218b87aec5eb77e7216 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:09:35 -0500 Subject: [PATCH 49/54] ws-tex: image/ani (animated cursors -> frames through the decodeImage hook; write through encodeImage) seq / rate steps, jiffy delays, CUR hotspots, INFO title; AF_ICON clear is UNSUPPORTED. Tested against Pillow-written ICO / CUR frames assembled into ANI files. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 +++ src/Formats/image/ani/init.luau | 183 ++++++++++++++++++++++++++++++++ tests/image/ani.luau | 72 +++++++++++++ tools/fixtures/ani.py | 66 ++++++++++++ 5 files changed, 334 insertions(+) create mode 100644 src/Formats/image/ani/init.luau create mode 100644 tests/image/ani.luau create mode 100644 tools/fixtures/ani.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 3c6c4b8..2419761 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -5,6 +5,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| +| image | ani | .ani | yes | yes | alpha: true, animation: true, frames: true | `tests/image/ani.luau` | | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | | image | exr | .exr | yes | yes | alpha: true, float: true, hdr: true, depths: 16, 32, multipart: true, tiled: true | `tests/image/exr.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index e82c9d8..267ea5f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -14,6 +14,18 @@ export type Entry = { } local list: { Entry } = { + { + name = "ani", + category = "image", + path = "image/ani", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, + load = function() + return require("@formats/image/ani") + end, + }, { name = "bmp", category = "image", diff --git a/src/Formats/image/ani/init.luau b/src/Formats/image/ani/init.luau new file mode 100644 index 0000000..b9f0ceb --- /dev/null +++ b/src/Formats/image/ani/init.luau @@ -0,0 +1,183 @@ +--!strict +-- image/ani: Windows animated cursors (RIFF "ACON": the anih header, rate / seq chunks, LIST fram of icon chunks; +-- containers/Riff; new code). Decode: every step of the animation as img.frames (the seq order when there is one, +-- each step's rate or the default iDispRate in jiffies of 1/60 s as the delay), the icon chunks (ICO / CUR files) +-- through the api hook opts.decodeImage (F.load passes it; without it: UNSUPPORTED), the hotspots of CUR frames +-- (frame image meta.hotspot), INFO title / author (meta.text). The image is the first step; img.loops = 0 (cursors +-- loop forever). Encode: img.frames (or the image) through opts.encodeImage(frame, "ico") as icon chunks, with a +-- rate chunk when the delays differ. Not supported: raw (non-icon) frame bitmaps (AF_ICON clear: UNSUPPORTED). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Riff = require("@formats/containers/Riff") + +-- ------------------------------------------------------------------------------------------------ contract +local Ani = { + name = "ani", + category = "image", + extensions = { "ani" }, + mime = { "application/x-navi-animation" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Riff" }, + caps = { decode = true, encode = true, alpha = true, animation = true, frames = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the ICO / CUR frames (the api passes one) + maxFrames: number?, -- refuse more steps (default 10000) +} +export type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the ICO / CUR frames (the api passes one) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Ani.sniff(r: Bytes.Reader): number + return if r:peek(4) == "RIFF" and r:peek(4, 8) == "ACON" then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Ani.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local f, ferr = Riff.read(r) + if not f then + return nil, ferr + end + if f.form ~= "ACON" then + return nil, Err.new(Err.CORRUPT, "not an ACON form", r.base + 8) + end + local anih = Riff.find(f, "anih") + if not anih or anih.avail < 36 then + return nil, Err.new(Err.CORRUPT, "missing anih header", r.base + 12) + end + local a = anih.offset + local nFrames, nSteps = Riff.u32(f, a + 4), Riff.u32(f, a + 8) + local dispRate, flags = Riff.u32(f, a + 28), Riff.u32(f, a + 32) + local maxFrames = opts and opts.maxFrames or 10000 + if nSteps == 0 then + nSteps = nFrames + end + if nFrames > maxFrames or nSteps > maxFrames then + return nil, Err.new(Err.LIMIT, "too many frames", a + 4) + end + if bit32.band(flags, 1) == 0 then + return nil, Err.new(Err.UNSUPPORTED, "raw frame bitmaps (AF_ICON clear)", a + 32) + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the decodeImage hook") + end + -- the icon chunks + local icons: { Types.Image } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "fram" then + for _, ic in Riff.list(f, c) do + if ic.id == "icon" then + local sub = buffer.create(ic.avail) + buffer.copy(sub, 0, f.buf, ic.offset, ic.avail) + local ok, im, ierr = pcall(decodeImage, sub) + if not ok or not im then + return nil, Err.new(Err.CORRUPT, "frame " .. (#icons + 1) .. ": " .. tostring(if ok then ierr else im), ic.offset) + end + table.insert(icons, im :: Types.Image) + end + end + end + end + if #icons == 0 then + return nil, Err.new(Err.TRUNCATED, "no icon frames") + end + local rate = Riff.find(f, "rate") + local seq = Riff.find(f, "seq ") + local frames: { Types.Frame } = {} + for s = 0, nSteps - 1 do + local idx = s + if seq and seq.avail >= (s + 1) * 4 then + idx = Riff.u32(f, seq.offset + s * 4) + end + local im = icons[idx + 1] + if not im then + if s >= #icons and not seq then + break -- fewer icons than steps: keep what is there + end + return nil, Err.new(Err.CORRUPT, "step " .. s .. " names frame " .. idx) + end + local jiffies = dispRate + if rate and rate.avail >= (s + 1) * 4 then + jiffies = Riff.u32(f, rate.offset + s * 4) + end + table.insert(frames, { image = im, delay = jiffies / 60, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame) + end + local first = frames[1].image + local img = Types.Image.new(0, 0, first.format) + img.width, img.height, img.pixels = first.width, first.height, first.pixels + img.frames = frames + img.loops = 0 + img.meta.hotspot = first.meta.hotspot + local text: { [string]: string } = {} + for _, c in f.chunks do + if c.id == "LIST" and Riff.listType(f, c) == "INFO" then + for _, it in Riff.list(f, c) do + local key = if it.id == "INAM" then "title" elseif it.id == "IART" then "author" else nil + if key then + text[key] = (string.gsub(buffer.readstring(f.buf, it.offset, it.avail), "%z+$", "")) + end + end + end + end + if next(text) then + img.meta.text = text + end + img.meta.source = { format = "ani", frames = #icons, steps = #frames, sequence = seq ~= nil, rate = dispRate } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Ani.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "needs an Image") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "icon frames need the encodeImage hook") + end + local frames: { Types.Frame } = if type(img.frames) == "table" and #img.frames > 0 then img.frames else { { image = img, delay = 1 / 6, x = 0, y = 0, dispose = "background", blend = "source" } :: Types.Frame } + local w = Riff.writer("ACON") + local jiffies: { number } = {} + local same = true + for i, fr in frames do + jiffies[i] = math.max(1, math.floor((fr.delay or 0) * 60 + 0.5)) + same = same and jiffies[i] == jiffies[1] + end + local head = Bytes.writer(36) + head:u32le(36) + head:u32le(#frames) + head:u32le(#frames) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(0) + head:u32le(jiffies[1]) + head:u32le(1) + w:chunk("anih", head:finish()) + if not same then + local rw = Bytes.writer(#frames * 4) + for _, j in jiffies do + rw:u32le(j) + end + w:chunk("rate", rw:finish()) + end + local items = {} + for i, fr in frames do + local im = fr.image + local ok, data, err = pcall(encodeImage, im, "ico") + if not ok or not data then + return nil, Err.new(Err.ARG, "frame " .. i .. ": " .. tostring(if ok then err else data)) + end + table.insert(items, { "icon", data }) + end + w:list("fram", items) + return w:finish() +end + +return Ani diff --git a/tests/image/ani.luau b/tests/image/ani.luau new file mode 100644 index 0000000..29c7465 --- /dev/null +++ b/tests/image/ani.luau @@ -0,0 +1,72 @@ +-- image/ani tests: animated cursors around Pillow-written ICO / CUR frames (seq + rate, plain, cursor hotspots, INFO +-- title) against Pillow's frame decodes and the written steps / delays; AF_ICON clear and a missing hook are +-- UNSUPPORTED; the encoder through the ICO hook round-trips; the fuzz no-throw pass. Fixtures: tools/fixtures/ani.py. +local T = require("@tests/T") +local Ani = require("@formats/image/ani") +local Ico = require("@formats/image/ico") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local R = require("@tests/image/_raster") +local Fx = require("@tests/gen/ani") + +local t = T.suite("ani") +t:eq(Ani.name, "ani", "name") +t:check(Ani.caps.decode and Ani.caps.encode, "caps") + +local hooks = { + decodeImage = function(b: buffer): (any, any) + -- Pillow writes the ICO entries as PNG: the ICO decoder gets its own hook + return Ico.decode(Bytes.reader(b), { decodeImage = function(p: buffer): (any, any) + return Png.decode(Bytes.reader(p)) + end }) + end, + encodeImage = function(img: any, _fmt: string): (any, any) + return Ico.encode(img) + end, +} + +for _, c in Fx.cases do + local img, err = Ani.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) + if c.unsupported then + t:check(img == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": UNSUPPORTED") + continue + end + t:check(img, c.name .. ": " .. tostring(err)) + t:check(img.width == c.w and img.height == c.h, c.name .. ": size") + t:eq(#img.frames, #c.steps, c.name .. ": steps") + for i, s in c.steps do + local f = img.frames[i] + t:check(math.abs(f.delay - s.delay) < 1e-9, c.name .. ": step " .. i .. " delay") + t:eq(R.maxDiff(f.image.pixels, buffer.fromstring(c.frames[s.frame]), c.w * c.h), 0, c.name .. ": step " .. i .. " pixels") + end + t:eq(img.loops, 0, c.name .. ": loops forever") + if c.title then + t:eq(img.meta.text.title, c.title, c.name .. ": title") + end + if c.hotspot then + t:check(img.meta.hotspot and img.meta.hotspot.x == c.hotspot[1] and img.meta.hotspot.y == c.hotspot[2], c.name .. ": hotspot") + end + -- re-encode through the ICO hook + local enc, eerr = Ani.encode(img, hooks) + t:check(enc, c.name .. ": encode " .. tostring(eerr)) + local back = Ani.decode(Bytes.reader(enc :: buffer), hooks) :: any + t:eq(#back.frames, #img.frames, c.name .. ": re-encoded steps") + for i, f in back.frames do + t:eq(buffer.tostring(f.image.pixels), buffer.tostring(img.frames[i].image.pixels), c.name .. ": re-encoded frame " .. i) + t:check(math.abs(f.delay - img.frames[i].delay) < 1 / 120, c.name .. ": re-encoded delay " .. i) + end +end +do + local c = Fx.cases[1] + t:eq(Ani.sniff(Bytes.reader(buffer.fromstring(c.data))), 1, "sniff") + t:eq(Ani.sniff(Bytes.reader(buffer.fromstring("RIFF\0\0\0\0WAVE"))), 0, "sniff WAVE") + local _, e = Ani.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(e and e.code == Err.UNSUPPORTED, "no hook") + local _, e2 = Ani.encode(Ico.decode(Bytes.reader(buffer.fromstring(c.data))) or ({ pixels = buffer.create(4) } :: any)) + t:check(e2 ~= nil, "encode without the hook") +end +t:fuzz("decode", function(b: buffer) + return Ani.decode(Bytes.reader(b), hooks) +end, R.samples(Fx.cases), { mutations = 10 }) +t:done() diff --git a/tools/fixtures/ani.py b/tools/fixtures/ani.py new file mode 100644 index 0000000..fcafb8c --- /dev/null +++ b/tools/fixtures/ani.py @@ -0,0 +1,66 @@ +# ANI fixtures (tools/fixtures.py): animated cursors assembled here around ICO / CUR frames written by Pillow (32 x 32 +# RGBA; the CUR ones patched from Pillow's ICO with hotspots): with seq + rate chunks, with neither, with INFO text, and +# one with AF_ICON clear (UNSUPPORTED). References: Pillow's decode of every frame, the step order and delays here. +# tests/gen/ani.luau { cases = { { name, data, w, h, steps = { { frame, delay } }, frames = { rgba }, hotspot?, +# title?, unsupported? } } } +import importlib.util, os, struct + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, T = _load("_raster_ref"), _load("_tex_reference") + + +def chunk(cid, data): + return cid + struct.pack(" Date: Sat, 31 Oct 2026 15:12:53 -0500 Subject: [PATCH 50/54] ws-tex: layered/ora (OpenRaster read + write through the PNG hooks) stack.xml tree (nested isolate / auto stacks, offsets, opacity, visibility, svg composite-ops), mergedimage, thumbnail. Tested against spec-built files and our file taken apart by python zipfile / ElementTree / Pillow. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 ++ src/Formats/layered/ora/init.luau | 293 ++++++++++++++++++++++++++++++ tests/layered/ora.luau | 124 +++++++++++++ tools/fixtures/_tex_encode.luau | 23 +++ tools/fixtures/ora.py | 95 ++++++++++ 6 files changed, 548 insertions(+) create mode 100644 src/Formats/layered/ora/init.luau create mode 100644 tests/layered/ora.luau create mode 100644 tools/fixtures/ora.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2419761..da7f1e1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -80,6 +80,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` | | vector | tiled | .tmx .tmj .tsx .tsj | yes | yes | tilesets: true, infinite: true | `tests/vector/tiled.luau` | | layered | aseprite | .aseprite .ase | yes | yes | layers: true, groups: true, animation: true, depths: 8, 16, 32 | `tests/layered/aseprite.luau` | +| layered | ora | .ora | yes | yes | layers: true, groups: true, depths: 8 | `tests/layered/ora.luau` | | layered | psd | .psd .psb | yes | yes | layers: true, groups: true, depths: 1, 8, 16, 32 | `tests/layered/psd.luau` | | subtitle | ass | .ass .ssa | yes | yes | styles: true | `tests/subtitle/ass.luau` | | subtitle | srt | .srt | yes | yes | styles: false | `tests/subtitle/srt.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 267ea5f..6e1151f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -914,6 +914,18 @@ local list: { Entry } = { return require("@formats/layered/aseprite") end, }, + { + name = "ora", + category = "layered", + path = "layered/ora", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, + load = function() + return require("@formats/layered/ora") + end, + }, { name = "psd", category = "layered", diff --git a/src/Formats/layered/ora/init.luau b/src/Formats/layered/ora/init.luau new file mode 100644 index 0000000..fcc72f1 --- /dev/null +++ b/src/Formats/layered/ora/init.luau @@ -0,0 +1,293 @@ +--!strict +-- layered/ora: OpenRaster (the OpenRaster 0.0.6 specification, freedesktop.org; new code): a zip (containers/Zip) with +-- a stored "mimetype" first, stack.xml (codecs/text/Xml), PNG layers, mergedimage.png and Thumbnails/thumbnail.png. +-- Decode: the stack tree (nested = groups: isolation="auto" is passThrough; name / src / x / y / +-- opacity / visibility / composite-op, svg:* ops mapped to the codecs/image/Blend names, unknown ones kept as written), +-- layers bottom to top as Types.Layered, the PNGs through the api hook opts.decodeImage (F.load passes it; without it: +-- UNSUPPORTED), mergedimage.png as meta.composite, the resolution (meta.dpi). Encode: a Layered (rgba8 layers, groups) +-- with every layer, the merged image (codecs/image/Blend flattens the tree, or opts.composite) and a thumbnail (up to +-- 256 px, nearest) as PNGs through opts.encodeImage. Not supported: non-PNG layer sources, the / / +-- elements (ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Zip = require("@formats/containers/Zip") +local Xml = require("@formats/codecs/text/Xml") +local Blend = require("@formats/codecs/image/Blend") + +-- ------------------------------------------------------------------------------------------------ contract +local Ora = { + name = "ora", + category = "layered", + extensions = { "ora" }, + mime = { "image/openraster" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip", "codecs/text/Xml", "codecs/image/Blend" }, + caps = { decode = true, encode = true, layers = true, groups = true, depths = { 8 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + decodeImage: ((buffer) -> (Types.Image?, Err.Err?))?, -- decodes the PNG layers (the api passes one) + composite: boolean?, -- decode mergedimage.png into meta.composite (default true) + maxLayers: number?, -- default 10000 +} +export type EncodeOptions = { + encodeImage: ((Types.Image, string) -> (buffer?, Err.Err?))?, -- writes the PNGs (the api passes one) + composite: Types.Image?, -- the merged image (default: the layers flattened with codecs/image/Blend) + thumbnail: boolean?, -- write Thumbnails/thumbnail.png (default true) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MIME = "image/openraster" +local OPS: { [string]: string } = { + ["svg:src-over"] = "normal", ["svg:multiply"] = "multiply", ["svg:screen"] = "screen", ["svg:overlay"] = "overlay", + ["svg:darken"] = "darken", ["svg:lighten"] = "lighten", ["svg:color-dodge"] = "colorDodge", ["svg:color-burn"] = "colorBurn", + ["svg:hard-light"] = "hardLight", ["svg:soft-light"] = "softLight", ["svg:difference"] = "difference", + ["svg:exclusion"] = "exclusion", ["svg:hue"] = "hue", ["svg:saturation"] = "saturation", ["svg:color"] = "color", + ["svg:luminosity"] = "luminosity", ["svg:plus"] = "linearDodge", +} +local BACK: { [string]: string } = {} +for k, v in OPS do + BACK[v] = k +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Ora.sniff(r: Bytes.Reader): number + -- a zip whose first (stored) entry is "mimetype" holding image/openraster + if r:peek(4) == "PK\3\4" and r:peek(8, 30) == "mimetype" and r:peek(#MIME, 38) == MIME then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function num(v: any, default: number): number + local n = tonumber(v) + return if n and n == n then n else default +end + +function Ora.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Layered?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local mt = zip:readString("mimetype") + if mt and string.gsub(mt, "%s+$", "") ~= MIME then + return nil, Err.new(Err.CORRUPT, "mimetype is not " .. MIME) + end + local stackText, serr = zip:readString("stack.xml") + if not stackText then + return nil, serr or Err.new(Err.CORRUPT, "missing stack.xml") + end + local doc, xerr = Xml.decode(stackText) + if not doc then + return nil, xerr + end + local root = doc.root + if not root or root.name ~= "image" then + return nil, Err.new(Err.CORRUPT, "stack.xml has no root") + end + local decodeImage = opts and opts.decodeImage + if not decodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the decodeImage hook") + end + local W, H = num(root.attrs.w, 0), num(root.attrs.h, 0) + if W < 1 or H < 1 or W > 65536 or H > 65536 then + return nil, Err.new(Err.CORRUPT, "bad image size") + end + local maxLayers = opts and opts.maxLayers or 10000 + local count = 0 + local function png(path: string): (Types.Image?, Err.Err?) + local data, derr = zip:read(path) + if not data then + return nil, derr or Err.new(Err.CORRUPT, "missing " .. path) + end + local ok, img, ierr = pcall(decodeImage, data) + if not ok or not img then + return nil, Err.new(Err.CORRUPT, path .. ": " .. tostring(if ok then ierr else img)) + end + return img, nil + end + -- a 's children, top first in the file -> bottom to top + local function stack(node: any, ox: number, oy: number): ({ Types.Layer }?, Err.Err?) + local out: { Types.Layer } = {} + for _, ch in node.children do + if type(ch) ~= "table" then + continue + end + local a = ch.attrs or {} + local visible = a.visibility ~= "hidden" + local op = a["composite-op"] or "svg:src-over" + local blend = OPS[op] or op + local x, y = ox + num(a.x, 0), oy + num(a.y, 0) + count += 1 + if count > maxLayers then + return nil, Err.new(Err.LIMIT, "too many layers") + end + if ch.name == "layer" then + local src = a.src + if type(src) ~= "string" then + continue + end + if string.lower(string.sub(src, -4)) ~= ".png" then + return nil, Err.new(Err.UNSUPPORTED, "layer source " .. src) + end + local img, perr = png(src) + if not img then + return nil, perr + end + local layer = Types.Layered.layer(a.name or src, img :: Types.Image, x, y) + layer.opacity = math.clamp(num(a.opacity, 1), 0, 1) + layer.visible = visible + layer.blend = blend + table.insert(out, 1, layer) + elseif ch.name == "stack" then + local kids, kerr = stack(ch, x, y) + if not kids then + return nil, kerr + end + local g = Types.Layered.group(a.name or "group", kids :: { Types.Layer }) + g.opacity = math.clamp(num(a.opacity, 1), 0, 1) + g.visible = visible + g.blend = if a.isolation == "isolate" then (if blend == "normal" then "normal" else blend) else "passThrough" + table.insert(out, 1, g) + end + end + return out, nil + end + local top = Xml.child(root, "stack") + if not top then + return nil, Err.new(Err.CORRUPT, "stack.xml has no ") + end + local layers, lerr = stack(top, 0, 0) + if not layers then + return nil, lerr + end + local doc2 = Types.Layered.new(W, H) + doc2.layers = layers :: { Types.Layer } + if not (opts and opts.composite == false) and zip:find("mergedimage.png") then + doc2.meta.composite = png("mergedimage.png") + end + local xr, yr = tonumber(root.attrs.xres), tonumber(root.attrs.yres) + if xr and yr then + doc2.meta.dpi = { x = xr, y = yr } + end + doc2.meta.source = { format = "ora", version = root.attrs.version, layers = count } + return doc2, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +-- nearest-neighbour downscale to fit max x max +local function thumbnail(img: Types.Image, max: number): Types.Image + local w, h = img.width, img.height + local s = math.min(1, max / math.max(w, h)) + local tw, th = math.max(1, math.floor(w * s)), math.max(1, math.floor(h * s)) + local t = Types.Image.new(tw, th, "rgba8") + for y = 0, th - 1 do + local sy = math.min(h - 1, math.floor(y / s)) + for x = 0, tw - 1 do + local sx = math.min(w - 1, math.floor(x / s)) + buffer.writeu32(t.pixels, (y * tw + x) * 4, buffer.readu32(img.pixels, (sy * w + sx) * 4)) + end + end + return t +end + +function Ora.encode(doc: Types.Layered, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(doc) ~= "table" or type(doc.layers) ~= "table" or type(doc.width) ~= "number" or doc.width < 1 or doc.height < 1 then + return nil, Err.new(Err.ARG, "needs a Layered document") + end + local encodeImage = opts and opts.encodeImage + if not encodeImage then + return nil, Err.new(Err.UNSUPPORTED, "PNG layers need the encodeImage hook") + end + local W, H = doc.width, doc.height + local zw = Zip.writer() + zw:add("mimetype", MIME, { method = "store" }) + local files: { { any } } = {} + local n = 0 + local function png(img: Types.Image, label: string): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" then + return nil, Err.new(Err.ARG, label .. ": layers need rgba8 images") + end + local ok, data, err = pcall(encodeImage, img, "png") + if not ok or not data then + return nil, Err.new(Err.ARG, label .. ": " .. tostring(if ok then err else data)) + end + return data, nil + end + -- layers bottom to top -> xml children top first + local function stack(layers: { Types.Layer }): ({ any }?, Err.Err?) + local kids = {} + for i = #layers, 1, -1 do + local l = layers[i] + local attrs: { [string]: string } = { + name = l.name or "", + opacity = string.format("%.6g", l.opacity or 1), + visibility = if l.visible == false then "hidden" else "visible", + } + if l.children then + attrs.isolation = if l.blend == "passThrough" then "auto" else "isolate" + if l.blend ~= "passThrough" then + attrs["composite-op"] = BACK[l.blend] or l.blend + end + local sub, serr = stack(l.children) + if not sub then + return nil, serr + end + table.insert(kids, Xml.element("stack", attrs, sub)) + else + n += 1 + local path = string.format("data/layer%03d.png", n) + local data, perr = png(l.image, "layer " .. tostring(l.name)) + if not data then + return nil, perr + end + table.insert(files, { path, data }) + attrs.src = path + attrs.x = tostring(math.floor(l.x or 0)) + attrs.y = tostring(math.floor(l.y or 0)) + attrs["composite-op"] = BACK[l.blend or "normal"] or l.blend or "svg:src-over" + table.insert(kids, Xml.element("layer", attrs)) + end + end + return kids, nil + end + local kids, kerr = stack(doc.layers) + if not kids then + return nil, kerr + end + local rootAttrs: { [string]: string } = { version = "0.0.6", w = tostring(W), h = tostring(H) } + local dpi = doc.meta and doc.meta.dpi + if dpi then + rootAttrs.xres, rootAttrs.yres = tostring(dpi.x), tostring(dpi.y) + end + local xml = Xml.encode(Xml.document(Xml.element("image", rootAttrs, { Xml.element("stack", {}, kids :: any) })), { indent = 1 }) + zw:add("stack.xml", xml :: string) + for _, f in files do + zw:add(f[1], f[2], { method = "store" }) + end + local merged = opts and opts.composite + if not merged then + local m = Types.Image.new(W, H, "rgba8") + Blend.flatten(doc.layers, m.pixels, W, H, false) + merged = m + end + local mdata, merr = png(merged :: Types.Image, "mergedimage") + if not mdata then + return nil, merr + end + zw:add("mergedimage.png", mdata, { method = "store" }) + if not (opts and opts.thumbnail == false) then + local tdata, terr = png(thumbnail(merged :: Types.Image, 256), "thumbnail") + if not tdata then + return nil, terr + end + zw:add("Thumbnails/thumbnail.png", tdata, { method = "store" }) + end + return zw:finish() +end + +return Ora diff --git a/tests/layered/ora.luau b/tests/layered/ora.luau new file mode 100644 index 0000000..86865b9 --- /dev/null +++ b/tests/layered/ora.luau @@ -0,0 +1,124 @@ +-- layered/ora tests: OpenRaster files assembled by the spec (offsets, opacity, hidden, composite-ops, nested isolate / +-- auto stacks, no merged image) against the attributes and pixels written there; our encoder's file taken apart by +-- python (stored mimetype first, stack.xml, Pillow's read of every PNG); round trips; hooks; errors; the fuzz no-throw +-- pass. Fixtures: tools/fixtures/ora.py. +local T = require("@tests/T") +local Ora = require("@formats/layered/ora") +local Png = require("@formats/image/png") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/ora") + +local t = T.suite("ora") +t:eq(Ora.name, "ora", "name") +t:eq(Ora.category, "layered", "category") +t:check(Ora.caps.decode and Ora.caps.encode, "caps") + +local hooks = { + decodeImage = function(b: buffer): (any, any) + return Png.decode(Bytes.reader(b)) + end, + encodeImage = function(img: any, _f: string): (any, any) + return Png.encode(img) + end, +} + +-- the tree depth-first, bottom to top, groups before their children +local function walk(layers: { any }, depth: number, out: { any }) + for _, l in layers do + table.insert(out, { layer = l, depth = depth }) + if l.children then + walk(l.children, depth + 1, out) + end + end + return out +end + +local function compare(label: string, doc: any, want: { any }) + local got = walk(doc.layers, 0, {}) + t:eq(#got, #want, label .. ": layer count") + for i, w in want do + local g = got[i] + if not g then + break + end + local l = g.layer + local ll = label .. ": " .. w.name + t:eq(l.name, w.name, ll .. " name") + t:eq(g.depth, w.depth, ll .. " depth") + t:check(math.abs(l.opacity - w.opacity) < 1e-6, ll .. " opacity") + t:eq(l.visible, w.visible, ll .. " visibility") + t:eq(l.blend, w.blend, ll .. " blend") + if not w.group then + t:check(l.x == w.x and l.y == w.y, ll .. " position") + t:check(l.image.width == w.w and l.image.height == w.h and buffer.tostring(l.image.pixels) == w.rgba, ll .. " pixels") + else + t:check(l.children ~= nil, ll .. " is a group") + end + end +end + +for _, c in Fx.cases do + local doc, err = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) + t:check(doc, c.name .. ": " .. tostring(err)) + t:check(doc.kind == "layered" and doc.width == c.w and doc.height == c.h, c.name .. ": size") + compare(c.name, doc, c.layers) + t:eq(doc.meta.composite ~= nil, c.merged, c.name .. ": merged image") + if c.dpi then + t:eq(doc.meta.dpi.x, c.dpi, c.name .. ": dpi") + end + -- round trip + local enc, eerr = Ora.encode(doc, hooks) + t:check(enc, c.name .. ": encode " .. tostring(eerr)) + local back = Ora.decode(Bytes.reader(enc :: buffer), hooks) + compare(c.name .. " round trip", back, c.layers) + t:eq(Ora.sniff(Bytes.reader(enc :: buffer)), 1, c.name .. ": sniff our file") +end + +-- our encoder's file, as python and Pillow read it +do + local o = Fx.ours + t:check(o.ok, "ours: mimetype first, stored") + t:eq(o.entries[1], "mimetype", "ours: first entry") + t:check(table.find(o.entries, "mergedimage.png") ~= nil and table.find(o.entries, "Thumbnails/thumbnail.png") ~= nil, "ours: merged image and thumbnail") + t:check(o.thumb[1] == 40 and o.thumb[2] == 30, "ours: thumbnail size") + local doc = Ora.decode(Bytes.reader(buffer.fromstring(o.data)), hooks) :: any + t:check(doc and doc.width == o.w and doc.height == o.h, "ours: decodes") + -- python's walk is top first (xml order): compare by name + local byName = {} + for _, g in walk(doc.layers, 0, {}) do + byName[g.layer.name] = g + end + for _, l in o.layers do + local g = byName[l.name] + t:check(g, "ours: layer " .. l.name) + if g then + t:check(math.abs(g.layer.opacity - l.opacity) < 1e-6 and g.layer.visible == l.visible and g.depth == l.depth, "ours: " .. l.name .. " attributes") + if l.tag == "layer" then + t:check(g.layer.x == l.x and g.layer.y == l.y, "ours: " .. l.name .. " position") + t:eq(buffer.tostring(g.layer.image.pixels), l.rgba, "ours: " .. l.name .. " pixels through Pillow") + end + end + end + t:eq(buffer.tostring(doc.meta.composite.pixels), o.merged.rgba, "ours: merged image through Pillow") +end + +do + local c = Fx.cases[1] + local _, e = Ora.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(e and e.code == Err.UNSUPPORTED, "no decodeImage hook") + local doc = Ora.decode(Bytes.reader(buffer.fromstring(c.data)), hooks) :: any + local _, e2 = Ora.encode(doc) + t:check(e2 and e2.code == Err.UNSUPPORTED, "no encodeImage hook") + local _, e3 = Ora.encode({} :: any, hooks) + t:check(e3 and e3.code == Err.ARG, "not a document") + t:eq(Ora.sniff(Bytes.reader(buffer.fromstring("PK\3\4"))), 0, "sniff a plain zip") +end +local samples = {} +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Ora.decode(Bytes.reader(b), hooks) +end, samples, { mutations = 12 }) +t:done() diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index 89a285e..ebaba84 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -168,3 +168,26 @@ if which == "icns" then base.pixels = base.frames[4].image.pixels emit("ours_legacy.icns", Icns.encode(base)) end + +if which == "ora" then + -- a layered document: background, an offset half-opaque multiply layer, a hidden one, a group with a screen layer + local Ora = require("@formats/layered/ora") + local Png = require("@formats/image/png") + local doc = Types.Layered.new(40, 30) + local bg = Types.Layered.layer("background", image(40, 30, "rgba8", 0)) + for i = 0, 40 * 30 - 1 do + buffer.writeu8(bg.image.pixels, i * 4 + 3, 255) + end + local mid = Types.Layered.layer("mid", image(20, 10, "rgba8", 1), 5, 7) + mid.opacity, mid.blend = 0.5, "multiply" + local hidden = Types.Layered.layer("hidden", image(8, 8, "rgba8", 2), 1, 1) + hidden.visible = false + local inner = Types.Layered.layer("inner", image(10, 10, "rgba8", 3), 20, 15) + inner.blend = "screen" + local g = Types.Layered.group("group", { inner }) + g.opacity = 0.75 + doc.layers = { bg, mid, hidden, g } + emit("ours_doc.ora", Ora.encode(doc, { encodeImage = function(img: any, _f: string): (any, any) + return Png.encode(img) + end })) +end diff --git a/tools/fixtures/ora.py b/tools/fixtures/ora.py new file mode 100644 index 0000000..8e1dcdf --- /dev/null +++ b/tools/fixtures/ora.py @@ -0,0 +1,95 @@ +# OpenRaster fixtures (tools/fixtures.py): ORA files assembled here by the specification (python zipfile, the stored +# mimetype first, stack.xml, Pillow-written PNG layers, mergedimage.png, a thumbnail): plain layers with offsets / +# opacity / hidden / composite-ops, nested stacks (isolate and auto), a file without mergedimage; and our encoder's +# file (tools/fixtures/_tex_encode.luau -a ora) taken apart by python (zip order and method, stack.xml, PNG pixels +# through Pillow). References: the layer attributes and source pixels written here. +# tests/gen/ora.luau { cases = { { name, data, w, h, layers (bottom to top, depth-first) = { { name, x, y, opacity, +# visible, blend, depth, rgba?, w?, h? } }, merged? } }, ours = { ok, entries, layers } } +import importlib.util, io, os, struct, xml.etree.ElementTree as ET, zipfile + +def _load(n): + spec = importlib.util.spec_from_file_location(n, os.path.join(os.path.dirname(os.path.abspath(__file__)), n + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + +R, S, T = _load("_raster_ref"), _load("_simple"), _load("_tex_reference") +INPUTS = ["tools/fixtures/_tex_encode.luau", "src/Formats/layered/ora"] +OPS = {"svg:src-over": "normal", "svg:multiply": "multiply", "svg:screen": "screen", "svg:overlay": "overlay", "svg:color-dodge": "colorDodge"} + + +def build(stack_xml, pngs, merged=True, w=40, h=30): + buf = io.BytesIO() + z = zipfile.ZipFile(buf, "w") + z.writestr(zipfile.ZipInfo("mimetype"), "image/openraster", compress_type=zipfile.ZIP_STORED) + z.writestr("stack.xml", stack_xml, compress_type=zipfile.ZIP_DEFLATED) + for n, d in pngs.items(): + z.writestr(n, d, compress_type=zipfile.ZIP_STORED) + if merged: + z.writestr("mergedimage.png", R.png(w, h, bytes(w * h * 4)), compress_type=zipfile.ZIP_STORED) + z.close() + return buf.getvalue() + + +def generate(ctx): + cases = [] + imgs = {} + for i, (w, h) in enumerate(((40, 30), (20, 10), (8, 8), (10, 12), (6, 5))): + imgs["data/l%d.png" % i] = (w, h, R.photo(w, h, i + 1, i > 0)) + pngs = {k: R.png(*v) for k, v in imgs.items()} + + def lay(src, name, x, y, op, vis, depth): + w, h, px = imgs[src] + return {"name": name, "x": x, "y": y, "opacity": op[0], "visible": vis, "blend": op[1], "depth": depth, "rgba": px, "w": w, "h": h} + + xml1 = ''' + + + + +''' + cases.append({"name": "plain", "data": build(xml1, pngs), "w": 40, "h": 30, "dpi": 144, "merged": True, "layers": [ + lay("data/l0.png", "background", 0, 0, (1.0, "normal"), True, 0), lay("data/l1.png", "mid", 5, 7, (0.5, "multiply"), True, 0), + lay("data/l2.png", "top hidden", 1, 2, (1.0, "normal"), False, 0)]}) + xml2 = ''' + + + + + +''' + cases.append({"name": "nested", "data": build(xml2, pngs, merged=False), "w": 40, "h": 30, "merged": False, "layers": [ + lay("data/l0.png", "base", 0, 0, (1.0, "normal"), True, 0), + {"name": "outer", "x": 0, "y": 0, "opacity": 0.8, "visible": True, "blend": "normal", "depth": 0, "group": True}, + {"name": "inner", "x": 0, "y": 0, "opacity": 0.5, "visible": True, "blend": "passThrough", "depth": 1, "group": True}, + lay("data/l4.png", "b", 2, 3, (1.0, "colorDodge"), True, 2), + lay("data/l3.png", "a", 3, 4, (1.0, "screen"), True, 1)]}) + # ours, taken apart + mine = S.ours(ctx, "ora")["ours_doc.ora"] + z = zipfile.ZipFile(io.BytesIO(mine)) + infos = z.infolist() + ok = infos[0].filename == "mimetype" and infos[0].compress_type == zipfile.ZIP_STORED and z.read("mimetype") == b"image/openraster" + root = ET.fromstring(z.read("stack.xml")) + layers = [] + + def walk(node, depth): + for ch in node: + a = ch.attrib + e = {"tag": ch.tag, "name": a.get("name", ""), "depth": depth, "opacity": float(a.get("opacity", "1")), + "visible": a.get("visibility", "visible") == "visible", "op": a.get("composite-op", ""), "isolation": a.get("isolation", "")} + if ch.tag == "layer": + e["x"], e["y"] = int(a.get("x", "0")), int(a.get("y", "0")) + e["src"] = a["src"] + layers.append(e) + if ch.tag == "stack": + walk(ch, depth + 1) + walk(root.find("stack"), 0) + srcs = [l["src"] for l in layers if l["tag"] == "layer"] + ["mergedimage.png", "Thumbnails/thumbnail.png"] + decoded = T.pillow(ctx, [z.read(s) for s in srcs]) + px = {s: {"w": d[1], "h": d[2], "rgba": T.rgba_from(d[0], d[3])} for s, d in zip(srcs, decoded)} + for l in layers: + if l["tag"] == "layer": + l.update(px[l["src"]]) + ours = {"data": mine, "ok": ok, "w": int(root.attrib["w"]), "h": int(root.attrib["h"]), "entries": [i.filename for i in infos], + "layers": layers, "merged": px["mergedimage.png"], "thumb": [px["Thumbnails/thumbnail.png"]["w"], px["Thumbnails/thumbnail.png"]["h"]]} + ctx.emit("ora", {"cases": cases, "ours": ours}) From 918c8310afa52b9735c05a1f0965f9236f748242 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:18:40 -0500 Subject: [PATCH 51/54] ws-tex: docs/guide sections (textures / HDR, OpenRaster); DDS / KTX pixelFormat option; XBM / XPM names from F.save F.save sets opts.format to the file format, so the DDS / KTX layout option is pixelFormat; XBM / XPM make a C identifier of opts.name (F.save passes the file name). --- docs/guide/image.md | 36 +++++++++++++++++++++++++++++++++ docs/guide/layered.md | 28 ++++++++++++++++++++++--- src/Formats/image/dds/init.luau | 8 ++++---- src/Formats/image/ktx/init.luau | 8 ++++---- src/Formats/image/xbm/init.luau | 9 +++++---- src/Formats/image/xpm/init.luau | 9 +++++---- tests/image/dds.luau | 6 +++--- tests/image/ktx.luau | 2 +- tests/image/xbm.luau | 4 ++-- tools/fixtures/_tex_encode.luau | 10 ++++----- 10 files changed, 90 insertions(+), 30 deletions(-) diff --git a/docs/guide/image.md b/docs/guide/image.md index 4d85bc0..8c919d6 100644 --- a/docs/guide/image.md +++ b/docs/guide/image.md @@ -207,6 +207,42 @@ Read and write unless noted; see [FORMATS.md](../FORMATS.md) for depths and deta | TIFF | pages | yes | 1..32-bit, float | | BMP, TGA, QOI, ICO / CUR, PNM / PAM / PFM | ICO entries | yes | | | HDR | | no | float (`native` gives rgbaf32) | +| DDS, KTX / KTX2 | faces / layers / slices | yes | GPU textures: BC1..BC7, ETC / EAC, every uncompressed layout; mips in `meta.mipmaps` | +| OpenEXR | parts (`opts.part`) | yes | half / float / uint, NONE / RLE / ZIPS / ZIP / PIZ, tiles; writes NONE / ZIPS / ZIP | +| PCX, SGI, Sun Raster, IFF ILBM / PBM, XPM, XBM | | yes (XBM 1-bit) | old paint / workstation formats; ILBM reads HAM and EHB | +| ICNS, ANI | ICNS sizes / ANI steps | yes | PNG / ICO entries through the api hooks | + +### Textures and HDR (DDS, KTX, EXR) + +DDS and KTX files hold GPU textures: block-compressed (BC1..BC7, ETC1 / ETC2 / EAC) or plain texel layouts, with mip +levels, cube faces and array layers. The image is the first surface; `img.frames` lists every face / layer / depth +slice when there is more than one (`meta.layout` is `"2d"`, `"cube"`, `"array"` or `"volume"`), and with `opts.mips` the +smaller levels of the first surface go to `meta.mipmaps`. Float and 16-bit sources keep their values with +`opts.native` (`rgbaf32` / `rgba16`); otherwise they are clamped into `rgba8`. Writers pick the stored layout with +`pixelFormat` (`format` is the file format): DDS writes `rgba8`, `bgra8`, `bc1`, `bc3`, `bc4`, `bc5`, `rgba16`, +`rgba16f`, `rgba32f`; KTX2 writes the uncompressed ones. + +```luau +local img = assert(F.ops.image.new(64, 64)) +assert(F.ops.image.fill(img, 200, 120, 40, 255)) +local dds = assert(F.save(img, nil, { format = "dds", pixelFormat = "bc1", mips = true })) +local tex = assert(F.load(dds, { mips = true })) +assert(tex.meta.source.pixelFormat == "bc1" and #tex.meta.mipmaps == 6) +local ktx = assert(F.save(img, nil, { format = "ktx", mips = true, zlib = 6 })) -- KTX2, ZLIB-supercompressed +assert(F.detect(ktx) == "ktx") +``` + +OpenEXR loads as linear floats with `opts.native` (`rgbaf32`); the default `rgba8` goes through the same 1 / 2.2 +display curve as Radiance HDR. `opts.part` picks a part of a multipart file, `opts.layer` reads `.R` / `.G` / ... + +```luau +local hdr = assert(F.ops.image.new(8, 8, "rgbaf32")) +assert(F.ops.image.fill(hdr, 4, 2, 0.5, 1)) -- floats may exceed 1 +local exr = assert(F.save(hdr, nil, { format = "exr", compression = "zip", pixelType = "half" })) +local linear = assert(F.load(exr, { native = true })) +assert(linear.format == "rgbaf32" and math.abs(buffer.readf32(linear.pixels, 0) - 4) < 1e-3) +assert(F.load(exr).format == "rgba8") -- the display conversion +``` An animated image also opens as a video (`F.video.open(gifBytes)`), and saves to a video format (`F.convert(gifBytes, "avi")`): see [video.md](video.md). diff --git a/docs/guide/layered.md b/docs/guide/layered.md index 043f2fc..1bd1d88 100644 --- a/docs/guide/layered.md +++ b/docs/guide/layered.md @@ -1,8 +1,8 @@ -# Layered images (PSD, Aseprite) +# Layered images (PSD, Aseprite, OpenRaster) -Photoshop documents and Aseprite sprites load as a `Layered`: a canvas size and a tree of layers, each with its own +Photoshop documents, Aseprite sprites and OpenRaster files load as a `Layered`: a canvas size and a tree of layers, each with its own rgba8 [Image](image.md), position, opacity, blend mode and visibility. `F.ops.layers.flatten` composites the tree -into one Image; `F.save` writes PSD or Aseprite, layers included. Aseprite animations also carry every frame's tree. +into one Image; `F.save` writes PSD, Aseprite or OpenRaster, layers included. Aseprite animations also carry every frame's tree. ```luau local doc = assert(F.layered.load(psdBytes)) @@ -230,6 +230,28 @@ assert(#back.frames == 4 and back.frames[3].layers[1].x == 3) |---|---|---|---| | PSD / PSB | 1 / 8 / 16 / 32-bit, every colour mode, layers, groups, masks, clipping | 8-bit RGB | adjustment, type and smart-object layers keep only their pixels; no layer effects | | Aseprite | RGBA, grayscale, indexed; frames, linked cels, tags, palette, user data | yes | tilemap layers are skipped (`meta.skipped`); slices not kept | +| OpenRaster (ORA) | the stack tree (nested stacks = groups), offsets, opacity, visibility, svg composite-ops | yes | layers are PNGs through the api hooks; `meta.composite` = mergedimage.png | + +### OpenRaster + +An `.ora` file is a zip of PNG layers and a `stack.xml` tree (the format GIMP, Krita and MyPaint exchange). It loads +like the others; nested ``s become groups (`isolation="auto"` is the `"passThrough"` blend). Saving writes every +layer, the flattened `mergedimage.png` and a thumbnail. + +```luau +local doc = F.Types.Layered.new(32, 24) +local base = assert(F.ops.image.new(32, 24)) +assert(F.ops.image.fill(base, 30, 60, 200, 255)) +local dot = assert(F.ops.image.new(8, 8)) +assert(F.ops.image.fill(dot, 255, 255, 0, 255)) +local top = F.Types.Layered.layer("dot", dot, 12, 8) +top.blend, top.opacity = "screen", 0.5 +doc.layers = { F.Types.Layered.layer("base", base), top } +local ora = assert(F.save(doc, nil, { format = "ora" })) +local back = assert(F.layered.load(ora)) +assert(#back.layers == 2 and back.layers[2].blend == "screen" and back.layers[2].x == 12) +assert(back.meta.composite.width == 32) -- mergedimage.png +``` See [FORMATS.md](../FORMATS.md) for the capability matrix. diff --git a/src/Formats/image/dds/init.luau b/src/Formats/image/dds/init.luau index 9b71ecf..d4ebc33 100644 --- a/src/Formats/image/dds/init.luau +++ b/src/Formats/image/dds/init.luau @@ -40,7 +40,7 @@ export type DecodeOptions = { maxPixels: number?, -- refuse larger images (default 2^26, counted over every decoded surface) } export type EncodeOptions = { - format: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: + pixelFormat: ("rgba8" | "bgra8" | "bc1" | "bc3" | "bc4" | "bc5" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: -- rgba8 for rgba8 images, rgba16 / rgba32f for rgba16 / rgbaf32 ones mips: boolean?, -- write a full mip chain (default false) dx10: boolean?, -- always write the DX10 header (default: only when the format needs it, or for arrays) @@ -440,13 +440,13 @@ function Dds.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") end - local f: string = (opts and opts.format) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f") + local f: string = (opts and opts.pixelFormat) or (if pf == "rgba8" then "rgba8" elseif pf == "rgba16" then "rgba16" else "rgba32f") if not DX10_OUT[f] then - return nil, Err.new(Err.ARG, "unknown format " .. tostring(f)) + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) end local needs = if f == "rgba16" then "rgba16" elseif f == "rgba16f" or f == "rgba32f" then "rgbaf32" else "rgba8" if pf ~= needs then - return nil, Err.new(Err.ARG, string.format("format %s needs an %s Image", f, needs)) + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) end -- surfaces: the frames (array / cube faces) or the image local images: { Types.Image } = { img } diff --git a/src/Formats/image/ktx/init.luau b/src/Formats/image/ktx/init.luau index 2fd15bb..e652863 100644 --- a/src/Formats/image/ktx/init.luau +++ b/src/Formats/image/ktx/init.luau @@ -39,7 +39,7 @@ export type DecodeOptions = { maxPixels: number?, -- refuse larger images (default 2^26, over every decoded surface) } export type EncodeOptions = { - format: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) + pixelFormat: ("rgba8" | "rgba16" | "rgba16f" | "rgba32f")?, -- default: the image's own (rgbaf32 -> rgba32f) srgb: boolean?, -- rgba8 as R8G8B8A8_SRGB (default: meta.colorSpace == "srgb") mips: boolean?, -- a full mip chain (box filter; default false) cube: boolean?, -- img.frames as cube faces (default: meta.layout == "cube") @@ -543,14 +543,14 @@ function Ktx.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if pf ~= "rgba8" and pf ~= "rgba16" and pf ~= "rgbaf32" then return nil, Err.new(Err.ARG, "needs an rgba8, rgba16 or rgbaf32 Image (got " .. tostring(pf) .. ")") end - local f: string = (opts and opts.format) or (if pf == "rgbaf32" then "rgba32f" else pf) + local f: string = (opts and opts.pixelFormat) or (if pf == "rgbaf32" then "rgba32f" else pf) local spec = OUT[f] if not spec then - return nil, Err.new(Err.ARG, "unknown format " .. tostring(f)) + return nil, Err.new(Err.ARG, "unknown pixelFormat " .. tostring(f)) end local needs = if f == "rgba16f" or f == "rgba32f" then "rgbaf32" else f if pf ~= needs then - return nil, Err.new(Err.ARG, string.format("format %s needs an %s Image", f, needs)) + return nil, Err.new(Err.ARG, string.format("pixelFormat %s needs an %s Image", f, needs)) end local srgb = f == "rgba8" and (if opts and opts.srgb ~= nil then opts.srgb else (img.meta and img.meta.colorSpace == "srgb")) local images: { Types.Image } = { img } diff --git a/src/Formats/image/xbm/init.luau b/src/Formats/image/xbm/init.luau index 7e1273a..05a5954 100644 --- a/src/Formats/image/xbm/init.luau +++ b/src/Formats/image/xbm/init.luau @@ -26,7 +26,7 @@ export type DecodeOptions = { maxPixels: number?, -- refuse larger images (default 2^26) } export type EncodeOptions = { - name: string?, -- the C identifier prefix (default "image") + name: string?, -- the C identifier prefix (default "image"; an extension is dropped, other characters become _) threshold: number?, -- luminance below this is black (default 128) } @@ -120,9 +120,10 @@ function Xbm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - local name = opts and opts.name or "image" - if not string.match(name, "^[%a_][%w_]*$") then - return nil, Err.new(Err.ARG, "name must be a C identifier") + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name end local th = opts and opts.threshold or 128 local px = img.pixels diff --git a/src/Formats/image/xpm/init.luau b/src/Formats/image/xpm/init.luau index 0be8459..ff5160d 100644 --- a/src/Formats/image/xpm/init.luau +++ b/src/Formats/image/xpm/init.luau @@ -28,7 +28,7 @@ export type DecodeOptions = { maxPixels: number?, -- refuse larger images (default 2^26) } export type EncodeOptions = { - name: string?, -- the C identifier (default "image") + name: string?, -- the C identifier (default "image"; an extension is dropped, other characters become _) } -- the characters of pixel codes (printable ASCII without '"' and '\') @@ -214,9 +214,10 @@ function Xpm.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) if w < 1 or h < 1 then return nil, Err.new(Err.ARG, "bad size") end - local name = opts and opts.name or "image" - if not string.match(name, "^[%a_][%w_]*$") then - return nil, Err.new(Err.ARG, "name must be a C identifier") + -- a C identifier from opts.name (F.save passes the file name: "out.xbm" -> out) + local name = string.gsub(string.gsub(opts and opts.name or "image", "%.[^.]*$", ""), "[^%w_]", "_") + if name == "" or string.match(name, "^%d") then + name = "_" .. name end local px = img.pixels local index: { [number]: number } = {} diff --git a/tests/image/dds.luau b/tests/image/dds.luau index f55a1df..f743e1c 100644 --- a/tests/image/dds.luau +++ b/tests/image/dds.luau @@ -163,7 +163,7 @@ do local img = Types.Image.new(37, 23) img.pixels = src for _, f in { "rgba8", "bgra8" } do - local back = dec(Dds.encode(img, { format = f :: any }) :: buffer) + local back = dec(Dds.encode(img, { pixelFormat = f :: any }) :: buffer) t:eq(buffer.tostring(back.pixels), buffer.tostring(src), f .. " round trip") end local f = Types.Image.new(3, 2, "rgbaf32") @@ -172,9 +172,9 @@ do end local back = dec(Dds.encode(f) :: buffer, { native = true }) t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip") - local _, e1 = Dds.encode(f, { format = "bc1" }) + local _, e1 = Dds.encode(f, { pixelFormat = "bc1" }) t:check(e1 and e1.code == Err.ARG, "bc1 needs rgba8") - local _, e2 = Dds.encode(img, { format = "bc7" :: any }) + local _, e2 = Dds.encode(img, { pixelFormat = "bc7" :: any }) t:check(e2 and e2.code == Err.ARG, "no bc7 encoder") end diff --git a/tests/image/ktx.luau b/tests/image/ktx.luau index 1c24fbf..afb8f32 100644 --- a/tests/image/ktx.luau +++ b/tests/image/ktx.luau @@ -133,7 +133,7 @@ do end local back = dec(Ktx.encode(f) :: buffer, { native = true }) t:eq(buffer.tostring(back.pixels), buffer.tostring(f.pixels), "rgba32f round trip") - local _, e = Ktx.encode(f, { format = "rgba8" }) + local _, e = Ktx.encode(f, { pixelFormat = "rgba8" }) t:check(e and e.code == Err.ARG, "format mismatch") local _, e2 = Ktx.encode(img, { zlib = 12 }) t:check(e2 and e2.code == Err.ARG, "zlib level") diff --git a/tests/image/xbm.luau b/tests/image/xbm.luau index b1066aa..0894f79 100644 --- a/tests/image/xbm.luau +++ b/tests/image/xbm.luau @@ -34,8 +34,8 @@ do t:eq(Xbm.sniff(Bytes.reader(buffer.fromstring("#define c_width 2\n"))), 0.9, "sniff") local _, e = Xbm.decode(Bytes.reader(buffer.fromstring("static char x[] = {};"))) t:check(e and e.code == Err.CORRUPT, "no defines") - local _, e2 = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1bad" }) - t:check(e2 and e2.code == Err.ARG, "bad name") + local named = Xbm.encode(R.image(1, 1, "\0\0\0\255"), { name = "1 bad.xbm" }) :: buffer + t:check(string.find(buffer.tostring(named), "#define _1_bad_width 1", 1, true) ~= nil, "name made an identifier") end t:fuzz("decode", function(b: buffer) return Xbm.decode(Bytes.reader(b)) diff --git a/tools/fixtures/_tex_encode.luau b/tools/fixtures/_tex_encode.luau index ebaba84..92a3d8e 100644 --- a/tools/fixtures/_tex_encode.luau +++ b/tools/fixtures/_tex_encode.luau @@ -56,13 +56,13 @@ if which == "dds" then local Dds = require("@formats/image/dds") local img = image(37, 23, "rgba8", 0) for _, f in { "rgba8", "bgra8", "bc1", "bc3", "bc4", "bc5" } do - emit("ours_" .. f .. ".dds", Dds.encode(img, { format = f :: any })) - emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { format = f :: any, mips = true })) + emit("ours_" .. f .. ".dds", Dds.encode(img, { pixelFormat = f :: any })) + emit("ours_" .. f .. "_mips.dds", Dds.encode(img, { pixelFormat = f :: any, mips = true })) end emit("ours_rgba8_dx10.dds", Dds.encode(img, { dx10 = true, mips = true })) emit("ours_rgba16.dds", Dds.encode(image(37, 23, "rgba16", 0), { mips = true })) emit("ours_rgba32f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true })) - emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" })) + emit("ours_rgba16f.dds", Dds.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" })) local cube = image(16, 16, "rgba8", 0) cube.frames = {} for i = 1, 6 do @@ -71,7 +71,7 @@ if which == "dds" then cube.meta.layout = "cube" emit("ours_cube.dds", Dds.encode(cube, { mips = true })) cube.meta.layout = "array" - emit("ours_array_bc1.dds", Dds.encode(cube, { format = "bc1" })) + emit("ours_array_bc1.dds", Dds.encode(cube, { pixelFormat = "bc1" })) end if which == "ktx" then @@ -82,7 +82,7 @@ if which == "ktx" then emit("ours_srgb_zlib.ktx2", Ktx.encode(img, { mips = true, srgb = true, zlib = 6 })) emit("ours_rgba16.ktx2", Ktx.encode(image(37, 23, "rgba16", 0), { mips = true })) emit("ours_rgba32f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { mips = true })) - emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { format = "rgba16f" })) + emit("ours_rgba16f.ktx2", Ktx.encode(image(37, 23, "rgbaf32", 0, 4), { pixelFormat = "rgba16f" })) local cube = image(16, 16, "rgba8", 0) cube.frames = {} for i = 1, 6 do From 625e21431bdf8ceb53e27834f44e7809f85a553d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:21:12 -0500 Subject: [PATCH 52/54] ws-3d3: docs/guide/scene.md sections for PMX / PMD, VRML and X3D (tested snippets); bench lines for vrml / x3d --- docs/guide/scene.md | 61 ++++++++++++++++++++++++++++++++++++++++++++- tools/bench.luau | 13 ++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..c44b70a 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,7 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, PMX / PMD, VRML, X3D) loads as one +`Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -291,6 +292,7 @@ the binary container. | OBJ | `.mtl` and texture files into `opts.files` | `name`, `mtlName`, `normals`, `texcoords`, `colors`, `flipV` | | STL | | `ascii = true` (default binary), `normals = "attribute"` | | PLY, OFF, FBX, DAE, 3MF, USDA, VOX | see [FORMATS.md](../FORMATS.md) and the format's options | | +| VRML, X3D | texture images into `opts.files` (else `url` = the texture's uri) | `name`, `flipV`; X3D `encoding = "x3dv"` (or a `.x3dv` destination) for the classic encoding | Mesh-only writers (STL, PLY, OFF, OBJ) bake the node transforms into the vertices. Extra files go into the `opts.files` table you pass, named after `opts.name`: @@ -317,6 +319,60 @@ assert(F.save(scene, "out/box.obj")) -- box.obj + box.mtl assert(F.convert("assets/Box.glb", "stl", { out = "out/box.stl" })) ``` +## MikuMikuDance (PMX / PMD) + +`.pmx` (PMX 2.0 / 2.1) and `.pmd` files load as one skinned mesh with one primitive per material. MMD is left-handed, +so z is negated and the winding reversed on load; `meta.up` is `"y"` (one unit is about 8 cm). Bones become nodes (a +translation relative to the parent bone) under the model's root node and one `Skin`; every vertex carries `JOINTS_0` / +`WEIGHTS_0` (BDEF1 / 2 / 4, SDEF and QDEF all as linear weights, normalized; the SDEF C / R0 / R1 vectors as +`_SDEF_C` / `_SDEF_R0` / `_SDEF_R1` and the deform type as `_DEFORM` when a file uses them), the additional UVs as +`_UVA1` .. `_UVA4` (vec4) and the edge scale as `_EDGE_SCALE`. Vertex morphs are morph targets (`mesh.extras.targetNames` +holds their names); the other morphs (group, bone, UV, material, flip, impulse) are in `mesh.extras.pmx.morphs`. +Materials take the diffuse colour as `baseColor`, the specular power as roughness and the no-cull flag as +`doubleSided`; the MMD terms (specular, ambient, edge, sphere map and its mode, toon texture or shared toon index, memo) +are in `material.extras.pmx`, bone flags / IK / inherit settings in `node.extras.pmx`, display frames, rigid bodies and +joints in `meta.source`. Textures are referenced by their file names (`opts.files` / `opts.resolve` give the bytes). +`morphs = false` skips the morph targets. + +## VRML and X3D + +VRML97 (`.wrl`, gzipped `.wrz`) and X3D (XML `.x3d`, classic `.x3dv`, gzipped `.x3dz` / `.x3dvz`) share one reader: the +scene graph becomes nodes (a `Transform` with a `center` or `scaleOrientation` adds an inner node), `DEF` / `USE` +shares meshes and materials, `PROTO` / `ProtoInstance` are expanded, Box / Sphere / Cone / Cylinder are tessellated +(`opts.segments`, default 32), polygons are fan-triangulated unless `triangulate = false`, texture coordinates are +flipped to glTF's top-left origin, viewpoints become cameras, lights become lights, and ROUTEs from a `TimeSensor` +through position / orientation interpolators to a `Transform` become animations. `Inline` files and textures come +from `opts.files` / `opts.resolve`. Binary X3D (`.x3db`) is `UNSUPPORTED`. + +```luau +local wrl = [[#VRML V2.0 utf8 +DEF Red Transform { translation 2 0 0 children Shape { + appearance Appearance { material Material { diffuseColor 1 0 0 } } + geometry Box { size 1 2 3 } } } +DEF Cam Viewpoint { position 0 0 10 } +]] +local scene = assert(F.load(wrl)) -- detected by the #VRML header +assert(scene.meta.source.format == "vrml" and #scene.cameras == 1) +assert(scene.nodes[1].name == "Red" and scene.materials[1].baseColor[1] == 1) +local lo, hi = F.ops.mesh.bounds(scene) +assert(lo[1] == 1.5 and hi[1] == 2.5) -- the Box, moved by its Transform +``` + +Both write too: VRML97 text, X3D XML, or the classic X3D encoding. Shared meshes are written once and `USE`d; textures +with bytes go into `opts.files`: + +```luau +local x3d = [[ + +]] +local quad = assert(F.load(x3d, { triangulate = false })) +assert(quad.meshes[1].primitives[1].mode == "polygons" and quad.meshes[1].primitives[1].faces.count == 1) +local out = assert(F.save(quad, nil, { format = "wrl" })) -- VRML97 +assert(buffer.readstring(out, 0, 15) == "#VRML V2.0 utf8") +local classic = assert(F.save(quad, nil, { format = "x3dv" })) -- the classic X3D encoding +assert(F.load(classic, { triangulate = false }).meshes[1].primitives[1].faces.count == 1) +``` + ## Voxels MagicaVoxel `.vox` files load as a Scene with `meta.up = "z"`, units of one voxel, and grids in `scene.voxels`; each @@ -392,6 +448,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| PMX / PMD (MikuMikuDance) | yes | | bones + skin, vertex morphs, MMD materials and physics in extras | +| VRML97 (WRL / WRZ) | yes | yes | primitives, PROTO, Inline, ROUTE animations, cameras, lights | +| X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/tools/bench.luau b/tools/bench.luau index b32ee01..06aee19 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -872,6 +872,19 @@ do bench("3mf encode", 2, buffer.len(tmf), function() ThreeMf.encode(scene) end) + local Wrl = require("@formats/model/vrml") + local X3d = require("@formats/model/x3d") + local wrl = assert(Wrl.encode(scene)) + bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function() + Wrl.decode(Bytes.reader(wrl)) + end) + bench("vrml encode", 2, buffer.len(wrl), function() + Wrl.encode(scene) + end) + local x3d = assert(X3d.encode(scene)) + bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function() + X3d.decode(Bytes.reader(x3d)) + end) local V = 128 local grid = Types.Voxels.new(V, V, V) for z = 0, V - 1 do From 458abff451581a695be7a82f52f84ace089337b1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:29:47 -0500 Subject: [PATCH 53/54] README: codecs/model list --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fb0e714..b8cfba3 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,8 @@ src/Formats/ codecs/audio/ Opus, Vorbis, Flac, Mpa (MP1-3), Aac, Alac, Mdct, Pcm, Stream, Resample, VorbisComment, Tracker, SoundFont codecs/video/ H264, Mpeg1, Video (the codec registry) - codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten + codecs/text/ codecs/font/ codecs/model/ Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten, Draco, + Sampler, Vrml, Rig host/ runtime adapters (only the api uses them) Types.luau the standard types + constructors core/ Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, Input, Sniff From 50d856ac4a931eb728299fbf7ea9ba2c66c25f07 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:43:32 -0500 Subject: [PATCH 54/54] ws-tex: Bcn BC4 / BC5 encoder: a smaller endpoint nudge search (3.7x faster, PSNR within 0.4 dB) --- src/Formats/codecs/image/Bcn/Encode.luau | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Formats/codecs/image/Bcn/Encode.luau b/src/Formats/codecs/image/Bcn/Encode.luau index 2aea052..c7531ab 100644 --- a/src/Formats/codecs/image/Bcn/Encode.luau +++ b/src/Formats/codecs/image/Bcn/Encode.luau @@ -333,8 +333,8 @@ local function channelBlock(out: buffer, o: number) else -- 8-value ramp, then a few nudged endpoints local bestErr, b0, b1 = math.huge, hi, lo - for d0 = 0, 2 do - for d1 = 0, 2 do + for d0 = 0, 1 do + for d1 = 0, 1 do local x0, x1 = hi - d0, lo + d1 if x0 > x1 then ramp(x0, x1)