Sub topic 17
Automating the Bake with Python
This chapter assumes you have already baked a normal map and an ambient occlusion (AO) map by hand with Selected to Active. It also assumes you can run a script from Blender's Scripting workspace or from the command line. Here you turn the manual steps into a script you can rerun when the high-poly mesh changes, when you switch resolution, or when you have many assets to process.
What a scripted bake must reproduce
A manual bake works because of state you set up in the interface: an engine, bake settings, a target image, an active Image Texture node, and a selection. The script has to set every one of these explicitly. Most scripted bakes that fail do so because one piece of state is missing, not because the bake call is wrong.
The settings that matter
All bake options live on scene.render.bake. The ones you set most often:
| Property | Meaning | Typical value |
|---|---|---|
| `use_selected_to_active` | Bake from the selected objects onto the active one | `True` |
| `cage_extrusion` | How far the ray origin is pushed out along normals | `0.02` |
| `max_ray_distance` | Limit on how far rays travel. `0.0` means no limit | `0.0` |
| `margin` | Pixels of padding around UV islands | `16` |
| `normal_space` | `'TANGENT'` or `'OBJECT'` | `'TANGENT'` |
| `normal_g` | Green channel direction: `'POS_Y'` (OpenGL) or `'NEG_Y'` (DirectX) | `'POS_Y'` |
Cage extrusion and max ray distance work together. If a ray starts at the extruded position and also has a distance limit, the limit is measured from that start point. Set the extrusion first, then decide whether you still need a limit.
A complete first version
This script bakes the normal map. It is the minimum that works, and the rest of the chapter improves on it.
import bpy
high = bpy.data.objects["Asset_high"]
low = bpy.data.objects["Asset_low"]
scene = bpy.context.scene
scene.render.engine = 'CYCLES'
scene.cycles.samples = 64
bake = scene.render.bake
bake.use_selected_to_active = True
bake.cage_extrusion = 0.02
bake.max_ray_distance = 0.0
bake.margin = 16
bake.normal_space = 'TANGENT'
img = bpy.data.images.new("Asset_normal", 2048, 2048)
img.colorspace_settings.name = 'Non-Color'
mat = low.active_material
mat.use_nodes = True
nodes = mat.node_tree.nodes
tex = nodes.new('ShaderNodeTexImage')
tex.image = img
nodes.active = tex
bpy.ops.object.select_all(action='DESELECT')
high.select_set(True)
low.select_set(True)
bpy.context.view_layer.objects.active = low
bpy.ops.object.bake(type='NORMAL')
img.filepath_raw = "//Asset_normal.png"
img.file_format = 'PNG'
img.save()Four lines carry the load:
img.colorspace_settings.name = 'Non-Color'stops Blender from applying a color transform to data that is not color.nodes.active = textells the baker which image to write into. Without it, the bake fails with an error about no active image.high.select_set(True)andlow.select_set(True)together withview_layer.objects.active = lowdefine source and target. The active object is always the target.bpy.ops.object.bake(type='NORMAL')is an operator, so it depends on that context and on the scene settings above.
Turning it into a reusable function
Running two bakes with copy-pasted code leaves temporary nodes and images behind. A function that creates the target, bakes, saves, and cleans up keeps the scene tidy. The version below also checks its inputs and restores object mode.
import bpy
def prepare_scene(cage=0.02, ray=0.0, margin=16, samples=64):
scene = bpy.context.scene
scene.render.engine = 'CYCLES'
scene.cycles.samples = samples
bake = scene.render.bake
bake.use_selected_to_active = True
bake.cage_extrusion = cage
bake.max_ray_distance = ray
bake.margin = margin
bake.normal_space = 'TANGENT'
bake.normal_g = 'POS_Y'
def bake_map(high, low, bake_type, name, size=2048):
if bpy.context.object and bpy.context.object.mode != 'OBJECT':
bpy.ops.object.mode_set(mode='OBJECT')
mat = low.active_material
if mat is None:
raise RuntimeError(f"{low.name} has no material to hold the bake target")
mat.use_nodes = True
nodes = mat.node_tree.nodes
img = bpy.data.images.new(name, size, size)
img.colorspace_settings.name = 'Non-Color'
tex = nodes.new('ShaderNodeTexImage')
tex.image = img
nodes.active = tex
bpy.ops.object.select_all(action='DESELECT')
high.select_set(True)
low.select_set(True)
bpy.context.view_layer.objects.active = low
try:
bpy.ops.object.bake(type=bake_type)
finally:
nodes.remove(tex)
img.filepath_raw = f"//{name}.png"
img.file_format = 'PNG'
img.save()
return img
high = bpy.data.objects["Asset_high"]
low = bpy.data.objects["Asset_low"]
prepare_scene()
bake_map(high, low, 'NORMAL', "Asset_normal")
bake_map(high, low, 'AO', "Asset_ao")The try/finally block removes the temporary node even if the bake raises an error, so a failed run does not pile up stray nodes in the material. The image stays in bpy.data.images so you can still inspect it.
A node you remove is no longer in the material, so the saved PNG is the durable result. To use the maps, rebuild the shader connections as in the earlier chapter on applying maps.
Wiring the normal map in code
You can also script the material side, so the baked result is visible immediately.
import bpy
mat = bpy.data.objects["Asset_low"].active_material
nodes = mat.node_tree.nodes
links = mat.node_tree.links
normal_tex = nodes.new('ShaderNodeTexImage')
normal_tex.image = bpy.data.images["Asset_normal"]
normal_tex.image.colorspace_settings.name = 'Non-Color'
normal_map = nodes.new('ShaderNodeNormalMap')
normal_map.space = 'TANGENT'
bsdf = nodes.get("Principled BSDF")
links.new(normal_tex.outputs['Color'], normal_map.inputs['Color'])
links.new(normal_map.outputs['Normal'], bsdf.inputs['Normal'])Run this after the bake, not before. If the Normal Map node chain is connected while you bake, the baker may pick up the existing normal input and the result will be wrong.
Running the script without the interface
Save the script as bake.py next to your .blend file and run:
blender -b asset.blend --python bake.pyThe -b flag runs Blender in the background with no window. The // prefix in the file paths resolves relative to the saved .blend, so the PNGs land next to it. Background mode is useful for batch jobs and for build servers.
Common errors
- "No active image found in material." The Image Texture node exists but is not active. Set
nodes.active = texafter creating it. - "Failed to find 'Selected to Active' source." Either the high-poly object is not selected, or it is hidden in the viewport or excluded from the view layer. Hidden objects cannot be selected with
select_set. - Black or flat output. The target object lacks UVs, or the rays miss. Check the cage extrusion, as in the troubleshooting chapter.
- Washed-out normal map. The image was left in an sRGB color space. Set
Non-Colorbefore baking. - Operator poll errors. The scene is not in Object Mode, or the engine is not Cycles. The function above handles both.
When scripting is worth it
Scripting pays off when you bake the same asset repeatedly while iterating on the sculpt, when you maintain several assets with the same naming scheme, or when a pipeline bakes automatically. For a single one-off bake, the interface is faster.
Exercise
Your script bakes AO into an image, but Blender reports that no active image was found in the material. The image exists and the node references it. What is the most likely missing line, and why is it needed?
Show answer
The Image Texture node was never made the active node, so the line nodes.active = tex is missing. The baker writes to the image of the active Image Texture node in the target object's material. Creating the node and assigning its image is not enough, because the baker looks at the active node, not at all nodes.
Exercise
You want the script to export a DirectX-style normal map for an engine that expects an inverted green channel. Which setting do you change, and where?
Show answer
Set scene.render.bake.normal_g = 'NEG_Y' before calling bpy.ops.object.bake(type='NORMAL'). The default 'POS_Y' produces the OpenGL convention.