model/blend, containers/Blend: read .blend files (2.4x-5.x headers, SDNA structs by name, gzip/zstd), scenes with meshes of every storage generation, materials, images, cameras, lights, armatures, skins, shape keys, actions
This commit is contained in:
1 parent
01c044805f
commit
2e82b7d0af
15 files changed
+4855
-2
No files matched your search
@@ -734,6 +734,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/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",
|
||||
|
||||
@@ -0,0 +1,741 @@
|
||||
--!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?)
|
||||
-- -> header size, pointer size, little, version, format | nil, error
|
||||
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)
|
||||
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)
|
||||
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), {}
|
||||
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 s: Struct = { name = types[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 += 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 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 = if pointer then ps else lengths[ft + 1]
|
||||
local fld: Field = {
|
||||
name = base, decl = decl, type = types[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, types = types, 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
|
||||
return nil, Err.new(if n < 12 then Err.TRUNCATED else Err.CORRUPT, 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
|
||||
code = string.gsub(code, "%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
|
||||
if glob and fg and fg.byName.subversion then
|
||||
local fld = fg.byName.subversion
|
||||
if fld.offset + 2 <= glob[1].size then
|
||||
f.subversion = f.i16(b, glob[1].offset + fld.offset)
|
||||
end
|
||||
end
|
||||
return f, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ structs
|
||||
export type View = {
|
||||
file: File,
|
||||
struct: Struct,
|
||||
offset: number, -- the struct's first byte in file.buf
|
||||
block: Block?,
|
||||
}
|
||||
|
||||
local View = {}
|
||||
View.__index = View
|
||||
Blend.View = View
|
||||
|
||||
local function view(f: File, s: Struct, offset: number, blk: Block?): View
|
||||
return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) :: any
|
||||
end
|
||||
|
||||
function Blend.structOf(f: File, blk: Block): Struct?
|
||||
return f.dna.structs[blk.sdna + 1]
|
||||
end
|
||||
|
||||
-- element i (0-based) of a block, as its own SDNA struct or as `as` (a struct name)
|
||||
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
|
||||
|
||||
-- a number (scalars), a string (char arrays), an array of numbers (other arrays), a View (embedded structs), the
|
||||
-- pointer key (pointers); nil when no field has any of the names
|
||||
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
|
||||
|
||||
-- the struct a pointer field points at (element i, 0-based), typed by the field's type or `as`
|
||||
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
|
||||
|
||||
-- all elements of a pointer-to-array field: the block's count (or byte size / struct size when that is larger)
|
||||
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)
|
||||
for k = 0, n - 1 do
|
||||
out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- a pointer to an array of pointers (Material **mat, ActionLayer **layer_array, ...): n keys (default: the block size)
|
||||
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
|
||||
|
||||
-- a ListBase field (first / last) walked through each element's `next`, typed as `as` or the first block's struct
|
||||
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
|
||||
|
||||
-- the bytes a pointer field points at: (block offset, block size) in file.buf
|
||||
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
|
||||
|
||||
-- a NUL-terminated string behind a char pointer
|
||||
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
|
||||
|
||||
-- an ID's name without its two-letter code ("OBCube" -> "Cube")
|
||||
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
|
||||
@@ -0,0 +1,290 @@
|
||||
--!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;
|
||||
-- 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
|
||||
|
||||
-- the f-curves an AnimData plays from its action (nil when it has none)
|
||||
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
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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
|
||||
|
||||
-- Penner easing: t in 0..d, from b by c
|
||||
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 if t <= 0 then 0 else 2 ^ (10 * (t - 1))
|
||||
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
|
||||
|
||||
-- "pose.bones[\"name\"].location" -> "name", "location"
|
||||
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
|
||||
@@ -0,0 +1,348 @@
|
||||
--!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 st = n.view:deref("storage", 0, "NodeTexImage")
|
||||
if st then
|
||||
local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0
|
||||
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 next(sampler) 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
|
||||
@@ -0,0 +1,604 @@
|
||||
--!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
|
||||
|
||||
-- a raw pointer field (Mesh.mvert, ...) as a layer when no CustomData layer has it
|
||||
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
|
||||
|
||||
-- reads element i (0-based) of a layer as number component c (0-based) of a generic kind
|
||||
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
|
||||
|
||||
-- a field of an SDNA-struct layer: element i -> value (number) of component c
|
||||
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
|
||||
|
||||
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
|
||||
-- positions
|
||||
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
|
||||
-- material index and smooth flags
|
||||
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
|
||||
-- corner index -> the element index in the source corner layers
|
||||
local remap: buffer? = corner.remap
|
||||
local function src(i: number): number
|
||||
return if remap then buffer.readu32(remap, i * 4) else i
|
||||
end
|
||||
-- UV maps
|
||||
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")
|
||||
if r then
|
||||
local d = buffer.create(nc * 8)
|
||||
for i = 0, nc - 1 do
|
||||
local tc = buffer.readu32(corner.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
|
||||
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
|
||||
-- colour attributes: f32 x 4 linear per element
|
||||
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
|
||||
-- MCol keeps alpha, blue, green, red in its a, r, g, b fields
|
||||
local st = f.dna.byName.MCol
|
||||
local d = buffer.create(nc * 16)
|
||||
local stride = if st then st.size else 4
|
||||
for i = 0, nc - 1 do
|
||||
local tc = buffer.readu32(corner.tess, i * 4)
|
||||
local at = (tc // 4) * 4 * stride + (tc % 4) * stride
|
||||
if at + 4 <= L.bytes then
|
||||
local o = L.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)
|
||||
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, aa / 255)
|
||||
end
|
||||
end
|
||||
table.insert(poly.colors, { name = L.name, domain = "corner", data = d })
|
||||
end
|
||||
end
|
||||
-- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes)
|
||||
-- custom normals
|
||||
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)
|
||||
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 }
|
||||
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, {
|
||||
name = kb:str("name") or ("Key " .. i), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d,
|
||||
mute = bit32.band(kb:num("flag") or 0, 2) ~= 0,
|
||||
})
|
||||
end
|
||||
if ref == nil and #out > 0 then
|
||||
ref = 1
|
||||
end
|
||||
return out, ref, key
|
||||
end
|
||||
|
||||
return Mesh
|
||||
@@ -0,0 +1,161 @@
|
||||
--!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
|
||||
-- walk back to the fan's first corner (crossing each corner's previous edge), then forward
|
||||
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)
|
||||
-- the fan's edges in order: the first corner's previous edge, then every corner's next edge
|
||||
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
|
||||
@@ -0,0 +1,452 @@
|
||||
--!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)
|
||||
if l > 1e-20 then
|
||||
x, y, z = x / l, y / l, z / l
|
||||
else
|
||||
local fi = readu32(fans.face, c * 4)
|
||||
x, y, z = readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8)
|
||||
end
|
||||
writef32(out, c * 12, x)
|
||||
writef32(out, c * 12 + 4, y)
|
||||
writef32(out, c * 12 + 8, z)
|
||||
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)
|
||||
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, pointColors = {}, {}
|
||||
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)
|
||||
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 = {}
|
||||
for k, s in 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 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
|
||||
@@ -0,0 +1,862 @@
|
||||
--!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
|
||||
|
||||
-- an object's or pose bone's transform properties, keyed by their RNA names
|
||||
local function objectProps(ob: Blend.View): Props
|
||||
local function v(n: number, ...: string): { number }
|
||||
local x = ob: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, "rot"),
|
||||
rotation_quaternion = v(4, "quat"),
|
||||
rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) },
|
||||
scale = v(3, "scale", "size"),
|
||||
delta_location = v(3, "dloc"),
|
||||
delta_rotation_euler = v(3, "drot"),
|
||||
delta_rotation_quaternion = v(4, "dquat"),
|
||||
delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v(3, "drotAxis")) },
|
||||
delta_scale = v(3, "dscale", "dsize"),
|
||||
rotmode = { ob:num("rotmode") or 1 },
|
||||
}
|
||||
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
|
||||
local half = (cam:num("ortho_scale") or 6) / 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: 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 then
|
||||
-- before 2.8 Cycles took the strength from the lamp's Emission node, else 100 (sun: 1); Blender's 2.8
|
||||
-- versioning moves that to energy
|
||||
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 }
|
||||
elseif t == LA_SPOT then
|
||||
local outer = (la:num("spotsize") or math.rad(45)) / 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 = 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 } = {}
|
||||
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"))
|
||||
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 curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData"))
|
||||
-- 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)
|
||||
curves = curves or {}
|
||||
name = name or mname
|
||||
table.insert(curves :: { Curve }, 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, 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 = {} }
|
||||
byAction[j.action] = anim
|
||||
table.insert(ctx.scene.animations, anim)
|
||||
end
|
||||
local lo, hi = Anim.range(j.curves)
|
||||
local fs = frames(lo, hi, step)
|
||||
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 = Anim.evaluate(c, fr)
|
||||
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
|
||||
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
|
||||
-- objects whose parent sits in a collection go under the parent; others under their (first) collection
|
||||
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
|
||||
-- meshes after every object exists (armatures first, for skins)
|
||||
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
|
||||
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
|
||||
@@ -0,0 +1,75 @@
|
||||
--!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 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/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
|
||||
function BlendFormat.sniff(r: Bytes.Reader): number
|
||||
if r:peek(7) == "BLENDER" then
|
||||
return 1
|
||||
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.evaluate = Anim.evaluate
|
||||
BlendFormat.curves = Anim.curves
|
||||
|
||||
return BlendFormat
|
||||
Reference in new issue
Block a user