Sub topic 12
Building the same graph with Python
Every graph you wire by hand in the Shader Editor can also be built from a script. This chapter shows how to create nodes, set their values, connect sockets and clean up. You will rebuild the Noise-to-Colour-Ramp material from earlier chapters and then look at the two other graphs as variations.
Prerequisites
This chapter assumes you have these skills:
- You know the Noise Texture, Voronoi Texture, Mapping and Colour Ramp nodes from the earlier chapters.
- You can open Blender's Text Editor and run a script with the Run Script button (Alt+P).
- You know basic Python: functions, dictionaries, keyword arguments and loops.
The examples target Blender 4.x. Notes on version differences appear where they matter.
Why script a node graph
Scripts give you things the editor does not:
- Repeatability. The same script produces the same material every time. You can rerun it after changing one number.
- Variation. A loop can make twenty rock materials with different Scale values.
- Batch work. You can run Blender without a window and build materials on many files.
- Inspection. A script can print every node and link, which helps when you debug a graph you did not build yourself.
Scripting is not a good way to design a look. Tune the pattern interactively first, then script it once you know the values.
The data model
A material owns a node tree. The tree holds nodes and links, and each node holds input and output sockets.
The objects you use most are these:
| Object | What it is | Typical use |
|---|---|---|
| `bpy.data.materials` | Every material in the file | `.new(name)`, `.get(name)` |
| `mat.node_tree.nodes` | The nodes in the graph | `.new(type_id)`, `.clear()` |
| `mat.node_tree.links` | The connections | `.new(output_socket, input_socket)` |
| `node.inputs` / `node.outputs` | Sockets, accessible by name or index | Set `default_value`, connect links |
| `node.location` | Position in the editor, as `(x, y)` | Keep the graph readable |
Two details trip people up:
- Node type identifiers are strings such as
"ShaderNodeTexNoise"and"ShaderNodeValToRGB". The Colour Ramp node is called ValToRGB because it turns a value into a colour. The Principled BSDF is"ShaderNodeBsdfPrincipled". - Sockets are linked, not nodes.
links.newtakes an output socket and an input socket. Passing nodes raises an error.
Rebuilding the noise graph
The earlier examples hard-code nodes["Principled BSDF"]. That lookup breaks if the node was renamed or if you start from a different default. The version below clears the tree and creates every node itself, so you can run it repeatedly. It also places the nodes in columns so the result is readable.
import bpy
def new_node(tree, idname, x, y, **props):
"""Create a node, place it, and set any plain properties."""
node = tree.nodes.new(idname)
node.location = (x, y)
for key, value in props.items():
setattr(node, key, value)
return node
def build_noise_material(name="NoiseRamp"):
mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)
mat.use_nodes = True
tree = mat.node_tree
tree.nodes.clear()
coord = new_node(tree, "ShaderNodeTexCoord", -900, 0)
mapping = new_node(tree, "ShaderNodeMapping", -700, 0)
noise = new_node(tree, "ShaderNodeTexNoise", -450, 0)
ramp = new_node(tree, "ShaderNodeValToRGB", -150, 0)
bsdf = new_node(tree, "ShaderNodeBsdfPrincipled", 150, 0)
out = new_node(tree, "ShaderNodeOutputMaterial", 450, 0)
noise.inputs["Scale"].default_value = 6.0
noise.inputs["Detail"].default_value = 8.0
noise.inputs["Roughness"].default_value = 0.6
cr = ramp.color_ramp
cr.interpolation = 'LINEAR'
cr.elements[0].position = 0.35
cr.elements[0].color = (0.05, 0.03, 0.02, 1.0)
cr.elements[1].position = 0.65
cr.elements[1].color = (0.6, 0.5, 0.4, 1.0)
links = tree.links
links.new(coord.outputs["Object"], mapping.inputs["Vector"])
links.new(mapping.outputs["Vector"], noise.inputs["Vector"])
links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
links.new(bsdf.outputs["BSDF"], out.inputs["Surface"])
return mat
mat = build_noise_material()
obj = bpy.context.active_object
if obj is not None and obj.type == 'MESH':
obj.data.materials.clear()
obj.data.materials.append(mat)Select a mesh object before running it. If nothing is selected, the script still creates the material, and you can assign it by hand.
What each part does
tree.nodes.clear()removes the default Principled BSDF and Material Output. The script then creates its own, so it never depends on default names.new_nodeforwards keyword arguments tosetattr. That is how you set enum properties, for examplenew_node(tree, "ShaderNodeTexVoronoi", 0, 0, feature='DISTANCE_TO_EDGE').- The Colour Ramp starts with two stops, at positions 0 and 1. Edit
elements[0]andelements[1]in place. Add stops withcr.elements.new(position). - Stops stay sorted by position. Move the first stop before you move the second so they never cross while you edit them.
Sockets: names, indices and duplicates
Looking up a socket by name is readable, and it keeps working if Blender reorders sockets in a later version. It fails when two sockets share a name.
The Mix node (ShaderNodeMix) is the common case. Since Blender 3.4 it holds float, vector and colour variants of its A and B inputs in one node. Only the variants matching data_type are visible, but all of them exist, so inputs["A"] returns the first one, which is the float. For the Color data type, use indices. Factor is inputs[0], A is inputs[6] and B is inputs[7]. The colour result is outputs[2].
When you are unsure, print the sockets:
import bpy
mat = bpy.data.materials["NoiseRamp"]
for node in mat.node_tree.nodes:
print(node.name, node.bl_idname)
for i, sock in enumerate(node.inputs):
print(f" in [{i}] {sock.name:<14} linked={sock.is_linked}")
for i, sock in enumerate(node.outputs):
print(f" out [{i}] {sock.name:<14} linked={sock.is_linked}")The output appears in Blender's system console. On Windows, open it with Window > Toggle System Console. On Linux and macOS, start Blender from a terminal.
Crack lines with Voronoi
The second graph from the plan uses Voronoi in Distance to Edge mode. The Distance output is near zero along cell borders and grows toward cell centres. The ramp maps 0 to black and 0.05 and above to white. The result is a mask that is dark only on thin lines. That mask drives Roughness and a Bump node, so the cracks are rougher and sit lower than the surface around them.
import bpy
mat = bpy.data.materials.new("VoronoiCracks")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
coord = nodes.new("ShaderNodeTexCoord")
voronoi = nodes.new("ShaderNodeTexVoronoi")
voronoi.feature = 'DISTANCE_TO_EDGE'
voronoi.inputs["Scale"].default_value = 4.0
ramp = nodes.new("ShaderNodeValToRGB")
cr = ramp.color_ramp
cr.elements[0].position = 0.0
cr.elements[0].color = (0.0, 0.0, 0.0, 1.0)
cr.elements[1].position = 0.05
cr.elements[1].color = (1.0, 1.0, 1.0, 1.0)
bump = nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = 0.8
links.new(coord.outputs["Object"], voronoi.inputs["Vector"])
links.new(voronoi.outputs["Distance"], ramp.inputs["Fac"])
links.new(ramp.outputs["Color"], bump.inputs["Height"])
links.new(ramp.outputs["Color"], bsdf.inputs["Roughness"])
links.new(bump.outputs["Normal"], bsdf.inputs["Normal"])This script finds the Principled BSDF by its type ('BSDF_PRINCIPLED') instead of its name. The type stays the same when the node is renamed or when Blender runs with another interface language. The nodes land at the origin because the script sets no locations. Choose Select All and then Arrange in the editor, or reuse new_node from the earlier script.
Warping with a second texture
The third graph feeds the Noise Texture's colour output into the Voronoi Vector input. The noise colour is a three-channel value that offsets the coordinates, so cell borders bend.
import bpy
mat = bpy.data.materials.new("WarpedVoronoi")
mat.use_nodes = True
nodes = mat.node_tree.nodes
links = mat.node_tree.links
bsdf = next(n for n in nodes if n.type == 'BSDF_PRINCIPLED')
coord = nodes.new("ShaderNodeTexCoord")
warp = nodes.new("ShaderNodeTexNoise")
warp.inputs["Scale"].default_value = 3.0
voronoi = nodes.new("ShaderNodeTexVoronoi")
voronoi.inputs["Scale"].default_value = 5.0
links.new(coord.outputs["Object"], warp.inputs["Vector"])
links.new(warp.outputs["Color"], voronoi.inputs["Vector"])
links.new(voronoi.outputs["Color"], bsdf.inputs["Base Color"])Because the noise colour replaces the coordinates instead of adding to them, the Voronoi pattern is heavily distorted. For a gentler effect, add a Vector Math node set to Add between the two nodes and scale the noise down first.
Editing a graph that already exists
You often need to change a graph instead of building one. Three operations cover most cases.
- Change a value. Find the node and set
default_value, for examplenodes["Noise Texture"].inputs["Scale"].default_value = 12.0. Node names such as "Noise Texture.001" are assigned in creation order, so loop over nodes and testnode.bl_idnamewhen you need a specific kind. - Remove a link. Find it in
tree.linksand calltree.links.remove(link). Thelink.from_socketandlink.to_socketattributes tell you which link it is. - Insert a node between two others. Remove the old link, create the new node, then add two links: from the old source to the new node, and from the new node to the old destination.
An input socket accepts one link. Linking a second output to the same input replaces the first link, with no error. An output can feed any number of inputs.
Common script errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'bpy_prop_collection[key]: key "X" not found'` | Wrong socket or node name | Print the sockets and check the exact spelling |
| `RuntimeError: Error: Link is not valid` or no link appears | Linked a node instead of a socket, or linked output to output | Link `node.outputs[...]` to `node.inputs[...]` |
| `TypeError: bpy_struct.new(): ...` | Wrong node type identifier | Check the `bl_idname`, for example `ShaderNodeValToRGB` |
| Colour looks wrong | Used an RGB tuple with three values | Colour sockets and ramp stops take four values, RGBA |
| Material is blank grey | Not assigned to an object | Append it to `obj.data.materials` |
| `use_nodes` warning in newer versions | Blender 5.0 deprecates `use_nodes` | Skip the line there, since new materials already use nodes |
Several runs of a script that calls materials.new create NoiseRamp, NoiseRamp.001 and so on. Use materials.get(name) or materials.new(name), as the first script does, to reuse one material.
Running without the interface
You can run a script on a file with no window open:
blender --background scene.blend --python build_materials.pyAdd bpy.ops.wm.save_mainfile() at the end of the script if you want the changes saved. Without it, the changes disappear when Blender exits.
Exercise
Exercise
You run your build script and get KeyError on mix.inputs["A"] followed, after fixing the name, by a grey result where you expected a coloured mix. The Mix node uses data type Color. What goes wrong, and how do you connect the ramp output to the right socket?
Show answer
Mix nodes since Blender 3.4 contain float, vector and colour variants of A and B, all with the same names. inputs["A"] returns the first match, the float variant, which is hidden when the data type is Color. A connection to a hidden socket has no visible effect. Link to the colour sockets by index instead: links.new(ramp.outputs["Color"], mix.inputs[6]) for A, and mix.inputs[7] for B. Read the result from mix.outputs[2]. Print enumerate(mix.inputs) to confirm the indices in your version.
Exercise
Write the lines that add a third stop at position 0.5 with a mid-brown colour to the ramp in build_noise_material, and explain why the order of the stops in cr.elements could change afterwards.
Show answer
Use stop = cr.elements.new(0.5) and then stop.color = (0.3, 0.2, 0.1, 1.0). Blender keeps the stops sorted by position, so the new stop becomes cr.elements[1] and the stop at 0.65 moves to index 2. Any code that still refers to elements[1] as the light stop now edits the new one. Hold references to the stops you create instead of relying on fixed indices.