Files
rosetta/src/Rosetta/model/blend/Material.luau
T

351 lines
11 KiB
Luau

--!strict
-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the
-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength
-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base
-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to
-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a
-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external
-- ones as uris (with the bytes when opts.files / opts.resolve has them).
local Blend = require("@rosetta/containers/Blend")
local Types = require("@rosetta/Types")
local Material = {}
type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any }
local readu8, readstring = buffer.readu8, buffer.readstring
local function sniffMime(b: buffer, o: number, n: number, path: string?): string?
if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then
return "image/png"
elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then
return "image/jpeg"
elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then
return "image/webp"
elseif n >= 2 and readstring(b, o, 2) == "BM" then
return "image/bmp"
elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then
return "image/x-exr"
end
local ext = path and string.lower(string.match(path, "%.(%w+)$") or "")
local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" }
return if ext then byExt[ext] else nil
end
local function fetch(ctx: Ctx, uri: string): buffer?
local opts = ctx.opts
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
if v == nil then
v = opts.files[string.match(uri, "[^/\\]+$") or uri]
end
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, uri)
v = if ok then res else nil
end
if type(v) == "string" then
return buffer.fromstring(v)
end
return if type(v) == "buffer" then v else nil
end
local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number?
local f = ctx.f
local key = img.block and img.block.addr
if key ~= nil and ctx.textures[key] then
return ctx.textures[key]
end
local name = img:idName()
-- the path field keeps its DNA name "name" (char[1024]) in every version
local pf0 = img.struct.byName.filepath or img.struct.byName.name
local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil
local pf = img:deref("packedfile", 0, "PackedFile")
if not pf then
for _, ipf in img:list("packedfiles", "ImagePackedFile") do
pf = ipf:deref("packedfile", 0, "PackedFile")
if pf then
break
end
end
end
local tex: Types.Texture = { name = name, sampler = sampler }
if pf then
local blk = pf:target("data")
local size = pf:num("size") or 0
if blk then
local n = math.min(size, blk.size)
local data = buffer.create(n)
buffer.copy(data, 0, f.buf, blk.offset, n)
tex.data = data
tex.mime = sniffMime(data, 0, n, path)
end
end
if path and path ~= "" then
local uri = string.gsub(path, "^//", "")
uri = string.gsub(uri, "\\", "/")
if not tex.data then
tex.uri = uri
local data = fetch(ctx, uri)
if data then
tex.data = data
tex.mime = sniffMime(data, 0, buffer.len(data), uri)
else
tex.mime = sniffMime(buffer.create(0), 0, 0, uri)
end
end
tex.extras = { blend = { filepath = path } }
end
if not tex.data and not tex.uri then
tex.extras = { blend = { generated = true } }
end
table.insert(ctx.scene.textures, tex)
local idx = #ctx.scene.textures
if key ~= nil then
ctx.textures[key] = idx
end
return idx
end
type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } }
type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr
local function graph(tree: Blend.View): Graph
local g: Graph = { nodes = {}, links = {} }
for _, n in tree:list("nodes", "bNode") do
local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} }
for _, s in n:list("inputs", "bNodeSocket") do
local id = s:str("identifier") or s:str("name") or ""
local nm = s:str("name") or id
node.inputs[nm] = s
if node.inputs[id] == nil then
node.inputs[id] = s
end
end
for _, s in n:list("outputs", "bNodeSocket") do
if s.block then
node.outputs[s.block.addr] = s:str("name") or ""
end
end
if n.block then
g.nodes[n.block.addr] = node
end
end
for _, l in tree:list("links", "bNodeLink") do
local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock")
local fn = from and g.nodes[from]
if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then
g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" }
end
end
return g
end
local function input(n: Node, ...: string): Blend.View?
for _, k in { ... } do
local s = n.inputs[k]
if s then
return s
end
end
return nil
end
local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }?
if not s or not s.block then
return nil
end
return g.links[s.block.addr]
end
local function value(s: Blend.View?, kind: string): any
if not s then
return nil
end
if kind == "rgba" then
local v = s:deref("default_value", 0, "bNodeSocketValueRGBA")
return v and v:vec("value")
end
local v = s:deref("default_value", 0, "bNodeSocketValueFloat")
return v and v:num("value")
end
local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?)
local l = link(g, s)
if not l then
return nil, nil
end
local n = l.node
if through and n.idname == through then
local inner = input(n, "Color", "Image")
local ref, tn = imageRef(ctx, g, uvNames, inner, nil)
return ref, if ref then n else tn
end
if n.idname ~= "ShaderNodeTexImage" then
return nil, n
end
local img = n.view:deref("id", 0, "Image")
if not img then
return nil, n
end
local sampler: Types.Sampler = {}
local custom = false
local st = n.view:deref("storage", 0, "NodeTexImage")
if st then
local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0
custom = interp == 1 or (ext >= 1 and ext <= 3)
if interp == 1 then
sampler.filter = "nearest"
sampler.minFilter = "nearest"
end
if ext == 1 or ext == 2 then
sampler.wrapS, sampler.wrapT = "clamp", "clamp"
elseif ext == 3 then
sampler.wrapS, sampler.wrapT = "mirror", "mirror"
end
end
local t = texture(ctx, img, if custom then sampler else nil)
if not t then
return nil, n
end
local ref: Types.TextureRef = { texture = t }
local vec = link(g, input(n, "Vector"))
if vec and vec.node.idname == "ShaderNodeUVMap" then
local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap")
local name = uvs and uvs:str("uv_map")
if name and uvNames and uvNames[name] then
ref.texCoord = uvNames[name]
end
end
return ref, n
end
local function principled(g: Graph): Node?
local first: Node? = nil
for _, n in g.nodes do
if n.idname == "ShaderNodeOutputMaterial" then
local l = link(g, n.inputs.Surface)
if l and l.node.idname == "ShaderNodeBsdfPrincipled" then
return l.node
end
elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then
first = n
end
end
return first
end
local function emissive(m: Types.Material, color: { number }, strength: number)
local e = { color[1] * strength, color[2] * strength, color[3] * strength }
local mx = math.max(e[1], e[2], e[3])
if mx > 1 then
m.extensions = m.extensions or {}
;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx }
e = { e[1] / mx, e[2] / mx, e[3] / mx }
end
m.emissive = e
end
function Material.get(ctx: Ctx, mv: Blend.View): number
local key = mv.block and mv.block.addr
if key ~= nil and ctx.materials[key] then
return ctx.materials[key]
end
local f = ctx.f
local m = Types.Scene.material(mv:idName())
local extras: { [string]: any } = {}
m.extras = { blend = extras }
local legacyAlpha = mv:num("a", "alpha") or 1
m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha }
m.metallic = mv:num("metallic") or 0
m.roughness = mv:num("roughness") or 0.5
if f.version < 280 then
m.roughness = 0.5
end
m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0
local tree = mv:deref("nodetree", 0, "bNodeTree")
local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500
local bsdf = nil
local g: Graph? = nil
if tree and useNodes then
g = graph(tree)
bsdf = principled(g :: Graph)
end
if bsdf and g then
extras.principled = true
local uvNames = ctx.meta.uvNames
local base = value(input(bsdf, "Base Color"), "rgba")
local alpha = value(input(bsdf, "Alpha"), "float") or 1
if base then
m.baseColor = { base[1], base[2], base[3], alpha }
end
m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic
m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness
local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil)
if bref then
m.baseColorTexture = bref
m.baseColor = { 1, 1, 1, alpha }
end
local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil)
if aref and not m.baseColorTexture then
m.baseColorTexture = aref
end
local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap")
if nref then
nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1
m.normalTexture = nref
end
local rl = link(g, input(bsdf, "Roughness"))
local ml = link(g, input(bsdf, "Metallic"))
local sep = (rl and rl.node) or (ml and ml.node)
if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then
local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil)
if mref then
m.metallicRoughnessTexture = mref
if rl then
m.roughness = 1
end
if ml then
m.metallic = 1
end
end
end
local es = input(bsdf, "Emission Color", "Emission")
local ecol = value(es, "rgba") or { 0, 0, 0, 1 }
local strength = value(input(bsdf, "Emission Strength"), "float") or 1
local eref = imageRef(ctx, g, uvNames, es, nil)
if eref then
m.emissiveTexture = eref
ecol = { 1, 1, 1, 1 }
end
emissive(m, ecol, strength)
if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then
m.emissive = { 0, 0, 0 }
end
local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil
if alpha < 1 or alphaLinked then
local bm = mv:num("blend_method") or 0
if bm == 3 then
m.alphaMode = "mask"
m.alphaCutoff = mv:num("alpha_threshold") or 0.5
else
m.alphaMode = "blend"
end
end
else
extras.legacy = true
if legacyAlpha < 1 then
m.alphaMode = "blend"
end
end
table.insert(ctx.scene.materials, m)
local idx = #ctx.scene.materials
if key ~= nil then
ctx.materials[key] = idx
end
return idx
end
return Material