model/blend: material inputs traced through reroutes, mix, colour adjustments, colour ramps and node groups; unresolved links flagged with neutral values; roughness / metallic image textures with their channel; vertex colours; bump; UDIM images with the <UDIM> token and their tiles

This commit is contained in:
4DBug committed 2026-11-03 02:22:45 -06:00
1 parent 8fd5a4c3f2
commit 3a56a66ac1
13 files changed
+1781 -531

No files matched your search

+164
View File
@@ -16,6 +16,10 @@
# track constraints; bone inheritance and b-bone settings; a saved pose basis; drivers
# (every variable type, keys, modifiers) on the rig, its data and the shape keys; custom
# properties on pose bones, bones and objects
# mat_<ver>.blend material graphs: images through Mix / MixRGB, Hue-Saturation, Bright-Contrast, Gamma,
# Invert, RGB Curves, Color Ramp, reroutes and node groups; roughness images linked directly
# or through a ramp; vertex colours; bump; unresolved links; a UDIM image with two tiles
# (2.82+, the tiles as udim.1001.png / udim.1002.png next to the file)
import bpy, sys, os, math
out = sys.argv[sys.argv.index("--") + 1]
@@ -824,9 +828,169 @@ def ctl_file():
save(os.path.join(out, "ctl_%s.blend" % TAG))
def mat_file():
reset()
old_mix = V < (3, 4)
diffuse = image("diffuse", 4, 4, lambda x, y: [x / 3, y / 3, 0.5, 1.0])
rough = image("rough", 4, 4, lambda x, y: [0.25 + x / 8] * 3 + [1.0])
bump = image("height", 4, 4, lambda x, y: [(x + y) / 6] * 3 + [1.0])
nrm = image("nrm", 4, 4, lambda x, y: [0.5, 0.5, 1.0, 1.0])
udim = None
if V >= (2, 82):
paths = []
for tile, col in ((1001, (1.0, 0.0, 0.0)), (1002, (0.0, 0.0, 1.0))):
p = os.path.join(out, "udim.%d.png" % tile)
t = bpy.data.images.new("udim_%d" % tile, 2, 2)
t.pixels = list(col + (1.0,)) * 4
t.filepath_raw = p
t.file_format = "PNG"
t.save()
bpy.data.images.remove(t)
paths.append(p)
udim = bpy.data.images.load(paths[0])
udim.name = "udim"
udim.source = "TILED"
if len(udim.tiles) < 2:
udim.tiles.new(1002)
udim.tiles[0].label = "front"
udim.filepath = "//" + os.path.basename(udim.filepath.replace("1001", "<UDIM>" if V >= (3, 0) else "1001"))
def material(name):
m = bpy.data.materials.new(name)
bsdf = principled(m, (0.8, 0.8, 0.8, 1.0), 0.0, 0.5)
return m, m.node_tree, bsdf
def tex(nt, img):
t = nt.nodes.new("ShaderNodeTexImage")
t.image = img
return t
def mix(nt, a, b, fac):
if old_mix:
n = nt.nodes.new("ShaderNodeMixRGB")
ia, ib, f, o = n.inputs["Color1"], n.inputs["Color2"], n.inputs["Fac"], n.outputs["Color"]
else:
n = nt.nodes.new("ShaderNodeMix")
n.data_type = "RGBA"
ia, ib, f, o = n.inputs[6], n.inputs[7], n.inputs[0], n.outputs[2]
if a:
nt.links.new(a, ia)
if b:
nt.links.new(b, ib)
if fac:
nt.links.new(fac, f)
return o
def vcol(nt):
if V >= (2, 81):
n = nt.nodes.new("ShaderNodeVertexColor")
n.layer_name = "Col"
else:
n = nt.nodes.new("ShaderNodeAttribute")
n.attribute_name = "Col"
return n.outputs["Color"]
def ramp(nt, src):
n = nt.nodes.new("ShaderNodeValToRGB")
nt.links.new(src, n.inputs["Fac"])
return n.outputs["Color"]
def reroute(nt, src):
n = nt.nodes.new("NodeReroute")
nt.links.new(src, n.inputs[0])
return n.outputs[0]
mats = []
# body: Mix(A = image, B = HueSat(image), Fac = ramp(vertex colour)); roughness image linked directly
m, nt, b = material("MatBody")
img = udim or diffuse
hs = nt.nodes.new("ShaderNodeHueSaturation")
nt.links.new(tex(nt, img).outputs["Color"], hs.inputs["Color"])
nt.links.new(mix(nt, tex(nt, img).outputs["Color"], hs.outputs["Color"], ramp(nt, vcol(nt))), b.inputs["Base Color"])
nt.links.new(tex(nt, rough).outputs["Color"], b.inputs["Roughness"])
mats.append(m)
# hands: Mix(A = image, Fac = ramp(vertex colour)), B unlinked
m, nt, b = material("MatHands")
nt.links.new(mix(nt, tex(nt, diffuse).outputs["Color"], None, ramp(nt, vcol(nt))), b.inputs["Base Color"])
nt.links.new(tex(nt, rough).outputs["Color"], b.inputs["Roughness"])
mats.append(m)
# hair: reroutes; roughness through a reroute and a ramp
m, nt, b = material("MatHair")
nt.links.new(reroute(nt, reroute(nt, tex(nt, diffuse).outputs["Color"])), b.inputs["Base Color"])
nt.links.new(reroute(nt, ramp(nt, tex(nt, rough).outputs["Color"])), b.inputs["Roughness"])
mats.append(m)
# eyebrows: vertex colour
m, nt, b = material("MatVcol")
nt.links.new(vcol(nt), b.inputs["Base Color"])
mats.append(m)
# jeans: image, normal map, roughness image linked directly, metallic through Separate RGB (packed)
m, nt, b = material("MatJeans")
nt.links.new(tex(nt, diffuse).outputs["Color"], b.inputs["Base Color"])
nm = nt.nodes.new("ShaderNodeNormalMap")
nt.links.new(tex(nt, nrm).outputs["Color"], nm.inputs["Color"])
nt.links.new(nm.outputs["Normal"], b.inputs["Normal"])
nt.links.new(tex(nt, rough).outputs["Color"], b.inputs["Roughness"])
mats.append(m)
# a chain of colour adjustments
m, nt, b = material("MatChain")
src = tex(nt, diffuse).outputs["Color"]
for idname in ("ShaderNodeRGBCurve", "ShaderNodeInvert", "ShaderNodeGamma", "ShaderNodeBrightContrast"):
n = nt.nodes.new(idname)
nt.links.new(src, n.inputs["Color"])
src = n.outputs["Color"]
nt.links.new(src, b.inputs["Base Color"])
mats.append(m)
# a node group: an image inside it, and a pass-through of an outside image
grp = bpy.data.node_groups.new("TexGroup", "ShaderNodeTree")
gi, go = grp.nodes.new("NodeGroupInput"), grp.nodes.new("NodeGroupOutput")
if hasattr(grp, "interface"):
grp.interface.new_socket("Tint", in_out="INPUT", socket_type="NodeSocketColor")
grp.interface.new_socket("Color", in_out="OUTPUT", socket_type="NodeSocketColor")
grp.interface.new_socket("Through", in_out="OUTPUT", socket_type="NodeSocketColor")
else:
grp.inputs.new("NodeSocketColor", "Tint")
grp.outputs.new("NodeSocketColor", "Color")
grp.outputs.new("NodeSocketColor", "Through")
inner = grp.nodes.new("ShaderNodeTexImage")
inner.image = rough
grp.links.new(inner.outputs["Color"], go.inputs[0])
grp.links.new(gi.outputs[0], go.inputs[1])
m, nt, b = material("MatGroup")
gn = nt.nodes.new("ShaderNodeGroup")
gn.node_tree = grp
nt.links.new(tex(nt, diffuse).outputs["Color"], gn.inputs[0])
nt.links.new(gn.outputs[1], b.inputs["Base Color"])
nt.links.new(gn.outputs[0], b.inputs["Roughness"])
mats.append(m)
# bump, and unresolved links (a noise texture, a math node)
m, nt, b = material("MatBump")
bp = nt.nodes.new("ShaderNodeBump")
bp.inputs["Strength"].default_value = 0.5
bp.inputs["Distance"].default_value = 0.2
nt.links.new(tex(nt, bump).outputs["Color"], bp.inputs["Height"])
nt.links.new(bp.outputs["Normal"], b.inputs["Normal"])
nz = nt.nodes.new("ShaderNodeTexNoise")
nt.links.new(nz.outputs["Color"], b.inputs["Base Color"])
b.inputs["Base Color"].default_value = (0.0, 0.0, 0.0, 1.0)
mt = nt.nodes.new("ShaderNodeMath")
nt.links.new(mt.outputs[0], b.inputs["Metallic"])
b.inputs["Metallic"].default_value = 0.9
mats.append(m)
for i, m in enumerate(mats):
me = mesh("Quad" + m.name, [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)])
uv(me, "UVMap", lambda k: ((k % 2) * 1.0, (k // 2) * 1.0))
byte_colors(me, "Col")
me.materials.append(m)
ob = link(bpy.data.objects.new("Quad" + m.name, me))
ob.location = (i * 1.5, 0, 0)
update()
save(os.path.join(out, "mat_%s.blend" % TAG))
scene_file()
rig_file()
ctl_file()
mat_file()
if OLD:
scene_file()
save(os.path.join(out, "compat_%s.blend" % TAG), compat=True)
+107 -1
View File
@@ -93,9 +93,115 @@ def linked_image(s):
return "?" + n.bl_idname
PASS = {"NodeReroute": ["Input"], "ShaderNodeMix": ["A_Color", "B_Color"], "ShaderNodeMixRGB": ["Color1", "Color2"],
"ShaderNodeHueSaturation": ["Color"], "ShaderNodeBrightContrast": ["Color"], "ShaderNodeGamma": ["Color"],
"ShaderNodeInvert": ["Color"], "ShaderNodeRGBCurve": ["Color"], "ShaderNodeValToRGB": ["Fac"]}
def by_identifier(sockets, ident):
for s in sockets:
if s.identifier == ident:
return s
return None
def trace(sock, via, stack, depth=0):
"""bpy's view of the reader's rules: (end node, from-socket name, group stack) of the first image, else the last node"""
if depth > 64 or not sock.is_linked:
return None, None
link = sock.links[0]
n, out = link.from_node, link.from_socket
if n.bl_idname == "ShaderNodeTexImage":
return n, out.name
if n.bl_idname == "ShaderNodeGroup" and n.node_tree:
outs = [x for x in n.node_tree.nodes if x.bl_idname == "NodeGroupOutput"]
if outs:
inner = by_identifier(outs[0].inputs, out.identifier)
if inner is not None:
via.append(n.bl_idname)
r, nm = trace(inner, via, stack + [n], depth + 1)
if r is not None and r.bl_idname == "ShaderNodeTexImage":
return r, nm
via.pop()
return n, out.name
if n.bl_idname == "NodeGroupInput" and stack:
g = stack[-1]
outer = by_identifier(g.inputs, out.identifier)
if outer is not None:
return trace(outer, via, stack[:-1], depth + 1)
return n, out.name
if n.bl_idname in PASS:
last = n
for ident in PASS[n.bl_idname]:
s = by_identifier(n.inputs, ident) or (n.inputs.get(ident) if hasattr(n.inputs, "get") else None)
if s is None and n.bl_idname == "NodeReroute":
s = n.inputs[0]
if s is None:
continue
sub = []
r, nm = trace(s, sub, stack, depth + 1)
if r is not None and r.bl_idname == "ShaderNodeTexImage":
via.append(n.bl_idname)
via.extend(sub)
return r, nm
if n.bl_idname == "NodeReroute":
return (r, nm) if r is not None else (n, out.name)
return last, out.name
return n, out.name
def image_info(img):
info = {"name": img.name, "source": img.source, "filepath": img.filepath}
if img.source == "TILED":
info["tiles"] = [{"number": t.number, "label": t.label} for t in img.tiles]
return info
def graph_info(m):
out = {}
if not m.node_tree:
return out
bsdf = None # the reader's choice: the Principled BSDF linked to an output's Surface, else the first
for n in m.node_tree.nodes:
if n.bl_idname == "ShaderNodeOutputMaterial" and n.inputs["Surface"].is_linked:
f = n.inputs["Surface"].links[0].from_node
if f.bl_idname == "ShaderNodeBsdfPrincipled":
bsdf = f
if bsdf is None:
bsdf = next((n for n in m.node_tree.nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"), None)
if bsdf is None:
return out
for name in ("Base Color", "Metallic", "Roughness", "Normal", "Alpha", "Emission Color", "Emission"):
s = bsdf.inputs.get(name)
if s is None or not s.is_linked:
continue
sock = s
e = {"linked": s.links[0].from_node.bl_idname}
if name == "Normal" and e["linked"] in ("ShaderNodeNormalMap", "ShaderNodeBump"):
nn = s.links[0].from_node
sock = nn.inputs["Color"] if e["linked"] == "ShaderNodeNormalMap" else nn.inputs["Height"]
if e["linked"] == "ShaderNodeBump":
e["strength"] = r6(nn.inputs["Strength"].default_value)
e["distance"] = r6(nn.inputs["Distance"].default_value)
via = []
n, outname = trace(sock, via, [])
if n is not None and n.bl_idname == "ShaderNodeTexImage" and n.image:
e["image"] = image_info(n.image)
e["via"] = via
e["output"] = outname
elif n is not None:
e["end"] = n.bl_idname
if n.bl_idname == "ShaderNodeVertexColor":
e["vertexColor"] = n.layer_name
elif n.bl_idname == "ShaderNodeAttribute":
e["vertexColor"] = n.attribute_name
out[name] = e
return out
def material_info(m):
info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness),
"use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling)}
"use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling), "graph": graph_info(m)}
if m.node_tree:
for n in m.node_tree.nodes:
if n.bl_idname == "ShaderNodeBsdfPrincipled":
+8 -2
View File
@@ -7,7 +7,7 @@
# old demos (fetched, never committed; 32-bit pointers, big-endian SGI / PowerPC files among them), with references
# from Blender 4.1 (5.0 dropped big-endian files).
# tests/gen/blend_<ver>.luau { { name, data, ref } } (<ver>: 279, 293, 35, 41, cur, old)
# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes })
# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes, UDIM tiles })
import json, os, shutil, subprocess, tempfile
INPUTS = ["tools/fixtures/_blend_make.py", "tools/fixtures/_blend_ref.py"]
@@ -118,6 +118,7 @@ def generate(ctx):
if not ok:
raise RuntimeError("blend: the reference Blender failed: " + log[-2000:])
sibling = None
tiles = {}
for tag, (out, files) in made.items():
cases = []
for f in files:
@@ -132,10 +133,15 @@ def generate(ctx):
ctx.emit("blend_" + name, cases)
if sibling is None and os.path.exists(os.path.join(out, "outside.png")):
sibling = open(os.path.join(out, "outside.png"), "rb").read()
for tile in ("udim.1001.png", "udim.1002.png"):
if tile not in tiles and os.path.exists(os.path.join(out, tile)):
tiles[tile] = open(os.path.join(out, tile), "rb").read()
for tag, _ in OLD + [("cur", None)]:
if tag not in made:
ctx.emit("blend_" + tag, [])
ctx.emit("blend_old", old_samples(ctx, tmp))
ctx.emit("blend_files", {"outside.png": sibling or b""})
files = {"outside.png": sibling or b""}
files.update(tiles)
ctx.emit("blend_files", files)
ctx.emit("blend_versions", sorted(made.keys()))
shutil.rmtree(tmp, ignore_errors=True)