From d41d64219a8783b48f74530f6a36f3ea9b84d1b0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:52:17 -0500 Subject: [PATCH 01/21] 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/21] 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 07dc6f7e84e0b9e095a2c7829e10fb4a73e13d34 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:00:57 -0500 Subject: [PATCH 03/21] 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 1aaf8fce68584b70532cb448014bec0afd697146 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:03:52 -0500 Subject: [PATCH 04/21] 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 05/21] 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 27518c55c53ea1486bf810c9fbfda3eb4b7971d6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:05:28 -0500 Subject: [PATCH 06/21] 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 9a6ddd5c162266194bce57e3a118df39fb810cf0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:14:50 -0500 Subject: [PATCH 07/21] 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 4f05c89f01afe51eb0a68a3b279b5d9aa0992111 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:17:28 -0500 Subject: [PATCH 08/21] 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 09/21] 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 e3ac2f8b366a6a5fa820135ac1f5168a079ecf9e Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:28:56 -0500 Subject: [PATCH 10/21] 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 11/21] 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 730820d1f6f7d6befe0ac01b320f6b554e4efce2 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:33:46 -0500 Subject: [PATCH 12/21] 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 13/21] 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 51daa00a67c5041bf9caf64634e908d20dbe57de Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:39:22 -0500 Subject: [PATCH 14/21] 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 1d45c661082bf194aae38190ef01b01f0bbc5c92 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:36 -0500 Subject: [PATCH 15/21] 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 f3df37012e7a3392a4f5d47420d2eb85b5fbbf01 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:54:21 -0500 Subject: [PATCH 16/21] 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 17/21] 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 4b9d8e3069c0bc539fda2bebf949358f7c75346d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:09 -0500 Subject: [PATCH 18/21] 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 406b894635bc9e60d421aed19dccd17e5b0bf931 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:03:40 -0500 Subject: [PATCH 19/21] 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 625e21431bdf8ceb53e27834f44e7809f85a553d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:21:12 -0500 Subject: [PATCH 20/21] 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 21/21] 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