diff --git a/README.md b/README.md index 557ca06..c5a1f8c 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -186 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +187 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -112,6 +112,7 @@ adds each format's capabilities. | 3D models | 3ds | .3ds | yes | yes | | 3D models | 3mf | .3mf | yes | yes | | 3D models | b3d | .b3d | yes | - | +| 3D models | blend | .blend | yes | - | | 3D models | bsp | .bsp | yes | - | | 3D models | buildmap | .map | yes | yes | | 3D models | d3map | .map | yes | - | @@ -255,7 +256,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs//` | model | Brush, Displacement, DoomMap, Draco, Mat4, MeshFlatten, Minecraft, Patch, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml | | text | Json, KeyValues, Lexer, Nbt, Text, Url, Xml | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | -| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | +| containers | Archive, AudioWrap, Avi, Blend, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | ## Licence diff --git a/build/Rosetta.luau b/build/Rosetta.luau index f98ee1f..f326ebc 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -1618,6 +1618,18 @@ local list: { Entry } = { return __include("model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return __include("model/blend") + end, + }, { name = "bsp", category = "model", @@ -110701,6 +110713,745 @@ end return Avi end +__FILES["containers/Blend"] = function() + +-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header +-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header +-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads); +-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC, +-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files. +-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address. +local Err = __include("core/Err") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") + +local Blend = {} + +local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring + +type Field = { + name: string, -- without '*', '(*...)()' and array dimensions + decl: string, -- as declared ("*next", "co[3]", "mat[4][4]") + type: string, + offset: number, + size: number, -- bytes of the whole field (all array elements) + pointer: boolean, + dims: { number }, + count: number, -- array elements (1 for scalars) + elem: number, -- bytes of one element +} +type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } } +type Dna = { + names: { string }, + types: { string }, + lengths: { number }, + structs: { Struct }, -- 1-based; a block's sdna is 0-based + byName: { [string]: Struct }, +} +type Block = { + code: string, -- "OB", "ME", "DATA", ... (trailing NULs removed) + sdna: number, -- 0-based struct index + addr: any, -- the old address (a key: a number for 4-byte pointers, an 8-byte string for 8-byte ones) + size: number, -- data bytes + count: number, -- struct elements + offset: number, -- data start in file.buf + index: number, + owner: number, -- the index of the ID block this block follows (DATA blocks belong to the ID before them) +} +type File = { + buf: buffer, -- the (decompressed) file + version: number, -- 279, 293, 401, 502, ... + subversion: number?, -- from the GLOB block + pointerSize: number, + little: boolean, + format: number, -- 0 (12-byte header) or the 5.0+ file format version + compression: string?, -- "gzip" | "zstd" + blocks: { Block }, + byAddr: { [any]: Block }, + shared: { [any]: { Block } }, -- addresses used by several blocks (reused between IDs): every block with it + byCode: { [string]: { Block } }, + dna: Dna, + -- endian-aware readers (the little-endian ones are buffer's own) + u16: (b: buffer, o: number) -> number, + i16: (b: buffer, o: number) -> number, + u32: (b: buffer, o: number) -> number, + i32: (b: buffer, o: number) -> number, + f32: (b: buffer, o: number) -> number, + f64: (b: buffer, o: number) -> number, +} +type Options = { maxBytes: number?, maxBlocks: number? } + +-- ------------------------------------------------------------------------------------------------ readers +local function swap16(b: buffer, o: number): number + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function swap32(b: buffer, o: number): number + return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3) +end +local scratch = buffer.create(8) +local function bei16(b: buffer, o: number): number + local v = swap16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function bei32(b: buffer, o: number): number + local v = swap32(b, o) + return if v >= 2147483648 then v - 4294967296 else v +end +local function bef32(b: buffer, o: number): number + for k = 0, 3 do + buffer.writeu8(scratch, k, readu8(b, o + 3 - k)) + end + return readf32(scratch, 0) +end +local function bef64(b: buffer, o: number): number + for k = 0, 7 do + buffer.writeu8(scratch, k, readu8(b, o + 7 - k)) + end + return readf64(scratch, 0) +end + +-- ------------------------------------------------------------------------------------------------ open +function Blend.sniff(buf: buffer, offset: number?, length: number?): number + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if n >= 12 and readstring(buf, o, 7) == "BLENDER" then + return 1 + end + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + return 0.05 -- a gzip member: blend only once decompressed + end + return 0 +end + +local function decompress(buf: buffer, o: number, n: number, opts: Options?): (buffer?, string?, any) + local maxBytes = opts and opts.maxBytes or 2 ^ 31 + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + local out, err = Deflate.gunzip(buf, o, n) + if not out then + return nil, nil, err + end + if buffer.len(out) > maxBytes then + return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes") + end + return out, "gzip", nil + end + if n >= 4 and readu32(buf, o) == 0xFD2FB528 then + local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes }) + if not out then + return nil, nil, err + end + return out, "zstd", nil + end + return nil, nil, nil +end + +local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?) + if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then + return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)" + end + local c = readstring(b, 7, 1) + if c == "_" or c == "-" then + local e = readstring(b, 8, 1) + local v = tonumber(readstring(b, 9, 3)) + if (e ~= "v" and e ~= "V") or not v then + return nil, 0, false, 0, 0, "bad header" + end + return 12, if c == "_" then 4 else 8, e == "v", v, 0, nil + end + local hs = tonumber(readstring(b, 7, 2)) + if not hs or hs < 17 or hs > n then + return nil, 0, false, 0, 0, "bad header size" + end + if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then + return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7)) + end + local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4)) + if not fmt or not v then + return nil, 0, false, 0, 0, "bad header" + end + if fmt ~= 1 then + return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt + end + return hs, 8, true, v, fmt, nil +end + +local PRIM: { [string]: boolean } = { + char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true, + float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true, + uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true, +} +Blend.PRIMITIVE = PRIM + +local function parseDna(f: File, at: number, size: number): string? + local b = f.buf + local e = at + size + local i32 = f.i32 + local function align(p: number): number + return at + ((p - at + 3) // 4) * 4 + end + local function strings(p: number, tag: string): ({ string }?, number) + if p + 8 > e or readstring(b, p, 4) ~= tag then + return nil, p + end + local n = i32(b, p + 4) + p += 8 + if n < 0 or n > e - p then + return nil, p + end + local out = table.create(n) :: { string } + for k = 1, n do + local q = p + while q < e and readu8(b, q) ~= 0 do + q += 1 + end + if q >= e then + return nil, p + end + out[k] = readstring(b, p, q - p) + p = q + 1 + end + return out, p + end + if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then + return "no SDNA in DNA1" + end + local names, p = strings(at + 4, "NAME") + if not names then + return "bad SDNA NAME" + end + local types + types, p = strings(align(p), "TYPE") + if not types then + return "bad SDNA TYPE" + end + p = align(p) + local nt = #types + if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then + return "bad SDNA TLEN" + end + local lengths = table.create(nt) :: { number } + for k = 1, nt do + lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) + end + p = align(p + 4 + nt * 2) + if p + 8 > e or readstring(b, p, 4) ~= "STRC" then + return "bad SDNA STRC" + end + local ns = i32(b, p + 4) + p += 8 + if ns < 0 or ns * 4 > e - p then + return "bad SDNA struct count" + end + local i16 = f.i16 + local ps = f.pointerSize + local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct } + for k = 1, ns do + if p + 4 > e then + return "truncated SDNA structs" + end + local t, nf = i16(b, p), i16(b, p + 2) + p += 4 + if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then + return "bad SDNA struct " .. k + end + local tnames = types :: { string } + local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} } + local off = 0 + for j = 1, nf do + local ft, fn = i16(b, p), i16(b, p + 2) + p += 4 + if ft < 0 or ft >= nt or fn < 0 or fn >= #names then + return "bad SDNA field in " .. s.name + end + local decl: string = (names :: { string })[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims: { number }, count = {}, 1 + for d in string.gmatch(decl, "%[(%d+)%]") do + local v = tonumber(d) or 1 + table.insert(dims, v) + count *= v + end + local base = string.gsub(decl, "%[.*$", "") + base = string.gsub(base, "[%*%(%)]", "") + local elem: number = if pointer then ps else lengths[ft + 1] + local fld: Field = { + name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count, + pointer = pointer, dims = dims, count = count, elem = elem, + } + s.fields[j] = fld + if s.byName[base] == nil then + s.byName[base] = fld + end + off += fld.size + end + structs[k] = s + byName[s.name] = s + end + f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName } + return nil +end + +function Blend.open(data: buffer, offset: number?, length: number?, opts: Options?): (File?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "bad range") + end + local b: buffer + local unpacked, compression, derr = decompress(data, o, n, opts) + if derr then + return nil, derr + end + if unpacked then + b = unpacked + n = buffer.len(b) + elseif o == 0 and n == buffer.len(data) then + b = data + else + b = buffer.create(n) + buffer.copy(b, 0, data, o, n) + end + local hs, ps, little, version, fmt, herr = header(b, n) + if not hs then + local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, herr or "bad header", 0) + end + local f: File = { + buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, + compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil :: any, + u16 = if little then readu16 else swap16, + i16 = if little then readi16 else bei16, + u32 = if little then readu32 else swap32, + i32 = if little then readi32 else bei32, + f32 = if little then readf32 else bef32, + f64 = if little then readf64 else bef64, + } + local u32, i32 = f.u32, f.i32 + local maxBlocks = opts and opts.maxBlocks or 2 ^ 22 + local bh = if fmt >= 1 then 32 elseif ps == 8 then 24 else 20 + local p = hs + local dnaBlock: Block? = nil + local owner = 0 + while true do + if p + bh > n then + if p + 4 <= n and readstring(b, p, 4) == "ENDB" then + break -- ENDB written with a short head + end + return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p) + end + local code = readstring(b, p, 4) + local size, addr, sdna, count + if fmt >= 1 then + sdna = i32(b, p + 4) + addr = readstring(b, p + 8, 8) + local lo, hi = u32(b, p + 16), i32(b, p + 20) + local clo, chi = u32(b, p + 24), i32(b, p + 28) + if hi ~= 0 or chi ~= 0 then + return nil, Err.new(Err.LIMIT, "block over 4 GiB", p) + end + size, count = lo, clo + else + size = i32(b, p + 4) + addr = if ps == 8 then readstring(b, p + 8, 8) else u32(b, p + 8) + sdna = i32(b, p + 8 + ps) + count = i32(b, p + 12 + ps) + end + p += bh + -- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files + code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "") + if code == "ENDB" then + break + end + if size < 0 or count < 0 or size > n - p then + return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh) + end + if #f.blocks >= maxBlocks then + return nil, Err.new(Err.LIMIT, "too many blocks") + end + local index = #f.blocks + 1 + if code ~= "DATA" then + owner = index + end + local blk: Block = { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner } + table.insert(f.blocks, blk) + local prev = f.byAddr[addr] + if prev == nil then + f.byAddr[addr] = blk + else + local list = f.shared[addr] + if not list then + list = { prev } + f.shared[addr] = list + end + table.insert(list, blk) + end + local list = f.byCode[code] + if not list then + list = {} + f.byCode[code] = list + end + table.insert(list, blk) + if code == "DNA1" then + dnaBlock = blk + end + p += size + end + if not dnaBlock then + return nil, Err.new(Err.CORRUPT, "no DNA1 block") + end + local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size) + if derr2 then + return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset) + end + f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil + local glob = f.byCode.GLOB + local fg = f.dna.byName.FileGlobal + local g1: Block? = if glob then glob[1] else nil + local fld = fg and fg.byName.subversion + if g1 and fld then + if fld.offset + 2 <= g1.size then + f.subversion = f.i16(b, g1.offset + fld.offset) + end + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ structs +local View = {} +View.__index = View +Blend.View = View + +type View = typeof(setmetatable( + {} :: { + file: File, + struct: Struct, + offset: number, -- the struct's first byte in file.buf + block: Block?, + }, + View +)) + +local function view(f: File, s: Struct, offset: number, blk: Block?): View + return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) +end + +function Blend.structOf(f: File, blk: Block): Struct? + return f.dna.structs[blk.sdna + 1] +end + +function Blend.struct(f: File, blk: Block, i: number?, as: string?): View? + local s = if as then f.dna.byName[as] else f.dna.structs[blk.sdna + 1] + if not s then + return nil + end + local at = (i or 0) * s.size + if at < 0 or at + s.size > blk.size then + return nil + end + return view(f, s, blk.offset + at, blk) +end + +function Blend.view(f: File, structName: string, offset: number): View? + local s = f.dna.byName[structName] + if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then + return nil + end + return view(f, s, offset, nil) +end + +function Blend.field(f: File, structName: string, ...: string): Field? + local s = f.dna.byName[structName] + if not s then + return nil + end + for _, name in { ... } do + local fld = s.byName[name] + if fld then + return fld + end + end + return nil +end + +function Blend.blocks(f: File, code: string): { Block } + return f.byCode[code] or {} +end + +local function pointerKey(f: File, o: number): any + local b = f.buf + if f.pointerSize == 8 then + if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then + return nil + end + return readstring(b, o, 8) + end + local v = f.u32(b, o) + return if v == 0 then nil else v +end +Blend.pointerKey = pointerKey + +-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the +-- pointer comes from first (from = the block holding the pointer), as Blender's reader does +function Blend.resolve(f: File, addr: any, from: Block?): Block? + if addr == nil then + return nil + end + local list = f.shared[addr] + if list and from then + for _, b in list do + if b.owner == from.owner then + return b + end + end + end + return f.byAddr[addr] +end + +local function find(self: View, names: { any }): Field? + local by = self.struct.byName + for _, name in names do + local fld = by[name] + if fld then + return fld + end + end + return nil +end + +function View.has(self: View, ...: string): boolean + return find(self, { ... }) ~= nil +end + +local function scalar(f: File, t: string, size: number, o: number): number + local b = f.buf + if t == "float" then + return f.f32(b, o) + elseif t == "double" then + return f.f64(b, o) + elseif t == "int" or t == "int32_t" or t == "long" then + return if size == 8 then f.u32(b, o + (if f.little then 0 else 4)) else f.i32(b, o) + elseif t == "short" or t == "int16_t" then + return f.i16(b, o) + elseif t == "ushort" or t == "uint16_t" then + return f.u16(b, o) + elseif t == "uint" or t == "uint32_t" or t == "ulong" then + return f.u32(b, o) + elseif t == "int8_t" then + return readi8(b, o) + elseif t == "int64_t" or t == "uint64_t" then + local lo, hi = f.u32(b, o + (if f.little then 0 else 4)), f.u32(b, o + (if f.little then 4 else 0)) + if t == "int64_t" and hi >= 2147483648 then + return (hi - 4294967296) * 4294967296 + lo + end + return hi * 4294967296 + lo + end + return readu8(b, o) -- char, uchar, uint8_t, bool +end + +function View.get(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld then + return nil + end + local f = self.file + local o = self.offset + fld.offset + if o + fld.size > buffer.len(f.buf) then + return nil + end + if fld.pointer then + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false + end + return out + end + return pointerKey(f, o) + end + local t = fld.type + if PRIM[t] then + if fld.count == 1 then + return scalar(f, t, fld.elem, o) + end + if t == "char" then + local s = readstring(f.buf, o, fld.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem) + end + return out + end + local s = f.dna.byName[t] + if not s then + return nil + end + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = view(f, s, o + k * s.size, self.block) + end + return out + end + return view(f, s, o, self.block) +end + +function View.num(self: View, ...: string): number? + local v = self:get(...) + return if type(v) == "number" then v else nil +end + +function View.str(self: View, ...: string): string? + local v = self:get(...) + return if type(v) == "string" then v else nil +end + +function View.vec(self: View, ...: string): { number }? + local v = self:get(...) + return if type(v) == "table" and type(v[1]) == "number" then v else nil +end + +function View.sub(self: View, ...: string): View? + local v = self:get(...) + return if type(v) == "table" and getmetatable(v) == View then v else nil +end + +function View.ptr(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then + return nil + end + return pointerKey(self.file, self.offset + fld.offset) +end + +function View.target(self: View, ...: string): Block? + return Blend.resolve(self.file, self:ptr(...), self.block) +end + +function View.deref(self: View, name: string | { string }, i: number?, as: string?): View? + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return nil + end + local blk = self:target(fld.name) + if not blk then + return nil + end + local f = self.file + local sname = as or fld.type + if not as and (sname == "void" or not f.dna.byName[sname]) then + local own = f.dna.structs[blk.sdna + 1] + sname = if own then own.name else sname + end + return Blend.struct(f, blk, i, sname) +end + +function View.array(self: View, name: string | { string }, as: string?): { View } + local first = self:deref(name, 0, as) + if not first or not first.block then + return {} + end + local blk = first.block :: Block + local s = first.struct + local n = if s.size > 0 then blk.size // s.size else 0 + local out = table.create(n) :: { View } + for k = 0, n - 1 do + out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) + end + return out +end + +function View.pointers(self: View, name: string | { string }, n: number?): { any } + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return {} + end + local blk = self:target(fld.name) + if not blk then + return {} + end + local f = self.file + local ps = f.pointerSize + local count = blk.size // ps + if n then + count = math.min(count, n) + end + local out = table.create(count) + for k = 0, count - 1 do + out[k + 1] = pointerKey(f, blk.offset + k * ps) or false + end + return out +end + +function View.list(self: View, name: string | { string }, as: string?, limit: number?): { View } + local names: { any } = if type(name) == "table" then name else { name } + local lb = self:sub(table.unpack(names)) + local out = {} + if not lb then + return out + end + local f = self.file + local addr = lb:ptr("first") + local seen = {} + local max = limit or 2 ^ 20 + while addr ~= nil and not seen[addr] and #out < max do + seen[addr] = true + local blk = Blend.resolve(f, addr, self.block) + if not blk then + break + end + local v = Blend.struct(f, blk, 0, as) + if not v then + break + end + table.insert(out, v) + addr = v:ptr("next") + if addr == nil and not v.struct.byName.next then + -- structs that start with an embedded header (ModifierData, ...) keep the link there + local head = v.struct.fields[1] + local sub = head and not head.pointer and f.dna.byName[head.type] + if sub then + addr = view(f, sub, v.offset + head.offset, v.block):ptr("next") + end + end + end + return out +end + +function View.data(self: View, ...: string): (number?, number) + local blk = self:target(...) + if not blk then + return nil, 0 + end + return blk.offset, blk.size +end + +function View.cstring(self: View, ...: string): string? + local blk = self:target(...) + if not blk then + return nil + end + local s = readstring(self.file.buf, blk.offset, blk.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +function View.idName(self: View): string? + local id = self:sub("id") + local n = if id then id:str("name") else self:str("name") + if not n then + return nil + end + return string.sub(n, 3) +end + +return Blend +end __FILES["containers/Chunks"] = function() -- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and @@ -148143,6 +148894,2945 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, return scene, nil, nil end +return Read +end +__FILES["model/blend"] = function() + +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Blend = __include("containers/Blend") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Read = __include("model/blend/Read") +local Anim = __include("model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true (false: "polygons" primitives) + flipV: boolean?, -- default true (glTF's top-left UV origin) + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- a scene by name (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, -- external images + files: { [string]: any }?, + maxBytes: number?, -- decompressed size limit (default 2^31) + maxVertices: number?, -- per mesh (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. +function BlendFormat.sniff(r: Bytes.Reader): number + local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?) + return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat +end +__FILES["model/blend/Anim"] = function() + +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = __include("containers/Blend") + +local Anim = {} + +type Key = { + x: number, + y: number, + lx: number, -- left handle + ly: number, + rx: number, -- right handle + ry: number, + ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine) + easing: number, -- 0 auto, 1 in, 2 out, 3 in-out + back: number, + amplitude: number, + period: number, +} +type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number } + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f: Blend.File, fc: Blend.View): Curve? + local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys: { Key } = {} + for _, b in fc:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in fc:array("fpt", "FPoint") do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) + if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list: { Blend.View } = act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in act:pointers("layer_array", act:num("layer_array_num")) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out: { Curve } = {} + for _, fc in list do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR: { [number]: { any } } = { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?) + if not ipo then + return nil, nil + end + local out: { Curve } = {} + for _, icu in ipo:list("curve", "IpoCurve") do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys: { Key } = {} + for _, b in icu:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number + local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a: Key, b: Key, x: number): number + local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = if d ~= 0 then t - (xt - x) / d else -1 + t = if nt > lo and nt < hi then nt else (lo + hi) / 2 + end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t: number, b: number, c: number, d: number): number + t /= d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t -= 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t -= 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t -= 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 + if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = if a.period > 0 then a.period / 10 else 0.3 + local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t -= 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a: Key, b: Key, x: number): number + local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c: Curve, x: number): number + local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves: { Curve }): (number, number) + local lo, hi = math.huge, -math.huge + for _, c in curves do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path: string): (string?, string?, string) + local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim +end +__FILES["model/blend/Material"] = function() + +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = __include("containers/Blend") +local Types = __include("Types") + +local Material = {} + +type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any } + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b: buffer, o: number, n: number, path: string?): string? + if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return if ext then byExt[ext] else nil +end + +local function fetch(ctx: Ctx, uri: string): buffer? + local opts = ctx.opts + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number? + local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil + local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in img:list("packedfiles", "ImagePackedFile") do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex: Types.Texture = { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + +type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } } +type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr + +local function graph(tree: Blend.View): Graph + local g: Graph = { nodes = {}, links = {} } + for _, n in tree:list("nodes", "bNode") do + local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in n:list("inputs", "bNodeSocket") do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in n:list("outputs", "bNodeSocket") do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in tree:list("links", "bNodeLink") do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n: Node, ...: string): Blend.View? + for _, k in { ... } do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }? + if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s: Blend.View?, kind: string): any + if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?) + local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, if ref then n else tn + end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler: Types.Sampler = {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, if custom then sampler else nil) + if not t then + return nil, n + end + local ref: Types.TextureRef = { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g: Graph): Node? + local first: Node? = nil + for _, n in g.nodes do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m: Types.Material, color: { number }, strength: number) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx: Ctx, mv: Blend.View): number + local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras: { [string]: any } = {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g: Graph? = nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g :: Graph) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1 + m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material +end +__FILES["model/blend/Mesh"] = function() + +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = __include("containers/Blend") + +local Mesh = {} + +type Layer = { + name: string, + domain: string, -- "point" | "edge" | "face" | "corner" | "tess" + kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, + -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) + offset: number, -- data start in file.buf + bytes: number, -- data bytes available + elem: number, -- bytes per element + single: boolean?, -- one value for every element (AttributeStorage single storage) + activeRender: boolean?, + cdtype: number?, +} + +type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner +type Poly = { + name: string?, + nv: number, + nf: number, + nc: number, + pos: buffer, -- f32 x 3 per vertex + cornerVert: buffer, -- u32 per corner + faceStart: buffer, -- u32 per face + 1 + faceMat: buffer, -- i32 per face + faceSmooth: buffer, -- u8 per face + uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner + activeUV: number, -- 1-based index into uvs (the active render layer) + colors: { Color }, + customNormals: buffer?, -- f32 x 3 per corner (free custom normals) + encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) + sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans + autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) + weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... + generation: string, -- "mface" | "mpoly" | "attributes" | "storage" + layers: { Layer }, +} + +local CD_KIND: { [number]: string } = { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND: { [number]: string } = { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE: { [string]: number } = { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end +Mesh.SRGB = SRGB + +local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = if st then st.size else SIZE[kind] or 0 + if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f: Blend.File, me: Blend.View, out: { Layer }) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? + for _, L in layers do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? + local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f: Blend.File, L: Layer): (number, number) -> number + local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 + return function(i: number, c: number): number + local at = (if single then 0 else i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? + local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i: number, c: number): number + local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at += o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer + local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255) + end + end + return d +end + +function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } + local layers: { Layer } = {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me: Blend.View, ...: string): number + local v = me:num(...) + return if v and v > 0 then v else 0 +end + +type Limits = { maxVertices: number? } + +function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) + local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get: ((number, number) -> number)? = nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_: number, _: number): number + return 0 + end + end + local g = get :: (number, number) -> number + for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly: Poly = { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", + layers = layers, + } + local corner: { [string]: any } = {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at += math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w += 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil + local flag = if mp then fieldReader(f, mp, "flag") else nil + local sr = if sf then reader(f, sf) else nil + for i = 0, np - 1 do + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, if s then 1 else 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at += k + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap: buffer? = corner.remap + local function src(i: number): number + return if remap then buffer.readu32(remap, i * 4) else i + end + for _, L in layers do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess :: buffer + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = tc // 4, tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess :: buffer + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in poly.uvs do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in layers do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = if L.domain == "corner" then nc else nv + local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = if L.domain == "corner" then src(i) else i + for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] + end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = if st then st.size else 4 + table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in layers do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) + for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i: number): number return er(i, 0) end + v2 = function(i: number): number return er(i, 1) end + sharp = function(i: number): boolean return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i: number): number return a(i, 0) end + v2 = function(i: number): number return b(i, 0) end + local ser = if se then reader(f, se) else nil + sharp = function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = table.create(nv) :: { { number } } + for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, blk.size // mw.size) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end + +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index +type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } +function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) + local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out: { Shape } = {} + local ref: number? = nil + for i, kb in blocks do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, n // 4 - 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh +end +__FILES["model/blend/Normals"] = function() + +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + +type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } } + +local function dir(pos: buffer, from: number, to: number): (number, number, number) + local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer + local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals :: buffer + local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done: { [number]: boolean } = {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard += 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = if nq then readu32(nxt, nq * 4) else c + if q < m then + m = q + end + guard += 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in edges do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count += 1 + end + end + alpha /= math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = if cyclic then edges[2] else edges[#edges] + local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in corners do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = (if a > 0 then alpha else TAU - alpha) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = (if b > 0 then beta else TAU - beta) * b + x += sa * (rx * cos(be) + tx * sin(be)) + y += sa * (ry * cos(be) + ty * sin(be)) + z += sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals +end +__FILES["model/blend/Prim"] = function() + +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") +local Rig = __include("codecs/model/Rig") +local Normals = __include("model/blend/Normals") +local MeshT = __include("model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + +type Options = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true (glTF's top-left UV origin) + normals: boolean?, -- default true +} +type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin + +local function face(poly: MeshT.Poly, fi: number): (number, number) + return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos: buffer, v: number): (number, number, number) + return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly: MeshT.Poly): (buffer, buffer) + local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = if c + 1 < s1 then c + 1 else s0 + local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx += (y1 - y2) * (z1 + z2) + ny += (z1 - z2) * (x1 + x2) + nz += (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = if c > s0 then c - 1 else s1 - 1 + local nc = if c + 1 < s1 then c + 1 else s0 + local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end + +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges +type Fans = { + next: buffer, -- u32 per corner: the next corner of its face + prev: buffer, -- u32 per corner + face: buffer, -- u32 per corner: its face + -- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner + -- at this corner's next vertex), or -1 where the edge splits fans + across: { [number]: number }, +} + +function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans + local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0) + writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1) + writeu32(fc, c * 4, fi) + end + end + local first: { [number]: number } = {} + local second: { [number]: number } = {} + local uses: { [number]: number } = {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across: { [number]: number } = {} + local smooth = poly.faceSmooth + local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil + for key, u in uses do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer) + local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c: number): number + local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a: number, b: number) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in fans.across do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12)) + writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4)) + writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8)) + end + return out, fanId +end + +function Prim.normals(poly: MeshT.Poly): buffer + local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals :: buffer + end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number }) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = table.create(n * 2) :: { number } + for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, if sign < 0 then -u else u) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t: { number }, comps: number): Types.Accessor + local n = #t // comps + local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built + local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil + local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0) + local nslots = math.max(#slots, 1) + local groups: { [number]: { number } } = {} + local order: { number } = {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {} + for _, c in poly.colors do + table.insert(if c.domain == "corner" then cornerColors else pointColors, c) + end + local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh: Types.Mesh = { name = poly.name, primitives = {} } + local sources: { { number } } = {} + local cv = poly.cornerVert + for _, m in order do + local faces = groups[m] + local map: { [string]: number } = {} + local vsrc: { number } = {} + local corners: { number } = {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in faces do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o += 12 + end + for _, uv in poly.uvs do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o += 8 + end + for _, col in cornerColors do + buffer.copy(scratch, o, col.data, c * 16, 16) + o += 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs: { [string]: Types.Accessor } = {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in poly.uvs do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in poly.colors do + local C = buffer.create(n * 16) + for i = 1, n do + local e = if col.domain == "corner" then corners[i] else vsrc[i] + buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci += 1 + end + if skin and poly.weights then + local lists = table.create(n) :: { { number } } + for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k]] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim: Types.Primitive = { attributes = attrs, mode = "triangles" } + local idx: { number } = {} + if triangulateOn then + for _, fi in faces do + local tri: { number } = {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in tri do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in faces do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in idx do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets: { { [string]: Types.Accessor } } = {} + for k, s in shapes do + if k ~= ref then + local t = table.create(n * 3) :: { number } + for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in shapes do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in order do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim +end +__FILES["model/blend/Read"] = function() + +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = __include("containers/Blend") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Mesh = __include("model/blend/Mesh") +local Prim = __include("model/blend/Prim") +local Anim = __include("model/blend/Anim") +local Material = __include("model/blend/Material") + +local Read = {} + +local Scene = Types.Scene +type M4 = { number } + +type Options = { + triangulate: boolean?, + flipV: boolean?, + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- the scene to read (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, +} + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME: { [number]: string } = { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q: { number }?): { number } + if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4 + if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m: M4, s: { number }): M4 + local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do + r[c * 4 + k] *= s[c + 1] + end + end + return r +end + +local function trs(t: { number }, r: M4, s: { number }): M4 + local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + +type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode + +local function objectProps(ob: Blend.View): Props + -- fields missing from old files take their neutral value + local function v(fallback: { number }, ...: string): { number } + local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p: Props = { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc: Blend.View?): Props + if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n: number, ...: string): { number } + local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p: Props): M4 + local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node: Types.Node, m: M4) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v: Blend.View?, ...: string): M4? + local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ scene +type Ctx = { + f: Blend.File, + scene: Types.Scene, + opts: Options, + objects: { [any]: number }, -- OB addr -> node + objView: { [number]: Blend.View }, -- node -> its object + parentOf: { [number]: number }, + world: { [number]: M4 }, + meshes: { [string]: number }, + materials: { [any]: number }, + textures: { [any]: number }, + armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) + props: { [number]: Props }, + meta: { [string]: any }, + pending: { { node: number, ob: Blend.View } }, +} + +local function worldOf(ctx: Ctx, node: number): M4 + local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = if p then Mat4.mul(worldOf(ctx, p), m) else m + ctx.world[node] = w + return w +end + +local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number + table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames: { [string]: Blend.View } = {} + if pose then + for _, pc in pose:list("chanbase", "bPoseChannel") do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) + if depth > 256 then + return + end + for _, bone in list do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest + local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode: Types.Node = { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = if parentJoint then info.joints[parentJoint] else node + local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx: Ctx, ob: Blend.View, node: number) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c: Types.Camera + if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera + else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera + end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx: Ctx, ob: Blend.View, node: number) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy *= 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in if tree then tree:list("nodes", "bNode") else {} do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in n:list("inputs", "bNodeSocket") do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l: Types.Light + if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light + elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light + elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light + else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number } + local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = if useOb then obMats[i] else meMats[i] + local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx :: any, mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View? + for _, md in ob:list("modifiers") do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob: Blend.View, me: Blend.View): { string } + local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in list do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin: Prim.Skinning? = nil + if armInfo then + local joints = {} + for gi, name in groupNames(ob, me) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number }) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx: Ctx) + for _, p in ctx.pending do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number? + local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode: number? = under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node: Types.Node = { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in ob:list("modifiers") do + table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props + local p: Props = {} + for k, v in props do + p[k] = table.clone(v) + end + for _, c in curves do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end +type Curve = Anim.Curve + +local function frames(lo: number, hi: number, step: number): { number } + local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f += step + end + table.insert(out, hi) + return out +end + +type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? } + +local function animations(ctx: Ctx) + local f = ctx.f + local jobs: { Job } = {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner: { [any]: string } = {} + for _, ob in ctx.objView do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in ctx.meta.shapeKeys do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves: { Curve }? = found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in sk.shapes do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in mc or {} do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list: { Curve } = curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in ctx.scene.nodes do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a: Job, b: Job): boolean + return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in jobs do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction: { [string]: Types.Animation } = {} + for _, j in jobs do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } :: Types.Animation + byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in fs do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node :: number + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in j.curves do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who]] = true + end + end + for b in touched do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in fs do + local k = 0 + for si, s in sk.shapes do + if si ~= sk.ref then + local v = s.value + for _, c in j.curves do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k += 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in times do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in j.nodes :: { number } do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any }, + } }) + end + end + for _, a in tmp.animations do + for _, ch in a.channels do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f: Blend.File, name: string?): Blend.View? + local scenes = Blend.blocks(f, "SC") + if name then + for _, b in scenes do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil +end + +function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) + local o: Options = opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta: { [string]: any } = { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx: Ctx = { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order: { { ob: Blend.View, under: number? } } = {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = if fps > 0 then fps else 24 + meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col: Blend.View, under: number?, depth: number) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in col:list("gobject", "CollectionObject") do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in col:list("children", "CollectionChild") do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn: number? = nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in sc:list("base", "Base") do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in Blend.blocks(f, "OB") do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder: { [any]: number? } = {} + for _, e in order do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in order do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, if u and u > 0 then u else nil, 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + return Read end __FILES["model/bsp"] = function() diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index c43d87c..3894870 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,575 +1,583 @@ [ [29, "src/Rosetta/init.luau"], [873, "src/Rosetta/Registry.luau"], -[3126, "src/Rosetta/Types.luau"], -[4209, "src/Rosetta/archive/7z/init.luau"], -[4594, "src/Rosetta/archive/7z/Header.luau"], -[5121, "src/Rosetta/archive/adf/init.luau"], -[5403, "src/Rosetta/archive/applesingle/init.luau"], -[5589, "src/Rosetta/archive/ar/init.luau"], -[5992, "src/Rosetta/archive/arj/init.luau"], -[6202, "src/Rosetta/archive/binhex/init.luau"], -[6451, "src/Rosetta/archive/br/init.luau"], -[6526, "src/Rosetta/archive/bz2/init.luau"], -[6590, "src/Rosetta/archive/cab/init.luau"], -[7003, "src/Rosetta/archive/cab/Sum.luau"], -[7044, "src/Rosetta/archive/cpio/init.luau"], -[7212, "src/Rosetta/archive/d64/init.luau"], -[7626, "src/Rosetta/archive/fat/init.luau"], -[7748, "src/Rosetta/archive/grp/init.luau"], -[7862, "src/Rosetta/archive/gzip/init.luau"], -[8047, "src/Rosetta/archive/iso/init.luau"], -[8119, "src/Rosetta/archive/lha/init.luau"], -[8544, "src/Rosetta/archive/lz4/init.luau"], -[8888, "src/Rosetta/archive/macbinary/init.luau"], -[9086, "src/Rosetta/archive/mpq/init.luau"], -[9492, "src/Rosetta/archive/mpq/Crypt.luau"], -[9557, "src/Rosetta/archive/pak/init.luau"], -[9691, "src/Rosetta/archive/rpm/init.luau"], -[10015, "src/Rosetta/archive/tar/init.luau"], -[10133, "src/Rosetta/archive/uu/init.luau"], -[10403, "src/Rosetta/archive/vpk/init.luau"], -[10714, "src/Rosetta/archive/vswap/init.luau"], -[10984, "src/Rosetta/archive/wad/init.luau"], -[11438, "src/Rosetta/archive/wad/Picture.luau"], -[11540, "src/Rosetta/archive/xz/init.luau"], -[11640, "src/Rosetta/archive/yenc/init.luau"], -[11912, "src/Rosetta/archive/z/init.luau"], -[12008, "src/Rosetta/archive/zip/init.luau"], -[12227, "src/Rosetta/archive/zoo/init.luau"], -[12423, "src/Rosetta/archive/zst/init.luau"], -[12487, "src/Rosetta/audio/aac/init.luau"], -[12693, "src/Rosetta/audio/ac3/init.luau"], -[12839, "src/Rosetta/audio/adpcm/init.luau"], -[12984, "src/Rosetta/audio/adx/init.luau"], -[13215, "src/Rosetta/audio/aiff/init.luau"], -[13606, "src/Rosetta/audio/ape/init.luau"], -[13734, "src/Rosetta/audio/au/init.luau"], -[13895, "src/Rosetta/audio/brstm/init.luau"], -[14186, "src/Rosetta/audio/caf/init.luau"], -[14848, "src/Rosetta/audio/flac/init.luau"], -[14996, "src/Rosetta/audio/flac/Meta.luau"], -[15218, "src/Rosetta/audio/flac/Stream.luau"], -[15588, "src/Rosetta/audio/m4a/init.luau"], -[15922, "src/Rosetta/audio/mp3/init.luau"], -[16182, "src/Rosetta/audio/mp3/Index.luau"], -[16373, "src/Rosetta/audio/mp3/Stream.luau"], -[16600, "src/Rosetta/audio/mp3/Tags.luau"], -[16912, "src/Rosetta/audio/mpc/init.luau"], -[17006, "src/Rosetta/audio/opus/init.luau"], -[17384, "src/Rosetta/audio/opus/Encode.luau"], -[17495, "src/Rosetta/audio/qoa/init.luau"], -[17675, "src/Rosetta/audio/tta/init.luau"], -[17793, "src/Rosetta/audio/vag/init.luau"], -[18016, "src/Rosetta/audio/voc/init.luau"], -[18291, "src/Rosetta/audio/vorbis/init.luau"], -[18745, "src/Rosetta/audio/vorbis/Encode.luau"], -[19558, "src/Rosetta/audio/wav/init.luau"], -[20179, "src/Rosetta/audio/wav/Codecs.luau"], -[20345, "src/Rosetta/audio/wavpack/init.luau"], -[20552, "src/Rosetta/cad/step/init.luau"], -[20934, "src/Rosetta/cad/step/Brep.luau"], -[21169, "src/Rosetta/cad/step/Parse.luau"], -[21726, "src/Rosetta/cad/step/Write.luau"], -[21974, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22293, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23176, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[23511, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[23670, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[24555, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[24656, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[25410, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[25712, "src/Rosetta/codecs/audio/Alac/init.luau"], -[25946, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26365, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[26777, "src/Rosetta/codecs/audio/Ape/init.luau"], -[26992, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[27753, "src/Rosetta/codecs/audio/ApeTag.luau"], -[27850, "src/Rosetta/codecs/audio/Flac/init.luau"], -[27861, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[28810, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[29407, "src/Rosetta/codecs/audio/Hively/init.luau"], -[29603, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[29852, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[30810, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31029, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31213, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[31422, "src/Rosetta/codecs/audio/MidiRender.luau"], -[31768, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[31782, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[31841, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[33444, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[33736, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34121, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[34762, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[34903, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35129, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[35474, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36368, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[36746, "src/Rosetta/codecs/audio/Opus/init.luau"], -[36760, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[38607, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[39672, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[39732, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40192, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[40529, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[40762, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[42798, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43172, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[43435, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[43732, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44014, "src/Rosetta/codecs/audio/Resample/init.luau"], -[44373, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[44427, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[44570, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45083, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[45864, "src/Rosetta/codecs/audio/Stream.luau"], -[46025, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[46507, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[46785, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[46954, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47082, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49070, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49186, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49303, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[49555, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[49568, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[49952, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[50518, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[50939, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[50978, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51030, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51252, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[52707, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[52770, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[52857, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[53826, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[54694, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[54742, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55258, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[55584, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56004, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[56439, "src/Rosetta/codecs/compress/Explode.luau"], -[56635, "src/Rosetta/codecs/compress/Lz4.luau"], -[56904, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[57508, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58048, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58086, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[58559, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[58735, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59003, "src/Rosetta/codecs/compress/Lzx.luau"], -[59437, "src/Rosetta/codecs/compress/PackBits.luau"], -[59527, "src/Rosetta/codecs/compress/Quantum.luau"], -[59764, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60068, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60137, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60194, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61152, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61304, "src/Rosetta/codecs/entropy/Huffman.luau"], -[61586, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[61597, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[61811, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62055, "src/Rosetta/codecs/font/Bitmap.luau"], -[62256, "src/Rosetta/codecs/font/Cff/init.luau"], -[62897, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63047, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63361, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[63753, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64255, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64362, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[64851, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65280, "src/Rosetta/codecs/image/Blend.luau"], -[65659, "src/Rosetta/codecs/image/Dct/init.luau"], -[66040, "src/Rosetta/codecs/image/Etc.luau"], -[66338, "src/Rosetta/codecs/image/Half.luau"], -[66407, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[66761, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67169, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[67406, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68166, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69047, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[69493, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[69571, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[69638, "src/Rosetta/codecs/image/Miptex.luau"], -[69854, "src/Rosetta/codecs/image/Pixels.luau"], -[70174, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70633, "src/Rosetta/codecs/image/Raster.luau"], -[71330, "src/Rosetta/codecs/image/Texel.luau"], -[71703, "src/Rosetta/codecs/image/Texture.luau"], -[71848, "src/Rosetta/codecs/image/Vp8/init.luau"], -[71978, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[73934, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74193, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74442, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74561, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[74665, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75518, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76470, "src/Rosetta/codecs/image/Yuv.luau"], -[76738, "src/Rosetta/codecs/model/Brush.luau"], -[77378, "src/Rosetta/codecs/model/Displacement.luau"], -[77527, "src/Rosetta/codecs/model/DoomMap/init.luau"], -[77972, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], -[78222, "src/Rosetta/codecs/model/Draco/init.luau"], -[78554, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[79023, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[80212, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[80361, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[80720, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[81682, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[82156, "src/Rosetta/codecs/model/Mat4.luau"], -[82415, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[82943, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[83495, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[83574, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[83681, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[83887, "src/Rosetta/codecs/model/Patch.luau"], -[84011, "src/Rosetta/codecs/model/Polygon.luau"], -[84245, "src/Rosetta/codecs/model/Rbx/init.luau"], -[84482, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[85236, "src/Rosetta/codecs/model/Rig.luau"], -[85479, "src/Rosetta/codecs/model/Sampler.luau"], -[85639, "src/Rosetta/codecs/model/SourceAnim.luau"], -[85860, "src/Rosetta/codecs/model/Vrml/init.luau"], -[86008, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[86582, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[86745, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[87494, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[88016, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[88743, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[88975, "src/Rosetta/codecs/text/Json/init.luau"], -[89244, "src/Rosetta/codecs/text/Json/Decode.luau"], -[89658, "src/Rosetta/codecs/text/Json/Encode.luau"], -[89960, "src/Rosetta/codecs/text/KeyValues/init.luau"], -[90530, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], -[90836, "src/Rosetta/codecs/text/Lexer/init.luau"], -[90968, "src/Rosetta/codecs/text/Nbt/init.luau"], -[91321, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[92013, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[92653, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[92891, "src/Rosetta/codecs/text/Text/init.luau"], -[92982, "src/Rosetta/codecs/text/Url/init.luau"], -[93187, "src/Rosetta/codecs/text/Xml/init.luau"], -[93590, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[94330, "src/Rosetta/codecs/video/Dsp.luau"], -[95053, "src/Rosetta/codecs/video/H263/init.luau"], -[95209, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[96067, "src/Rosetta/codecs/video/H263/Tables.luau"], -[96270, "src/Rosetta/codecs/video/H264/init.luau"], -[96643, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[96918, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[98049, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[98817, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[99075, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[100084, "src/Rosetta/codecs/video/H264/Inter.luau"], -[100338, "src/Rosetta/codecs/video/H264/Intra.luau"], -[100745, "src/Rosetta/codecs/video/H264/Mb.luau"], -[101651, "src/Rosetta/codecs/video/H264/Params.luau"], -[102098, "src/Rosetta/codecs/video/H264/Slice.luau"], -[102349, "src/Rosetta/codecs/video/H264/Tables.luau"], -[102390, "src/Rosetta/codecs/video/H264/Transform.luau"], -[102555, "src/Rosetta/codecs/video/Legacy/init.luau"], -[102753, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[103050, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[103417, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[103535, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[103643, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[103916, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[104311, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[104488, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[104500, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[104867, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[106374, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[106513, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[106651, "src/Rosetta/codecs/video/Theora/init.luau"], -[106914, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[108178, "src/Rosetta/codecs/video/Theora/Header.luau"], -[108541, "src/Rosetta/codecs/video/Video/init.luau"], -[109098, "src/Rosetta/codecs/video/Video/Source.luau"], -[109383, "src/Rosetta/containers/Archive.luau"], -[109650, "src/Rosetta/containers/AudioWrap.luau"], -[110153, "src/Rosetta/containers/Avi/init.luau"], -[110705, "src/Rosetta/containers/Chunks.luau"], -[110840, "src/Rosetta/containers/Cpio.luau"], -[111268, "src/Rosetta/containers/Demux.luau"], -[111543, "src/Rosetta/containers/Ebml/init.luau"], -[111856, "src/Rosetta/containers/Fat.luau"], -[112544, "src/Rosetta/containers/Iso9660.luau"], -[113049, "src/Rosetta/containers/IsoBmff/init.luau"], -[113219, "src/Rosetta/containers/IsoBmff/Box.luau"], -[113407, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[114252, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[114773, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[115289, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[115406, "src/Rosetta/containers/MacFile.luau"], -[115555, "src/Rosetta/containers/MpegEs.luau"], -[115721, "src/Rosetta/containers/MpegPs/init.luau"], -[115941, "src/Rosetta/containers/MpegTs/init.luau"], -[116733, "src/Rosetta/containers/Ogg/init.luau"], -[117158, "src/Rosetta/containers/Ogg/Mux.luau"], -[117353, "src/Rosetta/containers/Ogg/Page.luau"], -[117522, "src/Rosetta/containers/Riff/init.luau"], -[117839, "src/Rosetta/containers/Tar.luau"], -[118253, "src/Rosetta/containers/Zip/init.luau"], -[118885, "src/Rosetta/core/Adler32.luau"], -[118931, "src/Rosetta/core/Base64.luau"], -[119090, "src/Rosetta/core/Bits.luau"], -[119383, "src/Rosetta/core/Bytes.luau"], -[119910, "src/Rosetta/core/Crc16.luau"], -[119962, "src/Rosetta/core/Crc32.luau"], -[120074, "src/Rosetta/core/Err.luau"], -[120156, "src/Rosetta/core/Input.luau"], -[120232, "src/Rosetta/core/Md5.luau"], -[120391, "src/Rosetta/core/Sniff.luau"], -[120420, "src/Rosetta/data/cbor/init.luau"], -[120519, "src/Rosetta/data/cbor/Codec.luau"], -[121088, "src/Rosetta/data/csv/init.luau"], -[121400, "src/Rosetta/data/ini/init.luau"], -[121646, "src/Rosetta/data/json/init.luau"], -[121738, "src/Rosetta/data/msgpack/init.luau"], -[121827, "src/Rosetta/data/msgpack/Codec.luau"], -[122269, "src/Rosetta/data/nbt/init.luau"], -[122328, "src/Rosetta/data/plist/init.luau"], -[122634, "src/Rosetta/data/plist/Binary.luau"], -[122901, "src/Rosetta/data/snbt/init.luau"], -[122964, "src/Rosetta/data/toml/init.luau"], -[123031, "src/Rosetta/data/toml/Decode.luau"], -[123659, "src/Rosetta/data/toml/Encode.luau"], -[123868, "src/Rosetta/data/vdf/init.luau"], -[123969, "src/Rosetta/data/xml/init.luau"], -[124025, "src/Rosetta/data/yaml/init.luau"], -[124098, "src/Rosetta/data/yaml/Emit.luau"], -[124388, "src/Rosetta/data/yaml/Parse.luau"], -[125681, "src/Rosetta/font/bdf/init.luau"], -[125970, "src/Rosetta/font/bmfont/init.luau"], -[126397, "src/Rosetta/font/bmfont/Parse.luau"], -[126850, "src/Rosetta/font/eot/init.luau"], -[127082, "src/Rosetta/font/fon/init.luau"], -[127365, "src/Rosetta/font/hershey/init.luau"], -[127560, "src/Rosetta/font/pcf/init.luau"], -[127840, "src/Rosetta/font/psf/init.luau"], -[128160, "src/Rosetta/font/ttf/init.luau"], -[128211, "src/Rosetta/font/type1/init.luau"], -[128570, "src/Rosetta/font/type1/Charstring.luau"], -[128848, "src/Rosetta/font/woff/init.luau"], -[128980, "src/Rosetta/font/woff2/init.luau"], -[129037, "src/Rosetta/font/woff2/Rebuild.luau"], -[129577, "src/Rosetta/host/init.luau"], -[129622, "src/Rosetta/host/Love.luau"], -[129765, "src/Rosetta/host/LuaJIT.luau"], -[129815, "src/Rosetta/host/Luau.luau"], -[129838, "src/Rosetta/host/Roblox.luau"], -[130197, "src/Rosetta/image/ani/init.luau"], -[130377, "src/Rosetta/image/art/init.luau"], -[130865, "src/Rosetta/image/blp/init.luau"], -[131123, "src/Rosetta/image/bmp/init.luau"], -[131538, "src/Rosetta/image/dds/init.luau"], -[132021, "src/Rosetta/image/exr/init.luau"], -[132781, "src/Rosetta/image/exr/Codec.luau"], -[132892, "src/Rosetta/image/exr/Piz.luau"], -[133249, "src/Rosetta/image/gif/init.luau"], -[133765, "src/Rosetta/image/gif/Decode.luau"], -[133828, "src/Rosetta/image/hdr/init.luau"], -[134057, "src/Rosetta/image/hdr/Codec.luau"], -[134268, "src/Rosetta/image/icns/init.luau"], -[134599, "src/Rosetta/image/ico/init.luau"], -[134876, "src/Rosetta/image/ico/Dib.luau"], -[134971, "src/Rosetta/image/ilbm/init.luau"], -[135290, "src/Rosetta/image/jpeg/init.luau"], -[135426, "src/Rosetta/image/ktx/init.luau"], -[136086, "src/Rosetta/image/pcx/init.luau"], -[136350, "src/Rosetta/image/png/init.luau"], -[136930, "src/Rosetta/image/png/Apng.luau"], -[137010, "src/Rosetta/image/png/Decode.luau"], -[137250, "src/Rosetta/image/png/Encode.luau"], -[137405, "src/Rosetta/image/pnm/init.luau"], -[137783, "src/Rosetta/image/pnm/Codec.luau"], -[138060, "src/Rosetta/image/qoi/init.luau"], -[138182, "src/Rosetta/image/qoi/Codec.luau"], -[138332, "src/Rosetta/image/sgi/init.luau"], -[138617, "src/Rosetta/image/sunras/init.luau"], -[138863, "src/Rosetta/image/tga/init.luau"], -[139133, "src/Rosetta/image/tga/Codec.luau"], -[139285, "src/Rosetta/image/tiff/init.luau"], -[140112, "src/Rosetta/image/tiff/Pixels.luau"], -[140502, "src/Rosetta/image/tim/init.luau"], -[140744, "src/Rosetta/image/vtf/init.luau"], -[140979, "src/Rosetta/image/webp/init.luau"], -[141589, "src/Rosetta/image/webp/Alpha.luau"], -[141665, "src/Rosetta/image/webp/Anim.luau"], -[141820, "src/Rosetta/image/xbm/init.luau"], -[141981, "src/Rosetta/image/xpm/init.luau"], -[142249, "src/Rosetta/image/xpm/Names.luau"], -[142305, "src/Rosetta/layered/aseprite/init.luau"], -[143043, "src/Rosetta/layered/ora/init.luau"], -[143330, "src/Rosetta/layered/psd/init.luau"], -[144065, "src/Rosetta/layered/psd/Channels.luau"], -[144417, "src/Rosetta/model/3ds/init.luau"], -[144500, "src/Rosetta/model/3ds/Build.luau"], -[145147, "src/Rosetta/model/3ds/Read.luau"], -[145643, "src/Rosetta/model/3ds/Write.luau"], -[146448, "src/Rosetta/model/3mf/init.luau"], -[146530, "src/Rosetta/model/3mf/Read.luau"], -[147118, "src/Rosetta/model/3mf/Write.luau"], -[147523, "src/Rosetta/model/b3d/init.luau"], -[147578, "src/Rosetta/model/b3d/Read.luau"], -[148149, "src/Rosetta/model/bsp/init.luau"], -[148294, "src/Rosetta/model/bsp/Brush.luau"], -[148557, "src/Rosetta/model/bsp/Quake3.luau"], -[148785, "src/Rosetta/model/buildmap/init.luau"], -[149057, "src/Rosetta/model/buildmap/Geometry.luau"], -[149460, "src/Rosetta/model/d3map/init.luau"], -[149742, "src/Rosetta/model/d3map/Parse.luau"], -[149940, "src/Rosetta/model/dae/init.luau"], -[150129, "src/Rosetta/model/dae/Math.luau"], -[150176, "src/Rosetta/model/dae/Read.luau"], -[152026, "src/Rosetta/model/dae/Write.luau"], -[152395, "src/Rosetta/model/fbx/init.luau"], -[152543, "src/Rosetta/model/fbx/Ascii.luau"], -[152813, "src/Rosetta/model/fbx/Binary.luau"], -[153268, "src/Rosetta/model/fbx/Read.luau"], -[154630, "src/Rosetta/model/fbx/Write.luau"], -[155615, "src/Rosetta/model/fbx/Xform.luau"], -[155656, "src/Rosetta/model/gltf/init.luau"], -[155893, "src/Rosetta/model/gltf/Pack.luau"], -[155962, "src/Rosetta/model/gltf/Read.luau"], -[156693, "src/Rosetta/model/gltf/Write.luau"], -[157373, "src/Rosetta/model/iqm/init.luau"], -[157449, "src/Rosetta/model/iqm/Read.luau"], -[157804, "src/Rosetta/model/iqm/Write.luau"], -[158491, "src/Rosetta/model/ldraw/init.luau"], -[158569, "src/Rosetta/model/ldraw/Colors.luau"], -[158887, "src/Rosetta/model/ldraw/Read.luau"], -[159464, "src/Rosetta/model/lwo/init.luau"], -[159540, "src/Rosetta/model/lwo/Build.luau"], -[160002, "src/Rosetta/model/lwo/Parse.luau"], -[160545, "src/Rosetta/model/map/init.luau"], -[160862, "src/Rosetta/model/map/Build.luau"], -[161105, "src/Rosetta/model/map/Parse.luau"], -[161490, "src/Rosetta/model/map/Write.luau"], -[161636, "src/Rosetta/model/mca/init.luau"], -[161978, "src/Rosetta/model/mca/Chunk.luau"], -[162111, "src/Rosetta/model/mca/Lz4Block.luau"], -[162181, "src/Rosetta/model/md2/init.luau"], -[162380, "src/Rosetta/model/md3/init.luau"], -[162608, "src/Rosetta/model/md5/init.luau"], -[162689, "src/Rosetta/model/md5/Read.luau"], -[163122, "src/Rosetta/model/mdl/init.luau"], -[163204, "src/Rosetta/model/mdl/HalfLife.luau"], -[163508, "src/Rosetta/model/mdl/Quake.luau"], -[163726, "src/Rosetta/model/ms3d/init.luau"], -[163798, "src/Rosetta/model/ms3d/Read.luau"], -[164244, "src/Rosetta/model/ms3d/Write.luau"], -[164713, "src/Rosetta/model/obj/init.luau"], -[165455, "src/Rosetta/model/obj/Mtl.luau"], -[165742, "src/Rosetta/model/off/init.luau"], -[166204, "src/Rosetta/model/ply/init.luau"], -[167309, "src/Rosetta/model/ply/Binary.luau"], -[167510, "src/Rosetta/model/pmx/init.luau"], -[167579, "src/Rosetta/model/pmx/Build.luau"], -[167875, "src/Rosetta/model/pmx/Pmd.luau"], -[168210, "src/Rosetta/model/pmx/Read.luau"], -[168614, "src/Rosetta/model/proc/init.luau"], -[168996, "src/Rosetta/model/qb/init.luau"], -[169389, "src/Rosetta/model/rbxm/init.luau"], -[169981, "src/Rosetta/model/rbxmx/init.luau"], -[170634, "src/Rosetta/model/robloxmesh/init.luau"], -[171293, "src/Rosetta/model/robloxmesh/Parse.luau"], -[171750, "src/Rosetta/model/robloxmesh/Write.luau"], -[171859, "src/Rosetta/model/schematic/init.luau"], -[172180, "src/Rosetta/model/schematic/Common.luau"], -[172300, "src/Rosetta/model/schematic/Litematic.luau"], -[172511, "src/Rosetta/model/schematic/Mcedit.luau"], -[172755, "src/Rosetta/model/schematic/Sponge.luau"], -[172884, "src/Rosetta/model/smd/init.luau"], -[172951, "src/Rosetta/model/smd/Read.luau"], -[173220, "src/Rosetta/model/smd/Write.luau"], -[173463, "src/Rosetta/model/sourcemdl/init.luau"], -[173634, "src/Rosetta/model/sourcemdl/Build.luau"], -[174064, "src/Rosetta/model/sourcemdl/Material.luau"], -[174225, "src/Rosetta/model/sourcemdl/Mdl.luau"], -[174752, "src/Rosetta/model/sourcemdl/Phy.luau"], -[174875, "src/Rosetta/model/sourcemdl/Vtx.luau"], -[175057, "src/Rosetta/model/sourcemdl/Vvd.luau"], -[175151, "src/Rosetta/model/stl/init.luau"], -[175601, "src/Rosetta/model/stl/Decode.luau"], -[175675, "src/Rosetta/model/udmf/init.luau"], -[175758, "src/Rosetta/model/usda/init.luau"], -[175967, "src/Rosetta/model/usda/Build.luau"], -[177245, "src/Rosetta/model/usda/Parse.luau"], -[178043, "src/Rosetta/model/usda/Write.luau"], -[178860, "src/Rosetta/model/vbsp/init.luau"], -[179306, "src/Rosetta/model/vbsp/Faces.luau"], -[179530, "src/Rosetta/model/vbsp/Props.luau"], -[179622, "src/Rosetta/model/vmf/init.luau"], -[179947, "src/Rosetta/model/vmf/Build.luau"], -[180371, "src/Rosetta/model/vox/init.luau"], -[181257, "src/Rosetta/model/vox/Grid.luau"], -[181314, "src/Rosetta/model/vrml/init.luau"], -[181380, "src/Rosetta/model/x/init.luau"], -[181510, "src/Rosetta/model/x/Build.luau"], -[182073, "src/Rosetta/model/x/Parse.luau"], -[182370, "src/Rosetta/model/x3d/init.luau"], -[182448, "src/Rosetta/music/669/init.luau"], -[182654, "src/Rosetta/music/ahx/init.luau"], -[182705, "src/Rosetta/music/far/init.luau"], -[182934, "src/Rosetta/music/hmp/init.luau"], -[183198, "src/Rosetta/music/hvl/init.luau"], -[183249, "src/Rosetta/music/it/init.luau"], -[183667, "src/Rosetta/music/it/Itsex.luau"], -[183783, "src/Rosetta/music/med/init.luau"], -[184430, "src/Rosetta/music/midi/init.luau"], -[184573, "src/Rosetta/music/midi/Smf.luau"], -[184984, "src/Rosetta/music/mod/init.luau"], -[185337, "src/Rosetta/music/mtm/init.luau"], -[185559, "src/Rosetta/music/mus/init.luau"], -[185716, "src/Rosetta/music/okt/init.luau"], -[185997, "src/Rosetta/music/ptm/init.luau"], -[186219, "src/Rosetta/music/s3m/init.luau"], -[186455, "src/Rosetta/music/sf2/init.luau"], -[186498, "src/Rosetta/music/stm/init.luau"], -[186729, "src/Rosetta/music/ult/init.luau"], -[187033, "src/Rosetta/music/umx/init.luau"], -[187249, "src/Rosetta/music/xm/init.luau"], -[187810, "src/Rosetta/music/xmi/init.luau"], -[188018, "src/Rosetta/ops/AudioOps.luau"], -[188467, "src/Rosetta/ops/ImageOps/init.luau"], -[189111, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[189621, "src/Rosetta/ops/LayerOps.luau"], -[189714, "src/Rosetta/ops/MeshOps/init.luau"], -[190750, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[190917, "src/Rosetta/ops/MusicOps.luau"], -[191265, "src/Rosetta/playlist/m3u/init.luau"], -[191618, "src/Rosetta/playlist/pls/init.luau"], -[191796, "src/Rosetta/playlist/xspf/init.luau"], -[191999, "src/Rosetta/subtitle/ass/init.luau"], -[192443, "src/Rosetta/subtitle/srt/init.luau"], -[192616, "src/Rosetta/subtitle/vtt/init.luau"], -[192819, "src/Rosetta/vector/gamemaps/init.luau"], -[193006, "src/Rosetta/vector/gamemaps/Expand.luau"], -[193103, "src/Rosetta/vector/svg/init.luau"], -[193189, "src/Rosetta/vector/svg/Parse.luau"], -[193935, "src/Rosetta/vector/svg/PathData.luau"], -[194303, "src/Rosetta/vector/svg/Render.luau"], -[194720, "src/Rosetta/vector/svg/Style.luau"], -[195092, "src/Rosetta/vector/svg/Write.luau"], -[195292, "src/Rosetta/vector/tiled/init.luau"], -[195472, "src/Rosetta/vector/tiled/Data.luau"], -[195623, "src/Rosetta/vector/tiled/Tmj.luau"], -[196254, "src/Rosetta/vector/tiled/Tmx.luau"], -[196866, "src/Rosetta/video/avi/init.luau"], -[197160, "src/Rosetta/video/fli/init.luau"], -[197311, "src/Rosetta/video/flv/init.luau"], -[197695, "src/Rosetta/video/flv/Amf.luau"], -[197853, "src/Rosetta/video/flv/Mux.luau"], -[198134, "src/Rosetta/video/h264/init.luau"], -[198273, "src/Rosetta/video/mkv/init.luau"], -[198429, "src/Rosetta/video/mkv/Mux.luau"], -[198708, "src/Rosetta/video/mkv/Parse.luau"], -[199429, "src/Rosetta/video/mp4/init.luau"], -[199757, "src/Rosetta/video/mpegps/init.luau"], -[199944, "src/Rosetta/video/mpegts/init.luau"], -[200182, "src/Rosetta/video/ogv/init.luau"], -[200577, "src/Rosetta/video/smk/init.luau"], -[200886, "src/Rosetta/video/smk/Audio.luau"], -[201006, "src/Rosetta/video/y4m/init.luau"] +[3138, "src/Rosetta/Types.luau"], +[4221, "src/Rosetta/archive/7z/init.luau"], +[4606, "src/Rosetta/archive/7z/Header.luau"], +[5133, "src/Rosetta/archive/adf/init.luau"], +[5415, "src/Rosetta/archive/applesingle/init.luau"], +[5601, "src/Rosetta/archive/ar/init.luau"], +[6004, "src/Rosetta/archive/arj/init.luau"], +[6214, "src/Rosetta/archive/binhex/init.luau"], +[6463, "src/Rosetta/archive/br/init.luau"], +[6538, "src/Rosetta/archive/bz2/init.luau"], +[6602, "src/Rosetta/archive/cab/init.luau"], +[7015, "src/Rosetta/archive/cab/Sum.luau"], +[7056, "src/Rosetta/archive/cpio/init.luau"], +[7224, "src/Rosetta/archive/d64/init.luau"], +[7638, "src/Rosetta/archive/fat/init.luau"], +[7760, "src/Rosetta/archive/grp/init.luau"], +[7874, "src/Rosetta/archive/gzip/init.luau"], +[8059, "src/Rosetta/archive/iso/init.luau"], +[8131, "src/Rosetta/archive/lha/init.luau"], +[8556, "src/Rosetta/archive/lz4/init.luau"], +[8900, "src/Rosetta/archive/macbinary/init.luau"], +[9098, "src/Rosetta/archive/mpq/init.luau"], +[9504, "src/Rosetta/archive/mpq/Crypt.luau"], +[9569, "src/Rosetta/archive/pak/init.luau"], +[9703, "src/Rosetta/archive/rpm/init.luau"], +[10027, "src/Rosetta/archive/tar/init.luau"], +[10145, "src/Rosetta/archive/uu/init.luau"], +[10415, "src/Rosetta/archive/vpk/init.luau"], +[10726, "src/Rosetta/archive/vswap/init.luau"], +[10996, "src/Rosetta/archive/wad/init.luau"], +[11450, "src/Rosetta/archive/wad/Picture.luau"], +[11552, "src/Rosetta/archive/xz/init.luau"], +[11652, "src/Rosetta/archive/yenc/init.luau"], +[11924, "src/Rosetta/archive/z/init.luau"], +[12020, "src/Rosetta/archive/zip/init.luau"], +[12239, "src/Rosetta/archive/zoo/init.luau"], +[12435, "src/Rosetta/archive/zst/init.luau"], +[12499, "src/Rosetta/audio/aac/init.luau"], +[12705, "src/Rosetta/audio/ac3/init.luau"], +[12851, "src/Rosetta/audio/adpcm/init.luau"], +[12996, "src/Rosetta/audio/adx/init.luau"], +[13227, "src/Rosetta/audio/aiff/init.luau"], +[13618, "src/Rosetta/audio/ape/init.luau"], +[13746, "src/Rosetta/audio/au/init.luau"], +[13907, "src/Rosetta/audio/brstm/init.luau"], +[14198, "src/Rosetta/audio/caf/init.luau"], +[14860, "src/Rosetta/audio/flac/init.luau"], +[15008, "src/Rosetta/audio/flac/Meta.luau"], +[15230, "src/Rosetta/audio/flac/Stream.luau"], +[15600, "src/Rosetta/audio/m4a/init.luau"], +[15934, "src/Rosetta/audio/mp3/init.luau"], +[16194, "src/Rosetta/audio/mp3/Index.luau"], +[16385, "src/Rosetta/audio/mp3/Stream.luau"], +[16612, "src/Rosetta/audio/mp3/Tags.luau"], +[16924, "src/Rosetta/audio/mpc/init.luau"], +[17018, "src/Rosetta/audio/opus/init.luau"], +[17396, "src/Rosetta/audio/opus/Encode.luau"], +[17507, "src/Rosetta/audio/qoa/init.luau"], +[17687, "src/Rosetta/audio/tta/init.luau"], +[17805, "src/Rosetta/audio/vag/init.luau"], +[18028, "src/Rosetta/audio/voc/init.luau"], +[18303, "src/Rosetta/audio/vorbis/init.luau"], +[18757, "src/Rosetta/audio/vorbis/Encode.luau"], +[19570, "src/Rosetta/audio/wav/init.luau"], +[20191, "src/Rosetta/audio/wav/Codecs.luau"], +[20357, "src/Rosetta/audio/wavpack/init.luau"], +[20564, "src/Rosetta/cad/step/init.luau"], +[20946, "src/Rosetta/cad/step/Brep.luau"], +[21181, "src/Rosetta/cad/step/Parse.luau"], +[21738, "src/Rosetta/cad/step/Write.luau"], +[21986, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22305, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23188, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23523, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[23682, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24567, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[24668, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25422, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[25724, "src/Rosetta/codecs/audio/Alac/init.luau"], +[25958, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26377, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[26789, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27004, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[27765, "src/Rosetta/codecs/audio/ApeTag.luau"], +[27862, "src/Rosetta/codecs/audio/Flac/init.luau"], +[27873, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[28822, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29419, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29615, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[29864, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[30822, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31041, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31225, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31434, "src/Rosetta/codecs/audio/MidiRender.luau"], +[31780, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[31794, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[31853, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33456, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[33748, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34133, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[34774, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[34915, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35141, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35486, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36380, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[36758, "src/Rosetta/codecs/audio/Opus/init.luau"], +[36772, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38619, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[39684, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[39744, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40204, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40541, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[40774, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[42810, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43184, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43447, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[43744, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44026, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44385, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44439, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44582, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45095, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[45876, "src/Rosetta/codecs/audio/Stream.luau"], +[46037, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46519, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[46797, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[46966, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47094, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49082, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49198, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49315, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49567, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49580, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[49964, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50530, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[50951, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[50990, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51042, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51264, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[52719, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[52782, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[52869, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[53838, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[54706, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[54754, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55270, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55596, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56016, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56451, "src/Rosetta/codecs/compress/Explode.luau"], +[56647, "src/Rosetta/codecs/compress/Lz4.luau"], +[56916, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57520, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58060, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58098, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58571, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[58747, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59015, "src/Rosetta/codecs/compress/Lzx.luau"], +[59449, "src/Rosetta/codecs/compress/PackBits.luau"], +[59539, "src/Rosetta/codecs/compress/Quantum.luau"], +[59776, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60080, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60149, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60206, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61164, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61316, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61598, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61609, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[61823, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62067, "src/Rosetta/codecs/font/Bitmap.luau"], +[62268, "src/Rosetta/codecs/font/Cff/init.luau"], +[62909, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63059, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63373, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[63765, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64267, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64374, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[64863, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65292, "src/Rosetta/codecs/image/Blend.luau"], +[65671, "src/Rosetta/codecs/image/Dct/init.luau"], +[66052, "src/Rosetta/codecs/image/Etc.luau"], +[66350, "src/Rosetta/codecs/image/Half.luau"], +[66419, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[66773, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67181, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67418, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68178, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69059, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69505, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69583, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69650, "src/Rosetta/codecs/image/Miptex.luau"], +[69866, "src/Rosetta/codecs/image/Pixels.luau"], +[70186, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70645, "src/Rosetta/codecs/image/Raster.luau"], +[71342, "src/Rosetta/codecs/image/Texel.luau"], +[71715, "src/Rosetta/codecs/image/Texture.luau"], +[71860, "src/Rosetta/codecs/image/Vp8/init.luau"], +[71990, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[73946, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74205, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74454, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74573, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[74677, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75530, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76482, "src/Rosetta/codecs/image/Yuv.luau"], +[76750, "src/Rosetta/codecs/model/Brush.luau"], +[77390, "src/Rosetta/codecs/model/Displacement.luau"], +[77539, "src/Rosetta/codecs/model/DoomMap/init.luau"], +[77984, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], +[78234, "src/Rosetta/codecs/model/Draco/init.luau"], +[78566, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[79035, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[80224, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[80373, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80732, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81694, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[82168, "src/Rosetta/codecs/model/Mat4.luau"], +[82427, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[82955, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[83507, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[83586, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83693, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[83899, "src/Rosetta/codecs/model/Patch.luau"], +[84023, "src/Rosetta/codecs/model/Polygon.luau"], +[84257, "src/Rosetta/codecs/model/Rbx/init.luau"], +[84494, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[85248, "src/Rosetta/codecs/model/Rig.luau"], +[85491, "src/Rosetta/codecs/model/Sampler.luau"], +[85651, "src/Rosetta/codecs/model/SourceAnim.luau"], +[85872, "src/Rosetta/codecs/model/Vrml/init.luau"], +[86020, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[86594, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86757, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[87506, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[88028, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88755, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[88987, "src/Rosetta/codecs/text/Json/init.luau"], +[89256, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89670, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89972, "src/Rosetta/codecs/text/KeyValues/init.luau"], +[90542, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], +[90848, "src/Rosetta/codecs/text/Lexer/init.luau"], +[90980, "src/Rosetta/codecs/text/Nbt/init.luau"], +[91333, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[92025, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[92665, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[92903, "src/Rosetta/codecs/text/Text/init.luau"], +[92994, "src/Rosetta/codecs/text/Url/init.luau"], +[93199, "src/Rosetta/codecs/text/Xml/init.luau"], +[93602, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[94342, "src/Rosetta/codecs/video/Dsp.luau"], +[95065, "src/Rosetta/codecs/video/H263/init.luau"], +[95221, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[96079, "src/Rosetta/codecs/video/H263/Tables.luau"], +[96282, "src/Rosetta/codecs/video/H264/init.luau"], +[96655, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[96930, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[98061, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[98829, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[99087, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[100096, "src/Rosetta/codecs/video/H264/Inter.luau"], +[100350, "src/Rosetta/codecs/video/H264/Intra.luau"], +[100757, "src/Rosetta/codecs/video/H264/Mb.luau"], +[101663, "src/Rosetta/codecs/video/H264/Params.luau"], +[102110, "src/Rosetta/codecs/video/H264/Slice.luau"], +[102361, "src/Rosetta/codecs/video/H264/Tables.luau"], +[102402, "src/Rosetta/codecs/video/H264/Transform.luau"], +[102567, "src/Rosetta/codecs/video/Legacy/init.luau"], +[102765, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[103062, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[103429, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[103547, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[103655, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[103928, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[104323, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[104500, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[104512, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[104879, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[106386, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[106525, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[106663, "src/Rosetta/codecs/video/Theora/init.luau"], +[106926, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[108190, "src/Rosetta/codecs/video/Theora/Header.luau"], +[108553, "src/Rosetta/codecs/video/Video/init.luau"], +[109110, "src/Rosetta/codecs/video/Video/Source.luau"], +[109395, "src/Rosetta/containers/Archive.luau"], +[109662, "src/Rosetta/containers/AudioWrap.luau"], +[110165, "src/Rosetta/containers/Avi/init.luau"], +[110717, "src/Rosetta/containers/Blend.luau"], +[111456, "src/Rosetta/containers/Chunks.luau"], +[111591, "src/Rosetta/containers/Cpio.luau"], +[112019, "src/Rosetta/containers/Demux.luau"], +[112294, "src/Rosetta/containers/Ebml/init.luau"], +[112607, "src/Rosetta/containers/Fat.luau"], +[113295, "src/Rosetta/containers/Iso9660.luau"], +[113800, "src/Rosetta/containers/IsoBmff/init.luau"], +[113970, "src/Rosetta/containers/IsoBmff/Box.luau"], +[114158, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[115003, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[115524, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[116040, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[116157, "src/Rosetta/containers/MacFile.luau"], +[116306, "src/Rosetta/containers/MpegEs.luau"], +[116472, "src/Rosetta/containers/MpegPs/init.luau"], +[116692, "src/Rosetta/containers/MpegTs/init.luau"], +[117484, "src/Rosetta/containers/Ogg/init.luau"], +[117909, "src/Rosetta/containers/Ogg/Mux.luau"], +[118104, "src/Rosetta/containers/Ogg/Page.luau"], +[118273, "src/Rosetta/containers/Riff/init.luau"], +[118590, "src/Rosetta/containers/Tar.luau"], +[119004, "src/Rosetta/containers/Zip/init.luau"], +[119636, "src/Rosetta/core/Adler32.luau"], +[119682, "src/Rosetta/core/Base64.luau"], +[119841, "src/Rosetta/core/Bits.luau"], +[120134, "src/Rosetta/core/Bytes.luau"], +[120661, "src/Rosetta/core/Crc16.luau"], +[120713, "src/Rosetta/core/Crc32.luau"], +[120825, "src/Rosetta/core/Err.luau"], +[120907, "src/Rosetta/core/Input.luau"], +[120983, "src/Rosetta/core/Md5.luau"], +[121142, "src/Rosetta/core/Sniff.luau"], +[121171, "src/Rosetta/data/cbor/init.luau"], +[121270, "src/Rosetta/data/cbor/Codec.luau"], +[121839, "src/Rosetta/data/csv/init.luau"], +[122151, "src/Rosetta/data/ini/init.luau"], +[122397, "src/Rosetta/data/json/init.luau"], +[122489, "src/Rosetta/data/msgpack/init.luau"], +[122578, "src/Rosetta/data/msgpack/Codec.luau"], +[123020, "src/Rosetta/data/nbt/init.luau"], +[123079, "src/Rosetta/data/plist/init.luau"], +[123385, "src/Rosetta/data/plist/Binary.luau"], +[123652, "src/Rosetta/data/snbt/init.luau"], +[123715, "src/Rosetta/data/toml/init.luau"], +[123782, "src/Rosetta/data/toml/Decode.luau"], +[124410, "src/Rosetta/data/toml/Encode.luau"], +[124619, "src/Rosetta/data/vdf/init.luau"], +[124720, "src/Rosetta/data/xml/init.luau"], +[124776, "src/Rosetta/data/yaml/init.luau"], +[124849, "src/Rosetta/data/yaml/Emit.luau"], +[125139, "src/Rosetta/data/yaml/Parse.luau"], +[126432, "src/Rosetta/font/bdf/init.luau"], +[126721, "src/Rosetta/font/bmfont/init.luau"], +[127148, "src/Rosetta/font/bmfont/Parse.luau"], +[127601, "src/Rosetta/font/eot/init.luau"], +[127833, "src/Rosetta/font/fon/init.luau"], +[128116, "src/Rosetta/font/hershey/init.luau"], +[128311, "src/Rosetta/font/pcf/init.luau"], +[128591, "src/Rosetta/font/psf/init.luau"], +[128911, "src/Rosetta/font/ttf/init.luau"], +[128962, "src/Rosetta/font/type1/init.luau"], +[129321, "src/Rosetta/font/type1/Charstring.luau"], +[129599, "src/Rosetta/font/woff/init.luau"], +[129731, "src/Rosetta/font/woff2/init.luau"], +[129788, "src/Rosetta/font/woff2/Rebuild.luau"], +[130328, "src/Rosetta/host/init.luau"], +[130373, "src/Rosetta/host/Love.luau"], +[130516, "src/Rosetta/host/LuaJIT.luau"], +[130566, "src/Rosetta/host/Luau.luau"], +[130589, "src/Rosetta/host/Roblox.luau"], +[130948, "src/Rosetta/image/ani/init.luau"], +[131128, "src/Rosetta/image/art/init.luau"], +[131616, "src/Rosetta/image/blp/init.luau"], +[131874, "src/Rosetta/image/bmp/init.luau"], +[132289, "src/Rosetta/image/dds/init.luau"], +[132772, "src/Rosetta/image/exr/init.luau"], +[133532, "src/Rosetta/image/exr/Codec.luau"], +[133643, "src/Rosetta/image/exr/Piz.luau"], +[134000, "src/Rosetta/image/gif/init.luau"], +[134516, "src/Rosetta/image/gif/Decode.luau"], +[134579, "src/Rosetta/image/hdr/init.luau"], +[134808, "src/Rosetta/image/hdr/Codec.luau"], +[135019, "src/Rosetta/image/icns/init.luau"], +[135350, "src/Rosetta/image/ico/init.luau"], +[135627, "src/Rosetta/image/ico/Dib.luau"], +[135722, "src/Rosetta/image/ilbm/init.luau"], +[136041, "src/Rosetta/image/jpeg/init.luau"], +[136177, "src/Rosetta/image/ktx/init.luau"], +[136837, "src/Rosetta/image/pcx/init.luau"], +[137101, "src/Rosetta/image/png/init.luau"], +[137681, "src/Rosetta/image/png/Apng.luau"], +[137761, "src/Rosetta/image/png/Decode.luau"], +[138001, "src/Rosetta/image/png/Encode.luau"], +[138156, "src/Rosetta/image/pnm/init.luau"], +[138534, "src/Rosetta/image/pnm/Codec.luau"], +[138811, "src/Rosetta/image/qoi/init.luau"], +[138933, "src/Rosetta/image/qoi/Codec.luau"], +[139083, "src/Rosetta/image/sgi/init.luau"], +[139368, "src/Rosetta/image/sunras/init.luau"], +[139614, "src/Rosetta/image/tga/init.luau"], +[139884, "src/Rosetta/image/tga/Codec.luau"], +[140036, "src/Rosetta/image/tiff/init.luau"], +[140863, "src/Rosetta/image/tiff/Pixels.luau"], +[141253, "src/Rosetta/image/tim/init.luau"], +[141495, "src/Rosetta/image/vtf/init.luau"], +[141730, "src/Rosetta/image/webp/init.luau"], +[142340, "src/Rosetta/image/webp/Alpha.luau"], +[142416, "src/Rosetta/image/webp/Anim.luau"], +[142571, "src/Rosetta/image/xbm/init.luau"], +[142732, "src/Rosetta/image/xpm/init.luau"], +[143000, "src/Rosetta/image/xpm/Names.luau"], +[143056, "src/Rosetta/layered/aseprite/init.luau"], +[143794, "src/Rosetta/layered/ora/init.luau"], +[144081, "src/Rosetta/layered/psd/init.luau"], +[144816, "src/Rosetta/layered/psd/Channels.luau"], +[145168, "src/Rosetta/model/3ds/init.luau"], +[145251, "src/Rosetta/model/3ds/Build.luau"], +[145898, "src/Rosetta/model/3ds/Read.luau"], +[146394, "src/Rosetta/model/3ds/Write.luau"], +[147199, "src/Rosetta/model/3mf/init.luau"], +[147281, "src/Rosetta/model/3mf/Read.luau"], +[147869, "src/Rosetta/model/3mf/Write.luau"], +[148274, "src/Rosetta/model/b3d/init.luau"], +[148329, "src/Rosetta/model/b3d/Read.luau"], +[148900, "src/Rosetta/model/blend/init.luau"], +[148996, "src/Rosetta/model/blend/Anim.luau"], +[149342, "src/Rosetta/model/blend/Material.luau"], +[149694, "src/Rosetta/model/blend/Mesh.luau"], +[150329, "src/Rosetta/model/blend/Normals.luau"], +[150490, "src/Rosetta/model/blend/Prim.luau"], +[150939, "src/Rosetta/model/blend/Read.luau"], +[151839, "src/Rosetta/model/bsp/init.luau"], +[151984, "src/Rosetta/model/bsp/Brush.luau"], +[152247, "src/Rosetta/model/bsp/Quake3.luau"], +[152475, "src/Rosetta/model/buildmap/init.luau"], +[152747, "src/Rosetta/model/buildmap/Geometry.luau"], +[153150, "src/Rosetta/model/d3map/init.luau"], +[153432, "src/Rosetta/model/d3map/Parse.luau"], +[153630, "src/Rosetta/model/dae/init.luau"], +[153819, "src/Rosetta/model/dae/Math.luau"], +[153866, "src/Rosetta/model/dae/Read.luau"], +[155716, "src/Rosetta/model/dae/Write.luau"], +[156085, "src/Rosetta/model/fbx/init.luau"], +[156233, "src/Rosetta/model/fbx/Ascii.luau"], +[156503, "src/Rosetta/model/fbx/Binary.luau"], +[156958, "src/Rosetta/model/fbx/Read.luau"], +[158320, "src/Rosetta/model/fbx/Write.luau"], +[159305, "src/Rosetta/model/fbx/Xform.luau"], +[159346, "src/Rosetta/model/gltf/init.luau"], +[159583, "src/Rosetta/model/gltf/Pack.luau"], +[159652, "src/Rosetta/model/gltf/Read.luau"], +[160383, "src/Rosetta/model/gltf/Write.luau"], +[161063, "src/Rosetta/model/iqm/init.luau"], +[161139, "src/Rosetta/model/iqm/Read.luau"], +[161494, "src/Rosetta/model/iqm/Write.luau"], +[162181, "src/Rosetta/model/ldraw/init.luau"], +[162259, "src/Rosetta/model/ldraw/Colors.luau"], +[162577, "src/Rosetta/model/ldraw/Read.luau"], +[163154, "src/Rosetta/model/lwo/init.luau"], +[163230, "src/Rosetta/model/lwo/Build.luau"], +[163692, "src/Rosetta/model/lwo/Parse.luau"], +[164235, "src/Rosetta/model/map/init.luau"], +[164552, "src/Rosetta/model/map/Build.luau"], +[164795, "src/Rosetta/model/map/Parse.luau"], +[165180, "src/Rosetta/model/map/Write.luau"], +[165326, "src/Rosetta/model/mca/init.luau"], +[165668, "src/Rosetta/model/mca/Chunk.luau"], +[165801, "src/Rosetta/model/mca/Lz4Block.luau"], +[165871, "src/Rosetta/model/md2/init.luau"], +[166070, "src/Rosetta/model/md3/init.luau"], +[166298, "src/Rosetta/model/md5/init.luau"], +[166379, "src/Rosetta/model/md5/Read.luau"], +[166812, "src/Rosetta/model/mdl/init.luau"], +[166894, "src/Rosetta/model/mdl/HalfLife.luau"], +[167198, "src/Rosetta/model/mdl/Quake.luau"], +[167416, "src/Rosetta/model/ms3d/init.luau"], +[167488, "src/Rosetta/model/ms3d/Read.luau"], +[167934, "src/Rosetta/model/ms3d/Write.luau"], +[168403, "src/Rosetta/model/obj/init.luau"], +[169145, "src/Rosetta/model/obj/Mtl.luau"], +[169432, "src/Rosetta/model/off/init.luau"], +[169894, "src/Rosetta/model/ply/init.luau"], +[170999, "src/Rosetta/model/ply/Binary.luau"], +[171200, "src/Rosetta/model/pmx/init.luau"], +[171269, "src/Rosetta/model/pmx/Build.luau"], +[171565, "src/Rosetta/model/pmx/Pmd.luau"], +[171900, "src/Rosetta/model/pmx/Read.luau"], +[172304, "src/Rosetta/model/proc/init.luau"], +[172686, "src/Rosetta/model/qb/init.luau"], +[173079, "src/Rosetta/model/rbxm/init.luau"], +[173671, "src/Rosetta/model/rbxmx/init.luau"], +[174324, "src/Rosetta/model/robloxmesh/init.luau"], +[174983, "src/Rosetta/model/robloxmesh/Parse.luau"], +[175440, "src/Rosetta/model/robloxmesh/Write.luau"], +[175549, "src/Rosetta/model/schematic/init.luau"], +[175870, "src/Rosetta/model/schematic/Common.luau"], +[175990, "src/Rosetta/model/schematic/Litematic.luau"], +[176201, "src/Rosetta/model/schematic/Mcedit.luau"], +[176445, "src/Rosetta/model/schematic/Sponge.luau"], +[176574, "src/Rosetta/model/smd/init.luau"], +[176641, "src/Rosetta/model/smd/Read.luau"], +[176910, "src/Rosetta/model/smd/Write.luau"], +[177153, "src/Rosetta/model/sourcemdl/init.luau"], +[177324, "src/Rosetta/model/sourcemdl/Build.luau"], +[177754, "src/Rosetta/model/sourcemdl/Material.luau"], +[177915, "src/Rosetta/model/sourcemdl/Mdl.luau"], +[178442, "src/Rosetta/model/sourcemdl/Phy.luau"], +[178565, "src/Rosetta/model/sourcemdl/Vtx.luau"], +[178747, "src/Rosetta/model/sourcemdl/Vvd.luau"], +[178841, "src/Rosetta/model/stl/init.luau"], +[179291, "src/Rosetta/model/stl/Decode.luau"], +[179365, "src/Rosetta/model/udmf/init.luau"], +[179448, "src/Rosetta/model/usda/init.luau"], +[179657, "src/Rosetta/model/usda/Build.luau"], +[180935, "src/Rosetta/model/usda/Parse.luau"], +[181733, "src/Rosetta/model/usda/Write.luau"], +[182550, "src/Rosetta/model/vbsp/init.luau"], +[182996, "src/Rosetta/model/vbsp/Faces.luau"], +[183220, "src/Rosetta/model/vbsp/Props.luau"], +[183312, "src/Rosetta/model/vmf/init.luau"], +[183637, "src/Rosetta/model/vmf/Build.luau"], +[184061, "src/Rosetta/model/vox/init.luau"], +[184947, "src/Rosetta/model/vox/Grid.luau"], +[185004, "src/Rosetta/model/vrml/init.luau"], +[185070, "src/Rosetta/model/x/init.luau"], +[185200, "src/Rosetta/model/x/Build.luau"], +[185763, "src/Rosetta/model/x/Parse.luau"], +[186060, "src/Rosetta/model/x3d/init.luau"], +[186138, "src/Rosetta/music/669/init.luau"], +[186344, "src/Rosetta/music/ahx/init.luau"], +[186395, "src/Rosetta/music/far/init.luau"], +[186624, "src/Rosetta/music/hmp/init.luau"], +[186888, "src/Rosetta/music/hvl/init.luau"], +[186939, "src/Rosetta/music/it/init.luau"], +[187357, "src/Rosetta/music/it/Itsex.luau"], +[187473, "src/Rosetta/music/med/init.luau"], +[188120, "src/Rosetta/music/midi/init.luau"], +[188263, "src/Rosetta/music/midi/Smf.luau"], +[188674, "src/Rosetta/music/mod/init.luau"], +[189027, "src/Rosetta/music/mtm/init.luau"], +[189249, "src/Rosetta/music/mus/init.luau"], +[189406, "src/Rosetta/music/okt/init.luau"], +[189687, "src/Rosetta/music/ptm/init.luau"], +[189909, "src/Rosetta/music/s3m/init.luau"], +[190145, "src/Rosetta/music/sf2/init.luau"], +[190188, "src/Rosetta/music/stm/init.luau"], +[190419, "src/Rosetta/music/ult/init.luau"], +[190723, "src/Rosetta/music/umx/init.luau"], +[190939, "src/Rosetta/music/xm/init.luau"], +[191500, "src/Rosetta/music/xmi/init.luau"], +[191708, "src/Rosetta/ops/AudioOps.luau"], +[192157, "src/Rosetta/ops/ImageOps/init.luau"], +[192801, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[193311, "src/Rosetta/ops/LayerOps.luau"], +[193404, "src/Rosetta/ops/MeshOps/init.luau"], +[194440, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[194607, "src/Rosetta/ops/MusicOps.luau"], +[194955, "src/Rosetta/playlist/m3u/init.luau"], +[195308, "src/Rosetta/playlist/pls/init.luau"], +[195486, "src/Rosetta/playlist/xspf/init.luau"], +[195689, "src/Rosetta/subtitle/ass/init.luau"], +[196133, "src/Rosetta/subtitle/srt/init.luau"], +[196306, "src/Rosetta/subtitle/vtt/init.luau"], +[196509, "src/Rosetta/vector/gamemaps/init.luau"], +[196696, "src/Rosetta/vector/gamemaps/Expand.luau"], +[196793, "src/Rosetta/vector/svg/init.luau"], +[196879, "src/Rosetta/vector/svg/Parse.luau"], +[197625, "src/Rosetta/vector/svg/PathData.luau"], +[197993, "src/Rosetta/vector/svg/Render.luau"], +[198410, "src/Rosetta/vector/svg/Style.luau"], +[198782, "src/Rosetta/vector/svg/Write.luau"], +[198982, "src/Rosetta/vector/tiled/init.luau"], +[199162, "src/Rosetta/vector/tiled/Data.luau"], +[199313, "src/Rosetta/vector/tiled/Tmj.luau"], +[199944, "src/Rosetta/vector/tiled/Tmx.luau"], +[200556, "src/Rosetta/video/avi/init.luau"], +[200850, "src/Rosetta/video/fli/init.luau"], +[201001, "src/Rosetta/video/flv/init.luau"], +[201385, "src/Rosetta/video/flv/Amf.luau"], +[201543, "src/Rosetta/video/flv/Mux.luau"], +[201824, "src/Rosetta/video/h264/init.luau"], +[201963, "src/Rosetta/video/mkv/init.luau"], +[202119, "src/Rosetta/video/mkv/Mux.luau"], +[202398, "src/Rosetta/video/mkv/Parse.luau"], +[203119, "src/Rosetta/video/mp4/init.luau"], +[203447, "src/Rosetta/video/mpegps/init.luau"], +[203634, "src/Rosetta/video/mpegts/init.luau"], +[203872, "src/Rosetta/video/ogv/init.luau"], +[204267, "src/Rosetta/video/smk/init.luau"], +[204576, "src/Rosetta/video/smk/Audio.luau"], +[204696, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/Rosetta.rbxm b/build/Rosetta.rbxm index c24dcd4..0a1a661 100644 Binary files a/build/Rosetta.rbxm and b/build/Rosetta.rbxm differ diff --git a/build/Rosetta.rbxm.linemap.json b/build/Rosetta.rbxm.linemap.json index 863a7e5..9720666 100644 --- a/build/Rosetta.rbxm.linemap.json +++ b/build/Rosetta.rbxm.linemap.json @@ -1,5 +1,5 @@ { -"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3105, "src/Rosetta/Types.luau"], [4188, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4942, "src/Rosetta/codecs/image/Yuv.luau"], [5210, "src/Rosetta/codecs/model/Rbx/init.luau"], [5447, "src/Rosetta/codecs/video/Video/init.luau"], [6004, "src/Rosetta/containers/AudioWrap.luau"], [6507, "src/Rosetta/containers/Ogg/Mux.luau"], [6702, "src/Rosetta/containers/Ogg/Page.luau"], [6871, "src/Rosetta/core/Bytes.luau"], [7398, "src/Rosetta/core/Crc32.luau"], [7510, "src/Rosetta/core/Err.luau"], [7592, "src/Rosetta/core/Input.luau"], [7668, "src/Rosetta/host/init.luau"]], +"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3117, "src/Rosetta/Types.luau"], [4200, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4954, "src/Rosetta/codecs/image/Yuv.luau"], [5222, "src/Rosetta/codecs/model/Rbx/init.luau"], [5459, "src/Rosetta/codecs/video/Video/init.luau"], [6016, "src/Rosetta/containers/AudioWrap.luau"], [6519, "src/Rosetta/containers/Ogg/Mux.luau"], [6714, "src/Rosetta/containers/Ogg/Page.luau"], [6883, "src/Rosetta/core/Bytes.luau"], [7410, "src/Rosetta/core/Crc32.luau"], [7522, "src/Rosetta/core/Err.luau"], [7604, "src/Rosetta/core/Input.luau"], [7680, "src/Rosetta/host/init.luau"]], "Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]], "Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]], "H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]], @@ -39,7 +39,7 @@ "codecs_model": [[8, "src/Rosetta/codecs/model/Brush.luau"], [648, "src/Rosetta/codecs/model/Displacement.luau"], [797, "src/Rosetta/codecs/model/DoomMap/init.luau"], [1242, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], [1492, "src/Rosetta/codecs/model/Mat4.luau"], [1751, "src/Rosetta/codecs/model/MeshFlatten.luau"], [2279, "src/Rosetta/codecs/model/Minecraft/init.luau"], [2831, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [2910, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [3017, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [3223, "src/Rosetta/codecs/model/Patch.luau"], [3347, "src/Rosetta/codecs/model/Polygon.luau"], [3581, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [4335, "src/Rosetta/codecs/model/Rig.luau"], [4578, "src/Rosetta/codecs/model/Sampler.luau"], [4738, "src/Rosetta/codecs/model/SourceAnim.luau"], [4959, "src/Rosetta/codecs/model/Vrml/init.luau"], [5107, "src/Rosetta/codecs/model/Vrml/Build.luau"], [5681, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [5844, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [6593, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [7115, "src/Rosetta/codecs/model/Vrml/Write.luau"], [7842, "src/Rosetta/codecs/model/Vrml/Xml.luau"]], "codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/KeyValues/init.luau"], [1563, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1869, "src/Rosetta/codecs/text/Lexer/init.luau"], [2001, "src/Rosetta/codecs/text/Nbt/init.luau"], [2354, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [3046, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3686, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3924, "src/Rosetta/codecs/text/Text/init.luau"], [4015, "src/Rosetta/codecs/text/Url/init.luau"], [4220, "src/Rosetta/codecs/text/Xml/init.luau"], [4623, "src/Rosetta/codecs/text/Xml/Parse.luau"]], "codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]], -"containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Chunks.luau"], [962, "src/Rosetta/containers/Cpio.luau"], [1390, "src/Rosetta/containers/Demux.luau"], [1665, "src/Rosetta/containers/Ebml/init.luau"], [1978, "src/Rosetta/containers/Fat.luau"], [2666, "src/Rosetta/containers/Iso9660.luau"], [3171, "src/Rosetta/containers/IsoBmff/init.luau"], [3341, "src/Rosetta/containers/IsoBmff/Box.luau"], [3529, "src/Rosetta/containers/IsoBmff/Demux.luau"], [4374, "src/Rosetta/containers/IsoBmff/Meta.luau"], [4895, "src/Rosetta/containers/IsoBmff/Mux.luau"], [5411, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [5528, "src/Rosetta/containers/MacFile.luau"], [5677, "src/Rosetta/containers/Ogg/init.luau"], [6102, "src/Rosetta/containers/Riff/init.luau"], [6419, "src/Rosetta/containers/Tar.luau"], [6833, "src/Rosetta/containers/Zip/init.luau"]], +"containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Blend.luau"], [1566, "src/Rosetta/containers/Chunks.luau"], [1701, "src/Rosetta/containers/Cpio.luau"], [2129, "src/Rosetta/containers/Demux.luau"], [2404, "src/Rosetta/containers/Ebml/init.luau"], [2717, "src/Rosetta/containers/Fat.luau"], [3405, "src/Rosetta/containers/Iso9660.luau"], [3910, "src/Rosetta/containers/IsoBmff/init.luau"], [4080, "src/Rosetta/containers/IsoBmff/Box.luau"], [4268, "src/Rosetta/containers/IsoBmff/Demux.luau"], [5113, "src/Rosetta/containers/IsoBmff/Meta.luau"], [5634, "src/Rosetta/containers/IsoBmff/Mux.luau"], [6150, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [6267, "src/Rosetta/containers/MacFile.luau"], [6416, "src/Rosetta/containers/Ogg/init.luau"], [6841, "src/Rosetta/containers/Riff/init.luau"], [7158, "src/Rosetta/containers/Tar.luau"], [7572, "src/Rosetta/containers/Zip/init.luau"]], "core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]], "data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/snbt/init.luau"], [2552, "src/Rosetta/data/toml/init.luau"], [2619, "src/Rosetta/data/toml/Decode.luau"], [3247, "src/Rosetta/data/toml/Encode.luau"], [3456, "src/Rosetta/data/vdf/init.luau"], [3557, "src/Rosetta/data/xml/init.luau"], [3613, "src/Rosetta/data/yaml/init.luau"], [3686, "src/Rosetta/data/yaml/Emit.luau"], [3976, "src/Rosetta/data/yaml/Parse.luau"]], "font": [[8, "src/Rosetta/font/bdf/init.luau"], [297, "src/Rosetta/font/bmfont/init.luau"], [724, "src/Rosetta/font/bmfont/Parse.luau"], [1177, "src/Rosetta/font/eot/init.luau"], [1409, "src/Rosetta/font/fon/init.luau"], [1692, "src/Rosetta/font/hershey/init.luau"], [1887, "src/Rosetta/font/pcf/init.luau"], [2167, "src/Rosetta/font/psf/init.luau"], [2487, "src/Rosetta/font/ttf/init.luau"], [2538, "src/Rosetta/font/type1/init.luau"], [2897, "src/Rosetta/font/type1/Charstring.luau"], [3175, "src/Rosetta/font/woff/init.luau"], [3307, "src/Rosetta/font/woff2/init.luau"], [3364, "src/Rosetta/font/woff2/Rebuild.luau"]], @@ -47,11 +47,12 @@ "image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/pcx/init.luau"], [6161, "src/Rosetta/image/pnm/init.luau"], [6539, "src/Rosetta/image/pnm/Codec.luau"], [6816, "src/Rosetta/image/qoi/init.luau"], [6938, "src/Rosetta/image/qoi/Codec.luau"], [7088, "src/Rosetta/image/sgi/init.luau"], [7373, "src/Rosetta/image/sunras/init.luau"], [7619, "src/Rosetta/image/tga/init.luau"]], "image_2": [[8, "src/Rosetta/image/tga/Codec.luau"], [160, "src/Rosetta/image/tiff/init.luau"], [987, "src/Rosetta/image/tiff/Pixels.luau"], [1377, "src/Rosetta/image/tim/init.luau"], [1619, "src/Rosetta/image/vtf/init.luau"], [1854, "src/Rosetta/image/webp/init.luau"], [2464, "src/Rosetta/image/webp/Alpha.luau"], [2540, "src/Rosetta/image/webp/Anim.luau"], [2695, "src/Rosetta/image/xbm/init.luau"], [2856, "src/Rosetta/image/xpm/init.luau"], [3124, "src/Rosetta/image/xpm/Names.luau"]], "layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]], -"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4148, "src/Rosetta/model/bsp/Quake3.luau"], [4376, "src/Rosetta/model/buildmap/init.luau"], [4648, "src/Rosetta/model/buildmap/Geometry.luau"], [5051, "src/Rosetta/model/d3map/init.luau"], [5333, "src/Rosetta/model/d3map/Parse.luau"], [5531, "src/Rosetta/model/dae/init.luau"], [5720, "src/Rosetta/model/dae/Math.luau"], [5767, "src/Rosetta/model/dae/Read.luau"]], -"model_2": [[8, "src/Rosetta/model/dae/Write.luau"], [377, "src/Rosetta/model/fbx/init.luau"], [525, "src/Rosetta/model/fbx/Ascii.luau"], [795, "src/Rosetta/model/fbx/Binary.luau"], [1250, "src/Rosetta/model/fbx/Read.luau"], [2612, "src/Rosetta/model/fbx/Write.luau"], [3597, "src/Rosetta/model/fbx/Xform.luau"], [3638, "src/Rosetta/model/gltf/init.luau"], [3875, "src/Rosetta/model/gltf/Pack.luau"], [3944, "src/Rosetta/model/gltf/Read.luau"], [4675, "src/Rosetta/model/gltf/Write.luau"], [5355, "src/Rosetta/model/iqm/init.luau"], [5431, "src/Rosetta/model/iqm/Read.luau"], [5786, "src/Rosetta/model/iqm/Write.luau"], [6473, "src/Rosetta/model/ldraw/init.luau"], [6551, "src/Rosetta/model/ldraw/Colors.luau"], [6869, "src/Rosetta/model/ldraw/Read.luau"]], -"model_3": [[8, "src/Rosetta/model/lwo/init.luau"], [84, "src/Rosetta/model/lwo/Build.luau"], [546, "src/Rosetta/model/lwo/Parse.luau"], [1089, "src/Rosetta/model/map/init.luau"], [1406, "src/Rosetta/model/map/Build.luau"], [1649, "src/Rosetta/model/map/Parse.luau"], [2034, "src/Rosetta/model/map/Write.luau"], [2180, "src/Rosetta/model/mca/init.luau"], [2522, "src/Rosetta/model/mca/Chunk.luau"], [2655, "src/Rosetta/model/mca/Lz4Block.luau"], [2725, "src/Rosetta/model/md2/init.luau"], [2924, "src/Rosetta/model/md3/init.luau"], [3152, "src/Rosetta/model/md5/init.luau"], [3233, "src/Rosetta/model/md5/Read.luau"], [3666, "src/Rosetta/model/mdl/init.luau"], [3748, "src/Rosetta/model/mdl/HalfLife.luau"], [4052, "src/Rosetta/model/mdl/Quake.luau"], [4270, "src/Rosetta/model/ms3d/init.luau"], [4342, "src/Rosetta/model/ms3d/Read.luau"], [4788, "src/Rosetta/model/ms3d/Write.luau"], [5257, "src/Rosetta/model/obj/init.luau"], [5999, "src/Rosetta/model/obj/Mtl.luau"], [6286, "src/Rosetta/model/off/init.luau"], [6748, "src/Rosetta/model/ply/init.luau"]], -"model_4": [[8, "src/Rosetta/model/ply/Binary.luau"], [209, "src/Rosetta/model/pmx/init.luau"], [278, "src/Rosetta/model/pmx/Build.luau"], [574, "src/Rosetta/model/pmx/Pmd.luau"], [909, "src/Rosetta/model/pmx/Read.luau"], [1313, "src/Rosetta/model/proc/init.luau"], [1695, "src/Rosetta/model/qb/init.luau"], [2088, "src/Rosetta/model/rbxm/init.luau"], [2680, "src/Rosetta/model/rbxmx/init.luau"], [3333, "src/Rosetta/model/robloxmesh/init.luau"], [3992, "src/Rosetta/model/robloxmesh/Parse.luau"], [4449, "src/Rosetta/model/robloxmesh/Write.luau"], [4558, "src/Rosetta/model/schematic/init.luau"], [4879, "src/Rosetta/model/schematic/Common.luau"], [4999, "src/Rosetta/model/schematic/Litematic.luau"], [5210, "src/Rosetta/model/schematic/Mcedit.luau"], [5454, "src/Rosetta/model/schematic/Sponge.luau"], [5583, "src/Rosetta/model/smd/init.luau"], [5650, "src/Rosetta/model/smd/Read.luau"], [5919, "src/Rosetta/model/smd/Write.luau"], [6162, "src/Rosetta/model/sourcemdl/init.luau"], [6333, "src/Rosetta/model/sourcemdl/Build.luau"], [6763, "src/Rosetta/model/sourcemdl/Material.luau"], [6924, "src/Rosetta/model/sourcemdl/Mdl.luau"], [7451, "src/Rosetta/model/sourcemdl/Phy.luau"], [7574, "src/Rosetta/model/sourcemdl/Vtx.luau"], [7756, "src/Rosetta/model/sourcemdl/Vvd.luau"]], -"model_5": [[8, "src/Rosetta/model/stl/init.luau"], [458, "src/Rosetta/model/stl/Decode.luau"], [532, "src/Rosetta/model/udmf/init.luau"], [615, "src/Rosetta/model/usda/init.luau"], [824, "src/Rosetta/model/usda/Build.luau"], [2102, "src/Rosetta/model/usda/Parse.luau"], [2900, "src/Rosetta/model/usda/Write.luau"], [3717, "src/Rosetta/model/vbsp/init.luau"], [4163, "src/Rosetta/model/vbsp/Faces.luau"], [4387, "src/Rosetta/model/vbsp/Props.luau"], [4479, "src/Rosetta/model/vmf/init.luau"], [4804, "src/Rosetta/model/vmf/Build.luau"], [5228, "src/Rosetta/model/vox/init.luau"], [6114, "src/Rosetta/model/vox/Grid.luau"], [6171, "src/Rosetta/model/vrml/init.luau"], [6237, "src/Rosetta/model/x/init.luau"], [6367, "src/Rosetta/model/x/Build.luau"], [6930, "src/Rosetta/model/x/Parse.luau"], [7227, "src/Rosetta/model/x3d/init.luau"]], +"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/blend/init.luau"], [3836, "src/Rosetta/model/blend/Anim.luau"], [4182, "src/Rosetta/model/blend/Material.luau"], [4534, "src/Rosetta/model/blend/Mesh.luau"], [5169, "src/Rosetta/model/blend/Normals.luau"], [5330, "src/Rosetta/model/blend/Prim.luau"], [5779, "src/Rosetta/model/blend/Read.luau"], [6679, "src/Rosetta/model/bsp/init.luau"], [6824, "src/Rosetta/model/bsp/Brush.luau"], [7087, "src/Rosetta/model/bsp/Quake3.luau"]], +"model_2": [[8, "src/Rosetta/model/buildmap/init.luau"], [280, "src/Rosetta/model/buildmap/Geometry.luau"], [683, "src/Rosetta/model/d3map/init.luau"], [965, "src/Rosetta/model/d3map/Parse.luau"], [1163, "src/Rosetta/model/dae/init.luau"], [1352, "src/Rosetta/model/dae/Math.luau"], [1399, "src/Rosetta/model/dae/Read.luau"], [3249, "src/Rosetta/model/dae/Write.luau"], [3618, "src/Rosetta/model/fbx/init.luau"], [3766, "src/Rosetta/model/fbx/Ascii.luau"], [4036, "src/Rosetta/model/fbx/Binary.luau"], [4491, "src/Rosetta/model/fbx/Read.luau"], [5853, "src/Rosetta/model/fbx/Write.luau"], [6838, "src/Rosetta/model/fbx/Xform.luau"], [6879, "src/Rosetta/model/gltf/init.luau"], [7116, "src/Rosetta/model/gltf/Pack.luau"]], +"model_3": [[8, "src/Rosetta/model/gltf/Read.luau"], [739, "src/Rosetta/model/gltf/Write.luau"], [1419, "src/Rosetta/model/iqm/init.luau"], [1495, "src/Rosetta/model/iqm/Read.luau"], [1850, "src/Rosetta/model/iqm/Write.luau"], [2537, "src/Rosetta/model/ldraw/init.luau"], [2615, "src/Rosetta/model/ldraw/Colors.luau"], [2933, "src/Rosetta/model/ldraw/Read.luau"], [3510, "src/Rosetta/model/lwo/init.luau"], [3586, "src/Rosetta/model/lwo/Build.luau"], [4048, "src/Rosetta/model/lwo/Parse.luau"], [4591, "src/Rosetta/model/map/init.luau"], [4908, "src/Rosetta/model/map/Build.luau"], [5151, "src/Rosetta/model/map/Parse.luau"], [5536, "src/Rosetta/model/map/Write.luau"], [5682, "src/Rosetta/model/mca/init.luau"], [6024, "src/Rosetta/model/mca/Chunk.luau"], [6157, "src/Rosetta/model/mca/Lz4Block.luau"], [6227, "src/Rosetta/model/md2/init.luau"], [6426, "src/Rosetta/model/md3/init.luau"], [6654, "src/Rosetta/model/md5/init.luau"], [6735, "src/Rosetta/model/md5/Read.luau"], [7168, "src/Rosetta/model/mdl/init.luau"], [7250, "src/Rosetta/model/mdl/HalfLife.luau"]], +"model_4": [[8, "src/Rosetta/model/mdl/Quake.luau"], [226, "src/Rosetta/model/ms3d/init.luau"], [298, "src/Rosetta/model/ms3d/Read.luau"], [744, "src/Rosetta/model/ms3d/Write.luau"], [1213, "src/Rosetta/model/obj/init.luau"], [1955, "src/Rosetta/model/obj/Mtl.luau"], [2242, "src/Rosetta/model/off/init.luau"], [2704, "src/Rosetta/model/ply/init.luau"], [3809, "src/Rosetta/model/ply/Binary.luau"], [4010, "src/Rosetta/model/pmx/init.luau"], [4079, "src/Rosetta/model/pmx/Build.luau"], [4375, "src/Rosetta/model/pmx/Pmd.luau"], [4710, "src/Rosetta/model/pmx/Read.luau"], [5114, "src/Rosetta/model/proc/init.luau"], [5496, "src/Rosetta/model/qb/init.luau"], [5889, "src/Rosetta/model/rbxm/init.luau"], [6481, "src/Rosetta/model/rbxmx/init.luau"], [7134, "src/Rosetta/model/robloxmesh/init.luau"]], +"model_5": [[8, "src/Rosetta/model/robloxmesh/Parse.luau"], [465, "src/Rosetta/model/robloxmesh/Write.luau"], [574, "src/Rosetta/model/schematic/init.luau"], [895, "src/Rosetta/model/schematic/Common.luau"], [1015, "src/Rosetta/model/schematic/Litematic.luau"], [1226, "src/Rosetta/model/schematic/Mcedit.luau"], [1470, "src/Rosetta/model/schematic/Sponge.luau"], [1599, "src/Rosetta/model/smd/init.luau"], [1666, "src/Rosetta/model/smd/Read.luau"], [1935, "src/Rosetta/model/smd/Write.luau"], [2178, "src/Rosetta/model/sourcemdl/init.luau"], [2349, "src/Rosetta/model/sourcemdl/Build.luau"], [2779, "src/Rosetta/model/sourcemdl/Material.luau"], [2940, "src/Rosetta/model/sourcemdl/Mdl.luau"], [3467, "src/Rosetta/model/sourcemdl/Phy.luau"], [3590, "src/Rosetta/model/sourcemdl/Vtx.luau"], [3772, "src/Rosetta/model/sourcemdl/Vvd.luau"], [3866, "src/Rosetta/model/stl/init.luau"], [4316, "src/Rosetta/model/stl/Decode.luau"], [4390, "src/Rosetta/model/udmf/init.luau"], [4473, "src/Rosetta/model/usda/init.luau"], [4682, "src/Rosetta/model/usda/Build.luau"], [5960, "src/Rosetta/model/usda/Parse.luau"], [6758, "src/Rosetta/model/usda/Write.luau"], [7575, "src/Rosetta/model/vbsp/init.luau"]], +"model_6": [[8, "src/Rosetta/model/vbsp/Faces.luau"], [232, "src/Rosetta/model/vbsp/Props.luau"], [324, "src/Rosetta/model/vmf/init.luau"], [649, "src/Rosetta/model/vmf/Build.luau"], [1073, "src/Rosetta/model/vox/init.luau"], [1959, "src/Rosetta/model/vox/Grid.luau"], [2016, "src/Rosetta/model/vrml/init.luau"], [2082, "src/Rosetta/model/x/init.luau"], [2212, "src/Rosetta/model/x/Build.luau"], [2775, "src/Rosetta/model/x/Parse.luau"], [3072, "src/Rosetta/model/x3d/init.luau"]], "music": [[8, "src/Rosetta/music/669/init.luau"], [214, "src/Rosetta/music/ahx/init.luau"], [265, "src/Rosetta/music/far/init.luau"], [494, "src/Rosetta/music/hmp/init.luau"], [758, "src/Rosetta/music/hvl/init.luau"], [809, "src/Rosetta/music/it/init.luau"], [1227, "src/Rosetta/music/it/Itsex.luau"], [1343, "src/Rosetta/music/med/init.luau"], [1990, "src/Rosetta/music/midi/init.luau"], [2133, "src/Rosetta/music/midi/Smf.luau"], [2544, "src/Rosetta/music/mod/init.luau"], [2897, "src/Rosetta/music/mtm/init.luau"], [3119, "src/Rosetta/music/mus/init.luau"], [3276, "src/Rosetta/music/okt/init.luau"], [3557, "src/Rosetta/music/ptm/init.luau"], [3779, "src/Rosetta/music/s3m/init.luau"], [4015, "src/Rosetta/music/sf2/init.luau"], [4058, "src/Rosetta/music/stm/init.luau"], [4289, "src/Rosetta/music/ult/init.luau"], [4593, "src/Rosetta/music/umx/init.luau"], [4809, "src/Rosetta/music/xm/init.luau"], [5370, "src/Rosetta/music/xmi/init.luau"]], "ops": [[8, "src/Rosetta/ops/AudioOps.luau"], [457, "src/Rosetta/ops/LayerOps.luau"], [550, "src/Rosetta/ops/MeshOps/init.luau"], [1586, "src/Rosetta/ops/MeshOps/Greedy.luau"], [1753, "src/Rosetta/ops/MusicOps.luau"]], "playlist": [[8, "src/Rosetta/playlist/m3u/init.luau"], [361, "src/Rosetta/playlist/pls/init.luau"], [539, "src/Rosetta/playlist/xspf/init.luau"]], diff --git a/build/Rosetta.rbxmx b/build/Rosetta.rbxmx index 4712d3e..fcdeef8 100644 --- a/build/Rosetta.rbxmx +++ b/build/Rosetta.rbxmx @@ -314,6 +314,7 @@ local __CHUNK = { ["codecs/video/Video/Source"] = "codecs_video", ["containers/Archive"] = "containers", ["containers/Avi"] = "containers", + ["containers/Blend"] = "containers", ["containers/Chunks"] = "containers", ["containers/Cpio"] = "containers", ["containers/Demux"] = "containers", @@ -424,16 +425,23 @@ local __CHUNK = { ["model/3mf/Write"] = "model_1", ["model/b3d"] = "model_1", ["model/b3d/Read"] = "model_1", + ["model/blend"] = "model_1", + ["model/blend/Anim"] = "model_1", + ["model/blend/Material"] = "model_1", + ["model/blend/Mesh"] = "model_1", + ["model/blend/Normals"] = "model_1", + ["model/blend/Prim"] = "model_1", + ["model/blend/Read"] = "model_1", ["model/bsp"] = "model_1", ["model/bsp/Brush"] = "model_1", ["model/bsp/Quake3"] = "model_1", - ["model/buildmap"] = "model_1", - ["model/buildmap/Geometry"] = "model_1", - ["model/d3map"] = "model_1", - ["model/d3map/Parse"] = "model_1", - ["model/dae"] = "model_1", - ["model/dae/Math"] = "model_1", - ["model/dae/Read"] = "model_1", + ["model/buildmap"] = "model_2", + ["model/buildmap/Geometry"] = "model_2", + ["model/d3map"] = "model_2", + ["model/d3map/Parse"] = "model_2", + ["model/dae"] = "model_2", + ["model/dae/Math"] = "model_2", + ["model/dae/Read"] = "model_2", ["model/dae/Write"] = "model_2", ["model/fbx"] = "model_2", ["model/fbx/Ascii"] = "model_2", @@ -443,14 +451,14 @@ local __CHUNK = { ["model/fbx/Xform"] = "model_2", ["model/gltf"] = "model_2", ["model/gltf/Pack"] = "model_2", - ["model/gltf/Read"] = "model_2", - ["model/gltf/Write"] = "model_2", - ["model/iqm"] = "model_2", - ["model/iqm/Read"] = "model_2", - ["model/iqm/Write"] = "model_2", - ["model/ldraw"] = "model_2", - ["model/ldraw/Colors"] = "model_2", - ["model/ldraw/Read"] = "model_2", + ["model/gltf/Read"] = "model_3", + ["model/gltf/Write"] = "model_3", + ["model/iqm"] = "model_3", + ["model/iqm/Read"] = "model_3", + ["model/iqm/Write"] = "model_3", + ["model/ldraw"] = "model_3", + ["model/ldraw/Colors"] = "model_3", + ["model/ldraw/Read"] = "model_3", ["model/lwo"] = "model_3", ["model/lwo/Build"] = "model_3", ["model/lwo/Parse"] = "model_3", @@ -467,14 +475,14 @@ local __CHUNK = { ["model/md5/Read"] = "model_3", ["model/mdl"] = "model_3", ["model/mdl/HalfLife"] = "model_3", - ["model/mdl/Quake"] = "model_3", - ["model/ms3d"] = "model_3", - ["model/ms3d/Read"] = "model_3", - ["model/ms3d/Write"] = "model_3", - ["model/obj"] = "model_3", - ["model/obj/Mtl"] = "model_3", - ["model/off"] = "model_3", - ["model/ply"] = "model_3", + ["model/mdl/Quake"] = "model_4", + ["model/ms3d"] = "model_4", + ["model/ms3d/Read"] = "model_4", + ["model/ms3d/Write"] = "model_4", + ["model/obj"] = "model_4", + ["model/obj/Mtl"] = "model_4", + ["model/off"] = "model_4", + ["model/ply"] = "model_4", ["model/ply/Binary"] = "model_4", ["model/pmx"] = "model_4", ["model/pmx/Build"] = "model_4", @@ -485,23 +493,23 @@ local __CHUNK = { ["model/rbxm"] = "model_4", ["model/rbxmx"] = "model_4", ["model/robloxmesh"] = "model_4", - ["model/robloxmesh/Parse"] = "model_4", - ["model/robloxmesh/Write"] = "model_4", - ["model/schematic"] = "model_4", - ["model/schematic/Common"] = "model_4", - ["model/schematic/Litematic"] = "model_4", - ["model/schematic/Mcedit"] = "model_4", - ["model/schematic/Sponge"] = "model_4", - ["model/smd"] = "model_4", - ["model/smd/Read"] = "model_4", - ["model/smd/Write"] = "model_4", - ["model/sourcemdl"] = "model_4", - ["model/sourcemdl/Build"] = "model_4", - ["model/sourcemdl/Material"] = "model_4", - ["model/sourcemdl/Mdl"] = "model_4", - ["model/sourcemdl/Phy"] = "model_4", - ["model/sourcemdl/Vtx"] = "model_4", - ["model/sourcemdl/Vvd"] = "model_4", + ["model/robloxmesh/Parse"] = "model_5", + ["model/robloxmesh/Write"] = "model_5", + ["model/schematic"] = "model_5", + ["model/schematic/Common"] = "model_5", + ["model/schematic/Litematic"] = "model_5", + ["model/schematic/Mcedit"] = "model_5", + ["model/schematic/Sponge"] = "model_5", + ["model/smd"] = "model_5", + ["model/smd/Read"] = "model_5", + ["model/smd/Write"] = "model_5", + ["model/sourcemdl"] = "model_5", + ["model/sourcemdl/Build"] = "model_5", + ["model/sourcemdl/Material"] = "model_5", + ["model/sourcemdl/Mdl"] = "model_5", + ["model/sourcemdl/Phy"] = "model_5", + ["model/sourcemdl/Vtx"] = "model_5", + ["model/sourcemdl/Vvd"] = "model_5", ["model/stl"] = "model_5", ["model/stl/Decode"] = "model_5", ["model/udmf"] = "model_5", @@ -510,17 +518,17 @@ local __CHUNK = { ["model/usda/Parse"] = "model_5", ["model/usda/Write"] = "model_5", ["model/vbsp"] = "model_5", - ["model/vbsp/Faces"] = "model_5", - ["model/vbsp/Props"] = "model_5", - ["model/vmf"] = "model_5", - ["model/vmf/Build"] = "model_5", - ["model/vox"] = "model_5", - ["model/vox/Grid"] = "model_5", - ["model/vrml"] = "model_5", - ["model/x"] = "model_5", - ["model/x/Build"] = "model_5", - ["model/x/Parse"] = "model_5", - ["model/x3d"] = "model_5", + ["model/vbsp/Faces"] = "model_6", + ["model/vbsp/Props"] = "model_6", + ["model/vmf"] = "model_6", + ["model/vmf/Build"] = "model_6", + ["model/vox"] = "model_6", + ["model/vox/Grid"] = "model_6", + ["model/vrml"] = "model_6", + ["model/x"] = "model_6", + ["model/x/Build"] = "model_6", + ["model/x/Parse"] = "model_6", + ["model/x3d"] = "model_6", ["music/669"] = "music", ["music/ahx"] = "music", ["music/far"] = "music", @@ -2233,6 +2241,18 @@ local list: { Entry } = { return __include("model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return __include("model/blend") + end, + }, { name = "bsp", category = "model", @@ -115607,7 +115627,7 @@ end --!optimize 2 --!nocheck -- rosetta chunk containers (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 19 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- 20 modules (1 native: @native); the Rosetta root requires it when one of them is first included. -- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). return function(__FILES, __include) __FILES["containers/Archive"] = function() @@ -116429,6 +116449,745 @@ end return Avi end +__FILES["containers/Blend"] = function() + +-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header +-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header +-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads); +-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC, +-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files. +-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address. +local Err = __include("core/Err") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") + +local Blend = {} + +local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring + +type Field = { + name: string, -- without '*', '(*...)()' and array dimensions + decl: string, -- as declared ("*next", "co[3]", "mat[4][4]") + type: string, + offset: number, + size: number, -- bytes of the whole field (all array elements) + pointer: boolean, + dims: { number }, + count: number, -- array elements (1 for scalars) + elem: number, -- bytes of one element +} +type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } } +type Dna = { + names: { string }, + types: { string }, + lengths: { number }, + structs: { Struct }, -- 1-based; a block's sdna is 0-based + byName: { [string]: Struct }, +} +type Block = { + code: string, -- "OB", "ME", "DATA", ... (trailing NULs removed) + sdna: number, -- 0-based struct index + addr: any, -- the old address (a key: a number for 4-byte pointers, an 8-byte string for 8-byte ones) + size: number, -- data bytes + count: number, -- struct elements + offset: number, -- data start in file.buf + index: number, + owner: number, -- the index of the ID block this block follows (DATA blocks belong to the ID before them) +} +type File = { + buf: buffer, -- the (decompressed) file + version: number, -- 279, 293, 401, 502, ... + subversion: number?, -- from the GLOB block + pointerSize: number, + little: boolean, + format: number, -- 0 (12-byte header) or the 5.0+ file format version + compression: string?, -- "gzip" | "zstd" + blocks: { Block }, + byAddr: { [any]: Block }, + shared: { [any]: { Block } }, -- addresses used by several blocks (reused between IDs): every block with it + byCode: { [string]: { Block } }, + dna: Dna, + -- endian-aware readers (the little-endian ones are buffer's own) + u16: (b: buffer, o: number) -> number, + i16: (b: buffer, o: number) -> number, + u32: (b: buffer, o: number) -> number, + i32: (b: buffer, o: number) -> number, + f32: (b: buffer, o: number) -> number, + f64: (b: buffer, o: number) -> number, +} +type Options = { maxBytes: number?, maxBlocks: number? } + +-- ------------------------------------------------------------------------------------------------ readers +local function swap16(b: buffer, o: number): number + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function swap32(b: buffer, o: number): number + return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3) +end +local scratch = buffer.create(8) +local function bei16(b: buffer, o: number): number + local v = swap16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function bei32(b: buffer, o: number): number + local v = swap32(b, o) + return if v >= 2147483648 then v - 4294967296 else v +end +local function bef32(b: buffer, o: number): number + for k = 0, 3 do + buffer.writeu8(scratch, k, readu8(b, o + 3 - k)) + end + return readf32(scratch, 0) +end +local function bef64(b: buffer, o: number): number + for k = 0, 7 do + buffer.writeu8(scratch, k, readu8(b, o + 7 - k)) + end + return readf64(scratch, 0) +end + +-- ------------------------------------------------------------------------------------------------ open +function Blend.sniff(buf: buffer, offset: number?, length: number?): number + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if n >= 12 and readstring(buf, o, 7) == "BLENDER" then + return 1 + end + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + return 0.05 -- a gzip member: blend only once decompressed + end + return 0 +end + +local function decompress(buf: buffer, o: number, n: number, opts: Options?): (buffer?, string?, any) + local maxBytes = opts and opts.maxBytes or 2 ^ 31 + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + local out, err = Deflate.gunzip(buf, o, n) + if not out then + return nil, nil, err + end + if buffer.len(out) > maxBytes then + return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes") + end + return out, "gzip", nil + end + if n >= 4 and readu32(buf, o) == 0xFD2FB528 then + local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes }) + if not out then + return nil, nil, err + end + return out, "zstd", nil + end + return nil, nil, nil +end + +local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?) + if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then + return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)" + end + local c = readstring(b, 7, 1) + if c == "_" or c == "-" then + local e = readstring(b, 8, 1) + local v = tonumber(readstring(b, 9, 3)) + if (e ~= "v" and e ~= "V") or not v then + return nil, 0, false, 0, 0, "bad header" + end + return 12, if c == "_" then 4 else 8, e == "v", v, 0, nil + end + local hs = tonumber(readstring(b, 7, 2)) + if not hs or hs < 17 or hs > n then + return nil, 0, false, 0, 0, "bad header size" + end + if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then + return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7)) + end + local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4)) + if not fmt or not v then + return nil, 0, false, 0, 0, "bad header" + end + if fmt ~= 1 then + return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt + end + return hs, 8, true, v, fmt, nil +end + +local PRIM: { [string]: boolean } = { + char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true, + float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true, + uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true, +} +Blend.PRIMITIVE = PRIM + +local function parseDna(f: File, at: number, size: number): string? + local b = f.buf + local e = at + size + local i32 = f.i32 + local function align(p: number): number + return at + ((p - at + 3) // 4) * 4 + end + local function strings(p: number, tag: string): ({ string }?, number) + if p + 8 > e or readstring(b, p, 4) ~= tag then + return nil, p + end + local n = i32(b, p + 4) + p += 8 + if n < 0 or n > e - p then + return nil, p + end + local out = table.create(n) :: { string } + for k = 1, n do + local q = p + while q < e and readu8(b, q) ~= 0 do + q += 1 + end + if q >= e then + return nil, p + end + out[k] = readstring(b, p, q - p) + p = q + 1 + end + return out, p + end + if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then + return "no SDNA in DNA1" + end + local names, p = strings(at + 4, "NAME") + if not names then + return "bad SDNA NAME" + end + local types + types, p = strings(align(p), "TYPE") + if not types then + return "bad SDNA TYPE" + end + p = align(p) + local nt = #types + if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then + return "bad SDNA TLEN" + end + local lengths = table.create(nt) :: { number } + for k = 1, nt do + lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) + end + p = align(p + 4 + nt * 2) + if p + 8 > e or readstring(b, p, 4) ~= "STRC" then + return "bad SDNA STRC" + end + local ns = i32(b, p + 4) + p += 8 + if ns < 0 or ns * 4 > e - p then + return "bad SDNA struct count" + end + local i16 = f.i16 + local ps = f.pointerSize + local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct } + for k = 1, ns do + if p + 4 > e then + return "truncated SDNA structs" + end + local t, nf = i16(b, p), i16(b, p + 2) + p += 4 + if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then + return "bad SDNA struct " .. k + end + local tnames = types :: { string } + local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} } + local off = 0 + for j = 1, nf do + local ft, fn = i16(b, p), i16(b, p + 2) + p += 4 + if ft < 0 or ft >= nt or fn < 0 or fn >= #names then + return "bad SDNA field in " .. s.name + end + local decl: string = (names :: { string })[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims: { number }, count = {}, 1 + for d in string.gmatch(decl, "%[(%d+)%]") do + local v = tonumber(d) or 1 + table.insert(dims, v) + count *= v + end + local base = string.gsub(decl, "%[.*$", "") + base = string.gsub(base, "[%*%(%)]", "") + local elem: number = if pointer then ps else lengths[ft + 1] + local fld: Field = { + name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count, + pointer = pointer, dims = dims, count = count, elem = elem, + } + s.fields[j] = fld + if s.byName[base] == nil then + s.byName[base] = fld + end + off += fld.size + end + structs[k] = s + byName[s.name] = s + end + f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName } + return nil +end + +function Blend.open(data: buffer, offset: number?, length: number?, opts: Options?): (File?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "bad range") + end + local b: buffer + local unpacked, compression, derr = decompress(data, o, n, opts) + if derr then + return nil, derr + end + if unpacked then + b = unpacked + n = buffer.len(b) + elseif o == 0 and n == buffer.len(data) then + b = data + else + b = buffer.create(n) + buffer.copy(b, 0, data, o, n) + end + local hs, ps, little, version, fmt, herr = header(b, n) + if not hs then + local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, herr or "bad header", 0) + end + local f: File = { + buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, + compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil :: any, + u16 = if little then readu16 else swap16, + i16 = if little then readi16 else bei16, + u32 = if little then readu32 else swap32, + i32 = if little then readi32 else bei32, + f32 = if little then readf32 else bef32, + f64 = if little then readf64 else bef64, + } + local u32, i32 = f.u32, f.i32 + local maxBlocks = opts and opts.maxBlocks or 2 ^ 22 + local bh = if fmt >= 1 then 32 elseif ps == 8 then 24 else 20 + local p = hs + local dnaBlock: Block? = nil + local owner = 0 + while true do + if p + bh > n then + if p + 4 <= n and readstring(b, p, 4) == "ENDB" then + break -- ENDB written with a short head + end + return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p) + end + local code = readstring(b, p, 4) + local size, addr, sdna, count + if fmt >= 1 then + sdna = i32(b, p + 4) + addr = readstring(b, p + 8, 8) + local lo, hi = u32(b, p + 16), i32(b, p + 20) + local clo, chi = u32(b, p + 24), i32(b, p + 28) + if hi ~= 0 or chi ~= 0 then + return nil, Err.new(Err.LIMIT, "block over 4 GiB", p) + end + size, count = lo, clo + else + size = i32(b, p + 4) + addr = if ps == 8 then readstring(b, p + 8, 8) else u32(b, p + 8) + sdna = i32(b, p + 8 + ps) + count = i32(b, p + 12 + ps) + end + p += bh + -- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files + code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "") + if code == "ENDB" then + break + end + if size < 0 or count < 0 or size > n - p then + return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh) + end + if #f.blocks >= maxBlocks then + return nil, Err.new(Err.LIMIT, "too many blocks") + end + local index = #f.blocks + 1 + if code ~= "DATA" then + owner = index + end + local blk: Block = { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner } + table.insert(f.blocks, blk) + local prev = f.byAddr[addr] + if prev == nil then + f.byAddr[addr] = blk + else + local list = f.shared[addr] + if not list then + list = { prev } + f.shared[addr] = list + end + table.insert(list, blk) + end + local list = f.byCode[code] + if not list then + list = {} + f.byCode[code] = list + end + table.insert(list, blk) + if code == "DNA1" then + dnaBlock = blk + end + p += size + end + if not dnaBlock then + return nil, Err.new(Err.CORRUPT, "no DNA1 block") + end + local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size) + if derr2 then + return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset) + end + f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil + local glob = f.byCode.GLOB + local fg = f.dna.byName.FileGlobal + local g1: Block? = if glob then glob[1] else nil + local fld = fg and fg.byName.subversion + if g1 and fld then + if fld.offset + 2 <= g1.size then + f.subversion = f.i16(b, g1.offset + fld.offset) + end + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ structs +local View = {} +View.__index = View +Blend.View = View + +type View = typeof(setmetatable( + {} :: { + file: File, + struct: Struct, + offset: number, -- the struct's first byte in file.buf + block: Block?, + }, + View +)) + +local function view(f: File, s: Struct, offset: number, blk: Block?): View + return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) +end + +function Blend.structOf(f: File, blk: Block): Struct? + return f.dna.structs[blk.sdna + 1] +end + +function Blend.struct(f: File, blk: Block, i: number?, as: string?): View? + local s = if as then f.dna.byName[as] else f.dna.structs[blk.sdna + 1] + if not s then + return nil + end + local at = (i or 0) * s.size + if at < 0 or at + s.size > blk.size then + return nil + end + return view(f, s, blk.offset + at, blk) +end + +function Blend.view(f: File, structName: string, offset: number): View? + local s = f.dna.byName[structName] + if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then + return nil + end + return view(f, s, offset, nil) +end + +function Blend.field(f: File, structName: string, ...: string): Field? + local s = f.dna.byName[structName] + if not s then + return nil + end + for _, name in { ... } do + local fld = s.byName[name] + if fld then + return fld + end + end + return nil +end + +function Blend.blocks(f: File, code: string): { Block } + return f.byCode[code] or {} +end + +local function pointerKey(f: File, o: number): any + local b = f.buf + if f.pointerSize == 8 then + if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then + return nil + end + return readstring(b, o, 8) + end + local v = f.u32(b, o) + return if v == 0 then nil else v +end +Blend.pointerKey = pointerKey + +-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the +-- pointer comes from first (from = the block holding the pointer), as Blender's reader does +function Blend.resolve(f: File, addr: any, from: Block?): Block? + if addr == nil then + return nil + end + local list = f.shared[addr] + if list and from then + for _, b in list do + if b.owner == from.owner then + return b + end + end + end + return f.byAddr[addr] +end + +local function find(self: View, names: { any }): Field? + local by = self.struct.byName + for _, name in names do + local fld = by[name] + if fld then + return fld + end + end + return nil +end + +function View.has(self: View, ...: string): boolean + return find(self, { ... }) ~= nil +end + +local function scalar(f: File, t: string, size: number, o: number): number + local b = f.buf + if t == "float" then + return f.f32(b, o) + elseif t == "double" then + return f.f64(b, o) + elseif t == "int" or t == "int32_t" or t == "long" then + return if size == 8 then f.u32(b, o + (if f.little then 0 else 4)) else f.i32(b, o) + elseif t == "short" or t == "int16_t" then + return f.i16(b, o) + elseif t == "ushort" or t == "uint16_t" then + return f.u16(b, o) + elseif t == "uint" or t == "uint32_t" or t == "ulong" then + return f.u32(b, o) + elseif t == "int8_t" then + return readi8(b, o) + elseif t == "int64_t" or t == "uint64_t" then + local lo, hi = f.u32(b, o + (if f.little then 0 else 4)), f.u32(b, o + (if f.little then 4 else 0)) + if t == "int64_t" and hi >= 2147483648 then + return (hi - 4294967296) * 4294967296 + lo + end + return hi * 4294967296 + lo + end + return readu8(b, o) -- char, uchar, uint8_t, bool +end + +function View.get(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld then + return nil + end + local f = self.file + local o = self.offset + fld.offset + if o + fld.size > buffer.len(f.buf) then + return nil + end + if fld.pointer then + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false + end + return out + end + return pointerKey(f, o) + end + local t = fld.type + if PRIM[t] then + if fld.count == 1 then + return scalar(f, t, fld.elem, o) + end + if t == "char" then + local s = readstring(f.buf, o, fld.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem) + end + return out + end + local s = f.dna.byName[t] + if not s then + return nil + end + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = view(f, s, o + k * s.size, self.block) + end + return out + end + return view(f, s, o, self.block) +end + +function View.num(self: View, ...: string): number? + local v = self:get(...) + return if type(v) == "number" then v else nil +end + +function View.str(self: View, ...: string): string? + local v = self:get(...) + return if type(v) == "string" then v else nil +end + +function View.vec(self: View, ...: string): { number }? + local v = self:get(...) + return if type(v) == "table" and type(v[1]) == "number" then v else nil +end + +function View.sub(self: View, ...: string): View? + local v = self:get(...) + return if type(v) == "table" and getmetatable(v) == View then v else nil +end + +function View.ptr(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then + return nil + end + return pointerKey(self.file, self.offset + fld.offset) +end + +function View.target(self: View, ...: string): Block? + return Blend.resolve(self.file, self:ptr(...), self.block) +end + +function View.deref(self: View, name: string | { string }, i: number?, as: string?): View? + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return nil + end + local blk = self:target(fld.name) + if not blk then + return nil + end + local f = self.file + local sname = as or fld.type + if not as and (sname == "void" or not f.dna.byName[sname]) then + local own = f.dna.structs[blk.sdna + 1] + sname = if own then own.name else sname + end + return Blend.struct(f, blk, i, sname) +end + +function View.array(self: View, name: string | { string }, as: string?): { View } + local first = self:deref(name, 0, as) + if not first or not first.block then + return {} + end + local blk = first.block :: Block + local s = first.struct + local n = if s.size > 0 then blk.size // s.size else 0 + local out = table.create(n) :: { View } + for k = 0, n - 1 do + out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) + end + return out +end + +function View.pointers(self: View, name: string | { string }, n: number?): { any } + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return {} + end + local blk = self:target(fld.name) + if not blk then + return {} + end + local f = self.file + local ps = f.pointerSize + local count = blk.size // ps + if n then + count = math.min(count, n) + end + local out = table.create(count) + for k = 0, count - 1 do + out[k + 1] = pointerKey(f, blk.offset + k * ps) or false + end + return out +end + +function View.list(self: View, name: string | { string }, as: string?, limit: number?): { View } + local names: { any } = if type(name) == "table" then name else { name } + local lb = self:sub(table.unpack(names)) + local out = {} + if not lb then + return out + end + local f = self.file + local addr = lb:ptr("first") + local seen = {} + local max = limit or 2 ^ 20 + while addr ~= nil and not seen[addr] and #out < max do + seen[addr] = true + local blk = Blend.resolve(f, addr, self.block) + if not blk then + break + end + local v = Blend.struct(f, blk, 0, as) + if not v then + break + end + table.insert(out, v) + addr = v:ptr("next") + if addr == nil and not v.struct.byName.next then + -- structs that start with an embedded header (ModifierData, ...) keep the link there + local head = v.struct.fields[1] + local sub = head and not head.pointer and f.dna.byName[head.type] + if sub then + addr = view(f, sub, v.offset + head.offset, v.block):ptr("next") + end + end + end + return out +end + +function View.data(self: View, ...: string): (number?, number) + local blk = self:target(...) + if not blk then + return nil, 0 + end + return blk.offset, blk.size +end + +function View.cstring(self: View, ...: string): string? + local blk = self:target(...) + if not blk then + return nil + end + local s = readstring(self.file.buf, blk.offset, blk.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +function View.idName(self: View): string? + local id = self:sub("id") + local n = if id then id:str("name") else self:str("name") + if not n then + return nil + end + return string.sub(n, 3) +end + +return Blend +end __FILES["containers/Chunks"] = function() -- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and @@ -150536,6 +151295,2945 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, return scene, nil, nil end +return Read +end +__FILES["model/blend"] = function() + +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Blend = __include("containers/Blend") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Read = __include("model/blend/Read") +local Anim = __include("model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true (false: "polygons" primitives) + flipV: boolean?, -- default true (glTF's top-left UV origin) + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- a scene by name (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, -- external images + files: { [string]: any }?, + maxBytes: number?, -- decompressed size limit (default 2^31) + maxVertices: number?, -- per mesh (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. +function BlendFormat.sniff(r: Bytes.Reader): number + local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?) + return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat +end +__FILES["model/blend/Anim"] = function() + +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = __include("containers/Blend") + +local Anim = {} + +type Key = { + x: number, + y: number, + lx: number, -- left handle + ly: number, + rx: number, -- right handle + ry: number, + ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine) + easing: number, -- 0 auto, 1 in, 2 out, 3 in-out + back: number, + amplitude: number, + period: number, +} +type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number } + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f: Blend.File, fc: Blend.View): Curve? + local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys: { Key } = {} + for _, b in fc:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in fc:array("fpt", "FPoint") do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) + if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list: { Blend.View } = act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in act:pointers("layer_array", act:num("layer_array_num")) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out: { Curve } = {} + for _, fc in list do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR: { [number]: { any } } = { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?) + if not ipo then + return nil, nil + end + local out: { Curve } = {} + for _, icu in ipo:list("curve", "IpoCurve") do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys: { Key } = {} + for _, b in icu:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number + local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a: Key, b: Key, x: number): number + local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = if d ~= 0 then t - (xt - x) / d else -1 + t = if nt > lo and nt < hi then nt else (lo + hi) / 2 + end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t: number, b: number, c: number, d: number): number + t /= d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t -= 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t -= 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t -= 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 + if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = if a.period > 0 then a.period / 10 else 0.3 + local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t -= 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a: Key, b: Key, x: number): number + local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c: Curve, x: number): number + local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves: { Curve }): (number, number) + local lo, hi = math.huge, -math.huge + for _, c in curves do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path: string): (string?, string?, string) + local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim +end +__FILES["model/blend/Material"] = function() + +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = __include("containers/Blend") +local Types = __include("Types") + +local Material = {} + +type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any } + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b: buffer, o: number, n: number, path: string?): string? + if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return if ext then byExt[ext] else nil +end + +local function fetch(ctx: Ctx, uri: string): buffer? + local opts = ctx.opts + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number? + local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil + local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in img:list("packedfiles", "ImagePackedFile") do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex: Types.Texture = { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + +type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } } +type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr + +local function graph(tree: Blend.View): Graph + local g: Graph = { nodes = {}, links = {} } + for _, n in tree:list("nodes", "bNode") do + local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in n:list("inputs", "bNodeSocket") do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in n:list("outputs", "bNodeSocket") do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in tree:list("links", "bNodeLink") do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n: Node, ...: string): Blend.View? + for _, k in { ... } do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }? + if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s: Blend.View?, kind: string): any + if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?) + local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, if ref then n else tn + end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler: Types.Sampler = {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, if custom then sampler else nil) + if not t then + return nil, n + end + local ref: Types.TextureRef = { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g: Graph): Node? + local first: Node? = nil + for _, n in g.nodes do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m: Types.Material, color: { number }, strength: number) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx: Ctx, mv: Blend.View): number + local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras: { [string]: any } = {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g: Graph? = nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g :: Graph) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1 + m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material +end +__FILES["model/blend/Mesh"] = function() + +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = __include("containers/Blend") + +local Mesh = {} + +type Layer = { + name: string, + domain: string, -- "point" | "edge" | "face" | "corner" | "tess" + kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, + -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) + offset: number, -- data start in file.buf + bytes: number, -- data bytes available + elem: number, -- bytes per element + single: boolean?, -- one value for every element (AttributeStorage single storage) + activeRender: boolean?, + cdtype: number?, +} + +type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner +type Poly = { + name: string?, + nv: number, + nf: number, + nc: number, + pos: buffer, -- f32 x 3 per vertex + cornerVert: buffer, -- u32 per corner + faceStart: buffer, -- u32 per face + 1 + faceMat: buffer, -- i32 per face + faceSmooth: buffer, -- u8 per face + uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner + activeUV: number, -- 1-based index into uvs (the active render layer) + colors: { Color }, + customNormals: buffer?, -- f32 x 3 per corner (free custom normals) + encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) + sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans + autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) + weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... + generation: string, -- "mface" | "mpoly" | "attributes" | "storage" + layers: { Layer }, +} + +local CD_KIND: { [number]: string } = { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND: { [number]: string } = { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE: { [string]: number } = { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end +Mesh.SRGB = SRGB + +local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = if st then st.size else SIZE[kind] or 0 + if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f: Blend.File, me: Blend.View, out: { Layer }) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? + for _, L in layers do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? + local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f: Blend.File, L: Layer): (number, number) -> number + local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 + return function(i: number, c: number): number + local at = (if single then 0 else i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? + local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i: number, c: number): number + local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at += o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer + local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255) + end + end + return d +end + +function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } + local layers: { Layer } = {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me: Blend.View, ...: string): number + local v = me:num(...) + return if v and v > 0 then v else 0 +end + +type Limits = { maxVertices: number? } + +function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) + local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get: ((number, number) -> number)? = nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_: number, _: number): number + return 0 + end + end + local g = get :: (number, number) -> number + for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly: Poly = { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", + layers = layers, + } + local corner: { [string]: any } = {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at += math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w += 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil + local flag = if mp then fieldReader(f, mp, "flag") else nil + local sr = if sf then reader(f, sf) else nil + for i = 0, np - 1 do + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, if s then 1 else 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at += k + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap: buffer? = corner.remap + local function src(i: number): number + return if remap then buffer.readu32(remap, i * 4) else i + end + for _, L in layers do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess :: buffer + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = tc // 4, tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess :: buffer + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in poly.uvs do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in layers do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = if L.domain == "corner" then nc else nv + local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = if L.domain == "corner" then src(i) else i + for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] + end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = if st then st.size else 4 + table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in layers do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) + for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i: number): number return er(i, 0) end + v2 = function(i: number): number return er(i, 1) end + sharp = function(i: number): boolean return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i: number): number return a(i, 0) end + v2 = function(i: number): number return b(i, 0) end + local ser = if se then reader(f, se) else nil + sharp = function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = table.create(nv) :: { { number } } + for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, blk.size // mw.size) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end + +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index +type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } +function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) + local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out: { Shape } = {} + local ref: number? = nil + for i, kb in blocks do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, n // 4 - 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh +end +__FILES["model/blend/Normals"] = function() + +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + +type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } } + +local function dir(pos: buffer, from: number, to: number): (number, number, number) + local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer + local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals :: buffer + local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done: { [number]: boolean } = {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard += 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = if nq then readu32(nxt, nq * 4) else c + if q < m then + m = q + end + guard += 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in edges do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count += 1 + end + end + alpha /= math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = if cyclic then edges[2] else edges[#edges] + local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in corners do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = (if a > 0 then alpha else TAU - alpha) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = (if b > 0 then beta else TAU - beta) * b + x += sa * (rx * cos(be) + tx * sin(be)) + y += sa * (ry * cos(be) + ty * sin(be)) + z += sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals +end +__FILES["model/blend/Prim"] = function() + +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") +local Rig = __include("codecs/model/Rig") +local Normals = __include("model/blend/Normals") +local MeshT = __include("model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + +type Options = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true (glTF's top-left UV origin) + normals: boolean?, -- default true +} +type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin + +local function face(poly: MeshT.Poly, fi: number): (number, number) + return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos: buffer, v: number): (number, number, number) + return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly: MeshT.Poly): (buffer, buffer) + local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = if c + 1 < s1 then c + 1 else s0 + local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx += (y1 - y2) * (z1 + z2) + ny += (z1 - z2) * (x1 + x2) + nz += (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = if c > s0 then c - 1 else s1 - 1 + local nc = if c + 1 < s1 then c + 1 else s0 + local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end + +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges +type Fans = { + next: buffer, -- u32 per corner: the next corner of its face + prev: buffer, -- u32 per corner + face: buffer, -- u32 per corner: its face + -- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner + -- at this corner's next vertex), or -1 where the edge splits fans + across: { [number]: number }, +} + +function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans + local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0) + writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1) + writeu32(fc, c * 4, fi) + end + end + local first: { [number]: number } = {} + local second: { [number]: number } = {} + local uses: { [number]: number } = {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across: { [number]: number } = {} + local smooth = poly.faceSmooth + local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil + for key, u in uses do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer) + local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c: number): number + local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a: number, b: number) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in fans.across do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12)) + writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4)) + writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8)) + end + return out, fanId +end + +function Prim.normals(poly: MeshT.Poly): buffer + local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals :: buffer + end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number }) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = table.create(n * 2) :: { number } + for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, if sign < 0 then -u else u) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t: { number }, comps: number): Types.Accessor + local n = #t // comps + local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built + local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil + local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0) + local nslots = math.max(#slots, 1) + local groups: { [number]: { number } } = {} + local order: { number } = {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {} + for _, c in poly.colors do + table.insert(if c.domain == "corner" then cornerColors else pointColors, c) + end + local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh: Types.Mesh = { name = poly.name, primitives = {} } + local sources: { { number } } = {} + local cv = poly.cornerVert + for _, m in order do + local faces = groups[m] + local map: { [string]: number } = {} + local vsrc: { number } = {} + local corners: { number } = {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in faces do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o += 12 + end + for _, uv in poly.uvs do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o += 8 + end + for _, col in cornerColors do + buffer.copy(scratch, o, col.data, c * 16, 16) + o += 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs: { [string]: Types.Accessor } = {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in poly.uvs do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in poly.colors do + local C = buffer.create(n * 16) + for i = 1, n do + local e = if col.domain == "corner" then corners[i] else vsrc[i] + buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci += 1 + end + if skin and poly.weights then + local lists = table.create(n) :: { { number } } + for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k]] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim: Types.Primitive = { attributes = attrs, mode = "triangles" } + local idx: { number } = {} + if triangulateOn then + for _, fi in faces do + local tri: { number } = {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in tri do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in faces do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in idx do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets: { { [string]: Types.Accessor } } = {} + for k, s in shapes do + if k ~= ref then + local t = table.create(n * 3) :: { number } + for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in shapes do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in order do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim +end +__FILES["model/blend/Read"] = function() + +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = __include("containers/Blend") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Mesh = __include("model/blend/Mesh") +local Prim = __include("model/blend/Prim") +local Anim = __include("model/blend/Anim") +local Material = __include("model/blend/Material") + +local Read = {} + +local Scene = Types.Scene +type M4 = { number } + +type Options = { + triangulate: boolean?, + flipV: boolean?, + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- the scene to read (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, +} + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME: { [number]: string } = { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q: { number }?): { number } + if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4 + if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m: M4, s: { number }): M4 + local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do + r[c * 4 + k] *= s[c + 1] + end + end + return r +end + +local function trs(t: { number }, r: M4, s: { number }): M4 + local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + +type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode + +local function objectProps(ob: Blend.View): Props + -- fields missing from old files take their neutral value + local function v(fallback: { number }, ...: string): { number } + local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p: Props = { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc: Blend.View?): Props + if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n: number, ...: string): { number } + local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p: Props): M4 + local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node: Types.Node, m: M4) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v: Blend.View?, ...: string): M4? + local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ scene +type Ctx = { + f: Blend.File, + scene: Types.Scene, + opts: Options, + objects: { [any]: number }, -- OB addr -> node + objView: { [number]: Blend.View }, -- node -> its object + parentOf: { [number]: number }, + world: { [number]: M4 }, + meshes: { [string]: number }, + materials: { [any]: number }, + textures: { [any]: number }, + armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) + props: { [number]: Props }, + meta: { [string]: any }, + pending: { { node: number, ob: Blend.View } }, +} + +local function worldOf(ctx: Ctx, node: number): M4 + local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = if p then Mat4.mul(worldOf(ctx, p), m) else m + ctx.world[node] = w + return w +end + +local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number + table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames: { [string]: Blend.View } = {} + if pose then + for _, pc in pose:list("chanbase", "bPoseChannel") do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) + if depth > 256 then + return + end + for _, bone in list do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest + local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode: Types.Node = { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = if parentJoint then info.joints[parentJoint] else node + local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx: Ctx, ob: Blend.View, node: number) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c: Types.Camera + if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera + else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera + end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx: Ctx, ob: Blend.View, node: number) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy *= 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in if tree then tree:list("nodes", "bNode") else {} do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in n:list("inputs", "bNodeSocket") do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l: Types.Light + if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light + elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light + elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light + else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number } + local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = if useOb then obMats[i] else meMats[i] + local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx :: any, mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View? + for _, md in ob:list("modifiers") do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob: Blend.View, me: Blend.View): { string } + local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in list do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin: Prim.Skinning? = nil + if armInfo then + local joints = {} + for gi, name in groupNames(ob, me) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number }) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx: Ctx) + for _, p in ctx.pending do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number? + local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode: number? = under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node: Types.Node = { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in ob:list("modifiers") do + table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props + local p: Props = {} + for k, v in props do + p[k] = table.clone(v) + end + for _, c in curves do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end +type Curve = Anim.Curve + +local function frames(lo: number, hi: number, step: number): { number } + local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f += step + end + table.insert(out, hi) + return out +end + +type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? } + +local function animations(ctx: Ctx) + local f = ctx.f + local jobs: { Job } = {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner: { [any]: string } = {} + for _, ob in ctx.objView do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in ctx.meta.shapeKeys do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves: { Curve }? = found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in sk.shapes do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in mc or {} do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list: { Curve } = curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in ctx.scene.nodes do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a: Job, b: Job): boolean + return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in jobs do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction: { [string]: Types.Animation } = {} + for _, j in jobs do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } :: Types.Animation + byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in fs do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node :: number + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in j.curves do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who]] = true + end + end + for b in touched do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in fs do + local k = 0 + for si, s in sk.shapes do + if si ~= sk.ref then + local v = s.value + for _, c in j.curves do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k += 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in times do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in j.nodes :: { number } do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any }, + } }) + end + end + for _, a in tmp.animations do + for _, ch in a.channels do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f: Blend.File, name: string?): Blend.View? + local scenes = Blend.blocks(f, "SC") + if name then + for _, b in scenes do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil +end + +function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) + local o: Options = opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta: { [string]: any } = { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx: Ctx = { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order: { { ob: Blend.View, under: number? } } = {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = if fps > 0 then fps else 24 + meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col: Blend.View, under: number?, depth: number) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in col:list("gobject", "CollectionObject") do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in col:list("children", "CollectionChild") do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn: number? = nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in sc:list("base", "Base") do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in Blend.blocks(f, "OB") do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder: { [any]: number? } = {} + for _, e in order do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in order do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, if u and u > 0 then u else nil, 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + return Read end __FILES["model/bsp"] = function() @@ -151174,6 +154872,19 @@ end return Quake3 end +end + + + + + + model_2 + --!optimize 2 +--!nocheck +-- rosetta chunk model_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 16 modules (2 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/buildmap"] = function() -- model/buildmap: Build engine maps (.map versions 7-9: Duke Nukem 3D, Shadow Warrior, eduke32), from Ken Silverman's @@ -154415,19 +158126,6 @@ end return Read end -end - - - - - - model_2 - --!optimize 2 ---!nocheck --- rosetta chunk model_2 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 17 modules (2 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/dae/Write"] = function() -- model/dae/Write: Scene -> Collada 1.4.1 text; strips and fans unrolled, points skipped, nodes as row-major <matrix>. @@ -158364,6 +162062,19 @@ end return Pack end +end + + + + + + model_3 + --!optimize 2 +--!nocheck +-- rosetta chunk model_3 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 24 modules (0 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/gltf/Read"] = function() -- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are @@ -161866,19 +165577,6 @@ end return Read end -end - - - - - - model_3 - --!optimize 2 ---!nocheck --- rosetta chunk model_3 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 24 modules (0 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/lwo"] = function() -- model/lwo: LightWave objects LWO2 (6+), LWOB (5.x) and Modo's LXOB, read; from the LWO2 / LWOB specs, checked against @@ -165923,6 +169621,19 @@ end return HalfLife end +end + + + + + + model_4 + --!optimize 2 +--!nocheck +-- rosetta chunk model_4 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 18 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/mdl/Quake"] = function() -- model/mdl/Quake: Quake 1 MDL ("IDPO" v6), from "Quake Specs 3.4" section 5 and modelgen.h; no code taken. Seam @@ -169724,19 +173435,6 @@ end return Ply end -end - - - - - - model_4 - --!optimize 2 ---!nocheck --- rosetta chunk model_4 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 27 modules (3 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/ply/Binary"] = @native function() @@ -173721,6 +177419,19 @@ end return RobloxMesh end +end + + + + + + model_5 + --!optimize 2 +--!nocheck +-- rosetta chunk model_5 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 25 modules (3 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/robloxmesh/Parse"] = @native function() @@ -177579,19 +181290,6 @@ end return Vvd end -end - - - - - - model_5 - --!optimize 2 ---!nocheck --- rosetta chunk model_5 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. --- 19 modules (2 native: @native); the Rosetta root requires it when one of them is first included. --- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). -return function(__FILES, __include) __FILES["model/stl"] = function() -- model/stl: STL (3D Systems; Wikipedia "STL (file format)", the SLC spec), ASCII and binary, read + write. Supports: @@ -181747,6 +185445,19 @@ end return Vbsp end +end + + + + + + model_6 + --!optimize 2 +--!nocheck +-- rosetta chunk model_6 (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit. +-- 11 modules (1 native: @native); the Rosetta root requires it when one of them is first included. +-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where). +return function(__FILES, __include) __FILES["model/vbsp/Faces"] = function() -- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013 @@ -184893,7 +188604,7 @@ end - + music --!optimize 2 @@ -190476,7 +194187,7 @@ end - + ops --!optimize 2 @@ -192582,7 +196293,7 @@ end - + playlist --!optimize 2 @@ -193329,7 +197040,7 @@ end - + subtitle --!optimize 2 @@ -194162,7 +197873,7 @@ end - + vector --!optimize 2 @@ -198222,7 +201933,7 @@ end - + video --!optimize 2 diff --git a/build/rosetta.lua b/build/rosetta.lua index c356d85..1bc6478 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -2249,6 +2249,18 @@ local list= { return __include("model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return __include("model/blend") + end, + }, { name = "bsp", category = "model", @@ -111332,6 +111344,745 @@ end return Avi end +__FILES["containers/Blend"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header +-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header +-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads); +-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC, +-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files. +-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address. +local Err = __include("core/Err") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") + +local Blend = {} + +local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring + +-- ------------------------------------------------------------------------------------------------ readers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function swap16(b, o) +return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function swap32(b, o) +return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3) +end +local scratch = buffer.create(8) +local function bei16(b, o) +local v = swap16(b, o) + return (v >= 32768 and((v - 65536 ))or(v +))end +local function bei32(b, o) +local v = swap32(b, o) + return (v >= 2147483648 and((v - 4294967296 ))or(v +))end +local function bef32(b, o) +for k = 0, 3 do + buffer.writeu8(scratch, k, readu8(b, o + 3 - k)) + end + return readf32(scratch, 0) +end +local function bef64(b, o) +for k = 0, 7 do + buffer.writeu8(scratch, k, readu8(b, o + 7 - k)) + end + return readf64(scratch, 0) +end + +-- ------------------------------------------------------------------------------------------------ open +function Blend.sniff(buf, offset, length) +local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if n >= 12 and readstring(buf, o, 7) == "BLENDER" then + return 1 + end + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + return 0.05 -- a gzip member: blend only once decompressed + end + return 0 +end + +local function decompress(buf, o, n, opts) +local maxBytes = opts and opts.maxBytes or 2 ^ 31 + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + local out, err = Deflate.gunzip(buf, o, n) + if not out then + return nil, nil, err + end + if buffer.len(out) > maxBytes then + return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes") + end + return out, "gzip", nil + end + if n >= 4 and readu32(buf, o) == 0xFD2FB528 then + local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes }) + if not out then + return nil, nil, err + end + return out, "zstd", nil + end + return nil, nil, nil +end + +local function header(b, n) +if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then + return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)" + end + local c = readstring(b, 7, 1) + if c == "_" or c == "-" then + local e = readstring(b, 8, 1) + local v = tonumber(readstring(b, 9, 3)) + if (e ~= "v" and e ~= "V") or not v then + return nil, 0, false, 0, 0, "bad header" + end + return 12, c == "_" and 4 or 8, e == "v", v, 0, nil + end + local hs = tonumber(readstring(b, 7, 2)) + if not hs or hs < 17 or hs > n then + return nil, 0, false, 0, 0, "bad header size" + end + if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then + return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7)) + end + local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4)) + if not fmt or not v then + return nil, 0, false, 0, 0, "bad header" + end + if fmt ~= 1 then + return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt + end + return hs, 8, true, v, fmt, nil +end + +local PRIM= { + char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true, + float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true, + uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true, +} +Blend.PRIMITIVE = PRIM + +local function parseDna(f, at, size) +local b = f.buf + local e = at + size + local i32 = f.i32 + local function align(p) +return at + (math.floor((p - at + 3) / 4)) * 4 + end + local function strings(p, tag) +if p + 8 > e or readstring(b, p, 4) ~= tag then + return nil, p + end + local n = i32(b, p + 4) + p =p+ 8 + if n < 0 or n > e - p then + return nil, p + end + local out = (table.create(n) ) +for k = 1, n do + local q = p + while q < e and readu8(b, q) ~= 0 do + q =q+ 1 + end + if q >= e then + return nil, p + end + out[k] = readstring(b, p, q - p) + p = q + 1 + end + return out, p + end + if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then + return "no SDNA in DNA1" + end + local names, p = strings(at + 4, "NAME") + if not names then + return "bad SDNA NAME" + end + local types + types, p = strings(align(p), "TYPE") + if not types then + return "bad SDNA TYPE" + end + p = align(p) + local nt = #types + if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then + return "bad SDNA TLEN" + end + local lengths = (table.create(nt) ) +for k = 1, nt do + lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) + end + p = align(p + 4 + nt * 2) + if p + 8 > e or readstring(b, p, 4) ~= "STRC" then + return "bad SDNA STRC" + end + local ns = i32(b, p + 4) + p =p+ 8 + if ns < 0 or ns * 4 > e - p then + return "bad SDNA struct count" + end + local i16 = f.i16 + local ps = f.pointerSize + local structs, byName = (table.create(ns) ), {} +for k = 1, ns do + if p + 4 > e then + return "truncated SDNA structs" + end + local t, nf = i16(b, p), i16(b, p + 2) + p =p+ 4 + if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then + return "bad SDNA struct " .. k + end + local tnames = types +local s= { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = (table.create(nf) ), byName = {} } + local off = 0 + for j = 1, nf do + local ft, fn = i16(b, p), i16(b, p + 2) + p =p+ 4 + if ft < 0 or ft >= nt or fn < 0 or fn >= #names then + return "bad SDNA field in " .. s.name + end + local decl= (names )[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims, count = {}, 1 + for d in __iter(string.gmatch(decl, "%[(%d+)%]")) do + local v = tonumber(d) or 1 + table.insert(dims, v) + count =count* v + end + local base = string.gsub(decl, "%[.*$", "") + base = string.gsub(base, "[%*%(%)]", "") + local elem= (pointer and{ps }or{lengths[ft + 1] +})[1] local fld= { + name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count, + pointer = pointer, dims = dims, count = count, elem = elem, + } + s.fields[j] = fld + if s.byName[base] == nil then + s.byName[base] = fld + end + off =off+ fld.size + end + structs[k] = s + byName[s.name] = s + end + f.dna = { names = names , types = types , lengths = lengths, structs = structs, byName = byName } + return nil +end + +function Blend.open(data, offset, length, opts) +local o = offset or 0 + local n = length or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "bad range") + end + local b +local unpacked, compression, derr = decompress(data, o, n, opts) + if derr then + return nil, derr + end + if unpacked then + b = unpacked + n = buffer.len(b) + elseif o == 0 and n == buffer.len(data) then + b = data + else + b = buffer.create(n) + buffer.copy(b, 0, data, o, n) + end + local hs, ps, little, version, fmt, herr = header(b, n) + if not hs then + local code = (n < 12 and{Err.TRUNCATED }or{(herr and string.sub(herr, 1, 12) == "unsupported:" and{Err.UNSUPPORTED }or{Err.CORRUPT +})[1]})[1] return nil, Err.new(code, herr or "bad header", 0) + end + local f= { + buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, + compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil , + u16 = (little and{readu16 }or{swap16})[1], + i16 = (little and{readi16 }or{bei16})[1], + u32 = (little and{readu32 }or{swap32})[1], + i32 = (little and{readi32 }or{bei32})[1], + f32 = (little and{readf32 }or{bef32})[1], + f64 = (little and{readf64 }or{bef64})[1], + } + local u32, i32 = f.u32, f.i32 + local maxBlocks = opts and opts.maxBlocks or 2 ^ 22 + local bh = fmt >= 1 and 32 or(ps == 8 and 24 or 20 +) local p = hs + local dnaBlock= nil + local owner = 0 + while true do + if p + bh > n then + if p + 4 <= n and readstring(b, p, 4) == "ENDB" then + break -- ENDB written with a short head + end + return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p) + end + local code = readstring(b, p, 4) + local size, addr, sdna, count + if fmt >= 1 then + sdna = i32(b, p + 4) + addr = readstring(b, p + 8, 8) + local lo, hi = u32(b, p + 16), i32(b, p + 20) + local clo, chi = u32(b, p + 24), i32(b, p + 28) + if hi ~= 0 or chi ~= 0 then + return nil, Err.new(Err.LIMIT, "block over 4 GiB", p) + end + size, count = lo, clo + else + size = i32(b, p + 4) + addr = (ps == 8 and{(readstring(b, p + 8, 8) )}or{(u32(b, p + 8) +)})[1] sdna = i32(b, p + 8 + ps) + count = i32(b, p + 12 + ps) + end + p =p+ bh + -- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files + code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "") + if code == "ENDB" then + break + end + if size < 0 or count < 0 or size > n - p then + return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh) + end + if #f.blocks >= maxBlocks then + return nil, Err.new(Err.LIMIT, "too many blocks") + end + local index = #f.blocks + 1 + if code ~= "DATA" then + owner = index + end + local blk= { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner } + table.insert(f.blocks, blk) + local prev = f.byAddr[addr] + if prev == nil then + f.byAddr[addr] = blk + else + local list = f.shared[addr] + if not list then + list = { prev } + f.shared[addr] = list + end + table.insert(list, blk) + end + local list = f.byCode[code] + if not list then + list = {} + f.byCode[code] = list + end + table.insert(list, blk) + if code == "DNA1" then + dnaBlock = blk + end + p =p+ size + end + if not dnaBlock then + return nil, Err.new(Err.CORRUPT, "no DNA1 block") + end + local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size) + if derr2 then + return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset) + end + f.byAddr[(ps == 8 and{(string.rep("\0", 8) )}or{0})[1] ] = nil + local glob = f.byCode.GLOB + local fg = f.dna.byName.FileGlobal + local g1= (glob and{glob[1] }or{nil +})[1] local fld = fg and fg.byName.subversion + if g1 and fld then + if fld.offset + 2 <= g1.size then + f.subversion = f.i16(b, g1.offset + fld.offset) + end + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ structs +local View = {} +View.__index = View +Blend.View = View + + + + + + + + + + + +local function view(f, s, offset, blk) +return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) +end + +function Blend.structOf(f, blk) +return f.dna.structs[blk.sdna + 1] +end + +function Blend.struct(f, blk, i, as) +local s = (as and{f.dna.byName[as] }or{f.dna.structs[blk.sdna + 1] +})[1] if not s then + return nil + end + local at = (i or 0) * s.size + if at < 0 or at + s.size > blk.size then + return nil + end + return view(f, s, blk.offset + at, blk) +end + +function Blend.view(f, structName, offset) +local s = f.dna.byName[structName] + if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then + return nil + end + return view(f, s, offset, nil) +end + +function Blend.field(f, structName, ...) +local s = f.dna.byName[structName] + if not s then + return nil + end + for _, name in __iter({ ... }) do + local fld = s.byName[name] + if fld then + return fld + end + end + return nil +end + +function Blend.blocks(f, code) +return f.byCode[code] or {} +end + +local function pointerKey(f, o) +local b = f.buf + if f.pointerSize == 8 then + if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then + return nil + end + return readstring(b, o, 8) + end + local v = f.u32(b, o) + return (v == 0 and{nil }or{v +})[1]end +Blend.pointerKey = pointerKey + +-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the +-- pointer comes from first (from = the block holding the pointer), as Blender's reader does +function Blend.resolve(f, addr, from) +if addr == nil then + return nil + end + local list = f.shared[addr] + if list and from then + for _, b in __iter(list) do + if b.owner == from.owner then + return b + end + end + end + return f.byAddr[addr] +end + +local function find(self, names) +local by = self.struct.byName + for _, name in __iter(names) do + local fld = by[name] + if fld then + return fld + end + end + return nil +end + +function View.has(self, ...) +return find(self, { ... }) ~= nil +end + +local function scalar(f, t, size, o) +local b = f.buf + if t == "float" then + return f.f32(b, o) + elseif t == "double" then + return f.f64(b, o) + elseif t == "int" or t == "int32_t" or t == "long" then + return (size == 8 and{(f.u32(b, o + (f.little and 0 or 4)) )}or{(f.i32(b, o) +)})[1] elseif t == "short" or t == "int16_t" then + return f.i16(b, o) + elseif t == "ushort" or t == "uint16_t" then + return f.u16(b, o) + elseif t == "uint" or t == "uint32_t" or t == "ulong" then + return f.u32(b, o) + elseif t == "int8_t" then + return readi8(b, o) + elseif t == "int64_t" or t == "uint64_t" then + local lo, hi = f.u32(b, o + (f.little and 0 or 4)), f.u32(b, o + (f.little and 4 or 0)) + if t == "int64_t" and hi >= 2147483648 then + return (hi - 4294967296) * 4294967296 + lo + end + return hi * 4294967296 + lo + end + return readu8(b, o) -- char, uchar, uint8_t, bool +end + +function View.get(self, ...) +local fld = find(self, { ... }) + if not fld then + return nil + end + local f = self.file + local o = self.offset + fld.offset + if o + fld.size > buffer.len(f.buf) then + return nil + end + if fld.pointer then + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false + end + return out + end + return pointerKey(f, o) + end + local t = fld.type + if PRIM[t] then + if fld.count == 1 then + return scalar(f, t, fld.elem, o) + end + if t == "char" then + local s = readstring(f.buf, o, fld.size) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1] end + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem) + end + return out + end + local s = f.dna.byName[t] + if not s then + return nil + end + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = view(f, s, o + k * s.size, self.block) + end + return out + end + return view(f, s, o, self.block) +end + +function View.num(self, ...) +local v = self:get(...) + return (type(v) == "number" and{v }or{nil +})[1]end + +function View.str(self, ...) +local v = self:get(...) + return (type(v) == "string" and{v }or{nil +})[1]end + +function View.vec(self, ...) +local v = self:get(...) + return (type(v) == "table" and type(v[1]) == "number" and{v }or{nil +})[1]end + +function View.sub(self, ...) +local v = self:get(...) + return (type(v) == "table" and getmetatable(v) == View and{v }or{nil +})[1]end + +function View.ptr(self, ...) +local fld = find(self, { ... }) + if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then + return nil + end + return pointerKey(self.file, self.offset + fld.offset) +end + +function View.target(self, ...) +return Blend.resolve(self.file, self:ptr(...), self.block) +end + +function View.deref(self, name, i, as) +local names= (type(name) == "table" and{name }or{{ name } +})[1] local fld = find(self, names) + if not fld or not fld.pointer then + return nil + end + local blk = self:target(fld.name) + if not blk then + return nil + end + local f = self.file + local sname = as or fld.type + if not as and (sname == "void" or not f.dna.byName[sname]) then + local own = f.dna.structs[blk.sdna + 1] + sname = (own and{own.name }or{sname +})[1] end + return Blend.struct(f, blk, i, sname) +end + +function View.array(self, name, as) +local first = self:deref(name, 0, as) + if not first or not first.block then + return {} + end + local blk = first.block +local s = first.struct + local n = (s.size > 0 and{(math.floor(blk.size / s.size ))}or{0 +})[1] local out = (table.create(n) ) +for k = 0, n - 1 do + out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) + end + return out +end + +function View.pointers(self, name, n) +local names= (type(name) == "table" and{name }or{{ name } +})[1] local fld = find(self, names) + if not fld or not fld.pointer then + return {} + end + local blk = self:target(fld.name) + if not blk then + return {} + end + local f = self.file + local ps = f.pointerSize + local count = math.floor(blk.size / ps +) if n then + count = math.min(count, n) + end + local out = table.create(count) + for k = 0, count - 1 do + out[k + 1] = pointerKey(f, blk.offset + k * ps) or false + end + return out +end + +function View.list(self, name, as, limit) +local names= (type(name) == "table" and{name }or{{ name } +})[1] local lb = self:sub(table.unpack(names)) + local out = {} + if not lb then + return out + end + local f = self.file + local addr = lb:ptr("first") + local seen = {} + local max = limit or 2 ^ 20 + while addr ~= nil and not seen[addr] and #out < max do + seen[addr] = true + local blk = Blend.resolve(f, addr, self.block) + if not blk then + break + end + local v = Blend.struct(f, blk, 0, as) + if not v then + break + end + table.insert(out, v) + addr = v:ptr("next") + if addr == nil and not v.struct.byName.next then + -- structs that start with an embedded header (ModifierData, ...) keep the link there + local head = v.struct.fields[1] + local sub = head and not head.pointer and f.dna.byName[head.type] + if sub then + addr = view(f, sub, v.offset + head.offset, v.block):ptr("next") + end + end + end + return out +end + +function View.data(self, ...) +local blk = self:target(...) + if not blk then + return nil, 0 + end + return blk.offset, blk.size +end + +function View.cstring(self, ...) +local blk = self:target(...) + if not blk then + return nil + end + local s = readstring(self.file.buf, blk.offset, blk.size) + local z = string.find(s, "\0", 1, true) + return (z and{(string.sub(s, 1, z - 1) )}or{s +})[1]end + +function View.idName(self) +local id = self:sub("id") + local n = (id and{(id:str("name") )}or{(self:str("name") +)})[1] if not n then + return nil + end + return string.sub(n, 3) +end + +return Blend +end __FILES["containers/Chunks"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and @@ -148774,6 +149525,2945 @@ return e[a + 1] > e[b + 1] return scene, nil, nil end +return Read +end +__FILES["model/blend"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Blend = __include("containers/Blend") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Read = __include("model/blend/Read") +local Anim = __include("model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. + + + + + + + + + + + + + + +function BlendFormat.sniff(r) +local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return inner and buffer.tostring(inner) == "BLENDER" and 1 or 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" and 1 or 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r, opts) +return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r, opts) +local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat +end +__FILES["model/blend/Anim"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = __include("containers/Blend") + +local Anim = {} + + + + + + + + + + + + + + + + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f, fc) +local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys= {} + for _, b in __iter(fc:array("bezt", "BezTriple")) do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in __iter(fc:array("fpt", "FPoint")) do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a, b) +return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f, adt) +if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list= act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in __iter(act:pointers("layer_array", act:num("layer_array_num"))) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in __iter(layer:pointers("strip_array", layer:num("strip_array_num"))) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in __iter(kd:pointers("channelbag_array", kd:num("channelbag_array_num"))) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in __iter(bag:pointers("fcurve_array", bag:num("fcurve_array_num"))) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out= {} + for _, fc in __iter(list) do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR= { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f, ipo, keyNames) +if not ipo then + return nil, nil + end + local out= {} + for _, icu in __iter(ipo:list("curve", "IpoCurve")) do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys= {} + for _, b in __iter(icu:array("bezt", "BezTriple")) do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = ((ipoMode == CONST or ipoMode == LIN )and{ipoMode }or{BEZ})[1], easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a, b) +return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = (icu:num("extrap") or 0) == 1 and 1 or 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0, p1, p2, p3, t) +local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a, b, x) +local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = (d ~= 0 and((t - (xt - x) / d ))or((-1 +))) t = (nt > lo and nt < hi and{nt }or{((lo + hi) / 2 +)})[1] end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t, b, c, d) +t =t/ d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t =t- 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t =t- 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t =t- 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo, t, a) +if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = (a.period > 0 and((a.period / 10 ))or(0.3 +)) local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t =t- 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a, b, x) +local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = (a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC )and 2 or 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c, x) +local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = math.floor((lo + hi) / 2 +) if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves) +local lo, hi = math.huge, -math.huge + for _, c in __iter(curves) do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path) +local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim +end +__FILES["model/blend/Material"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = __include("containers/Blend") +local Types = __include("Types") + +local Material = {} + + + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b, o, n, path) +if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return (ext and{byExt[ext] }or{nil +})[1]end + +local function fetch(ctx, uri) +local opts = ctx.opts + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1]end + +local function texture(ctx, img, sampler) +local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = (pf0 and pf0.size >= 256 and{(img:str(pf0.name) )}or{nil +})[1] local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in __iter(img:list("packedfiles", "ImagePackedFile")) do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex= { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + + + + +local function graph(tree) +local g= { nodes = {}, links = {} } + for _, n in __iter(tree:list("nodes", "bNode")) do + local node= { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in __iter(n:list("inputs", "bNodeSocket")) do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in __iter(n:list("outputs", "bNodeSocket")) do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in __iter(tree:list("links", "bNodeLink")) do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n, ...) +for _, k in __iter({ ... }) do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g, s) +if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s, kind) +if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx, g, uvNames, s, through) +local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, (ref and{n }or{tn +})[1] end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler= {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, (custom and{sampler }or{nil})[1]) + if not t then + return nil, n + end + local ref= { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g) +local first= nil + for _, n in __iter(g.nodes) do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m, color, strength) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions ).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx, mv) +local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras= {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g= nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g ) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = (nnode and{value(nnode.inputs.Strength, "float") or 1 }or{1 +})[1] m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material +end +__FILES["model/blend/Mesh"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = __include("containers/Blend") + +local Mesh = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local CD_KIND= { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND= { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN= { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE= { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = (c <= 0.04045 and((c / 12.92 ))or((((c + 0.055) / 1.055) ^ 2.4 +)))end +Mesh.SRGB = SRGB + +local function customData(f, me, names, domain, out) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = (st and{st.size }or{SIZE[kind] or 0 +})[1] if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f, me, out) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, single and"AttributeSingle" or"AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers, domain, kind, name) +for _, L in __iter(layers) do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f, me, field, kind, domain) +local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f, L) +local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = k == "short2" and 2 or((k == "int8" or k == "bool" or k == "bytecolor" )and 1 or 4 +) return function(i, c) +local at = (single and 0 or i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f, L, field) +local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i, c) +local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at =at+ o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f, tess, nc, offset, bytes, faceStride, first, cornerStride, swap, opaque) +local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (math.floor(tc / 4)) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, opaque and 1 or aa / 255) + end + end + return d +end + +function Mesh.layers(f, me) +local layers= {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me, ...) +local v = me:num(...) + return (v and v > 0 and{v }or{0 +})[1]end + + + +function Mesh.read(f, me, limits) +local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get= nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_, _) +return 0 + end + end + local g = get +for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly= { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = P and P.cdtype == nil and"storage" or(P and"attributes" or"mpoly"), + layers = layers, + } + local corner= {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at =at+ math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = (cv and{(reader(f, cv) )}or{(ml and{(fieldReader(f, ml, "v") )}or{nil +})[1]})[1] if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w =w+ 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = (cv and{(reader(f, cv) )}or{(ml and{(fieldReader(f, ml, "v") )}or{nil +})[1]})[1] if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = (mi and{(reader(f, mi) )}or{(mp and{(fieldReader(f, mp, "mat_nr") )}or{nil +})[1]})[1] local flag = (mp and{(fieldReader(f, mp, "flag") )}or{nil +})[1] local sr = (sf and{(reader(f, sf) )}or{nil +})[1] for i = 0, np - 1 do + buffer.writei32(mats, i * 4, (mr and{(mr(i, 0) )}or{0})[1]) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, s and 1 or 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = (v[4] )(i, 0) ~= 0 and 4 or 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] )(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at =at+ k + buffer.writei32(mats, i * 4, (mr and{(mr(i, 0) )}or{0})[1]) + buffer.writeu8(smooth, i, flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 and 1 or 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap= corner.remap + local function src(i) +return (remap and{(buffer.readu32(remap, i * 4) )}or{i +})[1] end + for _, L in __iter(layers) do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = (L.kind == "float2" and{(reader(f, L) )}or{(fieldReader(f, L, "uv") +)})[1] if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess +if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = math.floor(tc / 4), tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess +local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(math.floor(tc / 4), (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(math.floor(tc / 4), (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in __iter(poly.uvs) do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in __iter(layers) do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = (L.domain == "corner" and{nc }or{nv +})[1] local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = (L.domain == "corner" and{(src(i) )}or{i +})[1] for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = (c == 3 and{(x / 255 )}or{SRGB[math.clamp(x, 0, 255) + 1] +})[1] end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = (st and{st.size }or{4 +})[1] table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess , nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess , nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess , nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in __iter(layers) do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = (free.domain == "corner" and{(src(i) )}or{(free.domain == "face" and{fi }or{(buffer.readu32(poly.cornerVert, i * 4) +)})[1]})[1] for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i)return er(i, 0) end + v2 = function(i)return er(i, 1) end + sharp = function(i)return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i)return a(i, 0) end + v2 = function(i)return b(i, 0) end + local ser = (se and{(reader(f, se) )}or{nil +})[1] sharp = function(i) +if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = (table.create(nv) ) +for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, math.floor(blk.size / mw.size)) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index + + +function Mesh.shapes(f, me, nv) +local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out= {} + local ref= nil + for i, kb in __iter(blocks) do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, math.floor(n / 4 )- 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh +end +__FILES["model/blend/Normals"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + + + +local function dir(pos, from, to) +local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly, lnor, fanId, fans, _ang) +local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals +local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done= {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard =guard+ 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = (nq and{(readu32(nxt, nq * 4) )}or{c +})[1] if q < m then + m = q + end + guard =guard+ 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in __iter(edges) do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha =alpha+ acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count =count+ 1 + end + end + alpha =alpha/ math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = (cyclic and{edges[2] }or{edges[#edges] +})[1] local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, (cyclic and{refEdge }or{edges[1]})[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in __iter(corners) do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = ((a > 0 and{alpha }or{(TAU - alpha)})[1]) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = ((b > 0 and{beta }or{(TAU - beta)})[1]) * b + x =x+ sa * (rx * cos(be) + tx * sin(be)) + y =y+ sa * (ry * cos(be) + ty * sin(be)) + z =z+ sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals +end +__FILES["model/blend/Prim"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") +local Rig = __include("codecs/model/Rig") +local Normals = __include("model/blend/Normals") +local MeshT = __include("model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + + + + + + + + +local function face(poly, fi) +return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos, v) +return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly) +local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = (c + 1 < s1 and((c + 1 ))or(s0 +)) local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx =nx+ (y1 - y2) * (z1 + z2) + ny =ny+ (z1 - z2) * (x1 + x2) + nz =nz+ (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = (c > s0 and((c - 1 ))or((s1 - 1 +))) local nc = (c + 1 < s1 and((c + 1 ))or(s0 +)) local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges + + + + + + + + + + +function Prim.fans(poly, fn) +local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, (c + 1 < s1 and((c + 1 ))or(s0))) + writeu32(prv, c * 4, (c > s0 and((c - 1 ))or((s1 - 1)))) + writeu32(fc, c * 4, fi) + end + end + local first= {} + local second= {} + local uses= {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across= {} + local smooth = poly.faceSmooth + local cosLimit = (poly.autoSmooth and{(math.cos(poly.autoSmooth) )}or{nil +})[1] for key, u in __iter(uses) do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly, fn, ang, fans) +local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c) +local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a, b) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in __iter(fans.across) do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, (l > 1e-20 and{(x / l )}or{(readf32(fn, fi * 12))})[1]) + writef32(out, c * 12 + 4, (l > 1e-20 and{(y / l )}or{(readf32(fn, fi * 12 + 4))})[1]) + writef32(out, c * 12 + 8, (l > 1e-20 and{(z / l )}or{(readf32(fn, fi * 12 + 8))})[1]) + end + return out, fanId +end + +function Prim.normals(poly) +local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals +end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly, fi, fnx, fny, fnz, out) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = (table.create(n * 2) ) +for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, (sign < 0 and{(-u )}or{u})[1]) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t, comps) +local n = math.floor(#t / comps +) local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints + + +function Prim.build(poly, slots, opts, skin, shapes, ref) +local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = (withNormals and poly.nf > 0 and{(Prim.normals(poly) )}or{nil +})[1] local fn = (poly.nf > 0 and{(Prim.geometry(poly)) }or{(buffer.create(0) +)})[1] local nslots = math.max(#slots, 1) + local groups= {} + local order= {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors, pointColors= {}, {} + for _, c in __iter(poly.colors) do + table.insert((c.domain == "corner" and{cornerColors }or{pointColors})[1], c) + end + local keyBytes = 4 + (nrm and 12 or 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh= { name = poly.name, primitives = {} } + local sources= {} + local cv = poly.cornerVert + for _, m in __iter(order) do + local faces = groups[m] + local map= {} + local vsrc= {} + local corners= {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in __iter(faces) do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o =o+ 12 + end + for _, uv in __iter(poly.uvs) do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o =o+ 8 + end + for _, col in __iter(cornerColors) do + buffer.copy(scratch, o, col.data, c * 16, 16) + o =o+ 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs= {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in __iter(poly.uvs) do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, (flipV and((1 - v ))or(v))) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in __iter(poly.colors) do + local C = buffer.create(n * 16) + for i = 1, n do + local e = (col.domain == "corner" and{corners[i] }or{vsrc[i] +})[1] buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci =ci+ 1 + end + if skin and poly.weights then + local lists = (table.create(n) ) +for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k] ] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim= { attributes = attrs, mode = "triangles" } + local idx= {} + if triangulateOn then + for _, fi in __iter(faces) do + local tri= {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in __iter(tri) do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in __iter(faces) do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in __iter(idx) do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets= {} + for k, s in __iter(shapes) do + if k ~= ref then + local t = (table.create(n * 3) ) +for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } ) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in __iter(shapes) do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in __iter(order) do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim +end +__FILES["model/blend/Read"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = __include("containers/Blend") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Mesh = __include("model/blend/Mesh") +local Prim = __include("model/blend/Prim") +local Anim = __include("model/blend/Anim") +local Material = __include("model/blend/Material") + +local Read = {} + +local Scene = Types.Scene + + + + + + + + + + + + + + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME= { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q) +if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode, eul, quat, axis, angle) +if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m, s) +local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do +do local __DARKLUA_VAR=c * 4 + k r[__DARKLUA_VAR]=r[__DARKLUA_VAR]* s[c + 1] +end end + end + return r +end + +local function trs(t, r, s) +local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + + + +local function objectProps(ob) -- fields missing from old files take their neutral value + +local function v(fallback, ...) +local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p= { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc) +if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n, ...) +local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p) +local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node, m) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v, ...) +local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end +-- ------------------------------------------------------------------------------------------------ scene + + + + + + + + + + + + + + + + + + + +local function worldOf(ctx, node) +local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = (p and{(Mat4.mul(worldOf(ctx, p), m) )}or{m +})[1] ctx.world[node] = w + return w +end + +local function addNode(ctx, node, parent) +table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx, ob, node) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames= {} + if pose then + for _, pc in __iter(pose:list("chanbase", "bPoseChannel")) do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list, parentJoint, parentRest, depth) + if depth > 256 then + return + end + for _, bone in __iter(list) do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = (parentRest and{(Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) )}or{rest +})[1] local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode= { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = (parentJoint and{info.joints[parentJoint] }or{node +})[1] local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx, ob, node) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c +if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } +else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } +end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx, ob, node) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy =energy* 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = (t == LA_SUN or t == LA_HEMI )and 1 or 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in __iter((tree and{(tree:list("nodes", "bNode") )}or{{} })[1])do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in __iter(n:list("inputs", "bNodeSocket")) do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l +if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } +elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } +elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } +else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = t == LA_AREA and"area" or tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx, ob, me) +local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = (useOb and{obMats[i] }or{meMats[i] +})[1] local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx , mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx, ob) +for _, md in __iter(ob:list("modifiers")) do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob, me) +local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in __iter(list) do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx, ob, node) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin= nil + if armInfo then + local joints = {} + for gi, name in __iter(groupNames(ob, me)) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights ) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx) + for _, p in __iter(ctx.pending) do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx, ob, under, depth) +local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode= under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node= { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras= { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in __iter(ob:list("modifiers")) do + table.insert(mods, { name = md:sub("modifier") and ((md:sub("modifier") )):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props, curves, frame, prefix, name) +local p= {} + for k, v in __iter(props) do + p[k] = table.clone(v) + end + for _, c in __iter(curves) do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end + + +local function frames(lo, hi, step) +local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f =f+ step + end + table.insert(out, hi) + return out +end + + + +local function animations(ctx) + local f = ctx.f + local jobs= {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner= {} + for _, ob in __iter(ctx.objView) do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in __iter(ctx.meta.shapeKeys) do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves= found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in __iter(sk.shapes) do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in __iter(mc or {}) do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list= curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in __iter(ctx.scene.nodes) do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves , action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a, b) +return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in __iter(jobs) do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction= {} + for _, j in __iter(jobs) do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } +byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in __iter(fs) do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node +local track = { translation = {}, rotation = {}, scale = {} } + local last= nil + for _, fr in __iter(fs) do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in __iter(j.curves) do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who] ] = true + end + end + for b in __iter(touched) do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last= nil + for _, fr in __iter(fs) do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks , nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in __iter(fs) do + local k = 0 + for si, s in __iter(sk.shapes) do + if si ~= sk.ref then + local v = s.value + for _, c in __iter(j.curves) do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k =k+ 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in __iter(times) do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in __iter(j.nodes) do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" , input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" }, + } }) + end + end + for _, a in __iter(tmp.animations) do + for _, ch in __iter(a.channels) do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f, name) +local scenes = Blend.blocks(f, "SC") + if name then + for _, b in __iter(scenes) do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return (scenes[1] and{(Blend.struct(f, scenes[1], 0, "Scene") )}or{nil +})[1]end + +function Read.scene(f, opts) +local o= opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta= { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx= { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order= {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = (fps > 0 and{fps }or{24 +})[1] meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col, under, depth) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in __iter(col:list("gobject", "CollectionObject")) do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in __iter(col:list("children", "CollectionChild")) do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn= nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in __iter(sc:list("base", "Base")) do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in __iter(Blend.blocks(f, "OB")) do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder= {} + for _, e in __iter(order) do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in __iter(order) do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, (u and u > 0 and{u }or{nil})[1], 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + return Read end __FILES["model/bsp"] = function() diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index 8d39af3..1efad02 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -1,575 +1,583 @@ [ [660, "src/Rosetta/init.luau"], [1504, "src/Rosetta/Registry.luau"], -[3757, "src/Rosetta/Types.luau"], -[4840, "src/Rosetta/archive/7z/init.luau"], -[5225, "src/Rosetta/archive/7z/Header.luau"], -[5752, "src/Rosetta/archive/adf/init.luau"], -[6034, "src/Rosetta/archive/applesingle/init.luau"], -[6220, "src/Rosetta/archive/ar/init.luau"], -[6623, "src/Rosetta/archive/arj/init.luau"], -[6833, "src/Rosetta/archive/binhex/init.luau"], -[7082, "src/Rosetta/archive/br/init.luau"], -[7157, "src/Rosetta/archive/bz2/init.luau"], -[7221, "src/Rosetta/archive/cab/init.luau"], -[7634, "src/Rosetta/archive/cab/Sum.luau"], -[7675, "src/Rosetta/archive/cpio/init.luau"], -[7843, "src/Rosetta/archive/d64/init.luau"], -[8257, "src/Rosetta/archive/fat/init.luau"], -[8379, "src/Rosetta/archive/grp/init.luau"], -[8493, "src/Rosetta/archive/gzip/init.luau"], -[8678, "src/Rosetta/archive/iso/init.luau"], -[8750, "src/Rosetta/archive/lha/init.luau"], -[9175, "src/Rosetta/archive/lz4/init.luau"], -[9519, "src/Rosetta/archive/macbinary/init.luau"], -[9717, "src/Rosetta/archive/mpq/init.luau"], -[10123, "src/Rosetta/archive/mpq/Crypt.luau"], -[10188, "src/Rosetta/archive/pak/init.luau"], -[10322, "src/Rosetta/archive/rpm/init.luau"], -[10646, "src/Rosetta/archive/tar/init.luau"], -[10764, "src/Rosetta/archive/uu/init.luau"], -[11034, "src/Rosetta/archive/vpk/init.luau"], -[11345, "src/Rosetta/archive/vswap/init.luau"], -[11615, "src/Rosetta/archive/wad/init.luau"], -[12069, "src/Rosetta/archive/wad/Picture.luau"], -[12171, "src/Rosetta/archive/xz/init.luau"], -[12271, "src/Rosetta/archive/yenc/init.luau"], -[12543, "src/Rosetta/archive/z/init.luau"], -[12639, "src/Rosetta/archive/zip/init.luau"], -[12858, "src/Rosetta/archive/zoo/init.luau"], -[13054, "src/Rosetta/archive/zst/init.luau"], -[13118, "src/Rosetta/audio/aac/init.luau"], -[13324, "src/Rosetta/audio/ac3/init.luau"], -[13470, "src/Rosetta/audio/adpcm/init.luau"], -[13615, "src/Rosetta/audio/adx/init.luau"], -[13846, "src/Rosetta/audio/aiff/init.luau"], -[14237, "src/Rosetta/audio/ape/init.luau"], -[14365, "src/Rosetta/audio/au/init.luau"], -[14526, "src/Rosetta/audio/brstm/init.luau"], -[14817, "src/Rosetta/audio/caf/init.luau"], -[15479, "src/Rosetta/audio/flac/init.luau"], -[15627, "src/Rosetta/audio/flac/Meta.luau"], -[15849, "src/Rosetta/audio/flac/Stream.luau"], -[16219, "src/Rosetta/audio/m4a/init.luau"], -[16553, "src/Rosetta/audio/mp3/init.luau"], -[16813, "src/Rosetta/audio/mp3/Index.luau"], -[17004, "src/Rosetta/audio/mp3/Stream.luau"], -[17231, "src/Rosetta/audio/mp3/Tags.luau"], -[17543, "src/Rosetta/audio/mpc/init.luau"], -[17637, "src/Rosetta/audio/opus/init.luau"], -[18015, "src/Rosetta/audio/opus/Encode.luau"], -[18126, "src/Rosetta/audio/qoa/init.luau"], -[18306, "src/Rosetta/audio/tta/init.luau"], -[18424, "src/Rosetta/audio/vag/init.luau"], -[18647, "src/Rosetta/audio/voc/init.luau"], -[18922, "src/Rosetta/audio/vorbis/init.luau"], -[19376, "src/Rosetta/audio/vorbis/Encode.luau"], -[20189, "src/Rosetta/audio/wav/init.luau"], -[20810, "src/Rosetta/audio/wav/Codecs.luau"], -[20976, "src/Rosetta/audio/wavpack/init.luau"], -[21183, "src/Rosetta/cad/step/init.luau"], -[21565, "src/Rosetta/cad/step/Brep.luau"], -[21800, "src/Rosetta/cad/step/Parse.luau"], -[22357, "src/Rosetta/cad/step/Write.luau"], -[22605, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22924, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23807, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24142, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24301, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25186, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25287, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26041, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26343, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26577, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26996, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27408, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27623, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28384, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28481, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28492, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29441, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30038, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30234, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30483, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31441, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31660, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31844, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32053, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32399, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32413, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32472, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34075, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34367, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34752, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35393, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35534, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35760, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36105, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36999, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37377, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37391, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39238, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40303, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40363, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40823, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41160, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41393, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43429, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43803, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44066, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44363, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44645, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45004, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45058, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45201, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45714, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46495, "src/Rosetta/codecs/audio/Stream.luau"], -[46656, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47138, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47416, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47585, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47713, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49701, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49817, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49934, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50186, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50199, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50583, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51149, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51570, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51609, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51661, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51883, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53338, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53401, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53488, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54457, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55325, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55373, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55889, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56215, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56635, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57070, "src/Rosetta/codecs/compress/Explode.luau"], -[57266, "src/Rosetta/codecs/compress/Lz4.luau"], -[57535, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58139, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58679, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58717, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59190, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59366, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59634, "src/Rosetta/codecs/compress/Lzx.luau"], -[60068, "src/Rosetta/codecs/compress/PackBits.luau"], -[60158, "src/Rosetta/codecs/compress/Quantum.luau"], -[60395, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60699, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60768, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60825, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61783, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61935, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62217, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62228, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62442, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62686, "src/Rosetta/codecs/font/Bitmap.luau"], -[62887, "src/Rosetta/codecs/font/Cff/init.luau"], -[63528, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63678, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63992, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64384, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64886, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64993, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65482, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65911, "src/Rosetta/codecs/image/Blend.luau"], -[66290, "src/Rosetta/codecs/image/Dct/init.luau"], -[66671, "src/Rosetta/codecs/image/Etc.luau"], -[66969, "src/Rosetta/codecs/image/Half.luau"], -[67038, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67392, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67800, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68037, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68797, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69678, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70124, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70202, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70269, "src/Rosetta/codecs/image/Miptex.luau"], -[70485, "src/Rosetta/codecs/image/Pixels.luau"], -[70805, "src/Rosetta/codecs/image/Quantize/init.luau"], -[71264, "src/Rosetta/codecs/image/Raster.luau"], -[71961, "src/Rosetta/codecs/image/Texel.luau"], -[72334, "src/Rosetta/codecs/image/Texture.luau"], -[72479, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72609, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74565, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74824, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[75073, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[75192, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75296, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[76149, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[77101, "src/Rosetta/codecs/image/Yuv.luau"], -[77369, "src/Rosetta/codecs/model/Brush.luau"], -[78009, "src/Rosetta/codecs/model/Displacement.luau"], -[78158, "src/Rosetta/codecs/model/DoomMap/init.luau"], -[78603, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], -[78853, "src/Rosetta/codecs/model/Draco/init.luau"], -[79185, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[79654, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[80843, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[80992, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[81351, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[82313, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[82787, "src/Rosetta/codecs/model/Mat4.luau"], -[83046, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[83574, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[84126, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[84205, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[84312, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[84518, "src/Rosetta/codecs/model/Patch.luau"], -[84642, "src/Rosetta/codecs/model/Polygon.luau"], -[84876, "src/Rosetta/codecs/model/Rbx/init.luau"], -[85113, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[85867, "src/Rosetta/codecs/model/Rig.luau"], -[86110, "src/Rosetta/codecs/model/Sampler.luau"], -[86270, "src/Rosetta/codecs/model/SourceAnim.luau"], -[86491, "src/Rosetta/codecs/model/Vrml/init.luau"], -[86639, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[87213, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[87376, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[88125, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[88647, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[89374, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[89606, "src/Rosetta/codecs/text/Json/init.luau"], -[89875, "src/Rosetta/codecs/text/Json/Decode.luau"], -[90289, "src/Rosetta/codecs/text/Json/Encode.luau"], -[90591, "src/Rosetta/codecs/text/KeyValues/init.luau"], -[91161, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], -[91467, "src/Rosetta/codecs/text/Lexer/init.luau"], -[91599, "src/Rosetta/codecs/text/Nbt/init.luau"], -[91952, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[92644, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[93284, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[93522, "src/Rosetta/codecs/text/Text/init.luau"], -[93613, "src/Rosetta/codecs/text/Url/init.luau"], -[93818, "src/Rosetta/codecs/text/Xml/init.luau"], -[94221, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[94961, "src/Rosetta/codecs/video/Dsp.luau"], -[95684, "src/Rosetta/codecs/video/H263/init.luau"], -[95840, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[96698, "src/Rosetta/codecs/video/H263/Tables.luau"], -[96901, "src/Rosetta/codecs/video/H264/init.luau"], -[97274, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[97549, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[98680, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[99448, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[99706, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[100715, "src/Rosetta/codecs/video/H264/Inter.luau"], -[100969, "src/Rosetta/codecs/video/H264/Intra.luau"], -[101376, "src/Rosetta/codecs/video/H264/Mb.luau"], -[102282, "src/Rosetta/codecs/video/H264/Params.luau"], -[102729, "src/Rosetta/codecs/video/H264/Slice.luau"], -[102980, "src/Rosetta/codecs/video/H264/Tables.luau"], -[103021, "src/Rosetta/codecs/video/H264/Transform.luau"], -[103186, "src/Rosetta/codecs/video/Legacy/init.luau"], -[103384, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[103681, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[104048, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[104166, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[104274, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[104547, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[104942, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[105119, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[105131, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[105498, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[107005, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[107144, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[107282, "src/Rosetta/codecs/video/Theora/init.luau"], -[107545, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[108809, "src/Rosetta/codecs/video/Theora/Header.luau"], -[109172, "src/Rosetta/codecs/video/Video/init.luau"], -[109729, "src/Rosetta/codecs/video/Video/Source.luau"], -[110014, "src/Rosetta/containers/Archive.luau"], -[110281, "src/Rosetta/containers/AudioWrap.luau"], -[110784, "src/Rosetta/containers/Avi/init.luau"], -[111336, "src/Rosetta/containers/Chunks.luau"], -[111471, "src/Rosetta/containers/Cpio.luau"], -[111899, "src/Rosetta/containers/Demux.luau"], -[112174, "src/Rosetta/containers/Ebml/init.luau"], -[112487, "src/Rosetta/containers/Fat.luau"], -[113175, "src/Rosetta/containers/Iso9660.luau"], -[113680, "src/Rosetta/containers/IsoBmff/init.luau"], -[113850, "src/Rosetta/containers/IsoBmff/Box.luau"], -[114038, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[114883, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[115404, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[115920, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[116037, "src/Rosetta/containers/MacFile.luau"], -[116186, "src/Rosetta/containers/MpegEs.luau"], -[116352, "src/Rosetta/containers/MpegPs/init.luau"], -[116572, "src/Rosetta/containers/MpegTs/init.luau"], -[117364, "src/Rosetta/containers/Ogg/init.luau"], -[117789, "src/Rosetta/containers/Ogg/Mux.luau"], -[117984, "src/Rosetta/containers/Ogg/Page.luau"], -[118153, "src/Rosetta/containers/Riff/init.luau"], -[118470, "src/Rosetta/containers/Tar.luau"], -[118884, "src/Rosetta/containers/Zip/init.luau"], -[119516, "src/Rosetta/core/Adler32.luau"], -[119562, "src/Rosetta/core/Base64.luau"], -[119721, "src/Rosetta/core/Bits.luau"], -[120014, "src/Rosetta/core/Bytes.luau"], -[120541, "src/Rosetta/core/Crc16.luau"], -[120593, "src/Rosetta/core/Crc32.luau"], -[120705, "src/Rosetta/core/Err.luau"], -[120787, "src/Rosetta/core/Input.luau"], -[120863, "src/Rosetta/core/Md5.luau"], -[121022, "src/Rosetta/core/Sniff.luau"], -[121051, "src/Rosetta/data/cbor/init.luau"], -[121150, "src/Rosetta/data/cbor/Codec.luau"], -[121719, "src/Rosetta/data/csv/init.luau"], -[122031, "src/Rosetta/data/ini/init.luau"], -[122277, "src/Rosetta/data/json/init.luau"], -[122369, "src/Rosetta/data/msgpack/init.luau"], -[122458, "src/Rosetta/data/msgpack/Codec.luau"], -[122900, "src/Rosetta/data/nbt/init.luau"], -[122959, "src/Rosetta/data/plist/init.luau"], -[123265, "src/Rosetta/data/plist/Binary.luau"], -[123532, "src/Rosetta/data/snbt/init.luau"], -[123595, "src/Rosetta/data/toml/init.luau"], -[123662, "src/Rosetta/data/toml/Decode.luau"], -[124290, "src/Rosetta/data/toml/Encode.luau"], -[124499, "src/Rosetta/data/vdf/init.luau"], -[124600, "src/Rosetta/data/xml/init.luau"], -[124656, "src/Rosetta/data/yaml/init.luau"], -[124729, "src/Rosetta/data/yaml/Emit.luau"], -[125019, "src/Rosetta/data/yaml/Parse.luau"], -[126312, "src/Rosetta/font/bdf/init.luau"], -[126601, "src/Rosetta/font/bmfont/init.luau"], -[127028, "src/Rosetta/font/bmfont/Parse.luau"], -[127481, "src/Rosetta/font/eot/init.luau"], -[127713, "src/Rosetta/font/fon/init.luau"], -[127996, "src/Rosetta/font/hershey/init.luau"], -[128191, "src/Rosetta/font/pcf/init.luau"], -[128471, "src/Rosetta/font/psf/init.luau"], -[128791, "src/Rosetta/font/ttf/init.luau"], -[128842, "src/Rosetta/font/type1/init.luau"], -[129201, "src/Rosetta/font/type1/Charstring.luau"], -[129479, "src/Rosetta/font/woff/init.luau"], -[129611, "src/Rosetta/font/woff2/init.luau"], -[129668, "src/Rosetta/font/woff2/Rebuild.luau"], -[130208, "src/Rosetta/host/init.luau"], -[130253, "src/Rosetta/host/Love.luau"], -[130396, "src/Rosetta/host/LuaJIT.luau"], -[130446, "src/Rosetta/host/Luau.luau"], -[130469, "src/Rosetta/host/Roblox.luau"], -[130828, "src/Rosetta/image/ani/init.luau"], -[131008, "src/Rosetta/image/art/init.luau"], -[131496, "src/Rosetta/image/blp/init.luau"], -[131754, "src/Rosetta/image/bmp/init.luau"], -[132169, "src/Rosetta/image/dds/init.luau"], -[132652, "src/Rosetta/image/exr/init.luau"], -[133412, "src/Rosetta/image/exr/Codec.luau"], -[133523, "src/Rosetta/image/exr/Piz.luau"], -[133880, "src/Rosetta/image/gif/init.luau"], -[134396, "src/Rosetta/image/gif/Decode.luau"], -[134459, "src/Rosetta/image/hdr/init.luau"], -[134688, "src/Rosetta/image/hdr/Codec.luau"], -[134899, "src/Rosetta/image/icns/init.luau"], -[135230, "src/Rosetta/image/ico/init.luau"], -[135507, "src/Rosetta/image/ico/Dib.luau"], -[135602, "src/Rosetta/image/ilbm/init.luau"], -[135921, "src/Rosetta/image/jpeg/init.luau"], -[136057, "src/Rosetta/image/ktx/init.luau"], -[136717, "src/Rosetta/image/pcx/init.luau"], -[136981, "src/Rosetta/image/png/init.luau"], -[137561, "src/Rosetta/image/png/Apng.luau"], -[137641, "src/Rosetta/image/png/Decode.luau"], -[137881, "src/Rosetta/image/png/Encode.luau"], -[138036, "src/Rosetta/image/pnm/init.luau"], -[138414, "src/Rosetta/image/pnm/Codec.luau"], -[138691, "src/Rosetta/image/qoi/init.luau"], -[138813, "src/Rosetta/image/qoi/Codec.luau"], -[138963, "src/Rosetta/image/sgi/init.luau"], -[139248, "src/Rosetta/image/sunras/init.luau"], -[139494, "src/Rosetta/image/tga/init.luau"], -[139764, "src/Rosetta/image/tga/Codec.luau"], -[139916, "src/Rosetta/image/tiff/init.luau"], -[140743, "src/Rosetta/image/tiff/Pixels.luau"], -[141133, "src/Rosetta/image/tim/init.luau"], -[141375, "src/Rosetta/image/vtf/init.luau"], -[141610, "src/Rosetta/image/webp/init.luau"], -[142220, "src/Rosetta/image/webp/Alpha.luau"], -[142296, "src/Rosetta/image/webp/Anim.luau"], -[142451, "src/Rosetta/image/xbm/init.luau"], -[142612, "src/Rosetta/image/xpm/init.luau"], -[142880, "src/Rosetta/image/xpm/Names.luau"], -[142936, "src/Rosetta/layered/aseprite/init.luau"], -[143674, "src/Rosetta/layered/ora/init.luau"], -[143961, "src/Rosetta/layered/psd/init.luau"], -[144696, "src/Rosetta/layered/psd/Channels.luau"], -[145048, "src/Rosetta/model/3ds/init.luau"], -[145131, "src/Rosetta/model/3ds/Build.luau"], -[145778, "src/Rosetta/model/3ds/Read.luau"], -[146274, "src/Rosetta/model/3ds/Write.luau"], -[147079, "src/Rosetta/model/3mf/init.luau"], -[147161, "src/Rosetta/model/3mf/Read.luau"], -[147749, "src/Rosetta/model/3mf/Write.luau"], -[148154, "src/Rosetta/model/b3d/init.luau"], -[148209, "src/Rosetta/model/b3d/Read.luau"], -[148780, "src/Rosetta/model/bsp/init.luau"], -[148925, "src/Rosetta/model/bsp/Brush.luau"], -[149188, "src/Rosetta/model/bsp/Quake3.luau"], -[149416, "src/Rosetta/model/buildmap/init.luau"], -[149688, "src/Rosetta/model/buildmap/Geometry.luau"], -[150091, "src/Rosetta/model/d3map/init.luau"], -[150373, "src/Rosetta/model/d3map/Parse.luau"], -[150571, "src/Rosetta/model/dae/init.luau"], -[150760, "src/Rosetta/model/dae/Math.luau"], -[150807, "src/Rosetta/model/dae/Read.luau"], -[152657, "src/Rosetta/model/dae/Write.luau"], -[153026, "src/Rosetta/model/fbx/init.luau"], -[153174, "src/Rosetta/model/fbx/Ascii.luau"], -[153444, "src/Rosetta/model/fbx/Binary.luau"], -[153899, "src/Rosetta/model/fbx/Read.luau"], -[155261, "src/Rosetta/model/fbx/Write.luau"], -[156246, "src/Rosetta/model/fbx/Xform.luau"], -[156287, "src/Rosetta/model/gltf/init.luau"], -[156524, "src/Rosetta/model/gltf/Pack.luau"], -[156593, "src/Rosetta/model/gltf/Read.luau"], -[157324, "src/Rosetta/model/gltf/Write.luau"], -[158004, "src/Rosetta/model/iqm/init.luau"], -[158080, "src/Rosetta/model/iqm/Read.luau"], -[158435, "src/Rosetta/model/iqm/Write.luau"], -[159122, "src/Rosetta/model/ldraw/init.luau"], -[159200, "src/Rosetta/model/ldraw/Colors.luau"], -[159518, "src/Rosetta/model/ldraw/Read.luau"], -[160095, "src/Rosetta/model/lwo/init.luau"], -[160171, "src/Rosetta/model/lwo/Build.luau"], -[160633, "src/Rosetta/model/lwo/Parse.luau"], -[161176, "src/Rosetta/model/map/init.luau"], -[161493, "src/Rosetta/model/map/Build.luau"], -[161736, "src/Rosetta/model/map/Parse.luau"], -[162121, "src/Rosetta/model/map/Write.luau"], -[162267, "src/Rosetta/model/mca/init.luau"], -[162609, "src/Rosetta/model/mca/Chunk.luau"], -[162742, "src/Rosetta/model/mca/Lz4Block.luau"], -[162812, "src/Rosetta/model/md2/init.luau"], -[163011, "src/Rosetta/model/md3/init.luau"], -[163239, "src/Rosetta/model/md5/init.luau"], -[163320, "src/Rosetta/model/md5/Read.luau"], -[163753, "src/Rosetta/model/mdl/init.luau"], -[163835, "src/Rosetta/model/mdl/HalfLife.luau"], -[164139, "src/Rosetta/model/mdl/Quake.luau"], -[164357, "src/Rosetta/model/ms3d/init.luau"], -[164429, "src/Rosetta/model/ms3d/Read.luau"], -[164875, "src/Rosetta/model/ms3d/Write.luau"], -[165344, "src/Rosetta/model/obj/init.luau"], -[166086, "src/Rosetta/model/obj/Mtl.luau"], -[166373, "src/Rosetta/model/off/init.luau"], -[166835, "src/Rosetta/model/ply/init.luau"], -[167940, "src/Rosetta/model/ply/Binary.luau"], -[168141, "src/Rosetta/model/pmx/init.luau"], -[168210, "src/Rosetta/model/pmx/Build.luau"], -[168506, "src/Rosetta/model/pmx/Pmd.luau"], -[168841, "src/Rosetta/model/pmx/Read.luau"], -[169245, "src/Rosetta/model/proc/init.luau"], -[169627, "src/Rosetta/model/qb/init.luau"], -[170020, "src/Rosetta/model/rbxm/init.luau"], -[170612, "src/Rosetta/model/rbxmx/init.luau"], -[171265, "src/Rosetta/model/robloxmesh/init.luau"], -[171924, "src/Rosetta/model/robloxmesh/Parse.luau"], -[172381, "src/Rosetta/model/robloxmesh/Write.luau"], -[172490, "src/Rosetta/model/schematic/init.luau"], -[172811, "src/Rosetta/model/schematic/Common.luau"], -[172931, "src/Rosetta/model/schematic/Litematic.luau"], -[173142, "src/Rosetta/model/schematic/Mcedit.luau"], -[173386, "src/Rosetta/model/schematic/Sponge.luau"], -[173515, "src/Rosetta/model/smd/init.luau"], -[173582, "src/Rosetta/model/smd/Read.luau"], -[173851, "src/Rosetta/model/smd/Write.luau"], -[174094, "src/Rosetta/model/sourcemdl/init.luau"], -[174265, "src/Rosetta/model/sourcemdl/Build.luau"], -[174695, "src/Rosetta/model/sourcemdl/Material.luau"], -[174856, "src/Rosetta/model/sourcemdl/Mdl.luau"], -[175383, "src/Rosetta/model/sourcemdl/Phy.luau"], -[175506, "src/Rosetta/model/sourcemdl/Vtx.luau"], -[175688, "src/Rosetta/model/sourcemdl/Vvd.luau"], -[175782, "src/Rosetta/model/stl/init.luau"], -[176232, "src/Rosetta/model/stl/Decode.luau"], -[176306, "src/Rosetta/model/udmf/init.luau"], -[176389, "src/Rosetta/model/usda/init.luau"], -[176598, "src/Rosetta/model/usda/Build.luau"], -[177876, "src/Rosetta/model/usda/Parse.luau"], -[178674, "src/Rosetta/model/usda/Write.luau"], -[179491, "src/Rosetta/model/vbsp/init.luau"], -[179937, "src/Rosetta/model/vbsp/Faces.luau"], -[180161, "src/Rosetta/model/vbsp/Props.luau"], -[180253, "src/Rosetta/model/vmf/init.luau"], -[180578, "src/Rosetta/model/vmf/Build.luau"], -[181002, "src/Rosetta/model/vox/init.luau"], -[181888, "src/Rosetta/model/vox/Grid.luau"], -[181945, "src/Rosetta/model/vrml/init.luau"], -[182011, "src/Rosetta/model/x/init.luau"], -[182141, "src/Rosetta/model/x/Build.luau"], -[182704, "src/Rosetta/model/x/Parse.luau"], -[183001, "src/Rosetta/model/x3d/init.luau"], -[183079, "src/Rosetta/music/669/init.luau"], -[183285, "src/Rosetta/music/ahx/init.luau"], -[183336, "src/Rosetta/music/far/init.luau"], -[183565, "src/Rosetta/music/hmp/init.luau"], -[183829, "src/Rosetta/music/hvl/init.luau"], -[183880, "src/Rosetta/music/it/init.luau"], -[184298, "src/Rosetta/music/it/Itsex.luau"], -[184414, "src/Rosetta/music/med/init.luau"], -[185061, "src/Rosetta/music/midi/init.luau"], -[185204, "src/Rosetta/music/midi/Smf.luau"], -[185615, "src/Rosetta/music/mod/init.luau"], -[185968, "src/Rosetta/music/mtm/init.luau"], -[186190, "src/Rosetta/music/mus/init.luau"], -[186347, "src/Rosetta/music/okt/init.luau"], -[186628, "src/Rosetta/music/ptm/init.luau"], -[186850, "src/Rosetta/music/s3m/init.luau"], -[187086, "src/Rosetta/music/sf2/init.luau"], -[187129, "src/Rosetta/music/stm/init.luau"], -[187360, "src/Rosetta/music/ult/init.luau"], -[187664, "src/Rosetta/music/umx/init.luau"], -[187880, "src/Rosetta/music/xm/init.luau"], -[188441, "src/Rosetta/music/xmi/init.luau"], -[188649, "src/Rosetta/ops/AudioOps.luau"], -[189098, "src/Rosetta/ops/ImageOps/init.luau"], -[189742, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[190252, "src/Rosetta/ops/LayerOps.luau"], -[190345, "src/Rosetta/ops/MeshOps/init.luau"], -[191381, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[191548, "src/Rosetta/ops/MusicOps.luau"], -[191896, "src/Rosetta/playlist/m3u/init.luau"], -[192249, "src/Rosetta/playlist/pls/init.luau"], -[192427, "src/Rosetta/playlist/xspf/init.luau"], -[192630, "src/Rosetta/subtitle/ass/init.luau"], -[193074, "src/Rosetta/subtitle/srt/init.luau"], -[193247, "src/Rosetta/subtitle/vtt/init.luau"], -[193450, "src/Rosetta/vector/gamemaps/init.luau"], -[193637, "src/Rosetta/vector/gamemaps/Expand.luau"], -[193734, "src/Rosetta/vector/svg/init.luau"], -[193820, "src/Rosetta/vector/svg/Parse.luau"], -[194566, "src/Rosetta/vector/svg/PathData.luau"], -[194934, "src/Rosetta/vector/svg/Render.luau"], -[195351, "src/Rosetta/vector/svg/Style.luau"], -[195723, "src/Rosetta/vector/svg/Write.luau"], -[195923, "src/Rosetta/vector/tiled/init.luau"], -[196103, "src/Rosetta/vector/tiled/Data.luau"], -[196254, "src/Rosetta/vector/tiled/Tmj.luau"], -[196885, "src/Rosetta/vector/tiled/Tmx.luau"], -[197497, "src/Rosetta/video/avi/init.luau"], -[197791, "src/Rosetta/video/fli/init.luau"], -[197942, "src/Rosetta/video/flv/init.luau"], -[198326, "src/Rosetta/video/flv/Amf.luau"], -[198484, "src/Rosetta/video/flv/Mux.luau"], -[198765, "src/Rosetta/video/h264/init.luau"], -[198904, "src/Rosetta/video/mkv/init.luau"], -[199060, "src/Rosetta/video/mkv/Mux.luau"], -[199339, "src/Rosetta/video/mkv/Parse.luau"], -[200060, "src/Rosetta/video/mp4/init.luau"], -[200388, "src/Rosetta/video/mpegps/init.luau"], -[200575, "src/Rosetta/video/mpegts/init.luau"], -[200813, "src/Rosetta/video/ogv/init.luau"], -[201208, "src/Rosetta/video/smk/init.luau"], -[201517, "src/Rosetta/video/smk/Audio.luau"], -[201637, "src/Rosetta/video/y4m/init.luau"] +[3769, "src/Rosetta/Types.luau"], +[4852, "src/Rosetta/archive/7z/init.luau"], +[5237, "src/Rosetta/archive/7z/Header.luau"], +[5764, "src/Rosetta/archive/adf/init.luau"], +[6046, "src/Rosetta/archive/applesingle/init.luau"], +[6232, "src/Rosetta/archive/ar/init.luau"], +[6635, "src/Rosetta/archive/arj/init.luau"], +[6845, "src/Rosetta/archive/binhex/init.luau"], +[7094, "src/Rosetta/archive/br/init.luau"], +[7169, "src/Rosetta/archive/bz2/init.luau"], +[7233, "src/Rosetta/archive/cab/init.luau"], +[7646, "src/Rosetta/archive/cab/Sum.luau"], +[7687, "src/Rosetta/archive/cpio/init.luau"], +[7855, "src/Rosetta/archive/d64/init.luau"], +[8269, "src/Rosetta/archive/fat/init.luau"], +[8391, "src/Rosetta/archive/grp/init.luau"], +[8505, "src/Rosetta/archive/gzip/init.luau"], +[8690, "src/Rosetta/archive/iso/init.luau"], +[8762, "src/Rosetta/archive/lha/init.luau"], +[9187, "src/Rosetta/archive/lz4/init.luau"], +[9531, "src/Rosetta/archive/macbinary/init.luau"], +[9729, "src/Rosetta/archive/mpq/init.luau"], +[10135, "src/Rosetta/archive/mpq/Crypt.luau"], +[10200, "src/Rosetta/archive/pak/init.luau"], +[10334, "src/Rosetta/archive/rpm/init.luau"], +[10658, "src/Rosetta/archive/tar/init.luau"], +[10776, "src/Rosetta/archive/uu/init.luau"], +[11046, "src/Rosetta/archive/vpk/init.luau"], +[11357, "src/Rosetta/archive/vswap/init.luau"], +[11627, "src/Rosetta/archive/wad/init.luau"], +[12081, "src/Rosetta/archive/wad/Picture.luau"], +[12183, "src/Rosetta/archive/xz/init.luau"], +[12283, "src/Rosetta/archive/yenc/init.luau"], +[12555, "src/Rosetta/archive/z/init.luau"], +[12651, "src/Rosetta/archive/zip/init.luau"], +[12870, "src/Rosetta/archive/zoo/init.luau"], +[13066, "src/Rosetta/archive/zst/init.luau"], +[13130, "src/Rosetta/audio/aac/init.luau"], +[13336, "src/Rosetta/audio/ac3/init.luau"], +[13482, "src/Rosetta/audio/adpcm/init.luau"], +[13627, "src/Rosetta/audio/adx/init.luau"], +[13858, "src/Rosetta/audio/aiff/init.luau"], +[14249, "src/Rosetta/audio/ape/init.luau"], +[14377, "src/Rosetta/audio/au/init.luau"], +[14538, "src/Rosetta/audio/brstm/init.luau"], +[14829, "src/Rosetta/audio/caf/init.luau"], +[15491, "src/Rosetta/audio/flac/init.luau"], +[15639, "src/Rosetta/audio/flac/Meta.luau"], +[15861, "src/Rosetta/audio/flac/Stream.luau"], +[16231, "src/Rosetta/audio/m4a/init.luau"], +[16565, "src/Rosetta/audio/mp3/init.luau"], +[16825, "src/Rosetta/audio/mp3/Index.luau"], +[17016, "src/Rosetta/audio/mp3/Stream.luau"], +[17243, "src/Rosetta/audio/mp3/Tags.luau"], +[17555, "src/Rosetta/audio/mpc/init.luau"], +[17649, "src/Rosetta/audio/opus/init.luau"], +[18027, "src/Rosetta/audio/opus/Encode.luau"], +[18138, "src/Rosetta/audio/qoa/init.luau"], +[18318, "src/Rosetta/audio/tta/init.luau"], +[18436, "src/Rosetta/audio/vag/init.luau"], +[18659, "src/Rosetta/audio/voc/init.luau"], +[18934, "src/Rosetta/audio/vorbis/init.luau"], +[19388, "src/Rosetta/audio/vorbis/Encode.luau"], +[20201, "src/Rosetta/audio/wav/init.luau"], +[20822, "src/Rosetta/audio/wav/Codecs.luau"], +[20988, "src/Rosetta/audio/wavpack/init.luau"], +[21195, "src/Rosetta/cad/step/init.luau"], +[21577, "src/Rosetta/cad/step/Brep.luau"], +[21812, "src/Rosetta/cad/step/Parse.luau"], +[22369, "src/Rosetta/cad/step/Write.luau"], +[22617, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22936, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23819, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24154, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24313, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25198, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25299, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26053, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26355, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26589, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27008, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27420, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27635, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28396, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28493, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28504, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29453, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30050, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30246, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30495, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31453, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31672, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31856, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32065, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32411, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32425, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32484, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34087, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34379, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34764, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35405, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35546, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35772, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36117, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37011, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37389, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37403, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39250, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40315, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40375, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40835, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41172, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41405, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43441, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43815, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44078, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44375, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44657, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45016, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45070, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45213, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45726, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46507, "src/Rosetta/codecs/audio/Stream.luau"], +[46668, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47150, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47428, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47597, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47725, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49713, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49829, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49946, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50198, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50211, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50595, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51161, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51582, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51621, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51673, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51895, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53350, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53413, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53500, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54469, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55337, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55385, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55901, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56227, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56647, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57082, "src/Rosetta/codecs/compress/Explode.luau"], +[57278, "src/Rosetta/codecs/compress/Lz4.luau"], +[57547, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58151, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58691, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58729, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59202, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59378, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59646, "src/Rosetta/codecs/compress/Lzx.luau"], +[60080, "src/Rosetta/codecs/compress/PackBits.luau"], +[60170, "src/Rosetta/codecs/compress/Quantum.luau"], +[60407, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60711, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60780, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60837, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61795, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61947, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62229, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62240, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62454, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62698, "src/Rosetta/codecs/font/Bitmap.luau"], +[62899, "src/Rosetta/codecs/font/Cff/init.luau"], +[63540, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63690, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64004, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64396, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64898, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65005, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65494, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65923, "src/Rosetta/codecs/image/Blend.luau"], +[66302, "src/Rosetta/codecs/image/Dct/init.luau"], +[66683, "src/Rosetta/codecs/image/Etc.luau"], +[66981, "src/Rosetta/codecs/image/Half.luau"], +[67050, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67404, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67812, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68049, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68809, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69690, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70136, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70214, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70281, "src/Rosetta/codecs/image/Miptex.luau"], +[70497, "src/Rosetta/codecs/image/Pixels.luau"], +[70817, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71276, "src/Rosetta/codecs/image/Raster.luau"], +[71973, "src/Rosetta/codecs/image/Texel.luau"], +[72346, "src/Rosetta/codecs/image/Texture.luau"], +[72491, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72621, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74577, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74836, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[75085, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[75204, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75308, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[76161, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[77113, "src/Rosetta/codecs/image/Yuv.luau"], +[77381, "src/Rosetta/codecs/model/Brush.luau"], +[78021, "src/Rosetta/codecs/model/Displacement.luau"], +[78170, "src/Rosetta/codecs/model/DoomMap/init.luau"], +[78615, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], +[78865, "src/Rosetta/codecs/model/Draco/init.luau"], +[79197, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[79666, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[80855, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[81004, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[81363, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[82325, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[82799, "src/Rosetta/codecs/model/Mat4.luau"], +[83058, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[83586, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[84138, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[84217, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[84324, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[84530, "src/Rosetta/codecs/model/Patch.luau"], +[84654, "src/Rosetta/codecs/model/Polygon.luau"], +[84888, "src/Rosetta/codecs/model/Rbx/init.luau"], +[85125, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[85879, "src/Rosetta/codecs/model/Rig.luau"], +[86122, "src/Rosetta/codecs/model/Sampler.luau"], +[86282, "src/Rosetta/codecs/model/SourceAnim.luau"], +[86503, "src/Rosetta/codecs/model/Vrml/init.luau"], +[86651, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[87225, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[87388, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[88137, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[88659, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[89386, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[89618, "src/Rosetta/codecs/text/Json/init.luau"], +[89887, "src/Rosetta/codecs/text/Json/Decode.luau"], +[90301, "src/Rosetta/codecs/text/Json/Encode.luau"], +[90603, "src/Rosetta/codecs/text/KeyValues/init.luau"], +[91173, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], +[91479, "src/Rosetta/codecs/text/Lexer/init.luau"], +[91611, "src/Rosetta/codecs/text/Nbt/init.luau"], +[91964, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[92656, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[93296, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[93534, "src/Rosetta/codecs/text/Text/init.luau"], +[93625, "src/Rosetta/codecs/text/Url/init.luau"], +[93830, "src/Rosetta/codecs/text/Xml/init.luau"], +[94233, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[94973, "src/Rosetta/codecs/video/Dsp.luau"], +[95696, "src/Rosetta/codecs/video/H263/init.luau"], +[95852, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[96710, "src/Rosetta/codecs/video/H263/Tables.luau"], +[96913, "src/Rosetta/codecs/video/H264/init.luau"], +[97286, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[97561, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[98692, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[99460, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[99718, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[100727, "src/Rosetta/codecs/video/H264/Inter.luau"], +[100981, "src/Rosetta/codecs/video/H264/Intra.luau"], +[101388, "src/Rosetta/codecs/video/H264/Mb.luau"], +[102294, "src/Rosetta/codecs/video/H264/Params.luau"], +[102741, "src/Rosetta/codecs/video/H264/Slice.luau"], +[102992, "src/Rosetta/codecs/video/H264/Tables.luau"], +[103033, "src/Rosetta/codecs/video/H264/Transform.luau"], +[103198, "src/Rosetta/codecs/video/Legacy/init.luau"], +[103396, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[103693, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[104060, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[104178, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[104286, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[104559, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[104954, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[105131, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[105143, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[105510, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[107017, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[107156, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[107294, "src/Rosetta/codecs/video/Theora/init.luau"], +[107557, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[108821, "src/Rosetta/codecs/video/Theora/Header.luau"], +[109184, "src/Rosetta/codecs/video/Video/init.luau"], +[109741, "src/Rosetta/codecs/video/Video/Source.luau"], +[110026, "src/Rosetta/containers/Archive.luau"], +[110293, "src/Rosetta/containers/AudioWrap.luau"], +[110796, "src/Rosetta/containers/Avi/init.luau"], +[111348, "src/Rosetta/containers/Blend.luau"], +[112087, "src/Rosetta/containers/Chunks.luau"], +[112222, "src/Rosetta/containers/Cpio.luau"], +[112650, "src/Rosetta/containers/Demux.luau"], +[112925, "src/Rosetta/containers/Ebml/init.luau"], +[113238, "src/Rosetta/containers/Fat.luau"], +[113926, "src/Rosetta/containers/Iso9660.luau"], +[114431, "src/Rosetta/containers/IsoBmff/init.luau"], +[114601, "src/Rosetta/containers/IsoBmff/Box.luau"], +[114789, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[115634, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[116155, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[116671, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[116788, "src/Rosetta/containers/MacFile.luau"], +[116937, "src/Rosetta/containers/MpegEs.luau"], +[117103, "src/Rosetta/containers/MpegPs/init.luau"], +[117323, "src/Rosetta/containers/MpegTs/init.luau"], +[118115, "src/Rosetta/containers/Ogg/init.luau"], +[118540, "src/Rosetta/containers/Ogg/Mux.luau"], +[118735, "src/Rosetta/containers/Ogg/Page.luau"], +[118904, "src/Rosetta/containers/Riff/init.luau"], +[119221, "src/Rosetta/containers/Tar.luau"], +[119635, "src/Rosetta/containers/Zip/init.luau"], +[120267, "src/Rosetta/core/Adler32.luau"], +[120313, "src/Rosetta/core/Base64.luau"], +[120472, "src/Rosetta/core/Bits.luau"], +[120765, "src/Rosetta/core/Bytes.luau"], +[121292, "src/Rosetta/core/Crc16.luau"], +[121344, "src/Rosetta/core/Crc32.luau"], +[121456, "src/Rosetta/core/Err.luau"], +[121538, "src/Rosetta/core/Input.luau"], +[121614, "src/Rosetta/core/Md5.luau"], +[121773, "src/Rosetta/core/Sniff.luau"], +[121802, "src/Rosetta/data/cbor/init.luau"], +[121901, "src/Rosetta/data/cbor/Codec.luau"], +[122470, "src/Rosetta/data/csv/init.luau"], +[122782, "src/Rosetta/data/ini/init.luau"], +[123028, "src/Rosetta/data/json/init.luau"], +[123120, "src/Rosetta/data/msgpack/init.luau"], +[123209, "src/Rosetta/data/msgpack/Codec.luau"], +[123651, "src/Rosetta/data/nbt/init.luau"], +[123710, "src/Rosetta/data/plist/init.luau"], +[124016, "src/Rosetta/data/plist/Binary.luau"], +[124283, "src/Rosetta/data/snbt/init.luau"], +[124346, "src/Rosetta/data/toml/init.luau"], +[124413, "src/Rosetta/data/toml/Decode.luau"], +[125041, "src/Rosetta/data/toml/Encode.luau"], +[125250, "src/Rosetta/data/vdf/init.luau"], +[125351, "src/Rosetta/data/xml/init.luau"], +[125407, "src/Rosetta/data/yaml/init.luau"], +[125480, "src/Rosetta/data/yaml/Emit.luau"], +[125770, "src/Rosetta/data/yaml/Parse.luau"], +[127063, "src/Rosetta/font/bdf/init.luau"], +[127352, "src/Rosetta/font/bmfont/init.luau"], +[127779, "src/Rosetta/font/bmfont/Parse.luau"], +[128232, "src/Rosetta/font/eot/init.luau"], +[128464, "src/Rosetta/font/fon/init.luau"], +[128747, "src/Rosetta/font/hershey/init.luau"], +[128942, "src/Rosetta/font/pcf/init.luau"], +[129222, "src/Rosetta/font/psf/init.luau"], +[129542, "src/Rosetta/font/ttf/init.luau"], +[129593, "src/Rosetta/font/type1/init.luau"], +[129952, "src/Rosetta/font/type1/Charstring.luau"], +[130230, "src/Rosetta/font/woff/init.luau"], +[130362, "src/Rosetta/font/woff2/init.luau"], +[130419, "src/Rosetta/font/woff2/Rebuild.luau"], +[130959, "src/Rosetta/host/init.luau"], +[131004, "src/Rosetta/host/Love.luau"], +[131147, "src/Rosetta/host/LuaJIT.luau"], +[131197, "src/Rosetta/host/Luau.luau"], +[131220, "src/Rosetta/host/Roblox.luau"], +[131579, "src/Rosetta/image/ani/init.luau"], +[131759, "src/Rosetta/image/art/init.luau"], +[132247, "src/Rosetta/image/blp/init.luau"], +[132505, "src/Rosetta/image/bmp/init.luau"], +[132920, "src/Rosetta/image/dds/init.luau"], +[133403, "src/Rosetta/image/exr/init.luau"], +[134163, "src/Rosetta/image/exr/Codec.luau"], +[134274, "src/Rosetta/image/exr/Piz.luau"], +[134631, "src/Rosetta/image/gif/init.luau"], +[135147, "src/Rosetta/image/gif/Decode.luau"], +[135210, "src/Rosetta/image/hdr/init.luau"], +[135439, "src/Rosetta/image/hdr/Codec.luau"], +[135650, "src/Rosetta/image/icns/init.luau"], +[135981, "src/Rosetta/image/ico/init.luau"], +[136258, "src/Rosetta/image/ico/Dib.luau"], +[136353, "src/Rosetta/image/ilbm/init.luau"], +[136672, "src/Rosetta/image/jpeg/init.luau"], +[136808, "src/Rosetta/image/ktx/init.luau"], +[137468, "src/Rosetta/image/pcx/init.luau"], +[137732, "src/Rosetta/image/png/init.luau"], +[138312, "src/Rosetta/image/png/Apng.luau"], +[138392, "src/Rosetta/image/png/Decode.luau"], +[138632, "src/Rosetta/image/png/Encode.luau"], +[138787, "src/Rosetta/image/pnm/init.luau"], +[139165, "src/Rosetta/image/pnm/Codec.luau"], +[139442, "src/Rosetta/image/qoi/init.luau"], +[139564, "src/Rosetta/image/qoi/Codec.luau"], +[139714, "src/Rosetta/image/sgi/init.luau"], +[139999, "src/Rosetta/image/sunras/init.luau"], +[140245, "src/Rosetta/image/tga/init.luau"], +[140515, "src/Rosetta/image/tga/Codec.luau"], +[140667, "src/Rosetta/image/tiff/init.luau"], +[141494, "src/Rosetta/image/tiff/Pixels.luau"], +[141884, "src/Rosetta/image/tim/init.luau"], +[142126, "src/Rosetta/image/vtf/init.luau"], +[142361, "src/Rosetta/image/webp/init.luau"], +[142971, "src/Rosetta/image/webp/Alpha.luau"], +[143047, "src/Rosetta/image/webp/Anim.luau"], +[143202, "src/Rosetta/image/xbm/init.luau"], +[143363, "src/Rosetta/image/xpm/init.luau"], +[143631, "src/Rosetta/image/xpm/Names.luau"], +[143687, "src/Rosetta/layered/aseprite/init.luau"], +[144425, "src/Rosetta/layered/ora/init.luau"], +[144712, "src/Rosetta/layered/psd/init.luau"], +[145447, "src/Rosetta/layered/psd/Channels.luau"], +[145799, "src/Rosetta/model/3ds/init.luau"], +[145882, "src/Rosetta/model/3ds/Build.luau"], +[146529, "src/Rosetta/model/3ds/Read.luau"], +[147025, "src/Rosetta/model/3ds/Write.luau"], +[147830, "src/Rosetta/model/3mf/init.luau"], +[147912, "src/Rosetta/model/3mf/Read.luau"], +[148500, "src/Rosetta/model/3mf/Write.luau"], +[148905, "src/Rosetta/model/b3d/init.luau"], +[148960, "src/Rosetta/model/b3d/Read.luau"], +[149531, "src/Rosetta/model/blend/init.luau"], +[149627, "src/Rosetta/model/blend/Anim.luau"], +[149973, "src/Rosetta/model/blend/Material.luau"], +[150325, "src/Rosetta/model/blend/Mesh.luau"], +[150960, "src/Rosetta/model/blend/Normals.luau"], +[151121, "src/Rosetta/model/blend/Prim.luau"], +[151570, "src/Rosetta/model/blend/Read.luau"], +[152470, "src/Rosetta/model/bsp/init.luau"], +[152615, "src/Rosetta/model/bsp/Brush.luau"], +[152878, "src/Rosetta/model/bsp/Quake3.luau"], +[153106, "src/Rosetta/model/buildmap/init.luau"], +[153378, "src/Rosetta/model/buildmap/Geometry.luau"], +[153781, "src/Rosetta/model/d3map/init.luau"], +[154063, "src/Rosetta/model/d3map/Parse.luau"], +[154261, "src/Rosetta/model/dae/init.luau"], +[154450, "src/Rosetta/model/dae/Math.luau"], +[154497, "src/Rosetta/model/dae/Read.luau"], +[156347, "src/Rosetta/model/dae/Write.luau"], +[156716, "src/Rosetta/model/fbx/init.luau"], +[156864, "src/Rosetta/model/fbx/Ascii.luau"], +[157134, "src/Rosetta/model/fbx/Binary.luau"], +[157589, "src/Rosetta/model/fbx/Read.luau"], +[158951, "src/Rosetta/model/fbx/Write.luau"], +[159936, "src/Rosetta/model/fbx/Xform.luau"], +[159977, "src/Rosetta/model/gltf/init.luau"], +[160214, "src/Rosetta/model/gltf/Pack.luau"], +[160283, "src/Rosetta/model/gltf/Read.luau"], +[161014, "src/Rosetta/model/gltf/Write.luau"], +[161694, "src/Rosetta/model/iqm/init.luau"], +[161770, "src/Rosetta/model/iqm/Read.luau"], +[162125, "src/Rosetta/model/iqm/Write.luau"], +[162812, "src/Rosetta/model/ldraw/init.luau"], +[162890, "src/Rosetta/model/ldraw/Colors.luau"], +[163208, "src/Rosetta/model/ldraw/Read.luau"], +[163785, "src/Rosetta/model/lwo/init.luau"], +[163861, "src/Rosetta/model/lwo/Build.luau"], +[164323, "src/Rosetta/model/lwo/Parse.luau"], +[164866, "src/Rosetta/model/map/init.luau"], +[165183, "src/Rosetta/model/map/Build.luau"], +[165426, "src/Rosetta/model/map/Parse.luau"], +[165811, "src/Rosetta/model/map/Write.luau"], +[165957, "src/Rosetta/model/mca/init.luau"], +[166299, "src/Rosetta/model/mca/Chunk.luau"], +[166432, "src/Rosetta/model/mca/Lz4Block.luau"], +[166502, "src/Rosetta/model/md2/init.luau"], +[166701, "src/Rosetta/model/md3/init.luau"], +[166929, "src/Rosetta/model/md5/init.luau"], +[167010, "src/Rosetta/model/md5/Read.luau"], +[167443, "src/Rosetta/model/mdl/init.luau"], +[167525, "src/Rosetta/model/mdl/HalfLife.luau"], +[167829, "src/Rosetta/model/mdl/Quake.luau"], +[168047, "src/Rosetta/model/ms3d/init.luau"], +[168119, "src/Rosetta/model/ms3d/Read.luau"], +[168565, "src/Rosetta/model/ms3d/Write.luau"], +[169034, "src/Rosetta/model/obj/init.luau"], +[169776, "src/Rosetta/model/obj/Mtl.luau"], +[170063, "src/Rosetta/model/off/init.luau"], +[170525, "src/Rosetta/model/ply/init.luau"], +[171630, "src/Rosetta/model/ply/Binary.luau"], +[171831, "src/Rosetta/model/pmx/init.luau"], +[171900, "src/Rosetta/model/pmx/Build.luau"], +[172196, "src/Rosetta/model/pmx/Pmd.luau"], +[172531, "src/Rosetta/model/pmx/Read.luau"], +[172935, "src/Rosetta/model/proc/init.luau"], +[173317, "src/Rosetta/model/qb/init.luau"], +[173710, "src/Rosetta/model/rbxm/init.luau"], +[174302, "src/Rosetta/model/rbxmx/init.luau"], +[174955, "src/Rosetta/model/robloxmesh/init.luau"], +[175614, "src/Rosetta/model/robloxmesh/Parse.luau"], +[176071, "src/Rosetta/model/robloxmesh/Write.luau"], +[176180, "src/Rosetta/model/schematic/init.luau"], +[176501, "src/Rosetta/model/schematic/Common.luau"], +[176621, "src/Rosetta/model/schematic/Litematic.luau"], +[176832, "src/Rosetta/model/schematic/Mcedit.luau"], +[177076, "src/Rosetta/model/schematic/Sponge.luau"], +[177205, "src/Rosetta/model/smd/init.luau"], +[177272, "src/Rosetta/model/smd/Read.luau"], +[177541, "src/Rosetta/model/smd/Write.luau"], +[177784, "src/Rosetta/model/sourcemdl/init.luau"], +[177955, "src/Rosetta/model/sourcemdl/Build.luau"], +[178385, "src/Rosetta/model/sourcemdl/Material.luau"], +[178546, "src/Rosetta/model/sourcemdl/Mdl.luau"], +[179073, "src/Rosetta/model/sourcemdl/Phy.luau"], +[179196, "src/Rosetta/model/sourcemdl/Vtx.luau"], +[179378, "src/Rosetta/model/sourcemdl/Vvd.luau"], +[179472, "src/Rosetta/model/stl/init.luau"], +[179922, "src/Rosetta/model/stl/Decode.luau"], +[179996, "src/Rosetta/model/udmf/init.luau"], +[180079, "src/Rosetta/model/usda/init.luau"], +[180288, "src/Rosetta/model/usda/Build.luau"], +[181566, "src/Rosetta/model/usda/Parse.luau"], +[182364, "src/Rosetta/model/usda/Write.luau"], +[183181, "src/Rosetta/model/vbsp/init.luau"], +[183627, "src/Rosetta/model/vbsp/Faces.luau"], +[183851, "src/Rosetta/model/vbsp/Props.luau"], +[183943, "src/Rosetta/model/vmf/init.luau"], +[184268, "src/Rosetta/model/vmf/Build.luau"], +[184692, "src/Rosetta/model/vox/init.luau"], +[185578, "src/Rosetta/model/vox/Grid.luau"], +[185635, "src/Rosetta/model/vrml/init.luau"], +[185701, "src/Rosetta/model/x/init.luau"], +[185831, "src/Rosetta/model/x/Build.luau"], +[186394, "src/Rosetta/model/x/Parse.luau"], +[186691, "src/Rosetta/model/x3d/init.luau"], +[186769, "src/Rosetta/music/669/init.luau"], +[186975, "src/Rosetta/music/ahx/init.luau"], +[187026, "src/Rosetta/music/far/init.luau"], +[187255, "src/Rosetta/music/hmp/init.luau"], +[187519, "src/Rosetta/music/hvl/init.luau"], +[187570, "src/Rosetta/music/it/init.luau"], +[187988, "src/Rosetta/music/it/Itsex.luau"], +[188104, "src/Rosetta/music/med/init.luau"], +[188751, "src/Rosetta/music/midi/init.luau"], +[188894, "src/Rosetta/music/midi/Smf.luau"], +[189305, "src/Rosetta/music/mod/init.luau"], +[189658, "src/Rosetta/music/mtm/init.luau"], +[189880, "src/Rosetta/music/mus/init.luau"], +[190037, "src/Rosetta/music/okt/init.luau"], +[190318, "src/Rosetta/music/ptm/init.luau"], +[190540, "src/Rosetta/music/s3m/init.luau"], +[190776, "src/Rosetta/music/sf2/init.luau"], +[190819, "src/Rosetta/music/stm/init.luau"], +[191050, "src/Rosetta/music/ult/init.luau"], +[191354, "src/Rosetta/music/umx/init.luau"], +[191570, "src/Rosetta/music/xm/init.luau"], +[192131, "src/Rosetta/music/xmi/init.luau"], +[192339, "src/Rosetta/ops/AudioOps.luau"], +[192788, "src/Rosetta/ops/ImageOps/init.luau"], +[193432, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[193942, "src/Rosetta/ops/LayerOps.luau"], +[194035, "src/Rosetta/ops/MeshOps/init.luau"], +[195071, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[195238, "src/Rosetta/ops/MusicOps.luau"], +[195586, "src/Rosetta/playlist/m3u/init.luau"], +[195939, "src/Rosetta/playlist/pls/init.luau"], +[196117, "src/Rosetta/playlist/xspf/init.luau"], +[196320, "src/Rosetta/subtitle/ass/init.luau"], +[196764, "src/Rosetta/subtitle/srt/init.luau"], +[196937, "src/Rosetta/subtitle/vtt/init.luau"], +[197140, "src/Rosetta/vector/gamemaps/init.luau"], +[197327, "src/Rosetta/vector/gamemaps/Expand.luau"], +[197424, "src/Rosetta/vector/svg/init.luau"], +[197510, "src/Rosetta/vector/svg/Parse.luau"], +[198256, "src/Rosetta/vector/svg/PathData.luau"], +[198624, "src/Rosetta/vector/svg/Render.luau"], +[199041, "src/Rosetta/vector/svg/Style.luau"], +[199413, "src/Rosetta/vector/svg/Write.luau"], +[199613, "src/Rosetta/vector/tiled/init.luau"], +[199793, "src/Rosetta/vector/tiled/Data.luau"], +[199944, "src/Rosetta/vector/tiled/Tmj.luau"], +[200575, "src/Rosetta/vector/tiled/Tmx.luau"], +[201187, "src/Rosetta/video/avi/init.luau"], +[201481, "src/Rosetta/video/fli/init.luau"], +[201632, "src/Rosetta/video/flv/init.luau"], +[202016, "src/Rosetta/video/flv/Amf.luau"], +[202174, "src/Rosetta/video/flv/Mux.luau"], +[202455, "src/Rosetta/video/h264/init.luau"], +[202594, "src/Rosetta/video/mkv/init.luau"], +[202750, "src/Rosetta/video/mkv/Mux.luau"], +[203029, "src/Rosetta/video/mkv/Parse.luau"], +[203750, "src/Rosetta/video/mp4/init.luau"], +[204078, "src/Rosetta/video/mpegps/init.luau"], +[204265, "src/Rosetta/video/mpegts/init.luau"], +[204503, "src/Rosetta/video/ogv/init.luau"], +[204898, "src/Rosetta/video/smk/init.luau"], +[205207, "src/Rosetta/video/smk/Audio.luau"], +[205327, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 8352b74..0b52f83 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -66,6 +66,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | +| model | blend | .blend | yes | - | materials: true, textures: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true, compressed: true | `tests/model/blend.luau` | | model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` | | model | buildmap | .map | yes | yes | sprites: true, slopes: true | `tests/model/buildmap.luau` | | model | d3map | .map | yes | - | patches: true, variants: "doom3", "quake4" | `tests/model/d3map.luau` | diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 588a929..01f0afc 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -2,7 +2,7 @@ Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD, -[Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes +[Blender .blend](#blender-blend), [Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) 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`. @@ -884,6 +884,54 @@ assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri") assert(back.meshes[1].primitives[1].indices.count == 3) ``` +## Blender (.blend) + +`.blend` files load read only, from every Blender version since 2.4x: plain, gzip (before 3.0) or zstd (3.0+) +compressed, 32 or 64-bit pointers, either byte order, and the 5.0+ header. Each file is read through its own SDNA (the +struct catalogue Blender writes into every file), so fields are found by name whatever version wrote them. The +current scene loads: objects (transforms with euler orders, quaternions, axis angles, delta transforms, the parent +inverse, bone parents), collections as nodes (`collections = false` flattens them), meshes, materials, images, +cameras, lights, armatures, skins, shape keys and actions. Blender is z-up (`meta.up = "z"`). + +| Part | What loads | +|---|---| +| Meshes | every storage generation: MFace (before 2.63 and the 2.7x "legacy mesh format"), MPoly / MLoop (2.63 - 3.x), attribute layers (`position`, `.corner_vert`, ... 3.x - 4.x), AttributeStorage (5.x); a primitive per used material slot, `triangulate = false` keeps the faces (`"polygons"`) | +| Mesh data | UV maps (`TEXCOORD_n`, v flipped to glTF's origin), colour attributes (byte and float, point and corner) as linear `COLOR_n`, corner normals from Blender's smooth fans (sharp edges / faces, auto smooth before 4.1) or the stored custom normals, weights (`JOINTS_0` / `WEIGHTS_0`: the 4 largest deform-bone groups, normalized) | +| Materials | the Principled BSDF (base colour, metallic, roughness, alpha, emission and its strength, image textures on Base Color / Emission, Normal through a Normal Map node, Roughness / Metallic through Separate RGB), else the legacy `r, g, b` colour | +| Images | packed images as encoded bytes (`texture.data`), external ones as `uri` (relative to the `.blend`, bytes through `files` / `resolve`) | +| Cameras, lights | perspective (`yfov` from the lens, sensor fit and render aspect) / orthographic; point, sun, spot (watts to candela / lux as Blender's glTF exporter does); area lights are skipped (`meta.source.skippedLights`) | +| Armatures | a joint node per bone (rest pose times the saved pose), one skin per deformed mesh | +| Animation | the active action of each object, armature (pose bones) and shape key set, f-curves evaluated (constant, linear, bezier, easing; extrapolation) and sampled once per frame (`sampleStep`) into channels; time 0 is `meta.source.frameZero` at `meta.source.fps` | +| Not loaded | modifiers (listed per object in `meta.source.modifiers`, never applied), curves, text, metaballs, grease pencil, volumes, NLA strips, drivers, constraints, linked libraries | + +```luau +local scene = assert(F.model.load(riggedBlendBytes)) +local src = scene.meta.source +assert(src.format == "blend" and src.version >= 500 and src.compression == "zstd") +assert(scene.meta.up == "z" and #scene.skins == 1 and #scene.animations == 1) +local tube = scene.meshes[1].primitives[1] +assert(tube.attributes.JOINTS_0 and tube.attributes.WEIGHTS_0 and #tube.targets == 1) +assert(scene.materials[1].name == "Skin" and scene.materials[1].roughness > 0.69) +print(src.modifiers.Tube[1].type) -- Armature (not applied) +``` + +Anything else in the file is reachable through the container: `F.format("blend").open` parses the blocks and the +SDNA, and every struct reads by field name (`get`, `num`, `str`, `vec`, `sub`, `deref`, `list` for ListBase, `array` +and `pointers` behind pointers). + +```luau +local blend = F.format("blend") +local file = assert(blend.open(F.Bytes.reader(riggedBlendBytes))) +local Blend = blend.container +for _, block in Blend.blocks(file, "OB") do + local ob = assert(Blend.struct(file, block)) + print(ob:idName(), ob:num("type"), ob:vec("loc")[3]) -- Rig 25 0 / Tube 1 0 +end +local arm = assert(Blend.struct(file, Blend.blocks(file, "AR")[1])) +local bones = arm:list("bonebase") +assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("name") == "upper") +``` + ## Formats | Format | Read | Write | Notes | @@ -921,6 +969,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | Doom 3 / Quake 4 `.proc` | yes | | render geometry per area, portals and BSP nodes as data | | Doom 3 / Quake 4 `.map` (d3map) | yes | | brushDef3, patchDef2 / 3, entities as nodes | | UDMF (`.udmf`, `TEXTMAP`) | yes | | Doom maps as text: see "Doom maps (UDMF)" above | +| Blender `.blend` | yes | | 2.4x - 5.x, compressed; meshes of every generation, materials, skins, shape keys, actions; see "Blender" above | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 24aeeb9..aa2b131 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -746,6 +746,18 @@ local list: { Entry } = { return require("@rosetta/model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return require("@rosetta/model/blend") + end, + }, { name = "bsp", category = "model", diff --git a/src/Rosetta/containers/Blend.luau b/src/Rosetta/containers/Blend.luau new file mode 100644 index 0000000..72561dd --- /dev/null +++ b/src/Rosetta/containers/Blend.luau @@ -0,0 +1,737 @@ +--!strict +-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header +-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header +-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads); +-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC, +-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files. +-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address. +local Err = require("@rosetta/core/Err") +local Deflate = require("@rosetta/codecs/compress/Deflate") +local Zstd = require("@rosetta/codecs/compress/Zstd") + +local Blend = {} + +local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32 +local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring + +export type Field = { + name: string, -- without '*', '(*...)()' and array dimensions + decl: string, -- as declared ("*next", "co[3]", "mat[4][4]") + type: string, + offset: number, + size: number, -- bytes of the whole field (all array elements) + pointer: boolean, + dims: { number }, + count: number, -- array elements (1 for scalars) + elem: number, -- bytes of one element +} +export type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } } +export type Dna = { + names: { string }, + types: { string }, + lengths: { number }, + structs: { Struct }, -- 1-based; a block's sdna is 0-based + byName: { [string]: Struct }, +} +export type Block = { + code: string, -- "OB", "ME", "DATA", ... (trailing NULs removed) + sdna: number, -- 0-based struct index + addr: any, -- the old address (a key: a number for 4-byte pointers, an 8-byte string for 8-byte ones) + size: number, -- data bytes + count: number, -- struct elements + offset: number, -- data start in file.buf + index: number, + owner: number, -- the index of the ID block this block follows (DATA blocks belong to the ID before them) +} +export type File = { + buf: buffer, -- the (decompressed) file + version: number, -- 279, 293, 401, 502, ... + subversion: number?, -- from the GLOB block + pointerSize: number, + little: boolean, + format: number, -- 0 (12-byte header) or the 5.0+ file format version + compression: string?, -- "gzip" | "zstd" + blocks: { Block }, + byAddr: { [any]: Block }, + shared: { [any]: { Block } }, -- addresses used by several blocks (reused between IDs): every block with it + byCode: { [string]: { Block } }, + dna: Dna, + -- endian-aware readers (the little-endian ones are buffer's own) + u16: (b: buffer, o: number) -> number, + i16: (b: buffer, o: number) -> number, + u32: (b: buffer, o: number) -> number, + i32: (b: buffer, o: number) -> number, + f32: (b: buffer, o: number) -> number, + f64: (b: buffer, o: number) -> number, +} +export type Options = { maxBytes: number?, maxBlocks: number? } + +-- ------------------------------------------------------------------------------------------------ readers +local function swap16(b: buffer, o: number): number + return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function swap32(b: buffer, o: number): number + return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3) +end +local scratch = buffer.create(8) +local function bei16(b: buffer, o: number): number + local v = swap16(b, o) + return if v >= 32768 then v - 65536 else v +end +local function bei32(b: buffer, o: number): number + local v = swap32(b, o) + return if v >= 2147483648 then v - 4294967296 else v +end +local function bef32(b: buffer, o: number): number + for k = 0, 3 do + buffer.writeu8(scratch, k, readu8(b, o + 3 - k)) + end + return readf32(scratch, 0) +end +local function bef64(b: buffer, o: number): number + for k = 0, 7 do + buffer.writeu8(scratch, k, readu8(b, o + 7 - k)) + end + return readf64(scratch, 0) +end + +-- ------------------------------------------------------------------------------------------------ open +function Blend.sniff(buf: buffer, offset: number?, length: number?): number + local o = offset or 0 + local n = length or (buffer.len(buf) - o) + if n >= 12 and readstring(buf, o, 7) == "BLENDER" then + return 1 + end + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + return 0.05 -- a gzip member: blend only once decompressed + end + return 0 +end + +local function decompress(buf: buffer, o: number, n: number, opts: Options?): (buffer?, string?, any) + local maxBytes = opts and opts.maxBytes or 2 ^ 31 + if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then + local out, err = Deflate.gunzip(buf, o, n) + if not out then + return nil, nil, err + end + if buffer.len(out) > maxBytes then + return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes") + end + return out, "gzip", nil + end + if n >= 4 and readu32(buf, o) == 0xFD2FB528 then + local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes }) + if not out then + return nil, nil, err + end + return out, "zstd", nil + end + return nil, nil, nil +end + +local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?) + if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then + return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)" + end + local c = readstring(b, 7, 1) + if c == "_" or c == "-" then + local e = readstring(b, 8, 1) + local v = tonumber(readstring(b, 9, 3)) + if (e ~= "v" and e ~= "V") or not v then + return nil, 0, false, 0, 0, "bad header" + end + return 12, if c == "_" then 4 else 8, e == "v", v, 0, nil + end + local hs = tonumber(readstring(b, 7, 2)) + if not hs or hs < 17 or hs > n then + return nil, 0, false, 0, 0, "bad header size" + end + if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then + return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7)) + end + local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4)) + if not fmt or not v then + return nil, 0, false, 0, 0, "bad header" + end + if fmt ~= 1 then + return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt + end + return hs, 8, true, v, fmt, nil +end + +local PRIM: { [string]: boolean } = { + char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true, + float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true, + uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true, +} +Blend.PRIMITIVE = PRIM + +local function parseDna(f: File, at: number, size: number): string? + local b = f.buf + local e = at + size + local i32 = f.i32 + local function align(p: number): number + return at + ((p - at + 3) // 4) * 4 + end + local function strings(p: number, tag: string): ({ string }?, number) + if p + 8 > e or readstring(b, p, 4) ~= tag then + return nil, p + end + local n = i32(b, p + 4) + p += 8 + if n < 0 or n > e - p then + return nil, p + end + local out = table.create(n) :: { string } + for k = 1, n do + local q = p + while q < e and readu8(b, q) ~= 0 do + q += 1 + end + if q >= e then + return nil, p + end + out[k] = readstring(b, p, q - p) + p = q + 1 + end + return out, p + end + if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then + return "no SDNA in DNA1" + end + local names, p = strings(at + 4, "NAME") + if not names then + return "bad SDNA NAME" + end + local types + types, p = strings(align(p), "TYPE") + if not types then + return "bad SDNA TYPE" + end + p = align(p) + local nt = #types + if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then + return "bad SDNA TLEN" + end + local lengths = table.create(nt) :: { number } + for k = 1, nt do + lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) + end + p = align(p + 4 + nt * 2) + if p + 8 > e or readstring(b, p, 4) ~= "STRC" then + return "bad SDNA STRC" + end + local ns = i32(b, p + 4) + p += 8 + if ns < 0 or ns * 4 > e - p then + return "bad SDNA struct count" + end + local i16 = f.i16 + local ps = f.pointerSize + local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct } + for k = 1, ns do + if p + 4 > e then + return "truncated SDNA structs" + end + local t, nf = i16(b, p), i16(b, p + 2) + p += 4 + if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then + return "bad SDNA struct " .. k + end + local tnames = types :: { string } + local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} } + local off = 0 + for j = 1, nf do + local ft, fn = i16(b, p), i16(b, p + 2) + p += 4 + if ft < 0 or ft >= nt or fn < 0 or fn >= #names then + return "bad SDNA field in " .. s.name + end + local decl: string = (names :: { string })[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims: { number }, count = {}, 1 + for d in string.gmatch(decl, "%[(%d+)%]") do + local v = tonumber(d) or 1 + table.insert(dims, v) + count *= v + end + local base = string.gsub(decl, "%[.*$", "") + base = string.gsub(base, "[%*%(%)]", "") + local elem: number = if pointer then ps else lengths[ft + 1] + local fld: Field = { + name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count, + pointer = pointer, dims = dims, count = count, elem = elem, + } + s.fields[j] = fld + if s.byName[base] == nil then + s.byName[base] = fld + end + off += fld.size + end + structs[k] = s + byName[s.name] = s + end + f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName } + return nil +end + +function Blend.open(data: buffer, offset: number?, length: number?, opts: Options?): (File?, Err.Err?) + local o = offset or 0 + local n = length or (buffer.len(data) - o) + if o < 0 or n < 0 or o + n > buffer.len(data) then + return nil, Err.new(Err.ARG, "bad range") + end + local b: buffer + local unpacked, compression, derr = decompress(data, o, n, opts) + if derr then + return nil, derr + end + if unpacked then + b = unpacked + n = buffer.len(b) + elseif o == 0 and n == buffer.len(data) then + b = data + else + b = buffer.create(n) + buffer.copy(b, 0, data, o, n) + end + local hs, ps, little, version, fmt, herr = header(b, n) + if not hs then + local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT + return nil, Err.new(code, herr or "bad header", 0) + end + local f: File = { + buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, + compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil :: any, + u16 = if little then readu16 else swap16, + i16 = if little then readi16 else bei16, + u32 = if little then readu32 else swap32, + i32 = if little then readi32 else bei32, + f32 = if little then readf32 else bef32, + f64 = if little then readf64 else bef64, + } + local u32, i32 = f.u32, f.i32 + local maxBlocks = opts and opts.maxBlocks or 2 ^ 22 + local bh = if fmt >= 1 then 32 elseif ps == 8 then 24 else 20 + local p = hs + local dnaBlock: Block? = nil + local owner = 0 + while true do + if p + bh > n then + if p + 4 <= n and readstring(b, p, 4) == "ENDB" then + break -- ENDB written with a short head + end + return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p) + end + local code = readstring(b, p, 4) + local size, addr, sdna, count + if fmt >= 1 then + sdna = i32(b, p + 4) + addr = readstring(b, p + 8, 8) + local lo, hi = u32(b, p + 16), i32(b, p + 20) + local clo, chi = u32(b, p + 24), i32(b, p + 28) + if hi ~= 0 or chi ~= 0 then + return nil, Err.new(Err.LIMIT, "block over 4 GiB", p) + end + size, count = lo, clo + else + size = i32(b, p + 4) + addr = if ps == 8 then readstring(b, p + 8, 8) else u32(b, p + 8) + sdna = i32(b, p + 8 + ps) + count = i32(b, p + 12 + ps) + end + p += bh + -- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files + code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "") + if code == "ENDB" then + break + end + if size < 0 or count < 0 or size > n - p then + return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh) + end + if #f.blocks >= maxBlocks then + return nil, Err.new(Err.LIMIT, "too many blocks") + end + local index = #f.blocks + 1 + if code ~= "DATA" then + owner = index + end + local blk: Block = { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner } + table.insert(f.blocks, blk) + local prev = f.byAddr[addr] + if prev == nil then + f.byAddr[addr] = blk + else + local list = f.shared[addr] + if not list then + list = { prev } + f.shared[addr] = list + end + table.insert(list, blk) + end + local list = f.byCode[code] + if not list then + list = {} + f.byCode[code] = list + end + table.insert(list, blk) + if code == "DNA1" then + dnaBlock = blk + end + p += size + end + if not dnaBlock then + return nil, Err.new(Err.CORRUPT, "no DNA1 block") + end + local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size) + if derr2 then + return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset) + end + f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil + local glob = f.byCode.GLOB + local fg = f.dna.byName.FileGlobal + local g1: Block? = if glob then glob[1] else nil + local fld = fg and fg.byName.subversion + if g1 and fld then + if fld.offset + 2 <= g1.size then + f.subversion = f.i16(b, g1.offset + fld.offset) + end + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ structs +local View = {} +View.__index = View +Blend.View = View + +export type View = typeof(setmetatable( + {} :: { + file: File, + struct: Struct, + offset: number, -- the struct's first byte in file.buf + block: Block?, + }, + View +)) + +local function view(f: File, s: Struct, offset: number, blk: Block?): View + return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) +end + +function Blend.structOf(f: File, blk: Block): Struct? + return f.dna.structs[blk.sdna + 1] +end + +function Blend.struct(f: File, blk: Block, i: number?, as: string?): View? + local s = if as then f.dna.byName[as] else f.dna.structs[blk.sdna + 1] + if not s then + return nil + end + local at = (i or 0) * s.size + if at < 0 or at + s.size > blk.size then + return nil + end + return view(f, s, blk.offset + at, blk) +end + +function Blend.view(f: File, structName: string, offset: number): View? + local s = f.dna.byName[structName] + if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then + return nil + end + return view(f, s, offset, nil) +end + +function Blend.field(f: File, structName: string, ...: string): Field? + local s = f.dna.byName[structName] + if not s then + return nil + end + for _, name in { ... } do + local fld = s.byName[name] + if fld then + return fld + end + end + return nil +end + +function Blend.blocks(f: File, code: string): { Block } + return f.byCode[code] or {} +end + +local function pointerKey(f: File, o: number): any + local b = f.buf + if f.pointerSize == 8 then + if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then + return nil + end + return readstring(b, o, 8) + end + local v = f.u32(b, o) + return if v == 0 then nil else v +end +Blend.pointerKey = pointerKey + +-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the +-- pointer comes from first (from = the block holding the pointer), as Blender's reader does +function Blend.resolve(f: File, addr: any, from: Block?): Block? + if addr == nil then + return nil + end + local list = f.shared[addr] + if list and from then + for _, b in list do + if b.owner == from.owner then + return b + end + end + end + return f.byAddr[addr] +end + +local function find(self: View, names: { any }): Field? + local by = self.struct.byName + for _, name in names do + local fld = by[name] + if fld then + return fld + end + end + return nil +end + +function View.has(self: View, ...: string): boolean + return find(self, { ... }) ~= nil +end + +local function scalar(f: File, t: string, size: number, o: number): number + local b = f.buf + if t == "float" then + return f.f32(b, o) + elseif t == "double" then + return f.f64(b, o) + elseif t == "int" or t == "int32_t" or t == "long" then + return if size == 8 then f.u32(b, o + (if f.little then 0 else 4)) else f.i32(b, o) + elseif t == "short" or t == "int16_t" then + return f.i16(b, o) + elseif t == "ushort" or t == "uint16_t" then + return f.u16(b, o) + elseif t == "uint" or t == "uint32_t" or t == "ulong" then + return f.u32(b, o) + elseif t == "int8_t" then + return readi8(b, o) + elseif t == "int64_t" or t == "uint64_t" then + local lo, hi = f.u32(b, o + (if f.little then 0 else 4)), f.u32(b, o + (if f.little then 4 else 0)) + if t == "int64_t" and hi >= 2147483648 then + return (hi - 4294967296) * 4294967296 + lo + end + return hi * 4294967296 + lo + end + return readu8(b, o) -- char, uchar, uint8_t, bool +end + +function View.get(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld then + return nil + end + local f = self.file + local o = self.offset + fld.offset + if o + fld.size > buffer.len(f.buf) then + return nil + end + if fld.pointer then + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false + end + return out + end + return pointerKey(f, o) + end + local t = fld.type + if PRIM[t] then + if fld.count == 1 then + return scalar(f, t, fld.elem, o) + end + if t == "char" then + local s = readstring(f.buf, o, fld.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s + end + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem) + end + return out + end + local s = f.dna.byName[t] + if not s then + return nil + end + if fld.count > 1 then + local out = table.create(fld.count) + for k = 0, fld.count - 1 do + out[k + 1] = view(f, s, o + k * s.size, self.block) + end + return out + end + return view(f, s, o, self.block) +end + +function View.num(self: View, ...: string): number? + local v = self:get(...) + return if type(v) == "number" then v else nil +end + +function View.str(self: View, ...: string): string? + local v = self:get(...) + return if type(v) == "string" then v else nil +end + +function View.vec(self: View, ...: string): { number }? + local v = self:get(...) + return if type(v) == "table" and type(v[1]) == "number" then v else nil +end + +function View.sub(self: View, ...: string): View? + local v = self:get(...) + return if type(v) == "table" and getmetatable(v) == View then v else nil +end + +function View.ptr(self: View, ...: string): any + local fld = find(self, { ... }) + if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then + return nil + end + return pointerKey(self.file, self.offset + fld.offset) +end + +function View.target(self: View, ...: string): Block? + return Blend.resolve(self.file, self:ptr(...), self.block) +end + +function View.deref(self: View, name: string | { string }, i: number?, as: string?): View? + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return nil + end + local blk = self:target(fld.name) + if not blk then + return nil + end + local f = self.file + local sname = as or fld.type + if not as and (sname == "void" or not f.dna.byName[sname]) then + local own = f.dna.structs[blk.sdna + 1] + sname = if own then own.name else sname + end + return Blend.struct(f, blk, i, sname) +end + +function View.array(self: View, name: string | { string }, as: string?): { View } + local first = self:deref(name, 0, as) + if not first or not first.block then + return {} + end + local blk = first.block :: Block + local s = first.struct + local n = if s.size > 0 then blk.size // s.size else 0 + local out = table.create(n) :: { View } + for k = 0, n - 1 do + out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) + end + return out +end + +function View.pointers(self: View, name: string | { string }, n: number?): { any } + local names: { any } = if type(name) == "table" then name else { name } + local fld = find(self, names) + if not fld or not fld.pointer then + return {} + end + local blk = self:target(fld.name) + if not blk then + return {} + end + local f = self.file + local ps = f.pointerSize + local count = blk.size // ps + if n then + count = math.min(count, n) + end + local out = table.create(count) + for k = 0, count - 1 do + out[k + 1] = pointerKey(f, blk.offset + k * ps) or false + end + return out +end + +function View.list(self: View, name: string | { string }, as: string?, limit: number?): { View } + local names: { any } = if type(name) == "table" then name else { name } + local lb = self:sub(table.unpack(names)) + local out = {} + if not lb then + return out + end + local f = self.file + local addr = lb:ptr("first") + local seen = {} + local max = limit or 2 ^ 20 + while addr ~= nil and not seen[addr] and #out < max do + seen[addr] = true + local blk = Blend.resolve(f, addr, self.block) + if not blk then + break + end + local v = Blend.struct(f, blk, 0, as) + if not v then + break + end + table.insert(out, v) + addr = v:ptr("next") + if addr == nil and not v.struct.byName.next then + -- structs that start with an embedded header (ModifierData, ...) keep the link there + local head = v.struct.fields[1] + local sub = head and not head.pointer and f.dna.byName[head.type] + if sub then + addr = view(f, sub, v.offset + head.offset, v.block):ptr("next") + end + end + end + return out +end + +function View.data(self: View, ...: string): (number?, number) + local blk = self:target(...) + if not blk then + return nil, 0 + end + return blk.offset, blk.size +end + +function View.cstring(self: View, ...: string): string? + local blk = self:target(...) + if not blk then + return nil + end + local s = readstring(self.file.buf, blk.offset, blk.size) + local z = string.find(s, "\0", 1, true) + return if z then string.sub(s, 1, z - 1) else s +end + +function View.idName(self: View): string? + local id = self:sub("id") + local n = if id then id:str("name") else self:str("name") + if not n then + return nil + end + return string.sub(n, 3) +end + +return Blend diff --git a/src/Rosetta/model/blend/Anim.luau b/src/Rosetta/model/blend/Anim.luau new file mode 100644 index 0000000..7d1eebf --- /dev/null +++ b/src/Rosetta/model/blend/Anim.luau @@ -0,0 +1,344 @@ +--!strict +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = require("@rosetta/containers/Blend") + +local Anim = {} + +export type Key = { + x: number, + y: number, + lx: number, -- left handle + ly: number, + rx: number, -- right handle + ry: number, + ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine) + easing: number, -- 0 auto, 1 in, 2 out, 3 in-out + back: number, + amplitude: number, + period: number, +} +export type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number } + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f: Blend.File, fc: Blend.View): Curve? + local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys: { Key } = {} + for _, b in fc:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in fc:array("fpt", "FPoint") do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) + if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list: { Blend.View } = act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in act:pointers("layer_array", act:num("layer_array_num")) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out: { Curve } = {} + for _, fc in list do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR: { [number]: { any } } = { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?) + if not ipo then + return nil, nil + end + local out: { Curve } = {} + for _, icu in ipo:list("curve", "IpoCurve") do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys: { Key } = {} + for _, b in icu:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number + local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a: Key, b: Key, x: number): number + local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = if d ~= 0 then t - (xt - x) / d else -1 + t = if nt > lo and nt < hi then nt else (lo + hi) / 2 + end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t: number, b: number, c: number, d: number): number + t /= d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t -= 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t -= 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t -= 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 + if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = if a.period > 0 then a.period / 10 else 0.3 + local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t -= 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a: Key, b: Key, x: number): number + local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c: Curve, x: number): number + local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves: { Curve }): (number, number) + local lo, hi = math.huge, -math.huge + for _, c in curves do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path: string): (string?, string?, string) + local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim diff --git a/src/Rosetta/model/blend/Material.luau b/src/Rosetta/model/blend/Material.luau new file mode 100644 index 0000000..157e2f2 --- /dev/null +++ b/src/Rosetta/model/blend/Material.luau @@ -0,0 +1,350 @@ +--!strict +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = require("@rosetta/containers/Blend") +local Types = require("@rosetta/Types") + +local Material = {} + +type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any } + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b: buffer, o: number, n: number, path: string?): string? + if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return if ext then byExt[ext] else nil +end + +local function fetch(ctx: Ctx, uri: string): buffer? + local opts = ctx.opts + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number? + local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil + local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in img:list("packedfiles", "ImagePackedFile") do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex: Types.Texture = { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + +type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } } +type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr + +local function graph(tree: Blend.View): Graph + local g: Graph = { nodes = {}, links = {} } + for _, n in tree:list("nodes", "bNode") do + local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in n:list("inputs", "bNodeSocket") do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in n:list("outputs", "bNodeSocket") do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in tree:list("links", "bNodeLink") do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n: Node, ...: string): Blend.View? + for _, k in { ... } do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }? + if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s: Blend.View?, kind: string): any + if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?) + local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, if ref then n else tn + end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler: Types.Sampler = {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, if custom then sampler else nil) + if not t then + return nil, n + end + local ref: Types.TextureRef = { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g: Graph): Node? + local first: Node? = nil + for _, n in g.nodes do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m: Types.Material, color: { number }, strength: number) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx: Ctx, mv: Blend.View): number + local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras: { [string]: any } = {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g: Graph? = nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g :: Graph) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1 + m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material diff --git a/src/Rosetta/model/blend/Mesh.luau b/src/Rosetta/model/blend/Mesh.luau new file mode 100644 index 0000000..25155b5 --- /dev/null +++ b/src/Rosetta/model/blend/Mesh.luau @@ -0,0 +1,633 @@ +--!strict +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = require("@rosetta/containers/Blend") + +local Mesh = {} + +export type Layer = { + name: string, + domain: string, -- "point" | "edge" | "face" | "corner" | "tess" + kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, + -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) + offset: number, -- data start in file.buf + bytes: number, -- data bytes available + elem: number, -- bytes per element + single: boolean?, -- one value for every element (AttributeStorage single storage) + activeRender: boolean?, + cdtype: number?, +} + +export type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner +export type Poly = { + name: string?, + nv: number, + nf: number, + nc: number, + pos: buffer, -- f32 x 3 per vertex + cornerVert: buffer, -- u32 per corner + faceStart: buffer, -- u32 per face + 1 + faceMat: buffer, -- i32 per face + faceSmooth: buffer, -- u8 per face + uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner + activeUV: number, -- 1-based index into uvs (the active render layer) + colors: { Color }, + customNormals: buffer?, -- f32 x 3 per corner (free custom normals) + encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) + sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans + autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) + weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... + generation: string, -- "mface" | "mpoly" | "attributes" | "storage" + layers: { Layer }, +} + +local CD_KIND: { [number]: string } = { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND: { [number]: string } = { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE: { [string]: number } = { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end +Mesh.SRGB = SRGB + +local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = if st then st.size else SIZE[kind] or 0 + if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f: Blend.File, me: Blend.View, out: { Layer }) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? + for _, L in layers do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? + local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f: Blend.File, L: Layer): (number, number) -> number + local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 + return function(i: number, c: number): number + local at = (if single then 0 else i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? + local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i: number, c: number): number + local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at += o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer + local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255) + end + end + return d +end + +function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } + local layers: { Layer } = {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me: Blend.View, ...: string): number + local v = me:num(...) + return if v and v > 0 then v else 0 +end + +export type Limits = { maxVertices: number? } + +function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) + local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get: ((number, number) -> number)? = nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_: number, _: number): number + return 0 + end + end + local g = get :: (number, number) -> number + for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly: Poly = { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", + layers = layers, + } + local corner: { [string]: any } = {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at += math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w += 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil + local flag = if mp then fieldReader(f, mp, "flag") else nil + local sr = if sf then reader(f, sf) else nil + for i = 0, np - 1 do + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, if s then 1 else 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at += k + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap: buffer? = corner.remap + local function src(i: number): number + return if remap then buffer.readu32(remap, i * 4) else i + end + for _, L in layers do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess :: buffer + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = tc // 4, tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess :: buffer + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in poly.uvs do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in layers do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = if L.domain == "corner" then nc else nv + local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = if L.domain == "corner" then src(i) else i + for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] + end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = if st then st.size else 4 + table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in layers do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) + for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i: number): number return er(i, 0) end + v2 = function(i: number): number return er(i, 1) end + sharp = function(i: number): boolean return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i: number): number return a(i, 0) end + v2 = function(i: number): number return b(i, 0) end + local ser = if se then reader(f, se) else nil + sharp = function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = table.create(nv) :: { { number } } + for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, blk.size // mw.size) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end + +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index +export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } +function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) + local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out: { Shape } = {} + local ref: number? = nil + for i, kb in blocks do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, n // 4 - 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh diff --git a/src/Rosetta/model/blend/Normals.luau b/src/Rosetta/model/blend/Normals.luau new file mode 100644 index 0000000..52f372d --- /dev/null +++ b/src/Rosetta/model/blend/Normals.luau @@ -0,0 +1,159 @@ +--!strict +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + +type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } } + +local function dir(pos: buffer, from: number, to: number): (number, number, number) + local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer + local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals :: buffer + local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done: { [number]: boolean } = {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard += 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = if nq then readu32(nxt, nq * 4) else c + if q < m then + m = q + end + guard += 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in edges do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count += 1 + end + end + alpha /= math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = if cyclic then edges[2] else edges[#edges] + local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in corners do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = (if a > 0 then alpha else TAU - alpha) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = (if b > 0 then beta else TAU - beta) * b + x += sa * (rx * cos(be) + tx * sin(be)) + y += sa * (ry * cos(be) + ty * sin(be)) + z += sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals diff --git a/src/Rosetta/model/blend/Prim.luau b/src/Rosetta/model/blend/Prim.luau new file mode 100644 index 0000000..010b907 --- /dev/null +++ b/src/Rosetta/model/blend/Prim.luau @@ -0,0 +1,447 @@ +--!strict +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = require("@rosetta/Types") +local Polygon = require("@rosetta/codecs/model/Polygon") +local Rig = require("@rosetta/codecs/model/Rig") +local Normals = require("@rosetta/model/blend/Normals") +local MeshT = require("@rosetta/model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + +export type Options = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true (glTF's top-left UV origin) + normals: boolean?, -- default true +} +export type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin + +local function face(poly: MeshT.Poly, fi: number): (number, number) + return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos: buffer, v: number): (number, number, number) + return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly: MeshT.Poly): (buffer, buffer) + local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = if c + 1 < s1 then c + 1 else s0 + local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx += (y1 - y2) * (z1 + z2) + ny += (z1 - z2) * (x1 + x2) + nz += (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = if c > s0 then c - 1 else s1 - 1 + local nc = if c + 1 < s1 then c + 1 else s0 + local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end + +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges +export type Fans = { + next: buffer, -- u32 per corner: the next corner of its face + prev: buffer, -- u32 per corner + face: buffer, -- u32 per corner: its face + -- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner + -- at this corner's next vertex), or -1 where the edge splits fans + across: { [number]: number }, +} + +function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans + local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0) + writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1) + writeu32(fc, c * 4, fi) + end + end + local first: { [number]: number } = {} + local second: { [number]: number } = {} + local uses: { [number]: number } = {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across: { [number]: number } = {} + local smooth = poly.faceSmooth + local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil + for key, u in uses do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer) + local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c: number): number + local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a: number, b: number) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in fans.across do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12)) + writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4)) + writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8)) + end + return out, fanId +end + +function Prim.normals(poly: MeshT.Poly): buffer + local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals :: buffer + end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number }) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = table.create(n * 2) :: { number } + for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, if sign < 0 then -u else u) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t: { number }, comps: number): Types.Accessor + local n = #t // comps + local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +export type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built + local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil + local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0) + local nslots = math.max(#slots, 1) + local groups: { [number]: { number } } = {} + local order: { number } = {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {} + for _, c in poly.colors do + table.insert(if c.domain == "corner" then cornerColors else pointColors, c) + end + local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh: Types.Mesh = { name = poly.name, primitives = {} } + local sources: { { number } } = {} + local cv = poly.cornerVert + for _, m in order do + local faces = groups[m] + local map: { [string]: number } = {} + local vsrc: { number } = {} + local corners: { number } = {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in faces do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o += 12 + end + for _, uv in poly.uvs do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o += 8 + end + for _, col in cornerColors do + buffer.copy(scratch, o, col.data, c * 16, 16) + o += 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs: { [string]: Types.Accessor } = {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in poly.uvs do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in poly.colors do + local C = buffer.create(n * 16) + for i = 1, n do + local e = if col.domain == "corner" then corners[i] else vsrc[i] + buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci += 1 + end + if skin and poly.weights then + local lists = table.create(n) :: { { number } } + for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k]] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim: Types.Primitive = { attributes = attrs, mode = "triangles" } + local idx: { number } = {} + if triangulateOn then + for _, fi in faces do + local tri: { number } = {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in tri do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in faces do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in idx do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets: { { [string]: Types.Accessor } } = {} + for k, s in shapes do + if k ~= ref then + local t = table.create(n * 3) :: { number } + for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in shapes do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in order do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim diff --git a/src/Rosetta/model/blend/Read.luau b/src/Rosetta/model/blend/Read.luau new file mode 100644 index 0000000..494c5e0 --- /dev/null +++ b/src/Rosetta/model/blend/Read.luau @@ -0,0 +1,898 @@ +--!strict +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = require("@rosetta/containers/Blend") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Rig = require("@rosetta/codecs/model/Rig") +local Mesh = require("@rosetta/model/blend/Mesh") +local Prim = require("@rosetta/model/blend/Prim") +local Anim = require("@rosetta/model/blend/Anim") +local Material = require("@rosetta/model/blend/Material") + +local Read = {} + +local Scene = Types.Scene +type M4 = { number } + +export type Options = { + triangulate: boolean?, + flipV: boolean?, + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- the scene to read (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, +} + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME: { [number]: string } = { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q: { number }?): { number } + if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4 + if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m: M4, s: { number }): M4 + local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do + r[c * 4 + k] *= s[c + 1] + end + end + return r +end + +local function trs(t: { number }, r: M4, s: { number }): M4 + local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + +export type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode + +local function objectProps(ob: Blend.View): Props + -- fields missing from old files take their neutral value + local function v(fallback: { number }, ...: string): { number } + local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p: Props = { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc: Blend.View?): Props + if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n: number, ...: string): { number } + local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p: Props): M4 + local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node: Types.Node, m: M4) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v: Blend.View?, ...: string): M4? + local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ scene +type Ctx = { + f: Blend.File, + scene: Types.Scene, + opts: Options, + objects: { [any]: number }, -- OB addr -> node + objView: { [number]: Blend.View }, -- node -> its object + parentOf: { [number]: number }, + world: { [number]: M4 }, + meshes: { [string]: number }, + materials: { [any]: number }, + textures: { [any]: number }, + armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) + props: { [number]: Props }, + meta: { [string]: any }, + pending: { { node: number, ob: Blend.View } }, +} + +local function worldOf(ctx: Ctx, node: number): M4 + local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = if p then Mat4.mul(worldOf(ctx, p), m) else m + ctx.world[node] = w + return w +end + +local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number + table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames: { [string]: Blend.View } = {} + if pose then + for _, pc in pose:list("chanbase", "bPoseChannel") do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) + if depth > 256 then + return + end + for _, bone in list do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest + local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode: Types.Node = { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = if parentJoint then info.joints[parentJoint] else node + local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx: Ctx, ob: Blend.View, node: number) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c: Types.Camera + if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera + else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera + end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx: Ctx, ob: Blend.View, node: number) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy *= 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in if tree then tree:list("nodes", "bNode") else {} do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in n:list("inputs", "bNodeSocket") do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l: Types.Light + if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light + elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light + elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light + else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number } + local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = if useOb then obMats[i] else meMats[i] + local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx :: any, mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View? + for _, md in ob:list("modifiers") do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob: Blend.View, me: Blend.View): { string } + local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in list do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin: Prim.Skinning? = nil + if armInfo then + local joints = {} + for gi, name in groupNames(ob, me) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number }) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx: Ctx) + for _, p in ctx.pending do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number? + local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode: number? = under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node: Types.Node = { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in ob:list("modifiers") do + table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props + local p: Props = {} + for k, v in props do + p[k] = table.clone(v) + end + for _, c in curves do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end +type Curve = Anim.Curve + +local function frames(lo: number, hi: number, step: number): { number } + local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f += step + end + table.insert(out, hi) + return out +end + +type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? } + +local function animations(ctx: Ctx) + local f = ctx.f + local jobs: { Job } = {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner: { [any]: string } = {} + for _, ob in ctx.objView do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in ctx.meta.shapeKeys do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves: { Curve }? = found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in sk.shapes do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in mc or {} do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list: { Curve } = curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in ctx.scene.nodes do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a: Job, b: Job): boolean + return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in jobs do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction: { [string]: Types.Animation } = {} + for _, j in jobs do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } :: Types.Animation + byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in fs do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node :: number + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in j.curves do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who]] = true + end + end + for b in touched do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in fs do + local k = 0 + for si, s in sk.shapes do + if si ~= sk.ref then + local v = s.value + for _, c in j.curves do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k += 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in times do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in j.nodes :: { number } do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any }, + } }) + end + end + for _, a in tmp.animations do + for _, ch in a.channels do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f: Blend.File, name: string?): Blend.View? + local scenes = Blend.blocks(f, "SC") + if name then + for _, b in scenes do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil +end + +function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) + local o: Options = opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta: { [string]: any } = { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx: Ctx = { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order: { { ob: Blend.View, under: number? } } = {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = if fps > 0 then fps else 24 + meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col: Blend.View, under: number?, depth: number) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in col:list("gobject", "CollectionObject") do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in col:list("children", "CollectionChild") do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn: number? = nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in sc:list("base", "Base") do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in Blend.blocks(f, "OB") do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder: { [any]: number? } = {} + for _, e in order do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in order do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, if u and u > 0 then u else nil, 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + +return Read diff --git a/src/Rosetta/model/blend/init.luau b/src/Rosetta/model/blend/init.luau new file mode 100644 index 0000000..0f14405 --- /dev/null +++ b/src/Rosetta/model/blend/init.luau @@ -0,0 +1,94 @@ +--!strict +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Types = require("@rosetta/Types") +local Blend = require("@rosetta/containers/Blend") +local Deflate = require("@rosetta/codecs/compress/Deflate") +local Zstd = require("@rosetta/codecs/compress/Zstd") +local Read = require("@rosetta/model/blend/Read") +local Anim = require("@rosetta/model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- default true (false: "polygons" primitives) + flipV: boolean?, -- default true (glTF's top-left UV origin) + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- a scene by name (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, -- external images + files: { [string]: any }?, + maxBytes: number?, -- decompressed size limit (default 2^31) + maxVertices: number?, -- per mesh (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. +function BlendFormat.sniff(r: Bytes.Reader): number + local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?) + return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat diff --git a/tests/containers/blend.luau b/tests/containers/blend.luau new file mode 100644 index 0000000..0ba2458 --- /dev/null +++ b/tests/containers/blend.luau @@ -0,0 +1,294 @@ +-- containers/Blend tests: synthetic files in every header / pointer size / byte order (12-byte header with 4 and 8 +-- byte pointers, little and big endian; the 5.0+ 17-byte header with large block heads), structs by name, arrays, +-- pointers, ListBase walks, addresses reused between IDs, gzip; the real files of tools/fixtures/blend.py (headers, +-- versions, zstd); errors; the fuzz pass. +local T = require("@tests/T") +local Blend = require("@rosetta/containers/Blend") +local Deflate = require("@rosetta/codecs/compress/Deflate") +local Err = require("@rosetta/core/Err") +local Cur = require("@tests/gen/blend_cur") +local Old = require("@tests/gen/blend_293") + +local t = T.suite("containers/Blend") + +-- a writer of either byte order +local function writer(little: boolean) + local parts: { string } = {} + local w = {} + local function bytes(v: number, n: number): string + local s = {} + for k = 0, n - 1 do + s[k + 1] = string.char(math.floor(v / 256 ^ k) % 256) + end + local str = table.concat(s) + return if little then str else string.reverse(str) + end + function w.u8(v: number) + table.insert(parts, string.char(v)) + end + function w.i16(v: number) + table.insert(parts, bytes(v % 65536, 2)) + end + function w.i32(v: number) + table.insert(parts, bytes(v % 4294967296, 4)) + end + function w.u64(v: number) + table.insert(parts, bytes(v, 8)) + end + function w.f32(v: number) + local b = buffer.create(4) + buffer.writef32(b, 0, v) + local s = buffer.tostring(b) + table.insert(parts, if little then s else string.reverse(s)) + end + function w.f64(v: number) + local b = buffer.create(8) + buffer.writef64(b, 0, v) + local s = buffer.tostring(b) + table.insert(parts, if little then s else string.reverse(s)) + end + function w.str(s: string) + table.insert(parts, s) + end + function w.ptr(v: number, ps: number) + if ps == 8 then + w.u64(v) + else + w.i32(v) + end + end + function w.done(): string + return table.concat(parts) + end + return w +end + +-- SDNA: ListBase { void *first, *last }; Thing { Thing *next, *prev; int a; float b[2]; char name[8]; short s; +-- char pad[2]; void *data }; Holder { ListBase things; Thing *one; double d; ID-less } +local NAMES = { "*first", "*last", "*next", "*prev", "a", "b[2]", "name[8]", "s", "pad[2]", "*data", "things", "*one", "d" } +local TYPES = { "char", "short", "int", "float", "double", "void", "ListBase", "Thing", "Holder" } + +local function sdna(little: boolean, ps: number): string + local w = writer(little) + local function pad() + local s = w.done() + return (4 - #s % 4) % 4 + end + w.str("SDNA") + w.str("NAME") + w.i32(#NAMES) + for _, n in NAMES do + w.str(n .. "\0") + end + for _ = 1, pad() do + w.u8(0) + end + w.str("TYPE") + w.i32(#TYPES) + for _, n in TYPES do + w.str(n .. "\0") + end + for _ = 1, pad() do + w.u8(0) + end + w.str("TLEN") + local thing = ps * 2 + 4 + 8 + 8 + 2 + 2 + ps + for _, l in { 1, 2, 4, 4, 8, 0, ps * 2, thing, ps * 2 + ps + 8 } do + w.i16(l) + end + for _ = 1, pad() do + w.u8(0) + end + w.str("STRC") + w.i32(3) + local function struct(ty: number, fields: { { number } }) + w.i16(ty) + w.i16(#fields) + for _, f in fields do + w.i16(f[1]) + w.i16(f[2]) + end + end + -- type / name indices are 0-based + struct(6, { { 5, 0 }, { 5, 1 } }) + struct(7, { { 7, 2 }, { 7, 3 }, { 2, 4 }, { 3, 5 }, { 0, 6 }, { 1, 7 }, { 0, 8 }, { 5, 9 } }) + struct(8, { { 6, 10 }, { 7, 11 }, { 4, 12 } }) + return w.done() +end + +local function file(little: boolean, ps: number, large: boolean, dupe: boolean?): string + local w = writer(little) + if large then + w.str("BLENDER17-01v0502") + else + w.str("BLENDER" .. (if ps == 8 then "-" else "_") .. (if little then "v" else "V") .. "279") + end + local function head(code: string, size: number, addr: number, sdnaIndex: number, count: number) + w.str(code .. string.rep("\0", 4 - #code)) + if large then + w.i32(sdnaIndex) + w.u64(addr) + w.u64(size) + w.u64(count) + else + w.i32(size) + w.ptr(addr, ps) + w.i32(sdnaIndex) + w.i32(count) + end + end + local thingSize = ps * 2 + 24 + ps + head("HO", ps * 3 + 8, 0x1000, 2, 1) + w.ptr(0x2000, ps) -- things.first + w.ptr(0x3000, ps) -- things.last + w.ptr(0x3000, ps) -- one + w.f64(2.5) + local function thing(next: number, prev: number, a: number, b1: number, b2: number, name: string, s: number, data: number) + w.ptr(next, ps) + w.ptr(prev, ps) + w.i32(a) + w.f32(b1) + w.f32(b2) + w.str(name .. string.rep("\0", 8 - #name)) + w.i16(s) + w.str("\0\0") + w.ptr(data, ps) + end + head("DATA", thingSize, 0x2000, 1, 1) + thing(0x3000, 0, -7, 1.5, -2.25, "first", -300, 0x4000) + head("DATA", thingSize, 0x3000, 1, 1) + thing(0, 0x2000, 123456, 0.5, 4, "second!", 1234, 0) + head("DATA", 6, 0x4000, 0, 1) + w.str("hello\0") + if dupe then + -- a second ID whose own data reuses the address 0x4000 + head("H2", ps * 3 + 8, 0x5000, 2, 1) + w.ptr(0, ps) + w.ptr(0, ps) + w.ptr(0x4000, ps) + w.f64(-1) + head("DATA", thingSize, 0x4000, 1, 1) + thing(0, 0, 99, 0, 0, "dup", 0, 0) + end + local dna = sdna(little, ps) + head("DNA1", #dna, 0x9000, 0, 1) + w.str(dna) + head("ENDB", 0, 0, 0, 0) + return w.done() +end + +for _, v in { { true, 8, false }, { true, 4, false }, { false, 8, false }, { false, 4, false }, { true, 8, true } } do + local little, ps, large = v[1], v[2], v[3] + local label = string.format("%s-endian, %d-byte pointers%s", if little then "little" else "big", ps, if large then ", 5.0 header" else "") + local f, err = Blend.open(buffer.fromstring(file(little, ps, large))) + t:check(f, label .. ": open: " .. tostring(err)) + if not f then + continue + end + t:eq(f.pointerSize, ps, label .. ": pointer size") + t:eq(f.little, little, label .. ": byte order") + t:eq(f.version, if large then 502 else 279, label .. ": version") + t:eq(f.format, if large then 1 else 0, label .. ": format") + t:eq(#f.blocks, 5, label .. ": blocks (ENDB not listed)") + t:eq(f.dna.byName.Thing.size, ps * 3 + 24, label .. ": struct size from TLEN") + t:eq(f.dna.byName.Thing.byName.data.offset, ps * 2 + 24, label .. ": field offsets") + local ho = assert(Blend.struct(f, Blend.blocks(f, "HO")[1])) + t:eq(ho:num("d"), 2.5, label .. ": double") + local list = ho:list("things") + t:eq(#list, 2, label .. ": ListBase walk") + t:eq(list[1]:num("a"), -7, label .. ": int") + t:eq(list[2]:num("a"), 123456, label .. ": int 2") + t:eq(list[1]:num("s"), -300, label .. ": short") + t:eq(list[1]:str("name"), "first", label .. ": char array") + t:eq(list[2]:str("name"), "second!", label .. ": char array 2") + local b = list[1]:vec("b") + t:check(b and b[1] == 1.5 and b[2] == -2.25, label .. ": float array") + t:eq(list[1]:cstring("data"), "hello", label .. ": pointer to raw data") + local one = ho:deref("one") + t:check(one and one:num("a") == 123456, label .. ": deref by field type") + t:check(ho:ptr("one") ~= nil and list[2]:ptr("next") == nil, label .. ": null pointers are nil") + t:check(ho:get("missing") == nil and ho:has("d") and not ho:has("missing"), label .. ": unknown fields") + t:eq(ho:num("missing", "d"), 2.5, label .. ": the first existing of several names") + local fld = Blend.field(f, "Thing", "nope", "b") + t:check(fld and fld.count == 2 and fld.type == "float" and #fld.dims == 1, label .. ": Blend.field") +end + +-- an address reused by another ID's data resolves inside the ID that points at it +do + local f = assert(Blend.open(buffer.fromstring(file(true, 8, false, true)))) + local h1 = assert(Blend.struct(f, Blend.blocks(f, "HO")[1])) + local h2 = assert(Blend.struct(f, Blend.blocks(f, "H2")[1])) + t:eq(h1:list("things")[1]:cstring("data"), "hello", "reused address: the first ID's raw data") + local d = h2:deref("one") + t:check(d and d:num("a") == 99 and d:str("name") == "dup", "reused address: the second ID's own block") +end + +-- gzip (Blender before 3.0) +do + local raw = file(true, 8, false) + local gz = assert(Deflate.gzip(raw)) + local f, err = Blend.open(gz) + t:check(f and f.compression == "gzip" and #f.blocks == 5, "gzip: " .. tostring(err)) + t:eq(Blend.sniff(gz), 0.05, "gzip sniffs weakly") + t:eq(Blend.sniff(buffer.fromstring(raw)), 1, "magic") +end + +-- the real files: headers and compression +for _, set in { Cur, Old } do + for _, c in set do + local f, err = Blend.open(buffer.fromstring(c.data)) + t:check(f, c.name .. ": " .. tostring(err)) + if f then + local want = c.ref.version[1] * 100 + c.ref.version[2] + t:eq(f.version, want, c.name .. ": version") + t:eq(f.format, if want >= 500 then 1 else 0, c.name .. ": header format") + if string.find(c.name, "_z%.blend$") then + t:eq(f.compression, if want >= 300 then "zstd" else "gzip", c.name .. ": compression") + end + t:check(f.dna.byName.Object and f.dna.byName.Mesh and #Blend.blocks(f, "OB") > 0, c.name .. ": SDNA and objects") + end + end +end + +-- errors +local function code(s: string): string? + local f, e = Blend.open(buffer.fromstring(s)) + return if f then nil else e.code +end +local good = file(true, 8, false) +t:eq(code("BLEND"), Err.TRUNCATED, "short file") +t:eq(code("NOTBLEND-v279" .. string.rep("\0", 40)), Err.CORRUPT, "bad magic") +t:eq(code(string.sub(good, 1, #good - 30)), Err.TRUNCATED, "no ENDB") +t:eq(code("BLENDER17-02v0502" .. string.rep("\0", 40)), Err.UNSUPPORTED, "unknown header format version") +local noDna = string.gsub(good, "DNA1", "DNA2") +t:eq(code(noDna), Err.CORRUPT, "no DNA1") +local badDna = string.gsub(good, "STRC", "STRX") +t:eq(code(badDna), Err.CORRUPT, "bad SDNA") +local _, e = Blend.open(buffer.fromstring(good), 0, 999999) +t:eq(e and e.code, Err.ARG, "bad range") + +local samples = { good, file(false, 4, false), file(true, 8, true, true) } +t:fuzz("open", function(b: buffer) + local f = Blend.open(b) + if f then + for _, blk in f.blocks do + local v = Blend.struct(f, blk) + if v then + for _, fld in v.struct.fields do + local x = v:get(fld.name) + if fld.pointer then + v:deref(fld.name) + v:array(fld.name) + v:pointers(fld.name) + v:cstring(fld.name) + elseif fld.type == "ListBase" then + v:list(fld.name) + end + local _ = x + end + end + end + end + return f +end, samples, { mutations = 64 }) +t:done() diff --git a/tests/model/blend.luau b/tests/model/blend.luau new file mode 100644 index 0000000..31d4fd9 --- /dev/null +++ b/tests/model/blend.luau @@ -0,0 +1,652 @@ +-- model/blend tests: scenes saved by Blender 2.79, 2.93, 3.5, 4.1 and 5.x (plain, gzip, zstd; the 2.79 legacy mesh +-- format) against the current Blender's own values for the same files (world matrices, mesh counts, bounds, UV / colour +-- sums, corner normals, weights, shape keys, f-curve values, posed matrices per frame, skinned positions) and its +-- glTF exporter (materials, cameras, lights, skins, triangle counts). Fixtures: tools/fixtures/blend.py. +local T = require("@tests/T") +local F = require("@rosetta") +local B = require("@rosetta/model/blend") +local Blend = require("@rosetta/containers/Blend") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Sampler = require("@rosetta/codecs/model/Sampler") +local Versions = require("@tests/gen/blend_versions") +local Files = require("@tests/gen/blend_files") +local Sets = { + ["279"] = require("@tests/gen/blend_279"), + ["293"] = require("@tests/gen/blend_293"), + ["35"] = require("@tests/gen/blend_35"), + ["41"] = require("@tests/gen/blend_41"), + cur = require("@tests/gen/blend_cur"), + old = require("@tests/gen/blend_old"), -- Blender 1.66 - 2.04 demo files (big-endian among them) +} + +local t = T.suite("blend") +local Scene = Types.Scene + +t:eq(B.name, "blend", "name") +t:eq(B.category, "model", "category") +t:check(B.caps.decode and not B.caps.encode, "read only") +t:eq(#Versions, 5, "every Blender version made its files (" .. table.concat(Versions, " ") .. ")") + +local function decode(data: string, opts: any?): (any, any) + return B.decode(Bytes.reader(buffer.fromstring(data)), 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 + +local function nearList(a: { number }?, b: { number }?, eps: number): boolean + if not a or not b or #a ~= #b then + return false + end + for i = 1, #a do + if not near(a[i], b[i], eps) then + return false + end + end + return true +end + +local function fmt(m: { number }?): string + if not m then + return "nil" + end + local s = {} + for i, v in m do + s[i] = string.format("%.4f", v) + end + return table.concat(s, " ") +end + +-- world matrices of every node, with an optional pose ({ [node] = { translation, rotation, scale, weights } }) +local function worlds(scene: any, pose: any?): { [number]: { number } } + local out = {} + local function walk(i: number, parent: { number }) + local n = scene.nodes[i] + local p = pose and pose[i] + local m + if p then + local base = if n.matrix then { Mat4.decompose(n.matrix) } else { n.translation, n.rotation, n.scale } + m = Mat4.compose(p.translation or base[1], p.rotation or base[2], p.scale or base[3]) + else + m = Scene.nodeMatrix(n) + end + local w = Scene.mul(parent, m) + out[i] = w + for _, c in n.children do + walk(c, w) + end + end + for _, r in scene.roots do + walk(r, Mat4.identity()) + end + return out +end + +local function byName(scene: any): ({ [string]: number }, { [string]: number }) + local objects, bones = {}, {} + for i, n in scene.nodes do + local e = n.extras and n.extras.blend + if e and e.bone then + bones[n.name] = i + elseif e and e.type then + objects[n.name] = i + end + end + return objects, bones +end + +local function read(acc: any): (number, number) -> number + return assert(Scene.reader(acc)) +end + +-- the corners of the polygons decode in Blender's loop order: { prim, vertex } per corner +local function corners(mesh: any, facemats: { number }, faceSizes: { number }?): { { any } }? + local slots = {} + local cursor = {} + for _, p in mesh.primitives do + table.insert(slots, p) + end + local used = {} + for _, m in facemats do + used[m] = true + end + local order = {} + for m in used do + table.insert(order, m) + end + table.sort(order) + local primOf = {} + for k, m in order do + primOf[m] = slots[k] + end + local out = {} + for fi, m in facemats do + local p = primOf[m] + if not p or not p.faces then + return nil + end + local c = cursor[p] or { face = 0, at = 0 } + cursor[p] = c + local size = buffer.readu32(p.faces.data, c.face * 4) + if faceSizes and faceSizes[fi] ~= size then + return nil + end + for k = 0, size - 1 do + table.insert(out, { p, buffer.readu32(p.indices.data, (c.at + k) * 4) }) + end + c.face += 1 + c.at += size + end + return out +end + +local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } +local samples = {} + +t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")") +for _, tag in { "old", "279", "293", "35", "41", "cur" } do + for _, c in Sets[tag] do + local ref = c.ref + local label = c.name + local scene, err = decode(c.data, { files = Files }) + t:check(scene, label .. ": decode: " .. tostring(err)) + if not scene then + continue + end + if #c.data < 500000 and #samples < 2 then + table.insert(samples, c.data) + end + local src = scene.meta.source + t:eq(src.format, "blend", label .. ": meta.source.format") + t:eq(scene.meta.up, "z", label .. ": z up") + if string.find(label, "_z%.blend$") then + t:eq(src.compression, if src.version < 300 then "gzip" else "zstd", label .. ": compression") + end + local objects, bones = byName(scene) + local W = worlds(scene) + -- objects: world matrices at the saved frame + for _, o in ref.objects do + local i = objects[o.name] + t:check(i, label .. ": object " .. o.name) + if i then + t:check(nearList(W[i], o.world, 1e-4), label .. ": " .. o.name .. " world\n got " .. fmt(W[i]) .. "\n want " .. fmt(o.world)) + checked.worlds += 1 + end + end + -- meshes + local polyScene = decode(c.data, { triangulate = false }) + local polyObjects = polyScene and byName(polyScene) + for _, o in ref.objects do + local mi = o.mesh + local i = objects[o.name] + if not mi or not i then + continue + end + local node = scene.nodes[i] + local mesh = scene.meshes[node.mesh] + t:check(mesh, label .. ": " .. o.name .. " has a mesh") + if not mesh then + continue + end + local e = mesh.extras.blend + t:eq(e.vertices, mi.vertices, label .. ": " .. o.name .. " vertices") + local tris = 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, p in mesh.primitives do + tris += p.indices.count // 3 + local P = read(p.attributes.POSITION) + for v = 0, p.attributes.POSITION.count - 1 do + for k = 1, 3 do + lo[k] = math.min(lo[k], P(v, k - 1)) + hi[k] = math.max(hi[k], P(v, k - 1)) + end + end + end + t:eq(tris, mi.triangles, label .. ": " .. o.name .. " triangles") + if e.generation == "mface" then + -- the 2.7x legacy save drops n-gons, leaving their vertices loose: inside the bounds + local inside = true + for k = 1, 3 do + inside = inside and lo[k] >= mi.min[k] - 1e-5 and hi[k] <= mi.max[k] + 1e-5 + end + t:check(inside, label .. ": " .. o.name .. " bounds") + else + t:check(nearList(lo, mi.min, 1e-5) and nearList(hi, mi.max, 1e-5), label .. ": " .. o.name .. " bounds") + end + t:eq(e.faces, mi.faces, label .. ": " .. o.name .. " faces") + t:eq(e.corners, mi.corners, label .. ": " .. o.name .. " corners") + t:eq(#mesh.primitives, (function() + local u, n = {}, 0 + for _, m in mi.facemats do + if not u[m] then + u[m] = true + n += 1 + end + end + return n + end)(), label .. ": " .. o.name .. " one primitive per used slot") + checked.meshes += 1 + -- corner level (the polygons decode, in Blender's loop order) + local pm = polyScene and polyScene.meshes[polyScene.nodes[polyObjects[o.name]].mesh] + local cs = pm and corners(pm, mi.facemats) + t:check(cs and #cs == mi.corners, label .. ": " .. o.name .. " corners in loop order") + if not cs then + continue + end + for k, uv in mi.uvs do + local su, sv = 0, 0 + for _, cv in cs do + local acc = cv[1].attributes["TEXCOORD_" .. (k - 1)] + if acc then + local get = read(acc) + su += get(cv[2], 0) + sv += 1 - get(cv[2], 1) + end + end + t:check(near(su, uv.sum[1], 1e-4) and near(sv, uv.sum[2], 1e-4), label .. ": " .. o.name .. " uv " .. uv.name .. " sums " .. su .. " " .. sv) + end + for _, col in mi.colors do + local s = { 0, 0, 0, 0 } + local found = false + for _, cv in cs do + for name, acc in cv[1].attributes do + if string.sub(name, 1, 6) == "COLOR_" and acc.name == col.name then + found = true + local get = read(acc) + for k = 1, 4 do + s[k] += get(cv[2], k - 1) + end + end + end + end + t:check(found and nearList(s, col.cornerSum, 1e-3), label .. ": " .. o.name .. " colour " .. col.name .. " " .. fmt(s) .. " / " .. fmt(col.cornerSum)) + end + if mi.normals then + local worst = 0 + for ci, cv in cs do + local get = read(cv[1].attributes.NORMAL) + local want = mi.normals[ci] + for k = 1, 3 do + worst = math.max(worst, math.abs(get(cv[2], k - 1) - want[k])) + end + end + t:check(worst < (if mi.custom then 2e-3 else 1e-4), label .. ": " .. o.name .. " corner normals (worst " .. string.format("%.2g", worst) .. (if mi.custom then ", custom" else "") .. ")") + checked.normals += 1 + end + -- deform weights: the deform bones' groups, top 4 normalized + local arm = nil + for _, a in ref.armatures do + arm = a + end + if mi.weights and arm and node.skin then + local deform = {} + for _, b in arm do + deform[b.name] = b.deform + end + local skin = scene.skins[node.skin] + local jointOf = {} + for j, n in skin.joints do + jointOf[scene.nodes[n].name] = j - 1 + end + local bad = 0 + for ci, cv in cs do + local list = {} + for _, g in mi.weights[mi.cornerVerts[ci] + 1] do + if deform[g[1]] and g[2] > 0 then + table.insert(list, { jointOf[g[1]], g[2] }) + end + end + table.sort(list, function(a, b) + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #list) do + sum += list[k][2] + end + local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0) + for k = 1, math.min(4, #list) do + local ok = false + for q = 0, 3 do + if J(cv[2], q) == list[k][1] and near(Wt(cv[2], q), list[k][2] / sum, 1e-5) then + ok = true + end + end + if not ok then + bad += 1 + end + end + end + t:eq(bad, 0, label .. ": " .. o.name .. " joints / weights per corner") + checked.weights += 1 + end + if mi.shapes then + local refIndex = 1 + for k, s in mi.shapes do + if s.name == mi.reference then + refIndex = k + end + end + t:eq(#(mesh.weights or {}), #mi.shapes - 1, label .. ": " .. o.name .. " morph weights") + local ti = 0 + local worst = 0 + for k, s in mi.shapes do + if k ~= refIndex then + ti += 1 + if not o.shapeAction then -- animated values are checked per frame below + t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") + end + for ci, cv in if mi.cornerVerts then cs else {} do + local tgt = cv[1].targets and cv[1].targets[ti] + local get = tgt and read(tgt.POSITION) + local v = mi.cornerVerts[ci] + for q = 1, 3 do + local want = s.co[v * 3 + q] - mi.shapes[refIndex].co[v * 3 + q] + worst = math.max(worst, if get then math.abs(get(cv[2], q - 1) - want) else math.huge) + end + end + end + end + t:check(worst < 1e-5, label .. ": " .. o.name .. " shape key deltas (worst " .. worst .. ")") + checked.shapes += 1 + end + end + -- materials against the glTF exporter (Principled) or the legacy colour + local gl = ref.gltf or {} + local glMats = {} + for _, m in gl.materials or {} do + glMats[m.name] = m + end + for _, m in scene.materials do + local g = glMats[m.name] + if m.extras.blend.principled and g then + local pbr = g.pbrMetallicRoughness or {} + t:check(nearList(m.baseColor, pbr.baseColorFactor or { 1, 1, 1, 1 }, 1e-5), label .. ": " .. m.name .. " base colour " .. fmt(m.baseColor)) + t:check(near(m.metallic, pbr.metallicFactor or 1, 1e-5) and near(m.roughness, pbr.roughnessFactor or 1, 1e-5), label .. ": " .. m.name .. " metallic / roughness") + t:check(nearList(m.emissive, g.emissiveFactor or { 0, 0, 0 }, 1e-5), label .. ": " .. m.name .. " emissive " .. fmt(m.emissive)) + local ges = g.extensions and g.extensions.KHR_materials_emissive_strength + local es = m.extensions and m.extensions.KHR_materials_emissive_strength + t:check(near(es and es.emissiveStrength or 1, ges and ges.emissiveStrength or 1, 1e-5), label .. ": " .. m.name .. " emissive strength") + t:eq(string.upper(m.alphaMode), g.alphaMode or "OPAQUE", label .. ": " .. m.name .. " alpha mode") + t:eq(m.baseColorTexture ~= nil, pbr.baseColorTexture ~= nil, label .. ": " .. m.name .. " base colour texture") + t:eq(m.emissiveTexture ~= nil, g.emissiveTexture ~= nil, label .. ": " .. m.name .. " emissive texture") + t:eq(m.normalTexture ~= nil, g.normalTexture ~= nil, label .. ": " .. m.name .. " normal texture") + if g.normalTexture and m.normalTexture then + t:check(near(m.normalTexture.scale, g.normalTexture.scale or 1, 1e-5), label .. ": " .. m.name .. " normal scale") + end + checked.materials += 1 + elseif not m.extras.blend.principled then + for _, rm in ref.materials do + if rm.name == m.name then + t:check(nearList({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, { rm.diffuse[1], rm.diffuse[2], rm.diffuse[3] }, 1e-5), label .. ": " .. m.name .. " legacy colour") + checked.materials += 1 + end + end + end + end + -- images: packed bytes, external uris (with the bytes from opts.files) + for _, im in ref.images do + local tex = nil + for _, x in scene.textures do + if x.name == im.name then + tex = x + end + end + if not tex then + continue -- not used by a node material (legacy texture slots, face images) + elseif im.packed > 0 then + t:check(tex.data and buffer.len(tex.data) == im.packed and (tag == "old" or tex.mime == "image/png"), label .. ": packed image " .. im.name) + else + t:eq(tex.uri, "outside.png", label .. ": external image uri") + t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files") + end + end + -- cameras and lights against the glTF exporter + for _, gc in gl.cameras or {} do + local cam = nil + for _, x in scene.cameras do + if x.name == gc.name then + cam = x + end + end + t:check(cam, label .. ": camera " .. gc.name) + if cam then + if gc.type == "perspective" then + t:check(cam.type == "perspective" and near(cam.yfov, gc.perspective.yfov, 1e-5) and near(cam.znear, gc.perspective.znear, 1e-5) and near(cam.zfar, gc.perspective.zfar, 1e-5), label .. ": perspective " .. gc.name) + else + t:check(cam.type == "orthographic" and near(cam.xmag, gc.orthographic.xmag, 1e-5) and near(cam.ymag, gc.orthographic.ymag, 1e-5), label .. ": orthographic " .. gc.name) + end + checked.cameras += 1 + end + end + local glLights = gl.extensions and gl.extensions.KHR_lights_punctual and gl.extensions.KHR_lights_punctual.lights or {} + t:eq(#scene.lights, #glLights, label .. ": lights (the area light is skipped)") + for _, gli in glLights do + local l = nil + for _, x in scene.lights do + if x.name == gli.name then + l = x + end + end + t:check(l and l.type == gli.type and near(l.intensity, gli.intensity, 1e-5) and nearList(l.color, gli.color, 1e-5), label .. ": light " .. gli.name .. " " .. (l and l.intensity or -1) .. " " .. gli.intensity) + if l and gli.spot then + t:check(near(l.outerCone, gli.spot.outerConeAngle, 1e-5) and near(l.innerCone, gli.spot.innerConeAngle, 1e-5), label .. ": spot cones") + end + checked.lights += 1 + end + -- triangles: the glTF exporter's meshes + local curves = false -- the exporter turns curves / text / surfaces / metaballs into meshes; we do not + for _, o in ref.objects do + curves = curves or o.type == "CURVE" or o.type == "FONT" or o.type == "SURFACE" or o.type == "META" + end + if gl.meshes and not curves then + -- per instance (both sides share meshes differently) + local want = 0 + for _, n in gl.nodes or {} do + if n.mesh then + for _, p in gl.meshes[n.mesh + 1].primitives do + want += gl.accessors[p.indices + 1].count // 3 + end + end + end + local got = 0 + for _, n in scene.nodes do + if n.mesh then + for _, p in scene.meshes[n.mesh].primitives do + got += p.indices.count // 3 + end + end + end + t:eq(got, want, label .. ": triangles (glTF exporter)") + end + t:eq(#scene.skins, #(gl.skins or {}), label .. ": skins (glTF exporter)") + for k, s in scene.skins do + t:eq(#s.joints, #gl.skins[k].joints, label .. ": skin joints") + end + -- bones at the saved frame (the rest pose here) + for armName, list in ref.armatures do + local aw = W[objects[armName]] + for _, b in list do + local j = bones[b.name] + t:check(j and nearList(W[j], Scene.mul(aw, b["local"]), 1e-4), label .. ": bone " .. b.name) + end + end + -- f-curves through the evaluator, at every half frame (bezier, linear, constant, extrapolation) + local file = assert(Blend.open(buffer.fromstring(c.data))) + for _, o in ref.objects do + local refCurves = o.action and ref.actions[o.action] + if refCurves then + local ob = nil + for _, blk in Blend.blocks(file, "OB") do + local v = Blend.struct(file, blk) + if v and v:idName() == o.name then + ob = v + end + end + local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData")) + if not curves and ob and not ob:has("adt") then + curves = B.ipo(file, ob:deref("ipo", 0, "Ipo")) -- before 2.5 + end + curves = curves or {} + for _, rc in refCurves do + local p = rc.path + if not (p == "location" or p == "scale" or string.find(p, "rotation") or string.find(p, "^delta_")) then + continue -- only the transform curves are read + end + local cur = nil + for _, x in curves do + if x.path == rc.path and x.index == rc.index then + cur = x + end + end + local worst = 0 + for k, want in rc.values do + local got = if cur then B.evaluate(cur, 1 + 0.5 * (k - 1)) else math.huge + worst = math.max(worst, math.abs(got - want)) + end + t:check(worst < 1e-4, label .. ": " .. o.name .. " " .. rc.path .. "[" .. rc.index .. "] (worst " .. worst .. ")") + checked.curves += 1 + end + end + end + -- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions + if #ref.poses > 0 then + local animated = false -- transform or shape key curves (others, such as an object colour, are not read) + for _, list in ref.actions do + for _, rc in list do + local p = rc.path + animated = animated or p == "location" or p == "scale" or string.find(p, "rotation") ~= nil or string.find(p, "key_blocks") ~= nil + end + end + t:check(#scene.animations > 0 or not animated, label .. ": animations") + local caches = {} + for _, p in ref.poses do + local frame = p.frame + if frame ~= math.floor(frame) or frame > 20 then + continue + end + local time = (frame - (src.frameZero or src.frameStart)) / src.fps + local pose = {} + for ai, a in scene.animations do + caches[ai] = caches[ai] or {} + for node, v in Sampler.pose(scene, a, time, caches[ai]) do + pose[node] = pose[node] or {} + for k, x in v do + pose[node][k] = x + end + end + end + local PW = worlds(scene, pose) + for name, want in p.objects do + local i = objects[name] + t:check(i and nearList(PW[i], want, 1e-3), label .. ": frame " .. frame .. " " .. name .. "\n got " .. fmt(i and PW[i]) .. "\n want " .. fmt(want)) + end + for key, want in p.bones do + local j = bones[string.match(key, "/(.+)$")] + t:check(j and nearList(PW[j], want, 1e-3), label .. ": frame " .. frame .. " bone " .. key) + end + for name, values in p.shapes do + local i = objects[name] + local w = pose[i] and pose[i].weights or scene.nodes[i].weights + local want = table.move(values, 2, #values, 1, {}) + -- pre-2.5 IPO bezier keys: Blender recomputes auto handles when converting them; we keep the stored ones + local eps = if tag == "old" then 1e-2 else 1e-3 + t:check(nearList(w, want, eps), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) + end + for name, want in p.skinned or {} do + -- morph, then skin: sum of w * jointWorld * inverseBind * position + local i = objects[name] + local node = polyScene.nodes[polyObjects[name]] + local mi = nil + for _, o in ref.objects do + if o.name == name then + mi = o.mesh + end + end + local pm = polyScene.meshes[node.mesh] + local cs = corners(pm, mi.facemats) + local skin = scene.skins[scene.nodes[i].skin] + local IB = read(skin.inverseBindMatrices) + local weights = pose[i] and pose[i].weights or scene.nodes[i].weights or {} + local worst = 0 + for ci, cv in cs do + local P = read(cv[1].attributes.POSITION) + local x, y, z = P(cv[2], 0), P(cv[2], 1), P(cv[2], 2) + for ti, tg in cv[1].targets or {} do + local D = read(tg.POSITION) + x += D(cv[2], 0) * (weights[ti] or 0) + y += D(cv[2], 1) * (weights[ti] or 0) + z += D(cv[2], 2) * (weights[ti] or 0) + end + local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0) + local ox, oy, oz = 0, 0, 0 + for q = 0, 3 do + local w = Wt(cv[2], q) + if w > 0 then + local j = J(cv[2], q) + local ib = {} + for k = 0, 15 do + ib[k + 1] = IB(j, k) + end + local m = Scene.mul(PW[skin.joints[j + 1]], ib) + local px, py, pz = Mat4.point(m, x, y, z) + ox += w * px + oy += w * py + oz += w * pz + end + end + local v = mi.cornerVerts[ci] + worst = math.max(worst, math.abs(ox - want[v * 3 + 1]), math.abs(oy - want[v * 3 + 2]), math.abs(oz - want[v * 3 + 3])) + end + t:check(worst < 1e-3, label .. ": frame " .. frame .. " " .. name .. " skinned positions (worst " .. worst .. ")") + checked.skinned += 1 + end + checked.frames += 1 + end + end + end +end +t:note("checked: %d world matrices, %d meshes, %d corner normal sets, %d weight sets, %d shape key sets, %d f-curves, %d posed frames, %d skinned frames, %d materials, %d cameras, %d lights", + checked.worlds, checked.meshes, checked.normals, checked.weights, checked.shapes, checked.curves, checked.frames, checked.skinned, checked.materials, checked.cameras, checked.lights) + +-- the api: by extension and magic, compressed files included +local cur = Sets.cur[1] +if cur then + t:eq(F.detect(buffer.fromstring(cur.data)), "blend", "F.detect") + local s = F.load(buffer.fromstring(cur.data)) + t:check(s and s.kind == "scene", "F.load") +end + +-- compressed files: by content for model loads, by extension otherwise +for _, c in Sets.cur do + if string.find(c.name, "_z%.blend$") then + local b = buffer.fromstring(c.data) + local s = F.model.load(b) + t:check(s and s.meta.source.compression == "zstd", "F.model.load of a zstd .blend") + t:eq(F.detect(b, { name = "x.blend" }), "blend", "F.detect of a zstd .blend by name") + end +end +for _, c in Sets["293"] do + if string.find(c.name, "_z%.blend$") then + local s = F.model.load(buffer.fromstring(c.data)) + t:check(s and s.meta.source.compression == "gzip", "F.model.load of a gzip .blend") + end +end + +-- errors +local function code(data: string): string? + local s, e = decode(data) + return if s then nil else e.code +end +t:eq(code("BLENDER"), Err.TRUNCATED, "a 7-byte file is truncated") +t:eq(code("BLENDER-v279REND"), Err.TRUNCATED, "a truncated block header") +t:eq(code("BLENDERxv279" .. string.rep("\0", 24)), Err.CORRUPT, "bad pointer size") +t:eq(code("BLENDER-v279ENDB" .. string.rep("\0", 20)), Err.CORRUPT, "no DNA1 block") + +t:fuzz("decode", function(b: buffer) + return B.decode(Bytes.reader(b)) +end, samples, { mutations = 24 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 7c2e96f..51d1704 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -961,6 +961,15 @@ do bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function() Fbx.decode(Bytes.reader(fbxa)) end) + local BlendFmt = require("@rosetta/model/blend") + for _, c in require("@tests/gen/blend_cur") do + if c.name == "rig_52.blend" or c.name == "scene_52_z.blend" then + local bb = buffer.fromstring(c.data) + bench("blend decode " .. c.name .. " (" .. buffer.len(bb) // 1000 .. " KB)", 5, buffer.len(bb), function() + BlendFmt.decode(Bytes.reader(bb)) + end) + end + end local ThreeMf = require("@rosetta/model/3mf") local tmf = assert(ThreeMf.encode(scene)) bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function() diff --git a/tools/fixtures/_blend_make.py b/tools/fixtures/_blend_make.py new file mode 100644 index 0000000..0d91b24 --- /dev/null +++ b/tools/fixtures/_blend_make.py @@ -0,0 +1,402 @@ +# tools/fixtures/_blend_make: run by tools/fixtures/blend.py inside Blender 2.79 .. 5.x (blender -b --python -- +# ): builds the test scenes with whatever API the running version has and saves them as .blend files: +# scene_.blend collections, transforms (euler / quaternion / delta), parenting with a parent inverse, +# meshes (quads, an n-gon, smooth / flat), two UV maps, colour attributes, materials (Principled +# + packed and external images, a legacy one), cameras, lights, modifiers +# rig_.blend armature with rolls, a skinned mesh (vertex groups, 5 influences on some vertices), shape +# keys, actions on bones / objects / shape keys (bezier, linear, constant), a bone parent +# scene__z.blend scene_ saved compressed (gzip before 3.0, zstd after) +# compat_.blend 2.7x only: the "legacy mesh format" save (MFace tessellated faces) +import bpy, sys, os, math + +out = sys.argv[sys.argv.index("--") + 1] +V = bpy.app.version +TAG = "%d%d" % (V[0], V[1]) +OLD = V < (2, 80) + + +def reset(): + bpy.ops.wm.read_factory_settings(use_empty=True) if not OLD else bpy.ops.wm.read_factory_settings() + if OLD: + for o in list(bpy.data.objects): + bpy.data.objects.remove(o, do_unlink=True) + sc = bpy.context.scene + sc.render.fps = 24 + if OLD: + sc.render.engine = "CYCLES" + sc.frame_start, sc.frame_end = 1, 20 + + +def link(obj, coll=None): + sc = bpy.context.scene + if OLD: + sc.objects.link(obj) + else: + (coll or sc.collection).objects.link(obj) + return obj + + +def mesh(name, verts, faces, smooth=False): + me = bpy.data.meshes.new(name) + me.from_pydata(verts, [], faces) + me.update() + for p in me.polygons: + p.use_smooth = smooth + return me + + +def uv(me, name, f): + if OLD: + me.uv_textures.new(name) + layer = me.uv_layers[name] + else: + layer = me.uv_layers.new(name=name) + for i, d in enumerate(layer.data): + d.uv = f(i) + + +def byte_colors(me, name): + if V >= (3, 2): + a = me.color_attributes.new(name, "BYTE_COLOR", "CORNER") + data = a.data + else: + data = me.vertex_colors.new(name=name).data + for i, d in enumerate(data): + c = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6) + d.color = c + (1.0,) if len(d.color) == 4 else c + + +def image(name, w, h, f, pack=True, path=None): + img = bpy.data.images.new(name, w, h) + px = [] + for y in range(h): + for x in range(w): + px.extend(f(x, y)) + img.pixels = px + if path: + img.filepath_raw = path + img.file_format = "PNG" + img.save() + img.filepath = "//" + os.path.basename(path) + if pack: + if OLD: + img.pack(as_png=True) + else: + img.pack() + return img + + +def socket(node, *names): + for n in names: + if n in node.inputs: + return node.inputs[n] + return None + + +def principled(mat, base, metallic, rough, emission=None, strength=1.0, alpha=1.0): + mat.use_nodes = True + nt = mat.node_tree + bsdf = None + for n in nt.nodes: + if n.bl_idname == "ShaderNodeBsdfPrincipled": + bsdf = n + if bsdf is None: + for n in list(nt.nodes): + if n.bl_idname != "ShaderNodeOutputMaterial": + nt.nodes.remove(n) + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + outs = [n for n in nt.nodes if n.bl_idname == "ShaderNodeOutputMaterial"] + outn = outs[0] if outs else nt.nodes.new("ShaderNodeOutputMaterial") + nt.links.new(bsdf.outputs[0], outn.inputs["Surface"]) + socket(bsdf, "Base Color").default_value = base + socket(bsdf, "Metallic").default_value = metallic + socket(bsdf, "Roughness").default_value = rough + e = socket(bsdf, "Emission Color", "Emission") + if emission and e: + e.default_value = emission + (1.0,) + s = socket(bsdf, "Emission Strength") + if s: + s.default_value = strength + a = socket(bsdf, "Alpha") + if a: + a.default_value = alpha + return bsdf + + +def tex(mat, img, to, normal=False): + nt = mat.node_tree + t = nt.nodes.new("ShaderNodeTexImage") + t.image = img + if normal: + if not OLD: + img.colorspace_settings.name = "Non-Color" + nm = nt.nodes.new("ShaderNodeNormalMap") + nm.inputs["Strength"].default_value = 0.7 + nt.links.new(t.outputs["Color"], nm.inputs["Color"]) + nt.links.new(nm.outputs["Normal"], to) + else: + nt.links.new(t.outputs["Color"], to) + + +def camera(name, ortho=False): + cam = bpy.data.cameras.new(name) + if ortho: + cam.type = "ORTHO" + cam.ortho_scale = 7.0 + else: + cam.lens = 35.0 + cam.sensor_width = 36.0 + cam.clip_start, cam.clip_end = 0.1, 100.0 + return cam + + +def light(name, kind): + data = (bpy.data.lamps if OLD else bpy.data.lights).new(name, kind) + data.color = (1.0, 0.5, 0.25) + data.energy = {"POINT": 1000.0, "SUN": 3.0, "SPOT": 500.0, "AREA": 200.0}[kind] + if kind == "SPOT": + data.spot_size = 0.8 + data.spot_blend = 0.2 + return data + + +def save(path, compress=False, compat=False): + kw = {"filepath": path, "compress": compress} + if compat: + kw["use_mesh_compat"] = True + bpy.ops.wm.save_as_mainfile(**kw) + + +def update(): + if OLD: + bpy.context.scene.update() + else: + bpy.context.view_layer.update() + + +def scene_file(): + reset() + sc = bpy.context.scene + props = inner = None + if not OLD: + props = bpy.data.collections.new("Props") + sc.collection.children.link(props) + inner = bpy.data.collections.new("Inner") + props.children.link(inner) + cube_v = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)] + cube_f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] + me = mesh("BoxMesh", cube_v, cube_f) + uv(me, "UVMap", lambda i: ((i % 4) / 4 + 0.1, (i // 4) / 6)) + uv(me, "Second", lambda i: (1 - (i % 3) / 3, (i % 2) * 0.5)) + byte_colors(me, "Col") + if V >= (3, 2): + pc = me.color_attributes.new("PCol", "FLOAT_COLOR", "POINT") + for i, d in enumerate(pc.data): + d.color = (i / 8, 1 - i / 8, 0.5 + i / 16, 1.0) + checker = image("checker", 8, 8, lambda x, y: [float((x + y) % 2), 0.5, 0.25, 1.0]) + bumps = image("bumps", 4, 4, lambda x, y: [0.5 + x / 8, 0.5 + y / 8, 1.0, 1.0]) + outside = image("outside", 2, 2, lambda x, y: [1.0, 0.0, x * 1.0, 1.0], pack=False, + path=os.path.join(out, "outside.png")) + red = bpy.data.materials.new("Red") + bsdf = principled(red, (0.8, 0.1, 0.1, 1.0), 0.3, 0.4, (0.2, 0.3, 0.4), 2.0, 0.9) + tex(red, checker, socket(bsdf, "Base Color")) + tex(red, bumps, socket(bsdf, "Normal"), normal=True) + blue = bpy.data.materials.new("Blue") + blue.diffuse_color = (0.1, 0.2, 0.9) if OLD else (0.1, 0.2, 0.9, 1.0) + if not OLD: + blue.metallic = 0.25 + blue.roughness = 0.6 + if V >= (5, 0): + blue.use_nodes = False + me.materials.append(red) + me.materials.append(blue) + for i, p in enumerate(me.polygons): + p.material_index = i % 2 + box = link(bpy.data.objects.new("Box", me), props) + box.location = (1, 2, 3) + box.rotation_euler = (0.3, 0.2, 0.1) + box.scale = (1, 2, 0.5) + box.modifiers.new("Subdiv", "SUBSURF") + # triangle, quad, convex pentagon, concave hexagon + sv = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (2, 0, 0), (3, 0, 0), (3, 1, 0), (2, 1, 0), + (4, 0, 0), (5, 0, 0), (5.5, 0.8, 0), (4.5, 1.5, 0), (3.6, 0.8, 0), + (6, 0, 0), (8, 0, 0), (8, 2, 0), (7, 0.5, 0), (6, 2, 0), (6.5, 1, 0.2)] + sf = [(0, 1, 2), (3, 4, 5, 6), (7, 8, 9, 10, 11), (12, 13, 14, 15, 16, 17)] + shape_me = mesh("ShapeMesh", sv, sf, smooth=True) + glow = bpy.data.materials.new("Glow") + gb = principled(glow, (0.2, 0.9, 0.2, 1.0), 0.0, 0.8, (1.0, 0.8, 0.1), 5.0) + tex(glow, outside, socket(gb, "Emission Color", "Emission") or socket(gb, "Subsurface Color")) + shape_me.materials.append(glow) + shape = link(bpy.data.objects.new("Shape", shape_me), props) + shape.location = (-4, 0, 1) + shape.modifiers.new("Mirror", "MIRROR") + ball_me = mesh("BallMesh", [(math.cos(a * math.pi / 3) * 0.5, math.sin(a * math.pi / 3) * 0.5, z) + for z in (-0.4, 0.4) for a in range(6)], + [(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8), (3, 4, 10, 9), (4, 5, 11, 10), (5, 0, 6, 11), + (5, 4, 3, 2, 1, 0), (6, 7, 8, 9, 10, 11)], smooth=True) + ball = link(bpy.data.objects.new("Ball", ball_me), inner) + ball.location = (-3, 1, 0.5) + ball.rotation_euler = (0, 0, 0.7) + update() + ball.parent = box + ball.matrix_parent_inverse = box.matrix_world.inverted() + pivot = link(bpy.data.objects.new("Pivot", None), props) + pivot.location = (0, -3, 1) + pivot.rotation_mode = "QUATERNION" + q = (0.9, 0.1, 0.3, 0.2) + n = math.sqrt(sum(c * c for c in q)) + pivot.rotation_quaternion = tuple(c / n for c in q) + leaf_me = mesh("LeafMesh", [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)]) + leaf_me.materials.append(glow) + leaf = link(bpy.data.objects.new("Leaf", leaf_me), props) + leaf.parent = pivot + leaf.location = (0.5, 0.25, 0) + leaf.rotation_mode = "ZXY" + leaf.rotation_euler = (0.4, -0.3, 1.1) + leaf.scale = (1.5, 1, 1) + leaf.delta_location = (0, 0, 0.5) + leaf.delta_rotation_euler = (0, 0.2, 0) + leaf.delta_scale = (1, 1, 2) + # smooth grid with custom normals + gv = [(x, y, 0.1 * x * y) for y in range(3) for x in range(3)] + gf = [(0, 1, 4, 3), (1, 2, 5, 4), (3, 4, 7, 6), (4, 5, 8, 7)] + grid_me = mesh("BentMesh", gv, gf, smooth=True) + if V < (4, 1): + grid_me.use_auto_smooth = True + grid_me.normals_split_custom_set_from_vertices([(0.3 * (i % 3 - 1), 0.2 * (i // 3 - 1), 1.0) for i in range(9)]) + bent = link(bpy.data.objects.new("Bent", grid_me), props) + bent.location = (0, 4, 0) + cp = link(bpy.data.objects.new("CamP", camera("CamP"))) + cp.location = (7, -7, 5) + cp.rotation_euler = (1.1, 0, 0.8) + co = link(bpy.data.objects.new("CamO", camera("CamO", True))) + co.location = (0, 0, 10) + for kind in ("POINT", "SUN", "SPOT", "AREA"): + lo = link(bpy.data.objects.new("L" + kind.lower(), light("L" + kind.lower(), kind))) + lo.location = ({"POINT": 4, "SUN": 0, "SPOT": -4, "AREA": 2}[kind], 1, 6) + lo.rotation_euler = (0.5, 0.1, 0) + sc.frame_set(1) + update() + save(os.path.join(out, "scene_%s.blend" % TAG)) + save(os.path.join(out, "scene_%s_z.blend" % TAG), compress=True) + + +def rig_file(): + reset() + sc = bpy.context.scene + arm_data = bpy.data.armatures.new("RigData") + rig = link(bpy.data.objects.new("Rig", arm_data)) + rig.location = (0, 0, 0.5) + rig.rotation_euler = (0, 0, 0.2) + if OLD: + sc.objects.active = rig + else: + bpy.context.view_layer.objects.active = rig + bpy.ops.object.mode_set(mode="EDIT") + eb = arm_data.edit_bones + root = eb.new("root") + root.head, root.tail, root.roll = (0, 0, 0), (0, 0, 1), 0.0 + mid = eb.new("mid") + mid.head, mid.tail, mid.roll, mid.parent, mid.use_connect = (0, 0, 1), (0, 0.5, 2), 0.3, root, True + tip = eb.new("tip") + tip.head, tip.tail, tip.roll, tip.parent, tip.use_connect = (0, 0.5, 2), (0.3, 0.5, 2.8), -0.5, mid, True + aux = eb.new("aux") + aux.head, aux.tail, aux.roll, aux.parent = (0.5, 0, 0.5), (1, 0, 0.5), 0.0, root + nodef = eb.new("nodef") + nodef.head, nodef.tail, nodef.parent, nodef.use_deform = (-0.5, 0, 0.5), (-1, 0, 0.7), root, False + bpy.ops.object.mode_set(mode="OBJECT") + ring = [(math.cos(a * math.pi / 4) * 0.3, math.sin(a * math.pi / 4) * 0.3) for a in range(8)] + bv = [(x, y + (0.25 if z == 2 else 0), z) for z in (0, 1, 2) for x, y in ring] + bf = [(r * 8 + a, r * 8 + (a + 1) % 8, (r + 1) * 8 + (a + 1) % 8, (r + 1) * 8 + a) for r in range(2) for a in range(8)] + body_me = mesh("BodyMesh", bv, bf, smooth=True) + body = link(bpy.data.objects.new("Body", body_me)) + body.parent = rig + body.location = (0, 0, 0) + mod = body.modifiers.new("Armature", "ARMATURE") + mod.object = rig + groups = {n: body.vertex_groups.new(name=n) for n in ("root", "mid", "tip", "aux", "nodef", "extra")} + for i in range(24): + z = i // 8 + groups["root"].add([i], max(0.0, 1.0 - z * 0.6), "REPLACE") + groups["mid"].add([i], 0.3 + 0.2 * (z == 1), "REPLACE") + if z == 2: + groups["tip"].add([i], 0.9, "REPLACE") + if i % 3 == 0: + groups["aux"].add([i], 0.05 + 0.01 * i, "REPLACE") + groups["nodef"].add([i], 0.7, "REPLACE") + groups["extra"].add([i], 0.15, "REPLACE") + body.shape_key_add(name="Basis") + fat = body.shape_key_add(name="Fat") + for i, p in enumerate(fat.data): + p.co = (p.co[0] * 1.5, p.co[1] * 1.5, p.co[2]) + thin = body.shape_key_add(name="Thin") + for i, p in enumerate(thin.data): + p.co = (p.co[0] * 0.5, p.co[1] * 0.5, p.co[2] + 0.1) + thin.value = 0.25 + key = body_me.shape_keys + for f, v in ((1, 0.0), (10, 1.0), (20, 0.2)): + fat.value = v + fat.keyframe_insert("value", frame=f) + hat_me = mesh("HatMesh", [(-0.2, -0.2, 0), (0.2, -0.2, 0), (0, 0.2, 0), (0, 0, 0.3)], [(0, 1, 2), (0, 1, 3), (1, 2, 3), (2, 0, 3)]) + hat = link(bpy.data.objects.new("Hat", hat_me)) + hat.parent = rig + hat.parent_type = "BONE" + hat.parent_bone = "tip" + hat.location = (0.1, 0.2, 0.0) + pose = rig.pose.bones + pose["aux"].rotation_mode = "XYZ" + keys = ((1, (0, 0, 0), (1, 0, 0, 0), (1, 1, 1), (0, 0, 0)), + (10, (0.2, 0.1, 0), (0.92, 0.3, 0.2, 0.1), (1.2, 1, 1), (0.4, 0, 0.3)), + (20, (0, 0.3, 0.2), (0.8, -0.2, 0.5, 0.2), (0.8, 1.1, 1), (-0.3, 0.5, 0))) + for f, loc, quat, scl, eul in keys: + pose["root"].location = loc + pose["root"].keyframe_insert("location", frame=f) + n = math.sqrt(sum(c * c for c in quat)) + pose["mid"].rotation_quaternion = tuple(c / n for c in quat) + pose["mid"].keyframe_insert("rotation_quaternion", frame=f) + pose["tip"].scale = scl + pose["tip"].keyframe_insert("scale", frame=f) + pose["aux"].rotation_euler = eul + pose["aux"].keyframe_insert("rotation_euler", frame=f) + mover = link(bpy.data.objects.new("Mover", mesh("MoverMesh", [(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 1, 2)]))) + for f, loc, rot, scl in ((1, (3, 0, 0), (0, 0, 0), (1, 1, 1)), (8, (3, 2, 1), (0.5, 0, 1), (2, 1, 1)), + (20, (5, 2, 0), (0, 1, -1), (1, 1, 3))): + mover.location, mover.rotation_euler, mover.scale = loc, rot, scl + mover.keyframe_insert("location", frame=f) + mover.keyframe_insert("rotation_euler", frame=f) + mover.keyframe_insert("scale", frame=f) + # easing interpolations (Penner) with explicit and automatic easing + easer = link(bpy.data.objects.new("Easer", None)) + eases = (("SINE", "EASE_IN_OUT"), ("BOUNCE", "AUTO"), ("SINE", "EASE_OUT"), ("BACK", "EASE_IN"), + ("EXPO", "AUTO"), ("CIRC", "EASE_OUT"), ("QUART", "EASE_IN_OUT"), ("EXPO", "EASE_OUT"), ("EXPO", "EASE_IN_OUT"), ("CUBIC", "EASE_IN")) + for k in range(len(eases) + 1): + easer.location = (k % 2 * 2.0, k * 0.5, 0) + easer.keyframe_insert("location", frame=1 + k * 2.5) + for fc in (easer.animation_data.action.fcurves if hasattr(easer.animation_data.action, "fcurves") else + [c for l in easer.animation_data.action.layers for s in l.strips for b in s.channelbags for c in b.fcurves]): + for kp, (ipo, easing) in zip(fc.keyframe_points, eases): + kp.interpolation = ipo + kp.easing = easing + rig_action = rig.animation_data.action + mover_action = mover.animation_data.action + for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}), + (mover_action, {"rotation_euler": "LINEAR", "scale": "CONSTANT"})): + curves = act.fcurves if hasattr(act, "fcurves") else [c for l in act.layers for s in l.strips for b in s.channelbags for c in b.fcurves] + for fc in curves: + for k, ipo in rules.items(): + if fc.data_path.endswith(k): + for kp in fc.keyframe_points: + kp.interpolation = ipo + if fc.data_path == "location" and fc.array_index == 2: + fc.extrapolation = "LINEAR" + sc.frame_set(1) + update() + save(os.path.join(out, "rig_%s.blend" % TAG)) + + +scene_file() +rig_file() +if OLD: + scene_file() + save(os.path.join(out, "compat_%s.blend" % TAG), compat=True) +print("MADE", TAG) diff --git a/tools/fixtures/_blend_ref.py b/tools/fixtures/_blend_ref.py new file mode 100644 index 0000000..fb37763 --- /dev/null +++ b/tools/fixtures/_blend_ref.py @@ -0,0 +1,219 @@ +# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python +# -- ): opens each file (old ones through Blender's versioning) and writes +# /.json with the reference values (object world matrices, mesh counts / bounds / attribute sums / corner normals, +# vertex groups, shape keys, materials, images, cameras, lights, bones, f-curve values, posed world matrices per frame), +# and exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf". +import bpy, sys, os, json, struct, math + +args = sys.argv[sys.argv.index("--") + 1:] +paths, outdir = json.loads(args[0]), args[1] +V = bpy.app.version + + +def mat(m): + return [m[r][c] for c in range(4) for r in range(4)] # column-major + + +def r6(x): + return round(float(x), 6) + + +def color_attrs(me): + out = [] + attrs = me.color_attributes if hasattr(me, "color_attributes") else [] + for a in attrs: + s = [0.0, 0.0, 0.0, 0.0] + for l in me.loops: + d = a.data[l.index if a.domain == "CORNER" else l.vertex_index] + for k in range(4): + s[k] += d.color[k] + out.append({"name": a.name, "domain": a.domain, "type": a.data_type, "count": len(a.data), "cornerSum": [r6(x) for x in s]}) + return out + + +def mesh_info(ob): + me = ob.data + me.calc_loop_triangles() + vs = [v.co for v in me.vertices] + lo = [min(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] + hi = [max(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] + info = { + "name": me.name, "vertices": len(me.vertices), "corners": len(me.loops), "faces": len(me.polygons), + "triangles": len(me.loop_triangles), "min": [r6(x) for x in lo], "max": [r6(x) for x in hi], + "possum": [r6(sum(v[k] for v in vs)) for k in range(3)], + "uvs": [], "colors": color_attrs(me), "slots": [s.material.name if s.material else "" for s in ob.material_slots], + "facemats": [p.material_index for p in me.polygons], + "smooth": [1 if p.use_smooth else 0 for p in me.polygons], + } + for layer in me.uv_layers: + su = sv = 0.0 + for d in layer.data: + su += d.uv[0] + sv += d.uv[1] + info["uvs"].append({"name": layer.name, "sum": [r6(su), r6(sv)], "active_render": bool(layer.active_render)}) + if len(me.loops) <= 400: + if hasattr(me, "corner_normals"): + info["normals"] = [[r6(c) for c in n.vector] for n in me.corner_normals] + info["cornerVerts"] = [l.vertex_index for l in me.loops] + info["custom"] = bool(me.has_custom_normals) + groups = {g.index: g.name for g in ob.vertex_groups} + if groups: + info["weights"] = [[[groups.get(g.group, "?"), r6(g.weight)] for g in v.groups] for v in me.vertices] + if me.shape_keys: + k = me.shape_keys + info["shapes"] = [{"name": b.name, "value": r6(b.value), "relative": b.relative_key.name, + "co": [r6(p.co[c]) for p in b.data for c in range(3)]} for b in k.key_blocks] + info["reference"] = k.reference_key.name + info["modifiers"] = [m.type for m in ob.modifiers] + return info + + +def socket_val(s): + if s is None: + return None + v = s.default_value + try: + return [r6(x) for x in v] + except TypeError: + return r6(v) + + +def linked_image(s): + if s is None or not s.is_linked: + return None + n = s.links[0].from_node + if n.bl_idname == "ShaderNodeNormalMap": + return linked_image(n.inputs["Color"]) + if n.bl_idname == "ShaderNodeTexImage" and n.image: + return n.image.name + return "?" + n.bl_idname + + +def material_info(m): + info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness), + "use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling)} + if m.node_tree: + for n in m.node_tree.nodes: + if n.bl_idname == "ShaderNodeBsdfPrincipled": + ins = n.inputs + g = lambda *names: next((ins[x] for x in names if x in ins), None) + info["principled"] = { + "base": socket_val(g("Base Color")), "metallic": socket_val(g("Metallic")), "roughness": socket_val(g("Roughness")), + "emission": socket_val(g("Emission Color", "Emission")), "strength": socket_val(g("Emission Strength")), + "alpha": socket_val(g("Alpha")), + "baseTex": linked_image(g("Base Color")), "normalTex": linked_image(g("Normal")), + "emissionTex": linked_image(g("Emission Color", "Emission")), + } + if n.bl_idname == "ShaderNodeNormalMap": + info["normalStrength"] = r6(n.inputs["Strength"].default_value) + return info + + +def fcurves(act): + if act is None: + return [] + if hasattr(act, "fcurves") and V < (5, 0): + return list(act.fcurves) + out = [] + for layer in act.layers: + for strip in layer.strips: + for bag in strip.channelbags: + out.extend(bag.fcurves) + return out + + +FRAMES = [1 + 0.5 * i for i in range(43)] # 1 .. 22 (past the last key: extrapolation) + + +def curve_info(act): + out = [] + for fc in fcurves(act): + out.append({"path": fc.data_path, "index": fc.array_index, "extrapolation": fc.extrapolation, + "keys": len(fc.keyframe_points), "values": [r6(fc.evaluate(f)) for f in FRAMES]}) + return out + + +def dump(path): + bpy.ops.wm.open_mainfile(filepath=path) + sc = bpy.context.scene + sc.frame_set(sc.frame_current) + obs = list(sc.objects) + ref = {"version": list(bpy.data.version), "fps": sc.render.fps / sc.render.fps_base, "frameStart": sc.frame_start, + "frameCurrent": sc.frame_current, "resolution": [sc.render.resolution_x, sc.render.resolution_y], + "objects": [], "materials": [], "images": [], "cameras": {}, "lights": {}, "armatures": {}, "actions": {}} + for ob in obs: + o = {"name": ob.name, "type": ob.type, "parent": ob.parent.name if ob.parent else "", "parent_type": ob.parent_type, + "parent_bone": ob.parent_bone, "world": [r6(x) for x in mat(ob.matrix_world)], + "collections": [c.name for c in ob.users_collection]} + if ob.type == "MESH": + o["mesh"] = mesh_info(ob) + if ob.animation_data and ob.animation_data.action: + a = ob.animation_data.action + ref["actions"][a.name] = curve_info(a) + o["action"] = a.name + if ob.type == "MESH" and ob.data.shape_keys and ob.data.shape_keys.animation_data and ob.data.shape_keys.animation_data.action: + a = ob.data.shape_keys.animation_data.action + ref["actions"][a.name] = curve_info(a) + o["shapeAction"] = a.name + ref["objects"].append(o) + if ob.type == "CAMERA": + c = ob.data + ref["cameras"][ob.name] = {"type": c.type, "lens": r6(c.lens), "sensor": [r6(c.sensor_width), r6(c.sensor_height)], + "fit": c.sensor_fit, "ortho": r6(c.ortho_scale), "clip": [r6(c.clip_start), r6(c.clip_end)], + "angle": [r6(c.angle_x), r6(c.angle_y)]} + if ob.type == "LIGHT": + l = ob.data + ref["lights"][ob.name] = {"type": l.type, "color": [r6(x) for x in l.color], "energy": r6(l.energy), + "spot": [r6(l.spot_size), r6(l.spot_blend)] if l.type == "SPOT" else [0, 0]} + if ob.type == "ARMATURE": + ref["armatures"][ob.name] = [{"name": b.name, "parent": b.parent.name if b.parent else "", "deform": b.use_deform, + "local": [r6(x) for x in mat(b.matrix_local)], "length": r6(b.length)} for b in ob.data.bones] + for m in bpy.data.materials: + ref["materials"].append(material_info(m)) + for im in bpy.data.images: + if im.source in ("FILE", "GENERATED") and im.type == "IMAGE": + ref["images"].append({"name": im.name, "filepath": im.filepath, "packed": im.packed_file.size if im.packed_file else 0, + "source": im.source}) + # posed world matrices: objects, pose bones (world), shape key values + poses = [] + if ref["actions"]: + for f in FRAMES: + sc.frame_set(int(math.floor(f)), subframe=f - math.floor(f)) + p = {"frame": f, "objects": {}, "bones": {}, "shapes": {}} + for ob in obs: + p["objects"][ob.name] = [r6(x) for x in mat(ob.matrix_world)] + if ob.type == "ARMATURE": + for pb in ob.pose.bones: + p["bones"][ob.name + "/" + pb.name] = [r6(x) for x in mat(ob.matrix_world @ pb.matrix)] + if ob.type == "MESH" and ob.data.shape_keys: + p["shapes"][ob.name] = [r6(b.value) for b in ob.data.shape_keys.key_blocks] + if ob.type == "MESH" and any(m.type == "ARMATURE" for m in ob.modifiers) and f == math.floor(f): + ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get()) + em = ev.to_mesh() + w = ob.matrix_world + p.setdefault("skinned", {})[ob.name] = [r6(c) for v in em.vertices for c in (w @ v.co)] + ev.to_mesh_clear() + poses.append(p) + ref["poses"] = poses + # Blender's glTF exporter on the same file (Z up, modifiers not applied) + glb = os.path.join(outdir, os.path.basename(path) + ".glb") + try: + bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_yup=False, export_apply=False, + export_cameras=True, export_lights=True) + with open(glb, "rb") as fh: + data = fh.read() + n = struct.unpack_from(".luau { { name, data, ref } } (: 279, 293, 35, 41, cur, old) +# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes }) +import json, os, shutil, subprocess, tempfile + +INPUTS = ["tools/fixtures/_blend_make.py", "tools/fixtures/_blend_ref.py"] + +OLD = [ + ("279", ["--impure", "--expr", '(import (builtins.fetchTarball "https://github.com/NixOS/nixpkgs/archive/nixos-19.03.tar.gz") {}).blender']), + ("293", ["github:NixOS/nixpkgs/nixos-21.11#blender"]), + ("35", ["github:NixOS/nixpkgs/nixos-23.05#blender"]), + ("41", ["github:NixOS/nixpkgs/nixos-24.05#blender"]), +] + + +OLD_DEMOS = "https://download.blender.org/demo/old_demos/" +OLD_FILES = ["escher.blend", "hairball.blend", "nmesh.blend", "relative.blend", "demo2.04.blend.gz"] + + +def old_samples(ctx, tmp): + import gzip, urllib.request + out = os.path.join(tmp, "olddemos") + os.makedirs(out) + files = [] + for f in OLD_FILES: + try: + with urllib.request.urlopen(OLD_DEMOS + f, timeout=60) as r: + data = r.read() + except OSError as e: + print("blend: could not fetch %s: %s" % (f, e)) + continue + if f.endswith(".gz"): + data = gzip.decompress(data) + f = f[:-3].replace("2.04", "204") + with open(os.path.join(out, f), "wb") as fh: + fh.write(data) + files.append(os.path.join(out, f)) + if not files: + return [] + refdir = os.path.join(tmp, "oldref") + os.makedirs(refdir) + ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py") + ok, log = run(["nix", "shell"] + OLD[3][1] + ["-c", "blender", "-b", "--factory-startup", "--python", ref, "--", json.dumps(files), refdir]) + cases = [] + for p in files: + rp = os.path.join(refdir, os.path.basename(p) + ".json") + if not os.path.exists(rp): + continue + r = json.load(open(rp)) + if r.get("error"): + continue + g = r.get("gltf") + if g: + for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"): + g.pop(k, None) + cases.append({"name": "old/" + os.path.basename(p), "data": open(p, "rb").read(), "ref": clean(r)}) + if not cases: + print("blend: Blender 4.1 gave no reference for the old demos: " + log[-400:]) + return cases + + +def env(): + e = dict(os.environ) + e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have + return e + + +def current(): + exe = shutil.which("blender") + return [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"] + + +def run(cmd, timeout=1800): + try: + res = subprocess.run(cmd, capture_output=True, timeout=timeout, env=env()) + return res.returncode == 0, res.stdout.decode("utf-8", "replace") + res.stderr.decode("utf-8", "replace") + except (subprocess.TimeoutExpired, OSError) as e: + return False, str(e) + + +def clean(v): + if isinstance(v, dict): + return {k: clean(x) for k, x in v.items() if x is not None} + if isinstance(v, list): + return [False if x is None else clean(x) for x in v] + return v + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="blendfx") + make = os.path.join(ctx.root, "tools", "fixtures", "_blend_make.py") + ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py") + made = {} + for tag, inst in OLD + [("cur", None)]: + out = os.path.join(tmp, tag) + os.makedirs(out) + if inst is None: + cmd = current() + else: + cmd = ["nix", "shell"] + inst + ["-c", "blender"] + ok, log = run(cmd + ["-b", "--factory-startup", "--python", make, "--", out]) + files = sorted(f for f in os.listdir(out) if f.endswith(".blend")) + if not ok or not files: + print("blend: Blender %s did not run (skipped): %s" % (tag, log[-400:])) + continue + made[tag] = (out, files) + paths = [os.path.join(out, f) for out, files in made.values() for f in files] + refdir = os.path.join(tmp, "ref") + os.makedirs(refdir) + ok, log = run(current() + ["-b", "--factory-startup", "--python", ref, "--", json.dumps(paths), refdir], timeout=3600) + if not ok: + raise RuntimeError("blend: the reference Blender failed: " + log[-2000:]) + sibling = None + for tag, (out, files) in made.items(): + cases = [] + for f in files: + p = os.path.join(out, f) + r = json.load(open(os.path.join(refdir, f + ".json"))) + g = r.get("gltf") + if g: + for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"): + g.pop(k, None) + cases.append({"name": f, "data": open(p, "rb").read(), "ref": clean(r)}) + name = "cur" if tag == "cur" else tag + ctx.emit("blend_" + name, cases) + if sibling is None and os.path.exists(os.path.join(out, "outside.png")): + sibling = open(os.path.join(out, "outside.png"), "rb").read() + for tag, _ in OLD + [("cur", None)]: + if tag not in made: + ctx.emit("blend_" + tag, []) + ctx.emit("blend_old", old_samples(ctx, tmp)) + ctx.emit("blend_files", {"outside.png": sibling or b""}) + ctx.emit("blend_versions", sorted(made.keys())) + shutil.rmtree(tmp, ignore_errors=True) diff --git a/tools/fixtures/docs_blend.py b/tools/fixtures/docs_blend.py new file mode 100644 index 0000000..e8f59f1 --- /dev/null +++ b/tools/fixtures/docs_blend.py @@ -0,0 +1,73 @@ +# Docs inputs for the .blend section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains the +# inputs): a small rig saved zstd-compressed by the nixpkgs Blender (a two-bone armature, a skinned cylinder with a +# shape key, a bone action and a Principled material). +# tests/gen/docs_blend.luau { files = { ["rig.blend"] = bytes }, vars = { riggedBlendBytes = "rig.blend" } } +import importlib.util, os, shutil, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + +SCRIPT = r''' +import bpy, sys, math +out = sys.argv[sys.argv.index("--") + 1] +bpy.ops.wm.read_factory_settings(use_empty=True) +arm = bpy.data.armatures.new("RigData") +rig = bpy.data.objects.new("Rig", arm) +bpy.context.scene.collection.objects.link(rig) +bpy.context.view_layer.objects.active = rig +bpy.ops.object.mode_set(mode="EDIT") +a = arm.edit_bones.new("lower") +a.head, a.tail = (0, 0, 0), (0, 0, 1) +b = arm.edit_bones.new("upper") +b.head, b.tail, b.parent, b.use_connect = (0, 0, 1), (0, 0, 2), a, True +bpy.ops.object.mode_set(mode="OBJECT") +ring = [(math.cos(k * math.pi / 3) * 0.3, math.sin(k * math.pi / 3) * 0.3) for k in range(6)] +verts = [(x, y, z) for z in (0, 1, 2) for x, y in ring] +faces = [(r * 6 + k, r * 6 + (k + 1) % 6, (r + 1) * 6 + (k + 1) % 6, (r + 1) * 6 + k) for r in range(2) for k in range(6)] +me = bpy.data.meshes.new("Tube") +me.from_pydata(verts, [], faces) +mat = bpy.data.materials.new("Skin") +mat.use_nodes = True +bsdf = mat.node_tree.nodes["Principled BSDF"] +bsdf.inputs["Base Color"].default_value = (0.9, 0.6, 0.5, 1) +bsdf.inputs["Roughness"].default_value = 0.7 +me.materials.append(mat) +tube = bpy.data.objects.new("Tube", me) +bpy.context.scene.collection.objects.link(tube) +tube.parent = rig +tube.modifiers.new("Armature", "ARMATURE").object = rig +lo, up = tube.vertex_groups.new(name="lower"), tube.vertex_groups.new(name="upper") +for i in range(18): + lo.add([i], 1.0 - (i // 6) * 0.5, "REPLACE") + up.add([i], (i // 6) * 0.5, "REPLACE") +tube.shape_key_add(name="Basis") +bulge = tube.shape_key_add(name="Bulge") +for p in bulge.data: + p.co = (p.co[0] * 1.4, p.co[1] * 1.4, p.co[2]) +pb = rig.pose.bones["upper"] +for f, angle in ((1, 0.0), (12, 0.8), (24, 0.0)): + pb.rotation_quaternion = (math.cos(angle / 2), math.sin(angle / 2), 0, 0) + pb.keyframe_insert("rotation_quaternion", frame=f) +bpy.context.scene.frame_set(1) +bpy.ops.wm.save_as_mainfile(filepath=out, compress=True) +''' + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + check = importlib.util.module_from_spec(spec) + spec.loader.exec_module(check) + tmp = tempfile.mkdtemp(prefix="formats-docs-blend-") + try: + script = os.path.join(tmp, "make.py") + with open(script, "w") as f: + f.write(SCRIPT) + out = os.path.join(tmp, "rig.blend") + exe = shutil.which("blender") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"] + env = dict(os.environ) + env.pop("LD_LIBRARY_PATH", None) + subprocess.run(cmd + ["-b", "--factory-startup", "--python", script, "--", out], capture_output=True, check=True, timeout=900, env=env) + files = {"rig.blend": open(out, "rb").read()} + finally: + shutil.rmtree(tmp, ignore_errors=True) + check.emit_inputs(ctx, files, {"riggedBlendBytes": "rig.blend"})