Sub topic 13
Optional: Building the Scene with Python
Everything you built by hand in the earlier chapters can also be produced by a script. This chapter shows how to write one script that creates the ground, trees and rocks, adds a light and a camera, and renders an image. You don't need it to finish the tutorial. It is useful when you want repeatable results, many copies of an object with small variations, or a scene you can rebuild after changing one number.
Prerequisites
This chapter assumes you have:
- Blender 4.x installed and the scene-building chapters completed.
- Basic Python: functions, loops, tuples and the
randommodule. - Familiarity with the Scripting workspace (the tab at the top of the window) or with running Blender from a terminal.
The working model: two ways to talk to Blender
The bpy module gives you two main routes into Blender's data. Knowing which one you are using explains most scripting errors.
| Route | Example | How it behaves |
|---|---|---|
| `bpy.ops` (operators) | `bpy.ops.mesh.primitive_cone_add(...)` | Does what the menu item does. Depends on context: the current mode, the active object, the selection. |
| `bpy.data` (data API) | `bpy.data.materials.new(...)` | Creates or edits data directly. Needs no selection or mode. |
Operators are convenient for primitives because they build the mesh for you. After an operator adds an object, that object is the active one, so bpy.context.active_object returns it. The data API is more reliable for everything else, such as materials, lights, cameras and cleanup.
Plan of the script
The script follows the same order as your manual workflow. Each stage is a function, so you can test it alone.
Helper functions
Start with the pieces that several stages share: cleanup, materials and flat shading.
import math
import os
import random
import bpy
from mathutils import Vector
random.seed(7) # same seed, same scene every run
def clear_scene():
# Data API removal needs no selection and works in any mode
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
def make_material(name, color):
mat = bpy.data.materials.get(name) or bpy.data.materials.new(name=name)
mat.use_nodes = True
mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = color
mat.diffuse_color = color # colour in the solid viewport
return mat
def finish(obj, mat):
# Flat shading, then one solid-colour material
for poly in obj.data.polygons:
poly.use_smooth = False
obj.data.update()
obj.data.materials.append(mat)
return objmake_material reuses a material that already has the given name. Without that check, running the script twice would create Leaf, Leaf.001, Leaf.002 and so on.
Building the objects
Each builder calls one operator, reads the new active object and passes it to finish.
def add_ground(mat):
bpy.ops.mesh.primitive_plane_add(size=20, location=(0, 0, 0))
ground = bpy.context.active_object
ground.name = "Ground"
return finish(ground, mat)
def add_tree(x, y, s, trunk_mat, leaf_mat):
bpy.ops.mesh.primitive_cylinder_add(
vertices=6, radius=0.2 * s, depth=1.0 * s, location=(x, y, 0.5 * s))
trunk = bpy.context.active_object
trunk.name = "Trunk"
finish(trunk, trunk_mat)
bpy.ops.mesh.primitive_cone_add(
vertices=6, radius1=1.0 * s, radius2=0.0, depth=2.0 * s,
location=(x, y, 2.0 * s))
foliage = bpy.context.active_object
foliage.name = "Foliage"
finish(foliage, leaf_mat)
def add_rock(x, y, mat):
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, radius=1.0, location=(x, y, 0.2))
rock = bpy.context.active_object
rock.name = "Rock"
rock.scale = (random.uniform(0.3, 0.6), random.uniform(0.3, 0.6), random.uniform(0.2, 0.4))
rock.rotation_euler[2] = random.uniform(0, math.tau)
return finish(rock, mat)The trunk is 1.0 * s tall and sits on the ground, so its centre is at half that height. The cone's base meets the trunk top at 1.0 * s, and its centre is half its depth above that, at 2.0 * s. If you change the proportions in one place, change the matching height in the other.
Setting rock.scale and rotation_euler is the scripted version of the Object Mode transforms from the earlier chapter. Random variation in proportions keeps the rocks from looking like copies.
Light, camera and render
Lights and cameras are plain data blocks. You create the data, wrap it in an object, and link the object to a collection.
def add_sun():
sun_data = bpy.data.lights.new(name="Sun", type='SUN')
sun_data.energy = 3.0
sun = bpy.data.objects.new("Sun", sun_data)
bpy.context.scene.collection.objects.link(sun)
sun.rotation_euler = (math.radians(50), 0, math.radians(30))
def add_camera(target=(0, 0, 1)):
cam_data = bpy.data.cameras.new("Camera")
cam = bpy.data.objects.new("Camera", cam_data)
bpy.context.scene.collection.objects.link(cam)
cam.location = (12, -12, 8)
direction = Vector(target) - cam.location
# A camera looks down its -Z axis, with +Y as "up"
cam.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
bpy.context.scene.camera = cam
def render(path):
scene = bpy.context.scene
scene.render.resolution_x = 1280
scene.render.resolution_y = 720
scene.render.filepath = path
bpy.ops.render.render(write_still=True)An object that is not linked to a collection exists in bpy.data but never appears in the scene. That is a common reason for a light or camera that "does nothing".
Putting it together
The main function builds the scene. Trees are placed by trying random positions and rejecting any that fall too close to a tree already placed.
def main():
clear_scene()
grass = make_material("Grass", (0.25, 0.6, 0.2, 1.0))
bark = make_material("Bark", (0.35, 0.2, 0.1, 1.0))
leaf = make_material("Leaf", (0.1, 0.5, 0.15, 1.0))
stone = make_material("Stone", (0.5, 0.5, 0.52, 1.0))
add_ground(grass)
placed = []
while len(placed) < 6:
x, y = random.uniform(-8, 8), random.uniform(-8, 8)
if all(math.hypot(x - px, y - py) > 3 for px, py in placed):
placed.append((x, y))
add_tree(x, y, random.uniform(0.8, 1.4), bark, leaf)
for _ in range(8):
add_rock(random.uniform(-8, 8), random.uniform(-8, 8), stone)
add_sun()
add_camera()
render(os.path.join(os.path.expanduser("~"), "lowpoly.png"))
main()Run it in either of these ways:
- Paste all the blocks into one file in the Scripting workspace and press Run Script.
- Save them as
build_scene.pyand runblender --background --python build_scene.pyfrom a terminal.
The six-tree loop terminates because the ground is large enough for six points with a gap of 3 units. If you raise the count or the gap, add an attempt limit so the loop cannot run forever.
Common errors
RuntimeError: Operator bpy.ops... poll() failed, context is incorrect. The operator cannot run in the current mode or area. Switch to Object Mode first withbpy.ops.object.mode_set(mode='OBJECT')if an object is in Edit Mode, or use the data API instead.AttributeError: 'NoneType' object has no attribute 'data'.bpy.context.active_objectisNonebecause no object was added or selected. Check that the operator before it did not fail.- Everything is black or very dark. The scene has no light, or the sun's rotation points it away from the ground. Check that
add_sunran and try a differentrotation_euler. - The render shows nothing from the right angle.
scene.camerawas never set. Linking a camera object is not enough, because Blender renders through the scene's active camera. - Edits to mesh data do not show. In Edit Mode, mesh changes live in a separate edit buffer. Return to Object Mode before reading or writing
obj.data.polygons. - The render engine. Engine names have changed between releases, for example
BLENDER_EEVEE_NEXTin 4.2 to 4.4 andBLENDER_EEVEEbefore and after. The script leaves the scene's engine alone to avoid version errors. If you set it, check the allowed values for your version.
When scripting is worth it
Scripting pays off when you repeat a task, such as 50 trees with slightly different sizes. Hand modelling still wins for one-off shapes where you work by eye, such as a rock you keep adjusting in Edit Mode. A practical mix is to model one good tree by hand and then use a script, or linked duplicates, to place copies of it.
Exercise
The script creates the trunk and the foliage as two separate objects. A tree at scale s = 2 looks wrong because the foliage floats above the trunk. Which values in add_tree fix the heights, and what should they be for scale s?
Show answer
The trunk's centre height is 0.5 s (half its depth of 1.0 s), and the foliage's centre height is 2.0 s (trunk top at 1.0 s, plus half the cone depth of 2.0 s, which is 1.0 s). Both heights must be multiples of the same s as the sizes. If one is left at a fixed number, the parts separate as s changes.
Exercise
You run the script twice in the same file without calling clear_scene(). Name two things you would see, and name the code that prevents one of them.
Show answer
Objects are duplicated (Ground, Trunk, Foliage and Rock gain .001 suffixes), and materials could also multiply. The bpy.data.materials.get(name) or bpy.data.materials.new(name=name) check in make_material prevents duplicate materials. clear_scene() removes the duplicate objects.