1 ***********************
2 Quickstart Introduction
3 ***********************
8 This API is generally stable but some areas are still being added and improved.
10 The Blender/Python API can do the following:
12 * Edit any data the user interface can (Scenes, Meshes, Particles etc.)
14 * Modify user preferences, keymaps and themes
16 * Run tools with own settings
18 * Create user interface elements such as menus, headers and panels
22 * Create interactive tools
24 * Create new rendering engines that integrate with Blender
26 * Define new settings in existing Blender data
28 * Draw in the 3D view using OpenGL commands from Python
31 The Blender/Python API **can't** (yet)...
33 * Create new space types.
35 * Assign custom properties to every type.
37 * Define callbacks or listeners to be notified when data is changed.
43 This document isn't intended to fully cover each topic. Rather, its purpose is to familiarize you with Blender 2.5's new Python API.
46 A quick list of helpful things to know before starting:
48 * Blender uses Python 3.x; some 3rd party extensions are not available yet.
50 * The interactive console in Blender 2.5 has been improved; testing one-liners in the console is a good way to learn.
52 * Button tool tips show Python attributes and operator names.
54 * Right clicking on buttons and menu items directly links to API documentation.
56 * For more examples, the text menu has a templates section where some example operators can be found.
58 * To examine further scripts distributed with Blender, see ``~/.blender/scripts/startup/bl_ui`` for the user interface and ``~/.blender/scripts/startup/bl_op`` for operators.
70 Python accesses Blender's data in the same way as the animation system and user interface, which means any setting that is changed via a button can also be changed from Python.
72 Accessing data from the currently loaded blend file is done with the module :mod:`bpy.data`. This gives access to library data. For example:
75 <bpy_collection[3], BlendDataObjects>
78 <bpy_collection[1], BlendDataScenes>
80 >>> bpy.data.materials
81 <bpy_collection[1], BlendDataMaterials>
87 You'll notice that an index as well as a string can be used to access members of the collection.
89 Unlike Python's dictionaries, both methods are acceptable; however, the index of a member may change while running Blender.
91 >>> list(bpy.data.objects)
92 [bpy.data.objects["Cube"], bpy.data.objects["Plane"]]
94 >>> bpy.data.objects['Cube']
95 bpy.data.objects["Cube"]
97 >>> bpy.data.objects[0]
98 bpy.data.objects["Cube"]
104 Once you have a data block such as a material, object, groups etc. its attributes can be accessed just like changing a setting in the interface; in fact, the button tooltip also displays the Python attribute which can help in finding what settings to change in a script.
106 >>> bpy.data.objects[0].name
109 >>> bpy.data.scenes["Scene"]
110 bpy.data.scenes['Scene']
112 >>> bpy.data.materials.new("MyMaterial")
113 bpy.data.materials['MyMaterial']
116 For testing what data to access it's useful to use the "Console", which is its own space type in Blender 2.5. This supports auto-complete, giving you a fast way to dig into different data in your file.
118 Example of a data path that can be quickly found via the console:
120 >>> bpy.data.scenes[0].render.resolution_percentage
122 >>> bpy.data.scenes[0].objects["Torus"].data.vertices[0].co.x
129 Python can access properties on any datablock that has an ID (data that can be linked in and accessed from :mod:`bpy.data`. When assigning a property, you can make up your own names, these will be created when needed or overwritten if they exist.
131 This data is saved with the blend file and copied with objects.
135 .. code-block:: python
137 bpy.context.object["MyOwnProperty"] = 42
139 if "SomeProp" in bpy.context.object:
140 print("Property found")
142 # Use the get function like a python dictionary
143 # which can have a fallback value.
144 value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
146 # dictionaries can be assigned as long as they only use basic types.
147 group = bpy.data.groups.new("MyTestGroup")
148 group["GameSettings"] = {"foo": 10, "bar": "spam", "baz": {}}
150 del group["GameSettings"]
153 Note that these properties can only be assigned basic Python types.
157 * array of ints/floats
159 * dictionary (only string keys are supported, values must be basic types too)
161 These properties are valid outside of Python. They can be animated by curves or used in driver paths.
167 While it's useful to be able to access data directly by name or as a list, it's more common to operate on the user's selection. The context is always available from '''bpy.context''' and can be used to get the active object, scene, tool settings along with many other attributes.
171 >>> bpy.context.object
172 >>> bpy.context.selected_objects
173 >>> bpy.context.visible_bones
175 Note that the context is read-only. These values cannot be modified directly, though they may be changed by running API functions or by using the data API.
177 So ``bpy.context.object = obj`` will raise an error.
179 But ``bpy.context.scene.objects.active = obj`` will work as expected.
182 The context attributes change depending on where it is accessed. The 3D view has different context members to the Console, so take care when accessing context attributes that the user state is known.
184 See :mod:`bpy.context` API reference
190 Operators are tools generally accessed by the user from buttons, menu items or key shortcuts. From the user perspective they are a tool but Python can run these with its own settings through the :mod:`bpy.ops` module.
194 >>> bpy.ops.mesh.flip_normals()
196 >>> bpy.ops.mesh.hide(unselected=False)
198 >>> bpy.ops.object.scale_apply()
203 The menu item: Help -> Operator Cheat Sheet" gives a list of all operators and their default values in Python syntax, along with the generated docs. This is a good way to get an overview of all blender's operators.
209 Many operators have a "poll" function which may check that the mouse is a valid area or that the object is in the correct mode (Edit Mode, Weight Paint etc). When an operator's poll function fails within python, an exception is raised.
211 For example, calling bpy.ops.view3d.render_border() from the console raises the following error:
213 .. code-block:: python
215 RuntimeError: Operator bpy.ops.view3d.render_border.poll() failed, context is incorrect
217 In this case the context must be the 3d view with an active camera.
219 To avoid using try/except clauses wherever operators are called you can call the operators own .poll() function to check if it can run in the current context.
221 .. code-block:: python
223 if bpy.ops.view3d.render_border.poll():
224 bpy.ops.view3d.render_border()
230 Python scripts can integrate with Blender in the following ways:
232 * By defining a rendering engine.
234 * By defining operators.
236 * By defining menus, headers and panels.
238 * By inserting new buttons into existing menus, headers and panels
241 In Python, this is done by defining a class, which is a subclass of an existing type.
247 .. literalinclude:: ../../../release/scripts/templates/operator_simple.py
249 Once this script runs, ``SimpleOperator`` is registered with Blender and can be called from the operator search popup or added to the toolbar.
253 #. Highlight the above code then press Ctrl+C to copy it.
257 #. Press Ctrl+Right twice to change to the Scripting layout.
259 #. Press Ctrl+V to paste the code into the text panel (the upper left frame).
261 #. Click on the button **Run Script**.
263 #. Move you're mouse into the 3D view, press spacebar for the operator search
264 menu, and type "Simple".
266 #. Click on the "Simple Operator" item found in search.
269 .. seealso:: The class members with the **bl_** prefix are documented in the API
270 reference :class:`bpy.types.Operator`
276 Panels register themselves as a class, like an operator. Notice the extra **bl_** variables used to set the context they display in.
278 .. literalinclude:: ../../../release/scripts/templates/ui_panel_simple.py
282 #. Highlight the above code then press Ctrl+C to copy it
286 #. Press Ctrl+Right twice to change to the Scripting layout
288 #. Press Ctrl+V to paste the code into the text panel (the upper left frame)
290 #. Click on the button **Run Script**.
295 #. Select the the default cube.
297 #. Click on the Object properties icon in the buttons panel (far right; appears as a tiny cube).
299 #. Scroll down to see a panel named **Hello World Panel**.
301 #. Changing the object name also updates **Hello World Panel's** Name: field.
303 Note the row distribution and the label and properties that are available through the code.
305 .. seealso:: :class:`bpy.types.Panel`
311 Blender defines a number of Python types but also uses Python native types.
313 Blender's Python API can be split up into 3 categories.
319 In simple cases returning a number or a string as a custom type would be cumbersome, so these are accessed as normal python types.
321 * blender float/int/boolean -> float/int/boolean
323 * blender enumerator -> string
325 >>> C.object.rotation_mode = 'AXIS_ANGLE'
328 * blender enumerator (multiple) -> set of strings
330 .. code-block:: python
332 # setting multiple camera overlay guides
333 bpy.context.scene.camera.data.show_guide = {'GOLDEN', 'CENTER'}
335 # passing as an operator argument for report types
336 self.report({'WARNING', 'INFO'}, "Some message!")
342 Used for Blender datablocks and collections: :class:`bpy.types.bpy_struct`
344 For data that contains its own attributes groups/meshes/bones/scenes... etc.
346 There are 2 main types that wrap Blenders data, one for datablocks (known internally as bpy_struct), another for properties.
348 >>> bpy.context.object
349 bpy.data.objects['Cube']
352 bpy.data.scenes['Scene'].objects
354 Note that these types reference Blender's data so modifying them is immediately visible.
360 Used for vectors, quaternion, eulers, matrix and color types, accessible from :mod:`mathutils`
362 Some attributes such as :class:`bpy.types.Object.location`, :class:`bpy.types.PoseBone.rotation_euler` and :class:`bpy.types.Scene.cursor_location` can be accessed as special math types which can be used together and manipulated in various useful ways.
364 Example of a matrix, vector multiplication:
366 .. code-block:: python
368 bpy.context.object.matrix_world * bpy.context.object.data.verts[0].co
372 mathutils types keep a reference to Blender's internal data so changes can
378 .. code-block:: python
380 # modifies the Z axis in place.
381 bpy.context.object.location.z += 2.0
383 # location variable holds a reference to the object too.
384 location = bpy.context.object.location
387 # Copying the value drops the reference so the value can be passed to
388 # functions and modified without unwanted side effects.
389 location = bpy.context.object.location.copy()
395 There are 2 ways to add keyframes through Python.
397 The first is through key properties directly, which is similar to inserting a keyframe from the button as a user. You can also manually create the curves and keyframe data, then set the path to the property. Here are examples of both methods.
399 Both examples insert a keyframe on the active object's Z axis.
403 .. code-block:: python
405 obj = bpy.context.object
406 obj.location[2] = 0.0
407 obj.keyframe_insert(data_path="location", frame=10.0, index=2)
408 obj.location[2] = 1.0
409 obj.keyframe_insert(data_path="location", frame=20.0, index=2)
411 Using Low-Level Functions:
413 .. code-block:: python
415 obj = bpy.context.object
416 obj.animation_data_create()
417 obj.animation_data.action = bpy.data.actions.new(name="MyAction")
418 fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)
419 fcu_z.keyframe_points.add(2)
420 fcu_z.keyframe_points[0].co = 10.0, 0.0
421 fcu_z.keyframe_points[1].co = 20.0, 1.0