Welcome to mirror list, hosted at ThFree Co, Russian Federation.

git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/doc
diff options
context:
space:
mode:
authorCampbell Barton <ideasman42@gmail.com>2011-08-27 12:09:12 +0400
committerCampbell Barton <ideasman42@gmail.com>2011-08-27 12:09:12 +0400
commit909d74d1246f55cd55113e47a3538210fbe8bca5 (patch)
treeaef4092d28e024251755251f9bf14b63122f48b9 /doc
parentcd0e92c5b7b5fb12f07305101fdba45a5cd10e9c (diff)
- use python convention for headings
- use implicit examples rather than .. code-block::
Diffstat (limited to 'doc')
-rw-r--r--doc/python_api/rst/info_gotcha.rst111
-rw-r--r--doc/python_api/rst/info_overview.rst43
-rw-r--r--doc/python_api/rst/info_quickstart.rst85
3 files changed, 82 insertions, 157 deletions
diff --git a/doc/python_api/rst/info_gotcha.rst b/doc/python_api/rst/info_gotcha.rst
index 3d869be7009..c97fc3ab427 100644
--- a/doc/python_api/rst/info_gotcha.rst
+++ b/doc/python_api/rst/info_gotcha.rst
@@ -1,12 +1,12 @@
-########
+********
Gotcha's
-########
+********
This document attempts to help you work with the Blender API in areas that can be troublesome and avoid practices that are known to give instability.
-***************
+
Using Operators
-***************
+===============
Blender's operators are tools for users to access, that python can access them too is very useful nevertheless operators have limitations that can make them cumbersome to script.
@@ -19,19 +19,13 @@ Main limits are...
* Operators poll function can fail where an API function would raise an exception giving details on exactly why.
-=================================
+
Why does an operator's poll fail?
-=================================
+---------------------------------
When calling an operator gives an error like this:
-.. code-block:: python
-
>>> bpy.ops.action.clean(threshold=0.001)
- Traceback (most recent call last):
- File "<blender_console>", line 1, in <module>
- File "scripts/modules/bpy/ops.py", line 179, in __call__
- ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.action.clean.poll() failed, context is incorrect
Which raises the question as to what the correct context might be?
@@ -51,14 +45,12 @@ Downloading and searching the C code isn't so simple, especially if you're not f
Blender does have the functionality for poll functions to describe why they fail, but its currently not used much, if you're interested to help improve our API feel free to add calls to ``CTX_wm_operator_poll_msg_set`` where its not obvious why poll fails.
- .. code-block:: python
-
>>> bpy.ops.gpencil.draw()
RuntimeError: Operator bpy.ops.gpencil.draw.poll() Failed to find Grease Pencil data to draw into
-================================
+
The operator still doesn't work!
-================================
+--------------------------------
Certain operators in Blender are only intended for use in a specific context, some operators for example are only called from the properties window where they check the current material, modifier or constraint.
@@ -72,13 +64,11 @@ Examples of this are:
Another possibility is that you are the first person to attempt to use this operator in a script and some modifications need to be made to the operator to run in a different context, if the operator should logically be able to run but fails when accessed from a script it should be reported to the bug tracker.
-**********
Stale Data
-**********
+==========
-===============================
No updates after setting values
-===============================
+-------------------------------
Sometimes you want to modify values from python and immediately access the updated values, eg:
@@ -97,9 +87,9 @@ However, while the script runs you may want to access the updated values.
This can be done by calling :class:`bpy.types.Scene.update` after modifying values which recalculates all data that is tagged to be updated.
-===============================
+
Can I redraw during the script?
-===============================
+-------------------------------
The official answer to this is no, or... *"You don't want to do that"*.
@@ -128,18 +118,16 @@ If you insist - yes its possible, but scripts that use this hack wont be conside
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
-******************************
Matrix multiplication is wrong
-******************************
+==============================
Every so often users complain that Blenders matrix math is wrong, the confusion comes from mathutils matrices being column-major to match OpenGL and the rest of Blenders matrix operations and stored matrix data.
This is different to **numpy** which is row-major which matches what you would expect when using conventional matrix math notation.
-***********************************
I can't edit the mesh in edit-mode!
-***********************************
+===================================
Blenders EditMesh is an internal data structure (not saved and not exposed to python), this gives the main annoyance that you need to exit edit-mode to edit the mesh from python.
@@ -152,9 +140,8 @@ write useful tools in python which are also fast to execute while in edit-mode.
For the time being this limitation just has to be worked around but we're aware its frustrating needs to be addressed.
-***********************************
EditBones, PoseBones, Bone... Bones
-***********************************
+===================================
Armature Bones in Blender have three distinct data structures that contain them. If you are accessing the bones through one of them, you may not have access to the properties you really need.
@@ -163,49 +150,48 @@ Armature Bones in Blender have three distinct data structures that contain them.
In the following examples ``bpy.context.object`` is assumed to be an armature object.
-==========
Edit Bones
-==========
+----------
``bpy.context.object.data.edit_bones`` contains a editbones; to access them you must set the armature mode to edit mode first (editbones do not exist in object or pose mode). Use these to create new bones, set their head/tail or roll, change their parenting relationships to other bones, etc.
Example using :class:`bpy.types.EditBone` in armature editmode:
-.. code-block:: python
+This is only possible in edit mode.
+
+ >>> bpy.context.object.data.edit_bones["Bone"].head = Vector((1.0, 2.0, 3.0))
- # This is only possible in edit mode.
- bpy.context.object.data.edit_bones["Bone"].head = Vector((1.0, 2.0, 3.0))
+This will be empty outside of editmode.
- # This will be empty outside of editmode.
- mybones = bpy.context.selected_editable_bones
+ >>> mybones = bpy.context.selected_editable_bones
- # Returns an editbone only in edit mode.
- bpy.context.active_bone
+Returns an editbone only in edit mode.
+
+ >>> bpy.context.active_bone
-===================
Bones (Object Mode)
-===================
+-------------------
``bpy.context.object.data.bones`` contains bones. These *live* in object mode, and have various properties you can change, note that the head and tail properties are read-only.
Example using :class:`bpy.types.Bone` in object or pose mode:
-.. code-block:: python
+Returns a bone (not an editbone) outside of edit mode
- # returns a bone (not an editbone) outside of edit mode
- bpy.context.active_bone
+ >>> bpy.context.active_bone
- # This works, as with blender the setting can be edited in any mode
- bpy.context.object.data.bones["Bone"].use_deform = True
+This works, as with blender the setting can be edited in any mode
- # Accessible but read-only
- tail = myobj.data.bones["Bone"].tail
+ >>> bpy.context.object.data.bones["Bone"].use_deform = True
+
+Accessible but read-only
+
+ >>> tail = myobj.data.bones["Bone"].tail
-==========
Pose Bones
-==========
+----------
``bpy.context.object.pose.bones`` contains pose bones. This is where animation data resides, i.e. animatable transformations are applied to pose bones, as are constraints and ik-settings.
@@ -229,18 +215,16 @@ Examples using :class:`bpy.types.PoseBone` in object or pose mode:
Strictly speaking PoseBone's are not bones, they are just the state of the armature, stored in the :class:`bpy.types.Object` rather than the :class:`bpy.types.Armature`, the real bones are however accessible from the pose bones - :class:`bpy.types.PoseBone.bone`
-=======================
Armature Mode Switching
-=======================
+-----------------------
While writing scripts that deal with armatures you may find you have to switch between modes, when doing so take care when switching out of editmode not to keep references to the edit-bones or their head/tail vectors. Further access to these will crash blender so its important the script clearly separates sections of the code which operate in different modes.
This is mainly an issue with editmode since pose data can be manipulated without having to be in pose mode, however for operator access you may still need to enter pose mode.
-****************
Unicode Problems
-****************
+================
Python supports many different encpdings so there is nothing stopping you from writing a script in latin1 or iso-8859-15.
@@ -256,8 +240,6 @@ Paths are an exception to this rule since we cannot ignore the existane of non-u
This means seemingly harmless expressions can raise errors, eg.
-.. code-block:: python
-
>>> print(bpy.data.filepath)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 10-21: ordinal not in range(128)
@@ -267,9 +249,7 @@ This means seemingly harmless expressions can raise errors, eg.
TypeError: bpy_struct: item.attr= val: Object.name expected a string type, not str
-Here are 2 ways around filesystem encoding issues.
-
-.. code-block:: python
+Here are 2 ways around filesystem encoding issues:
>>> print(repr(bpy.data.filepath))
@@ -292,9 +272,8 @@ Unicode encoding/decoding is a big topic with comprehensive python documentation
* **Possibly** - use bytes instead of python strings, when reading some input its less trouble to read it as binary data though you will still need to deciede how to treat any strings you want to use with Blender, some importers do this.
-***************************************
Strange errors using 'threading' module
-***************************************
+=======================================
Python threading with Blender only works properly when the threads finish up before the script does. By using ``threading.join()`` for example.
@@ -361,9 +340,8 @@ So far no work has gone into making Blenders python integration thread safe, so
Pythons threads only allow co-currency and wont speed up you're scripts on multi-processor systems, the ``subprocess`` and ``multiprocess`` modules can be used with blender and make use of multiple CPU's too.
-*******************************
Help! My script crashes Blender
-*******************************
+===============================
Ideally it would be impossible to crash Blender from python however there are some problems with the API where it can be made to crash.
@@ -380,16 +358,13 @@ Here are some general hints to avoid running into these problems.
* Crashes may not happen every time, they may happen more on some configurations/operating-systems.
-=========
Undo/Redo
-=========
+---------
Undo invalidates all :class:`bpy.types.ID` instances (Object, Scene, Mesh etc).
This example shows how you can tell undo changes the memory locations.
-.. code-block:: python
-
>>> hash(bpy.context.object)
-9223372036849950810
>>> hash(bpy.context.object)
@@ -403,9 +378,8 @@ This example shows how you can tell undo changes the memory locations.
As suggested above, simply not holding references to data when Blender is used interactively by the user is the only way to ensure the script doesn't become unstable.
-===================
Array Re-Allocation
-===================
+-------------------
When adding new points to a curve or vertices's/edges/faces to a mesh, internally the array which stores this data is re-allocated.
@@ -423,9 +397,8 @@ This can be avoided by re-assigning the point variables after adding the new one
The best way is to sidestep the problem altogether add all the points to the curve at once. This means you don't have to worry about array re-allocation and its faster too since reallocating the entire array for every point added is inefficient.
-=============
Removing Data
-=============
+-------------
**Any** data that you remove shouldn't be modified or accessed afterwards, this includes f-curves, drivers, render layers, timeline markers, modifiers, constraints along with objects, scenes, groups, bones.. etc.
diff --git a/doc/python_api/rst/info_overview.rst b/doc/python_api/rst/info_overview.rst
index 9c1b932df64..fe730088c44 100644
--- a/doc/python_api/rst/info_overview.rst
+++ b/doc/python_api/rst/info_overview.rst
@@ -1,12 +1,12 @@
-###################
+*******************
Python API Overview
-###################
+*******************
This document is to give an understanding of how python and blender fit together, covering some of the functionality that isn't obvious from reading the API reference and example scripts.
-*****************
+
Python in Blender
-*****************
+=================
Blender embeds a python interpreter which is started with blender and stays active. This interpreter runs scripts to draw the user interface and is used for some of Blender's internal tools too.
@@ -22,18 +22,16 @@ Here is a simple example of moving a vertex of the object named **Cube**:
This modifies Blender's internal data directly. When you run this in the interactive console you will see the 3D viewport update.
-***********************
The Default Environment
-***********************
+=======================
When developing your own scripts it may help to understand how blender sets up its python environment. Many python scripts come bundled with blender and can be used as a reference because they use the same API that script authors write tools in. Typical usage for scripts include: user interface, import/export, scene manipulation, automation, defining your own toolset and customization.
On startup blender scans the ``scripts/startup/`` directory for python modules and imports them. The exact location of this directory depends on your installation. `See the directory layout docs <http://wiki.blender.org/index.php/Doc:2.5/Manual/Introduction/Installing_Blender/DirectoryLayout>`_
-**************
Script Loading
-**************
+==============
This may seem obvious but it's important to note the difference between executing a script directly or importing it as a module.
@@ -64,9 +62,8 @@ To run as modules:
* define as an addon, enabling the addon will load it as a python module.
-======
Addons
-======
+------
Some of blenders functionality is best kept optional, alongside scripts loaded at startup we have addons which are kept in their own directory ``scripts/addons``, and only load on startup if selected from the user preferences.
@@ -77,9 +74,8 @@ The user preferences addon listing uses **bl_info** to display information about
`See Addons <http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Guidelines/Addons>`_ for details on the **bl_info** dictionary.
-***************************
Integration through Classes
-***************************
+===========================
Running python scripts in the text editor is useful for testing but you’ll want to extend blender to make tools accessible like other built-in functionality.
@@ -159,14 +155,12 @@ To run operators you can call them through the operator api, eg:
User interface classes are given a context in which to draw, buttons window, file header, toolbar etc, then they are drawn when that area is displayed so they are never called by python scripts directly.
-************
Registration
-************
+============
-===================
Module Registration
-===================
+-------------------
Blender modules loaded at startup require ``register()`` and ``unregister()`` functions. These are the *only* functions that blender calls from your code, which is otherwise a regular python module.
@@ -206,9 +200,8 @@ This allows the script to be run directly in the text editor to test changes.
This ``register()`` call won't run when the script is imported as a module since ``__main__`` is reserved for direct execution.
-==================
Class Registration
-==================
+------------------
Registering a class with blender results in the class definition being loaded into blender, where it becomes available alongside existing functionality.
@@ -227,9 +220,8 @@ Using ``bl_idname = 1`` will raise.
``TypeError: validating class error: Operator.bl_idname expected a string type, not int``
-----------------
Multiple-Classes
-----------------
+^^^^^^^^^^^^^^^^
Loading classes into blender is described above, for simple cases calling :mod:`bpy.utils.register_class` (SomeClass) is sufficient, but when there are many classes or a packages submodule has its own classes it can be tedious to list them all for registration.
@@ -248,9 +240,8 @@ A script which defines many of its own operators, panels menus etc. you only nee
Internally blender collects subclasses on registrable types, storing them by the module in which they are defined. By passing the module name to :mod:`bpy.utils.register_module` blender can register all classes created by this module and its submodules.
---------------------------
Inter Classes Dependencies
---------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^
When customizing blender you may want to group your own settings together, after all, they will likely have to co-exist with other scripts. To group these properties classes need to be defined, for groups within groups or collections within groups you can find yourself having to deal with order of registration/unregistration.
@@ -315,9 +306,8 @@ Say you want to store material settings for a custom engine.
*The lower most class needs to be registered first and that unregister() is a mirror of register()*
---------------------
Manipulating Classes
---------------------
+^^^^^^^^^^^^^^^^^^^^
Properties can be added and removed as blender runs, normally happens on register or unregister but for some special cases it may be useful to modify types as the script runs.
@@ -346,9 +336,8 @@ This works just as well for PropertyGroup subclasses you define yourself.
my_float = bpy.props.FloatProperty()
-----------------------------------
Dynamic Defined-Classes (Advanced)
-----------------------------------
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In some cases the specifier for data may not be in blender, renderman shader definitions for example and it may be useful to define types and remove them on the fly.
@@ -374,8 +363,6 @@ In some cases the specifier for data may not be in blender, renderman shader def
Calling these operators:
-.. code-block:: python
-
>>> bpy.ops.object.operator_1()
Hello World OBJECT_OT_operator_1
{'FINISHED'}
diff --git a/doc/python_api/rst/info_quickstart.rst b/doc/python_api/rst/info_quickstart.rst
index 06218e48a95..e77e9a76d7f 100644
--- a/doc/python_api/rst/info_quickstart.rst
+++ b/doc/python_api/rst/info_quickstart.rst
@@ -1,10 +1,9 @@
-#######################
+***********************
Quickstart Introduction
-#######################
+***********************
-*****
Intro
-*****
+=====
This API is generally stable but some areas are still being added and improved.
@@ -38,9 +37,8 @@ The Blender/Python API **can't** (yet)...
* Define callbacks or listeners to be notified when data is changed.
-***************
Before Starting
-***************
+===============
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.
@@ -60,25 +58,19 @@ A quick list of helpful things to know before starting:
* 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.
-************
Key Concepts
-************
+============
-===========
Data Access
-===========
+-----------
---------------------
Accessing datablocks
---------------------
+^^^^^^^^^^^^^^^^^^^^
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.
Accessing data from the currently loaded blend file is done with the module :mod:`bpy.data`. This gives access to library data. For example:
-
-.. code-block:: python
-
>>> bpy.data.objects
<bpy_collection[3], BlendDataObjects>
@@ -89,17 +81,13 @@ Accessing data from the currently loaded blend file is done with the module :mod
<bpy_collection[1], BlendDataMaterials>
------------------
About Collections
------------------
+^^^^^^^^^^^^^^^^^
You'll notice that an index as well as a string can be used to access members of the collection.
Unlike Python's dictionaries, both methods are acceptable; however, the index of a member may change while running Blender.
-
-.. code-block:: python
-
>>> list(bpy.data.objects)
[bpy.data.objects["Cube"], bpy.data.objects["Plane"]]
@@ -110,14 +98,11 @@ Unlike Python's dictionaries, both methods are acceptable; however, the index of
bpy.data.objects["Cube"]
---------------------
Accessing attributes
---------------------
+^^^^^^^^^^^^^^^^^^^^
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.
-.. code-block:: python
-
>>> bpy.data.objects[0].name
'Camera'
@@ -132,17 +117,14 @@ For testing what data to access it's useful to use the "Console", which is its o
Example of a data path that can be quickly found via the console:
-.. code-block:: python
-
>>> bpy.data.scenes[0].render.resolution_percentage
100
>>> bpy.data.scenes[0].objects["Torus"].data.vertices[0].co.x
1.0
------------------
Custom Properties
------------------
+^^^^^^^^^^^^^^^^^
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.
@@ -179,16 +161,13 @@ Note that these properties can only be assigned basic Python types.
These properties are valid outside of Python. They can be animated by curves or used in driver paths.
-=======
Context
-=======
+-------
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.
Common-use cases:
-.. code-block:: python
-
>>> bpy.context.object
>>> bpy.context.selected_objects
>>> bpy.context.visible_bones
@@ -205,16 +184,13 @@ The context attributes change depending on where it is accessed. The 3D view has
See :mod:`bpy.context` API reference
-=================
Operators (Tools)
-=================
+-----------------
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.
Examples:
-.. code-block:: python
-
>>> bpy.ops.mesh.flip_normals()
{'FINISHED'}
>>> bpy.ops.mesh.hide(unselected=False)
@@ -227,9 +203,8 @@ Examples:
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.
----------------
Operator Poll()
----------------
+^^^^^^^^^^^^^^^
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.
@@ -249,9 +224,8 @@ To avoid using try/except clauses wherever operators are called you can call the
bpy.ops.view3d.render_border()
-***********
Integration
-***********
+===========
Python scripts can integrate with Blender in the following ways:
@@ -266,9 +240,9 @@ Python scripts can integrate with Blender in the following ways:
In Python, this is done by defining a class, which is a subclass of an existing type.
-================
+
Example Operator
-================
+----------------
.. literalinclude:: ../../../release/scripts/templates/operator_simple.py
@@ -296,9 +270,8 @@ To run the script:
reference :class:`bpy.types.Operator`
-=============
Example Panel
-=============
+-------------
Panels register themselves as a class, like an operator. Notice the extra **bl_** variables used to set the context they display in.
@@ -332,17 +305,16 @@ Note the row distribution and the label and properties that are available throug
.. seealso:: :class:`bpy.types.Panel`
-*****
Types
-*****
+=====
Blender defines a number of Python types but also uses Python native types.
Blender's Python API can be split up into 3 categories.
-============
+
Native Types
-============
+------------
In simple cases returning a number or a string as a custom type would be cumbersome, so these are accessed as normal python types.
@@ -350,8 +322,6 @@ In simple cases returning a number or a string as a custom type would be cumbers
* blender enumerator -> string
- .. code-block:: python
-
>>> C.object.rotation_mode = 'AXIS_ANGLE'
@@ -366,9 +336,8 @@ In simple cases returning a number or a string as a custom type would be cumbers
self.report({'WARNING', 'INFO'}, "Some message!")
-==============
Internal Types
-==============
+--------------
Used for Blender datablocks and collections: :class:`bpy.types.bpy_struct`
@@ -376,8 +345,6 @@ For data that contains its own attributes groups/meshes/bones/scenes... etc.
There are 2 main types that wrap Blenders data, one for datablocks (known internally as bpy_struct), another for properties.
-.. code-block:: python
-
>>> bpy.context.object
bpy.data.objects['Cube']
@@ -386,9 +353,9 @@ There are 2 main types that wrap Blenders data, one for datablocks (known intern
Note that these types reference Blender's data so modifying them is immediately visible.
-===============
+
Mathutils Types
-===============
+---------------
Used for vectors, quaternion, eulers, matrix and color types, accessible from :mod:`mathutils`
@@ -422,9 +389,8 @@ Example of a matrix, vector multiplication:
location = bpy.context.object.location.copy()
-*********
Animation
-*********
+=========
There are 2 ways to add keyframes through Python.
@@ -455,9 +421,8 @@ Using Low-Level Functions:
fcu_z.keyframe_points[1].co = 20.0, 1.0
-*****************
Style Conventions
-*****************
+=================
For Blender 2.5 we have chosen to follow python suggested style guide to avoid mixing styles amongst our own scripts and make it easier to use python scripts from other projects.