move wiki api intro and overview docs into the api reference docs.
Updated docs since some parts still were from beta still.
This commit is contained in:
parent
5f66f37e22
commit
50a9454e0f
|
@ -0,0 +1,386 @@
|
|||
###################
|
||||
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.
|
||||
|
||||
This is a typical python environment so tutorials on how to write python scripts will work running the scripts in blender too. Blender provides the :mod:`bpy` module to the python interpreter. This module can be imported in a script and gives access to blender data, classes, and functions. Scripts that deal with blender data will need to import this module.
|
||||
|
||||
Here is a simple example of moving a vertex of the object named **Cube**:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import bpy
|
||||
bpy.data.objects["Cube"].data.vertices[0].co.x += 1.0
|
||||
|
||||
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.
|
||||
|
||||
Scripts that extend blender - define classes that exist beyond the scripts execution, this makes future access to these classes (to unregister for example) more difficult than importing as a module where class instance is kept in the module and can be accessed by importing that module later on.
|
||||
|
||||
For this reason it's preferable to only use directly execute scripts that don't extend blender by registering classes.
|
||||
|
||||
|
||||
Here are some ways to run scripts directly in blender.
|
||||
|
||||
* Loaded in the text editor and press **Run Script**.
|
||||
|
||||
* Typed or pasted into the interactive console.
|
||||
|
||||
* Execute a python file from the command line with blender, eg:
|
||||
|
||||
``blender --python /home/me/my_script.py``
|
||||
|
||||
|
||||
To run as modules:
|
||||
|
||||
* The obvious way, ``import some_module`` command from the text window or interactive console.
|
||||
|
||||
* Open as a text block and tick "Register" option, this will load with the blend file.
|
||||
|
||||
* copy into one of the directories ``scripts/startup``, where they will be automatically imported on startup.
|
||||
|
||||
* 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.
|
||||
|
||||
The only difference between addons and built-in python modules is that addons must contain a **bl_info** variable which blender uses to read metadata such as name, author, category and URL.
|
||||
|
||||
The user preferences addon listing uses **bl_info** to display information about each addon.
|
||||
|
||||
`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.
|
||||
|
||||
The blender python api allows integration for:
|
||||
|
||||
* :class:`bpy.types.Panel`
|
||||
|
||||
* :class:`bpy.types.Menu`
|
||||
|
||||
* :class:`bpy.types.Operator`
|
||||
|
||||
* :class:`bpy.types.PropertyGroup`
|
||||
|
||||
* :class:`bpy.types.KeyingSet`
|
||||
|
||||
* :class:`bpy.types.RenderEngine`
|
||||
|
||||
|
||||
This is intentionally limited. Currently, for more advanced features such as mesh modifiers, object types, or shader nodes, C/C++ must be used.
|
||||
|
||||
For python intergration Blender defines methods which are common to all types. This works by creating a python subclass of a Blender class which contains variables and functions specified by the parent class which are pre-defined to interface with Blender.
|
||||
|
||||
For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import bpy
|
||||
class SimpleOperator(bpy.types.Operator):
|
||||
bl_idname = "object.simple_operator"
|
||||
bl_label = "Tool Name"
|
||||
|
||||
def execute(self, context):
|
||||
print("Hello World")
|
||||
return {'FINISHED'}
|
||||
|
||||
bpy.utils.register_class(SimpleOperator)
|
||||
|
||||
First note that we subclass a member of :mod:`bpy.types`, this is common for all classes which can be integrated with blender and used so we know if this is an Operator and not a Panel when registering.
|
||||
|
||||
Both class properties start with a **bl_** prefix. This is a convention used to distinguish blender properties from those you add yourself.
|
||||
|
||||
Next see the execute function, which takes an instance of the operator and the current context. A common prefix is not used for functions.
|
||||
|
||||
Lastly the register function is called, this takes the class and loads it into blender. See `Class Registration`_.
|
||||
|
||||
Regarding inheritance, blender doesn't impose restrictions on the kinds of class inheritance used, the registration checks will use attributes and functions defined in parent classes.
|
||||
|
||||
class mix-in example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import bpy
|
||||
class BaseOperator:
|
||||
def execute(self, context):
|
||||
print("Hello World BaseClass")
|
||||
return {'FINISHED'}
|
||||
|
||||
class SimpleOperator(bpy.types.Operator, BaseOperator):
|
||||
bl_idname = "object.simple_operator"
|
||||
bl_label = "Tool Name"
|
||||
|
||||
bpy.utils.register_class(SimpleOperator)
|
||||
|
||||
Notice these classes don't define an ``__init__(self)`` function. While ``__init__()`` and ``__del__()`` will be called if defined, the class instances lifetime only spans the execution. So a panel for example will have a new instance for every redraw, for this reason there is rarely a cause to store variables in the panel instance. Instead, persistent variables should be stored in Blenders data so that the state can be restored when blender is restarted.
|
||||
|
||||
.. note:: Modal operators are an exception, keeping their instance variable as blender runs, see modal operator template.
|
||||
|
||||
So once the class is registered with blender, instancing the class and calling the functions is left up to blender. In fact you cannot instance these classes from the script as you would expect with most python API's.
|
||||
|
||||
To run operators you can call them through the operator api, eg:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import bpy
|
||||
bpy.ops.object.simple_operator()
|
||||
|
||||
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.
|
||||
|
||||
A simple blender/python module can look like this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import bpy
|
||||
|
||||
class SimpleOperator(bpy.types.Operator):
|
||||
""" See example above """
|
||||
|
||||
def register():
|
||||
bpy.utils.register_class(SimpleOperator)
|
||||
|
||||
def unregister():
|
||||
bpy.utils.unregister_class(SimpleOperator)
|
||||
|
||||
if __name__ == "__main__":
|
||||
register()
|
||||
|
||||
These functions usually appear at the bottom of the script containing class registration sometimes adding menu items. You can also use them for internal purposes setting up data for your own tools but take care since register won't re-run when a new blend file is loaded.
|
||||
|
||||
The register/unregister calls are used so it's possible to toggle addons and reload scripts while blender runs.
|
||||
If the register calls were placed in the body of the script, registration would be called on import, meaning there would be no distinction between importing a module or loading its classes into blender.
|
||||
|
||||
This becomes problematic when a script imports classes from another module making it difficult to manage which classes are being loaded and when.
|
||||
|
||||
The last 2 lines are only for testing:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
if __name__ == "__main__":
|
||||
register()
|
||||
|
||||
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.
|
||||
|
||||
Once this class is loaded you can access it from :mod:`bpy.types`, using the bl_idname rather than the classes original name.
|
||||
|
||||
When loading a class, blender performs sanity checks making sure all required properties and functions are found, that properties have the correct type, and that functions have the right number of arguments.
|
||||
|
||||
Mostly you will not need concern yourself with this but if there is a problem with the class definition it will be raised on registering:
|
||||
|
||||
Using the function arguments ``def execute(self, context, spam)``, will raise an exception:
|
||||
|
||||
``ValueError: expected Operator, SimpleOperator class "execute" function to have 2 args, found 3``
|
||||
|
||||
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.
|
||||
|
||||
For more convenient loading/unloading :mod:`bpy.utils.register_module` (module) and :mod:`bpy.utils.unregister_module` (module) functions exist.
|
||||
|
||||
A script which defines many of its own operators, panels menus etc. you only need to write:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def register():
|
||||
bpy.utils.register_module(__name__)
|
||||
|
||||
def unregister():
|
||||
bpy.utils.unregister_module(__name__)
|
||||
|
||||
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.
|
||||
|
||||
Custom properties groups are themselves classes which need to be registered.
|
||||
|
||||
Say you want to store material settings for a custom engine.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Create new property
|
||||
# bpy.data.materials[0].my_custom_props.my_float
|
||||
import bpy
|
||||
|
||||
class MyMaterialProps(bpy.types.PropertyGroup):
|
||||
my_float = bpy.props.FloatProperty()
|
||||
|
||||
def register():
|
||||
bpy.utils.register_class(MyMaterialProps)
|
||||
bpy.types.Material.my_custom_props = bpy.props.PointerProperty(type=MyMaterialProps)
|
||||
|
||||
def unregister():
|
||||
del bpy.types.Material.my_custom_props
|
||||
bpy.utils.unregister_class(MyMaterialProps)
|
||||
|
||||
if __name__ == "__main__":
|
||||
register()
|
||||
|
||||
.. note::
|
||||
|
||||
*The class must be registered before being used in a property, failing to do so will raise an error:*
|
||||
|
||||
``ValueError: bpy_struct "Material" registration error: my_custom_props could not register``
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# Create new property group with a sub property
|
||||
# bpy.data.materials[0].my_custom_props.sub_group.my_float
|
||||
import bpy
|
||||
|
||||
class MyMaterialSubProps(bpy.types.PropertyGroup):
|
||||
my_float = bpy.props.FloatProperty()
|
||||
|
||||
class MyMaterialGroupProps(bpy.types.PropertyGroup):
|
||||
sub_group = bpy.props.PointerProperty(type=MyMaterialSubProps)
|
||||
|
||||
def register():
|
||||
bpy.utils.register_class(MyMaterialSubProps)
|
||||
bpy.utils.register_class(MyMaterialGroupProps)
|
||||
bpy.types.Material.my_custom_props = bpy.props.PointerProperty(type=MyMaterialGroupProps)
|
||||
|
||||
def unregister():
|
||||
del bpy.types.Material.my_custom_props
|
||||
bpy.utils.unregister_class(MyMaterialGroupProps)
|
||||
bpy.utils.unregister_class(MyMaterialSubProps)
|
||||
|
||||
if __name__ == "__main__":
|
||||
register()
|
||||
|
||||
.. note::
|
||||
|
||||
*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.
|
||||
|
||||
For example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# add a new property to an existing type
|
||||
bpy.types.Object.my_float = bpy.props.FloatProperty()
|
||||
# remove
|
||||
del bpy.types.Object.my_float
|
||||
|
||||
This works just as well for PropertyGroup subclasses you define yourself.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPropGroup(bpy.types.PropertyGroup):
|
||||
pass
|
||||
MyPropGroup.my_float = bpy.props.FloatProperty()
|
||||
|
||||
...this is equivalent to:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class MyPropGroup(bpy.types.PropertyGroup):
|
||||
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.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
for i in range(10):
|
||||
idname = "object.operator_%d" % i
|
||||
|
||||
def func(self, context):
|
||||
print("Hello World", self.bl_idname)
|
||||
return {'FINISHED'}
|
||||
|
||||
opclass = type("DynOp%d" % i,
|
||||
(bpy.types.Operator, ),
|
||||
{"bl_idname": idname, "bl_label": "Test", "execute": func},
|
||||
)
|
||||
bpy.utils.register_class(opclass)
|
||||
|
||||
.. note::
|
||||
|
||||
Notice ``type()`` is called to define the class. This is an alternative syntax for class creation in python, better suited to constructing classes dynamically.
|
||||
|
||||
|
||||
Calling these operators:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> bpy.ops.object.operator_1()
|
||||
Hello World OBJECT_OT_operator_1
|
||||
{'FINISHED'}
|
||||
|
||||
>>> bpy.ops.object.operator_2()
|
||||
Hello World OBJECT_OT_operator_2
|
||||
{'FINISHED'}
|
||||
|
|
@ -0,0 +1,503 @@
|
|||
#######################
|
||||
Quickstart Introduction
|
||||
#######################
|
||||
|
||||
*****
|
||||
Intro
|
||||
*****
|
||||
|
||||
This API is generally stable but some areas are still being added and improved.
|
||||
|
||||
The Blender/Python API can do the following:
|
||||
|
||||
* Edit any data the user interface can (Scenes, Meshes, Particles etc.)
|
||||
|
||||
* Modify user preferences, keymaps and themes
|
||||
|
||||
* Run tools with own settings
|
||||
|
||||
* Create user interface elements such as menus, headers and panels
|
||||
|
||||
* Create new tools
|
||||
|
||||
* Create interactive tools
|
||||
|
||||
* Create new rendering engines that integrate with Blender
|
||||
|
||||
* Define new settings in existing Blender data
|
||||
|
||||
* Draw in the 3D view using OpenGL commands from Python
|
||||
|
||||
|
||||
The Blender/Python API **can't** (yet)...
|
||||
|
||||
* Create new space types.
|
||||
|
||||
* Assign custom properties to every type.
|
||||
|
||||
* 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.
|
||||
|
||||
|
||||
A quick list of helpful things to know before starting:
|
||||
|
||||
* Blender uses Python 3.x; some 3rd party extensions are not available yet.
|
||||
|
||||
* The interactive console in Blender 2.5 has been improved; testing one-liners in the console is a good way to learn.
|
||||
|
||||
* Button tool tips show Python attributes and operator names.
|
||||
|
||||
* Right clicking on buttons and menu items directly links to API documentation.
|
||||
|
||||
* For more examples, the text menu has a templates section where some example operators can be found.
|
||||
|
||||
* 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>
|
||||
|
||||
>>> bpy.data.scenes
|
||||
<bpy_collection[1], BlendDataScenes>
|
||||
|
||||
>>> bpy.data.materials
|
||||
<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"]]
|
||||
|
||||
>>> bpy.data.objects['Cube']
|
||||
bpy.data.objects["Cube"]
|
||||
|
||||
>>> bpy.data.objects[0]
|
||||
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'
|
||||
|
||||
>>> bpy.data.scenes["Scene"]
|
||||
bpy.data.scenes['Scene']
|
||||
|
||||
>>> bpy.data.materials.new("MyMaterial")
|
||||
bpy.data.materials['MyMaterial']
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
This data is saved with the blend file and copied with objects.
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bpy.context.object["MyOwnProperty"] = 42
|
||||
|
||||
if "SomeProp" in bpy.context.object:
|
||||
print("Property found")
|
||||
|
||||
# Use the get function like a python dictionary
|
||||
# which can have a fallback value.
|
||||
value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
|
||||
|
||||
# dictionaries can be assigned as long as they only use basic types.
|
||||
group = bpy.data.groups.new("MyTestGroup")
|
||||
group["GameSettings"] = {"foo": 10, "bar": "spam", "baz": {}}
|
||||
|
||||
del group["GameSettings"]
|
||||
|
||||
|
||||
Note that these properties can only be assigned basic Python types.
|
||||
|
||||
* int, float, string
|
||||
|
||||
* array of ints/floats
|
||||
|
||||
* dictionary (only string keys types on this list)
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
So ``bpy.context.object = obj`` will raise an error.
|
||||
|
||||
But ``bpy.context.scene.objects.active = obj`` will work as expected.
|
||||
|
||||
|
||||
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.
|
||||
|
||||
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)
|
||||
{'FINISHED'}
|
||||
>>> bpy.ops.object.scale_apply()
|
||||
{'FINISHED'}
|
||||
|
||||
.. note::
|
||||
|
||||
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.
|
||||
|
||||
For example, calling bpy.ops.view3d.render_border() from the console raises the following error:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
RuntimeError: Operator bpy.ops.view3d.render_border.poll() failed, context is incorrect
|
||||
|
||||
In this case the context must be the 3d view with an active camera.
|
||||
|
||||
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.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
if bpy.ops.view3d.render_border.poll():
|
||||
bpy.ops.view3d.render_border()
|
||||
|
||||
|
||||
***********
|
||||
Integration
|
||||
***********
|
||||
|
||||
Python scripts can integrate with Blender in the following ways:
|
||||
|
||||
* By defining a rendering engine.
|
||||
|
||||
* By defining operators.
|
||||
|
||||
* By defining menus, headers and panels.
|
||||
|
||||
* By inserting new buttons into existing menus, headers and panels
|
||||
|
||||
|
||||
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
|
||||
|
||||
Once this script runs, ``SimpleOperator`` is registered with Blender and can be called from the operator search popup or added to the toolbar.
|
||||
|
||||
To run the script:
|
||||
|
||||
#. Highlight the above code then press Ctrl+C to copy it.
|
||||
|
||||
#. Start Blender
|
||||
|
||||
#. Press Ctrl+Right twice to change to the Scripting layout.
|
||||
|
||||
#. Press Ctrl+V to paste the code into the text panel (the upper left frame).
|
||||
|
||||
#. Click on the button **Run Script**.
|
||||
|
||||
#. Move you're mouse into the 3D view, press spacebar for the operator search
|
||||
menu, and type "Simple".
|
||||
|
||||
#. Click on the "Simple Operator" item found in search.
|
||||
|
||||
|
||||
.. seealso:: The class members with the **bl_** prefix are documented in the API
|
||||
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.
|
||||
|
||||
.. literalinclude:: ../../../release/scripts/templates/ui_panel_simple.py
|
||||
|
||||
To run the script:
|
||||
|
||||
#. Highlight the above code then press Ctrl+C to copy it
|
||||
|
||||
#. Start Blender
|
||||
|
||||
#. Press Ctrl+Right twice to change to the Scripting layout
|
||||
|
||||
#. Press Ctrl+V to paste the code into the text panel (the upper left frame)
|
||||
|
||||
#. Click on the button **Run Script**.
|
||||
|
||||
|
||||
To view the results:
|
||||
|
||||
#. Select the the default cube.
|
||||
|
||||
#. Click on the Object properties icon in the buttons panel (far right; appears as a tiny cube).
|
||||
|
||||
#. Scroll down to see a panel named **Hello World Panel**.
|
||||
|
||||
#. Changing the object name also updates **Hello World Panel's** Name: field.
|
||||
|
||||
Note the row distribution and the label and properties that are available through the code.
|
||||
|
||||
.. 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.
|
||||
|
||||
* blender float/int/boolean -> float/int/boolean
|
||||
|
||||
* blender enumerator -> string
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> C.object.rotation_mode = 'AXIS_ANGLE'
|
||||
|
||||
|
||||
* blender enumerator (multiple) -> set of strings
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# setting multiple camera overlay guides
|
||||
bpy.context.scene.camera.data.show_guide = {'GOLDEN', 'CENTER'}
|
||||
|
||||
# passing as an operator argument for report types
|
||||
self.report({'WARNING', 'INFO'}, "Some message!")
|
||||
|
||||
|
||||
==============
|
||||
Internal Types
|
||||
==============
|
||||
|
||||
Used for Blender datablocks and collections: :class:`bpy.types.bpy_struct`
|
||||
|
||||
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']
|
||||
|
||||
>>> C.scene.objects
|
||||
bpy.data.scenes['Scene'].objects
|
||||
|
||||
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`
|
||||
|
||||
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.
|
||||
|
||||
Example of a matrix, vector multiplication:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bpy.context.object.matrix_world * bpy.context.object.data.verts[0].co
|
||||
|
||||
.. note::
|
||||
|
||||
mathutils types keep a reference to Blender's internal data so changes can
|
||||
be applied back.
|
||||
|
||||
|
||||
Example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
# modifies the Z axis in place.
|
||||
bpy.context.object.location.z += 2.0
|
||||
|
||||
# location variable holds a reference to the object too.
|
||||
location = bpy.context.object.location
|
||||
location *= 2.0
|
||||
|
||||
# Copying the value drops the reference so the value can be passed to
|
||||
# functions and modified without unwanted side effects.
|
||||
location = bpy.context.object.location.copy()
|
||||
|
||||
|
||||
*********
|
||||
Animation
|
||||
*********
|
||||
|
||||
There are 2 ways to add keyframes through Python.
|
||||
|
||||
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.
|
||||
|
||||
Both examples insert a keyframe on the active object's Z axis.
|
||||
|
||||
Simple example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
obj = bpy.context.object
|
||||
obj.location[2] = 0.0
|
||||
obj.keyframe_insert(data_path="location", frame=10.0, index=2)
|
||||
obj.location[2] = 1.0
|
||||
obj.keyframe_insert(data_path="location", frame=20.0, index=2)
|
||||
|
||||
Using Low-Level Functions:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
obj = bpy.context.object
|
||||
obj.animation_data_create()
|
||||
obj.animation_data.action = bpy.data.actions.new(name="MyAction")
|
||||
fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)
|
||||
fcu_z.keyframe_points.add(2)
|
||||
fcu_z.keyframe_points[0].co = 10.0, 0.0
|
||||
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.
|
||||
|
||||
Using our style guide for your own scripts makes it easier if you eventually want to contribute them to blender.
|
||||
|
||||
This style guide is known as pep8 and can be found `here <http://www.python.org/dev/peps/pep-0008>`_
|
||||
|
||||
A brief listing of pep8 criteria.
|
||||
|
||||
* camel caps for class names: MyClass
|
||||
|
||||
* all lower case underscore separated module names: my_module
|
||||
|
||||
* indentation of 4 spaces (no tabs)
|
||||
|
||||
* spaces around operators. ``1 + 1``, not ``1+1``
|
||||
|
||||
* only use explicit imports, (no importing '*')
|
||||
|
||||
* don't use single line: ``if val: body``, separate onto 2 lines instead.
|
||||
|
||||
|
||||
As well as pep8 we have other conventions used for blender python scripts.
|
||||
|
||||
* Use single quotes for enums, and double quotes for strings.
|
||||
|
||||
Both are of course strings but in our internal API enums are unique items from a limited set. eg.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
bpy.context.scene.render.file_format = 'PNG'
|
||||
bpy.context.scene.render.filepath = "//render_out"
|
||||
|
||||
* pep8 also defines that lines should not exceed 79 characters, we felt this is too restrictive so this is optional per script.
|
||||
|
||||
Periodically we run checks for pep8 compliance on blender scripts, for scripts to be included in this check add this line as a comment at the top of the script.
|
||||
|
||||
``# <pep8 compliant>``
|
||||
|
||||
To enable line length checks use this instead.
|
||||
|
||||
``# <pep8-80 compliant>``
|
||||
|
|
@ -60,11 +60,13 @@ if __import__("sys").modules.get("bpy") is None:
|
|||
# Switch for quick testing
|
||||
if 1:
|
||||
# full build
|
||||
EXCLUDE_INFO_DOCS = False
|
||||
EXCLUDE_MODULES = ()
|
||||
FILTER_BPY_TYPES = None
|
||||
FILTER_BPY_OPS = None
|
||||
|
||||
else:
|
||||
EXCLUDE_INFO_DOCS = False
|
||||
# for testing so doc-builds dont take so long.
|
||||
EXCLUDE_MODULES = (
|
||||
"bpy.context",
|
||||
|
@ -74,7 +76,7 @@ else:
|
|||
"bpy.props",
|
||||
"bpy.utils",
|
||||
"bpy.context",
|
||||
#"bpy.types", # supports filtering
|
||||
"bpy.types", # supports filtering
|
||||
"bpy.ops", # supports filtering
|
||||
"bpy_extras",
|
||||
"bge",
|
||||
|
@ -96,6 +98,12 @@ sphinx-build doc/python_api/sphinx-in doc/python_api/sphinx-out
|
|||
|
||||
"""
|
||||
|
||||
# extra info, not api reference docs
|
||||
# stored in ./rst/info/
|
||||
INFO_DOCS = (
|
||||
("info_quickstart.rst", "Blender/Python Quickstart: new to blender/scripting and want to get you're feet wet?"),
|
||||
("info_overview.rst", "Blender/Python API Overview: a more complete explanation of python integration"),
|
||||
)
|
||||
|
||||
# import rpdb2; rpdb2.start_embedded_debugger('test')
|
||||
|
||||
|
@ -1001,14 +1009,17 @@ def rna2sphinx(BASEPATH):
|
|||
|
||||
fw("\n")
|
||||
|
||||
fw("============================\n")
|
||||
fw("Blender/Python Documentation\n")
|
||||
fw("============================\n")
|
||||
fw("\n")
|
||||
fw("\n")
|
||||
fw("* `Quickstart Intro <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Intro>`_ if you are new to scripting in blender and want to get you're feet wet!\n")
|
||||
fw("* `Blender/Python Overview <http://wiki.blender.org/index.php/Dev:2.5/Py/API/Overview>`_ for a more complete explanation of python integration in blender\n")
|
||||
fw("\n")
|
||||
if not EXCLUDE_INFO_DOCS:
|
||||
fw("============================\n")
|
||||
fw("Blender/Python Documentation\n")
|
||||
fw("============================\n")
|
||||
fw("\n")
|
||||
fw("\n")
|
||||
fw(".. toctree::\n")
|
||||
fw(" :maxdepth: 1\n\n")
|
||||
for info, info_desc in INFO_DOCS:
|
||||
fw(" %s <%s>\n\n" % (info_desc, info))
|
||||
fw("\n")
|
||||
|
||||
fw("===================\n")
|
||||
fw("Application Modules\n")
|
||||
|
@ -1210,6 +1221,11 @@ def rna2sphinx(BASEPATH):
|
|||
|
||||
shutil.copy2(os.path.join(BASEPATH, "..", "rst", "change_log.rst"), BASEPATH)
|
||||
|
||||
|
||||
if not EXCLUDE_INFO_DOCS:
|
||||
for info, info_desc in INFO_DOCS:
|
||||
shutil.copy2(os.path.join(BASEPATH, "..", "rst", info), BASEPATH)
|
||||
|
||||
if 0:
|
||||
filepath = os.path.join(BASEPATH, "bpy.rst")
|
||||
file = open(filepath, "w")
|
||||
|
|
|
@ -3,11 +3,21 @@
|
|||
# bash source/blender/python/doc/sphinx_doc_gen.sh
|
||||
# ssh upload means you need an account on the server
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Upload vars
|
||||
|
||||
# disable for testing
|
||||
DO_UPLOAD=true
|
||||
|
||||
BLENDER="./blender.bin"
|
||||
SSH_USER="ideasman42"
|
||||
SSH_HOST=$SSH_USER"@emo.blender.org"
|
||||
SSH_UPLOAD="/data/www/vhosts/www.blender.org/documentation" # blender_python_api_VERSION, added after
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Blender Version & Info
|
||||
|
||||
# 'Blender 2.53 (sub 1) Build' --> '2_53_1' as a shell script.
|
||||
# "_".join(str(v) for v in bpy.app.version)
|
||||
# custom blender vars
|
||||
|
@ -28,28 +38,52 @@ SSH_UPLOAD_FULL=$SSH_UPLOAD/"blender_python_api_"$BLENDER_VERSION
|
|||
|
||||
SPHINXBASE=doc/python_api/
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Generate reStructuredText (blender/python only)
|
||||
|
||||
# dont delete existing docs, now partial updates are used for quick builds.
|
||||
$BLENDER --background --factory-startup --python $SPHINXBASE/sphinx_doc_gen.py
|
||||
|
||||
# html
|
||||
sphinx-build $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
|
||||
|
||||
cp $SPHINXBASE/sphinx-out/contents.html $SPHINXBASE/sphinx-out/index.html
|
||||
ssh $SSH_USER@emo.blender.org 'rm -rf '$SSH_UPLOAD_FULL'/*'
|
||||
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/* $SSH_HOST:$SSH_UPLOAD_FULL/
|
||||
# ----------------------------------------------------------------------------
|
||||
# Generate HTML (sphinx)
|
||||
|
||||
## symlink the dir to a static URL
|
||||
#ssh $SSH_USER@emo.blender.org 'rm '$SSH_UPLOAD'/250PythonDoc && ln -s '$SSH_UPLOAD_FULL' '$SSH_UPLOAD'/250PythonDoc'
|
||||
sphinx-build -n -b html $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
|
||||
|
||||
# better redirect
|
||||
ssh $SSH_USER@emo.blender.org 'echo "<html><head><title>Redirecting...</title><meta http-equiv=\"REFRESH\" content=\"0;url=../blender_python_api_'$BLENDER_VERSION'/\"></head><body>Redirecting...</body></html>" > '$SSH_UPLOAD'/250PythonDoc/index.html'
|
||||
|
||||
# pdf
|
||||
sphinx-build -b latex $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
|
||||
cd $SPHINXBASE/sphinx-out
|
||||
make
|
||||
cd -
|
||||
# ----------------------------------------------------------------------------
|
||||
# Generate PDF (sphinx/laytex)
|
||||
|
||||
# rename so local PDF has matching name.
|
||||
sphinx-build -n -b latex $SPHINXBASE/sphinx-in $SPHINXBASE/sphinx-out
|
||||
make -C $SPHINXBASE/sphinx-out
|
||||
mv $SPHINXBASE/sphinx-out/contents.pdf $SPHINXBASE/sphinx-out/blender_python_reference_$BLENDER_VERSION.pdf
|
||||
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/blender_python_reference_$BLENDER_VERSION.pdf $SSH_HOST:$SSH_UPLOAD_FULL/blender_python_reference_$BLENDER_VERSION.pdf
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Upload to blender servers, comment this section for testing
|
||||
|
||||
if $DO_UPLOAD ; then
|
||||
|
||||
cp $SPHINXBASE/sphinx-out/contents.html $SPHINXBASE/sphinx-out/index.html
|
||||
ssh $SSH_USER@emo.blender.org 'rm -rf '$SSH_UPLOAD_FULL'/*'
|
||||
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/* $SSH_HOST:$SSH_UPLOAD_FULL/
|
||||
|
||||
## symlink the dir to a static URL
|
||||
#ssh $SSH_USER@emo.blender.org 'rm '$SSH_UPLOAD'/250PythonDoc && ln -s '$SSH_UPLOAD_FULL' '$SSH_UPLOAD'/250PythonDoc'
|
||||
|
||||
# better redirect
|
||||
ssh $SSH_USER@emo.blender.org 'echo "<html><head><title>Redirecting...</title><meta http-equiv=\"REFRESH\" content=\"0;url=../blender_python_api_'$BLENDER_VERSION'/\"></head><body>Redirecting...</body></html>" > '$SSH_UPLOAD'/250PythonDoc/index.html'
|
||||
|
||||
# rename so local PDF has matching name.
|
||||
rsync --progress -avze "ssh -p 22" $SPHINXBASE/sphinx-out/blender_python_reference_$BLENDER_VERSION.pdf $SSH_HOST:$SSH_UPLOAD_FULL/blender_python_reference_$BLENDER_VERSION.pdf
|
||||
|
||||
fi
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# Print some useful text
|
||||
|
||||
echo ""
|
||||
echo "Finished! view the docs from: "
|
||||
echo " html:" $SPHINXBASE/sphinx-out/contents.html
|
||||
echo " pdf:" $SPHINXBASE/sphinx-out/blender_python_reference_$BLENDER_VERSION.pdf
|
Loading…
Reference in New Issue