Filling in branch from trunk

This commit is contained in:
Martin Poirier
2007-11-06 22:29:20 +00:00
commit 0de103c1cd
3166 changed files with 1082581 additions and 0 deletions

View File

@@ -0,0 +1,247 @@
# This is not a real module, it's simply an introductory text.
"""
The Blender Python API Reference
================================
An asterisk (*) means the module has been updated.
for a full list of changes since 2.42 see U{http://mediawiki.blender.org/index.php/Release_Notes/Notes243/Python_API}
Top Module:
-----------
- L{Blender}
- L{bpy<Bpy>} (experimental)
Submodules:
-----------
- L{Armature} (*)
- L{NLA}
- L{Action<NLA.Action>}
- L{BezTriple} (*)
- L{BGL}
- L{Camera} (*)
- L{Curve} (*)
- L{Draw} (*)
- L{Effect}
- L{Geometry} (*)
- L{Group} (*)
- L{Image} (*)
- L{Ipo} (*)
- L{IpoCurve} (*)
- L{Key} (*)
- L{Lamp}
- L{Lattice} (*)
- L{Library} (*)
- L{Material} (*)
- L{Mathutils} (*)
- L{Mesh} (*)
- L{MeshPrimitives} (*)
- L{Metaball} (*)
- L{NMesh} (deprecated)
- L{Noise}
- L{Object} (*)
- L{Modifier} (*)
- L{Pose} (*)
- L{Constraint} (*)
- L{ActionStrips<NLA>} (*)
- L{Registry}
- L{Scene} (*)
- L{Radio}
- L{Render} (*)
- L{Sound} (*)
- L{Text}
- L{Text3d}
- L{Font}
- L{Texture} (*)
- L{TimeLine}
- L{Types}
- L{Window}
- L{Theme} (*)
- L{World}
- L{sys<Sys>}
Additional information:
-----------------------
- L{Special features<API_related>}:
- scripts: registering in menus, documenting, configuring (new);
- command line examples (new);
- script links (*), space handler script links, Group module (new).
Introduction:
=============
This reference documents the Blender Python API, a growing collection of
Python modules (libraries) that give access to part of the program's internal
data and functions.
Through scripting Blender can be extended in real-time via
U{Python <www.python.org>}, an impressive high level, multi-paradigm, open
source language. Newcomers are recommended to start with the tutorial that
comes with it.
This opens many interesting possibilities, ranging from automating repetitive
tasks to adding new functionality to the program: procedural models,
importers and exporters, even complex applications and so on. Blender itself
comes with some scripts, but many others can be found in the Scripts & Plugins
sections and forum posts at the Blender-related sites listed below.
Scripting and Blender:
======================
These are the basic ways to execute scripts in Blender:
1. They can be loaded or typed as text files in the Text Editor window, then
executed with ALT+P.
2. Via command line: C{blender -P <scriptname>} will start Blender and execute
the given script. <scriptname> can be a filename in the user's file system or
the name of a text saved in a .blend Blender file:
'blender myfile.blend -P textname'.
3. Via command line in I{background mode}: use the '-b' flag (the order is
important): C{blender -b <blendfile> -P <scriptname>}. <blendfile> can be any
.blend file, including the default .B.blend that is in Blender's home directory
L{Blender.Get}('homedir'). In this mode no window will be opened and the
program will leave as soon as the script finishes execution.
4. Properly registered scripts can be selected directly from the program's
menus.
5. Scriptlinks: these are also loaded or typed in the Text Editor window and
can be linked to objects, materials or scenes using the Scriptlink buttons
tab. Script links get executed automatically when their events (ONLOAD,
REDRAW, FRAMECHANGED) are triggered. Normal scripts can create (L{Text}) and
link other scripts to objects and events, see L{Object.Object.addScriptLink},
for example.
6. A script can call another script (that will run in its own context, with
its own global dictionary) with the L{Blender.Run} module function.
Interaction with users:
-----------------------
Scripts can:
- simply run and exit;
- pop messages, menus and small number and text input boxes;
- draw graphical user interfaces (GUIs) with OpenGL calls and native
program buttons, which stay there accepting user input like any other
Blender window until the user closes them;
- attach themselves to a space's event or drawing code (aka space handlers,
L{check here<API_related>});
- make changes to the 3D View (set visible layer(s), view point, etc);
- grab the main input event queue and process (or pass to Blender) selected
keyboard, mouse, redraw events -- not considered good practice, but still
available for private use;
- tell Blender to execute other scripts (see L{Blender.Run}());
- use external Python libraries, if available.
You can read the documentation for the L{Window}, L{Draw} and L{BGL} modules
for more information and also check the Python site for external modules that
might be useful to you. Note though that any imported module will become a
requirement of your script, since Blender itself does not bundle external
modules.
Command line mode:
------------------
Python was embedded in Blender, so to access BPython modules you need to
run scripts from the program itself: you can't import the Blender module
into an external Python interpreter.
On the other hand, for many tasks it's possible to control Blender via
some automated process using scripts. Interested readers should learn about
features like "OnLoad" script links, the "-b <blendfile>" (background mode)
and "-P <script>" (run script) command line options and API calls like
L{Blender.Save}, L{Blender.Load}, L{Blender.Quit} and the L{Library} and
L{Render} modules.
Note that command line scripts are run before Blender initializes its windows
(and in '-b' mode no window will be initialized), so many functions that get
or set window related attributes (like most in L{Window}) don't work here. If
you need those, use an ONLOAD script link (see L{Scene.Scene.addScriptLink})
instead -- it's also possible to use a command line script to write or set an
ONLOAD script link. Check the L{Blender.mode} module var to know if Blender
is being executed in "background" or "interactive" mode.
L{Click here for command line and background mode examples<API_related>}.
Demo mode:
----------
Blender has a demo mode, where once started it can work without user
intervention, "showing itself off". Demos can render stills and animations,
play rendered or real-time animations, calculate radiosity simulations and
do many other nifty things. If you want to turn a .blend file into a demo,
write a script to run the show and link it as a scene "OnLoad" scriptlink.
The demo will then be played automatically whenever this .blend file is
opened, B{unless Blender was started with the "-y" parameter}.
The Game Engine API:
--------------------
Blender has a game engine for users to create and play 3d games. This
engine lets programmers add scripts to improve game AI, control, etc, making
more complex interaction and tricks possible. The game engine API is
separate from the Blender Python API this document references and you can
find its own ref doc in the doc section of the main sites below.
Blender Data Structures:
------------------------
Programs manipulate data structures. Blender python scripts are no exception.
Blender uses an Object Oriented architecture. The BPython interface tries to
present Blender objects and their attributes in the same way you see them
through the User Interface (the GUI). One key to BPython programming is
understanding the information presented in Blender's OOPS window where Blender
objects and their relationships are displayed.
Each Blender graphic element (Mesh, Lamp, Curve, etc.) is composed from two
parts: an Object and ObData. The Object holds information about the position,
rotation and size of the element. This is information that all elements have
in common. The ObData holds information specific to that particular type of
element.
Each Object has a link to its associated ObData. A single ObData may be
shared by many Objects. A graphic element also has a link to a list of
Materials. By default, this list is associated with the ObData.
All Blender objects have a unique name. However, the name is qualified by the
type of the object. This means you can have a Lamp Object called Lamp.001
(OB:Lamp.001) and a Lamp ObData called Lamp.001 (LA:Lamp.001).
For a more in-depth look at Blender internals, and some understanding of why
Blender works the way it does, see the U{Blender Architecture document
<http://www.blender3d.org/cms/Blender_Architecture.336.0.html>}.
A note to newbie script writers:
--------------------------------
Interpreted languages are known to be much slower than compiled code, but for
many applications the difference is negligible or acceptable. Also, with
profiling (or even simple direct timing with L{Blender.sys.time<Sys.time>}) to
identify slow areas and well thought optimizations, the speed can be
I{considerably} improved in many cases. Try some of the best BPython scripts
to get an idea of what can be done, you may be surprised.
@author: The Blender Python Team
@requires: Blender 2.43 or newer.
@version: 2.43
@see: U{www.blender3d.org<http://www.blender3d.org>}: main site
@see: U{www.blender.org<http://www.blender.org>}: documentation and forum
@see: U{blenderartists.org<http://blenderartists.org>}: user forum
@see: U{projects.blender.org<http://projects.blender.org>}
@see: U{blender architecture<http://www.blender3d.org/cms/Blender_Architecture.336.0.html>}: blender architecture document
@see: U{www.python.org<http://www.python.org>}
@see: U{www.python.org/doc<http://www.python.org/doc>}
@see: U{Blending into Python<en.wikibooks.org/wiki/Blender_3D:_Blending_Into_Python>}: User contributed documentation, featuring a blender/python cookbook with many examples.
@note: the official version of this reference guide is only updated for each
new Blender release. But you can build the current CVS
version yourself: install epydoc, grab all files in the
source/blender/python/api2_2x/doc/ folder of Blender's CVS and use the
epy_docgen.sh script also found there to generate the html docs.
Naturally you will also need a recent Blender binary to try the new
features. If you prefer not to compile it yourself, there is a testing
builds forum at U{blender.org<http://www.blender.org>}.
"""

View File

@@ -0,0 +1,564 @@
# This is not a real module, it's simply an introductory text.
"""
Blender Python related features
===============================
L{Back to Main Page<API_intro>}
Introduction:
=============
This page describes special features available to BPython scripts:
- Command line mode is accessible with the '-P' and '-b' Blender options.
- Registration allows scripts to become available from some pre-defined menus
in Blender, like Import, Export, Wizards and so on.
- Script links are Blender Texts (scripts) executed when a particular event
(redraws, .blend file loading, saving, frame changed, etc.) occurs. Now
there are also "Space Handlers" to draw onto or get events from a given
space (only 3D View now) in some window.
- Proper documentation data is used by the 'Scripts Help Browser' script to
show help information for any registered script. Your own GUI can use
this facility with the L{Blender.ShowHelp} function.
- Configuration is for data in your script that can be tweaked according to
user taste or needs. Like documentation, this is another helper
functionality -- you don't need to provide a GUI yourself to edit config
data.
Command line usage:
===================
Specifying scripts:
-------------------
The '-P' option followed either by:
- a script filename (full pathname if not in the same folder where you run
the command);
- the name of a Text in a .blend file (that must also be specified)
will open Blender and immediately run the given script.
Example::
# open Blender and execute the given script:
blender -P script.py
Passing parameters:
-------------------
To pass parameters to the script you can:
- write them to a file before running Blender, then make your script parse that file;
- set environment variables and access them with the 'os' module:
Examples with parameters being passed to the script via command line::
# execute a command like:
myvar=value blender -P script.py
# and in script.py access myvar with os.getenv
# (os.environ and os.setenv are also useful):
# script.py:
import os
val = os.getenv('myvar')
# To pass multiple parameters, simply write them in sequence,
# separated by spaces:
myvar1=value1 myvar2=value2 mystr="some string data" blender -P script.py
Background mode:
----------------
In '-b' mode no windows will be opened: the program will run as a command
line tool able to render stills and animations and execute any working Python
script with complete access to loaded .blend's file contents. Once the task
is completed, the program will exit.
Background mode examples::
# Open Blender in background mode with file 'myfile.blend'
# and run the script 'script.py':
blender -b myfile.blend -P script.py
# Note: a .blend file is always required. 'script.py' can be a file
# in the file system or a Blender Text stored in 'myfile.blend'.
# Let's assume 'script.py' has code to render the current frame;
# this line will set the [s]tart and [e]nd (and so the current) frame to
# frame 44 and call the script:
blender -b myfile.blend -s 44 -e 44 -P script.py
# Using now a script written to render animations, we set different
# start and end frames and then execute this line:
blender -b myfile.blend -s 1 -e 10 -P script.py
# Note: we can also set frames and define if we want a single image or
# an animation in the script body itself, naturally.
The rendered pictures will be written to the default render folder, that can
also be set via BPython (take a look at L{Render.RenderData}). Their
names will be the equivalent frame number followed by the extension of the
chosen image type: 0001.png, for example. To rename them to something else,
coders can use the C{rename} function in the standard 'os' Python module.
Reminder: if you just need to render, it's not necessary to have a script.
Blender can create stills and animations with its own command line arguments.
Example:
- a single image at frame 44: blender -b myfile.blend -f 44
- an animation from frame 1 to 10: blender -b myfile.blend -s 1 -e 10 -a
Script links:
=============
Object script links:
--------------------
Users can link Blender Text scripts and objects to have the script
code executed when specific events occur to the objects. For example, if a
Camera has an script link set to "FrameChanged", the script will be executed
whenever the current frame is changed. Links can either be manually added by
users on the Buttons window -> Scripts tab or created by another script (see,
for example, L{Object.addScriptLink<Object.Object.addScriptLink>}).
These are the types which can be linked to scripts:
- Camera Data;
- Lamp Data;
- Materials;
- Objects;
- Scenes;
- Worlds.
And these are the available event choices:
- Redraw;
- FrameChanged;
- Render;
- OnLoad (*);
- OnSave (*).
(*) only available for scenes
There are three L{Blender} module variables that script link authors should
be aware of:
- B{bylink}: True if the script is running as a script link;
- B{link}: the object the running script was linked to (None if this is
not a script link);
- B{event}: the event type, if the running script is being executed as a
script link.
Example::
#script link
import Blender
if Blender.bylink: # we're running as a script link
print "Event: %s for %s" % (Blender.event, Blender.link)
B{Important note about "Render" events}:
Each "Render" script link is executed twice: before rendering and after, for
reverting changes and for possible clean up actions. Before rendering,
'Blender.event' will be "Render" and after rendering it will be "PostRender".
Example::
# render script link
import Blender
event = Blender.event
if event == "Render":
# prepare for rendering
create_my_very_detailed_mesh_data()
elif event == "PostRender":
# done rendering, clean up
delete_my_very_detailed_mesh_data()
As suggested by the example above, this is especially useful for script links
that need to generate data only useful while rendering, or in case they need
to switch between two mesh data objects, one meant for realtime display and
the other, more detailed, for renders.
Space Handler script links:
---------------------------
This is a new kind of script linked to spaces in a given window. Right now
only the 3D View has the necessary hooks, but the plan is to add access to
other types, too. Just to clarify naming conventions: in Blender, a screen
is partitioned in windows (also called areas) and each window can show any
space. Spaces are: 3D View, Text Editor, Scripts, Buttons, User Preferences,
Oops, etc.
Space handlers are texts in the Text Editor, like other script links, but they
need to have a special header to be recognized -- B{I{the first line in the
text file}} must inform:
1. that they are space handlers;
2. the space they belong to;
3. whether they are EVENT or DRAW handlers.
Example header for a 3D View EVENT handler::
# SPACEHANDLER.VIEW3D.EVENT
Example header for a 3D View DRAW handler::
# SPACEHANDLER.VIEW3D.DRAW
Available space handlers can be toggled "on" or "off" in the space header's
B{View->Space Handler Scripts} submenu, by the user.
EVENT space handler scripts are called by that space's event handling callback
in Blender. The script receives the event B{before} it is further processed
by the program. An EVENT handler script should check Blender.event (compare
it against L{Draw} events) and either:
- process it (the script must set Blender.event to None then);
- ignore it.
Setting C{Blender.event = None} tells Blender not to go on processing itself
the event, because it was grabbed by the script.
Example::
# SPACEHANDLER.VIEW3D.EVENT
import Blender
from Blender import Draw
evt = Blender.event
return_it = False
if evt == Draw.LEFTMOUSE:
print "Swallowing the left mouse button press"
elif evt == Draw.AKEY:
print "Swallowing an 'a' character"
else:
print "Let the 3D View itself process this event:", evt
return_it = True
# if Blender should not process itself the passed event:
if not return_it: Blender.event = None
DRAW space handlers are called by that space's drawing callback in Blender.
The script is called B{after} the space has been drawn.
Two of the L{Blender} module variables related to script links assume
different roles for space handlers:
- B{bylink} is the same: True if the script is running as a script link;
- B{link}: integer from the L{Blender}.SpaceHandlers constant dictionary,
tells what space this handler belongs to and the handler's type
(EVENT, DRAW);
- B{event}:
- EVENT handlers: an input event (check keys and mouse events in L{Draw})
to be processed or ignored.
- DRAW handlers: 0 always.
B{Guidelines (important)}:
- EVENT handlers can access and change Blender objects just like any other
script, but they should not draw to the screen, B{use a DRAW handler to do
that}. Specifically: L{Draw.Image} and the L{BGL} drawing functions
should not be used inside an EVENT handler.
- DRAW handlers should leave the space in the same state it was before they
were executed. OpenGL attributes and the modelview and projection matrices
are automatically saved (pushed) before a DRAW handler runs and restored
(popped) after it finishes, no need to worry about that. Draw handlers
should not grab events;
- If script handlers need to pass information to each other (for example an
EVENT handler passing info to a DRAW handler), use the L{Registry} module.
- in short: use the event handler to deal with events and the draw handler to
draw and your script will be following the recommended practices for
Blender code.
Registering scripts:
====================
To be registered a script needs two things:
- to be either in the default scripts directory or in the user defined scripts
path (see User Preferences window -> File Paths tab -> Python path);
- to have a proper header.
Try 'blender -d' to know where your default directory for scripts is, it will
inform either the directory or the file with that info already parsed, which is
in the same directory of the scripts folder.
The header should be like this one (all double and single apostrophes below
are required)::
#!BPY
# \"\"\"
# Name: 'Script Name'
# Blender: 233
# Group: 'Export'
# Submenu: 'All' all
# Submenu: 'Selected' sel
# Submenu: 'Configure (gui)' gui
# Tooltip: 'Export to some format.'
# \"\"\"
where:
- B{Name} is the string that will appear in the menu;
- B{Blender} is the minimum program version required to run the script;
- B{Group} defines where the script will be put, see all groups in the
Scripts Window's header, menu "Scripts";
- B{Submenu} adds optional submenus for further control;
- B{Tooltip} is the (short) tooltip string for the menu entry.
note:
- all double and single apostrophes above are required;
- you can "comment out" the header above, by starting lines with
'#', like we did. This is not required (except for the first line, #!BPY,
of course), but this way the header won't conflict with Python tools that
you can use to generate documentation for your script code. Just
remember to keep this header above any other line with triple
double-quotes (\"\"\") in your script.
Submenu lines are not required, use them if you want to provide extra
options. To see which submenu the user chose, check the "__script__"
dictionary in your code: __script__['arg'] has the defined keyword (the word
after the submenu string name: all, sel or gui in the example above) of the
chosen submenu. For example, if the user clicked on submenu 'Selected' above,
__script__['arg'] will be "sel".
If your script requires extra data or configuration files, there is a special
folder where they can be saved: see 'datadir' in L{Blender.Get}.
Documenting scripts:
====================
The "Scripts Help Browser" script in the Help menu can parse special variables
from registered scripts and display help information for users. For that,
authors only need to add proper information to their scripts, after the
registration header.
The expected variables:
- __bpydoc__ (or __doc__) (type: string):
- The main help text. Write a first short paragraph explaining what the
script does, then add the rest of the help text, leaving a blank line
between each new paragraph. To force line breaks you can use <br> tags.
- __author__ (type: string or list of strings):
- Author name(s).
- __version__ (type: string):
- Script version. A good recommendation is using a version number followed
by the date in the format YYYY/MM/DD: "1.0 2005/12/31".
- __url__ (type: string or list of strings):
- Internet links that are shown as buttons in the help screen. Clicking
them opens the user's default browser at the specified location. The
expected format for each url entry is e.g.
"Author's site, http://www.somewhere.com". The first part, before the
comma (','), is used as the button's tooltip. There are two preset
options: "blender" and "elysiun", which link to the Python forums at
blender.org and elysiun.com, respectively.
- __email__ (optional, type: string or list of strings):
- Equivalent to __url__, but opens the user's default email client. You
can write the email as someone:somewhere*com and the help script will
substitute accordingly: someone@somewhere.com. This is only a minor help
to hide emails from spammers, since your script may be available at some
site. "scripts" is the available preset, with the email address of the
mailing list devoted to scripting in Blender, bf-scripts-dev@blender.org.
You should only use this one if you are subscribed to the list:
http://projects.blender.org/mailman/listinfo/bf-scripts-dev for more
information.
Example::
__author__ = 'Mr. Author'
__version__ = '1.0 2005/01/01'
__url__ = ["Author's site, http://somewhere.com",
"Support forum, http://somewhere.com/forum/", "blender", "elysiun"]
__email__ = ["Mr. Author, mrauthor:somewhere*com", "scripts"]
__bpydoc__ = \"\"\"\\
This script does this and that.
Explaining better, this script helps you create ...
You can write as many paragraphs as needed.
Shortcuts:<br>
Esc or Q: quit.<br>
etc.
Supported:<br>
Meshes, metaballs.
Known issues:<br>
This is just an example, there's no actual script.
Notes:<br>
You can check scripts bundled with Blender to see more examples of how to
add documentation to your own works.
\"\"\"
B{Note}: your own GUI or menu code can display documentation by calling the
help browser with the L{Blender.ShowHelp} function.
Configuring scripts:
====================
The L{Blender.Registry<Registry>} module provides a simplified way to keep
scripts configuration options in memory and also saved in config files.
And with the "Scripts Config Editor" script in the System menu users can later
view and edit the options easily.
Let's first clarify what we mean by config options: they are simple data
(bools, ints, floats, strings) used by programs to conform to user
preferences. The buttons in Blender's User Preferences window are a good
example.
For example, a particular exporter might include:
- SEPARATE_MATS = False: a bool variable (True / False) to determine if it
should write materials to a separate file;
- VERSION = 2: an int to define an specific version of the export format;
- TEX_DIR = "/path/to/textures": a default texture dir to prepend to all
exported texture filenames instead of their actual paths.
The script needs to provide users a GUI to configure these options -- or else
directly editing the source code would be the only way to change them. And to
store changes made to the GUI so they can be reloaded any time the script is
executed, programmers have to write and load their own config files (ideally at
L{Blender.Get}('udatadir') or, if not available, L{Blender.Get}('datadir')).
This section describes BPython facilities (based on the L{Registry} module and
the config editor) that can take care of this in a simplified (and much
recommended) way.
Here's how it works::
# sample_exporter.py
import Blender
from Blender import Registry
# First define all config variables with their default values:
SEPARATE_MATERIALS = True
VERSION = True
TEX_DIR = ''
EXPORT_DIR = ''
# Then define a function to update the Registry:
def registry_update():
# populate a dict with current config values:
d = {
'SEPARATE_MATERIALS': SEPARATE_MATERIALS,
'VERSION': VERSION,
'TEX_DIR': TEX_DIR,
'EXPORT_DIR': EXPORT_DIR
}
# store the key (optional 3rd arg tells if
# the data should also be written to a file):
Registry.SetKey('sample_exporter', d, True)
# (A good convention is to use the script name as Registry key)
# Now we check if our key is available in the Registry or file system:
regdict = Registry.GetKey('sample_exporter', True)
# If this key already exists, update config variables with its values:
if regdict:
try:
SEPARATE_MATERIALS = regdict['SEPARATE_MATERIALS']
VERSION = regdict['VERSION']
TEX_DIR = regdict['TEX_DIR']
EXPORT_DIR = regdict['EXPORT_DIR']
# if data was corrupted (or a new version of the script changed
# (expanded, removed, renamed) the config vars and users may have
# the old config file around):
except: update_registry() # rewrite it
else: # if the key doesn't exist yet, use our function to create it:
update_registry()
# ...
Hint: nicer code than the simplistic example above can be written by keeping
config var names in a list of strings and using the exec function.
B{Note}: if your script's GUI lets users change config vars, call the
registry_update() function in the button events callback to save the changes.
On the other hand, you don't need to handle configuration
in your own gui, it can be left for the 'Scripts Config Editor',
which should have access to your script's config key as soon as the
above code is executed once (as soon as SetKey is executed).
B{Note} (limits for config vars): strings longer than 300 characters are
clamped and the number of items in dictionaries, sequences and the config key
itself is limited to 60.
Scripts Configuration Editor:
-----------------------------
This script should be available from the System menu in the Scripts window.
It provides a GUI to view and edit saved configuration data, both from the
Registry dictionary in memory and the scripts config data dir. This is
useful for all scripts with config vars, but especially for those without GUIs,
like most importers and exporters, since this editor will provide one for them.
The example above already gives a good idea of how the information can be
prepared to be accessible from this editor, but there is more worth knowing:
1. String vars that end with '_dir' or '_file' (can be upper case, too) are
recognized as input boxes for dirs or files and a 'browse' button is added to
their right side, to call the file selector.
2. Both key names and configuration variables names starting with an
underscore ('_') are ignored by the editor. Programmers can use this feature
for any key or config var that is not meant to be configured by this editor.
3. The following information refers to extra config variables that may be
added specifically to aid the configuration editor script. To clarify, in the
example code above these variables (the string 'script' and the dictionaries
'tooltips' and 'limits') would appear along with SEPARATE_MATERIALS, VERSION,
TEX_DIR and EXPORT_DIR, wherever they are written.
Minor note: these names are case insensitive: tooltips, TOOLTIPS, etc. are all
recognized.
3.1 The config editor will try to display a 'help' button for a key, to show
documentation for the script that owns it. To find this "owner script", it
will first look for a config variable called 'script', a string containing
the name of the owner Python file (with or without '.py' extension)::
script = 'sample_exporter.py'
If there is no such variable, the editor will check if the file formed by the
key name and the '.py' extension exists. If both alternatives fail, no help
button will be displayed.
3.2 You can define tooltips for the buttons that the editor creates for your
config data (string input, toggle, number sliders). Simply create a dict
called 'tooltips', where config var names are keys and their tooltips,
values::
tooltips = {
'EXPORT_DIR': 'default folder where exported files should be saved',
'VERBOSE': 'print info and warning messages to the console',
'SEPARATE_MATERIALS': 'write materials to their own file'
}
3.3 Int and float button sliders need min and max limits. This can be passed
to the editor via a dict called 'limits' (ivar1, ivar2 and fvar are meant as
extra config vars that might have been in the example code above)::
limits = {'ivar1': [-10, 10], 'ivar2': [0, 100], 'fvar1': [-12.3, 15.4]}
4. The Config Editor itself maintains a Registry key called "General", with
general options relevant to many scripts, like "verbose" to tell if the user
wants messages printed to the console and "confirm overwrite", to know if
a script should ask for confirmation before overwriting files (all exporters
are recommended to access the General key and check this var -- L{sys.exists
<Sys.exists>} tells if files or folders already exist).
Hint: for actual examples, try the ac3d importer and exporter (it's enough to
call them from the menus then cancel with ESC), as those have been updated to
use this config system. After calling them their config data will be available
in the Config Editor. We also recommend adding a section about config vars
in your script's help info, as done in the ac3d ones.
L{Back to Main Page<API_intro>}
===============================
"""

View File

@@ -0,0 +1,368 @@
# Blender.Armature module and the Armature PyType object
"""
The Blender.Armature submodule.
Armature
========
This module provides access to B{Armature} objects in Blender. These are
"skeletons", used to deform and animate other objects -- meshes, for
example.
Example::
import Blender
from Blender import Armature
from Blender.Mathutils import *
#
arms = Armature.Get()
for arm in arms.values():
arm.drawType = Armature.STICK #set the draw type
arm.makeEditable() #enter editmode
#generating new editbone
eb = Armature.Editbone()
eb.roll = 10
eb.parent = arm.bones['Bone.003']
eb.head = Vector(1,1,1)
eb.tail = Vector(0,0,1)
eb.options = [Armature.HINGE, Armature.CONNECTED]
#add the bone
arm.bones['myNewBone'] = eb
#delete an old bone
del arm.bones['Bone.002']
arm.update() #save changes
for bone in arm.bones.values():
#print bone.matrix['ARMATURESPACE']
print bone.parent, bone.name
print bone.children, bone.name
print bone.options, bone.name
Example::
# Adds empties for every bone in the selected armature, an example of getting worldspace locations for bones.
from Blender import *
def test_arm():
scn= Scene.GetCurrent()
arm_ob= scn.objects.active
if not arm_ob or arm_ob.type != 'Armature':
Draw.PupMenu('not an armature object')
return
# Deselect all
for ob in scn.objects:
if ob != arm_ob:
ob.sel= 0
arm_mat= arm_ob.matrixWorld
arm_data= arm_ob.getData()
bones= arm_data.bones.values()
for bone in bones:
bone_mat= bone.matrix['ARMATURESPACE']
bone_mat_world= bone_mat*arm_mat
ob_empty= scn.objects.new('Empty')
ob_empty.setMatrix(bone_mat_world)
test_arm()
@var CONNECTED: Connect this bone to parent
@type CONNECTED: Constant
@var HINGE: Don't inherit rotation or scale from parent
@type HINGE: Constant
@var NO_DEFORM: If bone will not deform geometry
@type NO_DEFORM: Constant
@var MULTIPLY: Multiply bone with vertex group
@type MULTIPLY: Constant
@var HIDDEN_EDIT: Bone is hidden in editmode
@type HIDDEN_EDIT: Constant
@var ROOT_SELECTED: Root of the Bone is selected
@type ROOT_SELECTED: Constant
@var BONE_SELECTED: Bone is selected
@type BONE_SELECTED: Constant
@var TIP_SELECTED: Tip of the Bone is selected
@type TIP_SELECTED: Constant
@var OCTAHEDRON: Bones drawn as octahedrons
@type OCTAHEDRON: Constant
@var STICK: Bones drawn as a line
@type STICK: Constant
@var BBONE: Bones draw as a segmented B-spline
@type BBONE: Constant
@var ENVELOPE: Bones draw as a stick with envelope influence
@type ENVELOPE: Constant
"""
def Get (name = None):
"""
Get the Armature object(s) from Blender.
@type name: string, nothing, or list of strings
@param name: The string name of an armature.
@rtype: Blender Armature or a list of Blender Armatures
@return: It depends on the I{name} parameter:
- (name): The Armature object with the given I{name};
- (name, name, ...): A list of Armature objects
- (): A list with all Armature objects in the current scene.
@warning: In versions 2.42 and earlier, a string argument for an armature
that doesn't exist will return None. Later versions raise a Value error.
"""
def New (name = None):
"""
Return a new armature.
@type name: string or nothing
@param name: The string name of the new armature.
@rtype: Blender Armature.
@return: A new armature.
"""
class Armature:
"""
The Armature object
===================
This object gives access to Armature-specific data in Blender.
@ivar bones: A Dictionary of Bones (BonesDict) that make up this armature.
@type bones: BonesDict Object
@ivar vertexGroups: Whether vertex groups define deformation
@type vertexGroups: Bool
@ivar envelopes: Whether bone envelopes define deformation
@type envelopes: Bool
@ivar restPosition: Show rest position (no posing possible)
@type restPosition: Bool
@ivar delayDeform: Don't deform children when manipulating bones
@type delayDeform: Bool
@ivar drawAxes: Draw bone axes
@type drawAxes: Bool
@ivar drawNames: Draw bone names
@type drawNames: Bool
@ivar ghost: Draw ghosts around frame for current Action
@type ghost: Bool
@ivar ghostStep: Number of frames between ghosts
@type ghostStep: Int
@ivar drawType: The drawing type that is used to display the armature
Acceptable values are:
- Armature.OCTAHEDRON: bones drawn as octahedrons
- Armature.STICK: bones drawn as sticks
- Armature.BBONE: bones drawn as b-bones
- Armature.ENVELOPE: bones drawn as sticks with envelopes
@type drawType: Constant Object
@ivar mirrorEdit: X-axis mirrored editing
@type mirrorEdit: Bool
@ivar autoIK: Adds temporary IK chains while grabbing bones
@type autoIK: Bool
@ivar layerMask: Layer bitmask
Example::
# set armature to layers 14 and 16
armature.layerMask = (1<<13) + (1<<15)
@type layerMask: Int
"""
def __init__(name = 'myArmature'):
"""
Initializer for the Armature TypeObject.
Example::
myNewArmature = Blender.Armature.Armature('AR_1')
@param name: The name for the new armature
@type name: string
@return: New Armature Object
@rtype: Armature Object
"""
def makeEditable():
"""
Put the armature into EditMode for editing purposes. (Enters Editmode)
@warning: Using Window.Editmode() to switch the editmode manually will cause problems and possibly even crash Blender.
@warning: This is only needed for operations such as adding and removing bones.
@warning: Do access pose data until you have called update() or settings will be lost.
@warning: The armature should not be in manual editmode
prior to calling this method. The armature must be parented
to an object prior to editing.
@rtype: None
"""
def update():
"""
Save all changes and update the armature. (Leaves Editmode)
@note: Must have called makeEditable() first.
@rtype: None
"""
import id_generics
Armature.__doc__ += id_generics.attributes
class BonesDict:
"""
The BonesDict object
====================
This object gives gives dictionary like access to the bones in an armature.
It is internal to blender but is called as 'Armature.bones'
Removing a bone:
Example::
del myArmature.bones['bone_name']
Adding a bone:
Example::
myEditBone = Armature.Editbone()
myArmature.bones['bone_name'] = myEditBone
"""
def items():
"""
Return the key, value pairs in this dictionary
@rtype: string, BPy_bone
@return: All strings, and py_bones in the armature (in that order)
"""
def keys():
"""
Return the keys in this dictionary
@rtype: string
@return: All strings representing the bone names
"""
def values():
"""
Return the values in this dictionary
@rtype: BPy_bone
@return: All BPy_bones in this dictionary
"""
class Bone:
"""
The Bone object
===============
This object gives access to Bone-specific data in Blender. This object
cannot be instantiated but is returned by BonesDict when the armature is not in editmode.
@ivar name: The name of this Bone.
@type name: String
@ivar roll: This Bone's roll value.
Keys are:
- 'ARMATURESPACE' - this roll in relation to the armature
- 'BONESPACE' - the roll in relation to itself
@type roll: Dictionary
@ivar head: This Bone's "head" ending position when in rest state.
Keys are:
- 'ARMATURESPACE' - this head position in relation to the armature
- 'BONESPACE' - the head position in relation to itself.
@type head: Dictionary
@ivar tail: This Bone's "tail" ending position when in rest state.
Keys are:
- 'ARMATURESPACE' - this tail position in relation to the armature
- 'BONESPACE' - the tail position in relation to itself
@type tail: Dictionary
@ivar matrix: This Bone's matrix. This cannot be set.
Keys are:
- 'ARMATURESPACE' - this matrix of the bone in relation to the armature
- 'BONESPACE' - the matrix of the bone in relation to itself
@type matrix: Matrix Object
@ivar parent: The parent Bone.
@type parent: Bone Object
@ivar children: The children directly attached to this bone.
@type children: List of Bone Objects
@ivar weight: The bone's weight.
@type weight: Float
@ivar options: Various bone options which can be:
- Armature.CONNECTED: IK to parent
- Armature.HINGE: No parent rotation or scaling
- Armature.NO_DEFORM: The bone does not deform geometry
- Armature.MULTIPLY: Multiply vgroups by envelope
- Armature.HIDDEN_EDIT: Hide bones in editmode
- Armature.ROOT_SELECTED: Selection of root ball of bone
- Armature.BONE_SELECTED: Selection of bone
- Armature.TIP_SELECTED: Selection of tip ball of bone
@type options: List of Constants
@ivar subdivision: The number of bone subdivisions.
@type subdivision: Int
@ivar deformDist: The deform distance of the bone
@type deformDist: Float
@ivar length: The length of the bone. This cannot be set.
@type length: Float
@ivar headRadius: The radius of this bones head (used for envalope bones)
@type headRadius: Float
@ivar tailRadius: The radius of this bones head (used for envalope bones)
@type tailRadius: Float
@ivar layerMask: Layer bitmask
Example::
# set bone to layers 14 and 16
bone.layerMask = (1<<13) + (1<<15)
@type layerMask: Int
"""
def hasParent():
"""
Whether or not this bone has a parent
@rtype: Bool
"""
def hasChildren():
"""
Whether or not this bone has children
@rtype: Bool
"""
def getAllChildren():
"""
Gets all the children under this bone including the children's children.
@rtype: List of Bone object
@return: all bones under this one
"""
class Editbone:
"""
The Editbone Object
===================
This object is a wrapper for editbone data and is used only in the manipulation
of the armature in editmode.
@ivar name: The name of this Bone.
@type name: String
@ivar roll: This Bone's roll value (armaturespace).
@type roll: Float
@ivar head: This Bone's "head" ending position when in rest state (armaturespace).
@type head: Vector Object
@ivar tail: This Bone's "tail" ending position when in rest state (armaturespace).
@type tail: Vector Object
@ivar matrix: This Bone's matrix. (armaturespace)
@type matrix: Matrix Object
@ivar parent: The parent Bone.
@type parent: Editbone Object
@ivar weight: The bone's weight.
@type weight: Float
@ivar options: Various bone options which can be:
- Armature.CONNECTED: IK to parent
- Armature.HINGE: No parent rotation or scaling
- Armature.NO_DEFORM: The bone does not deform geometry
- Armature.MULTIPLY: Multiply vgroups by envelope
- Armature.HIDDEN_EDIT: Hide bones in editmode
- Armature.ROOT_SELECTED: Selection of root ball of bone
- Armature.BONE_SELECTED: Selection of bone
- Armature.TIP_SELECTED: Selection of tip ball of bone
@type options: List of Constants
@ivar subdivision: The number of bone subdivisions.
@type subdivision: Int
@ivar deformDist: The deform distance of the bone
@type deformDist: Float
@ivar length: The length of the bone. This cannot be set.
@type length: Float
@ivar headRadius: The radius of this bones head (used for envalope bones)
@type headRadius: Float
@ivar tailRadius: The radius of this bones head (used for envalope bones)
@type tailRadius: Float
"""
def hasParent():
"""
Whether or not this bone has a parent
@rtype: Bool
"""
def clearParent():
"""
Set the parent to None
@rtype: None
"""

View File

@@ -0,0 +1,1778 @@
# Blender.BGL module (OpenGL wrapper)
"""
The Blender.BGL submodule (the OpenGL wrapper).
B{New}: some GLU functions: L{gluLookAt}, etc.
The Blender.BGL submodule
=========================
This module wraps OpenGL constants and functions, making them available from
within Blender Python.
The complete list can be retrieved from the module itself, by listing its
contents: dir(Blender.BGL). A simple search on the net can point to more
than enough material to teach OpenGL programming, from books to many
collections of tutorials.
The "red book": "I{OpenGL Programming Guide: The Official Guide to Learning
OpenGL}" and the online NeHe tutorials are two of the best resources.
Example::
import Blender
from Blender.BGL import *
from Blender import Draw
R = G = B = 0
A = 1
title = "Testing BGL + Draw"
instructions = "Use mouse buttons or wheel to change the background color."
quitting = " Press ESC or q to quit."
len1 = Draw.GetStringWidth(title)
len2 = Draw.GetStringWidth(instructions + quitting)
#
def show_win():
glClearColor(R,G,B,A) # define color used to clear buffers
glClear(GL_COLOR_BUFFER_BIT) # use it to clear the color buffer
glColor3f(0.35,0.18,0.92) # define default color
glBegin(GL_POLYGON) # begin a vertex data list
glVertex2i(165, 158)
glVertex2i(252, 55)
glVertex2i(104, 128)
glEnd()
glColor3f(0.4,0.4,0.4) # change default color
glRecti(40, 96, 60+len1, 113)
glColor3f(1,1,1)
glRasterPos2i(50,100) # move cursor to x = 50, y = 100
Draw.Text(title) # draw this text there
glRasterPos2i(350,40) # move cursor again
Draw.Text(instructions + quitting) # draw another msg
glBegin(GL_LINE_LOOP) # begin a vertex-data list
glVertex2i(46,92)
glVertex2i(120,92)
glVertex2i(120,115)
glVertex2i(46,115)
glEnd() # close this list
#
def ev(evt, val): # event callback for Draw.Register()
global R,G,B,A # ... it handles input events
if evt == Draw.ESCKEY or evt == Draw.QKEY:
Draw.Exit() # this quits the script
elif not val: return
elif evt == Draw.LEFTMOUSE: R = 1 - R
elif evt == Draw.MIDDLEMOUSE: G = 1 - G
elif evt == Draw.RIGHTMOUSE: B = 1 - B
elif evt == Draw.WHEELUPMOUSE:
R += 0.1
if R > 1: R = 1
elif evt == Draw.WHEELDOWNMOUSE:
R -= 0.1
if R < 0: R = 0
else:
return # don't redraw if nothing changed
Draw.Redraw(1) # make changes visible.
#
Draw.Register(show_win, ev, None) # start the main loop
@note: you can use the L{Image} module and L{Image.Image} BPy object to load
and set textures. See L{Image.Image.glLoad} and L{Image.Image.glFree},
for example.
@see: U{www.opengl.org}
@see: U{nehe.gamedev.net}
"""
def glAccum(op, value):
"""
Operate on the accumulation buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/accum.html}
@type op: Enumerated constant
@param op: The accumulation buffer operation.
@type value: float
@param value: a value used in the accumulation buffer operation.
"""
def glAlphaFunc(func, ref):
"""
Specify the alpha test function
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/alphafunc.html}
@type func: Enumerated constant
@param func: Specifies the alpha comparison function.
@type ref: float
@param ref: The reference value that incoming alpha values are compared to.
Clamped between 0 and 1.
"""
def glAreTexturesResident(n, textures, residences):
"""
Determine if textures are loaded in texture memory
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/aretexturesresident.html}
@type n: int
@param n: Specifies the number of textures to be queried.
@type textures: Buffer object I{type GL_INT}
@param textures: Specifies an array containing the names of the textures to be queried
@type residences: Buffer object I{type GL_INT}(boolean)
@param residences: An array in which the texture residence status in returned.The residence status of a
texture named by an element of textures is returned in the corresponding element of residences.
"""
def glBegin(mode):
"""
Delimit the vertices of a primitive or a group of like primatives
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/begin.html}
@type mode: Enumerated constant
@param mode: Specifies the primitive that will be create from vertices between glBegin and
glEnd.
"""
def glBindTexture(target, texture):
"""
Bind a named texture to a texturing target
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/bindtexture.html}
@type target: Enumerated constant
@param target: Specifies the target to which the texture is bound.
@type texture: unsigned int
@param texture: Specifies the name of a texture.
"""
def glBitmap(width, height, xorig, yorig, xmove, ymove, bitmap):
"""
Draw a bitmap
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/bitmap.html}
@type width, height: int
@param width, height: Specify the pixel width and height of the bitmap image.
@type xorig,yorig: float
@param xorig,yorig: Specify the location of the origin in the bitmap image. The origin is measured
from the lower left corner of the bitmap, with right and up being the positive axes.
@type xmove,ymove: float
@param xmove,ymove: Specify the x and y offsets to be added to the current raster position after
the bitmap is drawn.
@type bitmap: Buffer object I{type GL_BYTE}
@param bitmap: Specifies the address of the bitmap image.
"""
def glBlendFunc(sfactor, dfactor):
"""
Specify pixel arithmetic
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/blendfunc.html}
@type sfactor: Enumerated constant
@param sfactor: Specifies how the red, green, blue, and alpha source blending factors are
computed.
@type dfactor: Enumerated constant
@param dfactor: Specifies how the red, green, blue, and alpha destination blending factors are
computed.
"""
def glCallList(list):
"""
Execute a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/calllist.html}
@type list: unsigned int
@param list: Specifies the integer name of the display list to be executed.
"""
def glCallLists(n, type, lists):
"""
Execute a list of display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/calllists.html}
@type n: int
@param n: Specifies the number of display lists to be executed.
@type type: Enumerated constant
@param type: Specifies the type of values in lists.
@type lists: Buffer object
@param lists: Specifies the address of an array of name offsets in the display list.
The pointer type is void because the offsets can be bytes, shorts, ints, or floats,
depending on the value of type.
"""
def glClear(mask):
"""
Clear buffers to preset values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clear.html}
@type mask: Enumerated constant(s)
@param mask: Bitwise OR of masks that indicate the buffers to be cleared.
"""
def glClearAccum(red, green, blue, alpha):
"""
Specify clear values for the accumulation buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearaccum.html}
@type red,green,blue,alpha: float
@param red,green,blue,alpha: Specify the red, green, blue, and alpha values used when the
accumulation buffer is cleared. The initial values are all 0.
"""
def glClearColor(red, green, blue, alpha):
"""
Specify clear values for the color buffers
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearcolor.html}
@type red,green,blue,alpha: float
@param red,green,blue,alpha: Specify the red, green, blue, and alpha values used when the
color buffers are cleared. The initial values are all 0.
"""
def glClearDepth(depth):
"""
Specify the clear value for the depth buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/cleardepth.html}
@type depth: int
@param depth: Specifies the depth value used when the depth buffer is cleared.
The initial value is 1.
"""
def glClearIndex(c):
"""
Specify the clear value for the color index buffers
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearindex.html}
@type c: float
@param c: Specifies the index used when the color index buffers are cleared.
The initial value is 0.
"""
def glClearStencil(s):
"""
Specify the clear value for the stencil buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clearstencil.html}
@type s: int
@param s: Specifies the index used when the stencil buffer is cleared. The initial value is 0.
"""
def glClipPlane (plane, equation):
"""
Specify a plane against which all geometry is clipped
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/clipplane.html}
@type plane: Enumerated constant
@param plane: Specifies which clipping plane is being positioned.
@type equation: Buffer object I{type GL_FLOAT}(double)
@param equation: Specifies the address of an array of four double- precision floating-point
values. These values are interpreted as a plane equation.
"""
def glColor (red, green, blue, alpha):
"""
B{glColor3b, glColor3d, glColor3f, glColor3i, glColor3s, glColor3ub, glColor3ui, glColor3us,
glColor4b, glColor4d, glColor4f, glColor4i, glColor4s, glColor4ub, glColor4ui, glColor4us,
glColor3bv, glColor3dv, glColor3fv, glColor3iv, glColor3sv, glColor3ubv, glColor3uiv,
glColor3usv, glColor4bv, glColor4dv, glColor4fv, glColor4iv, glColor4sv, glColor4ubv,
glColor4uiv, glColor4usv}
Set a new color.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/color.html}
@type red,green,blue,alpha: Depends on function prototype.
@param red,green,blue: Specify new red, green, and blue values for the current color.
@param alpha: Specifies a new alpha value for the current color. Included only in the
four-argument glColor4 commands. (With '4' colors only)
"""
def glColorMask(red, green, blue, alpha):
"""
Enable and disable writing of frame buffer color components
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormask.html}
@type red,green,blue,alpha: int (boolean)
@param red,green,blue,alpha: Specify whether red, green, blue, and alpha can or cannot be
written into the frame buffer. The initial values are all GL_TRUE, indicating that the
color components can be written.
"""
def glColorMaterial(face, mode):
"""
Cause a material color to track the current color
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormaterial.html}
@type face: Enumerated constant
@param face: Specifies whether front, back, or both front and back material parameters should
track the current color.
@type mode: Enumerated constant
@param mode: Specifies which of several material parameters track the current color.
"""
def glCopyPixels(x, y, width, height, type):
"""
Copy pixels in the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/copypixels.html}
@type x,y: int
@param x,y: Specify the window coordinates of the lower left corner of the rectangular
region of pixels to be copied.
@type width, height: int
@param width,height: Specify the dimensions of the rectangular region of pixels to be copied.
Both must be non-negative.
@type type: Enumerated constant
@param type: Specifies whether color values, depth values, or stencil values are to be copied.
"""
def glCullFace(mode):
"""
Specify whether front- or back-facing facets can be culled
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/cullface.html}
@type mode: Enumerated constant
@param mode: Specifies whether front- or back-facing facets are candidates for culling.
"""
def glDeleteLists(list, range):
"""
Delete a contiguous group of display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/deletelists.html}
@type list: unsigned int
@param list: Specifies the integer name of the first display list to delete
@type range: int
@param range: Specifies the number of display lists to delete
"""
def glDeleteTextures(n, textures):
"""
Delete named textures
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/deletetextures.html}
@type n: int
@param n: Specifies the number of textures to be deleted
@type textures: Buffer I{GL_INT}
@param textures: Specifies an array of textures to be deleted
"""
def glDepthFunc(func):
"""
Specify the value used for depth buffer comparisons
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthfunc.html}
@type func: Enumerated constant
@param func: Specifies the depth comparison function.
"""
def glDepthMask(flag):
"""
Enable or disable writing into the depth buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthmask.html}
@type flag: int (boolean)
@param flag: Specifies whether the depth buffer is enabled for writing. If flag is GL_FALSE,
depth buffer writing is disabled. Otherwise, it is enabled. Initially, depth buffer
writing is enabled.
"""
def glDepthRange(zNear, zFar):
"""
Specify mapping of depth values from normalized device coordinates to window coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/depthrange.html}
@type zNear: int
@param zNear: Specifies the mapping of the near clipping plane to window coordinates.
The initial value is 0.
@type zFar: int
@param zFar: Specifies the mapping of the far clipping plane to window coordinates.
The initial value is 1.
"""
def glDisable(cap):
"""
Disable server-side GL capabilities
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html}
@type cap: Enumerated constant
@param cap: Specifies a symbolic constant indicating a GL capability.
"""
def glDrawBuffer(mode):
"""
Specify which color buffers are to be drawn into
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawbuffer.html}
@type mode: Enumerated constant
@param mode: Specifies up to four color buffers to be drawn into.
"""
def glDrawPixels(width, height, format, type, pixels):
"""
Write a block of pixels to the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/drawpixels.html}
@type width, height: int
@param width, height: Specify the dimensions of the pixel rectangle to be
written into the frame buffer.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type for pixels.
@type pixels: Buffer object
@param pixels: Specifies a pointer to the pixel data.
"""
def glEdgeFlag (flag):
"""
B{glEdgeFlag, glEdgeFlagv}
Flag edges as either boundary or non-boundary
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/edgeflag.html}
@type flag: Depends of function prototype
@param flag: Specifies the current edge flag value.The initial value is GL_TRUE.
"""
def glEnable(cap):
"""
Enable server-side GL capabilities
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/enable.html}
@type cap: Enumerated constant
@param cap: Specifies a symbolic constant indicating a GL capability.
"""
def glEnd():
"""
Delimit the vertices of a primitive or group of like primitives
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/begin.html}
"""
def glEndList():
"""
Create or replace a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/newlist.html}
"""
def glEvalCoord (u,v):
"""
B{glEvalCoord1d, glEvalCoord1f, glEvalCoord2d, glEvalCoord2f, glEvalCoord1dv, glEvalCoord1fv,
glEvalCoord2dv, glEvalCoord2fv}
Evaluate enabled one- and two-dimensional maps
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalcoord.html}
@type u: Depends on function prototype.
@param u: Specifies a value that is the domain coordinate u to the basis function defined
in a previous glMap1 or glMap2 command. If the function prototype ends in 'v' then
u specifies a pointer to an array containing either one or two domain coordinates. The first
coordinate is u. The second coordinate is v, which is present only in glEvalCoord2 versions.
@type v: Depends on function prototype. (only with '2' prototypes)
@param v: Specifies a value that is the domain coordinate v to the basis function defined
in a previous glMap2 command. This argument is not present in a glEvalCoord1 command.
"""
def glEvalMesh (mode, i1, i2):
"""
B{glEvalMesh1 or glEvalMesh2}
Compute a one- or two-dimensional grid of points or lines
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalmesh.html}
@type mode: Enumerated constant
@param mode: In glEvalMesh1, specifies whether to compute a one-dimensional
mesh of points or lines.
@type i1, i2: int
@param i1, i2: Specify the first and last integer values for the grid domain variable i.
"""
def glEvalPoint (i, j):
"""
B{glEvalPoint1 and glEvalPoint2}
Generate and evaluate a single point in a mesh
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/evalpoint.html}
@type i: int
@param i: Specifies the integer value for grid domain variable i.
@type j: int (only with '2' prototypes)
@param j: Specifies the integer value for grid domain variable j (glEvalPoint2 only).
"""
def glFeedbackBuffer (size, type, buffer):
"""
Controls feedback mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/feedbackbuffer.html}
@type size: int
@param size:Specifies the maximum number of values that can be written into buffer.
@type type: Enumerated constant
@param type:Specifies a symbolic constant that describes the information that
will be returned for each vertex.
@type buffer: Buffer object I{GL_FLOAT}
@param buffer: Returns the feedback data.
"""
def glFinish():
"""
Block until all GL execution is complete
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/finish.html}
"""
def glFlush():
"""
Force Execution of GL commands in finite time
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/flush.html}
"""
def glFog (pname, param):
"""
B{glFogf, glFogi, glFogfv, glFogiv}
Specify fog parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/fog.html}
@type pname: Enumerated constant
@param pname: Specifies a single-valued fog parameter. If the function prototype
ends in 'v' specifies a fog parameter.
@type param: Depends on function prototype.
@param param: Specifies the value or values to be assigned to pname. GL_FOG_COLOR
requires an array of four values. All other parameters accept an array containing
only a single value.
"""
def glFrontFace(mode):
"""
Define front- and back-facing polygons
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/frontface.html}
@type mode: Enumerated constant
@param mode: Specifies the orientation of front-facing polygons.
"""
def glFrustum(left, right, bottom, top, zNear, zFar):
"""
Multiply the current matrix by a perspective matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/frustum.html}
@type left, right: double (float)
@param left, right: Specify the coordinates for the left and right vertical
clipping planes.
@type top, bottom: double (float)
@param top, bottom: Specify the coordinates for the bottom and top horizontal
clipping planes.
@type zNear, zFar: double (float)
@param zNear, zFar: Specify the distances to the near and far depth clipping planes.
Both distances must be positive.
"""
def glGenLists(range):
"""
Generate a contiguous set of empty display lists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/genlists.html}
@type range: int
@param range: Specifies the number of contiguous empty display lists to be generated.
"""
def glGenTextures(n, textures):
"""
Generate texture names
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gentextures.html}
@type n: int
@param n: Specifies the number of textures name to be generated.
@type textures: Buffer object I{type GL_INT}
@param textures: Specifies an array in which the generated textures names are stored.
"""
def glGet (pname, param):
"""
B{glGetBooleanv, glGetfloatv, glGetFloatv, glGetIntegerv}
Return the value or values of a selected parameter
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/get.html}
@type pname: Enumerated constant
@param pname: Specifies the parameter value to be returned.
@type param: Depends on function prototype.
@param param: Returns the value or values of the specified parameter.
"""
def glGetClipPlane(plane, equation):
"""
Return the coefficients of the specified clipping plane
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getclipplane.html}
@type plane: Enumerated constant
@param plane: Specifies a clipping plane. The number of clipping planes depends on the
implementation, but at least six clipping planes are supported. They are identified by
symbolic names of the form GL_CLIP_PLANEi where 0 < i < GL_MAX_CLIP_PLANES.
@type equation: Buffer object I{type GL_FLOAT}
@param equation: Returns four float (double)-precision values that are the coefficients of the
plane equation of plane in eye coordinates. The initial value is (0, 0, 0, 0).
"""
def glGetError():
"""
Return error information
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/geterror.html}
"""
def glGetLight (light, pname, params):
"""
B{glGetLightfv and glGetLightiv}
Return light source parameter values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getlight.html}
@type light: Enumerated constant
@param light: Specifies a light source. The number of possible lights depends on the
implementation, but at least eight lights are supported. They are identified by symbolic
names of the form GL_LIGHTi where 0 < i < GL_MAX_LIGHTS.
@type pname: Enumerated constant
@param pname: Specifies a light source parameter for light.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetMap (target, query, v):
"""
B{glGetMapdv, glGetMapfv, glGetMapiv}
Return evaluator parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getmap.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of a map.
@type query: Enumerated constant
@param query: Specifies which parameter to return.
@type v: Buffer object. Depends on function prototype.
@param v: Returns the requested data.
"""
def glGetMaterial (face, pname, params):
"""
B{glGetMaterialfv, glGetMaterialiv}
Return material parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getmaterial.html}
@type face: Enumerated constant
@param face: Specifies which of the two materials is being queried.
representing the front and back materials, respectively.
@type pname: Enumerated constant
@param pname: Specifies the material parameter to return.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetPixelMap (map, values):
"""
B{glGetPixelMapfv, glGetPixelMapuiv, glGetPixelMapusv}
Return the specified pixel map
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getpixelmap.html}
@type map: Enumerated constant
@param map: Specifies the name of the pixel map to return.
@type values: Buffer object. Depends on function prototype.
@param values: Returns the pixel map contents.
"""
def glGetPolygonStipple(mask):
"""
Return the polygon stipple pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getpolygonstipple.html}
@type mask: Buffer object I{type GL_BYTE}
@param mask: Returns the stipple pattern. The initial value is all 1's.
"""
def glGetString(name):
"""
Return a string describing the current GL connection
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getstring.html}
@type name: Enumerated constant
@param name: Specifies a symbolic constant.
"""
def glGetTexEnv (target, pname, params):
"""
B{glGetTexEnvfv, glGetTexEnviv}
Return texture environment parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexenv.html}
@type target: Enumerated constant
@param target: Specifies a texture environment. Must be GL_TEXTURE_ENV.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a texture environment parameter.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexGen (coord, pname, params):
"""
B{glGetTexGendv, glGetTexGenfv, glGetTexGeniv}
Return texture coordinate generation parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexgen.html}
@type coord: Enumerated constant
@param coord: Specifies a texture coordinate.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the value(s) to be returned.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexImage(target, level, format, type, pixels):
"""
Return a texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/getteximage.html}
@type target: Enumerated constant
@param target: Specifies which texture is to be obtained.
@type level: int
@param level: Specifies the level-of-detail number of the desired image.
Level 0 is the base image level. Level n is the nth mipmap reduction image.
@type format: Enumerated constant
@param format: Specifies a pixel format for the returned data.
@type type: Enumerated constant
@param type: Specifies a pixel type for the returned data.
@type pixels: Buffer object.
@param pixels: Returns the texture image. Should be a pointer to an array of the
type specified by type
"""
def glGetTexLevelParameter (target, level, pname, params):
"""
B{glGetTexLevelParameterfv, glGetTexLevelParameteriv}
return texture parameter values for a specific level of detail
@see: U{opengl.org/developers/documentation/man_pages/hardcopy/GL/html/gl/gettexlevelparameter.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of the target texture.
@type level: int
@param level: Specifies the level-of-detail number of the desired image.
Level 0 is the base image level. Level n is the nth mipmap reduction image.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a texture parameter.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the requested data.
"""
def glGetTexParameter (target, pname, params):
"""
B{glGetTexParameterfv, glGetTexParameteriv}
Return texture parameter values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/gettexparameter.html}
@type target: Enumerated constant
@param target: Specifies the symbolic name of the target texture.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name the target texture.
@type params: Buffer object. Depends on function prototype.
@param params: Returns the texture parameters.
"""
def glHint(target, mode):
"""
Specify implementation-specific hints
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/hint.html}
@type target: Enumerated constant
@param target: Specifies a symbolic constant indicating the behavior to be
controlled.
@type mode: Enumerated constant
@param mode: Specifies a symbolic constant indicating the desired behavior.
"""
def glIndex (c):
"""
B{glIndexd, glIndexf, glIndexi, glIndexs, glIndexdv, glIndexfv, glIndexiv, glIndexsv}
Set the current color index
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/index_.html}
@type c: Buffer object. Depends on function prototype.
@param c: Specifies a pointer to a one element array that contains the new value for
the current color index.
"""
def glInitNames():
"""
Initialize the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/initnames.html}
"""
def glIsEnabled(cap):
"""
Test whether a capability is enabled
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/isenabled.html}
@type cap: Enumerated constant
@param cap: Specifies a constant representing a GL capability.
"""
def glIsList(list):
"""
Determine if a name corresponds to a display-list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/islist.html}
@type list: unsigned int
@param list: Specifies a potential display-list name.
"""
def glIsTexture(texture):
"""
Determine if a name corresponds to a texture
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/istexture.html}
@type texture: unsigned int
@param texture: Specifies a value that may be the name of a texture.
"""
def glLight (light, pname, param):
"""
B{glLightf,glLighti, glLightfv, glLightiv}
Set the light source parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/light.html}
@type light: Enumerated constant
@param light: Specifies a light. The number of lights depends on the implementation,
but at least eight lights are supported. They are identified by symbolic names of the
form GL_LIGHTi where 0 < i < GL_MAX_LIGHTS.
@type pname: Enumerated constant
@param pname: Specifies a single-valued light source parameter for light.
@type param: Depends on function prototype.
@param param: Specifies the value that parameter pname of light source light will be set to.
If function prototype ends in 'v' specifies a pointer to the value or values that
parameter pname of light source light will be set to.
"""
def glLightModel (pname, param):
"""
B{glLightModelf, glLightModeli, glLightModelfv, glLightModeliv}
Set the lighting model parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/lightmodel.html}
@type pname: Enumerated constant
@param pname: Specifies a single-value light model parameter.
@type param: Depends on function prototype.
@param param: Specifies the value that param will be set to. If function prototype ends in 'v'
specifies a pointer to the value or values that param will be set to.
"""
def glLineStipple(factor, pattern):
"""
Specify the line stipple pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/linestipple.html}
@type factor: int
@param factor: Specifies a multiplier for each bit in the line stipple pattern.
If factor is 3, for example, each bit in the pattern is used three times before
the next bit in the pattern is used. factor is clamped to the range [1, 256] and
defaults to 1.
@type pattern: unsigned short int
@param pattern: Specifies a 16-bit integer whose bit pattern determines which fragments
of a line will be drawn when the line is rasterized. Bit zero is used first; the default
pattern is all 1's.
"""
def glLineWidth(width):
"""
Specify the width of rasterized lines.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/linewidth.html}
@type width: float
@param width: Specifies the width of rasterized lines. The initial value is 1.
"""
def glListBase(base):
"""
Set the display-list base for glCallLists
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/listbase.html}
@type base: unsigned int
@param base: Specifies an integer offset that will be added to glCallLists
offsets to generate display-list names. The initial value is 0.
"""
def glLoadIdentity():
"""
Replace the current matrix with the identity matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadidentity.html}
"""
def glLoadMatrix (m):
"""
B{glLoadMatrixd, glLoadMatixf}
Replace the current matrix with the specified matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadmatrix.html}
@type m: Buffer object. Depends on function prototype.
@param m: Specifies a pointer to 16 consecutive values, which are used as the elements
of a 4x4 column-major matrix.
"""
def glLoadName(name):
"""
Load a name onto the name stack.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/loadname.html}
@type name: unsigned int
@param name: Specifies a name that will replace the top value on the name stack.
"""
def glLogicOp(opcode):
"""
Specify a logical pixel operation for color index rendering
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/logicop.html}
@type opcode: Enumerated constant
@param opcode: Specifies a symbolic constant that selects a logical operation.
"""
def glMap1 (target, u1, u2, stride, order, points):
"""
B{glMap1d, glMap1f}
Define a one-dimensional evaluator
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/map1.html}
@type target: Enumerated constant
@param target: Specifies the kind of values that are generated by the evaluator.
@type u1, u2: Depends on function prototype.
@param u1,u2: Specify a linear mapping of u, as presented to glEvalCoord1, to ^, t
he variable that is evaluated by the equations specified by this command.
@type stride: int
@param stride: Specifies the number of floats or float (double)s between the beginning
of one control point and the beginning of the next one in the data structure
referenced in points. This allows control points to be embedded in arbitrary data
structures. The only constraint is that the values for a particular control point must
occupy contiguous memory locations.
@type order: int
@param order: Specifies the number of control points. Must be positive.
@type points: Buffer object. Depends on function prototype.
@param points: Specifies a pointer to the array of control points.
"""
def glMap2 (target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, points):
"""
B{glMap2d, glMap2f}
Define a two-dimensional evaluator
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/map2.html}
@type target: Enumerated constant
@param target: Specifies the kind of values that are generated by the evaluator.
@type u1, u2: Depends on function prototype.
@param u1,u2: Specify a linear mapping of u, as presented to glEvalCoord2, to ^, t
he variable that is evaluated by the equations specified by this command. Initially
u1 is 0 and u2 is 1.
@type ustride: int
@param ustride: Specifies the number of floats or float (double)s between the beginning
of control point R and the beginning of control point R ij, where i and j are the u
and v control point indices, respectively. This allows control points to be embedded
in arbitrary data structures. The only constraint is that the values for a particular
control point must occupy contiguous memory locations. The initial value of ustride is 0.
@type uorder: int
@param uorder: Specifies the dimension of the control point array in the u axis.
Must be positive. The initial value is 1.
@type v1, v2: Depends on function prototype.
@param v1, v2: Specify a linear mapping of v, as presented to glEvalCoord2, to ^,
one of the two variables that are evaluated by the equations specified by this command.
Initially, v1 is 0 and v2 is 1.
@type vstride: int
@param vstride: Specifies the number of floats or float (double)s between the beginning of control
point R and the beginning of control point R ij, where i and j are the u and v control
point(indices, respectively. This allows control points to be embedded in arbitrary data
structures. The only constraint is that the values for a particular control point must
occupy contiguous memory locations. The initial value of vstride is 0.
@type vorder: int
@param vorder: Specifies the dimension of the control point array in the v axis.
Must be positive. The initial value is 1.
@type points: Buffer object. Depends on function prototype.
@param points: Specifies a pointer to the array of control points.
"""
def glMapGrid (un, u1,u2 ,vn, v1, v2):
"""
B{glMapGrid1d, glMapGrid1f, glMapGrid2d, glMapGrid2f}
Define a one- or two-dimensional mesh
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/mapgrid.html}
@type un: int
@param un: Specifies the number of partitions in the grid range interval
[u1, u2]. Must be positive.
@type u1, u2: Depends on function prototype.
@param u1, u2: Specify the mappings for integer grid domain values i=0 and i=un.
@type vn: int
@param vn: Specifies the number of partitions in the grid range interval [v1, v2]
(glMapGrid2 only).
@type v1, v2: Depends on function prototype.
@param v1, v2: Specify the mappings for integer grid domain values j=0 and j=vn
(glMapGrid2 only).
"""
def glMaterial (face, pname, params):
"""
Specify material parameters for the lighting model.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/material.html}
@type face: Enumerated constant
@param face: Specifies which face or faces are being updated. Must be one of:
@type pname: Enumerated constant
@param pname: Specifies the single-valued material parameter of the face
or faces that is being updated. Must be GL_SHININESS.
@type params: int
@param params: Specifies the value that parameter GL_SHININESS will be set to.
If function prototype ends in 'v' specifies a pointer to the value or values that
pname will be set to.
"""
def glMatrixMode(mode):
"""
Specify which matrix is the current matrix.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/matrixmode.html}
@type mode: Enumerated constant
@param mode: Specifies which matrix stack is the target for subsequent matrix operations.
"""
def glMultMatrix (m):
"""
B{glMultMatrixd, glMultMatrixf}
Multiply the current matrix with the specified matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/multmatrix.html}
@type m: Buffer object. Depends on function prototype.
@param m: Points to 16 consecutive values that are used as the elements of a 4x4 column
major matrix.
"""
def glNewList(list, mode):
"""
Create or replace a display list
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/newlist.html}
@type list: unsigned int
@param list: Specifies the display list name
@type mode: Enumerated constant
@param mode: Specifies the compilation mode.
"""
def glNormal3 (nx, ny, nz, v):
"""
B{Normal3b, Normal3bv, Normal3d, Normal3dv, Normal3f, Normal3fv, Normal3i, Normal3iv,
Normal3s, Normal3sv}
Set the current normal vector
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/normal.html}
@type nx, ny, nz: Depends on function prototype. (non - 'v' prototypes only)
@param nx, ny, nz: Specify the x, y, and z coordinates of the new current normal.
The initial value of the current normal is the unit vector, (0, 0, 1).
@type v: Buffer object. Depends on function prototype. ('v' prototypes)
@param v: Specifies a pointer to an array of three elements: the x,y, and z coordinates
of the new current normal.
"""
def glOrtho(left, right, bottom, top, zNear, zFar):
"""
Multiply the current matrix with an orthographic matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html}
@type left, right: double (float)
@param left, right: Specify the coordinates for the left and
right vertical clipping planes.
@type bottom, top: double (float)
@param bottom, top: Specify the coordinates for the bottom and top
horizontal clipping planes.
@type zNear, zFar: double (float)
@param zNear, zFar: Specify the distances to the nearer and farther
depth clipping planes. These values are negative if the plane is to be behind the viewer.
"""
def glPassThrough(token):
"""
Place a marker in the feedback buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/passthrough.html}
@type token: float
@param token: Specifies a marker value to be placed in the feedback
buffer following a GL_PASS_THROUGH_TOKEN.
"""
def glPixelMap (map, mapsize, values):
"""
B{glPixelMapfv, glPixelMapuiv, glPixelMapusv}
Set up pixel transfer maps
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelmap.html}
@type map: Enumerated constant
@param map: Specifies a symbolic map name.
@type mapsize: int
@param mapsize: Specifies the size of the map being defined.
@type values: Buffer object. Depends on function prototype.
@param values: Specifies an array of mapsize values.
"""
def glPixelStore (pname, param):
"""
B{glPixelStoref, glPixelStorei}
Set pixel storage modes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelstore.html}
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the parameter to be set.
Six values affect the packing of pixel data into memory.
Six more affect the unpacking of pixel data from memory.
@type param: Depends on function prototype.
@param param: Specifies the value that pname is set to.
"""
def glPixelTransfer (pname, param):
"""
B{glPixelTransferf, glPixelTransferi}
Set pixel transfer modes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixeltransfer.html}
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the pixel transfer parameter to be set.
@type param: Depends on function prototype.
@param param: Specifies the value that pname is set to.
"""
def glPixelZoom(xfactor, yfactor):
"""
Specify the pixel zoom factors
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pixelzoom.html}
@type xfactor, yfactor: float
@param xfactor, yfactor: Specify the x and y zoom factors for pixel write operations.
"""
def glPointSize(size):
"""
Specify the diameter of rasterized points
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pointsize.html}
@type size: float
@param size: Specifies the diameter of rasterized points. The initial value is 1.
"""
def glPolygonMode(face, mode):
"""
Select a polygon rasterization mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonmode.html}
@type face: Enumerated constant
@param face: Specifies the polygons that mode applies to.
Must be GL_FRONT for front-facing polygons, GL_BACK for back- facing polygons,
or GL_FRONT_AND_BACK for front- and back-facing polygons.
@type mode: Enumerated constant
@param mode: Specifies how polygons will be rasterized.
The initial value is GL_FILL for both front- and back- facing polygons.
"""
def glPolygonOffset(factor, units):
"""
Set the scale and units used to calculate depth values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonoffset.html}
@type factor: float
@param factor: Specifies a scale factor that is used to create a variable depth
offset for each polygon. The initial value is 0.
@type units: float
@param units: Is multiplied by an implementation-specific value to create a constant
depth offset. The initial value is 0.
"""
def glPolygonStipple(mask):
"""
Set the polygon stippling pattern
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/polygonstipple.html}
@type mask: Buffer object I{type GL_BYTE}
@param mask: Specifies a pointer to a 32x32 stipple pattern that will be unpacked
from memory in the same way that glDrawPixels unpacks pixels.
"""
def glPopAttrib():
"""
Pop the server attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html}
"""
def glPopClientAttrib():
"""
Pop the client attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushclientattrib.html}
"""
def glPopMatrix():
"""
Pop the current matrix stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html}
"""
def glPopName():
"""
Pop the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushname.html}
"""
def glPrioritizeTextures(n, textures, priorities):
"""
Set texture residence priority
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/prioritizetextures.html}
@type n: int
@param n:Specifies the number of textures to be prioritized.
@type textures: Buffer I{type GL_INT}
@param textures: Specifies an array containing the names of the textures to be prioritized.
@type priorities: Buffer I{type GL_FLOAT}
@param priorities: Specifies an array containing the texture priorities. A priority given
in an element of priorities applies to the texture named by the corresponding element of textures.
"""
def glPushAttrib(mask):
"""
Push the server attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushattrib.html}
@type mask: Enumerated constant(s)
@param mask: Specifies a mask that indicates which attributes to save.
"""
def glPushClientAttrib(mask):
"""
Push the client attribute stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushclientattrib.html}
@type mask: Enumerated constant(s)
@param mask: Specifies a mask that indicates which attributes to save.
"""
def glPushMatrix():
"""
Push the current matrix stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushmatrix.html}
"""
def glPushName(name):
"""
Push the name stack
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/pushname.html}
@type name: unsigned int
@param name: Specifies a name that will be pushed onto the name stack.
"""
def glRasterPos (x,y,z,w):
"""
B{glRasterPos2d, glRasterPos2f, glRasterPos2i, glRasterPos2s, glRasterPos3d,
glRasterPos3f, glRasterPos3i, glRasterPos3s, glRasterPos4d, glRasterPos4f,
glRasterPos4i, glRasterPos4s, glRasterPos2dv, glRasterPos2fv, glRasterPos2iv,
glRasterPos2sv, glRasterPos3dv, glRasterPos3fv, glRasterPos3iv, glRasterPos3sv,
glRasterPos4dv, glRasterPos4fv, glRasterPos4iv, glRasterPos4sv}
Specify the raster position for pixel operations
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rasterpos.html}
@type x, y, z, w: Depends on function prototype. (z and w for '3' and '4' prototypes only)
@param x,y,z,w: Specify the x,y,z, and w object coordinates (if present) for the
raster position. If function prototype ends in 'v' specifies a pointer to an array of two,
three, or four elements, specifying x, y, z, and w coordinates, respectively.
@note:
If you are drawing to the 3d view with a Scriptlink of a space handler
the zoom level of the panels will scale the glRasterPos by the view matrix.
so a X of 10 will not always offset 10 pixels as you would expect.
To work around this get the scale value of the view matrix and use it to scale your pixel values.
Workaround::
import Blender
from Blender.BGL import *
xval, yval= 100, 40
# Get the scale of the view matrix
viewMatrix = Buffer(GL_FLOAT, 16)
glGetFloatv(GL_MODELVIEW_MATRIX, viewMatrix)
f = 1/viewMatrix[0]
glRasterPos2f(xval*f, yval*f) # Instead of the usual glRasterPos2i(xval, yval)
"""
def glReadBuffer(mode):
"""
Select a color buffer source for pixels.
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/readbuffer.html}
@type mode: Enumerated constant
@param mode: Specifies a color buffer.
"""
def glReadPixels(x, y, width, height, format, type, pixels):
"""
Read a block of pixels from the frame buffer
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/readpixels.html}
@type x,y: int
@param x,y:Specify the window coordinates of the first pixel that is read
from the frame buffer. This location is the lower left corner of a rectangular
block of pixels.
@type width, height: int
@param width, height: Specify the dimensions of the pixel rectangle. width and
height of one correspond to a single pixel.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object
@param pixels: Returns the pixel data.
"""
def glRect (x1,y1,x2,y2,v1,v2):
"""
B{glRectd, glRectf, glRecti, glRects, glRectdv, glRectfv, glRectiv, glRectsv}
Draw a rectangle
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rect.html}
@type x1, y1: Depends on function prototype. (for non 'v' prototypes only)
@param x1, y1: Specify one vertex of a rectangle
@type x2, y2: Depends on function prototype. (for non 'v' prototypes only)
@param x2, y2: Specify the opposite vertex of the rectangle
@type v1, v2: Depends on function prototype. (for 'v' prototypes only)
@param v1, v2: Specifies a pointer to one vertex of a rectangle and the pointer
to the opposite vertex of the rectangle
"""
def glRenderMode(mode):
"""
Set rasterization mode
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rendermode.html}
@type mode: Enumerated constant
@param mode: Specifies the rasterization mode.
"""
def glRotate (angle, x, y, z):
"""
B{glRotated, glRotatef}
Multiply the current matrix by a rotation matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/rotate.html}
@type angle: Depends on function prototype.
@param angle: Specifies the angle of rotation in degrees.
@type x,y,z: Depends on function prototype.
@param x,y,z: Specify the x,y, and z coordinates of a vector respectively.
"""
def glScale (x,y,z):
"""
B{glScaled, glScalef}
Multiply the current matrix by a general scaling matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/scale.html}
@type x,y,z: Depends on function prototype.
@param x,y,z: Specify scale factors along the x,y, and z axes, respectively.
"""
def glScissor(x,y,width,height):
"""
Define the scissor box
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/scissor.html}
@type x,y: int
@param x,y: Specify the lower left corner of the scissor box. Initially (0, 0).
@type width, height: int
@param width height: Specify the width and height of the scissor box. When a
GL context is first attached to a window, width and height are set to the
dimensions of that window.
"""
def glSelectBuffer(size, buffer):
"""
Establish a buffer for selection mode values
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/selectbuffer.html}
@type size: int
@param size: Specifies the size of buffer
@type buffer: Buffer I{type GL_INT}
@param buffer: Returns the selection data
"""
def glShadeModel(mode):
"""
Select flat or smooth shading
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/shademodel.html}
@type mode: Enumerated constant
@param mode: Specifies a symbolic value representing a shading technique.
"""
def glStencilFuc(func, ref, mask):
"""
Set function and reference value for stencil testing
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilfunc.html}
@type func: Enumerated constant
@param func:Specifies the test function.
@type ref: int
@param ref:Specifies the reference value for the stencil test. ref is clamped to
the range [0,2n-1], where n is the number of bitplanes in the stencil buffer.
The initial value is 0.
@type mask: unsigned int
@param mask:Specifies a mask that is ANDed with both the reference value and
the stored stencil value when the test is done. The initial value is all 1's.
"""
def glStencilMask(mask):
"""
Control the writing of individual bits in the stencil planes
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilmask.html}
@type mask: unsigned int
@param mask: Specifies a bit mask to enable and disable writing of individual bits
in the stencil planes. Initially, the mask is all 1's.
"""
def glStencilOp(fail, zfail, zpass):
"""
Set stencil test actions
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/stencilop.html}
@type fail: Enumerated constant
@param fail: Specifies the action to take when the stencil test fails.
The initial value is GL_KEEP.
@type zfail: Enumerated constant
@param zfail: Specifies the stencil action when the stencil test passes, but the
depth test fails. zfail accepts the same symbolic constants as fail.
The initial value is GL_KEEP.
@type zpass: Enumerated constant
@param zpass: Specifies the stencil action when both the stencil test and the
depth test pass, or when the stencil test passes and either there is no depth
buffer or depth testing is not enabled. zpass accepts the same symbolic constants
as fail. The initial value is GL_KEEP.
"""
def glTexCoord (s,t,r,q,v):
"""
B{glTexCoord1d, glTexCoord1f, glTexCoord1i, glTexCoord1s, glTexCoord2d, glTexCoord2f,
glTexCoord2i, glTexCoord2s, glTexCoord3d, glTexCoord3f, glTexCoord3i, glTexCoord3s,
glTexCoord4d, glTexCoord4f, glTexCoord4i, glTexCoord4s, glTexCoord1dv, glTexCoord1fv,
glTexCoord1iv, glTexCoord1sv, glTexCoord2dv, glTexCoord2fv, glTexCoord2iv,
glTexCoord2sv, glTexCoord3dv, glTexCoord3fv, glTexCoord3iv, glTexCoord3sv,
glTexCoord4dv, glTexCoord4fv, glTexCoord4iv, glTexCoord4sv}
Set the current texture coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texcoord.html}
@type s,t,r,q: Depends on function prototype. (r and q for '3' and '4' prototypes only)
@param s,t,r,q: Specify s, t, r, and q texture coordinates. Not all parameters are
present in all forms of the command.
@type v: Buffer object. Depends on function prototype. (for 'v' prototypes only)
@param v: Specifies a pointer to an array of one, two, three, or four elements,
which in turn specify the s, t, r, and q texture coordinates.
"""
def glTexEnv (target, pname, param):
"""
B{glTextEnvf, glTextEnvi, glTextEnvfv, glTextEnviv}
Set texture environment parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texenv.html}
@type target: Enumerated constant
@param target: Specifies a texture environment. Must be GL_TEXTURE_ENV.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a single-valued texture environment
parameter. Must be GL_TEXTURE_ENV_MODE.
@type param: Depends on function prototype.
@param param: Specifies a single symbolic constant. If function prototype ends in 'v'
specifies a pointer to a parameter array that contains either a single symbolic
constant or an RGBA color
"""
def glTexGen (coord, pname, param):
"""
B{glTexGend, glTexGenf, glTexGeni, glTexGendv, glTexGenfv, glTexGeniv}
Control the generation of texture coordinates
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texgen.html}
@type coord: Enumerated constant
@param coord: Specifies a texture coordinate.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of the texture- coordinate generation function.
@type param: Depends on function prototype.
@param param: Specifies a single-valued texture generation parameter.
If function prototype ends in 'v' specifies a pointer to an array of texture
generation parameters. If pname is GL_TEXTURE_GEN_MODE, then the array must
contain a single symbolic constant. Otherwise, params holds the coefficients
for the texture-coordinate generation function specified by pname.
"""
def glTexImage1D(target, level, internalformat, width, border, format, type, pixels):
"""
Specify a one-dimensional texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage1d.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type level: int
@param level: Specifies the level-of-detail number. Level 0 is the base image level.
Level n is the nth mipmap reduction image.
@type internalformat: int
@param internalformat: Specifies the number of color components in the texture.
@type width: int
@param width: Specifies the width of the texture image. Must be 2n+2(border) for
some integer n. All implementations support texture images that are at least 64
texels wide. The height of the 1D texture image is 1.
@type border: int
@param border: Specifies the width of the border. Must be either 0 or 1.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object.
@param pixels: Specifies a pointer to the image data in memory.
"""
def glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels):
"""
Specify a two-dimensional texture image
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type level: int
@param level: Specifies the level-of-detail number. Level 0 is the base image level.
Level n is the nth mipmap reduction image.
@type internalformat: int
@param internalformat: Specifies the number of color components in the texture.
@type width: int
@param width: Specifies the width of the texture image. Must be 2n+2(border) for
some integer n. All implementations support texture images that are at least 64
texels wide.
@type height: int
@param height: Specifies the height of the texture image. Must be 2m+2(border) for
some integer m. All implementations support texture images that are at least 64
texels high.
@type border: int
@param border: Specifies the width of the border. Must be either 0 or 1.
@type format: Enumerated constant
@param format: Specifies the format of the pixel data.
@type type: Enumerated constant
@param type: Specifies the data type of the pixel data.
@type pixels: Buffer object.
@param pixels: Specifies a pointer to the image data in memory.
"""
def glTexParameter (target, pname, param):
"""
B{glTexParameterf, glTexParameteri, glTexParameterfv, glTexParameteriv}
Set texture parameters
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texparameter.html}
@type target: Enumerated constant
@param target: Specifies the target texture.
@type pname: Enumerated constant
@param pname: Specifies the symbolic name of a single-valued texture parameter.
@type param: Depends on function prototype.
@param param: Specifies the value of pname. If function prototype ends in 'v' specifies
a pointer to an array where the value or values of pname are stored.
"""
def glTranslate (x, y, z):
"""
B{glTranslatef, glTranslated}
Multiply the current matrix by a translation matrix
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/translate.html}
@type x,y,z: Depends on function prototype.
@param x,y,z: Specify the x, y, and z coordinates of a translation vector.
"""
def glVertex (x,y,z,w,v):
"""
B{glVertex2d, glVertex2f, glVertex2i, glVertex2s, glVertex3d, glVertex3f, glVertex3i,
glVertex3s, glVertex4d, glVertex4f, glVertex4i, glVertex4s, glVertex2dv, glVertex2fv,
glVertex2iv, glVertex2sv, glVertex3dv, glVertex3fv, glVertex3iv, glVertex3sv, glVertex4dv,
glVertex4fv, glVertex4iv, glVertex4sv}
Specify a vertex
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/vertex.html}
@type x,y,z,w: Depends on function prototype (z and w for '3' and '4' prototypes only)
@param x,y,z,w: Specify x, y, z, and w coordinates of a vertex. Not all parameters
are present in all forms of the command.
@type v: Buffer object. Depends of function prototype (for 'v' prototypes only)
@param v: Specifies a pointer to an array of two, three, or four elements. The
elements of a two-element array are x and y; of a three-element array, x, y, and z;
and of a four-element array, x, y, z, and w.
"""
def glViewport(x,y,width,height):
"""
Set the viewport
@see: U{www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/viewport.html}
@type x,y: int
@param x,y: Specify the lower left corner of the viewport rectangle,
in pixels. The initial value is (0,0).
@type width,height: int
@param width,height: Specify the width and height of the viewport. When a GL context
is first attached to a window, width and height are set to the dimensions of that window.
"""
def gluPerspective(fovY, aspect, zNear, zFar):
"""
Set up a perspective projection matrix.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5577288}
@type fovY: double
@param fovY: Specifies the field of view angle, in degrees, in the y direction.
@type aspect: double
@param aspect: Specifies the aspect ratio that determines the field of view in the x direction.
The aspect ratio is the ratio of x (width) to y (height).
@type zNear: double
@param zNear: Specifies the distance from the viewer to the near clipping plane (always positive).
@type zFar: double
@param zFar: Specifies the distance from the viewer to the far clipping plane (always positive).
"""
def gluLookAt(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz):
"""
Define a viewing transformation
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5573042}
@type eyex, eyey, eyez: double
@param eyex, eyey, eyez: Specifies the position of the eye point.
@type centerx, centery, centerz: double
@param centerx, centery, centerz: Specifies the position of the reference point.
@type upx, upy, upz: double
@param upx, upy, upz: Specifies the direction of the up vector.
"""
def gluOrtho2D(left, right, bottom, top):
"""
Define a 2-D orthographic projection matrix
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type left, right: double
@param left, right: Specify the coordinates for the left and right vertical clipping planes.
@type bottom, top: double
@param bottom, top: Specify the coordinates for the bottom and top horizontal clipping planes.
"""
def gluPickMatrix(x, y, width, height, viewport):
"""
Define a picking region
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type x, y: double
@param x, y: Specify the center of a picking region in window coordinates.
@type width, height: double
@param width, height: Specify the width and height, respectively, of the picking region in window coordinates.
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport.
"""
def gluProject(objx, objy, objz, modelMatrix, projMatrix, viewport, winx, winy, winz):
"""
Map object coordinates to window coordinates.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5578074}
@type objx, objy, objz: double
@param objx, objy, objz: Specify the object coordinates.
@type modelMatrix: Buffer object. [double]
@param modelMatrix: Specifies the current modelview matrix (as from a glGetDoublev call).
@type projMatrix: Buffer object. [double]
@param projMatrix: Specifies the current projection matrix (as from a glGetDoublev call).
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport (as from a glGetIntegerv call).
@type winx, winy, winz: Buffer object. [double]
@param winx, winy, winz: Return the computed window coordinates.
"""
def gluUnProject(winx, winy, winz, modelMatrix, projMatrix, viewport, objx, objy, objz):
"""
Map object coordinates to window
coordinates.
@see: U{http://biology.ncsa.uiuc.edu/cgi-bin/infosrch.cgi?cmd=getdoc&coll=0650&db=bks&fname=/SGI_Developer/OpenGL_RM/ch06.html#id5582204}
@type winx, winy, winz: double
@param winx, winy, winz: Specify the window coordinates to be mapped.
@type modelMatrix: Buffer object. [double]
@param modelMatrix: Specifies the current modelview matrix (as from a glGetDoublev call).
@type projMatrix: Buffer object. [double]
@param projMatrix: Specifies the current projection matrix (as from a glGetDoublev call).
@type viewport: Buffer object. [int]
@param viewport: Specifies the current viewport (as from a glGetIntegerv call).
@type objx, objy, objz: Buffer object. [double]
@param objx, objy, objz: Return the computed object coordinates.
"""
class Buffer:
"""
The Buffer object is simply a block of memory that is delineated and initialized by the
user. Many OpenGL functions return data to a C-style pointer, however, because this
is not possible in python the Buffer object can be used to this end. Wherever pointer
notation is used in the OpenGL functions the Buffer object can be used in it's BGL
wrapper. In some instances the Buffer object will need to be initialized with the template
parameter, while in other instances the user will want to create just a blank buffer
which will be zeroed by default.
Example with Buffer::
import Blender
from Blender import BGL
myByteBuffer = BGL.Buffer(BGL.GL_BYTE, [32,32])
BGL.glGetPolygonStipple(myByteBuffer)
print myByteBuffer.dimensions
print myByteBuffer.list
sliceBuffer = myByteBuffer[0:16]
print sliceBuffer
@ivar list: The contents of the Buffer.
@ivar dimensions: The size of the Buffer.
"""
def __init__(type, dimensions, template = None):
"""
This will create a new Buffer object for use with other BGL OpenGL commands.
Only the type of argument to store in the buffer and the dimensions of the buffer
are necessary. Buffers are zeroed by default unless a template is supplied, in
which case the buffer is initialized to the template.
@type type: int
@param type: The format to store data in. The type should be one of
GL_BYTE, GL_SHORT, GL_INT, or GL_FLOAT.
@type dimensions: An int or sequence object specifying the dimensions of the buffer.
@param dimensions: If the dimensions are specified as an int a linear array will
be created for the buffer. If a sequence is passed for the dimensions, the buffer
becomes n-Dimensional, where n is equal to the number of parameters passed in the
sequence. Example: [256,2] is a two- dimensional buffer while [256,256,4] creates
a three- dimensional buffer. You can think of each additional dimension as a sub-item
of the dimension to the left. i.e. [10,2] is a 10 element array each with 2 sub-items.
[(0,0), (0,1), (1,0), (1,1), (2,0), ...] etc.
@type template: A python sequence object (optional)
@param template: A sequence of matching dimensions which will be used to initialize
the Buffer. If a template is not passed in all fields will be initialized to 0.
@rtype: Buffer object
@return: The newly created buffer as a PyObject.
"""

View File

@@ -0,0 +1,96 @@
# Blender.BezTriple module and the BezTriple PyType object
"""
The Blender.BezTriple submodule
B{New}:
- new attributes L{handleTypes<BezTriple.handleTypes>},
L{selects<BezTriple.selects>} and L{weight<BezTriple.weight>}
This module provides access to the BezTriple Data in Blender. It is used by
CurNurb and IpoCurve objects.
@type HandleTypes: readonly dictionary
@var HandleTypes: The available BezTriple handle types.
- FREE - handle has no constraints
- AUTO - completely constrain handle based on knot position
- VECT - constraint handle to line between current and neighboring knot
- ALIGN - constrain handle to lie in a straight line with knot's other
handle
- AUTOANIM - constrain IPO handles to be horizontal on extremes
"""
def New (coords):
"""
Create a new BezTriple object.
@type coords: sequence of three or nine floats
@param coords: the coordinate values for the new control point. If three
floats are given, then the handle values are automatically generated.
@rtype: BezTriple
@return: a new BezTriple object
"""
class BezTriple:
"""
The BezTriple object
====================
This object gives access to generic data from all BezTriple objects in
Blender.
@ivar pt : the [x,y] coordinates for knot point of this BezTriple. After
changing coordinates of a Ipo curve, it is advisable to call
L{IpoCurve.recalc()<IpoCurve.IpoCurve.recalc>} to update the curve.
@type pt: list of two floats
@ivar vec : a list of the 3 points [ handle, knot, handle ] that comprise a
BezTriple, with each point composed of a list [x,y,z] of floats. The list
looks like [ [H1x, H1y, H1z], [Px, Py, Pz], [H2x, H2y, H2z] ].
Example::
# where bt is of type BezTriple
# and h1, p, and h2 are lists of 3 floats
h1, p, h2 = bt.vec
@type vec: list of points
@ivar tilt: the tilt/alpha value for the point
@type tilt: float
@ivar radius: the radius of this point (used for tapering bevels)
@type radius: float
@ivar hide: the visibility status of the knot. B{Note}: true/nonzero means
I{not} hidden. B{Note}: primarily intended for curves; not a good idea to
hide IPO control points.
@type hide: int
@ivar handleTypes: the types of the point's two handles. See
L{HandleTypes} for a complete description.
@type handleTypes list of two ints
@ivar selects: the select status for [handle, knot, handle]. True/nonzero
if the point is selected.
@type selects: list of three ints
@ivar weight: the weight assigned to the control point. Useful for
softbodies and possibly others.
@type weight: float
"""
def getPoints():
"""
Returns the x,y coordinates of the Bezier knot point (B{deprecated}).
See the L{BezTriple.pt} attribute.
@rtype: list of floats
@return: list of the x and y coordinates of the Bezier point.
"""
def setPoints(newval):
"""
Sets the x,y coordinates of the Bezier knot point (B{deprecated}).
See the L{BezTriple.pt} attribute.
@type newval: tuple of 2 floats
@param newval: the x and y coordinates of the new Bezier point.
@rtype: None
@return: None
"""
def getTriple():
"""
Returns the x,y,z coordinates for each of the three points that make up
a BezierTriple (B{deprecated}). See the L{BezTriple.vec} attribute.
@rtype: list consisting of 3 lists of 3 floats
@return: handle1, knot, handle2
"""

View File

@@ -0,0 +1,238 @@
# The Blender Module
# The module files in this folder are used to create the API documentation.
# Doc system used: epydoc - http://epydoc.sf.net
# pseudo command line (check the epy_docgen.sh file):
# epydoc -o BPY_API_23x --url "http://www.blender.org" -t Blender.py \
# -n "Blender" --no-private --no-frames Blender.py \
# Types.py Scene.py Object.py [ ... etc]
"""
The main Blender module.
B{New}: L{Run}, L{UpdateMenus}, new options to L{Get}, L{ShowHelp},
L{SpaceHandlers} dictionary.
L{UnpackModes} dictionary.
Blender
=======
@type bylink: bool
@var bylink: True if the current script is being executed as a script link.
@type link: Blender Object or None; integer (space handlers)
@var link: for normal script links, 'link' points to the linked Object (can be
a scene, object (mesh, camera, lamp), material or
world). For space handler script links, 'link' is an integer from the
Blender.L{SpaceHandlers} dictionary. For script not running as script
links, 'link' is None.
@type event: string or int
@var event: this has three possible uses: script link type or events callback
ascii value:
- for normal script links it is a string representing the link type
(OnLoad, FrameChanged, Redraw, etc.).
- for EVENT space handler script links it is the passed event.
- for normal L{GUI<Draw.Register>} scripts I{during the events callback},
it holds the ascii value of the current event, if it is a valid one.
Users interested in this should also check the builtin 'ord' and 'chr'
Python functions.
@type mode: string
@var mode: Blender's current mode:
- 'interactive': normal mode, with an open window answering to user input;
- 'background': Blender was started as 'C{blender -b <blender file>}' and
will exit as soon as it finishes rendering or executing a script
(ex: 'C{blender -b <blender file> -P <script>}'). Try 'C{blender -h}'
for more detailed informations.
@type UnpackModes: constant dictionary
@var UnpackModes: dictionary with available unpack modes.
- USE_LOCAL - use files in current directory (create when necessary)
- WRITE_LOCAL - write files in current directory (overwrite when necessary)
- USE_ORIGINAL - use files in original location (create when necessary)
- WRITE_ORIGINAL - write files in original location (overwrite when necessary)
@type SpaceHandlers: constant dictionary
@var SpaceHandlers: dictionary with space handler types.
- VIEW3D_EVENT;
- VIEW3D_DRAW.
"""
def Set (request, data):
"""
Update settings in Blender.
@type request: string
@param request: The setting to change:
- 'curframe': the current animation frame
- 'uscriptsdir': user scripts dir
- 'yfexportdir': yafray temp xml storage dir
- 'fontsdir': font dir
- 'texturesdir': textures dir
- 'seqpluginsdir': sequencer plugin dir
- 'renderdir': default render output dir
- 'soundsdir': sound dir
- 'tempdir': temp file storage dir
@type data: int or string
@param data: The new value.
"""
def Get (request):
"""
Retrieve settings from Blender.
@type request: string
@param request: The setting data to be returned:
- 'curframe': the current animation frame.
- 'curtime' : the current animation time.
- 'staframe': the start frame of the animation.
- 'endframe': the end frame of the animation.
- 'rt': the value of the 'rt' button for general debugging
- 'filename': the name of the last file read or written.
- 'homedir': Blender's home directory.
- 'datadir' : the path to the dir where scripts should store and
retrieve their data files, including saved configuration (can
be None, if not found).
- 'udatadir': the path to the user defined data dir. This may not be
available (is None if not found), but users that define uscriptsdir
have a place for their own scripts and script data that won't be
erased when a new version of Blender is installed. For this reason
we recommend scripts check this dir first and use it, if available.
- 'scriptsdir': the path to the main dir where scripts are stored.
- 'uscriptsdir': the path to the user defined dir for scripts. (*)
- 'icondir': the path to blenders icon theme files.
- 'yfexportdir': the path to the user defined dir for yafray export. (*)
- 'fontsdir': the path to the user defined dir for fonts. (*)
- 'texturesdir': the path to the user defined dir for textures. (*)
- 'texpluginsdir': the path to the user defined dir for texture plugins. (*)
- 'seqpluginsdir': the path to the user defined dir for sequence plugins. (*)
- 'renderdir': the path to the user defined dir for render output. (*)
- 'soundsdir': the path to the user defined dir for sound files. (*)
- 'tempdir': the path to the user defined dir for storage of Blender
temporary files. (*)
- 'version' : the Blender version number.
@note: (*) these can be set in Blender at the User Preferences window -> File
Paths tab.
@warn: this function returns None for requested dir paths that have not been
set or do not exist in the user's file system.
@return: The requested data or None if not found.
"""
def Redraw ():
"""
Redraw all 3D windows.
"""
def Load (filename = None):
"""
Load a Blender .blend file or any of the other supported file formats.
Supported formats:
- Blender's .blend;
- DXF;
- Open Inventor 1.0 ASCII;
- Radiogour;
- STL;
- Videoscape;
- VRML 1.0 asc.
@type filename: string
@param filename: the pathname to the desired file. If 'filename'
isn't given or if it contains the substring '.B.blend', the default
.B.blend file is loaded.
@warn: loading a new .blend file removes the current data in Blender. For
safety, this function saves the current data as an auto-save file in
the temporary dir used by Blender before loading a new Blender file.
@warn: after a call to Load(blendfile), current data in Blender is lost,
including the Python dictionaries. Any posterior references in the
script to previously defined data will generate a NameError. So it's
better to put Blender.Load as the last executed command in the script,
when this function is used to open .blend files.
@warn: if in edit mode, this function leaves it, since Blender itself
requires that.
@note: for all types except .blend files, this function only works in
interactive mode, not in background, following what Blender itself does.
"""
def Save (filename, overwrite = 0):
"""
Save a Blender .blend file with the current program data or export to
one of the builtin file formats.
Supported formats:
- Blender (.blend);
- DXF (.dxf);
- STL (.stl);
- Videoscape (.obj);
- VRML 1.0 (.wrl).
@type filename: string
@param filename: the filename for the file to be written. It must have one
of the supported extensions or an error will be returned.
@type overwrite: int (bool)
@param overwrite: if non-zero, file 'filename' will be overwritten if it
already exists (can be checked with L{Blender.sys.exists<Sys.exists>}.
By default existing files are not overwritten (an error is returned).
@note: The substring ".B.blend" is not accepted inside 'filename'.
@note: DXF, STL and Videoscape export only B{selected} meshes.
"""
def Run (script):
"""
Execute the given script.
@type script: string
@param script: the name of an available Blender Text (use L{Text.Get}() to
get a complete list) or the full pathname to a Python script file in the
system.
@note: the script is executed in its own context -- with its own global
dictionary -- as if it had been executed from the Text Editor or chosen
from a menu.
"""
def ShowHelp (script):
"""
Show help for the given script. This is a time-saver ("code-saver") for
scripts that need to feature a 'help' button in their GUIs or a 'help'
submenu option. With proper documentation strings, calling this function is
enough to present a screen with help information plus link and email buttons.
@type script: string
@param script: the filename of a registered Python script.
@note: this function uses L{Run} and the "Scripts Help Browser" script. This
means that it expects proper doc strings in the script to be able to show
help for it (otherwise it offers to load the script source code as text).
The necessary information about doc strings is L{given here<API_related>}.
@note: 'script' doesn't need to be a full path name: "filename.py" is enough.
Note, though, that this function only works for properly registered
scripts (those that appear in menus).
"""
def UpdateMenus ():
"""
Update the menus that list registered scripts. This will scan the default
and user defined (if available) folder(s) for scripts that have registration
data and will make them accessible via menus.
@note: only scripts that save other new scripts in the default or user
defined folders need to call this function.
"""
def UnpackAll (mode):
"""
Unpack all files with specified mode.
@param mode: The Mode for unpacking. Must be one of the modes in
Blender.UnpackModes dictionary.
@type mode: int
"""
def PackAll ():
"""
Pack all files.
"""
def CountPackedFiles():
"""
Returns the number of packed files.
"""
def Quit ():
"""
Exit from Blender immediately.
@warn: the use of this function should obviously be avoided, it is available
because there are some cases where it can be useful, like in automated
tests. For safety, a "quit.blend" file is saved (normal Blender behavior
upon exiting) when this function is called, so the data in Blender isn't
lost.
"""

View File

@@ -0,0 +1,44 @@
/* Generated by CaScadeS, a stylesheet editor for Mozilla Composer */
font { font-family: sans-serif ! important;
}
p { color: rgb(0, 0, 0);
font-family: sans-serif;
}
pre { color: rgb(0, 0, 0);
font-family: monospace;
}
a { font-family: sans-serif;
color: rgb(0, 135, 0);
font-weight: bold;
}
a:visited { font-family: sans-serif;
color: rgb(102, 102, 102);
}
a:hover { font-family: sans-serif;
color: rgb(184, 73, 0);
}
h1 { font-family: sans-serif;
color: rgb(255, 102, 0);
}
h2 { font-family: sans-serif;
color: rgb(255, 102, 0);
}
h3 { font-family: sans-serif;
color: rgb(255, 102, 0);
}
table { color: rgb(0, 0, 0);
opacity: 1;
border-bottom-color: rgb(0, 102, 0);
background-color: rgb(217, 216, 239);
}

View File

@@ -0,0 +1,25 @@
# bpy module and the bpy PyType object
"""
The bpy module.
bpy
===
ATTENTION: This module is EXPERIMENTAL.
Features documented here are subject to change.
The bpy module is intended as a replacement for the Blender module.
It will eventually provide the same features and functionality.
This module uses a different model for the way data is accessed, added and removed. The various types such as groups, meshes, etc., are unchanged.
At the moment it provides an alternative way to access data from python.
Submodules:
-----------
- L{data<Bpy_data>}
- L{libraries<LibData.Libraries>}
- L{config<Bpy_config>}
"""

View File

@@ -0,0 +1,38 @@
# bpy module and the bpy PyType object
"""
bpy.config
==========
This module gives you direct access to blenders preferences.
@var undoSteps: number of undo steps to store.
@type undoSteps: int
@var textureTimeout: free textures from openGL memory if unused after this time.
@type textureTimeout: int
@var textureCollectRate: tag textures as being used at this interval of time.
@type textureCollectRate: int
@var sequenceMemCacheLimit: how much memory to use for a sequencer cache.
@type sequenceMemCacheLimit: int
@var fontSize: display size for fonts in the user interface.
@type fontSize: int
@var yfExportDir: yafray export path.
@type yfExportDir: string
@var fontDir: default font path.
@type fontDir: string
@var renderDir: default render path.
@type renderDir: string
@var textureDir: default texture path.
@type textureDir: string
@var userScriptsDir: path for user scripts.
@type userScriptsDir: string
@var texturePluginsDir: default texture plugin path.
@type texturePluginsDir: string
@var soundDir: default sound path.
@type soundDir: string
@var sequencePluginsDir: default sequencer plugin path.
@type sequencePluginsDir: string
@var tempDir: path where temp files are saved.
@type tempDir: string
"""

View File

@@ -0,0 +1,281 @@
# bpy module and the bpy PyType object
"""
The bpy module.
bpy.data (Generic Data Access)
==============================
Example::
# apply the active image to the active mesh
# this script has no error checking to keep it small and readable.
sce= bpy.data.scenes.active
ob_act = sce.objects.active # assuming we have an active, might be None
me = ob_act.getData(mesh=1) # assuming a mesh type, could be any
img = bpy.data.images.active # assuming we have an active image
for f in me.faces:
f.image = img
Window.RedrawAll()
Example::
# make a new object from an existing mesh
# and make it active
scn= bpy.data.scenes.active
me = bpy.data.meshes['mymesh']
ob = sce.objects.new(me) # new object from the mesh
sce.objects.active = ob
Example::
# print the names of any non local objects
sce= bpy.data.scenes.active
for ob in sce.objects:
if ob.lib:
print 'external object:', ob.name, ob.lib
Example::
# add an empty object at each vertex of the active mesh
scn= bpy.data.scenes.active
ob_act = sce.objects.active
matrix = ob_act.matrixWorld
me = ob_act.getData(mesh=1)
for v in me.verts:
ob = sce.objects.new('Empty')
ob.loc = v.co * matrix # transform the vertex location by the objects matrix.
Example::
# load all the wave sound files in a directory
import os
sound_dir = '/home/me/soundfiles/'
sounds_new = []
for fname in os.listdir(sound_dir):
if fname.lower().endswith('.wav'):
try:
snd = bpy.data.sounds.new(filename = sound_dir + fname)
except:
snd = None
if snd:
sounds_new.append(snd)
# Print the sounds
for snd in sounds_new:
print snd
Example::
# apply a new image to each selected mesh object as a texface.
width, height= 512, 512
scn= bpy.data.scenes.active
for ob in sce.objects.context:
if not ob.lib and ob.type == 'Mesh': # object isn't from a library and is a mesh
me = ob.getData(mesh=1)
me.faceUV = True # add UV coords and textures if we don't have them.
# Make an image named after the mesh
img = bpy.data.images.new(me.name, width, height)
for f in me.faces:
f.image = img
Window.RedrawAll()
@var scenes: sequence for L{scene<Scene.Scene>} data
@type scenes: L{libBlockSeq}
@var objects: sequence for L{object<Object.Object>} data
@type objects: L{libBlockSeq}
@var meshes: sequence for L{mesh<Mesh.Mesh>} data
@type meshes: L{libBlockSeq}
@var curves: sequence for L{curve<Curve.Curve>} data, used to store Curve, Surface and Text3d data.
@type curves: L{libBlockSeq}
@var metaballs: sequence for L{metaball<Metaball.Metaball>} data
@type metaballs: L{libBlockSeq}
@var materials: sequence for L{material<Material.Material>} data
@type materials: L{libBlockSeq}
@var textures: sequence for L{texture<Texture.Texture>} data
@type textures: L{libBlockSeq}
@var images: sequence for L{image<Image.Image>} data
@type images: L{libBlockSeq}
@var lattices: sequence for L{lattice<Lattice.Lattice>} data
@type lattices: L{libBlockSeq}
@var lamps: sequence for L{lamp<Lamp.Lamp>} data
@type lamps: L{libBlockSeq}
@var cameras: sequence for L{camera<Camera.Camera>} data
@type cameras: L{libBlockSeq}
@var ipos: sequence for L{ipo<Ipo.Ipo>} data
@type ipos: L{libBlockSeq}
@var worlds: sequence for L{world<World.World>} data
@type worlds: L{libBlockSeq}
@var fonts: sequence for L{font<Font.Font>} data
@type fonts: L{libBlockSeq}
@var texts: sequence for L{text<Text.Text>} data
@type texts: L{libBlockSeq}
@var sounds: sequence for L{sound<Sound.Sound>} data
@type sounds: L{libBlockSeq}
@var groups: sequence for L{group<Group.Group>} data
@type groups: L{libBlockSeq}
@var armatures: sequence for L{armature<Armature.Armature>} data
@type armatures: L{libBlockSeq}
@var actions: sequence for L{action<NLA.Action>} data
@type actions: L{libBlockSeq}
"""
class libBlockSeq:
"""
Generic Data Access
===================
This provides a unified way to access and manipulate data types in Blender
(scene, object, mesh, curve, metaball, material, texture, image, lattice,
lamp, camera, ipo, world, font, text, sound, groups, armatures, actions).
Get Item
========
To get a datablock by name you can use dictionary-like syntax.
>>> ob = bpy.data.objects['myobject']
Note that this can only be used for getting.
>>> bpy.data.objects['myobject'] = data # will raise an error
B{Library distinctions}
Blender doesn't allow naming collisions within its own data, but it's
possible to run into naming collisions when you have data linked from an external blend file.
You can specify where the data is from by using a (name, library) pair as the key.
>>> group = bpy.data.groups['mygroup', '//mylib.blend'] # only return data linked from mylib
If you want to get a group from the local data only you can use None
>>> group = bpy.data.groups['mygroup', None] # always returns local data
Sequence
========
These generic datablocks are sequence datatypes. They are not lists. They support the dictionary and iterator protocols. This implies the following
- A B{for} statement allows you to loop through data using the iterator protocol without wasting resources on creating a large list.
>>> for me in bpy.data.meshes:
... print me.name
- You can also use len() to see how many datablocks exist.
>>> print len(bpy.data.scenes)
- Because the sequences are not lists and the [] operator is used to get items by name, you cannot use indexing to retrieve an item.
>>> ob = bpy.data.objects[-1] # will raise an error
- If you want to access the entire sequence as a list simply use the list() constructor.
>>> ipo_list = list(bpy.data.ipos)
@type tag: Bool
@ivar tag: A fast way to set the tag value of every member of the sequence to True or False
For example
>>> bpy.data.meshes.tag = True
Is the same as...
>>> for me in bpy.data.meshes: me.tag = True
@type active: Datablock or None
@ivar active: The active member of the datatype
Applies to:
- L{images}
- L{scenes}
- L{texts}
This can also be used to set the active data.
>>> bpy.data.images.active = bpy.data.images.new(filename = '/home/me/someimage.jpg')
"""
def new(name):
"""
fixme: need description for parameters.
This function returns a new datablock containing no data or loaded from a file.
Most datatypes accept a name for their argument except for L{sounds}, L{fonts}, L{ipos} and L{curves} that need an additional argument.
The name argument is optional if not given a default name will be assigned.
The name given may be modified by blender to make it unique.
Loading From File
=================
For L{images}, L{texts}, L{sounds}, L{fonts} types you can use the filename keyword to make a new datablock from a file.
New L{sounds}, L{fonts} can only be made with the a filename given.
The filename can a keyword or the second argument, use the keyword only for the datablocks new name to be set by the filename.
>>> sound = bpy.data.sounds.new('newsound', '~/mysound.wav') # uses the first string given for the name.
>>> sound = bpy.data.sounds.new(filename = '~/mysound.wav') # will use the filename to make the name.
Images
======
Images optionally accept extra 2 arguments for width and height, values between 4 and 5000 if no args are given they will be 256.
>>> img = bpy.data.images.new(name, 512, 512)
Curves
======
Curves need 2 arguments: bpy.data.curves.new(name, type) type must be one of the following...
- 'Curve'
- 'Text3d'
>>> text3d = bpy.data.curves.new('MyCurve', 'Text3d')
Ipos
====
Ipos need 2 arguments: bpy.data.ipos.new(name, type) type must be one of the following...
- 'Camera'
- 'World'
- 'Material'
- 'Texture'
- 'Lamp'
- 'Action'
- 'Constraint'
- 'Sequence'
- 'Curve'
- 'Key'
Objects cannot be created from bpy.data.objects;
objects must be created from the scene. Here are some examples.
>>> ob = bpy.data.scenes.active.objects.new('Empty')
>>> scn = bpy.data.scenes.active
... ob = sce.objects.new(bpy.data.meshes.new('mymesh'))
@rtype: datablock
"""
def unlink(datablock):
"""
This function removes a datablock.
applies to:
- L{scenes}
- L{groups}
- L{texts}
Other types will raise an error.
@rtype: None
"""

View File

@@ -0,0 +1,257 @@
# Blender.Camera module and the Camera PyType object
"""
The Blender.Camera submodule.
B{New}: L{Camera.clearScriptLinks} accepts a parameter now.
Camera Data
===========
This module provides access to B{Camera Data} objects in Blender.
Example::
from Blender import Camera, Object, Scene
cam = Camera.New('ortho') # create new ortho camera data
cam.scale = 6.0 # set scale value for ortho view
scn = Scene.GetCurrent() # get current scene
ob = scn.objects.new(cam) # add a new camera object from the data
scn.setCurrentCamera(ob) # make this camera the active
"""
def New (type = 'persp', name = 'CamData'):
"""
Create a new Camera Data object.
@type type: string
@param type: The Camera type: 'persp' or 'ortho'.
@type name: string
@param name: The Camera Data name.
@rtype: Blender Camera
@return: The created Camera Data object.
"""
def Get (name = None):
"""
Get the Camera Data object(s) from Blender.
@type name: string
@param name: The name of the Camera Data.
@rtype: Blender Camera or a list of Blender Cameras
@return: It depends on the I{name} parameter:
- (name): The Camera Data object with the given I{name};
- (): A list with all Camera Data objects in the current scene.
"""
class Camera:
"""
The Camera Data object
======================
This object gives access to Camera-specific data in Blender.
@ivar type: The Camera type: 'persp' or 'ortho'
@ivar mode: The mode flags: B{ORed value}: 'showLimits':1, 'showMist':2.
@ivar lens: The lens value in [1.0, 250.0], only relevant to *persp* cameras.
@ivar angle: The lens value in degrees [7.323871, 172.847331], only relevant to *persp* cameras.
@ivar scale: The scale value in [0.01, 1000.00], only relevant to *ortho* cameras.
@ivar clipStart: The clip start value in [0.0, 100.0].
@ivar clipEnd: The clip end value in [1.0, 5000.0].
@ivar dofDist: The dofDist value in [0.0, 5000.0].
@ivar shiftX: The horizontal offset of the camera [-2.0, 2.0].
@ivar shiftY: The vertical offset of the camera [-2.0, 2.0].
@ivar alpha: The PassePart alpha [0.0, 1.0].
@ivar drawSize: The display size for the camera an the 3d view [0.1, 10.0].
@type ipo: Blender Ipo
@ivar ipo: The "camera data" ipo linked to this camera data object.
Set to None to clear the ipo.
@ivar drawLimits: Toggle the option to show limits in the 3d view.
@ivar drawName: Toggle the option to show the camera name in the 3d view.
@ivar drawMist: Toggle the option to show mist in the 3d view.
@ivar drawTileSafe: Toggle the option to show tile safe in the 3d view.
@ivar drawPassepartout: Toggle the option to show pass part out in the 3d view.
@warning: Most member variables assume values in some [Min, Max] interval.
When trying to set them, the given parameter will be clamped to lie in
that range: if val < Min, then val = Min, if val > Max, then val = Max.
"""
def getName():
"""
Get the name of this Camera Data object. (B{deprecated}) See the L{name} attribute.
@rtype: string
"""
def setName(name):
"""
Set the name of this Camera Data object. (B{deprecated}) See the L{name} attribute.
@type name: string
@param name: The new name.
"""
def getIpo():
"""
Get the Ipo associated with this camera data object, if any. (B{deprecated})
@rtype: Ipo
@return: the wrapped ipo or None. (B{deprecated}) See the L{ipo} attribute.
"""
def setIpo(ipo):
"""
Link an ipo to this camera data object. (B{deprecated}) See the L{ipo} attribute.
@type ipo: Blender Ipo
@param ipo: a "camera data" ipo.
"""
def clearIpo():
"""
Unlink the ipo from this camera data object. (B{deprecated}) See the L{ipo} attribute.
@return: True if there was an ipo linked or False otherwise.
"""
def getType():
"""
Get this Camera's type. (B{deprecated}) See the L{type} attribute.
@rtype: int
@return: 0 for 'persp' or 1 for 'ortho'.
"""
def setType(type):
"""
Set this Camera's type. (B{deprecated}) See the L{type} attribute.
@type type: string
@param type: The Camera type: 'persp' or 'ortho'.
"""
def getMode():
"""
Get this Camera's mode flags. (B{deprecated}) See the L{mode} attribute.
@rtype: int
@return: B{OR'ed value}: 'showLimits' is 1, 'showMist' is 2, or
respectively, 01 and 10 in binary.
"""
def setMode(mode1 = None, mode2 = None):
"""
Set this Camera's mode flags. Mode strings given are turned 'on'. (B{deprecated}) See the L{mode} attribute.
Those not provided are turned 'off', so cam.setMode() -- without
arguments -- turns off all mode flags for Camera cam.
@type mode1: string
@type mode2: string
@param mode1: A mode flag: 'showLimits' or 'showMist'.
@param mode2: A mode flag: 'showLimits' or 'showMist'.
"""
def getLens():
"""
Get the lens value. (B{deprecated}) See the L{lens} attribute.
@rtype: float
@warn: lens is only relevant for perspective (L{getType}) cameras.
"""
def setLens(lens):
"""
Set the lens value. (B{deprecated}) See the L{lens} attribute.
@type lens: float
@param lens: The new lens value.
@warn: lens is only relevant for perspective (L{type}) cameras.
"""
def getScale():
"""
Get the scale value. (B{deprecated}) See the L{scale} attribute.
@rtype: float
@warn: scale is only relevant for ortho (L{type}) cameras.
"""
def setScale(scale):
"""
Set the scale value. (B{deprecated}) See the L{scale} attribute.
@type scale: float
@param scale: The new scale value in [0.01, 1000.00].
@warn: scale is only relevant for ortho (L{getType}) cameras.
"""
def getClipStart():
"""
Get the clip start value. (B{deprecated}) See the L{clipStart} attribute.
@rtype: float
"""
def setClipStart(clipstart):
"""
Set the clip start value. (B{deprecated}) See the L{clipStart} attribute.
@type clipstart: float
@param clipstart: The new lens value.
"""
def getClipEnd():
"""
Get the clip end value. (B{deprecated}) See the L{clipEnd} attribute.
@rtype: float
"""
def setClipEnd(clipend):
"""
Set the clip end value. (B{deprecated}) See the L{clipEnd} attribute.
@type clipend: float
@param clipend: The new clip end value.
"""
def getDrawSize():
"""
Get the draw size value. (B{deprecated}) See the L{drawSize} attribute.
@rtype: float
"""
def setDrawSize(drawsize):
"""
Set the draw size value. (B{deprecated}) See the L{drawSize} attribute.
@type drawsize: float
@param drawsize: The new draw size value.
"""
def getScriptLinks (event):
"""
Get a list with this Camera's script links of type 'event'.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this Camera. If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this Camera.
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
"""
def insertIpoKey(keytype):
"""
Inserts keytype values in camera ipo at curframe. Uses module constants.
@type keytype: Integer
@param keytype:
-LENS
-CLIPPING
@return: py_none
"""
def __copy__ ():
"""
Make a copy of this camera
@rtype: Camera
@return: a copy of this camera
"""
import id_generics
Camera.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,248 @@
# Blender.Constraint module and the Constraint PyType object
"""
The Blender.Constraint submodule
B{New}:
- provides access to Blender's constraint stack
This module provides access to the Constraint Data in Blender.
Examples::
from Blender import *
ob = Object.Get('Cube')
if len(ob.constraints) > 0:
const = ob.constraints[0]
if const.type == Constraint.Type.FLOOR:
offs = const[Constraint.Settings.OFFSET]
Or to print all the constraints attached to each bone in a pose::
from Blender import *
ob = Object.Get('Armature')
pose = ob.getPose()
for bonename in pose.bones.keys():
bone = pose.bones[bonename]
for const in bone.constraints:
print bone.name,'=>',const
@type Type: readonly dictionary
@var Type: Constant Constraint dict used by L{Constraints.append()} and
for comparison with L{Constraint.type}. Values are
TRACKTO, IKSOLVER, FOLLOWPATH, COPYROT, COPYLOC, COPYSIZE, ACTION,
LOCKTRACK, STRETCHTO, FLOOR, LIMITLOC, LIMITROT, LIMITSIZE, CLAMPTO,
PYTHON, CHILDOF, TRANSFORM, NULL
@type Settings: readonly dictionary
@var Settings: Constant dict used for changing constraint settings.
- Used for all constraints
- TARGET (Object) (Note: not used by Limit Location (LIMITLOC),
Limit Rotation (LIMITROT), Limit Scale (LIMITSIZE))
- BONE (string): name of Bone sub-target (for armature targets) (Note: not
used by Stretch To (STRETCHTO), Limit Location (LIMITLOC), Limit Rotation
(LIMITROT), Limit Scale (LIMITSIZE), Follow Path (FOLLOWPATH), Clamp To (CLAMPTO))
- Used by some constraints:
- OWNERSPACE (int): for TRACKTO, COPYLOC, COPYROT, COPYSIZE, LIMITLOC, LIMITROT, LIMITSIZE, PYTHON, TRANSFORM
If the owner is an object, values are SPACE_WORLD, SPACE_LOCAL
If the owner is a bone, values are SPACE_WORLD, SPACE_POSE, SPACE_PARLOCAL, SPACE_LOCAL
- TARGETSPACE (int): for TRACKTO, COPYLOC, COPYROT, COPYSIZE, PYTHON, TRANSFORM, ACTION
If the owner is an object, values are SPACE_WORLD, SPACE_LOCAL
If the owner is a bone, values are SPACE_WORLD, SPACE_POSE, SPACE_PARLOCAL, SPACE_LOCAL
- Used by IK Solver (IKSOLVER) constraint:
- TOLERANCE (float): clamped to [0.0001:1.0]
- ITERATIONS (int): clamped to [1,10000]
- CHAINLEN (int): clamped to [0,255]
- POSWEIGHT (float): clamped to [0.01,1.0]
- ROTWEIGHT (float): clamped to [0.01,1.0]
- ROTATE (bool)
- USETIP (bool)
- Used by Action (ACTION) constraint:
- ACTION (Action Object)
- START (int): clamped to [1,maxframe]
- END (int): clamped to [1,maxframe]
- MIN (float): clamped to [-1000.0,1000.0] for Location, [-180.0,180.0] for Rotation, [0.0001,1000.0] for Scaling
- MAX (float): clamped to [-1000.0,1000.0] for Location, [-180.0,180.0] for Rotation, [0.0001,1000.0] for Scaling
- KEYON (int): values are XLOC, YLOC, ZLOC, XROT, YROT, ZROT, XSIZE, YSIZE, ZSIZE
- Used by Track To (TRACKTO) constraint:
- TRACK (int): values are TRACKX, TRACKY, TRACKZ, TRACKNEGX,
TRACKNEGY, TRACKNEGZ
- UP (int): values are UPX, UPY, UPZ
- Used by Stretch To (STRETCHTO) constraint:
- RESTLENGTH (float): clamped to [0.0:100.0]
- VOLVARIATION (float): clamped to [0.0:100.0]
- VOLUMEMODE (int): values are VOLUMEXZ, VOLUMEX, VOLUMEZ,
VOLUMENONE
- PLANE (int): values are PLANEX, PLANEZ
- Used by Follow Path (FOLLOWPATH) constraint:
- FOLLOW (bool)
- OFFSET (float): clamped to [-maxframe:maxframe]
- FORWARD (int): values are TRACKX, TRACKY, TRACKZ, TRACKNEGX,
TRACKNEGY, TRACKNEGZ
- UP (int): values are UPX, UPY, UPZ
- Used by Lock Track (FOLLOWPATH) constraint:
- TRACK (int): values are TRACKX, TRACKY, TRACKZ, TRACKNEGX,
TRACKNEGY, TRACKNEGZ
- LOCK (int): values are LOCKX, LOCKY, LOCKZ
- Used by Clamp To (CLAMPTO) constraint:
- CLAMP (int): values are CLAMPAUTO, CLAMPX, CLAMPY, CLAMPZ
- CLAMPCYCLIC (bool)
- Used by Floor (FLOOR) constraint:
- MINMAX (int): values are MINX, MINY, MINZ, MAXX, MAXY, MAXZ
- OFFSET (float): clamped to [-100.0,100.0]
- STICKY (bool)
- Used by Copy Location (COPYLOC) and Copy Rotation (COPYROT)
- COPY (bitfield): any combination of COPYX, COPYY and COPYZ with possible addition of COPYXINVERT, COPYYINVERT and COPYZINVERT to invert that particular input (if on).
- Used by Copy Size (COPYSIZE) constraint:
- COPY (bitfield): any combination of COPYX, COPYY and COPYZ
- Used by Limit Location (LIMITLOC) constraint:
- LIMIT (bitfield): any combination of LIMIT_XMIN, LIMIT_XMAX,
LIMIT_YMIN, LIMIT_YMAX, LIMIT_ZMIN, LIMIT_ZMAX
- XMIN (float): clamped to [-1000.0,1000.0]
- XMAX (float): clamped to [-1000.0,1000.0]
- YMIN (float): clamped to [-1000.0,1000.0]
- YMAX (float): clamped to [-1000.0,1000.0]
- ZMIN (float): clamped to [-1000.0,1000.0]
- ZMAX (float): clamped to [-1000.0,1000.0]
- Used by Limit Rotation (LIMITROT) constraint:
- LIMIT (bitfield): any combination of LIMIT_XROT, LIMIT_YROT,
LIMIT_ZROT
- XMIN (float): clamped to [-360.0,360.0]
- XMAX (float): clamped to [-360.0,360.0]
- YMIN (float): clamped to [-360.0,360.0]
- YMAX (float): clamped to [-360.0,360.0]
- ZMIN (float): clamped to [-360.0,360.0]
- ZMAX (float): clamped to [-360.0,360.0]
- Used by Limit Scale (LIMITSIZE) constraint:
- LIMIT (bitfield): any combination of LIMIT_XMIN, LIMIT_XMAX,
LIMIT_YMIN, LIMIT_YMAX, LIMIT_ZMIN, LIMIT_ZMAX
- XMIN (float): clamped to [0.0001,1000.0]
- XMAX (float): clamped to [0.0001,1000.0]
- YMIN (float): clamped to [0.0001,1000.0]
- YMAX (float): clamped to [0.0001,1000.0]
- ZMIN (float): clamped to [0.0001,1000.0]
- ZMAX (float): clamped to [0.0001,1000.0]
- Used by Python Script (PYTHON) constraint:
- SCRIPT (Text): script to use
- PROPERTIES (IDProperties): ID-Properties of constraint
- Used by Child Of (CHILDOF) constraint:
- COPY (bitfield): any combination of PARLOCX, PARLOCY, PARLOCZ,
PARROTX, PARROTY, PARROTZ, PARSIZEX, PARSIZEY, PARSIZEZ.
- Used by Transformation (TRANSFORM) constraint:
- FROM (int): values are LOC, ROT, SCALE
- TO (int): values are LOC, ROT, SCALE
- MAPX, MAPY, MAPZ (int): values are LOC, ROT, SCALE
- EXTRAPOLATE (bool)
- FROM_MINX, FROM_MINY, FROM_MINZ, FROM_MAXX,
FROM_MAXY, FROM_MAXZ (float):
If FROM==LOC, then is clamped to [-1000.0, 1000.0]
If FROM==ROT, then is clamped to [-360.0, 360.0]
If FROM==SCALE, then is clamped to [0.0001, 1000.0]
- TO_MINX, TO_MINY, TO_MINZ, TO_MAXX, TO_MAXY, TO_MAXZ (float):
If TO==LOC, then is clamped to [-1000.0, 1000.0]
If TO==ROT, then is clamped to [-360.0, 360.0]
If TO==SCALE, then is clamped to [0.0001, 1000.0]
"""
class Constraints:
"""
The Constraints object
======================
This object provides access to sequence of
L{constraints<Constraint.Constraint>} for a particular object.
They can be accessed from L{Object.constraints<Object.Object.constraints>}.
or L{PoseBone.constraints<Pose.PoseBone.constraints>}.
"""
def __getitem__(index):
"""
This operator returns one of the constraints in the stack.
@type index: int
@return: an Constraint object
@rtype: Constraint
@raise KeyError: index was out of range
"""
def __len__():
"""
Returns the number of constraints in the constraint stack.
@return: number of Constraints
@rtype: int
"""
def append(type):
"""
Appends a new constraint to the end of the constraint stack.
@param type: a constant specifying the type of constraint to create. as from L{Type}
@type type: int constant
@rtype: Constraint
@return: the new Constraint
"""
def remove(con):
"""
Remove a constraint from this objects constraint sequence.
@param con: a constraint from this sequence to remove.
@type con: Constraint
@note: Accessing attributes of the constraint after it is removed will
throw an exception.
"""
def moveUp(con):
"""
Moves the constraint up in the object's constraint stack.
@param con: a constraint from this sequence to remove.
@type con: Constraint
@rtype: None
"""
def moveDown(con):
"""
Moves the constraint down in the object's constraint stack.
@param con: a constraint from this sequence to remove.
@type con: Constraint
@rtype: None
"""
class Constraint:
"""
The Constraint object
=====================
This object provides access to a constraint for a particular object
accessed from L{Constraints}.
@ivar name: The name of this constraint. 29 chars max.
@type name: string
@ivar type: The type of this constraint. Read-only. The returned value
matches the types in L{Type}.
@type type: int
@ivar influence: The influence value of the constraint. Valid values
are in the range [0.0,1.0].
@type influence: float
"""
def __getitem__(key):
"""
This operator returns one of the constraint's data attributes.
@param key: value from constraint's L{Constraint.Settings} constant
@type key: int constant
@return: the requested data
@rtype: varies
@raise KeyError: the key does not exist for the constraint
"""
def __setitem__(key):
"""
This operator changes one of the constraint's data attributes.
@param key: value from constraint's L{Constraint.Settings} constant
@type key: int constant
@raise KeyError: the key does not exist for the constraint
"""
def insertKey(frame):
"""
Adds an influence keyframe for the constraint Ipo.
@rtype: None
@param frame: the frame number at which to insert the key.
@type frame: float
"""

View File

@@ -0,0 +1,721 @@
# Blender.Curve module and the Curve PyType object
"""
The Blender.Curve submodule.
Curve Data
==========
This module provides access to B{Curve Data} objects in Blender.
A Blender Curve Data consists of multiple L{CurNurb}(s). Try converting a Text object to a Curve to see an example of this. Each curve is of
type Bezier or Nurb. The underlying L{CurNurb}(s) can be accessed with
the [] operator. Operator [] returns an object of type L{CurNurb}.
Note that L{CurNurb} can be used to acces a curve of any type (Poly, Bezier or Nurb)
The Curve module also supports the Python iterator interface. This means you
can access the L{CurNurb}(s) in a Curve and the control points in a L{CurNurb} using a
Python B{for} statement.
Add a Curve to a Scene Example::
from Blender import Curve, Object, Scene
cu = Curve.New() # create new curve data
scn = Scene.GetCurrent() # get current scene
ob = scn.objects.new(cu) # make a new curve from the curve data
Iterator Example::
from Blender import Curve, Object, Scene
scn = Scene.GetCurrent() # get current scene
ob = scn.objects.active
curvedata = ob.data
for curnurb in curvedata:
print type( curnurb ), curnurb
for point in curnurb:
print type( point ), point
Creating a Curve from a list of Vec triples Examples::
from Blender import *
def bezList2Curve(bezier_vecs):
'''
Take a list or vector triples and converts them into a bezier curve object
'''
def bezFromVecs(vecs):
'''
Bezier triple from 3 vecs, shortcut functon
'''
bt= BezTriple.New(\
vecs[0].x, vecs[0].y, vecs[0].z,\
vecs[1].x, vecs[1].y, vecs[1].z,\
vecs[2].x, vecs[2].y, vecs[2].z)
bt.handleTypes= (BezTriple.HandleTypes.FREE, BezTriple.HandleTypes.FREE)
return bt
# Create the curve data with one point
cu= Curve.New()
cu.appendNurb(bezFromVecs(bezier_vecs[0])) # We must add with a point to start with
cu_nurb= cu[0] # Get the first curve just added in the CurveData
i= 1 # skip first vec triple because it was used to init the curve
while i<len(bezier_vecs):
bt_vec_triple= bezier_vecs[i]
bt= bezFromVecs(bt_vec_triple)
cu_nurb.append(bt)
i+=1
# Add the Curve into the scene
scn= Scene.GetCurrent()
ob = scn.objects.new(cu)
return ob
"""
def New ( name):
"""
Create a new Curve Data object.
@type name: string
@param name: The Curve Data name.
@rtype: Blender Curve
@return: The created Curve Data object.
"""
def Get (name = None):
"""
Get the Curve Data object(s) from Blender.
@type name: string
@param name: The name of the Curve Data.
@rtype: Blender Curve or a list of Blender Curves
@return: It depends on the 'name' parameter:
- (name): The Curve Data object with the given name;
- (): A list with all Curve Data objects in the current scene.
"""
class Curve:
"""
The Curve Data object
=====================
This object gives access to Curve and Surface data linked from Blender Objects.
@ivar name: The Curve Data name.
@type name: string
@ivar pathlen: The Curve Data path length, used to set the number of frames for an animation (not the physical length).
@type pathlen: int
@ivar totcol: The Curve Data maximal number of linked materials. Read-only.
@type totcol: int
@ivar flag: The Curve Data flag value; see L{getFlag()} for the semantics.
@ivar bevresol: The Curve Data bevel resolution. [0 - 32]
@type bevresol: int
@ivar resolu: The Curve Data U-resolution (used for curve and surface resolution) [0 - 1024].
@type resolu: int
@ivar resolv: The Curve Data V-resolution (used for surface resolution) [0 - 1024].
@type resolv: int
@ivar width: The Curve Data width [0 - 2].
@type width: float
@ivar ext1: The Curve Data extent1 (for bevels).
@type ext1: float
@ivar ext2: The Curve Data extent2 (for bevels).
@type ext2: float
@ivar loc: The Curve Data location(from the center).
@type loc: list of 3 floats
@ivar rot: The Curve Data rotation(from the center).
@type rot: list of 3 floats
@ivar size: The Curve Data size(from the center).
@type size: list of 3 floats
@ivar bevob: The Curve Bevel Object
@type bevob: Blender L{Object<Object.Object>} or None
@ivar taperob: The Curve Taper Object
@type taperob: Blender L{Object<Object.Object>} or None
@ivar key: The Key object associated with this Curve, if any.
@type key: Blender L{Key<Key.Key>}
@ivar materials: The curves's materials. Each curve can reference up to
16 materials. Empty slots in the curve's list are represented by B{None}.
B{Note}: L{Object.colbits<Object.Object.colbits>} needs to be set correctly
for each object in order for these materials to be used instead of
the object's materials.
B{Note}: The list that's returned is I{not} linked to the original curve.
curve.materials.append(material) won't do anything.
Use curve.materials += [material] instead.
@type materials: list of L{Material}s
"""
def getName():
"""
Get the name of this Curve Data object.
@rtype: string
"""
def setName(name):
"""
Set the name of this Curve Data object.
@rtype: None
@type name: string
@param name: The new name.
"""
def getPathLen():
"""
Get this Curve's path frame length, used for an animated path.
@rtype: int
@return: the path length.
"""
def setPathLen(len):
"""
Set this Curve's path length.
@rtype: None
@type len: int
@param len: the new curve's length.
"""
def getTotcol():
"""
Get the number of materials linked to the Curve.
@rtype: int
@return: number of materials linked.
"""
def setTotcol(totcol):
"""
Set the number of materials linked to the Curve. B{Note}: this method
will probably be deprecated in the future.
@rtype: None
@type totcol: int
@param totcol: number of materials linked.
@warn: It is not advisable to use this method unless you know what you
are doing; it's possible to
corrupt a .blend file if you don't know what you're doing. If you want
to change the number of materials, use the L{materials} attribute.
"""
def getFlag():
"""
Get the Curve flag value.
This item is a bitfield whose value is a combination of the following parameters.
- Bit 0 : "3D" is set
- Bit 1 : "Front" is set
- Bit 2 : "Back" is set
- Bit 3 : "CurvePath" is set.
- Bit 4 : "CurveFollow" is set.
@rtype: integer bitfield
"""
def setFlag(val):
"""
Set the Curve flag value. The flag corresponds to the Blender settings for 3D, Front, Back, CurvePath and CurveFollow. This parameter is a bitfield.
@rtype: None
@type val: integer bitfield
@param val : The Curve's flag bits. See L{getFlag} for the meaning of the individual bits.
"""
def getBevresol():
"""
Get the Curve's bevel resolution value.
@rtype: float
"""
def setBevresol(bevelresol):
"""
Set the Curve's bevel resolution value.
@rtype: None
@type bevelresol: float
@param bevelresol: The new Curve's bevel resolution value.
"""
def getResolu():
"""
Get the Curve's U-resolution value.
@rtype: float
"""
def setResolu(resolu):
"""
Set the Curve's U-resolution value. [0 - 1024]
This is used for surfaces and curves.
@rtype: None
@type resolu: float
@param resolu: The new Curve's U-resolution value.
"""
def getResolv():
"""
Get the Curve's V-resolution value.
@rtype: float
"""
def setResolv(resolv):
"""
Set the Curve's V-resolution value. [0 - 1024].
This is used for surfaces only.
@rtype: None
@type resolv: float
@param resolv: The new Curve's V-resolution value.
"""
def getWidth():
"""
Get the Curve's width value.
@rtype: float
"""
def setWidth(width):
"""
Set the Curve's width value.
@rtype: None
@type width: float
@param width: The new Curve's width value.
"""
def getExt1():
"""
Get the Curve's ext1 value.
@rtype: float
"""
def setExt1(ext1):
"""
Set the Curve's ext1 value.
@rtype: None
@type ext1: float
@param ext1: The new Curve's ext1 value.
"""
def getExt2():
"""
Get the Curve's ext2 value.
@rtype: float
"""
def setExt2(ext2):
"""
Set the Curve's ext2 value.
@rtype: None
@type ext2: float
@param ext2: The new Curve's ext2 value.
"""
def getControlPoint(numcurve,numpoint):
"""
Get the curve's control point value (B{deprecated}). The numpoint arg
is an index into the list of points and starts with 0. B{Note}: new
scripts should use the [] operator on Curves and CurNurbs. Example::
curve = Blender.Curve.Get('Curve')
p0 = curve[0][0] # get first point from first nurb
# -- OR --
nurb = curve[0] # get first nurb
p0 = nurb[0] # get nurb's first point
@type numcurve: int
@type numpoint: int
@rtype: list of floats
@return: depends upon the curve's type.
- type Bezier : a list of nine floats. Values are x, y, z for handle-1, vertex and handle-2
- type Nurb : a list of 4 floats. Values are x, y, z, w.
"""
def setControlPoint( numcurve, numpoint, controlpoint):
"""
Set the Curve's controlpoint value. The numpoint arg is an index into the list of points and starts with 0.
@rtype: None
@type numcurve: int
@type numpoint: int
@type controlpoint: list
@param numcurve: index for spline in Curve, starting from 0
@param numpoint: index for point in spline, starting from 0
@param controlpoint: The new controlpoint value.
See L{getControlPoint} for the length of the list.
"""
def appendPoint( numcurve, new_control_point ):
"""
Add a new control point to the indicated curve (B{deprecated}).
New scripts should use L{CurNurb.append()}.
@rtype: None
@type numcurve: int
@type new_control_point: list of floats or BezTriple
@param numcurve: index for spline in Curve, starting from 0
@param new_control_point: depends on curve's type.
- type Bezier: a BezTriple
- type Nurb: a list of four or five floats for the xyzw values
@raise AttributeError: throws exception if numcurve is out of range.
"""
def appendNurb( new_point ):
"""
add a new curve to this Curve. The new point is added to the new curve. Blender does not support a curve with zero points. The new curve is added to the end of the list of curves in the Curve.
@rtype: CurNurb
@return: the newly added spline
@type new_point: BezTriple or list of xyzw coordinates for a Nurb curve.
@param new_point: see L{CurNurb.append} for description of parameter.
"""
def getLoc():
"""
Get the curve's location value.
@rtype: a list of 3 floats.
"""
def setLoc(location):
"""
Set the curve's location value.
@rtype: None
@type location: list[3]
@param location: The new Curve's location values.
"""
def getRot():
"""
Get the curve's rotation value.
@rtype: a list of 3 floats.
"""
def setRot(rotation):
"""
Set the Curve's rotation value.
@rtype: None
@type rotation: list[3]
@param rotation: The new Curve's rotation values.
"""
def getSize():
"""
Get the curve's size value.
@rtype: a list of 3 floats.
"""
def setSize(size):
"""
Set the curve size value.
@rtype: None
@type size: list[3]
@param size: The new Curve's size values.
"""
def getMaterials():
"""
Returns a list of materials assigned to the Curve.
@rtype: list of Material Objects
@return: list of Material Objects assigned to the Curve.
"""
def getBevOb():
"""
Returns the Bevel Object (BevOb) assigned to the Curve.
@rtype: Blender Object or None
@return: Bevel Object (BevOb) assigned to the Curve.
"""
def setBevOb( object ):
"""
Assign a Bevel Object (BevOb) to the Curve. Passing None as the object parameter removes the bevel.
@rtype: None
@return: None
@type object: Curve type Blender Object
@param object: Blender Object to assign as Bevel Object (BevOb)
@raise TypeError: throws exception if the parameter is not a Curve type Blender Object or None
"""
def getTaperOb():
"""
Returns the Taper Object (TaperOb) assigned to the Curve.
@rtype: Blender Object or None
@return: Taper Object (TaperOb) assigned to the Curve.
"""
def setTaperOb( object ):
"""
Assign a Taper Object (TaperOb) to the Curve. Passing None as the object parameter removes the taper.
@rtype: None
@return: None
@type object: Curve type Blender Object
@param object: Blender Object to assign as Taper Object (TaperOb)
@raise TypeError: throws exception if the parameter is not a Curve type Blender Object or None
"""
def update():
"""
Updates display list for a Curve.
Used after making changes to control points.
You B{must} use this if you want to see your changes!
@rtype: None
@return: None
"""
def isNurb( curve_num ):
"""
Tells type of a CurNurb (B{deprecated}).
New scripts should use L{CurNurb.isNurb()}.
@rtype: integer
@return: Zero if curve is type Bezier, one if curve is of type Nurb.
@type curve_num: integer
@param curve_num: zero-based index into list of curves in this Curve.
@raise AttributeError: throws exception if curve_num is out of range.
"""
def isCyclic( curve_num ):
"""
Tells whether or not a CurNurb is cyclic (closed) (B{deprecated}).
New scripts should use L{CurNurb.isCyclic()}.
@rtype: boolean
@return: True if is cyclic, False if not
@type curve_num: integer
@param curve_num: zero-based index into list of curves in this Curve
@raise AttributeError: throws exception if curve_num is out of range.
"""
def switchDirection( ):
"""
Reverse the direction of a curve.
@return: None
I{B{Example:}}
# This example switches the direction of all curves on the active object.
from Blender import *
scn = Scene.GetCurrent()
ob = scn.objects.active # must be a curve
data = ob.data
for cu in data: cu.switchDirection()
"""
def getNumCurves():
"""
Get the number of curves in this Curve Data object.
@rtype: integer
"""
def getNumPoints( curve_num ):
"""
Get the number of control points in the curve (B{deprecated}).
New scripts should use the len operator (I{len(curve)}).
@type curve_num: integer
@param curve_num: zero-based index into list of curves in this Curve
@rtype: integer
"""
def getKey():
"""
Return the L{Key<Key.Key>} object containing the keyframes for this
curve, if any.
@rtype: L{Key<Key.Key>} object or None
"""
def recalc():
"""
Recalculate control point handles after a curve has been changed.
@rtype: None
"""
def __copy__ ():
"""
Make a copy of this curve
@rtype: Curve
@return: a copy of this curve
"""
class CurNurb:
"""
The CurNurb Object
==================
This object provides access to the control points of the curves that make up a Blender Curve ObData.
The CurNurb supports the python iterator protocol which means you can use a python for statement to access the points in a curve.
The CurNurb also supports the sequence protocol which means you can access the control points of a CurNurb using the [] operator.
Note that CurNurb is used for accesing poly, bezier and nurbs type curves.
@ivar flagU: The CurNurb knot flag U. See L{setFlagU} for description.
@type flagU: int
@ivar flagV: The CurNurb knot flag V. See L{setFlagU} for description.
@type flagV: int
@ivar type: The type of the curve (Poly: 0, Bezier: 1, NURBS: 4)
@type type: int
@ivar knotsU: The knot vector in the U direction. The tuple will be empty
if the curve isn't a NURB or doesn't have knots in this direction.
@type knotsU: tuple of floats
@ivar knotsV: The knot vector in the V direction. The tuple will be empty
if the curve isn't a NURB or doesn't have knots in this direction.
@type knotsV: tuple of floats
"""
def __setitem__( n, point ):
"""
Replace the Nth point in the curve. The type of the argument must match the type of the curve. List of 4 floats (optional 5th float is the tilt value in radians) for Nurbs or BezTriple for Bezier.
@rtype: None
@return: None
@type n: integer
@param n: the index of the element to replace
@type point: BezTriple or list of 4 floats (optional 5th float is the tilt value in radians)
@param point: the point that will replace the one in the curve. The point can be either a BezTriple type or a list of 4 floats in x,y,z,w (optionally tilt in radians as 5th value) format for a Nurb curve.
"""
def __getitem__( n ):
"""
Get the Nth element in the curve. For Bezier curves, that element is a BezTriple. For the rest (Poly and Nurbs), it is a list of 5 floats: x, y, z, weight, tilt (in radians). NOTE 1: This element is independent on the curve, modifying it will not affect the curve. NOTE 2: Each successive call returns a new object.
@rtype: BezTriple (Bezier Curve) or List of 5 floats [x, y, z, w, t] for Poly or Nurbs
@return: The Nth element in the curve
@type n: integer
@param n: the index of the element to return
"""
def append( new_point ):
"""
Appends a new point to a curve. This method appends points to both Bezier and Nurb curves. The type of the argument must match the type of the curve. List of 4 floats (optional 5th float is the tilt value in radians) for Nurbs or BezTriple for Bezier.
@rtype: None
@return: None
@type new_point: BezTriple or list of 4 floats (optional 5th float is the tilt value in radians)
@param new_point: the new point to be appended to the curve. The new point can be either a BezTriple type or a list of 4 floats in x,y,z,w (optionally tilt in radians as 5th value) format for a Nurb curve.
"""
def setMatIndex( index ):
"""
Sets the Material index for this CurNurb.
@rtype: None
@return: None
@type index: integer
@param index: the new value for the Material number of this CurNurb. No range checking is done.
"""
def getMatIndex():
"""
Returns the Material index for this CurNurb.
@rtype: integer
@return: integer
"""
def isNurb():
"""
Boolean method used to determine whether a CurNurb is of type Bezier or of type Nurb.
@rtype: boolean
@return: True or False
"""
def isCyclic():
"""
Boolean method checks whether a CurNurb is cyclic (a closed curve) or not.
@rtype: boolean
@return: True or False
"""
def getFlagU():
"""
Get the CurNurb knot flag U.
@rtype: integer
@return: See L{setFlagU} for description of return value.
"""
def setFlagU( flag ):
"""
Set the entire CurNurb knot flag U (knots are recalculated automatically).
The flag can be one of six values:
- 0 or 1: uniform knots
- 2 or 3: endpoints knots
- 4 or 5: bezier knots
Bit 0 controls whether or not the curve is cyclic (1 = cyclic).
@type flag: integer
@param flag: CurNurb knot flag
@rtype: None
@return: None
"""
def getFlagV():
"""
Get the CurNurb knot flag V.
@rtype: integer
@return: See L{setFlagU} for description of return value.
"""
def setFlagV( value ):
"""
Set the CurNurb knot flag V (knots are recalculated automatically).
@type value: integer
@param value: See L{setFlagU} for description of return.
@rtype: None
@return: None
"""
def getType():
"""
Get the type of the curve.
@rtype: integer
@return: 0 - Poly, 1 - Bezier, 4 - NURBS
"""
def setType( value ):
"""
Set the type of the curve and converts the curve to its new type if needed
@type value: integer
@param value: CurNurb type flag (0 - Poly, 1 - Bezier, 4 - NURBS)
@rtype: None
@return: None
"""
class SurfNurb:
"""
The SurfNurb Object
===================
This object provides access to the control points of the surfaces that make
up a Blender Curve.
The SurfNurb supports the Python iterator and sequence protocols which
means you can use a python B{for} statement or [] operator to access the
points in a surface. Points are accessed linearly; for a N-by-M UV surface,
the first N control points correspond to V=0, then second N to V=1, and so
on.
@ivar flagU: The knot flag U. Changing the knot type automatically
recalculates the knots. The flag can be one of three values:
- 0 : uniform knots
- 1 : endpoints knots
- 2 : bezier knots
@type flagU: int
@ivar flagV: The knot flag V. See L{flagU} for description.
@type flagV: int
@ivar pointsU: The number of control points in the U direction (read only).
@type pointsU: int
@ivar pointsV: The number of control points in the V direction (read only).
@type pointsV: int
@ivar cyclicU: The cyclic setting for the U direction (True = cyclic).
@type cyclicU: boolean
@ivar cyclicV: The cyclic setting for the V direction (True = cyclic).
@type cyclicV: boolean
@ivar orderU: The order setting for the U direction. Values are clamped
to the range [2:6] and not greater than the U dimension.
@type orderU: int
@ivar orderV: The order setting for the V direction. Values are clamped
to the range [2:6] and not greater than the V dimension.
@type orderV: int
"""
def __setitem__( n, point ):
"""
Set the Nth control point in the surface.
@rtype: None
@return: None
@type n: integer
@param n: the index of the point to replace
@type point: list of 4 floats (optional 5th float is the tilt value
in radians)
@param point: the point that will replace the one in the curve. The
point is list of 4 floats in x,y,z,w (optionally tilt in radians as
5th value) format.
"""
def __getitem__( n ):
"""
Get the Nth control point in the surface.
@rtype: List of 5 floats [x, y, z, w, t] for Poly or Nurbs
@return: The Nth point in the curve
@type n: integer
@param n: the index of the point to return
@note: This returned value is independent on the curve; modifying it will not affect the curve.
@note: Each successive call returns a new object.
"""

View File

@@ -0,0 +1,105 @@
CURVE Module documentation
INTRODUCTION
The Curve module gives access to the curves objects. Curves are used for many things in blender : creation of graphical objects, duplication of meshes, displacement of meshes, in IPOs for instance.
Blender has three main types of curves :
nurbs curves, each control point has three coordinates.
bezier curves, each control point has nine coordinates.
text curves, which represent graphical text objects.
functions of the module :
Get(Name:string) : returns the Curve whose name is Name.
get : same as Get
New(Name:string (optional)) : Creates a new Curve Object.
If the parameter Name is given, it will be the name of the Curve Object,
else the name will be choosen by blender.
Curve Object member functions :
getName() : Retreives the Curve Object name.
setName(Name : string) : Sets the Curve Object name.
getPathLen() : Retrieves the Curve Object path length.
setPathLen(len:int) : Sets the Curve Object path length.
getTotcol() : Retreives the parameter totcol of the Curve.
setTotcol(val:int) : Sets the parameter totcol
/*I do not know what means this parameter...*/
getFlag()Retrieves the mode of the Curve Object
setFlag(val:int) :Sets the mode of the Curve.
The mode of the curve is a combination of parameters.
Bits 0,1,2 : "Back", "Front" and "3D".
Bit 3 : "CurvePath" is set.
Bit 4 : "CurveFollow" is set.
getBevresol() : Retreives the bevel resolution of the curve.
setBevresol(val:float) : Sets the bevel resolution of the curve.
getResolu() : Retreives the U-resolution of the curve.
setResolu(val:int) : sets the U-resolution of the curve.
getResolv() : Retreives the V-resolution of the curve.
setResolv(val:int) : sets the V-resolution of the curve.
getWidth() : Retreives the bevel width of the curve.
setWidth(val:float) : Sets the bevel width.
getExt1() : Retreives the bevel height1 of the curve.
setExt1(val:float) : Sets the bevel height1 of the curve.
getExt2() : Retreives the bevel height2 of the curve.
setExt2(val:float) : Sets the bevel height2 of the curve.
getControlPoint(i:int) : Retreives the i-th control point.
Depending upon the curve type, returne a list of 4(nurbs) or 9(bez) floats.
setControlPoint(i:int, x1:float,...x4:float)
setControlPoint(i:int, x1:float,...x9:float) : Sets the i-th control point value.
getLoc() : Retreives the Curve location(from the center)
setLoc(x:float,y:float,z:float) : Sets the Curve location
getRot() : Retreives the Curve rotation(from the center)
setRot(x:float,y:float,z:float) : Sets the Curve rotation.
getSize() : Retreives the Curve size.
setSize(x:float,y:float,z:float) : Sets the Curve size.
Direct acces to the parameters values : You cann read and write the parameter XXX with the following syntax :
val = obj.XXX
or obj.XXX = val.
The possible parameters names are :"name","pathlen","resolu","resolv","width","ext1", and "ext2"
Submodules : No submodule.

View File

@@ -0,0 +1,880 @@
# Blender.Draw module and the Button PyType object
"""
The Blender.Draw submodule.
Draw
====
B{New}:
- access to ASCII values in L{events<Register>} callbacks;
- 'large' fonts for L{Text} and L{GetStringWidth}.
- Pop-up blocks with L{PupBlock}
- Color Picker button with L{ColorPicker}
This module provides access to a B{windowing interface} in Blender. Its widgets
include many kinds of buttons: push, toggle, menu, number, string, slider,
scrollbar, plus support for text drawing. It also includes keyboard keys and
mouse button code values in its dictionary, see a list after this example.
Example::
import Blender
from Blender import Draw, BGL
mystring = ""
mymsg = ""
toggle = 0
def event(evt, val): # the function to handle input events
global mystring, mymsg
if not val: # val = 0: it's a key/mbutton release
if evt in [Draw.LEFTMOUSE, Draw.MIDDLEMOUSE, Draw.RIGHTMOUSE]:
mymsg = "You released a mouse button."
Draw.Redraw(1)
return
if evt == Draw.ESCKEY:
Draw.Exit() # exit when user presses ESC
return
elif Draw.AKEY <= evt <= Draw.ZKEY: mystring += chr(evt)
elif evt == Draw.SPACEKEY: mystring += ' '
elif evt == Draw.BACKSPACEKEY and len(mystring):
mystring = mystring[:-1]
else: return # no need to redraw if nothing changed
Draw.Redraw(1)
def button_event(evt): # the function to handle Draw Button events
global mymsg, toggle
if evt == 1:
mymsg = "You pressed the toggle button."
toggle = 1 - toggle
Draw.Redraw(1)
def gui(): # the function to draw the screen
global mystring, mymsg, toggle
if len(mystring) > 90: mystring = ""
BGL.glClearColor(0,0,1,1)
BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)
BGL.glColor3f(1,1,1)
Draw.Toggle("Toggle", 1, 10, 10, 55, 20, toggle,"A toggle button")
BGL.glRasterPos2i(72, 16)
if toggle: toggle_state = "down"
else: toggle_state = "up"
Draw.Text("The toggle button is %s." % toggle_state, "small")
BGL.glRasterPos2i(10, 230)
Draw.Text("Type letters from a to z, ESC to leave.")
BGL.glRasterPos2i(20, 200)
Draw.Text(mystring)
BGL.glColor3f(1,0.4,0.3)
BGL.glRasterPos2i(340, 70)
Draw.Text(mymsg, "tiny")
Draw.Register(gui, event, button_event) # registering the 3 callbacks
All available events:
- ACCENTGRAVEKEY
- AKEY
- BACKSLASHKEY
- BACKSPACEKEY
- BKEY
- CAPSLOCKKEY
- CKEY
- COMMAKEY
- DELKEY
- DKEY
- DOWNARROWKEY
- EIGHTKEY
- EKEY
- ENDKEY
- EQUALKEY
- ESCKEY
- F10KEY
- F11KEY
- F12KEY
- F1KEY
- F2KEY
- F3KEY
- F4KEY
- F5KEY
- F6KEY
- F7KEY
- F8KEY
- F9KEY
- FIVEKEY
- FKEY
- FOURKEY
- GKEY
- HKEY
- HOMEKEY
- IKEY
- INPUTCHANGE
- INSERTKEY
- JKEY
- KEYBD
- KKEY
- LEFTALTKEY
- LEFTARROWKEY
- LEFTBRACKETKEY
- LEFTCTRLKEY
- LEFTMOUSE
- LEFTSHIFTKEY
- LINEFEEDKEY
- LKEY
- MIDDLEMOUSE
- MINUSKEY
- MKEY
- MOUSEX
- MOUSEY
- NINEKEY
- NKEY
- OKEY
- ONEKEY
- PAD0
- PAD1
- PAD2
- PAD3
- PAD4
- PAD5
- PAD6
- PAD7
- PAD8
- PAD9
- PADASTERKEY
- PADENTER
- PADMINUS
- PADPERIOD
- PADPLUSKEY
- PADSLASHKEY
- PAGEDOWNKEY
- PAGEUPKEY
- PAUSEKEY
- PERIODKEY
- PKEY
- QFULL
- QKEY
- QUOTEKEY
- Q_FIRSTTIME
- RAWKEYBD
- REDRAW
- RETKEY
- RIGHTALTKEY
- RIGHTARROWKEY
- RIGHTBRACKETKEY
- RIGHTCTRLKEY
- RIGHTMOUSE
- RIGHTSHIFTKEY
- RKEY
- SEMICOLONKEY
- SEVENKEY
- SIXKEY
- SKEY
- SLASHKEY
- SPACEKEY
- TABKEY
- THREEKEY
- TIMER0
- TIMER1
- TIMER2
- TIMER3
- TKEY
- TWOKEY
- UKEY
- UPARROWKEY
- VKEY
- WHEELDOWNMOUSE
- WHEELUPMOUSE
- WINCLOSE
- WINFREEZE
- WINQUIT
- WINTHAW
- WKEY
- XKEY
- YKEY
- ZEROKEY
- ZKEY
@note: function Button has an alias: L{PushButton}.
@warn: B{very important}: if using your script causes "Error totblock"
messages when Blender exits (meaning that memory has been leaked), this may
have been caused by an ignored return value from one of the button types. To
avoid this, assign created buttons return values to B{global} variables,
instead of ignoring them. Examples::
# avoid this, it can cause memory leaks:
Draw.Toggle(...)
Draw.Number(...)
Draw.String(...)
# this is correct -- assuming the variables are globals:
my_toggle_button = Draw.Toggle(...)
my_int_button = Draw.Number(...)
my_str_button = Draw.String(...)
@warn: Inside the windowing loop (after Draw.Register() has been executed and
before Draw.Exit() is called), don't use the redraw functions from other
modules (Blender and Window). The Draw submodule has its own Draw.Redraw() and
Draw.Draw() functions that can be used inside the windowing loop.
"""
def Exit():
"""
Exit the windowing interface.
"""
def BeginAlign():
"""
Buttons after this function will draw aligned (button layout only).
"""
def EndAlign():
"""
Use after BeginAlign() to stop aligning the buttons (button layout only).
"""
def UIBlock(draw):
"""
This function creates a popup area where buttons, labels, sliders etc can be drawn.
@type draw: function
@param draw: A function to draw to the popup area, taking no arguments: draw().
@note: The size of the popup will expand to fit the bounds of the buttons created in the draw function.
@note: Be sure to use the mouse coordinates to position the buttons under the mouse,
so the popup dosn't exit as soon as it opens.
The coordinates for buttons start 0,0 at the bottom left hand side of the screen.
@note: Within this popup, Redraw events and the registered button callback will not work.
For buttons to run events, use per button callbacks.
@note: OpenGL drawing functions wont work within this popup, for text use L{Label} rather then L{Text}
@warning: L{Menu} will not work properly within a UIBlock, this is a limitation with blenders user interface internals.
"""
def Register(draw = None, event = None, button = None):
"""
Register callbacks for windowing.
@type draw: function
@type event: function
@type button: function
@param draw: A function to draw the screen, taking no arguments: draw().
@param event: A function to handle keyboard and mouse input events, taking
two arguments: f(evt, val), where:
- 'evt' (int) is the event number;
- 'val' (int) is the value modifier. If val = 0, the event refers to a
key or mouse button being released. Otherwise it's a key/button press.
@param button: A function to handle Draw Button events, taking one argument:
f(evt), where:
- 'evt' is the button number (see the I{event} parameter in L{Button}).
@note: note that in the example at the beginning of this page Draw.Register
is called only once. It's not necessary to re-register the callbacks,
they will stay until Draw.Exit is called. It's enough to redraw the
screen, when a relevant event is caught.
@note: only during the B{event} callback: the L{Blender}.ascii variable holds
the ASCII integer value (if it exists and is valid) of the current event.
"""
def Redraw(after = 0):
"""
Queue a redraw event. Redraw events are buffered so that, regardless of how
many events are queued, the window only receives one redraw event.
@type after: int
@param after: If non-zero, the redraw is processed before other input events.
"""
def Draw():
"""
Force an immediate redraw. Forced redraws are not buffered. In other words,
the window is redrawn once every time this function is called.
"""
def Create(value):
"""
Create a default Button object.
@type value: int, float, string or 3 floats
@param value: The value to store in the button.
@rtype: Blender Button
@return: The Button created.
@note: String values must have less then 400 characters.
"""
def PushButton(name, event, x, y, width, height, tooltip = None, callback = None):
"""
Create a new (push) Button object.
@type name: string
@param name: The string to display on the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@note: This function used to be called only "Button". We added an
alternative alias to avoid a name clash with the L{Button} class/type that
caused trouble in this documentation's generation. The old name shouldn't
be deprecated, use Button or PushButton (better) at your choice.
"""
def PupMenu(name, maxrow = None):
"""
Create a pop-up menu.
The menu options are specified through the 'name' parameter, like with
L{Menu}: options are followed by a format code and separated by the '|'
character. Valid format codes are:
- %t - The option should be used as the title of the pop-up;
- %l - insert a separating line (only works if 'maxrow' isn't given);
- %xB{N} - Chosen this option, PupMenu should return the integer B{N}.
Example::
name = "OK?%t|QUIT BLENDER" # if no %xN int is set, indices start from 1
result = Draw.PupMenu(name)
if result:
Draw.PupMenu("Really?%t|Yes|No")
@type name: string
@param name: The format string to define the contents of the button.
@type maxrow: int
@param maxrow: The maximum number of rows for each column in the pop-up.
@rtype: int
@return: the chosen entry number or -1 if none was chosen.
"""
def PupIntInput(text, default, min, max):
"""
Create an integer number input pop-up.
This allows python to use Blender's integer number pop-up input.
Example::
default = 50
min = 0
max = 100
msg = "Set this value between 0 and 100"
result = Draw.PupIntInput(msg, default, min, max)
if result != None:
print result
else:
print 'no user input'
@type text: string
@param text: The text that is displayed in the pop-up.
@type default: int
@param default: The value that the pop-up is set to initially.
@type min: int
@param min: The lowest value the pop-up will allow.
@type max: int
@param max: The highest value the pop-up will allow.
@rtype: int
@return: the number chosen or None if none was chosen.
"""
def PupFloatInput(text, default, min, max, clickStep, floatLen):
"""
Create a floating point number input pop-up.
This allows python to use Blender's floating point pop-up input.
Example::
default = 50
min = 0.0
max = 10.0
clickStep = 100
floatLen = 3
msg = "Set this value between 0 and 100"
result = Draw.PupFloatInput(msg, default, min, max, clickStep, floatLen)
if result != None:
print result
else:
print 'no user input'
@type text: string
@param text: The text that is displayed in the pop-up.
@type default: float
@param default: The value that the pop-up is set to initially.
@type min: float
@param min: The lowest value the pop-up will allow.
@type max: float
@param max: The highest value the pop-up will allow.
@type clickStep: int
@param clickStep: How much is incremented per user click, 100 will increment 1.0, 10 will increment 0.1 etc.
@type floatLen: int
@param floatLen: The number of decimal places to display, between 2 and 4.
@rtype: float
@return: the number chosen or None if none was chosen.
"""
def PupStrInput(text, default, max = 20):
"""
Create a string input pop-up.
This allows python to use Blender's string pop-up input.
Example::
Blender.Draw.PupStrInput("Name:", "untitled", 25)
@type text: string
@param text: The text that is displayed in the pop-up.
@type default: string
@param default: The value that the pop-up is set to initially. If it's longer
then 'max', it's truncated.
@type max: int
@param max: The most characters the pop-up input will allow. If not given
it defaults to 20 chars. It should be in the range [1, 100].
@rtype: string
@return: The text entered by the user or None if none was chosen.
"""
def PupBlock(title, sequence):
"""
Display a pop-up block.
Possible formats for the items in the sequence parameter.
(Value are objects created with L{Create})
- string: Defines a label
- (string, Value, string): Defines a toggle button. The first string is the text on the button, the optional second string is the tooltip.
- (string, Value, min, max, string): Defines a numeric or string button, depending on the content of Value. The first string is the text on the button, the optional second string is the tooltip. I{For string, max is the maximum length of the string and min is unused.}
Example::
import Blender
text = Blender.Draw.Create("short text")
f = Blender.Draw.Create(1.0)
i = Blender.Draw.Create(2)
tog = Blender.Draw.Create(0)
block = []
block.append(("Name: ", text, 0, 30, "this is some tool tip"))
block.append("Some Label")
block.append(("Value: ", f, 0.0, 100.0))
block.append(("Value: ", i, 0, 100))
block.append(("Option", tog, "another tooltip"))
retval = Blender.Draw.PupBlock("PupBlock test", block)
print "PupBlock returned", retval
print "text\\t", text
print "float\\t", f
print "int\\t", i
print "toggle\\t", tog
@warning: On cancel, the Value objects are brought back to there initial values except for string values which will still contain the modified values.
@type title: string
@param title: The title of the block.
@param sequence: A sequence defining what the block contains.
The order of the list is the order of appearance, from top down.
@rtype: int
@return: 1 if the pop-up is confirmed, 0 otherwise
"""
def Menu(name, event, x, y, width, height, default, tooltip = None, callback = None):
"""
Create a new Menu Button object.
The menu options are specified through the 'name' of the button. Options are
I{followed} by a format code and separated by the '|' (pipe) character. Valid
format codes are:
- %t - The option should be used as the title;
- %l - Insert a separating line;
- %xB{N} - The option should set the integer B{N} in the button value.
Example::
name = "The Title %t|First Entry %x1|Second Entry %x2|Third Entry %x3"
menu = Draw.Menu(name, 2, 60, 120, 200, 40, 3, "Just a test menu.")
# note that, since default = 3, the "Third Entry"
# will appear as the default choice in the Menu.
@type name: string
@param name: The format string to define the contents of the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type default: int
@param default: The number of the option to be selected by default.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
"""
def Toggle(name, event, x, y, width, height, default, tooltip = None, callback = None):
"""
Create a new Toggle Button object.
@type name: string
@param name: The string to display on the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type default: int
@param default: The value specifying the default state:
(0 for "up", 1 for "down").
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
"""
def Slider(name, event, x, y, width, height, initial, min, max, realtime = 1,
tooltip = None, callback = None):
"""
Create a new Slider Button object.
@type name: string
@param name: The string to display on the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type initial: int or float
@type min: int or float
@type max: int or float
@param initial: The initial value.
@param min: The minimum value.
@param max: The maximum value.
@type realtime: int
@param realtime: If non-zero (the default), the slider will emit events as
it is edited.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
@note: slider callbacks will not work if the realtime setting is enabled.
"""
#def Scrollbar(event, x, y, width, height, initial, min, max, realtime = 1,
# tooltip = None):
# """
# Create a new Scrollbar Button object.
# @type event: int
# @param event: The event number to pass to the button event function when
# activated.
# @type x: int
# @type y: int
# @param x: The lower left x (horizontal) coordinate of the button.
# @param y: The lower left y (vertical) coordinate of the button.
# @type width: int
# @type height: int
# @param width: The button width.
# @param height: The button height.
# @type initial: int or float
# @type min: int or float
# @type max: int or float
# @param initial: The initial value.
# @param min: The minimum value.
# @param max: The maximum value.
# @type realtime: int
# @param realtime: If non-zero (the default), the slider will emit events as
# it is edited.
# @type tooltip: string
# @param tooltip: The button's tooltip (the string that appears when the mouse
# is kept over the button).
# @rtype: Blender Button
# @return: The Button created.
# """
def ColorPicker(event, x, y, width, height, initial, tooltip = None, callback = None):
"""
Create a new Color Picker Button object.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type initial: 3-float tuple
@param initial: The initial color value. All values must be between 0 and 1
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
@note: The color picker will not work if the Register's event function is None.
@note: Using the same button variable with more then 1 button at a time will corrupt memory.
"""
def Normal(event, x, y, width, height, initial, tooltip = None, callback = None):
"""
Create a new Normal button, this allows you to set a 3d vector by rotating a sphere.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width - non square normal buttons .
@param height: The button height.
@type initial: 3-float tuple
@param initial: The initial vector value.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
@note: The normal button will not work if the Register's event function is None.
@note: Using the same button variable with more then 1 button at a time will corrupt memory.
"""
def Number(name, event, x, y, width, height, initial, min, max, tooltip = None, callback = None):
"""
Create a new Number Button object.
@type name: string
@param name: The string to display on the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type initial: int or float
@type min: int or float
@type max: int or float
@param initial: The initial value.
@param min: The minimum value.
@param max: The maximum value.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
I{B{Example:}}
This example draws a single floating point value::
from Blender import Draw
b= Draw.Create(0.0) # Data for floating point button
def bevent(evt):
print 'My Button event:', evt
def gui():
global b
b= Draw.Number('value: ', 1000, 0,0, 200, 20, b.val, 0,10, 'some text tip')
Draw.Register(gui, None, bevent) # we are not going to worry about keyboard and mouse events
"""
def String(name, event, x, y, width, height, initial, length, tooltip = None, callback = None):
"""
Create a new String Button object.
@type name: string
@param name: The string to display on the button.
@type event: int
@param event: The event number to pass to the button event function when
activated.
@type x: int
@type y: int
@param x: The lower left x (horizontal) coordinate of the button.
@param y: The lower left y (vertical) coordinate of the button.
@type width: int
@type height: int
@param width: The button width.
@param height: The button height.
@type initial: string
@param initial: The string to display initially.
@type length: int
@param length: The maximum input length.
@type tooltip: string
@param tooltip: The button's tooltip (the string that appears when the mouse
is kept over the button).
@type callback: function
@param callback: an optional argument so this button can have its own
callback function. the function will run whenever this button is pressed.
This function must accept 2 arguments (event, val).
@rtype: Blender Button
@return: The Button created.
"""
def GetStringWidth(string, fontsize = 'normal'):
"""
Get the width in pixels of a string.
@type string: string
@param string: A string.
@type fontsize: string
@param fontsize: The size of the font: 'large', 'normal', 'small' or 'tiny'.
@rtype: int
@return: The width of I{string} with the chosen I{fontsize}.
"""
def Text(string, fontsize = 'normal'):
"""
Draw a string on the screen.
Text location is set using the OpenGL raster location functions L{BGL.glRasterPos} before the text is drawn.
This sets the text location from the lower left corner of the current window.
Text color is set using the OpenGL color functions L{BGL.glColor} before the text is drawn.
@type string: string
@param string: The text string to draw.
@type fontsize: string
@param fontsize: The size of the font: 'large', 'normal', 'small' or 'tiny'.
@rtype: int
@return: The width of I{string} drawn with the chosen I{fontsize}.
@note: For drawing text in the 3d view see the workaround in L{BGL.glRasterPos}
"""
def Label(string, x, y, w, h):
"""
Draw a text lable on the screen.
@type string: string
@param string: The text string to draw.
@rtype: None
@return: None
"""
def Image(image, x, y, zoomx=1.0, zoomy=1.0, clipx=0, clipy=0, clipw=-1, cliph=-1):
"""
Draw an image on the screen.
The image is drawn at the location specified by the coordinates (x,y). A
pair of optional zoom factors (in horizontal and vertical directions) can
be applied to the image as it is drawn, and an additional clipping rectangle
can be applied to extract a particular sub-region of the image to draw.
Note that the clipping rectangle is given in image space coordinates. In
image space, the origin is located at the bottom left, with x coordinates
increasing to the right and y coordinates increasing upwards. No matter
where the clipping rectangle is placed in image space, the lower-left pixel
drawn on the screen is always placed at the coordinates (x,y). The
clipping rectangle is itself clipped to the dimensions of the image. If
either the width or the height of the clipping rectangle are negative then
the corresponding dimension (width or height) is set to include as much of
the image as possible.
For drawing images with alpha blending with the background you will need to enable blending as shown in the example.
Example::
import Blender
from Blender import BGL, Image, Draw
myimage = Image.Load('myimage.png')
def gui():
BGL.glEnable( BGL.GL_BLEND ) # Only needed for alpha blending images with background.
BGL.glBlendFunc(BGL.GL_SRC_ALPHA, BGL.GL_ONE_MINUS_SRC_ALPHA)
Draw.Image(myimage, 50, 50)
BGL.glDisable( BGL.GL_BLEND )
def event(evt, val):
if evt == Draw.ESCKEY:
Draw.Exit()
Draw.Register(gui, event, None)
@type image: Blender.Image
@param image: The image to draw.
@type x: int
@param x: The lower left x (horizontal) position of the origin of the image.
@type y: int
@param y: The lower left y (vertical) position of the origin of the image.
@type zoomx: float
@param zoomx: The x (horizontal) zoom factor to use when drawing the image.
@type zoomy: float
@param zoomy: The y (vertical) zoom factor to use when drawing the image.
@type clipx: int
@param clipx: The lower left x (horizontal) origin of the clipping rectangle
within the image. A value of 0 indicates the left of the
image.
@type clipy: int
@param clipy: The lower left y (vertical) origin of the clipping rectangle
within the image. A value of 0 indicates the bottom of the
image.
@type clipw: int
@param clipw: The width of the clipping rectangle within the image. If this
value is negative then the clipping rectangle includes as much
of the image as possible in the x (horizontal) direction.
@type cliph: int
@param cliph: The height of the clipping rectangle within the image. If this
value is negative then the clipping rectangle includes as much
of the image as possible in the y (vertical) direction.
"""
class Button:
"""
The Button object
=================
This object represents a button in Blender's GUI.
@type val: int or float, string or 3-float tuple (depends on button type).
@ivar val: The button's value.
"""

View File

@@ -0,0 +1,590 @@
# Blender.Effect module and the Effect PyType effect
"""
The Blender.Effect submodule
B{new}: now L{Get}('objname') (without specifying second parameter: 'position') returns a list of all effects linked to object "objname".
Effect
======
INTRODUCTION
The Effect module allows you to access all the data of particle effects.
An effect can modify a mesh object using particles, where vertex of
the mesh emits particles, which can themselves emit new particles.
In the Blender internals, the effect object is just a placeholder for
the particle effect. Prior to v2.39 build and wave effects were also
supported by Blender, and the Python API supported all three types of
effects. They were removed in v2.39 when the build and wave modifiers
were implemented.
Example::
import Blender
listffects = Blender.Effect.Get()
print listeffects
eff = listeffects[0]
#we suppose the first effect is a build effect
print eff.getLen()
eff.setLen(500)
@type Flags: read-only dictionary
@var Flags: The particle effect flags. Values can be ORed.
- SELECTED: The particle effect is selected in the UI. (Read-only)
- BSPLINE: Use a B-spline formula for particle interpolation
- STATIC: Make static particles
- ANIMATED: Recalculate static particles for each rendered frame
- VERTS: Emit particles from vertices
- FACES: Emit particles from faces
- EVENDIST: Use even distribution based on face area (requires FACES)
- TRUERAND: Use true random distribution based on face area (requires FACES)
- UNBORN: Make particles appear before they are emitted
- DIED: Make particles appear after they have died
- EMESH: Render emitter mesh
@type SpeedTypes: read-only dictionary
@var SpeedTypes: The available settings for selecting particle speed vectors.
Only one setting is active at a time.
- INTENSITY: Use texture intensity
- RGB: Use RGB values
- GRADIENT: Use texture gradient
"""
def New (name):
"""
Creates a new particle effect and attaches to an object.
@type name: string
@param name: The name of object to associate with the effect. Only mesh
objects are supported.
@rtype: Blender Effect
@return: the new effect
"""
def Get (name = None, position = None):
"""
Get an Effect from Blender.
@type name: string
@param name: The name of object linked to the effect.
@type position: int
@param position: The position of the effect in the list of effects linked to the object.
@rtype: Blender Effect or a list of Blender Effects
@return: It depends on the 'objname, position' parameters:
- (): A list with all Effects in the current scene;
- (name): A list with all Effects linked to the given object;
- (name, position): The Effect linked to the given object at the given position
"""
class Effect:
"""
The Effect object
=================
This object gives access to particle effect data in Blender.
@ivar child: The number of children a particle may have.
Values are clamped to the range [1,600].
@type child: tuple of 4 ints
@ivar childMat: The materials used by the 4 generation particles.
Values are clamped to the range [1,16].
@type childMat: tuple of 4 ints
@ivar damping: The particle damping factor. This controls the rate at
which particles decelerate.
Values are clamped to the range [0.0,1.0].
@type damping: float
@ivar defvec: The x, y and z axis of the force defined by the texture.
Values are clamped to the range [-1.0,1.0].
@type defvec: tuple of 3 floats
@ivar disp: The percentage of particles displayed.
Value is clamped to the range [0,100].
@type disp: int
@ivar dispMat: The material used for the particles.
Value is clamped to the range [1,16].
@type dispMat: int
@ivar emissionTex: The texture used for texture emission.
Value is clamped to the range [1,10].
@type emissionTex: int
@ivar end: The end time of the effect.
Value is clamped to the range [1.0,30000.0].
@type end: float
@ivar flag: The flag bitfield. See L{Flags} for values.
@type flag: int
@ivar force: The constant force applied to the parts.
Values are clamped to the range [-1.0,1.0].
@type force: tuple of 3 floats
@ivar forceTex: The texture used for force.
Value is clamped to the range [1,10].
@type forceTex: int
@ivar jitter: Jitter table distribution: maximum particles per face.
Values are clamped to the range [0,200].
@type jitter: int
@ivar life: The lifetime of of the next generation of particles.
Values are clamped to the range [1.0,30000.0].
@type life: tuple of 4 floats
@ivar lifetime: The lifetime of the effect.
Value is clamped to the range [1.0,30000.0].
@type lifetime: float
@ivar mult: The probabilities of a particle having a child.
Values are clamped to the range [0.0,1.0].
@type mult: tuple of 4 floats
@ivar nabla: The nabla value.
Value is clamped to the range [0.0001,1.0].
@type nabla: float
@ivar normfac: The normal strength of the particles relative to mesh.
Value is clamped to the range [-2.0,2.0].
@type normfac: float
@ivar obfac: The strength of the particles relative to objects.
Value is clamped to the range [-1.0,1.0].
@type obfac: float
@ivar randfac: The initial random speed of the particles.
Value is clamped to the range [0.0,2.0].
@type randfac: float
@ivar randlife: The variability of the life of the particles.
Value is clamped to the range [0.0,2.0].
@type randlife: float
@ivar seed: The seed of the random number generator.
Value is clamped to the range [0,255].
@type seed: int
@ivar speedType: Controls which texture property affects particle speeds.
See L{SpeedTypes} for values and their meanings.
@type speedType: int
@ivar speedVGroup: The name of the vertex group used for speed control.
@type speedVGroup: str
@ivar sta: The start time of the effect.
Value is clamped to the range [-250.0,30000.0].
@type sta: float
@ivar staticStep: percentage of skipped particles in static display.
Value is clamped to the range [1,100].
@type staticStep: int
@ivar stype: The bitfield for vector.
@type stype: int
@ivar texfac: The initial speed of the particles caused by the texture.
Value is clamped to the range [0.0,2.0].
@type texfac: float
@ivar totpart: The total number of particles.
Value is clamped to the range [1,100000].
@type totpart: int
@ivar totkey: The total number of key positions.
Value is clamped to the range [1,100].
@type totkey: int
@ivar type: The type of the effect. Deprecated.
@type type: int
@ivar vectsize: The size of vectors associated to the particles (if any).
Value is clamped to the range [0.0,1.0].
@type vectsize: float
@ivar vGroup: The name of the vertex group used for emitted particles.
@type vGroup: str
"""
def getType():
"""
Retrieves the type of an effect object.
Deprecated, since only particle effects are supported.
@rtype: int
@return: the type of an effect object : should always return 1
(particle effect)
"""
def setType(name):
"""
Deprecated, since only particle effects are supported.
@type name: int
@param name : the new type.
@rtype: None
@return: None
"""
def getFlag():
"""
Retrieves the flag of an effect object. The flag is a bit-mask.
@rtype: int
@return: The flag of the effect is a combination of parameters. See
L{Flags} for values.
"""
def setFlag(newflag):
"""
Sets the flag of an effect object. See L{Flags} for values.
@type newflag: int
@param newflag: the new flag.
@rtype: None
@return: None
"""
def getStartTime():
"""
Retrieves the starting time of a particle effect object
@rtype: float
@return: the starting time of the effect.
"""
def setSta(newstart):
"""
Sets the starting time of an particle effect object
@type newstart: float
@param newstart: the new starting time.
@rtype: None
@return: None
"""
def getEndTime():
"""
Retrieves the end time of a particle effect object
@rtype: float
@return: the end time of the effect.
"""
def setEnd(newendrt):
"""
Sets the end time of an particle effect object
@type newendrt: float
@param newendrt: the new end time.
@rtype: None
@return: None
"""
def getLifetime():
"""
Retrieves the lifetime of a particle effect object
@rtype: float
@return: the lifetime of the effect.
"""
def setLifetime(newlifetime):
"""
Sets the lifetime of a particle effect object
@type newlifetime: float
@param newlifetime: the new lifetime.
@rtype: None
@return: None
"""
def getNormfac():
"""
Retrieves the normal strength of the particles (relatively to mesh).
@rtype: float
@return: normal strength of the particles (relatively to mesh).
"""
def setNormfac(newnormfac):
"""
Sets the normal strength of the particles (relatively to mesh).
@type newnormfac: float
@param newnormfac: the normal strength of the particles (relatively to mesh).
@rtype: None
@return: None
"""
def getObfac():
"""
Retrieves the initial strength of the particles relatively to objects.
@rtype: float
@return: initial strength of the particles (relatively to mesh).
"""
def setObfac(newobfac):
"""
Sets the initial strength of the particles relatively to objects.
@type newobfac: float
@param newobfac: the initial strength of the particles relatively to objects.
@rtype: None
@return: None
"""
def getRandfac():
"""
Retrieves the random strength applied to the particles.
@rtype: float
@return: random strength applied to the particles.
"""
def setRandfac(newrandfac):
"""
Sets the random strength applied to the particles.
@type newrandfac: float
@param newrandfac: the random strength applied to the particles.
@rtype: None
@return: None
"""
def getStype():
"""
Retrieves the vect state of an effect object.
@rtype: int
@return: the Stype (Vect) of an effect object : 0 , Vect is not enabled, 1, Vect is enabled
(particle effect)
"""
def setStype(int):
"""
@type int : int
@param int : state of the Stype : 0 not enabled, 1 enabled.
@rtype: None
@return: None
"""
def getTexfac():
"""
Retrieves the strength applied to the particles from the texture of the object.
@rtype: float
@return: strength applied to the particles from the texture of the object.
"""
def setTexfac(newtexfac):
"""
Sets the strength applied to the particles from the texture of the object.
@type newtexfac: float
@param newtexfac: the strength applied to the particles from the texture of the object.
@rtype: None
@return: None
"""
def getRandlife():
"""
Retrieves the variability of the life of the particles.
@rtype: float
@return: variability of the life of the particles.
"""
def setRandlife(newrandlife):
"""
Sets the variability of the life of the particles.
@type newrandlife: float
@param newrandlife: the variability of the life of the particles.
@rtype: None
@return: None
"""
def getNabla():
"""
Retrieves the sensibility of the particles to the variations of the texture.
@rtype: float
@return: sensibility of the particles to the variations of the texture.
"""
def setNabla(newnabla):
"""
Sets the sensibility of the particles to the variations of the texture.
@type newnabla: float
@param newnabla: the sensibility of the particles to the variations of the texture.
@rtype: None
@return: None
"""
def getVectsize():
"""
Retrieves the size of the vector which is associated to the particles.
@rtype: float
@return: size of the vector which is associated to the particles.
"""
def setVectsize(newvectsize):
"""
Sets the size of the vector which is associated to the particles.
@type newvectsize: float
@param newvectsize: the size of the vector which is associated to the particles.
@rtype: None
@return: None
"""
def getTotpart():
"""
Retrieves the total number of particles.
@rtype: int
@return: the total number of particles.
"""
def setTotpart(newtotpart):
"""
Sets the the total number of particles.
@type newtotpart: int
@param newtotpart: the the total number of particles.
@rtype: None
@return: None
"""
def getTotkey():
"""
Retrieves the number of keys associated to the particles (kind of degree of freedom)
@rtype: int
@return: number of keys associated to the particles.
"""
def setTotkey(newtotkey):
"""
Sets the number of keys associated to the particles.
@type newtotkey: int
@param newtotkey: number of keys associated to the particles.
@rtype: None
@return: None
"""
def getSeed():
"""
Retrieves the random number generator seed.
@rtype: int
@return: current seed value.
"""
def setSeed(newseed):
"""
Sets the random number generator seed.
@type newseed: int
@param newseed: new seed value.
@rtype: None
@return: None
"""
def getForce():
"""
Retrieves the force applied to the particles.
@rtype: tuple of three floats
@return: force applied to the particles.
"""
def setForce(newforce):
"""
Sets the force applied to the particles.
@type newforce: tuple of 3 floats
@param newforce: force applied to the particles.
@rtype: None
@return: None
"""
def getMult():
"""
Retrieves the probabilities of a particle having a child.
@rtype: tuple of 4 floats
@return: probabilities of a particle having a child.
"""
def setMult(newmult):
"""
Sets the probabilities of a particle having a child.
@type newmult: tuple of 4 floats
@param newmult: probabilities of a particle having a child.
@rtype: None
@return: None
"""
def getLife():
"""
Retrieves the average life of the particles (4 generations)
@rtype: tuple of 4 floats
@return: average life of the particles (4 generations)
"""
def setLife(newlife):
"""
Sets the average life of the particles (4 generations).
@type newlife: tuple of 4 floats
@param newlife: average life of the particles (4 generations).
@rtype: None
@return: None
"""
def getChild():
"""
Retrieves the average number of children of the particles (4 generations).
@rtype: tuple of 4 ints
@return: average number of children of the particles (4 generations).
"""
def setChild(newchild):
"""
Sets the average number of children of the particles (4 generations).
@type newchild: tuple of 4 ints
@param newchild: average number of children of the particles (4 generations).
@rtype: None
@return: None
"""
def getMat():
"""
Retrieves the indexes of the materials associated to the particles (4 generations).
@rtype: tuple of 4 ints
@return: indexes of the materials associated to the particles (4 generations).
"""
def setMat(newmat):
"""
Sets the indexes of the materials associated to the particles (4 generations).
@type newmat: tuple of 4 ints
@param newmat: the indexes of the materials associated to the particles (4 generations).
@rtype: None
@return: None
"""
def getDefvec():
"""
Retrieves the x, y and z components of the force defined by the texture.
@rtype: tuple of 3 floats
@return: x, y and z components of the force defined by the texture.
"""
def setDefvec(newdefvec):
"""
Sets the x, y and z components of the force defined by the texture.
@type newdefvec: tuple of 3 floats
@param newdefvec: the x, y and z components of the force defined by the
texture.
@rtype: None
@return: None
"""
def getParticlesLoc():
"""
Gets the location of each particle at the current time in worldspace.
@rtype: A list of vector or a list of vector lists.
@return: The coordinates of each particle at the current time.
If the "Vect" option is enabled a list Vector pairs will be returned with a start and end point for each particle.
When static particles are enabled, a list of lists will be returned, each item a strand of particles.
Example::
import Blender
from Blender import Effect, Object
scn= Blender.Scene.GetCurrent()
ob= scn.getActiveObject()
effect= ob.effects[0]
particles= effect.getParticlesLoc()
# Check that particles are points only (not static and not vectors)
if not effect.getFlag() & Effect.Flags.STATIC or not effect.getStype():
for pt in particles:
ob_empty= scn.objects.new('Empty')
ob_empty.setLocation(pt)
else: # Particles will be a list
for pt in particles:
for pt_item in pt:
ob_empty= scn.objects.new('Empty')
ob_empty.setLocation(pt_item)
Example::
# Converts particles into a mesh with edges for strands
from Blender import Scene, Mathutils, Effect, Mesh, Object
scn= Scene.GetCurrent()
ob= scn.getActiveObject()
me= Mesh.New()
effects= Effect.Get()
for eff in effects:
for p in eff.getParticlesLoc():
# p is either a vector or a list of vectors. me.verts.extend() will deal with either
print p
me.verts.extend(p)
if type(p)==list: # Are we a strand or a pair, then add edges.
if len(p)>1:
edges= [(i, i+1) for i in range(len(me.verts)-len(p), len(me.verts)-1)]
me.edges.extend( edges )
print len(me.verts)
ob= scn.objects.new(me)
"""

View File

@@ -0,0 +1,257 @@
EFFECT Module documentation
INTRODUCTION
The module effect allows you to access all the data of an effect.
An effect can modify an object (typically a mesh) in three different ways.
a) the build effect : makes the mesh appear progressively.
b) the wave effect : waves appear on the mesh (which should be fine-grained)
c) the particle effect : every vertex of the mesh emits particles,
which can themselves emit new particles. This effect is the most parameterizable.
In the blender internals, the effect object is just a placeholder for the "real"
effect, which can be a wave, particle or build effect. The python API follows
this structure : the Effect module grants access to (the few) data which
are shared between all effects. It has three submodules : Wave, Build, Particle
, which grant r/w access to the real parameters of these effects.
functions of the module :
Get(Name:string,pos:int) : returns the pos-th Effect associated
to the object whose name is Name.
get : same as Get
New(Type:string ) : Creates and returns a new Effect Object.
The parameter Type can take the values "particle", "wave" or "build"
Effect object member functions :
getType() : Retrieves the type of the Effect Object.
setType(val:int) : Sets the type of the Effect Object.
The possible values of the type are :
0 : effect build.
1 : effect particle.
2 : effect wave.
getFlag()Retrieves the flag of the Effect Object
setFlag(val:int) :Sets the flag
The flag of the effect is a combination of parameters, whose semantics depend upon the effect type.
All types :
Bit 0 : set to 1 if the effect is selected in the effects window.
Wave effect :
Bits 1,2,3 : set to 1 if the button "X", "Y" or "Cycl" is clicked.
Particle effect :
Bits 1,2,3 : set to 1 if the button "Bspline", "Static" or "Face" is clicked.
Submodules : Wave, Build, Particle.
Wave module
functions of the module :
Get(Name:string,pos:int) : returns the pos-th wave Effect associated to the object whose name is Name.
get : same as Get
New( ) : Creates and returns a new Wave Object.
Wave object member functions :
getStartx() : returns the startx parameter of the wave object.
setStartx(val:int) : sets the startx parameter of the wave object.
getStarty() : returns the starty parameter of the wave object.
setStarty(val:int) : sets the starty parameter of the wave object.
getHeight() : returns the height parameter of the wave object.
setHeight(val:int) : sets the height parameter of the wave object.
getWidth() : returns the width parameter of the wave object.
setWidth(val:int) : sets the width parameter of the wave object.
getNarrow() : returns the narrow parameter of the wave object.
setNarrow(val:int) : sets the narrow parameter of the wave object.
getSpeed() : returns the speed parameter of the wave object.
setSpeed(val:int) : sets the speed parameter of the wave object.
getMinfac() : returns the minfac parameter of the wave object.
setMinfac(val:int) : sets the minfac parameter of the wave object.
getDamp() : returns the damp parameter of the wave object.
setDamp(val:int) : sets the damp parameter of the wave object.
getTimeoffs() : returns the timeoffs parameter of the wave object.
setTimeoffs(val:int) : sets the time offset parameter of the wave object.
getLifetime() : returns the lifetime parameter of the wave object.
setLifetime(val:int) : sets the lifetime parameter of the wave object.
The Object.attr syntax
Wave attributes can be read/written with the object.attr syntax.
Example :
w = Blender.Wave.Get("Obname",3) #retrieves the 4th effect associated to the object named Obname
a = w.speed # a is now the value corresponding to the speed of the effect
w.speed = 42 # the speed of the effect is now equal to 42
The parameter can take these values : "lifetime","timeoffs","damp","minfac","speed","narrow","width","height","startx","starty"
Build module
functions of the module :
Get(Name:string,pos:int) : returns the pos-th build Effect associated to the object whose name is Name.
get(Name:string,pos:int) : same as Get
New( ) : Creates and returns a new Build Object.
Build object member functions :
getLen() : returns the length of the effect (in frames).
setLen(val:float) : sets the length of the effect (in frames).
getSfra() : returns the starting frame of the effect.
setSfra(val:float) : sets the starting frame of the effect.
The Object.attribute syntax
The attribute can take these values : "sfra","len".
Particle module
functions of the module :
Get(Name:string,pos:int) : returns the pos-th particle Effect associated to the object whose name is Name.
get(Name:string,pos:int) : same as Get
New( ) : Creates and returns a new Effect Object.
Particle object member functions :
getStartTime() : returns the start time of the particle effect (in frames).
setStartTime(val:float) : sets the start time of the particle effect (in frames).
getEndTime() : returns the end time of the particle effect (in frames).
setEndTime(val:float) : sets the end time of the particle effect (in frames).
getLifeTime() : returns the life time of the particles.
setLifeTime(val:float) : sets the life time of the particles.
getNormfac() : returns the normal strength of the particles (relatively to mesh).
setNormfac(val:float) : sets the normal strength of the particles(relatively to mesh).
getObfac() : returns the initial of the particles relatively to objects.
setObfac(val:float) : sets the initial of the particles relatively to objects.
getRandfac() : returns the initial random speed of the particles.
setRandfac(val:float) : sets the initial random speed of the particles.
getTexfac() : returns the initial speed of the particles caused by the texture.
setTexfac(val:float) : sets the initial speed of the particles caused by the texture.
getRandlife() : returns the variability of the life of the particles.
setRandlife(val:float) : sets the variability of the life of the particles.
getNabla() : returns the dimension of the area for gradient computation.
setNabla(val:float) : sets the dimension of the area for gradient computation.
getTotpart() : returns the total number of particles.
setTotpart(val:int) : sets the total number of particles.
getTotkey() : returns the number of key positions.
setTotkey(val:int) : sets the number of key positions.
getSeed() : returns the seed of the RNG.
setSeed(val:int) : sets the seed of the RNG.
getSeed() : returns the x,y,z components of the constant force applied to the particles.
setSeed(valx:float,valy:float,valz:float) : sets the x,y,z components of the constant force applied to the particles.
getMult() : returns the 4 probabilities of a particle having a child.
setMult(val1:float,val2:float,val3:float,val4:float) : sets the 4 probabilities of a particle having a child.
getLife() : returns the lifespan of the 4 generation particles.
setLife(val1:float,val2:float,val3:float,val4:float) : sets the lifespan of the 4 generation particles.
getMat() : returns the material used by the 4 generation particles.
setMat(val1:float,val2:float,val3:float,val4:float) : sets the material used by the 4 generation particles.
getChild() : returns the number of children a particle may have.
setChild(val1:float,val2:float,val3:float,val4:float) : sets the number of children a particle may have.
getDefvec() : returns the x, y and z axis of the force defined by the texture.
setDefvec(val1:float,val2:float,val3:float) : sets the x, y and z axis of the force defined by the texture.
The Object.attribute syntax
The attribute can take these values : "seed","nabla","sta","end","lifetime","normfac","obfac","randfac","texfac","randlife","vectsize","totpart","force","mult","life","child","mat","defvec".

View File

@@ -0,0 +1,69 @@
# Blender.Text3d.Font module and the Font PyType object
"""
The Blender.Text3d.Font subsubmodule.
Text3d.Font Objects
===================
This module provides access to B{Font} objects in Blender.
Example::
import Blender
from Blender import Text3d
# Load a font
myfont= Text3d.Font.Load('/usr/share/fonts/ttf/verdana.ttf')
#
for font in Text3d.Font.Get():
print font.name, font.filename, font.packed
"""
def Load (filename):
"""
Create a new Text3d.Font object.
@type filename: string
@param filename: file of the font
@rtype: Blender Text3d.Font
@return: The created Text3d.Font Data object.
"""
def Get (name = None):
"""
Get the Text3d.Font object(s) from Blender.
@type name: string
@param name: The name of the Text3d object.
@rtype: Blender Text3d or a list of Blender Text3ds
@return: It depends on the 'name' parameter:
- (name): The Text3d object with the given name;
- (): A list with all Font objects in the current .blend file.
"""
class Font:
"""
The Text3d.Font object
======================
This object gives access Blender's B{Font} objects
@ivar filename: The filename (path) of the file loaded into this Font.
@type filename: string
@ivar packed: Boolean, True when the sample is packed (readonly).
@type packed: string
"""
def pack():
"""
Packs the sound into the current blend file.
@note: An error will be raised if the sound is already packed or the filename path does not exist.
@returns: nothing
@rtype: none
"""
def unpack(mode):
"""
Unpacks the sound to the samples filename.
@param mode: One of the values in Blender.UnpackModes dict.
@note: An error will be raised if the sound is not packed or the filename path does not exist.
@returns: nothing
@rtype: none
@type mode: int
"""

View File

@@ -0,0 +1,97 @@
# Blender.Geometry module and its subtypes
"""
The Blender.Geometry submodule.
Geometry
========
This new module provides access to a geometry function.
"""
def PolyFill(polylines):
"""
Takes a list of polylines and calculates triangles that would fill in the polylines.
Multiple lines can be used to make holes inside a polyline, or fill in 2 seperate lines at once.
@type polylines: List of lists containing vectors, each representing a closed polyline.
@rtype: list
@return: a list if tuples each a tuple of 3 ints representing a triangle indexing the points given.
@note: 2D Vectors will have an assumed Z axis of zero, 4D Vectors W axis is ignored.
@note: The order of points in a polyline effect the direction returned triangles face, reverse the order of a polyline to flip the normal of returned faces.
I{B{Example:}}
The example below creates 2 polylines and fills them in with faces, then makes a mesh in the current scene::
import Blender
Vector= Blender.Mathutils.Vector
# Outline of 5 points
polyline1= [Vector(-2.0, 1.0, 1.0), Vector(-1.0, 2.0, 1.0), Vector(1.0, 2.0, 1.0), Vector(1.0, -1.0, 1.0), Vector(-1.0, -1.0, 1.0)]
polyline2= [Vector(-1, 1, 1.0), Vector(0, 1, 1.0), Vector(0, 0, 1.0), Vector(-1.0, 0.0, 1.0)]
fill= Blender.Geometry.PolyFill([polyline1, polyline2])
# Make a new mesh and add the truangles into it
me= Blender.Mesh.New()
me.verts.extend(polyline1)
me.verts.extend(polyline2)
me.faces.extend(fill) # Add the faces, they reference the verts in polyline 1 and 2
scn = Blender.Scene.GetCurrent()
ob = scn.objects.new(me)
Blender.Redraw()
"""
def LineIntersect2D(vec1, vec2, vec3, vec4):
"""
Takes 2 lines vec1, vec2 for the 2 points of the first line and vec2, vec3 for the 2 points of the second line.
@rtype: Vector
@return: a 2D Vector for the intersection or None where there is no intersection.
"""
def ClosestPointOnLine(pt, vec1, vec2):
"""
Takes 2 lines vec1, vec2 for the 2 points of the first line and vec2, vec3 for the 2 points of the second line.
@rtype: tuple
@return: a tuple containing a vector and a float, the vector is the closest point on the line, the float is the position on the line, between 0 and 1 the point is on the line.
"""
def PointInTriangle2D(pt, tri_pt1, tri_pt2, tri_pt3):
"""
Takes 4 vectors (one for the test point and 3 for the triangle)
This is a 2d function so only X and Y are used, Z and W will be ignored.
@rtype: bool
@return: True or False depending on the points intersection.
"""
def BoxPack2D(boxlist):
"""
Takes a list of 2D boxes and packs them into a square.
Each box in boxlist must be a list of at least 4 items - [x,y,w,h], after running this script,
the X and Y values in each box will be moved to packed, non overlapping locations.
Example::
# Make 500 random boxes, pack them and make a mesh from it
from Blender import Geometry, Scene, Mesh
import random
boxes = []
for i in xrange(500):
boxes.append( [0,0, random.random()+0.1, random.random()+0.1] )
boxsize = Geometry.BoxPack2D(boxes)
print 'BoxSize', boxsize
me = Mesh.New()
for x in boxes:
me.verts.extend([(x[0],x[1], 0), (x[0],x[1]+x[3], 0), (x[0]+x[2],x[1]+x[3], 0), (x[0]+x[2],x[1], 0) ])
v1= me.verts[-1]
v2= me.verts[-2]
v3= me.verts[-3]
v4= me.verts[-4]
me.faces.extend([(v1,v2,v3,v4)])
scn = Scene.GetCurrent()
scn.objects.new(me)
@note: Each boxlist item can be longer then 4, the extra items are ignored and stay untouched.
@rtype: tuple
@return: a tuple pair - (width, height) of all the packed boxes.
"""

View File

@@ -0,0 +1,127 @@
# Blender.Group module and the Group PyType object
"""
The Blender.Group submodule.
Group
=====
This module provides access to B{Group} data in Blender.
Example::
# Make Dupli's Real, as a python script.
from Blender import *
scn= Scene.GetCurrent()
for ob in scn.objects:
print 'Object Group Settings'
print ob.name, ob.type
print 'enableDupVerts:', ob.enableDupVerts
print 'enableDupFrames:', ob.enableDupFrames
print 'enableDupGroup:', ob.enableDupGroup
print 'DupGroup:', ob.DupGroup
dupe_obs= ob.DupObjects
print 'num dup obs:', len(dupe_obs)
for dup_ob, dup_matrix in dupe_obs:
print '\tDupOb', dup_ob.name
scn.objects.new(dup_ob.data)
new_ob.setMatrix(dup_matrix)
new_ob.sel= 1 # select all real instances.
ob.sel=0 # Desel the original object
Window.RedrawAll()
Example::
# Make a new group with the selected objects, and add an instance of this group.
from Blender import *
scn= Scene.GetCurrent()
# New Group
grp= Group.New('mygroup')
grp.objects= scn.objects
# Instance the group at an empty using dupligroups
ob= scn.objects.new(None)
ob.enableDupGroup= True
ob.DupGroup= grp
Window.RedrawAll()
Example::
# Remove all non mesh objects from a group.
from Blender import *
scn= Scene.GetCurrent()
# New Group
grp= Group.Get('mygroup')
for ob in list(grp.objects): # Convert to a list before looping because we are removing items
if ob.type != 'Mesh':
grp.objects.unlink(ob)
"""
def New (name = None):
"""
Make a new empty group, name optional, default is "Group"
@type name: string
@param name: The name of the new group.
@rtype: Blender Group
@return: A Empty Blender Group object
"""
def Get (name = None):
"""
Get the Group object(s) from Blender.
@type name: string
@param name: The name of the Group object.
@rtype: Blender Group or a list of Blender Groups
@return: It depends on the I{name} parameter:
- (name): The Group object called I{name}, Exception if it is not found.
- (): A list with all Group objects in the current blend file.
"""
def Unlink (group):
"""
Unlink (delete) this group from Blender.
@Note: No objects will be removed, just the group that references them.
@type group: group
@param group: A group to remove from this blend file, does not remove objects that this group uses.
"""
class Group:
"""
The Group object
================
This object gives access to Groups in Blender.
@ivar layers: Layer bitmask for this group.
@type layers: int
@ivar objects: Objects that this group uses.
This is a sequence with-list like access so use list(grp.objects) if you need to use a list (where grp is a group).
The groups objects can be set by assigning a list or iterator of objects to the groups objects.
objects.link() and objects.unlink() also work with the the objects iterator just like with lists.
B{Note}: append() and remove() have been deprecated and replaced by link() and unlink(),
after Blender 2.43 append() and remove() will not be available.
@type objects: custom object sequence
"""
def __copy__ ():
"""
Make a copy of this group
@rtype: Group
@return: a copy of this group
"""
import id_generics
Group.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,130 @@
class IDGroup:
"""
The IDGroup Type
================
This type supports both iteration and the []
operator to get child ID properties.
You can also add new properties using the [] operator.
For example::
group['a float!'] = 0.0
group['an int!'] = 0
group['a string!'] = "hi!"
group['an array!'] = [0, 0, 1.0, 0]
group['a subgroup!] = {"float": 0.0, "an int": 1.0, "an array": [1, 2],
"another subgroup": {"a": 0.0, "str": "bleh"}}
Note that for arrays, the array type defaults to int unless a float is found
while scanning the template list; if any floats are found, then the whole
array is float.
You can also delete properties with the del operator. For example:
del group['property']
To get the type of a property, use the type() operator, for example::
if type(group['bleh']) == str: pass
To tell if the property is a group or array type, import the Blender.Types module and test
against IDGroupType and IDArrayType, like so::
from Blender.Types import IDGroupType, IDArrayType.
if type(group['bleghr']) == IDGroupType:
(do something)
@ivar name: The name of the property
@type name: string
"""
def pop(item):
"""
Pop an item from the group property.
@type item: string
@param item: The item name.
@rtype: can be dict, list, int, float or string.
@return: The removed property.
"""
def update(updatedict):
"""
Updates items in the dict, similar to normal python
dictionary method .update().
@type updatedict: dict
@param updatedict: A dict of simple types to derive updated/new IDProperties from.
@rtype: None
@return: None
"""
def keys():
"""
Returns a list of the keys in this property group.
@rtype: list of strings.
@return: a list of the keys in this property group.
"""
def values():
"""
Returns a list of the values in this property group.
Note that unless a value is itself a property group or an array, you
cannot change it by changing the values in this list, you must change them
in the parent property group.
For example,
group['some_property'] = new_value
. . .is correct, while,
values = group.values()
values[0] = new_value
. . .is wrong.
@rtype: list of strings.
@return: a list of the values in this property group.
"""
def iteritems():
"""
Implements the python dictionary iteritmes method.
For example::
for k, v in group.iteritems():
print "Property name: " + k
print "Property value: " + str(v)
@rtype: an iterator that spits out items of the form [key, value]
@return: an iterator.
"""
def convert_to_pyobject():
"""
Converts the entire property group to a purely python form.
@rtype: dict
@return: A python dictionary representing the property group
"""
class IDArray:
"""
The IDArray Type
================
@ivar type: returns the type of the array, can be either IDP_Int or IDP_Float
"""
def __getitem__(index):
pass
def __setitem__(index, value):
pass
def __len__():
pass

View File

@@ -0,0 +1,374 @@
# Blender.Image module and the Image PyType object
"""
The Blender.Image submodule.
Image
=====
B{New}: L{Image.clampX}, L{Image.clampY}.
This module provides access to B{Image} objects in Blender.
Example::
import Blender
from Blender import Image
#
image = Image.Load("/path/to/my/image.png") # load an image file
print "Image from", image.getFilename(),
print "loaded to obj", image.getName())
image.setXRep(4) # set x tiling factor
image.setYRep(2) # set y tiling factor
print "All Images available now:", Image.Get()
@type Sources: readonly dictionary
@var Sources: The available Image Source.
- STILL: Single image file
- MOVIE: Movie file
- SEQUENCE: Multiple image files, as sequence
- GENERATED: Generated image
"""
def Load (filename):
"""
Load the image called 'filename' into an Image object.
@type filename: string
@param filename: The full path to the image file.
@rtype: Blender Image
@return: A Blender Image object with the data from I{filename}.
"""
def New (name, width, height, depth):
"""
Create a new Image object.
@type name: string
@param name: The name of the new Image object.
@type width: int
@param width: The width of the new Image object, between 1 and 5000.
@type height: int
@param height: The height of the new Image object, between 1 and 5000.
@type depth: int
@param depth: The colour depth of the new Image object. (8:Grey, 24:RGB, 32:RGBA). (Not implimented yet, all new images will be 24bit)
@rtype: Blender Image
@return: A new Blender Image object.
"""
def Get (name = None):
"""
Get the Image object(s) from Blender.
@type name: string
@param name: The name of the Image object.
@rtype: Blender Image or a list of Blender Images
@return: It depends on the I{name} parameter:
- (name): The Image object called I{name}, None if not found;
- (): A list with all Image objects in the current scene.
"""
def GetCurrent ():
"""
Get the currently displayed Image from Blenders UV/Image window.
When multiple images are displayed, the last active UV/Image windows image is used.
@rtype: Blender Image
@return: The Current Blender Image, If there is no current image it returns None.
"""
from IDProp import IDGroup, IDArray
class Image:
"""
The Image object
================
This object gives access to Images in Blender.
@ivar filename: The filename (path) to the image file loaded into this Image
object.
@type filename: string
@ivar size: The [width, height] dimensions of the image (in pixels).
@type size: list
@ivar depth: The pixel depth of the image. [8, 16, 18, 24, 32]
@type depth: int
@ivar xrep: Texture tiling: the number of repetitions in the x (horizontal)
axis. [1, 16].
@ivar yrep: Texture tiling: the number of repetitions in the y (vertical)
axis [1, 16].
@type xrep: int
@type yrep: int
@ivar start: Texture's animation start frame [0, 128].
@type start: int
@ivar end: Texture's animation end frame [0, 128].
@type end: int
@ivar speed: Texture's animation speed [1, 100].
@type speed: int
@ivar packed: True when the Texture is packed (readonly).
@type packed: boolean
@ivar has_data: True when the image has pixel data (readonly).
@type has_data: boolean
@ivar fields: enable or disable the fields option for this image.
@type fields: boolean
@ivar fields_odd: enable or disable the odd fields option for this image.
@type fields_odd: boolean
@ivar antialias: enable or disable the antialias option for this image.
@type antialias: boolean
@ivar bindcode: Texture's bind code (readonly).
@type bindcode: int
@ivar source: Image source type. See L{the Sources dictionary<Sources>} .
@type source: int
@ivar clampX: When true the image will not tile horizontally.
@type clampX: bool
@ivar clampY: When true the image will not tile vertically.
@type clampY: bool
"""
def getName():
"""
Get the name of this Image object.
@rtype: string
"""
def getFilename():
"""
Get the filename of the image file loaded into this Image object.
@rtype: string
"""
def getSize():
"""
Get the [width, height] dimensions (in pixels) of this image.
@rtype: list of 2 ints
"""
def getDepth():
"""
Get the pixel depth of this image.
@rtype: int
"""
def getPixelF(x, y):
"""
Get the the colors of the current pixel in the form [r,g,b,a].
Returned values are floats normalized to 0.0 - 1.0.
Pixel coordinates are in the range from 0 to N-1. See L{getMaxXY}
@returns: [ r, g, b, a]
@rtype: list of 4 floats
@type x: int
@type y: int
@param x: the x coordinate of pixel.
@param y: the y coordinate of pixel.
"""
def getPixelI(x, y):
"""
Get the the colors of the current pixel in the form [r,g,b,a].
Returned values are ints normalized to 0 - 255.
Pixel coordinates are in the range from 0 to N-1. See L{getMaxXY}
@returns: [ r, g, b, a]
@rtype: list of 4 ints
@type x: int
@type y: int
@param x: the x coordinate of pixel.
@param y: the y coordinate of pixel.
"""
def getMaxXY():
"""
Get the x & y size for the image. Image coordinates range from 0 to size-1.
@returns: [x, y]
@rtype: list of 2 ints
"""
def getMinXY():
"""
Get the x & y origin for the image. Image coordinates range from 0 to size-1.
@returns: [x, y]
@rtype: list of 2 ints
"""
def getXRep():
"""
Get the number of repetitions in the x (horizontal) axis for this Image.
This is for texture tiling.
@rtype: int
"""
def getYRep():
"""
Get the number of repetitions in the y (vertical) axis for this Image.
This is for texture tiling.
@rtype: int
"""
def getBindCode():
"""
Get the Image's bindcode. This is for texture loading using BGL calls.
See, for example, L{BGL.glBindTexture} and L{glLoad}.
@rtype: int
"""
def getStart():
"""
Get the Image's start frame. Used for animated textures.
@rtype: int
"""
def getEnd():
"""
Get the Image's end frame. Used for animated textures.
@rtype: int
"""
def getSpeed():
"""
Get the Image's speed (fps). Used for animated textures.
@rtype: int
"""
def reload():
"""
Reloads this image from the filesystem. If used within a loop you need to
redraw the Window to see the change in the image, e.g. with
Window.RedrawAll().
@warn: if the image file is corrupt or still being written, it will be
replaced by a blank image in Blender, but no error will be returned.
@returns: None
"""
def glLoad():
"""
Load this image's data into OpenGL texture memory, if it is not already
loaded (image.bindcode is 0 if it is not loaded yet).
@note: Usually you don't need to call this method. It is only necessary
if you want to draw textured objects in the Scripts window and the
image's bind code is zero at that moment, otherwise Blender itself can
take care of binding / unbinding textures. Calling this method for an
image with nonzero bind code simply returns the image's bind code value
(see L{getBindCode}).
@rtype: int
@returns: the texture's bind code.
"""
def glFree():
"""
Delete this image's data from OpenGL texture memory, only (the image itself
is not removed from Blender's memory). Internally, glDeleteTextures (see
L{BGL.glDeleteTextures}) is used, but this method also updates Blender's
Image object so that its bind code is set to 0. See also L{Image.glLoad},
L{Image.getBindCode}.
"""
def setName(name):
"""
Set the name of this Image object.
@type name: string
@param name: The new name.
"""
def setFilename(name):
"""
Change the filename of this Image object.
@type name: string
@param name: The new full filename.
@warn: use this with caution and note that the filename is truncated if
larger than 160 characters.
"""
def setXRep(xrep):
"""
Texture tiling: set the number of x repetitions for this Image.
@type xrep: int
@param xrep: The new value in [1, 16].
"""
def setYRep(yrep):
"""
Texture tiling: set the number of y repetitions for this Image.
@type yrep: int
@param yrep: The new value in [1, 16].
"""
def setStart(start):
"""
Get the Image's start frame. Used for animated textures.
@type start: int
@param start: The new value in [0, 128].
"""
def setEnd(end):
"""
Set the Image's end frame. Used for animated textures.
@type end: int
@param end: The new value in [0, 128].
"""
def setSpeed(speed):
"""
Set the Image's speed (fps). Used for animated textures.
@type speed: int
@param speed: The new value in [1, 100].
"""
def setPixelF(x, y, (r, g, b,a )):
"""
Set the the colors of the current pixel in the form [r,g,b,a].
Color values must be floats in the range 0.0 - 1.0.
Pixel coordinates are in the range from 0 to N-1. See L{getMaxXY}
@type x: int
@type y: int
@type r: float
@type g: float
@type b: float
@type a: float
@returns: nothing
@rtype: none
"""
def setPixelI(x, y, (r, g, b, a)):
"""
Set the the colors of the current pixel in the form [r,g,b,a].
Color values must be ints in the range 0 - 255.
Pixel coordinates are in the range from 0 to N-1. See L{getMaxXY}
@type x: int
@type y: int
@type r: int
@type g: int
@type b: int
@type a: int
@returns: nothing
@rtype: none
"""
def save():
"""
Saves the current image to L{filename}
@note: Saving to a directory that doent exist will raise an error.
@note: Saving a packed image will make a unique (numbered) name if the file alredy exists. Remove the file first to be sure it will not be renamed.
@returns: None
"""
def pack():
"""
Packs the image into the current blend file.
Since 2.44 new images without valid filenames can be packed.
If the image is alredy packed, it will be repacked.
@returns: nothing
@rtype: none
"""
def unpack(mode):
"""
Unpacks the image to the images filename.
@param mode: One of the values in L{Blender.UnpackModes}.
@note: An error will be raised if the image is not packed or the filename path does not exist.
@returns: nothing
@rtype: none
@type mode: int
"""
def makeCurrent():
"""
Set the currently displayed Image from Blenders UV/Image window.
When multiple images are displayed, the last active UV/Image windows image is used.
@warn: Deprecated, set bpy.data.images.active = image instead.
@rtype: bool
@return: True if the current image could be set, if no window was available, return False.
"""
import id_generics
Image.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,437 @@
# Blender.Ipo module and the Ipo PyType object
"""
The Blender.Ipo submodule
B{New}:
- Ipo updates to both the program and Bpython access.
- access to Blender's new Ipo driver capabilities.
- Ipo now supports the mapping operator [] to access IpoCurves
This module provides access to the Ipo Data in Blender. An Ipo is composed of
several IpoCurves, and an IpoCurve is composed of several BezTriples.
Example::
from Blender import Ipo
ipo = Ipo.Get('ObIpo') # retrieves an Ipo object
ipo.name = 'ipo1' # change the Ipo's name
icu = ipo[Ipo.OB_LOCX] # request X Location Ipo curve
if icu != None and len(icu.bezierPoints) > 0: # if curve exists and has BezTriple points
val = icu[2.5] # get the curve's value at time 2.5
ipo[Ipo.OB_LOCX] = None # delete the Ipo curve
Each type of Ipo has different types Ipocurves. With the exception of Shape
Key Ipos, constants are used to specify all Ipocurves. There are two ways
to tell which Ipo curves go with which Ipo type:
- all constants start with a two-character identifier for their Ipo type;
for example, "OB_LOCX" is the LocX curve for an Object Ipo
- each Ipo now has a read-only attribute L{Ipo.curveConsts}, which returns
the valid Ipo curve types for that specific Ipo
The valid IpoCurve constants are:
1. Material Ipo: MA_R, MA_G, MA_B, MA_SPECR, MA_SPECG, MA_SPECB,
MA_MIRR, MA_MIRG, MA_MIRB, MA_REF, MA_ALPHA, MA_EMIT, MA_AMB,
MA_SPEC, MA_HARD, MA_SPTRA, MA_IOR, MA_MODE, MA_HASIZE, MA_TRANSLU,
MA_RAYMIR, MA_FRESMIR, MA_FRESMIRI, MA_FRESTRA, MA_FRESTRAI,
MA_TRAGLOW, MA_OFSX, MA_OFSY, MA_OFSZ, MA_SIZEX, MA_SIZEY, MA_SIZEZ,
MA_TEXR, MA_TEXG, MA_TEXB, MA_DEFVAR, MA_COL, MA_NOR, MA_VAR, MA_DISP
2. Lamp Ipo: LA_ENERG, LA_R, LA_G, LA_B, LA_DIST, LA_SPOSI, LA_SPOBL,
LA_QUAD1, LA_QUAD2, LA_HAINT, LA_OFSX, LA_OFSY, LA_OFSZ, LA_SIZEX,
LA_SIZEY, LA_SIZEZ, LA_TEXR, LA_TEXG, LA_TEXB, LA_DEFVAR, LA_COL
3. World Ipo: WO_HORR, WO_HORG, WO_HORB, WO_ZENR, WO_ZENG, WO_ZENB,
WO_EXPOS, WO_MISI, WO_MISDI, WO_MISSTA, WO_MISHI, WO_STARR,
WO_STARB, WO_STARG, WO_STARDI, WO_STARSI, WO_OFSX, WO_OFSY,
WO_OFSZ, WO_SIZEX, WO_SIZEY, WO_SIZEZ, WO_TEXR, WO_TEXG,
WO_TEXB, WO_DEFVAR, WO_COL, WO_NOR, WO_VAR
4. Camera Ipo: CA_LENS, CA_CLSTA, CA_CLEND, CA_APERT, CA_FDIST
5. Object Ipo: OB_LOCX, OB_LOCY, OB_LOCZ, OB_DLOCX, OB_DLOCY, OB_DLOCZ,
OB_ROTX, OB_ROTY, OB_ROTZ, OB_DROTX, OB_DROTY, OB_DROTZ,
OB_SIZEX, OB_SIZEY, OB_SIZEZ, OB_DSIZEX, OB_DSIZEY, OB_DSIZEZ,
OB_LAYER, OB_TIME, OB_COLR, OB_COLG, OB_COLB, OB_COLA,
OB_FSTRENG, OB_FFALL, OB_RDAMP, OB_DAMPING, OB_PERM
6. Curve Ipo: CU_SPEED
7. Constraint Ipo: CO_INF
8. Texture Ipo: TE_NSIZE, TE_NDEPTH, TE_NTYPE, TE_TURB, TE_VNW1, TE_VNW2,
TE_VNW3, TE_VNW4, TE_MINKMEXP, TE_DISTM, TE_COLT, TE_ISCALE,
TE_DISTA, TE_MGTYPE, TE_MGH, TE_LACU, TE_OCT, TE_MGOFF,
TE_MGGAIN, TE_NBASE1, TE_NBASE2, TE_COLR, TE_COLG, TE_COLB,
TE_BRIGHT, TE_CONTRAS
9. Pose/Action Ipo: PO_LOCX, PO_LOCY, PO_LOCZ, PO_SIZEX, PO_SIZEY,
PO_SIZEZ, PO_QUATW, PO_QUATX, PO_QUATY, PO_QUATZ
10. Sequence Ipo: SQ_FAC
Shape Key Ipos are handled differently from other Ipos. The user can rename
the curves, so string are used to access them instead of constants. The
L{Ipo.curveConsts} attribute for Shape Key Ipos returns a list of all defined
key names.
"""
def New (type, name):
"""
Creates a new Ipo.
@type type: string
@type name: string
@param type: The Ipo's blocktype. Depends on the object the Ipo will be
linked to. Currently supported types are Object, Camera, World,
Material, Texture, Lamp, Action, Constraint, Sequence, Curve, Key.
@param name: The name for this Ipo.
@rtype: Blender Ipo
@return: The created Ipo.
"""
def Get (name = None):
"""
Get the Ipo from Blender.
@type name: string
@param name: The name of the requested Ipo, or nothing.
@rtype: Blender Ipo or a list of Blender Ipos
@return: It depends on the 'name' parameter:
- (name): The Ipo with the given name;
- (): A list with all Ipos in the current scene.
"""
class Ipo:
"""
The Ipo object
==============
This object gives access to Ipo data from all objects in Blender.
@Note: Blender Materials, Lamps and Worlds have I{texture channels} which
allow the user to assign textures to them. The Blender Ipo Window allows
the user to access the IpoCurves for these channels by specifying a number
between 0 and 9 (the number appears next to the Ipo type in the window
header). Prior to Version 2.42, the BPy API did not allow users to access
these texture channels in a predictable manner. A new attribute named
L{channel} was added to the API in Version 2.42 to correct this problem.
The current channel setting has an effect on the operators B{[]}, B{len()}
and others. For example, suppose a Material has three IpoCurves
(R, G, and B), and two texture channels (numbered 0 and 1), and furthermore
channel 0 has one Ipocurve (Col). The IpoCurve Col can only be
"seen" through the API when B{ipo.channel} is 0. Setting B{ipo.channel} to
1 will cause this curve to be ignored by B{len(ipo)}::
from Blender import Ipo
ipo = Ipo.Get('MatIpo')
for channel in xrange(2):
ipo.channel = channel
print 'channel is',channel
print ' len is',len(ipo)
names = dict([(x[1],x[0]) for x in ipo.curveConsts.items()])
for curve in [Ipo.MA_R,Ipo.MA_COL]:
print ' ',names[curve],'is',curve in ipo
will output::
channel is 0
len is 4
MA_R is True
MA_COL is True
channel is 1
len is 3
MA_R is True
MA_COL is False
@ivar curves: Ipo curves currently defined for the Ipo.
@type curves: list of Ipocurves.
@ivar curveConsts: The valid Ipo curves for this Ipo. These can be used
by the [] mapping operator. The value
depends on the Ipo curve type. If the Ipo is any type other than a Key or
Shape Ipo, this attribute returns a set of constants that can be
used to specify a particular curve. For Key or Shape Ipos, the attribute
returns a list of all defined keys by name.
@type curveConsts: constant or list of strings. Read-only.
@ivar channel: the current texture channel for Blender object which support
textures (materials, lamps and worlds). Returns None if the Ipo does
not support texture channels. Value must be in the range [0,9].
@type channel: int or None
"""
def __contains__():
"""
The "in" operator for Ipos. It returns B{True} if the specified
IpoCurve exists for the Ipo. This operator B{should not} be used to
test for whether a curve constant is valid for a particular Ipo type.
Many constants for different Ipo types have the same value, and it is
the constant's value used internally.
No exceptions are raised if the argument is not a valid curve constant or
or string, nor does the operator return B{True} when the curve
constant is valid but does not currently exist. As such, it should only be
used to test for specific curves when the Ipo type is known::
ipo = Object.Get('Cube').ipo # get Object-type Ipo
if ipo:
print Ipo.OB_LOCX in ipo # prints "True" if 'LocX' curve exists
print Ipo.MA_R in ipo # also prints "True" since MA_R and OB_LOCX are have the same value
print 'hiccup' in ipo # always prints "False" since argument is not a constant
@return: see above.
@rtype: Boolean
"""
def __getitem__():
"""
This operator is similar to the Python dictionary mapping operator [],
except that the user cannot assign arbitrary keys. Each Ipo type has
a pre-defined set of IpoCurves which may or may not exist at a given time. This operator
will either return an IpoCurve object if the specified curve exists,
return None if the curve does not exists, or throws a KeyError exception
if the curve is not valid for this Ipo type.
@return: an IpoCurve object if it exists
@rtype: IpoCurve or None
@raise KeyError: an undefined IpoCurve was specified for the Ipo
"""
def __iter__():
"""
Iterator for Ipos. It returns all the defined IpoCurve objects associated
with the Ipo. For example::
from Blender import Ipo
ipo = Ipo.Get()
if len(ipo) > 0:
ipo = ipo[0]
print 'ipo name is',ipo.name
for icu in ipo:
print ' curve name is',icu.name
might result in::
ipo name is ObIpo
curve name is LocX
curve name is LocY
curve name is LocZ
@return: an IpoCurve object
@rtype: IpoCurve
"""
def __len__():
"""
Returns the number of curves defined for the Ipo.
@return: number of defined IpoCurves
@rtype: int
"""
def getName():
"""
Gets the name of the Ipo (B{deprecated}). See the L{name} attribute.
@rtype: string
@return: the name of the Ipo.
"""
def setName(newname):
"""
Sets the name of the Ipo (B{deprecated}). See the L{name} attribute.
@type newname: string
@rtype: None
@return: None
"""
def getCurves():
"""
Gets all the IpoCurves of the Ipo (B{deprecated}). Use the
L{iterator operator []<__iter__>} instead.
@rtype: list of IpoCurves
@return: A list (possibly empty) containing all the IpoCurves associated
to the Ipo object.
"""
def getCurve(curve):
"""
Return the specified IpoCurve (B{deprecated}). Use the L{mapping
operator B{[]}<__getitem__>} instead.
If the curve does not exist in the Ipo,
None is returned. I{curve} can be either a string or an integer,
denoting either the name of the Ipo curve or its internal adrcode.
The possible Ipo curve names are:
1. Camera Ipo: Lens, ClSta, ClEnd, Apert, FDist.
2. Material Ipo: R, G, B, SpecR, SpecG, SpecB, MirR, MirG, MirB, Ref,
Alpha, Emit, Amb, Spec, Hard, SpTra, Ior, Mode, HaSize, Translu,
RayMir, FresMir, FresMirI, FresTra, FresTraI, TraGlow, OfsX, OfsY,
OfsZ, SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var,
Disp.
3. Object Ipo: LocX, LocY, LocZ, dLocX, dLocY, dLocZ, RotX, RotY, RotZ,
dRotX, dRotY, dRotZ, SizeX, SizeY, SizeZ, dSizeX, dSizeY, dSizeZ,
Layer, Time, ColR, ColG, ColB, ColA, FStreng, FFall, Damping,
RDamp, Perm.
4. Lamp Ipo: Energ, R, G, B, Dist, SpoSi, SpoBl, Quad1, Quad2, HaInt.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StaR, StaG, StaB, StarDi, StarSi, OfsX, OfsY, OfsZ,
SizeX, SizeY, SizeZ, TexR, TexG, TexB, DefVar, Col, Nor, Var.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StarR, StarB, StarG, StarDi, StarSi, OfsX, OfsY, OfsZ,i
SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var.
6. Texture Ipo: NSize, NDepth, NType, Turb, Vnw1, Vnw2, Vnw3, Vnw4,
MinkMExp, DistM, ColT, iScale, DistA, MgType, MgH, Lacu, Oct,
MgOff, MgGain, NBase1, NBase2.
7. Curve Ipo: Speed.
8. Action Ipo: LocX, LocY, LocZ, SizeX, SizeY, SizeZ, QuatX, QuatY,
QuatZ, QuatW.
9. Sequence Ipo: Fac.
10. Constraint Ipo: Inf.
The adrcode for the Ipo curve can also be given; this is useful for
accessing curves for Shape Key Ipos. The adrcodes for Shape Key Ipo are
numbered consecutively starting at 0.
@type curve : string or int
@rtype: IpoCurve object
@return: the corresponding IpoCurve, or None.
@raise ValueError: I{curve} is not a valid name or adrcode for this Ipo
type.
"""
def addCurve(curvename):
"""
Add a new curve to the Ipo object. The possible values for I{curvename} are:
1. Camera Ipo: Lens, ClSta, ClEnd, Apert, FDist.
2. Material Ipo: R, G, B, SpecR, SpecG, SpecB, MirR, MirG, MirB, Ref,
Alpha, Emit, Amb, Spec, Hard, SpTra, Ior, Mode, HaSize, Translu,
RayMir, FresMir, FresMirI, FresTra, FresTraI, TraGlow, OfsX, OfsY,
OfsZ, SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var,
Disp.
3. Object Ipo: LocX, LocY, LocZ, dLocX, dLocY, dLocZ, RotX, RotY, RotZ,
dRotX, dRotY, dRotZ, SizeX, SizeY, SizeZ, dSizeX, dSizeY, dSizeZ,
Layer, Time, ColR, ColG, ColB, ColA, FStreng, FFall, Damping,
RDamp, Perm.
4. Lamp Ipo: Energ, R, G, B, Dist, SpoSi, SpoBl, Quad1, Quad2, HaInt.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StaR, StaG, StaB, StarDi, StarSi, OfsX, OfsY, OfsZ,
SizeX, SizeY, SizeZ, TexR, TexG, TexB, DefVar, Col, Nor, Var.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StarR, StarB, StarG, StarDi, StarSi, OfsX, OfsY, OfsZ,i
SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var.
6. Texture Ipo: NSize, NDepth, NType, Turb, Vnw1, Vnw2, Vnw3, Vnw4,
MinkMExp, DistM, ColT, iScale, DistA, MgType, MgH, Lacu, Oct,
MgOff, MgGain, NBase1, NBase2.
7. Curve Ipo: Speed.
8. Action Ipo: LocX, LocY, LocZ, SizeX, SizeY, SizeZ, QuatX, QuatY,
QuatZ, QuatW.
9. Sequence Ipo: Fac.
10. Constraint Ipo: Inf.
For Key IPOs, the name must be an existing KeyBlock name. Use
L{curveConsts} to determine the set of valid names.
@type curvename : string
@rtype: IpoCurve object
@return: the corresponding IpoCurve, or None.
@raise ValueError: I{curvename} is not valid or already exists
"""
def delCurve(curvename):
"""
Delete an existing curve from the Ipo object (B{deprecated}).
Use the L{mapping operator B{[]}<__getitem__>} instead::
from Blender import Ipo
ipo = Ipo.Get('ObIpo')
ipo[Ipo.LOCX] = None
@type curvename : string
@rtype: None
@return: None.
"""
def getBlocktype():
"""
Gets the blocktype of the Ipo.
@rtype: int
@return: the blocktype of the Ipo.
"""
def setBlocktype(newblocktype):
"""
Sets the blocktype of the Ipo.
@type newblocktype: int
@rtype: None
@return: None
@warn: 'newblocktype' should not be changed unless you really know what
you are doing ...
"""
def getRctf():
"""
Gets the rctf of the Ipo.
Kind of bounding box...
@rtype: list of floats
@return: the rctf of the Ipo.
"""
def setRctf(newrctf):
"""
Sets the rctf of the Ipo.
@type newrctf: four floats.
@rtype: None
@return: None
@warn: rctf should not be changed unless you really know what you are
doing ...
"""
def getNcurves():
"""
Gets the number of curves of the Ipo (B{deprecated}). Use
L{len(ipo)<__len__>} instead.
@rtype: int
@return: the number of curve of the Ipo.
"""
def getCurveBP(curvepos):
"""
This method is unsupported. BPoint Ipo curves are not implemented.
Calling this method throws a NotImplementedError exception.
@raise NotImplementedError: this method B{always} raises an exception
"""
def getBeztriple(curvepos,pointpos):
"""
Gets a beztriple of the Ipo (B{deprecated}). B{Note}:
Use L{IpoCurve.bezierPoints<IpoCurve.IpoCurve.bezierPoints>} instead.
@type curvepos: int
@param curvepos: the position of the curve in the Ipo.
@type pointpos: int
@param pointpos: the position of the point in the curve.
@rtype: list of 9 floats
@return: the beztriple of the Ipo, or an error is raised.
"""
def setBeztriple(curvepos,pointpos,newbeztriple):
"""
Sets the beztriple of the Ipo (B{deprecated}). B{Note}: use
L{IpoCurve.bezierPoints<IpoCurve.IpoCurve.bezierPoints>} to get a
BezTriple point, then use the
L{BezTriple} API to set the point's attributes.
@type curvepos: int
@param curvepos: the position of the curve in the Ipo.
@type pointpos: int
@param pointpos: the position of the point in the curve.
@type newbeztriple: list of 9 floats
@param newbeztriple: the new value for the point
@rtype: None
@return: None
"""
def getCurveCurval(curvepos):
"""
Gets the current value of a curve of the Ipo (B{deprecated}). B{Note}:
new scripts should use L{IpoCurve.evaluate()<IpoCurve.IpoCurve.evaluate>}.
@type curvepos: int or string
@param curvepos: the position of the curve in the Ipo or the name of the
curve
@rtype: float
@return: the current value of the selected curve of the Ipo.
"""
def EvaluateCurveOn(curvepos,time):
"""
Gets the value at a specific time of a curve of the Ipo (B{deprecated}).
B{Note}: new scripts should use
L{IpoCurve.evaluate()<IpoCurve.IpoCurve.evaluate>}.
@type curvepos: int
@param curvepos: the position of the curve in the Ipo.
@type time: float
@param time: the desired time.
@rtype: float
@return: the current value of the selected curve of the Ipo at the given
time.
"""
import id_generics
Ipo.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,226 @@
# Blender.IpoCurve module and the IpoCurve PyType object
"""
The Blender.IpoCurve submodule
B{New}:
- IpoCurves supports the operator [], which accesses the value of
curves at a given time.
This module provides access to the IpoCurve data in Blender. An Ipo is
composed of several IpoCurves, and an IpoCurve are composed of several
BezTriples.
Example::
import Blender
ipo = Blender.Ipo.Get('ObIpo') # retrieves an Ipo object
ipo.name = 'ipo1' # change the Ipo's name
icu = ipo[Blender.Ipo.OB_LOCX] # request X Location Ipo curve object
if icu != None and len(icu.bezierPoints) > 0: # if curve exists and has BezTriple points
val = icu[2.5] # get the curve's value at time 2.5
@type ExtendTypes: readonly dictionary
@var ExtendTypes: The available IpoCurve extend types.
- CONST - curve is constant beyond first and last knots
- EXTRAP - curve maintains same slope beyond first and last knots
- CYCLIC - curve values repeat beyond first and last knots
- CYCLIC_EXTRAP - curve values repeat beyond first and last knots,
but while retaining continuity
@type InterpTypes: readonly dictionary
@var InterpTypes: The available IpoCurve interpolation types.
- CONST - curve remains constant from current BezTriple knot
- LINEAR - curve is linearly interpolated between adjacent knots
- BEZIER - curve is interpolated by a Bezier curve between adjacent knots
"""
class IpoCurve:
"""
The IpoCurve object
===================
This object gives access to generic data from all Ipo curves objects
in Blender.
Important Notes for Rotation Ipo Curves:\n
For the rotation Ipo curves, the y values for points are in units of 10
degrees. For example, 45.0 degrees is stored as 4.50 degrees. These are the
same numbers you see in the Transform Properties pop-up menu ( NKey ) in
the IPO Curve Editor window. Positive rotations are in a counter-clockwise
direction, following the standard convention.
@ivar driver: Status of the driver. 1= on, 0= object, 2= python expression.
@type driver: int
@ivar driverObject: Object used to drive the Ipo curve.
@type driverObject: Blender Object or None
@ivar driverExpression: Python expression used to drive the Ipo curve. [0 - 127 chars]
@type driverExpression: string
@ivar sel: The selection state of this curve.
@type sel: bool
@ivar driverChannel: Object channel used to drive the Ipo curve.
Use module constants: IpoCurve.LOC_X, IpoCurve.LOC_Y, IpoCurve.LOC_Z,
IpoCurve.ROT_X, IpoCurve.ROT_Y, IpoCurve.ROT_Z, IpoCurve.SIZE_X,
IpoCurve.SIZE_Y, IpoCurve.SIZE_Z
@type driverChannel: int
@ivar name: The IpoCurve data name.
@type name: string
@ivar bezierPoints: The list of the curve's bezier points.
@type bezierPoints: list of BezTriples.
@ivar interpolation: The curve's interpolation mode. See L{InterpTypes} for
values.
@type interpolation: int
@ivar extend: The curve's extend mode. See L{ExtendTypes} for values.
B{Note}: Cyclic Ipo curves never reach the end value. If the first and
last bezier points do not have the same y coordinate, the value of the
curve when it "cycles" is that of the first point. If a user wants to
get the value of the final curve point, read the final point from the
curve::
ipo = Blender.Object.Get('Cube').ipo
icu = ipo['LocX']
endtime,endvalue = icu.bezierPoints[-1].pt
@type extend: int
"""
def __getitem__ (time):
"""
Returns the value of the curve at a particular time.
@type time: float
@param time: time (Vertex X) on the curve
@rtype: float
@return: value (Vertex Y) corresponding to the given time
"""
def __setitem__ (time):
"""
Sets the value (Vertex Y) of the curve at a particular time.
@type time: float
@param time: time (Vertex X) on the curve
"""
def setExtrapolation(extendmode):
"""
Sets the extend mode of the curve (B{deprecated}). B{Note}: new scripts
should use the L{extend} attribute instead.
@type extendmode: string
@param extendmode: the extend mode of the curve.
Can be Constant, Extrapolation, Cyclic or Cyclic_extrapolation.
@rtype: None
@return: None
"""
def getExtrapolation():
"""
Gets the extend mode of the curve (B{deprecated}). B{Note}: new scripts
should use the L{extend} attribute instead.
@rtype: string
@return: the extend mode of the curve. Can be Constant, Extrapolation, Cyclic or Cyclic_extrapolation.
"""
def setInterpolation(interpolationtype):
"""
Sets the interpolation type of the curve (B{deprecated}). B{Note}:
new scripts should use the L{interpolation} attribute instead.
@type interpolationtype: string
@param interpolationtype: the interpolation type of the curve. Can be Constant, Bezier, or Linear.
@rtype: None
@return: None
"""
def getInterpolation():
"""
Gets the interpolation type of the curve (B{deprecated}). B{Note}:
new scripts should use the L{interpolation} attribute instead.
@rtype: string
@return: the interpolation type of the curve. Can be Constant, Bezier, or Linear.
"""
def append(point):
"""
Adds a Bezier point to a IpoCurve.
@type point: BezTriple or tuple of 2 floats
@param point: Can either be a BezTriple, or the x and y coordinates of
the Bezier knot point.
@rtype: None
@return: None
"""
def addBezier(coordlist):
"""
Adds a Bezier point to a curve B{deprecated}). B{Note}: new scripts
should use L{append} instead.
@type coordlist: tuple of (at least) 2 floats
@param coordlist: the x and y coordinates of the new Bezier point.
@rtype: None
@return: None
"""
def delBezier(index):
"""
Deletes a Bezier point from a curve.
@type index: integer
@param index: the index of the Bezier point. Negative values index from the end of the list.
@rtype: None
@return: None
"""
def recalc():
"""
Recomputes the curve after changes to control points.
@rtype: None
@return: None
"""
def getName():
"""
Returns the name of the Ipo curve (B{deprecated}). B{Note}:
new scripts should use the L{name} attribute instead.
The name can be:
1. Camera Ipo: Lens, ClSta, ClEnd, Apert, FDist.
2. Material Ipo: R, G, B, SpecR, SpecG, SpecB, MirR, MirG, MirB, Ref,
Alpha, Emit, Amb, Spec, Hard, SpTra, Ior, Mode, HaSize, Translu,
RayMir, FresMir, FresMirI, FresTra, FresTraI, TraGlow, OfsX, OfsY,
OfsZ, SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var,
Disp.
3. Object Ipo: LocX, LocY, LocZ, dLocX, dLocY, dLocZ, RotX, RotY, RotZ,
dRotX, dRotY, dRotZ, SizeX, SizeY, SizeZ, dSizeX, dSizeY, dSizeZ,
Layer, Time, ColR, ColG, ColB, ColA, FStreng, FFall, Damping,
RDamp, Perm.
4. Lamp Ipo: Energ, R, G, B, Dist, SpoSi, SpoBl, Quad1, Quad2, HaInt.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StaR, StaG, StaB, StarDi, StarSi, OfsX, OfsY, OfsZ,
SizeX, SizeY, SizeZ, TexR, TexG, TexB, DefVar, Col, Nor, Var.
5. World Ipo: HorR, HorG, HorB, ZenR, ZenG, ZenB, Expos, Misi, MisDi,
MisSta, MisHi, StarR, StarB, StarG, StarDi, StarSi, OfsX, OfsY, OfsZ,i
SizeX, SizeY, SizeZ, texR, texG, texB, DefVar, Col, Nor, Var.
6. Texture Ipo: NSize, NDepth, NType, Turb, Vnw1, Vnw2, Vnw3, Vnw4,
MinkMExp, DistM, ColT, iScale, DistA, MgType, MgH, Lacu, Oct,
MgOff, MgGain, NBase1, NBase2.
7. Curve Ipo: Speed.
8. Action Ipo: LocX, LocY, LocZ, SizeX, SizeY, SizeZ, QuatX, QuatY,
QuatZ, QuatW.
9. Sequence Ipo: Fac.
10. Constraint Ipo: Inf.
@rtype: string
@return: the name of the Ipo curve.
"""
def getPoints():
"""
Returns all the points of the IpoCurve (B{deprecated}).
B{Note}: new scripts should use the L{bezierPoints} attribute instead.
@rtype: list of BezTriples
@return: the points of the Ipo curve.
"""
def evaluate( time ):
"""
Compute the value of the Ipo curve at a particular time (B{deprecated}).
B{Note}: new scripts should use L{icu[time]<__getitem__>} instead.
@type time: float
@param time: value along the X axis
@rtype: float
@return: the Y value of the curve at the given time
"""

View File

@@ -0,0 +1,66 @@
IPO Module documentation
INTRODUCTION
The module ipo allows you to access all the data of an ipo.
The most important part(s) of an ipo is its ipocurve(s). The ipocurve has a set of bezier points (defined by 9 coordinates). The ipo module grants the user read/write access to these points.
functions of the module :
Get(Name:string) : returns the Ipo associated whose name is Name.
get : same as Get
New(Name:string , idcode:int ) : Creates and returns a new Ipo Object.
The parameters are mandatory. If the name is already used, blender will change it to name.XXX (XXX is an integer)
Ipo object member functions :
getName() : Retrieves the name of the Ipo Object.
setName(newname:string) : Sets the name of the Ipo Object.
getBlocktype() : Retrieves the blocktype of the Ipo Object.
setBlocktype(newblocktype:string) : Sets the blocktype of the Ipo Object.
getShowkey() : Retrieves the showkey of the Ipo Object.
setShowkey(val:int) : Sets the showkey of the Ipo Object.
getPad() : Retrieves the pad of the Ipo Object.
setPad(val:int) : Sets the pad of the Ipo Object.
getRctf() : Retrieves the rctf of the Ipo Object.
setRctf(val:int) : Sets the rctf of the Ipo Object.
I do not fully understand the meaning of these parameters.
getNcurves() : returns the number of ipocurves the ipo object contains.
getBP() : returns the basepoint of the ipo object (generally NULL)
getCurveCurval(numcurve:int) : returns the current value of the ipo curve number numcurve.
getCurveBeztriple(numcurve:int,numpoint:int) : returns a list of 9 floats, which are the coordinates of the control point number numpoint of the ipocurve number numcurve.
setCurveBeztriple(numcurve:int,numpoint:int,newvalues : list of 9 floats) : sets the coordinates of the control point number numpoint of the ipocurve number numcurve to newvalues. (the z coordinate should be 0, but blender does not complain if non null values are passed)
Example :
import Blender
d = Blender.Ipo.Get('ObIpo') # hope there is an ipo named "ObIpo"...Else create it before.

View File

@@ -0,0 +1,124 @@
# Blender.Key module and the Key and KeyBlock PyType objects
"""
The Blender.Key submodule.
This module provides access to B{Key} objects in Blender.
@type Types: readonly dictionary
@var Types: The type of a key owner, indicating the type of data in the
data blocks.
- MESH - the key is a Mesh key; data blocks contain
L{NMVert<NMesh.NMVert>} vertices.
- CURVE - the key is a Curve key; data blocks contains either
L{BezTriples<BezTriple.BezTriple>} or points (represented by a list of
3 floating point numbers).
- LATTICE - the key is a Lattice key; data blocks contain
BPoints, each point represented by a list of 3 floating point numbers.
"""
def Get(name = None):
"""
Get the named Key object from Blender. If the name is omitted, it
will retrieve a list of all keys in Blender.
@type name: string
@param name: the name of the requested key
@return: If name was given, return that Key object (or None if not
found). If a name was not given, return a list of every Key object
in Blender.
"""
class Key:
"""
The Key object
==============
An object with keyframes (L{Lattice}, L{NMesh} or
L{Curve}) will contain a Key object representing the
keyframe data.
@ivar ipo: Key Ipo. Contains the Ipo if one is assigned to the
object, B{None} otherwise. Setting to B{None} clears the current Ipo.
@type ipo: Blender Ipo
@ivar value: The value of the key. Read-only.
@type value: float
@ivar type: An integer from the L{Types} dictionary
representing the Key type. Read-only.
@type type: int
@ivar blocks: A list of KeyBlocks for the key. Read-only.
@type blocks: Blender KeyBlock.
@ivar relative: Indicates whether the key is relative(=True) or normal.
@type relative: bool
"""
def getIpo():
"""
Get the L{Ipo} object associated with this key.
"""
def getBlocks():
"""
Get a list of L{KeyBlock}s, containing the keyframes defined for
this Key.
"""
class KeyBlock:
"""
The KeyBlock object
===================
Each Key object has a list of KeyBlocks attached, each KeyBlock
representing a keyframe.
@ivar curval: Current value of the corresponding IpoCurve. Read-only.
@type curval: float
@ivar name: The name of the Keyblock. Truncated to 32 characters.
@type name: string
@ivar pos: The position of the keyframe.
@type pos: float
@ivar slidermin: The minimum value for the action slider.
Value is clamped to the range [-10.0,10.0].
@type slidermin: float
@ivar slidermax: The maximum value for the action slider.
Value is clamped to the range [-10.0,10.0].
@type slidermax: float
@ivar vgroup: The assigned VGroup for the Key Block.
@type vgroup: string
@ivar data: The data of the KeyBlock (see L{getData}). This
attribute is read-only.
@type data: varies
"""
def getData():
"""
Get the data of a KeyBlock, as a list of data items. Each item
will have a different data format depending on the type of this
Key.
Note that prior to 2.45 the behaviour of this function
was different (and very wrong). Old scripts might need to be
updated.
- Mesh keys have a list of L{Vectors<Mathutils.Vector>} objects in the data
block.
- Lattice keys have a list of L{Vectors<Mathutils.Vector>} objects in the data
block.
- Curve keys return either a list of tuples, eacn containing
four L{Vectors<Mathutils.Vector>} (if the curve is a Bezier curve),
or otherwise just a list of L{Vectors<Mathutils.Vector>}.
For bezier keys, the first three vectors in the tuple are the Bezier
triple vectors, while the fourth vector's first element is the curve tilt
(the other two elements are reserved and are currently unused).
For non-Bezier keys, the first three elements of the returned vector is
the curve handle point, while the fourth element is the tilt.
A word on relative shape keys; relative shape keys are not actually
stored as offsets to the base shape key (like you'd expect). Instead,
each shape key stores an entire model (actually the state of the mesh
vertices after exiting editmode with any given key active).
The additive offset for a shape key is calculated (when needed) by
comparing the shape key with its base key, which is always the very
first in the keyblock list.
"""

View File

@@ -0,0 +1,521 @@
# Blender.Lamp module and the Lamp PyType object
"""
The Blender.Lamp submodule.
B{New}: L{Lamp.clearScriptLinks} accepts a parameter now.
Lamp Data
=========
This module provides control over B{Lamp Data} objects in Blender.
Example::
from Blender import Lamp, Scene
l = Lamp.New('Spot') # create new 'Spot' lamp data
l.setMode('Square', 'Shadow') # set these two lamp mode flags
scn = Scene.GetCurrent()
ob = scn.objects.new(l)
@type Types: read-only dictionary
@var Types: The lamp types.
- 'Lamp': 0
- 'Sun' : 1
- 'Spot': 2
- 'Hemi': 3
- 'Area': 4
- 'Photon': 5
@type Modes: read-only dictionary
@var Modes: The lamp modes. Modes may be ORed together.
- 'Shadows'
- 'Halo'
- 'Layer'
- 'Quad'
- 'Negative'
- 'OnlyShadow'
- 'Sphere'
- 'Square'
- 'NoDiffuse'
- 'NoSpecular'
- 'RayShadow'
Example::
from Blender import Lamp, Object
# Change the mode of selected lamp objects.
for ob in Object.GetSelected(): # Loop through the current selection
if ob.getType() == "Lamp": # if this is a lamp.
lamp = ob.getData() # get the lamp data.
if lamp.type == Lamp.Types["Spot"]: # Lamp type is not a flag
lamp.mode &= ~Lamp.Modes["RayShadow"] # Disable RayShadow.
lamp.mode |= Lamp.Modes["Shadows"] # Enable Shadowbuffer shadows
"""
def New (type = 'Lamp', name = 'LampData'):
"""
Create a new Lamp Data object.
@type type: string
@param type: The Lamp type: 'Lamp', 'Sun', 'Spot', 'Hemi', 'Area', or 'Photon'.
@type name: string
@param name: The Lamp Data name.
@rtype: Blender Lamp
@return: The created Lamp Data object.
"""
def Get (name = None):
"""
Get the Lamp Data object(s) from Blender.
@type name: string
@param name: The name of the Lamp Data.
@rtype: Blender Lamp or a list of Blender Lamps
@return: It depends on the I{name} parameter:
- (name): The Lamp Data object with the given I{name};
- (): A list with all Lamp Data objects in the current scene.
"""
class Lamp:
"""
The Lamp Data object
====================
This object gives access to Lamp-specific data in Blender.
@ivar B: Lamp color blue component.
Value is clamped to the range [0.0,1.0].
@type B: float
@ivar G: Lamp color green component.
Value is clamped to the range [0.0,1.0].
@type G: float
@ivar R: Lamp color red component.
Value is clamped to the range [0.0,1.0].
@type R: float
@ivar bias: Lamp shadow map sampling bias.
Value is clamped to the range [0.01,5.0].
@type bias: float
@ivar bufferSize: Lamp shadow buffer size.
Value is clamped to the range [512,5120].
@type bufferSize: int
@ivar clipEnd: Lamp shadow map clip end.
Value is clamped to the range [1.0,5000.0].
@type clipEnd: float
@ivar clipStart: Lamp shadow map clip start.
Value is clamped to the range [0.1,1000.0].
@type clipStart: float
@ivar col: Lamp RGB color triplet.
Components are clamped to the range [0.0,1.0].
@type col: RGB tuple
@ivar dist: Lamp clipping distance.
Value is clamped to the range [0.1,5000.0].
@type dist: float
@ivar energy: Lamp light intensity.
Value is clamped to the range [0.0,10.0].
@type energy: float
@ivar haloInt: Lamp spotlight halo intensity.
Value is clamped to the range [0.0,5.0].
@type haloInt: float
@ivar haloStep: Lamp volumetric halo sampling frequency.
Value is clamped to the range [0,12].
@type haloStep: int
@ivar ipo: Lamp Ipo.
Contains the Ipo if one is assigned to the object, B{None} otherwise. Setting to B{None} clears the current Ipo..
@type ipo: Blender Ipo
@ivar mode: Lamp mode bitfield. See L{Modes} for values.
@type mode: int
@ivar quad1: Quad lamp linear distance attenuation.
Value is clamped to the range [0.0,1.0].
@type quad1: float
@ivar quad2: Quad lamp quadratic distance attenuation.
Value is clamped to the range [0.0,1.0].
@type quad2: float
@ivar samples: Lamp shadow map samples.
Value is clamped to the range [1,16].
@type samples: int
@ivar raySamplesX: Lamp raytracing X samples (X is used for the Y axis with square area lamps).
Value is clamped to the range [1,16].
@type raySamplesX: int
@ivar raySamplesY: Lamp raytracing Y samples (Y is only used for rectangle area lamps).
Value is clamped to the range [1,16].
@type raySamplesY: int
@ivar areaSizeX: Lamp X size (X is used for the Y axis with square area lamps)
Value is clamped to the range [0.01,100.0].
@type areaSizeX: float
@ivar areaSizeY: Lamp Y size (Y is only used for rectangle area lamps).
Value is clamped to the range [0.01,100.0].
@type areaSizeY: float
@ivar softness: Lamp shadow sample area size.
Value is clamped to the range [1.0,100.0].
@type softness: float
@ivar spotBlend: Lamp spotlight edge softness.
Value is clamped to the range [0.0,1.0].
@type spotBlend: float
@ivar spotSize: Lamp spotlight beam angle (in degrees).
Value is clamped to the range [1.0,180.0].
@type spotSize: float
@ivar type: Lamp type. See L{Types} for values.
@type type: int
@warning: Most member variables assume values in some [Min, Max] interval.
When trying to set them, the given parameter will be clamped to lie in
that range: if val < Min, then val = Min, if val > Max, then val = Max.
"""
def getName():
"""
Get the name of this Lamp Data object.
@rtype: string
"""
def setName(name):
"""
Set the name of this Lamp Data object.
@type name: string
@param name: The new name.
"""
def getType():
"""
Get this Lamp's type.
@rtype: int
"""
def setType(type):
"""
Set this Lamp's type.
@type type: string
@param type: The Lamp type: 'Lamp', 'Sun', 'Spot', 'Hemi', 'Area', or 'Photon'
"""
def getMode():
"""
Get this Lamp's mode flags.
@rtype: int
@return: B{OR'ed value}. Use the Modes dictionary to check which flags
are 'on'.
Example::
flags = mylamp.getMode()
if flags & mylamp.Modes['Shadows']:
print "This lamp produces shadows"
else:
print "The 'Shadows' flag is off"
"""
def setMode(m = None, m2 = None, m3 = None, m4 = None,
m5 = None, m6 = None, m7 = None, m8 = None):
"""
Set this Lamp's mode flags. Mode strings given are turned 'on'.
Those not provided are turned 'off', so lamp.setMode() -- without
arguments -- turns off all mode flags for Lamp lamp.
@type m: string
@param m: A mode flag. From 1 to 8 can be set at the same time.
"""
def getSamples():
"""
Get this lamp's samples value.
@rtype: int
"""
def setSamples(samples):
"""
Set the samples value.
@type samples: int
@param samples: The new samples value.
"""
def getRaySamplesX():
"""
Get this lamp's raytracing sample value on the X axis.
This value is only used for area lamps.
@rtype: int
"""
def setRaySamplesX():
"""
Set the lamp's raytracing sample value on the X axis, between 1 and 16.
This value is only used for area lamps.
@rtype: int
"""
def getRaySamplesY():
"""
Get this lamp's raytracing sample value on the Y axis.
This value is only used for rectangle area lamps.
@rtype: int
"""
def setRaySamplesY():
"""
Set the lamp's raytracing sample value on the Y axis, between 1 and 16.
This value is only used for rectangle area lamps.
@rtype: int
"""
def getAreaSizeX():
"""
Get this lamp's size on the X axis.
This value is only used for area lamps.
@rtype: int
"""
def setAreaSizeX():
"""
Set this lamp's size on the X axis.
This value is only used for area lamps.
@rtype: int
"""
def getAreaSizeY():
"""
Get this lamp's size on the Y axis.
This value is only used for rectangle area lamps.
@rtype: int
"""
def setAreaSizeY():
"""
Set this lamp's size on the Y axis.
This value is only used for rectangle area lamps.
@rtype: int
"""
def getBufferSize():
"""
Get this lamp's buffer size.
@rtype: int
"""
def setBufferSize(bufsize):
"""
Set the buffer size value.
@type bufsize: int
@param bufsize: The new buffer size value.
"""
def getHaloStep():
"""
Get this lamp's halo step value.
@rtype: int
"""
def setHaloStep(hastep):
"""
Set the halo step value.
@type hastep: int
@param hastep: The new halo step value.
"""
def getEnergy():
"""
Get this lamp's energy intensity value.
@rtype: float
"""
def setEnergy(energy):
"""
Set the energy intensity value.
@type energy: float
@param energy: The new energy value.
"""
def getDist():
"""
Get this lamp's distance value.
@rtype: float
"""
def setDist(distance):
"""
Set the distance value.
@type distance: float
@param distance: The new distance value.
"""
def getSpotSize():
"""
Get this lamp's spot size value.
@rtype: float
"""
def setSpotSize(spotsize):
"""
Set the spot size value.
@type spotsize: float
@param spotsize: The new spot size value.
"""
def getSpotBlend():
"""
Get this lamp's spot blend value.
@rtype: float
"""
def setSpotBlend(spotblend):
"""
Set the spot blend value.
@type spotblend: float
@param spotblend: The new spot blend value.
"""
def getClipStart():
"""
Get this lamp's clip start value.
@rtype: float
"""
def setClipStart(clipstart):
"""
Set the clip start value.
@type clipstart: float
@param clipstart: The new clip start value.
"""
def getClipEnd():
"""
Get this lamp's clip end value.
@rtype: float
"""
def setClipEnd(clipend):
"""
Set the clip end value.
@type clipend: float
@param clipend: The new clip end value.
"""
def getBias():
"""
Get this lamp's bias value.
@rtype: float
"""
def setBias(bias):
"""
Set the bias value.
@type bias: float
@param bias: The new bias value.
"""
def getSoftness():
"""
Get this lamp's softness value.
@rtype: float
"""
def setSoftness(softness):
"""
Set the softness value.
@type softness: float
@param softness: The new softness value.
"""
def getHaloInt():
"""
Get this lamp's halo intensity value.
@rtype: float
"""
def setHaloInt(haloint):
"""
Set the halo intensity value.
@type haloint: float
@param haloint: The new halo intensity value.
"""
def getQuad1():
"""
Get this lamp's quad 1 value.
@rtype: float
@warning: this only applies to Lamps with the 'Quad' flag on.
"""
def setQuad1(quad1):
"""
Set the quad 1 value.
@type quad1: float
@warning: this only applies to Lamps with the 'Quad' flag on.
"""
def getQuad2():
"""
Get this lamp's quad 2 value.
@rtype: float
@warning: this only applies to Lamps with the 'Quad' flag on.
"""
def setQuad2(quad2):
"""
Set the quad 2 value.
@type quad2: float
@param quad2: The new quad 2 value.
@warning: this only applies to Lamps with the 'Quad' flag on.
"""
def getScriptLinks (event):
"""
Get a list with this Lamp's script links of type 'event'.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this Lamp. If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this Lamp.
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
"""
def getIpo():
"""
Get the Ipo associated with this Lamp object, if any.
@rtype: Ipo
@return: the wrapped ipo or None.
"""
def setIpo(ipo):
"""
Link an ipo to this Lamp object.
@type ipo: Blender Ipo
@param ipo: a "lamp data" ipo.
"""
def clearIpo():
"""
Unlink the ipo from this Lamp object.
@return: True if there was an ipo linked or False otherwise.
"""
def insertIpoKey(keytype):
"""
Inserts keytype values in lamp ipo at curframe. Uses module constants.
@type keytype: Integer
@param keytype:
-RGB
-ENERGY
-SPOTSIZE
-OFFSET
-SIZE
@return: None
"""
def __copy__ ():
"""
Make a copy of this lamp
@rtype: Lamp
@return: a copy of this lamp
"""
import id_generics
Lamp.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,209 @@
# Blender.Lattice module and the Lattice PyType object
"""
The Blender.Lattice submodule.
Lattice Object
==============
This module provides access to B{Lattice} object in Blender.
Example::
import Blender
from Blender import Lattice, Object, Scene, Modifier
# Make new lattice data
lattice_data = Lattice.New()
lattice_data.setPartitions(5,5,5)
lattice_data.setKeyTypes(Lattice.LINEAR, Lattice.CARDINAL, Lattice.BSPLINE)
lattice_data.setMode(Lattice.OUTSIDE)
for y in range(125):
vec = lattice_data.getPoint(y)
co1 = vec[0] + vec[0] / 5
co2 = vec[1] - vec[2] * 0.3
co3 = vec[2] * 3
lattice_data.setPoint(y,[co1,co2,co3])
# Create a new object from the lattice in the current scene
scn = Scene.GetCurrent()
ob_lattice = scn.objects.new(lattice_data)
# Get an object to deform with this lattice
mySphere = Object.Get('Sphere')
# Apply lattice modifier
mod= mySphere.modifiers.append(Modifier.Type.LATTICE)
mod[Modifier.Settings.OBJECT] = ob_lattice
mySphere.makeDisplayList()
Blender.Redraw()
"""
def New (name = None):
"""
Create a new Lattice object.
Passing a name to this function will name the Lattice
datablock, otherwise the Lattice data will be given a
default name.
@type name: string
@param name: The Lattice name.
@rtype: Blender Lattice
@return: The created Lattice Data object.
"""
def Get (name = None):
"""
Get the Lattice object(s) from Blender.
@type name: string
@param name: The name of the Lattice object.
@rtype: Blender Lattice or a list of Blender Lattices
@return: It depends on the 'name' parameter:
- (name): The Lattice object with the given name;
- (): A list with all Lattice objects in the current scene.
"""
class Lattice:
"""
The Lattice object
==================
This object gives access to Lattices in Blender.
@ivar width: The number of x dimension partitions.
@ivar height: The number of y dimension partitions.
@ivar depth: The number of z dimension partitions.
@ivar widthType: The x dimension key type.
@ivar heightType: The y dimension key type.
@ivar depthType: The z dimension key type.
@ivar mode: The current mode of the Lattice.
@ivar latSize: The number of points in this Lattice (width*height*depth).
@cvar key: The L{Key.Key} object associated with this Lattice or None.
"""
def getName():
"""
Get the name of this Lattice datablock.
@rtype: string
@return: The name of the Lattice datablock.
"""
def setName(name):
"""
Set the name of this Lattice datablock.
@type name: string
@param name: The new name.
"""
def getPartitions():
"""
Gets the number of 'walls' or partitions that the Lattice has
in the x, y, and z dimensions.
@rtype: list of ints
@return: A list corresponding to the number of partitions: [x,y,z]
"""
def setPartitions(x,y,z):
"""
Set the number of 'walls' or partitions that the
Lattice will be created with in the x, y, and z dimensions.
@type x: int
@param x: The number of partitions in the x dimension of the Lattice.
@type y: int
@param y: The number of partitions in the y dimension of the Lattice.
@type z: int
@param z: The number of partitions in the z dimension of the Lattice.
"""
def getKeyTypes():
"""
Returns the deformation key types for the x, y, and z dimensions of the
Lattice.
@rtype: list of strings
@return: A list corresponding to the key types will be returned: [x,y,z]
"""
def setKeyTypes(xType,yType,zType):
"""
Sets the deformation key types for the x, y, and z dimensions of the
Lattice.
There are three key types possible:
- Lattice.CARDINAL
- Lattice.LINEAR
- Lattice.BSPLINE
@type xType: enum constant
@param xType: the deformation key type for the x dimension of the Lattice
@type yType: enum constant
@param yType: the deformation key type for the y dimension of the Lattice
@type zType: enum constant
@param zType: the deformation key type for the z dimension of the Lattice
"""
def getMode():
"""
Returns the current Lattice mode
@rtype: string
@return: A string representing the current Lattice mode
"""
def setMode(modeType):
"""
Sets the current Lattice mode
There are two Lattice modes possible:
- Lattice.GRID
- Lattice.OUTSIDE
@type modeType: enum constant
@param modeType: the Lattice mode
"""
def getPoint(index):
"""
Returns the coordinates of a point in the Lattice by index.
@type index: int
@param index: The index of the point on the Lattice you want returned
@rtype: list of floats
@return: The x,y,z coordiates of the Lattice point : [x,y,z]
"""
def setPoint(index, position):
"""
Sets the coordinates of a point in the Lattice by index.
@type index: int
@param index: The index of the point on the Lattice you want set
@type position: list of floats
@param position: The x,y,z coordinates that you want the point to be: [x,y,z]
"""
def getKey():
"""
Returns the L{Key.Key} object associated with this Lattice.
@rtype: L{Key.Key}
@return: A key object representing the keyframes of the lattice or None.
"""
def insertKey(frame):
"""
Inserts the current state of the Lattice as a new absolute keyframe
B{Example}::
for z in range(5):
for y in range(125):
vec = myLat.getPoint(y)
co1 = vec[0] + vec[2]
co2 = vec[1] - vec[2]
co3 = vec[2] + vec[1]
myLat.setPoint(y,[co1,co2,co3])
w = (z + 1) * 10
myLat.insertKey(w)
@type frame: int
@param frame: the frame at which the Lattice will be set as a keyframe
"""
def __copy__ ():
"""
Make a copy of this lattice
@rtype: Lattice
@return: a copy of this lattice
"""
import id_generics
Lattice.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,137 @@
# bpy.lib submodule
"""
The bpy.libraries submodule.
Libraries
=========
This module provides access to objects stored in .blend files. With it scripts
can append from Blender files to the current scene, like the File->Append
menu entry in Blender does. It allows programmers to use .blend files as
data files for their scripts.
@warn: This module is new and being considered as a replacement for the
L{original Library<Library>} module. Users should stay tuned to see
which module is supported in the end.
Example::
import bpy
scn= bpy.scenes.active # get current scene
lib = bpy.libraries.load('//file.blend') # open file.blend
ob = scn.objects.link(lib.objects.append('Cube')) # append Cube object from library to current scene
mat = lib.objects.link('Material') # get a link to a material
me = ob.getData(mesh=1) # get mesh data
me.materials[0] = mat # assign linked material to mesh
"""
def load(filename):
"""
Select an existing .blend file for use as a library. Unlike the
Library module, multiple libraries can be defined at the same time.
@type filename: string
@param filename: The filename of a Blender file. Filenames starting with "//" will be loaded relative to the blend file's location.
@rtype: Library
@return: return a L{Library} object.
"""
class Libraries:
"""
The Library object
==================
This class provides a unified way to access and manipulate library types
in Blender.
It provides access to scenes, objects, meshes, curves, metaballs,
materials, textures, images, lattices, lamps, cameras, ipos, worlds,
fonts, texts, sounds, groups, armatures, and actions.
@ivar filename: The path to the library
@type filename: string
@ivar scenes: library L{scene<Scene.Scene>} data
@type scenes: L{LibData}
@ivar objects: library L{object<Object.Object>} data
@type objects: L{LibData}
@ivar meshes: library L{mesh<Mesh.Mesh>} data
@type meshes: L{LibData}
@ivar curves: library L{curve<Curve.Curve>} data
@type curves: L{LibData}
@ivar metaballs: library L{metaball<Metaball.Metaball>} data
@type metaballs: L{LibData}
@ivar materials: library L{material<Material.Material>} data
@type materials: L{LibData}
@ivar textures: library L{texture<Texture.Texture>} data
@type textures: L{LibData}
@ivar images: library L{image<Image.Image>} data
@type images: L{LibData}
@ivar lattices: library L{lattice<Lattice.Lattice>} data
@type lattices: L{LibData}
@ivar lamps: library L{lamp<Lamp.Lamp>} data
@type lamps: L{LibData}
@ivar cameras: library L{camera<Camera.Camera>} data
@type cameras: L{LibData}
@ivar ipos: library L{ipo<Ipo.Ipo>} data
@type ipos: L{LibData}
@ivar worlds: library L{world<World.World>} data
@type worlds: L{LibData}
@ivar fonts: library L{font<Font.Font>} data
@type fonts: L{LibData}
@ivar texts: library L{text<Text.Text>} data
@type texts: L{LibData}
@ivar sounds: library L{sound<Sound.Sound>} data
@type sounds: L{LibData}
@ivar groups: library L{group<Group.Group>} data
@type groups: L{LibData}
@ivar armatures: library L{armature<Armature.Armature>} data
@type armatures: L{LibData}
@ivar actions: library L{action<NLA.Action>} data
@type actions: L{LibData}
"""
class LibData:
"""
Generic Library Data Access
===========================
This class provides access to a specific type of library data.
"""
def append(name):
"""
Append a new datablock from a library. The new copy
is added to the current .blend file.
B{Note}: Blender Objects cannot be appended or linked without linking
them to a scene. For this reason, lib.objects.append() returns a
special "wrapper object" which must be passed to Scene.objects.link()
or bpy.scenes.active.link() in order to actually create the object.
So the following code will not create a new object::
import bpy
scn= bpy.scenes.active # get current scene
lib = bpy.libraries.load('//file.blend') # open file.blend
pseudoOb = lib.objects.append('Cube')) # get an object wrapper
But this code will::
import bpy
scn= bpy.scenes.active # get current scene
lib = bpy.libraries.load('//file.blend') # open file.blend
pseudoOb = lib.objects.append('Cube')) # get an object wrapper
ob = scn.objects.link(pseudoOb) # link to scene
@rtype: Blender data
@return: return a Blender datablock or object
@raise IOError: library cannot be read
@raise ValueError: library does not contain B{name}
"""
def link(name):
"""
Link a new datablock from a library. The linked data is not copied
into the local .blend file.
See L{append} for notes on special handling of Blender Objects.
@rtype: Blender data
@return: return a Blender datablock or object
@raise IOError: library cannot be read
@raise ValueError: library does not contain B{name}
"""

View File

@@ -0,0 +1,114 @@
# Blender.Library submodule
"""
The Blender.Library submodule.
Library
=======
This module provides access to objects stored in .blend files. With it scripts
can append from Blender files to the current scene, like the File->Append
menu entry in Blender does. It allows programmers to use .blend files as
data files for their scripts.
@warn: This module is being considered for deprecation. Users should
consider using the L{new Library<LibData>} module and stay tuned to see
which module is supported in the end.
Example::
import Blender
from Blender import Library
def f(name):
open_library(name)
def open_library(name):
Library.Open(name)
groups = Library.LinkableGroups()
for db in groups:
print "DATABLOCK %s:" % db
for obname in Library.Datablocks(db):
print obname
if 'Object' in groups:
for obname in Library.Datablocks('Object'):
Library.Load(obname, 'Object', 0) # note the 0...
Library.Update()
Library.Close()
b.Redraw()
b.Window.FileSelector(f, "Choose Library", "*.blend")
"""
def Open (filename):
"""
Open an existing .blend file. If there was already one open file, it is
closed first.
@type filename: string
@param filename: The filename of a Blender file. Filenames starting with "//" will be loaded relative to the blend file's location.
@rtype: bool
@return: 1 if successful. An IOError exception is thrown if the file cannot be opened.
"""
def Close ():
"""
Close the currently open library file, if any.
"""
def getName ():
"""
Get the filename of the currently open library file.
@rtype: string
@return: The open library filename.
"""
def LinkableGroups ():
"""
Get all the linkable group names from the currently open library file. These
are the available groups for linking with the current scene. Ex: 'Object',
'Mesh', 'Material', 'Text', etc.
@rtype: list of strings
@return: the list of linkable groups.
"""
def Datablocks (group):
"""
Get all datablock objects of the given 'group' available in the currently
open library file.
@type group: string
@param group: datablock group, see L{LinkableGroups}.
"""
def Load (datablock, group, update = 1, linked = 0):
"""
Load the given datablock object from the current library file
@type datablock: string
@type group: string
@type update: bool
@type linked: bool
@param datablock: an available object name, as returned by L{Datablocks}.
@param group: an available group name, as returned by L{LinkableGroups}.
@param update: defines if Blender should be updated after loading this
object. This means linking all objects and remaking all display lists,
so it is potentially very slow.
@param linked: Will keep objects linked to their source blend file, the update option or later updating will unlink the data from the original blend and make it local.
@warn: If you plan to load more than one object in sequence, it is
B{definitely recommended} to set 'update' to 0 in all calls to this
function and after them call L{Update}.
"""
def Update ():
"""
Update all links and display lists in Blender. This function should be
called after a series of L{Load}(datablock, group, B{0}) calls to make
everything behave nicely.
@warn: to use this function, remember to set the third L{Load} parameter to
zero or each loading will automatically update Blender, which will slow
down your script and make you look like a lousy programmer.
Enough warnings :)?
"""

View File

@@ -0,0 +1,1061 @@
# Blender.Material module and the Material PyObject
"""
The Blender.Material submodule.
B{New}: access to shader data.
Material
========
This module provides access to B{Material} objects in Blender.
Example::
import Blender
from Blender import Material
mat = Material.New('newMat') # create a new Material called 'newMat'
print mat.rgbCol # print its rgb color triplet sequence
mat.rgbCol = [0.8, 0.2, 0.2] # change its color
mat.setAlpha(0.2) # mat.alpha = 0.2 -- almost transparent
mat.emit = 0.7 # equivalent to mat.setEmit(0.8)
mat.mode |= Material.Modes.ZTRANSP # turn on Z-Buffer transparency
mat.setName('RedBansheeSkin') # change its name
mat.setAdd(0.8) # make it glow
mat.setMode('Halo') # turn 'Halo' "on" and all others "off"
@type Modes: readonly dictionary
@var Modes: The available Material Modes.
B{Note}: Some Modes are only available when the 'Halo' mode is I{off} and
others only when it is I{on}. But these two subsets of modes share the same
numerical values in their Blender C #defines. So, for example, if 'Halo' is
on, then 'NoMist' is actually interpreted as 'HaloShaded'. We marked all
such possibilities in the Modes dict below: each halo-related mode that
uses an already taken value is preceded by "+" and appear below the normal
mode which also uses that value.
- TRACEABLE - Make Material visible for shadow lamps.
- SHADOW - Enable Material for shadows.
- SHADOWBUF - Enable Material to cast shadows with shadow buffers.
- SHADELESS - Make Material insensitive to light or shadow.
- WIRE - Render only the edges of faces.
- VCOL_LIGHT - Add vertex colors as extra light.
- VCOL_PAINT - Replace basic colors with vertex colors.
- HALO - Render as a halo.
- ZTRANSP - Z-buffer transparent faces.
- ZINVERT - Render with inverted Z-buffer.
- + HALORINGS - Render rings over the basic halo.
- ENV - Do not render Material.
- + HALOLINES - Render star shaped lines over the basic halo.
- ONLYSHADOW - Let alpha be determined on the degree of shadow.
- + HALOXALPHA - Use extreme alpha.
- TEXFACE - UV-Editor assigned texture gives color and texture info for faces.
- + HALOSTAR - Render halo as a star.
- NOMIST - Set the Material insensitive to mist.
- + HALOSHADED - Let halo receive light.
- HALOTEX - Give halo a texture.
- HALOPUNO - Use the vertex normal to specify the dimension of the halo.
- HALOFLARE - Render halo as a lens flare.
- RAYMIRROR - Enables raytracing for mirror reflection rendering.
- RAYTRANSP - Enables raytracing for transparency rendering.
- RAYBIAS - Prevent ray traced shadow errors with Phong interpolated normals.
- RAMPCOL - Status of colorband ramp for Material's diffuse color. This is a read-only bit.
- RAMPSPEC - Status of colorband ramp for Material's specular color. This is a read-only bit.
- TANGENTSTR - Uses direction of strands as normal for tangent-shading.
- TRANSPSHADOW - Lets Material receive transparent shadows based on material color and alpha.
- FULLOSA - Force rendering of all OSA samples.
- TANGENT_V - Use the tangent vector in V direction for shading
- NMAP_TS - Tangent space normal mapping.
- GROUP_EXCLUSIVE - Light from this group even if the lights are on a hidden Layer.
@type Shaders: readonly dictionary
@var Shaders: The available Material Shaders.
- DIFFUSE_LAMBERT - Make Material use the lambert diffuse shader.
- DIFFUSE_ORENNAYAR - Make Material use the Oren-Nayer diffuse shader.
- DIFFUSE_TOON - Make Material use the toon diffuse shader.
- DIFFUSE_MINNAERT - Make Material use the minnaert diffuse shader.
- SPEC_COOKTORR - Make Material use the Cook-Torr specular shader.
- SPEC_PHONG - Make Material use the Phong specular shader.
- SPEC_BLINN - Make Material use the Blinn specular shader.
- SPEC_TOON - Make Material use the toon specular shader.
- SPEC_WARDISO - Make Material use the Ward-iso specular shader.
"""
def New (name = 'Mat'):
"""
Create a new Material object.
@type name: string
@param name: The Material name.
@rtype: Blender Material
@return: The created Material object.
"""
def Get (name = None):
"""
Get the Material object(s) from Blender.
@type name: string
@param name: The name of the Material.
@rtype: Blender Material or a list of Blender Materials
@return: It depends on the 'name' parameter:
- (name): The Material object with the given name;
- (): A list with all Material objects in the current scene.
"""
class Material:
"""
The Material object
===================
This object gives access to Materials in Blender.
@ivar B: Diffuse color (L{rgbCol}) blue component.
Value is clamped to the range [0.0,1.0].
@type B: float
@ivar G: Diffuse color (L{rgbCol}) green component.
Value is clamped to the range [0.0,1.0].
@type G: float
@ivar IOR: Angular index of refraction for raytrace.
Value is clamped to the range [1.0,3.0].
@type IOR: float
@ivar R: Diffuse color (L{rgbCol}) red component.
Value is clamped to the range [0.0,1.0].
@type R: float
@ivar add: Strength of the add effect.
Value is clamped to the range [0.0,1.0].
@type add: float
@ivar alpha: Alpha (translucency) component of the material.
Value is clamped to the range [0.0,1.0].
@type alpha: float
@ivar shadAlpha: Shadow Alpha for irregular shadow buffer.
Value is clamped to the range [0.0,1.0].
@type shadAlpha: float
@ivar amb: Amount of global ambient color material receives.
Value is clamped to the range [0.0,1.0].
@type amb: float
@ivar diffuseDarkness: Material's diffuse darkness ("Minnaert" diffuse shader only).
Value is clamped to the range [0.0,2.0].
@type diffuseDarkness: float
@ivar diffuseShader: Diffuse shader type (see L{Shaders}).
Value must be in the range [0,3].
@type diffuseShader: int
@ivar diffuseSize: Material's diffuse area size ("Toon" diffuse shader only).
Value is clamped to the range [0.0,3.14].
@type diffuseSize: float
@ivar diffuseSmooth: Material's diffuse area smoothing ("Toon" diffuse shader only).
Value is clamped to the range [0.0,1.0].
@type diffuseSmooth: float
@ivar emit: Amount of light the material emits.
Value is clamped to the range [0.0,1.0].
@type emit: float
@ivar filter: Amount of filtering when transparent raytrace is enabled.
Value is clamped to the range [0.0,1.0].
@type filter: float
@ivar flareBoost: Flare's extra strength.
Value is clamped to the range [0.1,1.0].
@type flareBoost: float
@ivar flareSeed: Offset in the flare seed table.
Value is clamped to the range [1,255].
@type flareSeed: int
@ivar flareSize: Ratio of flare size to halo size.
Value is clamped to the range [0.1,25.0].
@type flareSize: float
@ivar fresnelDepth: Power of Fresnel for mirror reflection.
Value is clamped to the range [0.0,5.0].
@type fresnelDepth: float
@ivar fresnelDepthFac: Blending factor for Fresnel mirror.
Value is clamped to the range [1.0,5.0].
@type fresnelDepthFac: float
@ivar fresnelTrans: Power of Fresnel for transparency.
Value is clamped to the range [0.0,5.0].
@type fresnelTrans: float
@ivar fresnelTransFac: Blending factor for Fresnel transparency.
Value is clamped to the range [1.0,5.0].
@type fresnelTransFac: float
@ivar rbFriction: Rigid Body Friction coefficient.
Value is clamped to the range [0.0,100.0].
@type rbFriction: float
@ivar rbRestitution: Rigid Body Friction restitution.
Value is clamped to the range [0.0,1.0].
@type rbRestitution: float
@ivar haloSeed: Randomizes halo ring dimension and line location.
Value is clamped to the range [1,255].
@type haloSeed: int
@ivar haloSize: Dimension of the halo.
Value is clamped to the range [0.0,100.0].
@type haloSize: float
@ivar hard: Hardness of the specularity.
Value is clamped to the range [1,255].
@type hard: int
@ivar ipo: Material Ipo data.
Contains the Ipo if one is assigned to the object, None otherwise. Setting to None clears the current Ipo.
@type ipo: Blender Ipo
@ivar mirCol: Mirror RGB color triplet.
Components are clamped to the range [0.0,1.0].
@type mirCol: list of 3 floats
@ivar mirB: Mirror color (L{mirCol}) blue component.
Value is clamped to the range [0.0,1.0].
@type mirB: float
@ivar mirG: Mirror color (L{mirCol}) green component.
Value is clamped to the range [0.0,1.0].
@type mirG: float
@ivar mirR: Mirror color (L{mirCol}) red component.
Value is clamped to the range [0.0,1.0].
@type mirR: float
@ivar sssCol: SubSsurface scattering RGB color triplet.
Components are clamped to the range [0.0,1.0].
@type sssCol: list of 3 floats
@ivar sssB: SubSsurface scattering color (L{sssCol}) blue component.
Value is clamped to the range [0.0,1.0].
@type sssB: float
@ivar sssG: SubSsurface scattering color (L{sssCol}) green component.
Value is clamped to the range [0.0,1.0].
@type sssG: float
@ivar sssR: SubSsurface scattering color (L{sssCol}) red component.
Value is clamped to the range [0.0,1.0].
@type sssR: float
@ivar mode: Mode mode bitfield. See L{the Modes dictionary<Modes>} keys and descriptions.
@type mode: int
@ivar nFlares: Number of subflares with halo.
Value is clamped to the range [1,32].
@type nFlares: int
@ivar nLines: Number of star-shaped lines with halo.
Value is clamped to the range [0,250].
@type nLines: int
@ivar nRings: Number of rings with halo.
Value is clamped to the range [0,24].
@type nRings: int
@ivar nStars: Number of star points with halo.
Value is clamped to the range [3,50].
@type nStars: int
@ivar oopsLoc: Material OOPs location. Returns None if material not found in list.
@type oopsLoc: list of 2 floats
@ivar oopsSel: Material OOPs selection flag.
Value must be in the range [0,1].
@type oopsSel: int
@ivar rayMirr: Mirror reflection amount for raytrace.
Value is clamped to the range [0.0,1.0].
@type rayMirr: float
@ivar rayMirrDepth: Amount of raytrace inter-reflections.
Value is clamped to the range [0,10].
@type rayMirrDepth: int
@ivar ref: Amount of reflections (for shader).
Value is clamped to the range [0.0,1.0].
@type ref: float
@ivar refracIndex: Material's Index of Refraction (applies to the "Blinn" Specular Shader only.
Value is clamped to the range [1.0,10.0].
@type refracIndex: float
@ivar rgbCol: Diffuse RGB color triplet.
Components are clamped to the range [0.0,1.0].
@type rgbCol: list of 3 floats
@ivar rms: Material's surface slope standard deviation ("WardIso" specular shader only).
Value is clamped to the range [0.0,0.4].
@type rms: float
@ivar roughness: Material's roughness ("Oren Nayar" diffuse shader only).
Value is clamped to the range [0.0,3.14].
@type roughness: float
@ivar spec: Degree of specularity.
Value is clamped to the range [0.0,2.0].
@type spec: float
@ivar specB: Specular color (L{specCol}) blue component.
Value is clamped to the range [0.0,1.0].
@type specB: float
@ivar specCol: Specular RGB color triplet.
Components are clamped to the range [0.0,1.0].
@type specCol: list of 3 floats
@ivar specG: Specular color (L{specCol}) green component.
Value is clamped to the range [0.0,1.0].
@type specG: float
@ivar specR: Specular color (L{specCol}) red component.
Value is clamped to the range [0.0,1.0].
@type specR: float
@ivar specShader: Specular shader type. See L{Shaders}.
Value must be in the range [0,4].
@type specShader: int
@ivar specSize: Material's specular area size ("Toon" specular shader only).
Value is clamped to the range [0.0,1.53].
@type specSize: float
@ivar specSmooth: Sets the smoothness of specular toon area.
Value is clamped to the range [0.0,1.0].
@type specSmooth: float
@ivar specTransp: Makes specular areas opaque on transparent materials.
Value is clamped to the range [0.0,1.0].
@type specTransp: float
@ivar subSize: Dimension of subflares, dots and circles.
Value is clamped to the range [0.1,25.0].
@type subSize: float
@ivar transDepth: calculated maximal. Amount of refractions for raytrace.
Value is clamped to the range [0,10].
@type transDepth: int
@ivar translucency: Amount of diffuse shading of the back side.
Value is clamped to the range [0.0,1.0].
@type translucency: float
@ivar zOffset: Artificial offset in the Z buffer (for Ztransp option).
Value is clamped to the range [0.0,10.0].
@type zOffset: float
@ivar lightGroup: Limits lights that affect this material to a group.
@type lightGroup: Group or None
@ivar uvlayer: The uv layer name to use, when UV mapping is enabled.
@type uvlayer: string
@ivar colorband: Material colorband, a list of colors,
each color a list of 5 floats [0 - 1], [r,g,b,a,pos].
The colorband can have between 1 and 31 colors.
@type colorband: list
@ivar colorbandDiffuse: Material colorband, a list of colors,
each color a list of 5 floats [0 - 1], [r,g,b,a,pos].
The colorband can have between 1 and 31 colors.
@type colorbandDiffuse: list
@ivar colorbandSpecular: Material colorband, a list of colors,
each color a list of 5 floats [0 - 1], [r,g,b,a,pos].
The colorband can have between 1 and 31 colors.
@type colorbandSpecular: list
@ivar enableSSS: If True, subsurface scattering will be rendered on this material.
@type enableSSS: bool
@ivar sssScale: If True, subsurface scattering will be rendered on this material.
Value is clamped to the range [0.1,1000.0].
@type sssScale: bool
@ivar sssRadiusRed: Mean red scattering path length.
Value is clamped to the range [0.0,10000.0].
@type sssRadiusRed: float
@ivar sssRadiusGreen: Mean green scattering path length.
Value is clamped to the range [0.0,10000.0].
@type sssRadiusGreen: float
@ivar sssRadiusBlue: Mean blue scattering path length.
Value is clamped to the range [0.0,10000.0].
@type sssRadiusBlue: float
@ivar sssIOR: Refraction index.
Value is clamped to the range [0.1,2.0].
@type sssIOR: float
@ivar sssError: Error allowance for the calculation (a low value is slower).
Value is clamped to the range [0.0,10.0].
@type sssError: float
@ivar sssColorBlend: Blend factor for SSS colors.
Value is clamped to the range [0.0,1.0].
@type sssColorBlend: float
@ivar sssTextureScatter: Texture scattering factor.
Value is clamped to the range [0.0,1.0].
@type sssTextureScatter: float
@ivar sssFront: Front scattering weight.
Value is clamped to the range [0.0,2.0].
@type sssFront: float
@ivar sssBack: Back scattering weight
Value is clamped to the range [0.0,10.0].
@type sssBack: float
@warning: Most member variables assume values in some [Min, Max] interval.
When trying to set them, the given parameter will be clamped to lie in
that range: if val < Min, then val = Min, if val > Max, then val = Max.
"""
def getName():
"""
Get the name of this Material object.
@rtype: string
"""
def setName(name):
"""
Set the name of this Material object.
@type name: string
@param name: The new name.
"""
def getIpo():
"""
Get the Ipo associated with this material, if any.
@rtype: Ipo
@return: the wrapped ipo or None.
"""
def setIpo(ipo):
"""
Link an ipo to this material.
@type ipo: Blender Ipo
@param ipo: a material type ipo.
"""
def clearIpo():
"""
Unlink the ipo from this material.
@return: True if there was an ipo linked or False otherwise.
"""
def insertIpoKey(keytype):
"""
Inserts keytype values in material ipo at curframe. Uses module constants.
@type keytype: Integer
@param keytype:
-RGB
-ALPHA
-HALOSIZE
-MODE
-ALLCOLOR
-ALLMIRROR
-OFS
-SIZE
-ALLMAPPING
@return: py_none
"""
def getMode():
"""
Get this Material's mode flags.
@rtype: int
@return: B{OR'ed value}. Use the Modes dictionary to check which flags
are 'on'.
Example::
import Blender
from Blender import Material
flags = mymat.getMode()
if flags & Material.Modes['HALO']:
print "This material is rendered as a halo"
else:
print "Not a halo"
"""
def setMode(param, stringN=None):
"""
Set this Material's mode flags. Up to 22 mode strings can be given
and specify the modes which are turned 'on'. Those not provided are
turned 'off', so mat.setMode() -- without arguments -- turns off all
mode flags for Material mat. Valid mode strings are "Traceable",
"Shadow", "Shadeless", "Wire", "VColLight", "VColPaint", "Halo",
"ZTransp", "ZInvert", "HaloRings", "HaloLines", "OnlyShadow",
"HaloXAlpha", "HaloStar", "TexFace", "HaloTex", "HaloPuno", "NoMist",
"HaloShaded", "HaloFlare", "Radio", "RayMirr", "ZTransp", "RayTransp",
"Env"
An integer can also be given, which directly sets the mode flag. The
Modes dictionary keys can (and should) be added or ORed to specify
which modes to turn 'on'. The value returned from getMode() can
also be modified and input to this method.
@type param: string, None or int
@param param: A mode value (int) or flag (string). Can also be None.
@type stringN: string
@param stringN: A mode flag. Up to 22 flags can be set at the same time.
"""
def getRGBCol():
"""
Get the rgb color triplet sequence.
@rtype: list of 3 floats
@return: [r, g, b]
"""
def setRGBCol(rgb = None):
"""
Set the rgb color triplet sequence. If B{rgb} is None, set the color to black.
@type rgb: three floats or a list of three floats
@param rgb: The rgb color values in [0.0, 1.0] as:
- a list of three floats: setRGBCol ([r, g, b]) B{or}
- three floats as separate parameters: setRGBCol (r,g,b).
"""
def getSpecCol():
"""
Get the specular color triplet sequence.
@rtype: list of 3 floats
@return: [specR, specG, specB]
"""
def setSpecCol(rgb = None):
"""
Set the specular color triplet sequence. If B{rgb} is None, set the color to black.
@type rgb: three floats or a list of three floats
@param rgb: The rgb color values in [0.0, 1.0] as:
- a list of three floats: setSpecCol ([r, g, b]) B{or}
- three floats as separate parameters: setSpecCol (r,g,b).
"""
def getMirCol():
"""
Get the mirror color triplet sequence.
@rtype: list of 3 floats
@return: [mirR, mirG, mirb]
"""
def setMirCol(rgb = None):
"""
Set the mirror color triplet sequence. If B{rgb} is None, set the color to black.
@type rgb: three floats or a list of three floats
@param rgb: The rgb color values in [0.0, 1.0] as:
- a list of three floats: setMirCol ([r, g, b]) B{or}
- three floats as separate parameters: setMirCol (r,g,b).
"""
def getAlpha():
"""
Get the alpha (transparency) value.
@rtype: float
"""
def setAlpha(alpha):
"""
Set the alpha (transparency) value.
@type alpha: float
@param alpha: The new value in [0.0, 1.0].
"""
def getAmb():
"""
Get the ambient color blend factor.
@rtype: float
"""
def setAmb(amb):
"""
Set the ambient color blend factor.
@type amb: float
@param amb: The new value in [0.0, 1.0].
"""
def getEmit():
"""
Get the emitting light intensity.
@rtype: float
"""
def setEmit(emit):
"""
Set the emitting light intensity.
@type emit: float
@param emit: The new value in [0.0, 1.0].
"""
def getRef():
"""
Get the reflectivity value.
@rtype: float
"""
def setRef(ref):
"""
Set the reflectivity value.
@type ref: float
@param ref: The new value in [0.0, 1.0].
"""
def getSpec():
"""
Get the specularity value.
@rtype: float
"""
def setSpec(spec):
"""
Set the specularity value.
@type spec: float
@param spec: The new value in [0.0, 2.0].
"""
def getSpecTransp():
"""
Get the specular transparency.
@rtype: float
"""
def setSpecTransp(spectransp):
"""
Set the specular transparency.
@type spectransp: float
@param spectransp: The new value in [0.0, 1.0].
"""
def setSpecShader(specShader):
"""
Set the material's specular shader from one of the shaders in Material.Shaders dict.
@type specShader: int
@param specShader: The new value in [0, 4].
"""
def getSpecShader(specShader):
"""
Get the material's specular shader from one of the shaders in Material.Shaders dict.
@rtype: int
"""
def setDiffuseShader(diffuseShader):
"""
Set the material's diffuse shader from one of the shaders in Material.Shaders dict.
@type diffuseShader: int
@param diffuseShader: The new value in [0, 3].
"""
def getDiffuseShader():
"""
Get the material's diffuse shader from one of the shaders in Material.Shaders dict.
@rtype: int
"""
def setRoughness(roughness):
"""
Set the material's roughness (applies to the \"Oren Nayar\" Diffuse Shader only)
@type roughness: float
@param roughness: The new value in [0.0, 3.14].
"""
def getRoughness():
"""
Get the material's roughness (applies to the \"Oren Nayar\" Diffuse Shader only)
@rtype: float
"""
def setSpecSize(specSize):
"""
Set the material's size of specular area (applies to the \"Toon\" Specular Shader only)
@type specSize: float
@param specSize: The new value in [0.0, 1.53].
"""
def getSpecSize():
"""
Get the material's size of specular area (applies to the \"Toon\" Specular Shader only)
@rtype specSize: float
"""
def setSpecSize(diffuseSize):
"""
Set the material's size of diffuse area (applies to the \"Toon\" Diffuse Shader only)
@type diffuseSize: float
@param diffuseSize: The new value in [0.0, 3.14].
"""
def getSpecSize():
"""
Get the material's size of diffuse area (applies to the \"Toon\" Diffuse Shader only)
@rtype: float
"""
def setSpecSmooth(specSmooth):
"""
Set the material's smoothing of specular area (applies to the \"Toon\" Specular Shader only)
@type specSmooth: float
@param specSmooth: The new value in [0.0, 1.0].
"""
def getSpecSmooth():
"""
Get the material's smoothing of specular area (applies to the \"Toon\" Specular Shader only)
@rtype: float
"""
def setDiffuseSmooth(diffuseSmooth):
"""
Set the material's smoothing of diffuse area (applies to the \"Toon\" Diffuse Shader only)
@type diffuseSmooth: float
@param diffuseSmooth: The new value in [0.0, 1.0].
"""
def getDiffuseSmooth():
"""
Get the material's smoothing of diffuse area (applies to the \"Toon\" Diffuse Shader only)
@rtype: float
"""
def setDiffuseDarkness(diffuseDarkness):
"""
Set the material's diffuse darkness (applies to the \"Minnaert\" Diffuse Shader only)
@type diffuseDarkness: float
@param diffuseDarkness: The new value in [0.0, 2.0].
"""
def getDiffuseDarkness():
"""
Get the material's diffuse darkness (applies to the \"Minnaert\" Diffuse Shader only)
@rtype: float
"""
def setRefracIndex(refracIndex):
"""
Set the material's Index of Refraction (applies to the \"Blinn\" Specular Shader only)
@type refracIndex: float
@param refracIndex: The new value in [1.0, 10.0].
"""
def getRefracIndex():
"""
Get the material's Index of Refraction (applies to the \"Blinn\" Specular Shader only)
@rtype: float
"""
def setRms(rms):
"""
Set the material's standard deviation of surface slope (applies to the \"WardIso\" Specular Shader only)
@type rms: float
@param rms: The new value in [0.0, 0.4].
"""
def getRms():
"""
Get the material's standard deviation of surface slope (applies to the \"WardIso\" Specular Shader only)
@rtype: float
"""
def setFilter(filter):
"""
Set the material's amount of filtering when transparent raytrace is enabled
@type filter: float
@param filter: The new value in [0.0, 1.0].
"""
def getFilter():
"""
Get the material's amount of filtering when transparent raytrace is enabled
@rtype: float
"""
def setTranslucency(translucency):
"""
Set the material's amount of diffuse shading of the back side
@type translucency: float
@param translucency: The new value in [0.0, 1.0].
"""
def getTranslucency():
"""
Get the material's amount of diffuse shading of the back side
@rtype: float
"""
def getAdd():
"""
Get the glow factor.
@rtype: float
"""
def setAdd(add):
"""
Set the glow factor.
@type add: float
@param add: The new value in [0.0, 1.0].
"""
def getZOffset():
"""
Get the artificial offset for faces with this Material.
@rtype: float
"""
def setZOffset(zoffset):
"""
Set the artificial offset for faces with this Material.
@type zoffset: float
@param zoffset: The new value in [0.0, 10.0].
"""
def getHaloSize():
"""
Get the halo size.
@rtype: float
"""
def setHaloSize(halosize):
"""
Set the halo size.
@type halosize: float
@param halosize: The new value in [0.0, 100.0].
"""
def getHaloSeed():
"""
Get the seed for random ring dimension and line location in halos.
@rtype: int
"""
def setHaloSeed(haloseed):
"""
Set the seed for random ring dimension and line location in halos.
@type haloseed: int
@param haloseed: The new value in [0, 255].
"""
def getFlareSize():
"""
Get the ratio: flareSize / haloSize.
@rtype: float
"""
def setFlareSize(flaresize):
"""
Set the ratio: flareSize / haloSize.
@type flaresize: float
@param flaresize: The new value in [0.1, 25.0].
"""
def getFlareSeed():
"""
Get flare's offset in the seed table.
@rtype: int
"""
def setFlareSeed(flareseed):
"""
Set flare's offset in the seed table.
@type flareseed: int
@param flareseed: The new value in [0, 255].
"""
def getFlareBoost():
"""
Get the flare's extra strength.
@rtype: float
"""
def setFlareBoost(flareboost):
"""
Set the flare's extra strength.
@type flareboost: float
@param flareboost: The new value in [0.1, 10.0].
"""
def getSubSize():
"""
Get the dimension of subflare, dots and circles.
@rtype: float
"""
def setSubSize(subsize):
"""
Set the dimension of subflare, dots and circles.
@type subsize: float
@param subsize: The new value in [0.1, 25.0].
"""
def getHardness():
"""
Get the hardness of the specularity.
@rtype: int
"""
def setHardness(hardness):
"""
Set the hardness of the specularity.
@type hardness: int
@param hardness: The new value in [1, 511].
"""
def getNFlares():
"""
Get the number of halo subflares.
@rtype: int
"""
def setNFlares(nflares):
"""
Set the number of halo subflares.
@type nflares: int
@param nflares: The new value in [1, 32].
"""
def getNStars():
"""
Get the number of points in the halo stars.
@rtype: int
"""
def setNStars(nstars):
"""
Set the number of points in the halo stars.
@type nstars: int
@param nstars: The new value in [3, 50].
"""
def getNLines():
"""
Get the number of star shaped lines on each halo.
@rtype: int
"""
def setNLines(nlines):
"""
Set the number of star shaped lines on each halo.
@type nlines: int
@param nlines: The new value in [0, 250].
"""
def getNRings():
"""
Get the number of rings on each halo.
@rtype: int
"""
def setNRings(nrings):
"""
Set the number of rings on each halo.
@type nrings: int
@param nrings: The new value in [0, 24].
"""
def getRayMirr():
"""
Get amount mirror reflection for raytrace.
@rtype: float
"""
def setRayMirr(nrmirr):
"""
Set amount mirror reflection for raytrace.
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def getRayMirrDepth():
"""
Get amount of inter-reflections calculated maximal.
@rtype: int
"""
def setRayMirrDepth(nrmirr):
"""
Set amount mirror reflection for raytrace.
@type nrmirr: int
@param nrmirr: The new value in [0.0, 1.0].
"""
def getFresnelMirr():
"""
Get power of Fresnel for mirror reflection.
@rtype: float
"""
def setFresnelMirr(nrmirr):
"""
Set power of Fresnel for mirror reflection.
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def getFresnelMirrFac():
"""
Get the number of Ray Mirror.
@rtype: float
"""
def setFresnelMirrFac(nrmirr):
"""
Set the number of ray mirror
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def getIOR():
"""
Get the angular index of refraction for raytrace.
@rtype: float
"""
def setIOR(nrmirr):
"""
Set the angular index of refraction for raytrace.
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def getTransDepth():
"""
Get amount of refractions calculated maximal.
@rtype: int
"""
def setTransDepth(nrmirr):
"""
Set amount of refractions calculated maximal.
@type nrmirr: int
@param nrmirr: The new value in [0.0, 1.0].
"""
def getFresnelTrans():
"""
Get power of Fresnel for transparency.
@rtype: float
"""
def setFresnelTrans(nrmirr):
"""
Set power of Fresnel for transparency.
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def getFresnelTransFac():
"""
Get blending factor for Fresnel.
@rtype: float
"""
def setFresnelTransFac(nrmirr):
"""
Set blending factor for Fresnel.
@type nrmirr: float
@param nrmirr: The new value in [0.0, 1.0].
"""
def setTexture(index, texture, texco, mapto):
"""
Assign a Blender Texture object to slot number 'number'.
@type index: int
@param index: material's texture index in [0, 9].
@type texture: Blender Texture
@param texture: a Blender Texture object.
@type texco: int
@param texco: optional ORed bitflag -- defaults to TexCo.ORCO. See TexCo var in L{Texture}.
@type mapto: int
@param mapto: optional ORed bitflag -- defaults to MapTo.COL. See MapTo var in L{Texture}.
"""
def clearTexture(index):
"""
Clear the ith (given by 'index') texture channel of this material.
@type index: int
@param index: material's texture channel index in [0, 9].
"""
def getTextures ():
"""
Get this Material's Texture list.
@rtype: list of MTex
@return: a list of Blender MTex objects. None is returned for each empty
texture slot.
"""
def getScriptLinks (event):
"""
Get a list with this Material's script links of type 'event'.
@type event: string
@param event: "FrameChanged" or "Redraw".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this Material. If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this Material.
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged" or "Redraw".
"""
def __copy__ ():
"""
Make a copy of this material
@rtype: Material
@return: a copy of this material
"""
import id_generics
Material.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,864 @@
# Blender.Mathutils module and its subtypes
"""
The Blender.Mathutils submodule.
Mathutils
=========
This module provides access to matrices, eulers, quaternions and vectors.
Example::
import Blender
from Blender import Mathutils
from Blender.Mathutils import *
vec = Vector([1,2,3])
mat = RotationMatrix(90, 4, 'x')
matT = TranslationMatrix(vec)
matTotal = mat * matT
matTotal.invert()
mat3 = matTotal.rotationPart
quat1 = mat.toQuat()
quat2 = mat3.toQuat()
angle = DifferenceQuats(quat1, quat2)
print angle
"""
def Rand (high = 1, low = 0):
"""
Return a random number within a range.
High and low represent the range from which the random
number must return its result.
@type high: float
@param high: The upper range.
@type low: float
@param low: The lower range.
"""
def Intersect(vec1, vec2, vec3, ray, orig, clip=1):
"""
Return the intersection between a ray and a triangle, if possible, return None otherwise.
@type vec1: Vector object.
@param vec1: A 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 3d vector, one corner of the triangle.
@type ray: Vector object.
@param ray: A 3d vector, the orientation of the ray. the length of the ray is not used, only the direction.
@type orig: Vector object.
@param orig: A 3d vector, the origin of the ray.
@type clip: integer
@param clip: if 0, don't restrict the intersection to the area of the triangle, use the infinite plane defined by the triangle.
@rtype: Vector object
@return: The intersection between a ray and a triangle, if possible, None otherwise.
"""
def TriangleArea(vec1, vec2, vec3):
"""
Return the area size of the 2D or 3D triangle defined.
@type vec1: Vector object.
@param vec1: A 2d or 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 2d or 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 2d or 3d vector, one corner of the triangle.
@rtype: float
@return: The area size of the 2D or 3D triangle defined.
"""
def TriangleNormal(vec1, vec2, vec3):
"""
Return the normal of the 3D triangle defined.
@type vec1: Vector object.
@param vec1: A 3d vector, one corner of the triangle.
@type vec2: Vector object.
@param vec2: A 3d vector, one corner of the triangle.
@type vec3: Vector object.
@param vec3: A 3d vector, one corner of the triangle.
@rtype: float
@return: The normal of the 3D triangle defined.
"""
def QuadNormal(vec1, vec2, vec3, vec4):
"""
Return the normal of the 3D quad defined.
@type vec1: Vector object.
@param vec1: A 3d vector, the first vertex of the quad.
@type vec2: Vector object.
@param vec2: A 3d vector, the second vertex of the quad.
@type vec3: Vector object.
@param vec3: A 3d vector, the third vertex of the quad.
@type vec4: Vector object.
@param vec4: A 3d vector, the fourth vertex of the quad.
@rtype: float
@return: The normal of the 3D quad defined.
"""
def LineIntersect(vec1, vec2, vec3, vec4):
"""
Return a tuple with the points on each line respectively closest to the other
(when both lines intersect, both vector hold the same value).
The lines are evaluated as infinite lines in space, the values returned may not be between the 2 points given for each line.
@type vec1: Vector object.
@param vec1: A 3d vector, one point on the first line.
@type vec2: Vector object.
@param vec2: A 3d vector, another point on the first line.
@type vec3: Vector object.
@param vec3: A 3d vector, one point on the second line.
@type vec4: Vector object.
@param vec4: A 3d vector, another point on the second line.
@rtype: (Vector object, Vector object)
@return: A tuple with the points on each line respectively closest to the other.
"""
def CopyVec(vector):
"""
Create a copy of the Vector object.
@attention: B{DEPRECATED} use vector.copy() instead.
@type vector: Vector object.
@param vector: A 2d,3d or 4d vector to be copied.
@rtype: Vector object.
@return: A new vector object which is a copy of the one passed in.
"""
def CrossVecs(vec1, vec2):
"""
Return the cross product of two vectors.
@type vec1: Vector object.
@param vec1: A 3d vector.
@type vec2: Vector object.
@param vec2: A 3d vector.
@rtype: Vector object.
@return: A new vector representing the cross product of
the two vectors.
"""
def DotVecs(vec1, vec2):
"""
Return the dot product of two vectors.
@type vec1: Vector object.
@param vec1: A 2d,3d or 4d vector.
@type vec2: Vector object.
@param vec2: A 2d,3d or 4d vector.
@rtype: float
@return: Return the scalar product of vector muliplication.
"""
def AngleBetweenVecs(vec1, vec2):
"""
Return the angle between two vectors. Zero length vectors raise an error.
@type vec1: Vector object.
@param vec1: A 2d or 3d vector.
@type vec2: Vector object.
@param vec2: A 2d or 3d vector.
@rtype: float
@return: The angle between the vectors in degrees.
@raise AttributeError: When there is a zero-length vector as an argument.
"""
def MidpointVecs(vec1, vec2):
"""
Return a vector to the midpoint between two vectors.
@type vec1: Vector object.
@param vec1: A 2d,3d or 4d vector.
@type vec2: Vector object.
@param vec2: A 2d,3d or 4d vector.
@rtype: Vector object
@return: The vector to the midpoint.
"""
def VecMultMat(vec, mat):
"""
Multiply a vector and matrix (pre-multiply)
Vector size and matrix column size must equal.
@type vec: Vector object.
@param vec: A 2d,3d or 4d vector.
@type mat: Matrix object.
@param mat: A 2d,3d or 4d matrix.
@rtype: Vector object
@return: The row vector that results from the muliplication.
@attention: B{DEPRECATED} You should now multiply vector * matrix direcly
Example::
result = myVector * myMatrix
"""
def ProjectVecs(vec1, vec2):
"""
Return the projection of vec1 onto vec2.
@type vec1: Vector object.
@param vec1: A 2d,3d or 4d vector.
@type vec2: Vector object.
@param vec2: A 2d,3d or 4d vector.
@rtype: Vector object
@return: The parallel projection vector.
"""
def RotationMatrix(angle, matSize, axisFlag, axis):
"""
Create a matrix representing a rotation.
@type angle: float
@param angle: The angle of rotation desired.
@type matSize: int
@param matSize: The size of the rotation matrix to construct.
Can be 2d, 3d, or 4d.
@type axisFlag: string (optional)
@param axisFlag: Possible values:
- "x - x-axis rotation"
- "y - y-axis rotation"
- "z - z-axis rotation"
- "r - arbitrary rotation around vector"
@type axis: Vector object. (optional)
@param axis: The arbitrary axis of rotation used with "R"
@rtype: Matrix object.
@return: A new rotation matrix.
"""
def TranslationMatrix(vector):
"""
Create a matrix representing a translation
@type vector: Vector object
@param vector: The translation vector
@rtype: Matrix object.
@return: An identity matrix with a translation.
"""
def ScaleMatrix(factor, matSize, axis):
"""
Create a matrix representing a scaling.
@type factor: float
@param factor: The factor of scaling to apply.
@type matSize: int
@param matSize: The size of the scale matrix to construct.
Can be 2d, 3d, or 4d.
@type axis: Vector object. (optional)
@param axis: Direction to influence scale.
@rtype: Matrix object.
@return: A new scale matrix.
"""
def OrthoProjectionMatrix(plane, matSize, axis):
"""
Create a matrix to represent an orthographic projection
@type plane: string
@param plane: Can be any of the following:
- "x - x projection (2D)"
- "y - y projection (2D)"
- "xy - xy projection"
- "xz - xz projection"
- "yz - yz projection"
- "r - arbitrary projection plane"
@type matSize: int
@param matSize: The size of the projection matrix to construct.
Can be 2d, 3d, or 4d.
@type axis: Vector object. (optional)
@param axis: Arbitrary perpendicular plane vector.
@rtype: Matrix object.
@return: A new projeciton matrix.
"""
def ShearMatrix(plane, factor, matSize):
"""
Create a matrix to represent an orthographic projection
@type plane: string
@param plane: Can be any of the following:
- "x - x shear (2D)"
- "y - y shear (2D)"
- "xy - xy shear"
- "xz - xz shear"
- "yz - yz shear"
@type factor: float
@param factor: The factor of shear to apply.
@type matSize: int
@param matSize: The size of the projection matrix to construct.
Can be 2d, 3d, or 4d.
@rtype: Matrix object.
@return: A new shear matrix.
"""
def CopyMat(matrix):
"""
Create a copy of the Matrix object.
@type matrix: Matrix object.
@param matrix: A 2d,3d or 4d matrix to be copied.
@rtype: Matrix object.
@return: A new matrix object which is a copy of the one passed in.
@attention: B{DEPRECATED} Use the matrix copy funtion to make a copy.
Example::
newMat = myMat.copy()
"""
def MatMultVec(mat, vec):
"""
Multiply a matrix and a vector (post-multiply)
Vector size and matrix row size must equal.
@type vec: Vector object.
@param vec: A 2d,3d or 4d vector.
@type mat: Matrix object.
@param mat: A 2d,3d or 4d matrix.
@rtype: Vector object
@return: The column vector that results from the muliplication.
@attention: B{DEPRECATED} You should use direct muliplication on the arguments
Example::
result = myMatrix * myVector
"""
def CopyQuat(quaternion):
"""
Create a copy of the Quaternion object.
@type quaternion: Quaternion object.
@param quaternion: Quaternion to be copied.
@rtype: Quaternion object.
@return: A new quaternion object which is a copy of the one passed in.
@attention: B{DEPRECATED} You should use the Quaterion() constructor directly
to create copies of quaternions
Example::
newQuat = Quaternion(myQuat)
"""
def CrossQuats(quat1, quat2):
"""
Return the cross product of two quaternions.
@type quat1: Quaternion object.
@param quat1: Quaternion.
@type quat2: Quaternion object.
@param quat2: Quaternion.
@rtype: Quaternion object.
@return: A new quaternion representing the cross product of
the two quaternions.
"""
def DotQuats(quat1, quat2):
"""
Return the dot product of two quaternions.
@type quat1: Quaternion object.
@param quat1: Quaternion.
@type quat2: Quaternion object.
@param quat2: Quaternion.
@rtype: float
@return: Return the scalar product of quaternion muliplication.
"""
def DifferenceQuats(quat1, quat2):
"""
Returns a quaternion represting the rotational difference.
@type quat1: Quaternion object.
@param quat1: Quaternion.
@type quat2: Quaternion object.
@param quat2: Quaternion.
@rtype: Quaternion object
@return: Return a quaternion which which represents the rotational
difference between the two quat rotations.
"""
def Slerp(quat1, quat2, factor):
"""
Returns the interpolation of two quaternions.
@type quat1: Quaternion object.
@param quat1: Quaternion.
@type quat2: Quaternion object.
@param quat2: Quaternion.
@type factor: float
@param factor: The interpolation value
@rtype: Quaternion object
@return: The interpolated rotation.
"""
def CopyEuler(euler):
"""
Create a new euler object.
@type euler: Euler object
@param euler: The euler to copy
@rtype: Euler object
@return: A copy of the euler object passed in.
@attention: B{DEPRECATED} You should use the Euler constructor directly
to make copies of Euler objects
Example::
newEuler = Euler(myEuler)
"""
def RotateEuler(euler, angle, axis):
"""
Roatate a euler by an amount in degrees around an axis.
@type euler: Euler object
@param euler: Euler to rotate.
@type angle: float
@param angle: The amount of rotation in degrees
@type axis: string
@param axis: axis to rotate around:
- "x"
- "y"
- "z"
"""
class Vector:
"""
The Vector object
=================
This object gives access to Vectors in Blender.
@ivar x: The x value.
@ivar y: The y value.
@ivar z: The z value (if any).
@ivar w: The w value (if any).
@ivar length: The magnitude of the vector.
@ivar magnitude: This is a synonym for length.
@ivar wrapped: Whether or not this item is wrapped data
@note: Comparison operators can be done on Vector classes:
- >, >=, <, <= test the vector magnitude
- ==, != test vector values e.g. 1,2,3 != 1,2,4 even if they are the same length
@note: Math can be performed on Vector classes
- vec + vec
- vec - vec
- vec * float/int
- vec * matrix
- vec * vec
- vec * quat
- -vec
@note: You can access a vector object like a sequence
- x = vector[0]
@attention: Vector data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
Example::
wrappedObject = Object.getAttribute() #this is wrapped data
print wrappedObject.wrapped #prints 'True'
copyOfObject = Object(wrappedObject) #creates a copy of the object
secondPointer = wrappedObject #creates a second pointer to the same data
print wrappedObject.attribute #prints '5'
secondPointer.attribute = 10
print wrappedObject.attribute #prints '10'
print copyOfObject.attribute #prints '5'
"""
def __init__(list = None):
"""
Create a new 2d, 3d, or 4d Vector object from a list of floating point numbers.
@note: that python uses higher precission floating point numbers, so values assigned to a vector may have some rounding error.
Example::
v = Vector(1,0,0)
v = Vector(myVec)
v = Vector(list)
@type list: PyList of float or int
@param list: The list of values for the Vector object. Can be a sequence or raw numbers.
Must be 2, 3, or 4 values. The list is mapped to the parameters as [x,y,z,w].
@rtype: Vector object.
@return: It depends wheter a parameter was passed:
- (list): Vector object initialized with the given values;
- (): An empty 3 dimensional vector.
"""
def copy():
"""
Returns a copy of this vector
@return: a copy of itself
"""
def zero():
"""
Set all values to zero.
@return: an instance of itself
"""
def normalize():
"""
Normalize the vector, making the length of the vector always 1.0
@note: Normalize works for vectors of all sizes, however 4D Vectors w axis is left untouched.
@note: Normalizing a vector where all values are zero results in all axis having a nan value (not a number).
@return: an instance of itself
"""
def negate():
"""
Set all values to their negative.
@return: an instance of its self
"""
def resize2D():
"""
Resize the vector to 2d.
@return: an instance of itself
"""
def resize3D():
"""
Resize the vector to 3d. New axis will be 0.0.
@return: an instance of itself
"""
def resize4D():
"""
Resize the vector to 4d. New axis will be 0.0.
The last component will be 1.0, to make multiplying 3d vectors by 4x4 matrices easier.
@return: an instance of itself
"""
def toTrackQuat(track, up):
"""
Return a quaternion rotation from the vector and the track and up axis.
@type track: String.
@param track: Possible values:
- "x - x-axis up"
- "y - y-axis up"
- "z - z-axis up"
- "-x - negative x-axis up"
- "-y - negative y-axis up"
- "-z - negative z-axis up"
@type up: String.
@param up: Possible values:
- "x - x-axis up"
- "y - y-axis up"
- "z - z-axis up"
@rtype: Quaternion
@return: Return a quaternion rotation from the vector and the track and up axis.
"""
class Euler:
"""
The Euler object
================
This object gives access to Eulers in Blender.
@ivar x: The heading value in degrees.
@ivar y: The pitch value in degrees.
@ivar z: The roll value in degrees.
@ivar wrapped: Whether or not this object is wrapping data directly
@note: You can access a euler object like a sequence
- x = euler[0]
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@attention: Euler data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
Example::
wrappedObject = Object.getAttribute() #this is wrapped data
print wrappedObject.wrapped #prints 'True'
copyOfObject = Object(wrappedObject) #creates a copy of the object
secondPointer = wrappedObject #creates a second pointer to the same data
print wrappedObject.attribute #prints '5'
secondPointer.attribute = 10
print wrappedObject.attribute #prints '10'
print copyOfObject.attribute #prints '5'
"""
def __init__(list = None):
"""
Create a new euler object.
Example::
euler = Euler(45,0,0)
euler = Euler(myEuler)
euler = Euler(sequence)
@type list: PyList of float/int
@param list: 3d list to initialize euler
@rtype: Euler object
@return: Euler representing heading, pitch, bank.
@note: Values are in degrees.
"""
def zero():
"""
Set all values to zero.
@return: an instance of itself
"""
def copy():
"""
@return: a copy of this euler.
"""
def unique():
"""
Calculate a unique rotation for this euler. Avoids gimble lock.
@return: an instance of itself
"""
def toMatrix():
"""
Return a matrix representation of the euler.
@rtype: Matrix object
@return: A roation matrix representation of the euler.
"""
def toQuat():
"""
Return a quaternion representation of the euler.
@rtype: Quaternion object
@return: Quaternion representation of the euler.
"""
class Quaternion:
"""
The Quaternion object
=====================
This object gives access to Quaternions in Blender.
@ivar w: The w value.
@ivar x: The x value.
@ivar y: The y value.
@ivar z: The z value.
@ivar wrapped: Wether or not this object wraps data directly
@ivar magnitude: The magnitude of the quaternion.
@ivar axis: Vector representing the axis of rotation.
@ivar angle: A scalar representing the amount of rotation
in degrees.
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@note: Math can be performed on Quaternion classes
- quat + quat
- quat - quat
- quat * float/int
- quat * vec
- quat * quat
@note: You can access a quaternion object like a sequence
- x = quat[0]
@attention: Quaternion data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
Example::
wrappedObject = Object.getAttribute() #this is wrapped data
print wrappedObject.wrapped #prints 'True'
copyOfObject = Object(wrappedObject) #creates a copy of the object
secondPointer = wrappedObject #creates a second pointer to the same data
print wrappedObject.attribute #prints '5'
secondPointer.attribute = 10
print wrappedObject.attribute #prints '10'
print copyOfObject.attribute #prints '5'
"""
def __init__(list, angle = None):
"""
Create a new quaternion object from initialized values.
Example::
quat = Quaternion(1,2,3,4)
quat = Quaternion(axis, angle)
quat = Quaternion()
quat = Quaternion(180, list)
@type list: PyList of int/float
@param list: A 3d or 4d list to initialize quaternion.
4d if intializing [w,x,y,z], 3d if used as an axis of rotation.
@type angle: float (optional)
@param angle: An arbitrary rotation amount around 'list'.
List is used as an axis of rotation in this case.
@rtype: New quaternion object.
@return: It depends wheter a parameter was passed:
- (list/angle): Quaternion object initialized with the given values;
- (): An identity 4 dimensional quaternion.
"""
def identity():
"""
Set the quaternion to the identity quaternion.
@return: an instance of itself
"""
def copy():
"""
make a copy of the quaternion.
@return: a copy of itself
"""
def negate():
"""
Set the quaternion to its negative.
@return: an instance of itself
"""
def conjugate():
"""
Set the quaternion to its conjugate.
@return: an instance of itself
"""
def inverse():
"""
Set the quaternion to its inverse
@return: an instance of itself
"""
def normalize():
"""
Normalize the quaternion.
@return: an instance of itself
"""
def toEuler():
"""
Return Euler representation of the quaternion.
@rtype: Euler object
@return: Euler representation of the quaternion.
"""
def toMatrix():
"""
Return a matrix representation of the quaternion.
@rtype: Matrix object
@return: A rotation matrix representation of the quaternion.
"""
class Matrix:
"""
The Matrix Object
=================
This object gives access to Matrices in Blender.
@ivar rowSize: The row size of the matrix.
@ivar colSize: The column size of the matrix.
@ivar wrapped: Whether or not this object wrapps internal data
@note: Math can be performed on Matrix classes
- mat + mat
- mat - mat
- mat * float/int
- mat * vec
- mat * mat
@note: Comparison operators can be done:
- ==, != test numeric values within epsilon
@note: You can access a quaternion object like a 2d sequence
- x = matrix[0][1]
- vector = matrix[2]
@attention: Quaternion data can be wrapped or non-wrapped. When a object is wrapped it
means that the object will give you direct access to the data inside of blender. Modification
of this object will directly change the data inside of blender. To copy a wrapped object
you need to use the object's constructor. If you copy and object by assignment you will not get
a second copy but a second reference to the same data. Only certain functions will return
wrapped data. This will be indicated in the method description.
Example::
wrappedObject = Object.getAttribute() #this is wrapped data
print wrappedObject.wrapped #prints 'True'
copyOfObject = Object(wrappedObject) #creates a copy of the object
secondPointer = wrappedObject #creates a second pointer to the same data
print wrappedObject.attribute #prints '5'
secondPointer.attribute = 10
print wrappedObject.attribute #prints '10'
print copyOfObject.attribute #prints '5'
"""
def __init__(list1 = None, list2 = None, list3 = None, list4 = None):
"""
Create a new matrix object from initialized values.
Example::
matrix = Matrix([1,1,1],[0,1,0],[1,0,0])
matrix = Matrix(mat)
matrix = Matrix(seq1, seq2, vector)
@type list1: PyList of int/float
@param list1: A 2d,3d or 4d list.
@type list2: PyList of int/float
@param list2: A 2d,3d or 4d list.
@type list3: PyList of int/float
@param list3: A 2d,3d or 4d list.
@type list4: PyList of int/float
@param list4: A 2d,3d or 4d list.
@rtype: New matrix object.
@return: It depends wheter a parameter was passed:
- (list1, etc.): Matrix object initialized with the given values;
- (): An empty 3 dimensional matrix.
"""
def zero():
"""
Set all matrix values to 0.
@return: an instance of itself
"""
def copy():
"""
Returns a copy of this matrix
@return: a copy of itself
"""
def identity():
"""
Set the matrix to the identity matrix.
An object with zero location and rotation, a scale of 1, will have an identity matrix.
See U{http://en.wikipedia.org/wiki/Identity_matrix}
@return: an instance of itself
"""
def transpose():
"""
Set the matrix to its transpose.
See U{http://en.wikipedia.org/wiki/Transpose}
@return: None
"""
def determinant():
"""
Return the determinant of a matrix.
See U{http://en.wikipedia.org/wiki/Determinant}
@rtype: float
@return: Return a the determinant of a matrix.
"""
def invert():
"""
Set the matrix to its inverse.
See U{http://en.wikipedia.org/wiki/Inverse_matrix}
@return: an instance of itself.
@raise ValueError: When matrix is singular.
"""
def rotationPart():
"""
Return the 3d submatrix corresponding to the linear term of the
embedded affine transformation in 3d. This matrix represents rotation
and scale. Note that the (4,4) element of a matrix can be used for uniform
scaling, too.
@rtype: Matrix object.
@return: Return the 3d matrix for rotation and scale.
"""
def translationPart():
"""
Return a the translation part of a 4 row matrix.
@rtype: Vector object.
@return: Return a the translation of a matrix.
"""
def scalePart():
"""
Return a the scale part of a 3x3 or 4x4 matrix.
@note: This method does not return negative a scale on any axis because it is not possible to obtain this data from the matrix alone.
@rtype: Vector object.
@return: Return a the scale of a matrix.
"""
def resize4x4():
"""
Resize the matrix to by 4x4
@return: an instance of itself.
"""
def toEuler():
"""
Return an Euler representation of the rotation matrix (3x3 or 4x4 matrix only).
@rtype: Euler object
@return: Euler representation of the rotation matrix.
"""
def toQuat():
"""
Return a quaternion representation of the rotation matrix
@rtype: Quaternion object
@return: Quaternion representation of the rotation matrix
"""

View File

@@ -0,0 +1,1210 @@
# Blender.Mesh module and the Mesh PyType object
"""
The Blender.Mesh submodule.
B{New}:
Mesh Data
=========
This module provides access to B{Mesh Data} objects in Blender. It differs
from the NMesh module by allowing direct access to the actual Blender data,
so that changes are done immediately without need to update or put the data
back into the original mesh. The result is faster operations with less memory
usage. The example below creates a simple pyramid, and sets some of the
face's attributes (the vertex color):
Example::
from Blender import *
import bpy
editmode = Window.EditMode() # are we in edit mode? If so ...
if editmode: Window.EditMode(0) # leave edit mode before getting the mesh
# define vertices and faces for a pyramid
coords=[ [-1,-1,-1], [1,-1,-1], [1,1,-1], [-1,1,-1], [0,0,1] ]
faces= [ [3,2,1,0], [0,1,4], [1,2,4], [2,3,4], [3,0,4] ]
me = bpy.data.meshes.new('myMesh') # create a new mesh
me.verts.extend(coords) # add vertices to mesh
me.faces.extend(faces) # add faces to the mesh (also adds edges)
me.vertexColors = 1 # enable vertex colors
me.faces[1].col[0].r = 255 # make each vertex a different color
me.faces[1].col[1].g = 255
me.faces[1].col[2].b = 255
scn = bpy.data.scenes.active # link object to current scene
ob = scn.objects.new(me, 'myObj')
if editmode: Window.EditMode(1) # optional, just being nice
Vertices, edges and faces are added to a mesh using the .extend() methods.
For best speed and efficiency, gather all vertices, edges or faces into a
list and call .extend() once as in the above example. Similarly, deleting
from the mesh is done with the .delete() methods and are most efficient when
done once.
@type Modes: readonly dictionary
@type FaceFlags: readonly dictionary
@type FaceModes: readonly dictionary
@type FaceTranspModes: readonly dictionary
@var Modes: The available mesh modes.
- NOVNORMALSFLIP - no flipping of vertex normals during render.
- TWOSIDED - double sided mesh.
- AUTOSMOOTH - turn auto smoothing of faces "on".
- note: SUBSURF and OPTIMAL have been removed, use Modifiers to apply subsurf.
@var FaceFlags: The available *texture face* (uv face select mode) selection
flags. Note: these refer to TexFace faces, available if mesh.faceUV
returns true.
- SELECT - selected (deprecated in versions after 2.43, use face.sel).
- HIDE - hidden (deprecated in versions after 2.43, use face.hide).
- ACTIVE - the active face, read only - Use L{mesh.activeFace<Mesh.Mesh.activeFace>} to set.
@var FaceModes: The available *texture face* modes. Note: these are only
meaningful if mesh.faceUV returns true, since in Blender this info is
stored at the TexFace (TexFace button in Edit Mesh buttons) structure.
- ALL - set all modes at once.
- BILLBOARD - always orient after camera.
- HALO - halo face, always point to camera.
- DYNAMIC - respond to collisions.
- INVISIBLE - invisible face.
- LIGHT - dynamic lighting.
- OBCOL - use object color instead of vertex colors.
- SHADOW - shadow type.
- SHAREDVERT - apparently unused in Blender.
- SHAREDCOL - shared vertex colors (per vertex).
- TEX - has texture image.
- TILES - uses tiled image.
- TWOSIDE - two-sided face.
@var FaceTranspModes: The available face transparency modes. Note: these are
enumerated values (enums), they can't be combined (ANDed, ORed, etc) like a bit vector.
- SOLID - draw solid.
- ADD - add to background (halo).
- ALPHA - draw with transparency.
- SUB - subtract from background.
@var EdgeFlags: The available edge flags.
- SELECT - selected (B{deprecated}). Use edge.sel attribute instead.
- EDGEDRAW - edge is drawn out of edition mode.
- EDGERENDER - edge is drawn out of edition mode.
- SEAM - edge is a seam for UV unwrapping
- FGON - edge is part of a F-Gon.
- LOOSE - Edge is not a part of a face (only set on leaving editmode)
- SHARP - Edge will be rendered sharp when used with the "Edge Split" modifier.
@type AssignModes: readonly dictionary.
@var AssignModes: The available vertex group assignment modes, used by
L{mesh.assignVertsToGroup()<Mesh.Mesh.assignVertsToGroup>}.
- ADD: if the vertex in the list is not assigned to the group
already, this creates a new association between this vertex and the
group with the weight specified, otherwise the weight given is added to
the current weight of an existing association between the vertex and
group.
- SUBTRACT: will attempt to subtract the weight passed from a vertex
already associated with a group, else it does nothing.\n
- REPLACE: attempts to replace a weight with the new weight value
for an already associated vertex/group, else it does nothing.
@type SelectModes: readonly dictionary.
@var SelectModes: The available edit select modes.
- VERTEX: vertex select mode.
- EDGE: edge select mode.
- FACE: face select mode.
"""
AssignModes = {'REPLACE':1}
def Get(name=None):
"""
Get the mesh data object called I{name} from Blender.
@type name: string
@param name: The name of the mesh data object.
@rtype: Mesh
@return: If a name is given, it returns either the requested mesh or None.
If no parameter is given, it returns all the meshes in the current scene.
"""
def New(name='Mesh'):
"""
Create a new mesh data object called I{name}.
@type name: string
@param name: The name of the mesh data object.
@rtype: Mesh
@return: a new Blender mesh.
@note: if the mesh is not linked to an object, its datablock will be deleted
when the object is deallocated.
"""
def Mode(mode=0):
"""
Get and/or set the selection modes for mesh editing. These are the modes
visible in the 3D window when a mesh is in Edit Mode.
@type mode: int
@param mode: The desired selection mode. See L{SelectModes} for values.
Modes can be combined. If omitted, the selection mode is not changed.
@rtype: int
@return: the current selection mode.
@note: The selection mode is an attribute of the current scene. If the
scene is changed, the selection mode may not be the same.
"""
def Unlink(name):
"""
Delete an unused mesh from Blender's database. The mesh must not have
any users (i.e., it must not be linked to any object).
@type name: string
@param name: The name of the mesh data object.
@rtype: None
@note: This function may be a temporary solution; it may be replaced
in the future by a more general unlink function for many datablock types.
Hopefully this will be decided prior to the 2.42 release of Blender.
"""
class MCol:
"""
The MCol object
===============
This object is four ints representing an RGBA color.
@ivar r: The Red component in [0, 255].
@type r: int
@ivar g: The Green component in [0, 255].
@type g: int
@ivar b: The Blue component in [0, 255].
@type b: int
@ivar a: The Alpha (transparency) component in [0, 255].
@type a: int
"""
class MVert:
"""
The MVert object
================
This object holds mesh vertex data.
@ivar co: The vertex coordinates (x, y, z).
@type co: vector (WRAPPED DATA)
@ivar no: The vertex's unit normal vector (x, y, z).
B{Note}: if vertex coordinates are changed, it may be necessary to use
L{Mesh.calcNormals()} to update the vertex normals.
B{Note}: Vertex normals can be set, but are not wrapped so modifying a normal
vector will not effect the verts normal. The result is only visible
when faces have the smooth option enabled.
Example::
# This won't work.
for v in me.verts:
v.no.x= 0
v.no.y= 0
v.no.z= 1
# This will work
no= Blender.Mathutils.Vector(0,0,1)
for v in me.verts:
v.no= no
@type no: vector
@ivar uvco: The vertex texture "sticky" coordinates (x, y),
B{Note}: These are not seen in the UV editor and they are not a part of UV a UVLayer. Use face UV's for that.
if present. Available for MVerts only.
Use L{Mesh.vertexUV} to test for presence before trying to access;
otherwise an exception will may be thrown.
(Sticky coordinates can be set when the object is in the Edit mode;
from the Editing Panel (F9), look under the "Mesh" properties for the
"Sticky" button).
@type uvco: vector (WRAPPED DATA)
@ivar index: The vertex's index within the mesh (MVerts only). Read-only.
@type index: int
@ivar sel: The vertex's selection state (selected=1).
B{Note}: a Mesh will return the selection state of the mesh when EditMode
was last exited. A Python script operating in EditMode must exit EditMode
before getting the current selection state of the mesh.
@type sel: int
@ivar hide: The face's B{edit mode} visibility state (hidden=1).
@type hide: int
@warn: There are two kinds of UV texture coordinates in Blender: per vertex
("sticky") and per face vertex (UV in L{MFace}). In the first, there's
only one UV pair of coordinates for each vertex in the mesh. In the
second, for each face it belongs to, a vertex can have different UV
coordinates. This makes the per face option more flexible, since two
adjacent faces won't have to be mapped to a continuous region in an image:
each face can be independently mapped to any part of its texture.
"""
def __init__(coord):
"""
Create a new PVert object.
@note: PVert-type objects are designed to be used for creating and
modifying a mesh's vertex list, but since they do not "wrap" any Blender
data there are some differences. The B{index} and B{uvco} attributes
are not defined for PVerts, and the B{no} attribute contains valid
data only if the PVert was created from an MVert (using a slice
operation on the mesh's vertex list.) PVerts also cannot be used as an
argument to any method which expects data wrapping a Blender mesh, such
as L{MVertSeq.delete()}.
Example::
v = Blender.Mesh.MVert(1,0,0)
v = Blender.Mesh.MVert(Blender.Mathutils.Vector([1,0,0]))
m = Blender.Mesh.Get('Mesh')
vlist = m.verts[:] # slice operation also returns PVerts
@type coord: three floats or a Vector object
@param coord: the coordinate values for the new vertex
@rtype: PVert
@return: a new PVert object
"""
class MVertSeq:
"""
The MVertSeq object
===================
This object provides sequence and iterator access to the mesh's vertices.
Access and assignment of single items and slices are also supported.
When a single item in the vertex list is accessed, the operator[] returns
a MVert object which "wraps" the actual vertex in the mesh; changing any
of the vertex's attributes will immediately change the data in the mesh.
When a slice of the vertex list is accessed, however, the operator[]
returns a list of PVert objects which are copies of the mesh's vertex
data. Changes to these objects have no effect on the mesh; they must be
assigned back to the mesh's vertex list.
Slice assignments cannot change the vertex list size. The size of the
list being assigned must be the same as the specified slice; otherwise an
exception is thrown.
Example::
import Blender
from Blender import Mesh
me = Mesh.Get("Plane") # get the mesh data called "Plane"
vert = me.verts[0] # vert accesses actual mesh data
vert.co[0] += 2 # change the vertex's X location
pvert = me.verts[-2:] # pvert is COPY of mesh's last two verts
pvert[0].co[0] += 2 # change the vertex's X location
pvert[1].co[0] += 2 # change the vertex's X location
me.verts[-1] = pvert[1] # put change to second vertex into mesh
@note: The mesh can be "cleared" by assigning B{None} to the mesh's vertex
list. This does not delete the Blender mesh object, it only deletes all
the memory allocated to the mesh. The result is equivalent to calling
Mesh.New(). The intent is to allow users writing exporters to free memory
after it is used in a quick and simple way.
Example::
import Blender
from Blender import Mesh
me = Mesh.Get("Plane") # get the mesh data called "Plane"
me.verts = None # delete all the mesh's attributes
"""
def extend(coords):
"""
Append zero or more vertices to the mesh. Unlike L{MEdgeSeq.extend()} and
L{MFaceSeq.extend()} no attempt is made to check for duplicate vertices in
the parameter list, or for vertices already in the mesh.
@note: Since Blender 2.44 all new verts are selected.
Example::
import Blender
from Blender import Mesh
from Blender.Mathutils import Vector
me = Mesh.Get("Plane") # get the mesh data called "Plane"
me.verts.extend(1,1,1) # add one vertex
l=[(.1,.1,.1),Vector([2,2,.5])]
me.verts.extend(l) # add multiple vertices
@type coords: sequences(s) of floats or vectors
@param coords: coords can be
- a sequence of three floats,
- a 3D vector, or
- a sequence (list or tuple) of either of the above.
"""
def delete(verts):
"""
Deletes one or more vertices from the mesh. Any edge or face which
uses the specified vertices are also deleted.
@type verts: multiple ints or MVerts
@param verts: can be
- a single MVert belonging to the mesh (B{note:} will not work with
PVerts)
- a single integer, specifying an index into the mesh's vertex list
- a sequence (list or tuple) containing two or more of either of
the above.
"""
def selected():
"""
Get selected vertices.
@return: a list of the indices for all vertices selected in edit mode.
@rtype: list of ints
"""
class MEdge:
"""
The MEdge object
================
This object holds mesh edge data.
@ivar v1: The first vertex of the edge.
@type v1: MVert
@ivar v2: The second vertex of the edge.
@type v2: MVert
@ivar length: The length of the edge, same as (ed.v1.co-ed.v2.co).length where "ed" is an MEdge.
@type length: float
@ivar crease: The crease value of the edge. It is in the range [0,255].
@type crease: int
@ivar flag: The bitfield describing edge properties. See L{EdgeFlags}.
Example::
# This script counts fgon and non fgon edges
from Blender import Scene, Mesh
scn= Scene.GetCurrent() # Current scene, important to be scene aware
ob= scn.objects.active # last selected object
me= ob.getData(mesh=1) # thin wrapper doesn't copy mesh data like nmesh
total_fgon_eds= total_nor_eds= 0
# Look through the edges and find any fgon edges, then print the findings to the console
for ed in me.edges: # all meshes have edge data now
if ed.flag & Mesh.EdgeFlags.FGON:
total_fgon_eds+=1
else:
total_nor_eds+=1
print 'Blender has', total_fgon_eds, 'fgon edges and', total_nor_eds, 'non fgon edges'
@type flag: int
@ivar index: The edge's index within the mesh. Read-only.
@type index: int
@ivar sel: The edge's B{edit mode} selection state (selected=1). B{Note}:
changing the select state of an edge changes the select state of the edge's
vertices.
@type sel: int
@ivar key: The edge's vert indices in an ordered tuple, which can be used
as a dictionary key. Read-only.
This is the same as (min(ed.v1.index, ed.v2.index), max(ed.v1.index, ed.v2.index))
@type key: tuple
"""
def __iter__():
"""
Iterator for MEdge. It iterates over the MVerts of the edge, returning
v1 then v2.
@return: one of the edge's vertices
@rtype: MVert
"""
class MEdgeSeq:
"""
The MEdgeSeq object
===================
This object provides sequence and iterator access to the mesh's edges.
"""
def extend(vertseq):
"""
Add zero or more edges to the mesh. Edges which already exist in the
mesh or with both vertices the same are ignored. If three or four verts
are specified in any sequence, an edge is also created between the first
and last vertices (this is useful when adding faces).
@note: Since Blender 2.44 all new edges are selected.
Example::
import Blender
from Blender import Mesh
me = Mesh.Get("Plane") # get the mesh data called "Plane"
v = me.verts # get vertices
if len(v) >= 6: # if there are enough vertices...
me.edges.extend(v[0],v[1]) # add a single edge
l=[(v[1],v[2],v[3]),[0,2,4,5]]
me.edges.extend(l) # add multiple edges
@type vertseq: sequence(s) of ints or MVerts
@param vertseq: either two to four ints or MVerts, or sequence
(list or tuple) of sequences each containing two to four ints or MVerts.
"""
def delete(edges):
"""
Deletes one or more edges from the mesh. In addition, also delete:
- any faces which uses the specified edge(s)
- any "orphan" vertices (belonging only to specified edge(s))
@type edges: multiple ints or MEdges
@param edges: can be
- a single MEdge belonging to the mesh
- a single integer, specifying an index into the mesh's edge list
- a sequence (list or tuple) containing two or more of either of
the above.
"""
def selected():
"""
Get selected edges.
Selected edges are those for which both vertices are selected.
@return: a list of the indices for all edges selected in edit mode.
@rtype: list of ints
"""
class MFace:
"""
The MFace object
================
This object holds mesh face data.
Example::
import Blender
from Blender import Mesh, Window
in_emode = Window.EditMode()
if in_emode: Window.EditMode(0)
me = Mesh.Get("Mesh")
faces = me.faces
## Example for editmode faces selection:
selected_faces = []
for f in faces:
if f.sel:
selected_faces.append(f)
# ... unselect selected and select all the others:
for f in faces:
f.sel = not f.sel # 1 becomes 0, 0 becomes 1
## Example for UV textured faces selection:
selected_faces = []
SEL = Mesh.FaceFlags['SELECT']
# get selected faces:
for f in faces:
if f.flag & SEL:
selected_faces.append(f)
# ... unselect selected and select all the others:
for f in faces:
if f.flag & SEL:
f.flag &= ~SEL # unselect these
else:
f.flag |= SEL # and select these
if in_emode: Window.EditMode(1)
Blender.Redraw()
@ivar verts: The face's vertices. Each face has 3 or 4 vertices.
@type verts: list of MVerts
@ivar v: Same as L{verts}. This attribute is only for compatibility with
NMesh scripts and will probably be deprecated in the future.
@ivar sel: The face's B{edit mode} selection state (selected=1).
This is not the same as the selection state of the textured faces
(see L{flag}). B{Note}: changing the select state of a face changes
the select state of the face's vertices.
@type sel: int
@ivar hide: The face's B{edit mode} visibility state (hidden=1).
This is not the same as the visibility state of
the textured faces (see L{flag}).
@type hide: int
@ivar smooth: If set, the vertex normals are averaged to make this
face look smooth. (This is the same as choosing "Set Smooth" in the
Editing Panel (F9) under "Link and Material" properties).
@type smooth: int
@ivar col: The face's vertex colors, if defined. Each vertex has its own
color.
Will throw an exception if L{Mesh.vertexColors} is False.
Example::
# This example uses vertex normals to apply normal colors to each face.
import bpy
from Blender import Window
scn= bpy.scenes.active # Current scene, important to be scene aware
ob= scn.objects.active # last selected object
me= ob.getData(mesh=1) # thin wrapper doesn't copy mesh data like nmesh
me.vertexColors= True # Enable face, vertex colors
for f in me.faces:
for i, v in enumerate(f):
no= v.no
col= f.col[i]
col.r= int((no.x+1)*128)
col.g= int((no.y+1)*128)
col.b= int((no.z+1)*128)
Window.RedrawAll()
@type col: tuple of MCols
@ivar mat: The face's index into the mesh's materials
list. It is in the range [0,15].
@type mat: int
@ivar image: The Image used as a texture for this face.
Setting this attribute will create UV faces if they do not exist.
Getting this attribute throw an exception if the mesh does not have
UV faces; use L{Mesh.faceUV} to test.
Assigning an image will automatically set the TEX attribute of the
L{mode} bitfield. Use "del f.image" or "f.image = None" to clear the
image assigned to the face.
@type image: Image
@ivar mode: The texture mode bitfield (see L{FaceModes}).
Will throw an exception if the mesh does not have UV faces; use
L{Mesh.faceUV} to test.
@type mode: int
@ivar index: The face's index within the mesh. Read-only.
@type index: int
@ivar flag: The face's B{texture mode} flags; indicates the selection,
active , and visibility states of a textured face (see
L{FaceFlags} for values).
This is not the same as the selection or visibility states of
the faces in edit mode (see L{sel} and L{hide}).
To set the active face, use
the L{Mesh.activeFace} attribute instead.
Will throw an exception if the mesh does not have UV faces; use
L{Mesh.faceUV} to test.
@ivar transp: Transparency mode. It is one of the values in
L{FaceTranspModes}).
Will throw an exception if the mesh does not have UV faces; use
L{Mesh.faceUV} to test.
@type transp: int
@ivar uv: The face's UV coordinates. Each vertex has its own UV coordinate.
Setting this attribute will create UV faces if they do not exist.
Getting this attribute throw an exception if the mesh does not have
UV faces; use L{Mesh.faceUV} to test.
@type uv: tuple of vectors (WRAPPED DATA)
@ivar uvSel: The face's UV coordinates selection state; a 1 indicates the
vertex is selected. Each vertex has its own UV coordinate select state
(this is not the same as the vertex's edit mode selection state).
Setting this attribute will create UV faces if they do not exist.
Getting this attribute throw an exception if the mesh does not have
UV faces; use L{Mesh.faceUV} to test.
@type uvSel: tuple of ints
@ivar no: The face's normal vector (x, y, z). Read-only.
@type no: vector
@ivar cent: The center of the face. Read-only.
@type cent: vector
@ivar area: The area of the face. Read-only.
@type area: float
@ivar edge_keys: A tuple, each item a key that can reference an edge by its
ordered indices. Read-only. This is useful for building connectivity data.
Example::
from Blender import Mesh
me = Mesh.Get('Cube')
# a dictionary where the edge is the key, and a list of faces that use it are the value
edge_faces = dict([(ed.key, []) for ed in me.edges])
# Add the faces to the dict
for f in me.faces:
for key in f.edge_keys:
edge_faces[key].append(f) # add this face to the edge as a user
# Print the edges and the number of face users
for key, face_users in edge_faces.iteritems():
print 'Edge:', key, 'uses:', len(face_users),'faces'
@type edge_keys: tuple
@note: there are regular faces and textured faces in Blender, both currently
with their own selection and visibility states, due to a mix of old and new
code. To (un)select or (un)hide regular faces (visible in EditMode), use
L{MFace.sel} and L{MFace.hide} attributes. For textured faces (UV Face
Select and Paint modes in Blender) use the L{MFace.flag} attribute.
Check the example above and note L{Window.EditMode}.
@note: Assigning UV textures to mesh faces in Blender works like this:
1. Select your mesh.
2. Enter face select mode (press f) and select at least some face(s).
3. In the UV/Image Editor window, load / select an image.
4. Play in both windows (better split the screen to see both at the same
time) until the UV coordinates are where you want them. Hint: in the
3D window, the 'u' key opens a menu of default UV choices and the 'r'
key lets you rotate the UV coords.
5. Leave face select mode (press f).
"""
def __iter__():
"""
Iterator for MVert. It iterates over the MVerts of the face, returning
v1, v2, v3 (and optionally v4);
@return: one of the face's vertices
@rtype: MVert
"""
def __len__():
"""
len for MVert. It returns the number of vertices in the face.
@rtype: int
"""
class MFaceSeq:
"""
The MFaceSeq object
===================
This object provides sequence and iterator access to the mesh's faces.
"""
def extend(vertseq,ignoreDups=True,indexList=True):
"""
Add zero or more faces and edges to the mesh. Faces which already exist
in the mesh, or faces which contain the same vertex multiple times are
ignored. Sequences of two vertices are accepted, but no face will be
created.
@note: Since Blender 2.44 all new faces are selected.
Example::
import Blender
from Blender import Mesh
me = Mesh.Get("Plane") # get the mesh data called "Plane"
v = me.verts # get vertices
if len(v) >= 6: # if there are enough vertices...
me.faces.extend(v[1],v[2],v[3]) # add a single edge
l=[(v[0],v[1]),[0,2,4,5]]
me.faces.extend(l) # add another face
@type vertseq: sequence(s) of MVerts
@param vertseq: either two to four ints or MVerts, or sequence (list or
tuple) of sequences each containing two to four ints or MVerts.
@type ignoreDups: boolean
@param ignoreDups: keyword parameter (default is False). If supplied and
True, do not check the input list or mesh for duplicate faces. This can
speed up scripts but can prossibly produce undesirable effects. Only
use if you know what you're doing.
@type indexList: boolean
@param indexList: keyword parameter (default is False). If supplied and
True, the method will return a list representing the new index for each
face in the input list. If faces are removed as duplicates, None is
inserted in place of the index.
@warning: Faces using the first vertex at the 3rd or 4th location in the
face's vertex list will have their order rotated so that the zero index
on in the first or second location in the face. When creating face data
with UVs or vertex colors, you may need to work around this, either by
checking for zero indices yourself or by adding a dummy first vertex to
the mesh that can be removed when your script has finished.
"""
def delete(deledges, faces):
"""
Deletes one or more faces (and optionally the edges associated with
the face(s)) from the mesh.
@type deledges: int
@param deledges: controls whether just the faces (deledges=0)
or the faces and edges (deledges=1) are deleted. These correspond to the
"Only Faces" and "Edges & Faces" options in the Edit Mode pop-up menu
@type faces: multiple ints or MFaces
@param faces: a sequence (list or tuple) containing one or more of:
- an MEdge belonging to the mesh
- a integer, specifying an index into the mesh's face list
"""
def sort():
"""
Sorts the faces using exactly the same syntax as pythons own list sorting function.
Example::
import Blender
from Blender import Mesh
me = Mesh.Get('mymesh')
me.faces.sort(key=lambda f: f.area)
me.faces.sort(key=lambda f: f.cent)
@note: Internally faces only refer to their index, so after sorting, faces you alredy have will not have their index changed to match the new sorted order.
"""
def selected():
"""
Get selected faces.
@return: a list of the indices for all faces selected in edit mode.
@rtype: list of ints
"""
from IDProp import IDGroup, IDArray
class Mesh:
"""
The Mesh Data object
====================
This object gives access to mesh data in Blender.
@note: the verts, edges and faces attributes are implemented as sequences.
The operator[] and len() are defined for these sequences. You cannot
assign to an item in the sequence, but you can assign to most of the
attributes of individual items.
@ivar edges: The mesh's edges.
@type edges: sequence of MEdges
@ivar faces: The mesh's faces.
@type faces: sequence of MFaces
@ivar verts: The mesh's vertices.
@type verts: sequence of MVerts
@ivar materials: The mesh's materials. Each mesh can reference up to
16 materials. Empty slots in the mesh's list are represented by B{None}.
B{Note}: L{Object.colbits<Object.Object.colbits>} needs to be set correctly
for each object in order for these materials to be used instead of
the object's materials.
B{Note}: Making the material list shorter does not change the face's material indices.
Take care when using the face's material indices to reference a material in this list.
B{Note}: The list that's returned is I{not} linked to the original mesh.
mesh.materials.append(material) won't do anything.
Use mesh.materials += [material] instead.
@type materials: list of L{Material}s
@ivar degr: The max angle for auto smoothing in [1,80].
@type degr: int
@ivar maxSmoothAngle: Same as L{degr}. This attribute is only for
compatibility with NMesh scripts and will probably be deprecated in
the future.
@ivar mode: The mesh's mode bitfield. See L{Modes}.
@type mode: int
@ivar sel: Sets selection status for all vertices, edges and faces in the
mesh (write only).
@type sel: boolean
@ivar hide: Sets hidden status for all vertices, edges and faces in the
mesh (write only).
@type hide: boolean
@ivar subDivLevels: The [display, rendering] subdivision levels in [1, 6].
@type subDivLevels: list of 2 ints
@ivar faceUV: The mesh contains UV-mapped textured faces.
@type faceUV: bool
@ivar vertexColors: The mesh contains vertex colors. Set True to add vertex colors.
@type vertexColors: bool
@ivar vertexUV: The mesh contains "sticky" per-vertex UV coordinates.
@type vertexUV: bool
@ivar activeFace: Index of the mesh's active face in UV Face Select and
Paint modes. Only one face can be active at a time. Note that this is
independent of the selected faces in Face Select and Edit modes.
Will throw an exception if the mesh does not have UV faces; use
L{faceUV} to test.
@type activeFace: int
@ivar activeGroup: The mesh's active vertex group. The mesh must be
linked to an object (read the comment in L{addVertGroup} for more info).
@type activeGroup: string or None
@ivar texMesh: The mesh's texMesh setting, used so coordinates from another
mesh can be used for rendering textures.
@type texMesh: Mesh or None
@ivar key: The L{Key<Key.Key>} object containing the keyframes for this mesh, if any.
@type key: Key or None
@ivar activeUVLayer: The mesh's active UV/Image layer. None if there is no UV/Image layers.
B{Note}: After setting this value, call L{update} so the result can be seen the the 3d view.
@type activeUVLayer: string
@ivar activeColorLayer: The mesh's active Vertex Color layer. None if there is no UV/Image layers.
B{Note}: After setting this value, call L{update} so the result can be seen the the 3d view.
@type activeColorLayer: string
@ivar renderUVLayer: The mesh's rendered UV/Image layer. None if there is no UV/Image layers.
@type renderUVLayer: string
@ivar renderColorLayer: The mesh's rendered Vertex Color layer. None if there is no UV/Image layers.
@type renderColorLayer: string
@ivar multires: The mesh has multires data, set True to add multires data.
Will throw an exception if the mesh has shape keys; use L{key} to test.
@type multires: bool
@ivar multiresLevelCount: The mesh has multires data. (read only)
@type multiresLevelCount: int
@ivar multiresDrawLevel: The multires level to display in the 3dview in [1 - multiresLevelCount].
@type multiresDrawLevel: int
@ivar multiresEdgeLevel: The multires level edge display in the 3dview [1 - multiresLevelCount].
@type multiresEdgeLevel: int
@ivar multiresPinLevel: The multires pin level, used for applying modifiers [1 - multiresLevelCount].
@type multiresPinLevel: int
@ivar multiresRenderLevel: The multires level to render [1 - multiresLevelCount].
@type multiresRenderLevel: int
"""
def getFromObject(object, cage=0, render=0):
"""
Replace the mesh's existing data with the raw mesh data from a Blender
Object. This method supports all the geometry based objects (mesh, text,
curve, surface, and meta). If the object has modifiers, they will be
applied before to the object before extracting the vertex data unless
the B{cage} parameter is 1.
@note: The mesh coordinates are in I{local space}, not the world space of
its object. For world space vertex coordinates, each vertex location must
be multiplied by the object's 4x4 transform matrix (see L{transform}).
@note: The objects materials will not be copied into the existing mesh,
however the face material indices will match the material list of the original data.
@type object: blender object or string
@param object: The Blender object or its name, which contains the geometry data.
@type cage: int
@param cage: determines whether the original vertices or derived vertices
@type render: int
@param render: determines whether the render setting for modifiers will be used or not.
(for objects with modifiers) are used. The default is derived vertices.
"""
def calcNormals():
"""
Recalculates the vertex normals using face data.
"""
def pointInside(vector):
"""
Returns true if vector is inside the mesh.
@note: Only returns a valid result for mesh data that has no holes.
"""
def transform(matrix, recalc_normals = False, selected_only=False):
"""
Transforms the mesh by the specified 4x4 matrix (such as returned by
L{Object.Object.getMatrix}). The matrix should be invertible.
Ideal usage for this is exporting to an external file where
global vertex locations are required for each object.
Sometimes external renderers or file formats do not use vertex normals.
In this case, you can skip transforming the vertex normals by leaving
the optional parameter recalc_normals as False or 0 (the default value).
Example::
# This script outputs deformed meshes worldspace vertex locations
# for a selected object without changing the object
import Blender
from Blender import Mesh, Object
ob = Object.GetSelected()[0] # Get the first selected object
me = Mesh.New() # Create a new mesh
me.getFromObject(ob.name) # Get the object's mesh data
verts = me.verts[:] # Save a copy of the vertices
me.transform(ob.matrix) # Convert verts to world space
for v in me.verts:
print 'worldspace vert', v.co
me.verts = verts # Restore the original verts
@type matrix: Py_Matrix
@param matrix: 4x4 Matrix which can contain location, scale and rotation.
@type recalc_normals: int
@param recalc_normals: if True or 1, also transform vertex normals.
@type selected_only: int
@param selected_only: if True or 1, only the selected verts will be transformed.
@warn: unlike L{NMesh.transform()<NMesh.NMesh.transform>}, this method
I{will immediately modify the mesh data} when it is used. If you
transform the mesh using the object's matrix to get the vertices'
world positions, the result will be a "double transform". To avoid
this you either need to set the object's matrix to the identity
matrix, perform the inverse transform after outputting the transformed
vertices, or make a copy of the vertices prior to using this method
and restore them after outputting the transformed vertices (as shown
in the example).
"""
def vertexShade(object):
"""
Colors vertices based on the current lighting setup, like when there
are no vertex colors and no textured faces and a user enters Vertex Paint
Mode in Blender (only lamps in visible layers account). An exception is
thrown if called while in EditMode.
@type object: Object
@param object: The Blender Object linked to the mesh.
"""
def update(key=None):
"""
Update display lists after changes to mesh. B{Note}: with changes taking
place for using a directed acyclic graph (DAG) for scene and object
updating, this method may be only temporary and may be removed in future
releases.
@type key: string
@param key: Use this optional argument to write the current vertex
locations to the a shape key. the name must match an existing shape key for this mesh
See L{Mesh.Mesh.key} and L{Key.Key.blocks} to get a list of the named shape keys, setting the active keys is
done from the object with L{Object.Object.pinShape}, L{Object.Object.activeShape}.
@warn: Since Blender 2.42 this function has changed; now it won't recalculate
vertex normals (seen when faces are smooth). See L{Mesh.calcNormals()}.
"""
def findEdges(edges):
"""
Quickly search for the location of an edges.
@type edges: sequence(s) of ints or MVerts
@param edges: can be tuples of MVerts or integer indexes (B{note:} will
not work with PVerts) or a sequence (list or tuple) containing two or
more sequences.
@rtype: int, None or list
@return: if an edge is found, its index is returned; otherwise None is
returned. If a sequence of edges is passed, a list is returned.
"""
def addVertGroup(group):
"""
Add a named and empty vertex (deform) group to the object this mesh is
linked to. The mesh must first be linked to an object (with object.link()
or object.getData() ) so the method knows which object to update.
This is because vertex groups in Blender are stored in I{the object} --
not in the mesh, which may be linked to more than one object.
@type group: string
@param group: the name for the new group.
"""
def removeVertGroup(group):
"""
Remove a named vertex (deform) group from the object linked to this mesh.
All vertices assigned to the group will be removed (just from the group,
not deleted from the mesh), if any. If this mesh was newly created, it
must first be linked to an object (read the comment in L{addVertGroup} for
more info).
@type group: string
@param group: the name of a vertex group.
"""
def assignVertsToGroup(group, vertList, weight, assignmode = AssignModes['REPLACE']):
"""
Adds an array (a Python list) of vertex points to a named vertex group
associated with a mesh. The vertex list is a list of vertex indices from
the mesh. You should assign vertex points to groups only when the mesh has
all its vertex points added to it and is already linked to an object.
I{B{Example:}}
The example here adds a new set of vertex indices to a sphere primitive::
import Blender
sphere = Blender.Object.Get('Sphere')
replace = Blender.Mesh.AssignModes.REPLACE
mesh = sphere.getData(mesh=True)
mesh.addVertGroup('firstGroup')
vertList = []
for x in range(300):
if x % 3 == 0:
vertList.append(x)
mesh.assignVertsToGroup('firstGroup', vertList, 0.5, replace)
@type group: string
@param group: the name of the group.
@type vertList: list of ints
@param vertList: a list of vertex indices.
@type weight: float
@param weight: the deform weight for (which means: the amount of influence
the group has over) the given vertices. It should be in the range
[0.0, 1.0]. If weight <= 0, the given vertices are removed from the
group. If weight > 1, it is clamped.
@type assignmode: module constant
@param assignmode: Three choices: REPLACE, ADD or SUBTRACT.
See L{AssignModes} for a complete description.
"""
def removeVertsFromGroup(group, vertList = None):
"""
Remove a list of vertices from the given group. If this mesh was newly
created, it must first be linked to an object (check L{addVertGroup}).
@type group: string
@param group: the name of a vertex group
@type vertList: list of ints
@param vertList: a list of vertex indices to be removed from I{group}.
If None, all vertices are removed -- the group is emptied.
"""
def getVertsFromGroup(group, weightsFlag = 0, vertList = None):
"""
Return a list of vertex indices associated with the passed group. This
method can be used to test whether a vertex index is part of a group and
if so, what its weight is.
I{B{Example:}}
Append this to the example from L{assignVertsToGroup}::
# ...
print "Vertex indices from group %s :" % groupName
print mesh.getVertsFromGroup('firstGroup')
print "Again, with weights:"
print mesh.getVertsFromGroup('firstGroup',1)
print "Again, with weights and restricted to the given indices:"
print mesh.getVertsFromGroup('firstGroup',1,[1,2,3,4,5,6])
@type group: string
@param group: the group name.
@type weightsFlag: bool
@param weightsFlag: if 1, each item in the list returned contains a
tuple pair (index, weight), the weight is a float between 0.0 and 1.0.
@type vertList: list of ints
@param vertList: if given, only those vertex points that are both in the
list and group passed in are returned.
"""
def renameVertGroup(groupName, newName):
"""
Renames a vertex group.
@type groupName: string
@param groupName: the vertex group name to be renamed.
@type newName: string
@param newName: the name to replace the old name.
"""
def getVertGroupNames():
"""
Return a list of all vertex group names.
@rtype: list of strings
@return: returns a list of strings representing all vertex group
associated with the mesh's object
"""
def getUVLayerNames():
"""
Return a list of all UV layer names
@rtype: list of strings
@return: returns a list of strings representing all UV layers
associated with the mesh's object
"""
def getColorLayerNames():
"""
Return a list of all color layer names
@rtype: list of strings
@return: returns a list of strings representing all color layers
associated with the mesh's object
"""
def getVertexInfluences(index):
"""
Get the bone influences for a specific vertex.
@type index: int
@param index: The index of a vertex.
@rtype: list of lists
@return: List of pairs [name, weight], where name is the bone name (string)
and weight is a float value.
"""
def removeAllKeys():
"""
Remove all mesh keys stored in this mesh.
@rtype: bool
@return: True if successful or False if the Mesh has no keys.
"""
def insertKey(frame = None, type = 'relative'):
"""
Insert a mesh key at the given frame.
@type frame: int
@type type: string
@param frame: The Scene frame where the mesh key should be inserted. If
None or the arg is not given, the current frame is used.
@param type: The mesh key type: 'relative' or 'absolute'. This is only
relevant on meshes with no keys.
@warn: This and L{removeAllKeys} were included in this release only to
make accessing vertex keys possible, but may not be a proper solution
and may be substituted by something better later. For example, it
seems that 'frame' should be kept in the range [1, 100]
(the curves can be manually tweaked in the Ipo Curve Editor window in
Blender itself later).
@warn: Will throw an error if the mesh has multires. use L{multires} to check.
"""
def addUVLayer(name):
"""
Adds a new UV/Image layer to this mesh, it will always be the last layer but not made active.
@type name: string
@param name: The name of the new UV layer, 31 characters max.
"""
def addColorLayer(name):
"""
Adds a new Vertex Color layer to this mesh, it will always be the last layer but not made active.
@type name: string
@param name: The name of the new Color layer, 31 characters max.
"""
def removeUVLayer(name):
"""
Removes the active UV/Image layer.
@type name: string
@param name: The name of the UV layer to remove.
"""
def removeColorLayer(name):
"""
Removes the active Vertex Color layer.
@type name: string
@param name: The name of the Color layer to remove.
"""
def renameUVLayer(name, newname):
"""
Renames the UV layer called name to newname.
@type name: string
@param name: The UV layer to rename.
@type newname: string
@param newname: The new name of the UV layer, will be made unique.
"""
def renameColorLayer(name, newname):
"""
Renames the color layer called name to newname.
@type name: string
@param name: The Color layer to rename.
@type newname: string
@param newname: The new name of the Color layer, will be made unique.
"""
def smooth():
"""
Flattens angle of selected faces. Experimental mesh tool.
An exception is thrown if called while in EditMode.
"""
def flipNormals():
"""
Toggles the direction of selected face's normals. Experimental mesh tool.
An exception is thrown if called while in EditMode.
"""
def toSphere():
"""
Moves selected vertices outward in a spherical shape. Experimental mesh
tool.
An exception is thrown if called while in EditMode.
"""
def fill():
"""
Scan fill a closed selected edge loop. Experimental mesh tool.
An exception is thrown if called while in EditMode.
"""
def triangleToQuad():
"""
Convert selected triangles to quads. Experimental mesh tool.
An exception is thrown if called while in EditMode.
"""
def quadToTriangle(mode=0):
"""
Convert selected quads to triangles. Experimental mesh tool.
An exception is thrown if called while in EditMode.
@type mode: int
@param mode: specifies whether a to add the new edge between the
closest (=0) or farthest(=1) vertices.
"""
def subdivide(beauty=0):
"""
Subdivide selected edges in a mesh. Experimental mesh tool.
An exception is thrown if called while in EditMode.
@type beauty: int
@param beauty: specifies whether a "beauty" subdivide should be
enabled (disabled is default). Value must be in the range [0,1].
"""
def remDoubles(limit):
"""
Removes duplicates from selected vertices. Experimental mesh tool.
An exception is thrown if called while in EditMode.
@type limit: float
@param limit: specifies the maximum distance considered for vertices
to be "doubles". Value is clamped to the range [0.0,1.0].
@rtype: int
@return: the number of vertices deleted
"""
def recalcNormals(direction=0):
"""
Recalculates inside or outside normals for selected faces. Experimental
mesh tool.
An exception is thrown if called while in EditMode.
@type direction: int
@param direction: specifies outward (0) or inward (1) normals. Outward
is the default. Value must be in the range [0,1].
"""
def __copy__ ():
"""
Make a copy of this mesh
@rtype: Mesh
@return: a copy of this mesh
"""
import id_generics
Mesh.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,157 @@
# Blender.Mesh.Primitives module
"""
The Blender.Mesh.Primitives submodule.
B{New}:
Mesh Primitive Data
===================
This submodule provides access Blender's mesh primitives. Each module
function returns a BPy_Mesh object which wraps the mesh data. This data can
then be manipulated using the L{Mesh} API.
Example::
from Blender import *
me = Mesh.Primitives.Cube(2.0) # create a new cube of size 2
sc = Scene.GetCurrent() # get current scene
sc.objects.new(me,'Mesh') # add a new mesh-type object to the scene
Window.RedrawAll() # update windows
"""
def Plane(size=2.0):
"""
Construct a filled planar mesh with 4 vertices. The default size
creates a 2 by 2 Blender unit plane, identical to the Blender UI.
@type size: float
@param size: optional size of the plane.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Cube(size=2.0):
"""
Construct a cube mesh. The default size creates a cube with each face
2 by 2 Blender units, identical to the Blender UI.
@type size: float
@param size: optional size of the cube.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Circle(verts=32,diameter=2.0):
"""
Construct a circle mesh. The defaults create a circle with a
diameter of 2 Blender units, identical to the Blender UI.
@type verts: int
@param verts: optional number of vertices for the circle.
Value must be in the range [3,100].
@type diameter: float
@param diameter: optional diameter of the circle.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Cylinder(verts=32, diameter=2.0, length=2.0):
"""
Construct a cylindrical mesh (ends filled). The defaults create a
cylinder with a diameter of 2 Blender units and length 2 units,
identical to the Blender UI.
@type verts: int
@param verts: optional number of vertices in the cylinder's perimeter.
Value must be in the range [3,100].
@type diameter: float
@param diameter: optional diameter of the cylinder.
@type length: float
@param length: optional length of the cylinder.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Tube(verts=32, diameter=2.0, length=2.0):
"""
Construct a cylindrical mesh (ends not filled). The defaults create a
cylinder with a diameter of 2 Blender units and length 2 units, identical
to the Blender UI.
@type verts: int
@param verts: optional number of vertices in the tube's perimeter.
Value must be in the range [3,100].
@type diameter: float
@param diameter: optional diameter of the tube.
@type length: float
@param length: optional length of the tube.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Cone(verts=32, diameter=2.0, length=2.0):
"""
Construct a conic mesh (ends filled). The defaulte create a cone with a
base diameter of 2 Blender units and length 2 units, identical to
the Blender UI.
@type verts: int
@param verts: optional number of vertices in the cone's perimeter.
Value must be in the range [3,100].
@type diameter: float
@param diameter: optional diameter of the cone.
@type length: float
@param length: optional length of the cone.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Grid(xres=32, yres=32, size=2.0):
"""
Construct a grid mesh. The defaults create a 32 by 32 mesh of size 2
Blender units, identical to the Blender UI.
@type xres: int
@param xres: optional grid size in the x direction.
Value must be in the range [2,100].
@type yres: int
@param yres: optional grid size in the y direction.
Value must be in the range [2,100].
@type size: float
@param size: optional size of the grid.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def UVsphere(segments=32, rings=32, diameter=2.0):
"""
Construct a UV sphere mesh. The defaults create a 32 by 32 sphere with
a diameter of 2 Blender units, identical to the Blender UI.
@type segments: int
@param segments: optional number of longitudinal divisions.
Value must be in the range [3,100].
@type rings: int
@param rings: optional number of latitudinal divisions.
Value must be in the range [3,100].
@type diameter: float
@param diameter: optional diameter of the sphere.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Icosphere(subdivisions=2, diameter=2.0):
"""
Construct a Icosphere mesh. The defaults create sphere with 2 subdivisions
and diameter of 2 Blender units, identical to the Blender UI.
@type subdivisions: int
@param subdivisions: optional number of subdivisions.
Value must be in the range [2,5].
@type diameter: float
@param diameter: optional diameter of the sphere.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""
def Monkey():
"""
Construct a Suzanne mesh.
@rtype: L{BPy_Mesh<Mesh>}
@return: returns a mesh object.
"""

View File

@@ -0,0 +1,246 @@
# Blender.Metaball module and the Metaball PyType metaball
"""
The Blender.Metaball submodule
This module provides access to B{Metaball} data in Blender and the elements they contain.
Example::
import Blender
mb = Blender.Metaball.New()
for i in xrange(20):
element= mb.elements.add()
element.co = Blender.Mathutils.Vector(i, 0, 0)
sce = Blender.Scene.GetCurrent()
sce.objects.new(mb)
Example::
# Converts the active armature into metaballs
from Blender import *
def main():
scn= Scene.GetCurrent()
ob_arm= scn.objects.active
if not ob_arm or ob_arm.type!='Armature':
Draw.PupMenu('No Armature Selected')
return
arm= ob_arm.data
res= Draw.PupFloatInput('res:', 0.2, 0.05, 2.0)
if not res:
return
# Make a metaball
mb= Metaball.New()
mb.wiresize= res
# Link to the Scene
ob_mb = scn.objects.new(ob_mb)
ob_arm.sel= 0
ob_mb.setMatrix(ob_arm.matrixWorld)
meta_type= 0 # all elemts are ball type
meta_stiffness= 2.0 # Volume
for bone in arm.bones.values():
print bone
# Find out how many metaballs to add based on bone length, 4 min
length= bone.length
if length < res:
mballs= 4
else:
mballs= int(length/res)
if mballs < 4:
mballs = 4
print 'metaball count', mballs
# get the bone properties
head_rad= bone.headRadius
tail_rad= bone.tailRadius
head_loc= bone.head['ARMATURESPACE']
tail_loc= bone.tail['ARMATURESPACE']
for i in range(mballs):
f= float(i)
w1= f/mballs # weighting of this position on the bone for rad and loc
w2= 1-w1
loc= head_loc*w1 + tail_loc*w2
rad= (head_rad*w1 + tail_rad*w2) * 1.3
# Add the metaball
ml= mb.elements.add()
ml.co= loc
ml.radius= rad
ml.stiffness= meta_stiffness
Window.RedrawAll()
main()
@type Types: readonly dictionary
@var Types: MeteElement types.
- BALL
- TUBE
- PLANE
- ELIPSOID
- CUBE
@type Update: readonly dictionary
@var Update: MeteElement types.
- ALWAYS
- HALFRES
- FAST
- NEVER
"""
def New (name):
"""
Creates a new Metaball.
@type name: string
@param name: The name of the metaball. If this parameter is not given (or not valid) blender will assign a name to the metaball.
@rtype: Blender Metaball
@return: The created Metaball.
"""
def Get (name):
"""
Get the Metaball from Blender.
@type name: string
@param name: The name of the requested Metaball.
@rtype: Blender Metaball or a list of Blender Metaballs
@return: It depends on the 'name' parameter:
- (name): The Metaball with the given name;
- (): A list with all Metaballs in the current scene.
"""
class Metaball:
"""
The Metaball object
===================
This metaball gives access to generic data from all metaballs in Blender.
@ivar elements: Element iterator of MetaElemSeq type.
@type elements: MetaElemSeq
@ivar wiresize: display resolution.
Value clamped between 0.05 and 1.0.
A lower value results in more polygons.
@type wiresize: float
@ivar rendersize: render resolution.
Value clamped between 0.05 and 1.0.
A lower value results in more polygons.
@type rendersize: float
@ivar thresh: Threshold setting for this metaball.
Value clamped between 0.0 and 5.0.
@type thresh: float
@ivar materials: List of up to 16 Materials or None types
Only the first material of the mother-ball used at the moment.
@type materials: list
@ivar update: The update method to use for this metaball.
@type update: int
"""
def __copy__():
"""
Return a copy of this metaball object data.
@rtype: Metaball
@return: Metaball
"""
import id_generics
Metaball.__doc__ += id_generics.attributes
class MetaElemSeq:
"""
The MetaElemSeq object
======================
This object provides sequence and iterator access to the metaballs elements.
The elements accessed within this iterator "wraps" the actual metaball elements; changing any
of the elements's attributes will immediately change the data in the metaball.
This iterator is most like pythons 'set' type.
"""
def add():
"""
Append a new element to the metaball.
no arguments are taken, instead a new metaelement is
added to the metaball data and returned.
This new element can then be modified.
@return: a new meta element.
@rtype: Metaelement
"""
def remove(element):
"""
remove an element from the metaball data.
if the element is not a part of the metaball data, an error will be raised.
@return: None
@rtype: None
"""
def __iter__():
"""
Iterate over elements in this metaball.
@return: One of the metaelem in this metaball.
@rtype: Metaelem
"""
def __len__():
"""
Iterate over elements in this metaball.
@return: The number of elements in this metaball
@rtype: int
"""
class Metaelem:
"""
The Metaelem object
===================
This gives direct access to meta element data within a metaball.
@ivar type: The type of the metaball.
Values must be from L{Types}
Example::
from Blender import Metaball
mb= Metaball.Get('mb')
for el in mb.elements:
el.type= Metaball.Types.CUBE
@type type: int
@ivar co: The location of this element.
@type co: Vector
@ivar dims: Element dimensions.
Values clamped between 0 and 20 on all axies.
@type dims: Vector
@ivar quat: Element rotation.
@type quat: Quaternion
@ivar stiffness: Element stiffness.
Value clamped between 0 and 10.
@type stiffness: float
@ivar radius: Element radius.
Value clamped between 0 and 5000.
@type radius: float
@ivar negative: Element negative volume status.
@type negative: bool
@ivar hide: Element hidden status.
@type hide: bool
"""

View File

@@ -0,0 +1,58 @@
METABALL Module documentation
INTRODUCTION
The metaball module effect allows you to access all the data of an metaball.
A metaball consists of several (maybe only one) metaelems, which are spheres, interacting with each other, thus creating soft organic volumes.
functions of the module :
New(name) : creates ans returns a metaball object.
Get(opt : name) : if the parameter name is given, returns the metaball object whose name has been passed, or Py_None, if no such metaball exists in the current scene. If no parameter is given, returns a list of all the metaballs in the current scene.
get : alias for Get
Metaball object member functions :
getName()Return Metaball name
setName(string newname) - Sets Metaball name
getWiresize() - Return Metaball wire size
setWiresize(float val) - Sets Metaball wire size
getRendersize() - Return Metaball render size
setRendersize(float newval- Sets Metaball render size
getThresh()- Return Metaball threshold
setThresh(float newval)- Sets Metaball threshold
getBbox,- Return Metaball bounding box(a list of eight lists of three elements)
getNMetaElems() Returns the number of Metaelems (basic spheres)
getMetatype(int num_metaelem): returns the type of the metaelem number num_metaelem.
0 : ball
1 : tubex
2 : tubey
3 : tubez
setMetatype(int num_metaelem,int newtype) : sets the type of the metaelem number num_metaelem.
getMetadata(field_name,int num_metaelem) gets Metaball MetaData. Explained later.
setMetadata(field_name,int num_metaelem,newval) sets Metaball MetaData. Explained later.
getMetalay(int num_metaelem)
getMetax(int num_metaelem) : gets the x coordinate of the metaelement
setMetax(int num_metaelem,float newval) : sets the x coordinate of the metaelement
getMetay(int num_metaelem) : gets the y coordinate of the metaelement
setMetay(int num_metaelem,float newval) : sets the y coordinate of the metaelement
getMetaz(int num_metaelem) : gets the z coordinate of the metaelement
setMetaz(int num_metaelem,float newval) : sets the z coordinate of the metaelement
getMetas(int num_metaelem) : gets the s coordinate of the metaelement
setMetas(int num_metaelem,float newval) : sets the s coordinate of the metaelement
getMetalen(int num_metaelem) : gets the length of the metaelement. Important for tubes.
setMetalen(int num_metaelem,float newval) : sets the length of the metaelement. Important for tubes.
getloc, - Gets Metaball loc values
setloc, (f f f) - Sets Metaball loc values
getrot, () - Gets Metaball rot values
setrot,, (f f f) - Sets Metaball rot values
getsize,() - Gets Metaball size values
setsize,(f f f) - Sets Metaball size values
The Object.attribute syntax
The attribute can take these values : seed,nabla,sta,end,lifetime,normfac,obfac,randfac,texfac,randlife,vectsize,totpart,force,mult,life,child,mat,defvec.

View File

@@ -0,0 +1,225 @@
# Blender.Modifier module and the Modifier PyType object
"""
The Blender.Modifier submodule
B{New}:
- Supports the new Cast and Smooth modifiers.
This module provides access to the Modifier Data in Blender.
Example::
from Blender import *
ob = Object.Get('Cube') # retrieve an object
mods = ob.modifiers # get the object's modifiers
for mod in mods:
print mod,mod.name # print each modifier and its name
mod = mods.append(Modifier.Types.SUBSURF) # add a new subsurf modifier
mod[Modifier.Settings.LEVELS] = 3 # set subsurf subdivision levels to 3
Example::
# Apply a lattice to an object and get the deformed object
# Uses an object called 'Cube' and a lattice called 'Lattice'
from Blender import *
ob_mesh= Object.Get('Cube')
ob_lattice= Object.Get('Lattice')
myMeshMod = ob_mesh.modifiers
mod = myMeshMod.append(Modifier.Types.LATTICE)
mod[Modifier.Settings.OBJECT] = ob_lattice
ob_mesh.makeDisplayList() # Needed to apply the modifier
Window.RedrawAll() # View the change
deformed_mesh= Mesh.New()
deformed_mesh.getFromObject(ob_mesh.name)
# Print the deformed locations
for v in deformed_mesh.verts:
print v.co
@type Types: readonly dictionary
@var Types: Constant Modifier dict used for L{ModSeq.append} to a
modifier sequence and comparing with L{Modifier.type}:
- ARMATURE - type value for Armature modifiers
- BOOLEAN - type value for Boolean modifiers
- BUILD - type value for Build modifiers
- CURVE - type value for Curve modifiers
- MIRROR - type value for Mirror modifiers
- DECIMATE - type value for Decimate modifiers
- LATTICE - type value for Lattice modifiers
- SUBSURF - type value for Subsurf modifiers
- WAVE - type value for Wave modifiers
- EDGESPLIT - type value for Edge Split modifiers
- DISPLACE - type value for Displace modifiers
- SMOOTH - type value for Smooth modifiers
- CAST - type value for Cast modifiers
@type Settings: readonly dictionary
@var Settings: Constant Modifier dict used for changing modifier settings.
- RENDER - Used for all modifiers (bool) If true, the modifier is enabled for rendering.
- REALTIME - Used for all modifiers (bool) If true, the modifier is enabled for interactive display.
- EDITMODE - Used for all modifiers (bool) If both REALTIME and EDITMODE are true, the modifier is enabled for interactive display while the object is in edit mode.
- ONCAGE - Used for all modifiers (bool) If true, the modifier is enabled for the editing cage during edit mode.
- OBJECT - Used for Armature, Lattice, Curve, Boolean and Array (Object)
- VERTGROUP - Used for Armature, Lattice, Curve, Smooth and Cast (String)
- LIMIT - Array and Mirror (float [0.0 - 1.0])
- FLAG - Mirror and Wave (int)
- COUNT - Decimator Polycount (readonly) and Array (int)
- LENGTH - Build [1.0-300000.0] and Array [0.0 - 10000.0] (float)
- FACTOR - Smooth [-10.0, 10.0] and Cast [-10.0, 10.0] (float)
- ENABLE_X = Smooth and Cast (bool, default: True)
- ENABLE_Y = Smooth and Cast (bool, default: True)
- ENABLE_Z = Smooth and Cast (bool, default: True)
- TYPES - Subsurf and Cast. For Subsurf it determines the subdivision algorithm - (int): 0 = Catmull-Clark; 1 = simple subdivision. For Cast it determines the shape to deform to = (int): 0 = Sphere; 1 = Cylinder; 2 = Cuboid
- LEVELS - Used for Subsurf only (int [0 - 6]). The number of subdivision levels used for interactive display.
- RENDLEVELS - Used for Subsurf only (int [0 - 6]). The number of subdivision levels used for rendering.
- OPTIMAL - Used for Subsurf only (bool). Enables Optimal Draw.
- UV - Used for Subsurf only (bool). Enables Subsurf UV.
- OBJECT_OFFSET - Used for Array only (Object)
- OBJECT_CURVE - Used for Array only (Curve Object)
- OFFSET_VEC - Used for Array only (3d Vector)
- SCALE_VEC - Used for Array only (3d Vector)
- MERGE_DIST - Used for Array only (float)
- ENVELOPES - Used for Armature only (bool)
- START - Used for Build only (int)
- SEED - Used for Build only (int)
- RANDOMIZE - Used for Build only (bool)
- AXIS_X - Used for Mirror only (bool)
- AXIS_Y - Used for Mirror only (bool)
- AXIS_Z - Used for Mirror only (bool)
- RATIO - Used for Decimate only (float [0.0 - 1.0])
- STARTX - Used for Wave only (float [-100.0 - 100.0])
- STARTY - Used for Wave only (float [-100.0 - 100.0])
- HEIGHT - Used for Wave only (float [-2.0 - 2.0])
- WIDTH - Used for Wave only (float [0.0 - 5.0])
- NARROW - Used for Wave only (float [0.0 - 10.0])
- SPEED - Used for Wave only (float [-2.0 - 2.0])
- DAMP - Used for Wave only (float [-MAXFRAME - MAXFRAME])
- LIFETIME - Used for Wave only (float [-MAXFRAME - MAXFRAME])
- TIMEOFFS - Used for Wave only (float [-MAXFRAME - MAXFRAME])
- OPERATION - Used for boolean only (int 0,1,2 : Intersect, Union, Difference)
- EDGESPLIT_ANGLE - Used for edge split only (float 0.0 - 180)
- EDGESPLIT_FROM_ANGLE - Used for edge split only, should the modifier use the edge angle (bool)
- EDGESPLIT_FROM_SHARP - Used for edge split only, should the modifier use the edge sharp flag (bool)
- UVLAYER - Used for Displace only
- MID_LEVEL - Used for Displace only (float [0.0, 1.0], default: 0.5)
- STRENGTH - Used for Displace only (float [-1000.0, 1000.0, default: 1.0)
- TEXTURE - Used for Displace only (string)
- MAPPING - Used for Displace only
- DIRECTION - Used for Displace only
- REPEAT - Used for Smooth only (int [0, 30], default: 1)
- RADIUS - Used for Cast only (float [0.0, 100.0], default: 0.0)
- SIZE - Used for Cast only (float [0.0, 100.0], default: 0.0)
- SIZE_FROM_RADIUS - Used for Cast only (bool, default: True)
- USE_OB_TRANSFORM - Used for Cast only (bool, default: False)
"""
class ModSeq:
"""
The ModSeq object
=================
This object provides access to list of L{modifiers<Modifier.Modifier>} for a particular object.
Only accessed from L{Object.Object.modifiers}.
"""
def __getitem__(index):
"""
This operator returns one of the object's modifiers.
@type index: int
@return: an Modifier object
@rtype: Modifier
@raise KeyError: index was out of range
"""
def __len__():
"""
Returns the number of modifiers in the object's modifier stack.
@return: number of Modifiers
@rtype: int
"""
def append(type):
"""
Appends a new modifier to the end of the object's modifier stack.
@type type: a constant specifying the type of modifier to create. as from L{Types}
@rtype: Modifier
@return: the new Modifier
"""
def remove(modifier):
"""
Remove a modifier from this objects modifier sequence.
@type modifier: a modifier from this sequence to remove.
@note: Accessing attributes of the modifier after removing will raise an error.
"""
def moveUp(modifier):
"""
Moves the modifier up in the object's modifier stack.
@type modifier: a modifier from this sequence to remove.
@rtype: None
@raise RuntimeError: request to move above another modifier requiring
original data
@note: Accessing attributes of the modifier after removing will raise an error.
"""
def moveDown(modifier):
"""
Moves the modifier down in the object's modifier stack.
@type modifier: a modifier from this sequence to remove.
@rtype: None
@raise RuntimeError: request to move modifier beyond a non-deforming
modifier
@note: Accessing attributes of the modifier after removing will raise an error.
"""
class Modifier:
"""
The Modifier object
===================
This object provides access to a modifier for a particular object accessed
from L{ModSeq}.
@ivar name: The name of this modifier. 31 chars max.
@type name: string
@ivar type: The type of this modifier. Read-only. The returned value
matches the types in L{Types}.
@type type: int
"""
def __getitem__(key):
"""
This operator returns one of the modifier's data attributes.
@type key: value from modifier's L{Modifier.Settings} constant
@return: the requested data
@rtype: varies
@raise KeyError: the key does not exist for the modifier
"""
def __setitem__(key):
"""
This operator modifiers one of the modifier's data attributes.
@type key: value from modifier's L{Modifier.Settings} constant
@raise KeyError: the key does not exist for the modifier
"""

View File

@@ -0,0 +1,245 @@
# Blender.Armature.NLA module and the Action PyType object
"""
The Blender.Armature.NLA submodule.
NLA
===
This module provides access to B{Action} objects in Blender. Actions are a
series of keyframes/Ipo curves that define the movement of a bone.
Actions are linked to objects of type armature.
@type Flags: readonly dictionary
@var Flags: Constant dict used by the L{ActionStrip.flag} attribute.
It is a bitmask and settings are ORed together.
- SELECT: action strip is selected in NLA window
- STRIDE_PATH: play action based on path position and stride.
- HOLD: continue displaying the last frame past the end of the strip
- ACTIVE: action strip is active in NLA window
- LOCK_ACTION: action start/end are automatically mapped to strip duration
@type StrideAxes: readonly dictionary
@var StrideAxes: Constant dict used by the L{ActionStrip.strideAxis} attribute.
Values are STRIDEAXIS_X, STRIDEAXIS_Y, and STRIDEAXIS_Z.
@type Modes: readonly dictionary
@var Modes: Constant dict used by the L{ActionStrip.mode} attribute.
Currently the only value is MODE_ADD.
"""
def NewAction (name = 'DefaultAction'):
"""
Create a new Action object.
@type name: string
@param name: The Action name.
@rtype: PyAction
"""
def CopyAction (action):
"""
Copy an action and it's keyframes
@type action: PyAction
@param action: The action to be copied.
@rtype: PyAction
@return: A copied action
"""
def GetActions ():
"""
Get all actions and return them as a Key : Value Dictionary.
@rtype: Dictionary of PyActions
@return: All the actions in blender
"""
class Action:
"""
The Action object
=================
This object gives access to Action-specific data in Blender.
"""
def getName():
"""
Get the name of this Action.
@rtype: string
"""
def setName(name):
"""
Set the name of this Action.
@type name: string
@param name: The new name
"""
def setActive(object):
"""
Set this action as the current action for an object.
@type object: PyObject
@param object: The object whose action is to be set
"""
def getChannelIpo(channel):
"""
Get the Ipo for the named channel in this action
@type channel: string
@param channel: The name of a channel in this action
@rtype: PyIpo or None
@return: the Ipo for the channel
"""
def getFrameNumbers():
"""
Gets the frame numbers at which a key was inserted into this action
@rtype: PyList
@return: a list of ints
"""
def removeChannel(channel):
"""
Remove a named channel from this action
@type channel: string
@param channel: The name of a channel in this action to be removed
"""
def getAllChannelIpos():
"""
Get the all the Ipos for this action
@rtype: Dictionary [channel : PyIpo or None]
@return: the Ipos for all the channels in the action
"""
def getChannelNames():
"""
Returns a list of channel names
@rtype: list
@return: the channel names that match bone and constraint names.
"""
def renameChannel(nameFrom, nameTo):
"""
rename an existing channel to a new name.
if the nameFrom channel dosnt exist or the nameTo exists, an error will be raised.
@return: None
"""
import id_generics
Action.__doc__ += id_generics.attributes
class ActionStrips:
"""
The ActionStrips object
=======================
This object gives access to sequence of L{ActionStrip} objects for
a particular Object.
"""
def __getitem__(index):
"""
This operator returns one of the action strips in the stack.
@type index: int
@return: an action strip object
@rtype: ActionStrip
@raise KeyError: index was out of range
"""
def __len__():
"""
Returns the number of action strips for the object.
@return: number of action strips
@rtype: int
"""
def append(action):
"""
Appends a new action to the end of the action strip sequence.
@type action: L{Action<NLA.Action>}
@param action: the action to use in the action strip
@rtype: ActionStrip
@return: the new action strip
"""
def remove(actionstrip):
"""
Remove an action strip from this object's actionstrip sequence.
@type actionstrip: an action strip from this sequence to remove.
@note: Accessing attributes of the action strip after it is removed will
throw an exception.
"""
def moveDown(actionstrip):
"""
Move the action strip down in the object's actionstrip sequence.
@type actionstrip: an action strip from this sequence.
"""
def moveUp(actionstrip):
"""
Move the action strip up in the object's actionstrip sequence.
@type actionstrip: an action strip from this sequence.
"""
class ActionStrip:
"""
The ActionStrip object
======================
This object gives access to a particular action strip.
@ivar action: Action associated with the strip.
@type action: BPy Action object
@ivar stripStart: Starting frame of the strip.
@type stripStart: float
@ivar stripEnd: Ending frame of the strip.
@type stripEnd: float
@ivar actionStart: Starting frame of the action.
@type actionStart: float
@ivar actionEnd: Ending frame of the action.
@type actionEnd: float
@ivar repeat: The number of times to repeat the action range.
@type repeat: float
@ivar mode: Controls the ActionStrip mode. See L{Modes} for
valid values.
@type mode: int
@ivar flag: Controls various ActionStrip attributes. Values can be ORed.
See L{Flags} for valid values.
@type flag: int
@ivar strideAxis: Dominant axis for stride bone. See L{StrideAxes} for
valid values.
@type strideAxis: int
@ivar strideLength: Distance covered by one complete cycle of the action
specified in the Action Range.
@type strideLength: float
@ivar strideBone: Name of Bone used for stride
@type strideBone: string
@ivar groupTarget: Armature object within DupliGroup for local animation
@type groupTarget: object
@ivar blendIn: Number of frames of motion blending.
@type blendIn: float
@ivar blendOut: Number of frames of ease-out.
@type blendOut: float
"""
def resetActionLimits():
"""
Activates the functionality found in NLA Strip menu under "Reset Action
Start/End". This method restores the values of ActionStart and
ActionEnd to their defaults, usually the first and last frames within
an action that contain keys.
@rtype: None
"""
def resetStripSize():
"""
Activates the functionality found in NLA Strip menu under "Reset Strip
Size". This method resets the action strip size to its creation values.
@rtype: None
"""
def snapToFrame():
"""
Activates the functionality found in NLA Strip menu under "Snap to Frame".
This function snaps the ends of the action strip to the nearest whole
numbered frame.
@rtype: None
"""

View File

@@ -0,0 +1,823 @@
# Blender.NMesh module and the NMesh PyType object
"""
The Blender.NMesh submodule.
B{Deprecated}:
This module is now maintained but not actively developed.
Access to data such as properties, library, UVLayers and ColorLayers is not available
further more, a mesh modified with NMesh will destroy inactive UV and Color layers
so writing tools that use NMesh is discouraged.
Use L{Mesh} instead.
Mesh Data
=========
This module provides access to B{Mesh Data} objects in Blender.
Example::
import Blender
from Blender import NMesh, Material, Window
editmode = Window.EditMode() # are we in edit mode? If so ...
if editmode: Window.EditMode(0) # leave edit mode before getting the mesh
me = NMesh.GetRaw("Plane") # get the mesh data called "Plane"
if not me.materials: # if there are no materials ...
newmat = Material.New() # create one ...
me.materials.append(newmat) # and append it to the mesh's list of mats
print me.materials # print the list of materials
mat = me.materials[0] # grab the first material in the list
mat.R = 1.0 # redefine its red component
for v in me.verts: # loop the list of vertices
v.co[0] *= 2.5 # multiply the coordinates
v.co[1] *= 5.0
v.co[2] *= 2.5
me.update() # update the real mesh in Blender
if editmode: Window.EditMode(1) # optional, just being nice
@type Modes: readonly dictionary
@type FaceFlags: readonly dictionary
@type FaceModes: readonly dictionary
@type FaceTranspModes: readonly dictionary
@var Modes: The available mesh modes.
- NOVNORMALSFLIP - no flipping of vertex normals during render.
- TWOSIDED - double sided mesh.
- AUTOSMOOTH - turn auto smoothing of faces "on".
@var FaceFlags: The available *texture face* (uv face select mode) selection
flags. Note: these refer to TexFace faces, available if nmesh.hasFaceUV()
returns true.
- SELECT - selected (deprecated after 2.43 release, use face.sel).
- HIDE - hidden (deprecated after 2.43 release, use face.sel).
- ACTIVE - the active face.
@var FaceModes: The available *texture face* modes. Note: these are only
meaningful if nmesh.hasFaceUV() returns true, since in Blender this info is
stored at the TexFace (TexFace button in Edit Mesh buttons) structure.
- ALL - set all modes at once.
- BILLBOARD - always orient after camera.
- HALO - halo face, always point to camera.
- DYNAMIC - respond to collisions.
- INVISIBLE - invisible face.
- LIGHT - dynamic lighting.
- OBCOL - use object color instead of vertex colors.
- SHADOW - shadow type.
- SHAREDVERT - apparently unused in Blender.
- SHAREDCOL - shared vertex colors (per vertex).
- TEX - has texture image.
- TILES - uses tiled image.
- TWOSIDE - two-sided face.
@var FaceTranspModes: The available face transparency modes. Note: these are
enumerated values (enums), they can't be combined (ANDed, ORed, etc) like a bit vector.
- SOLID - draw solid.
- ADD - add to background (halo).
- ALPHA - draw with transparency.
- SUB - subtract from background.
@var EdgeFlags: The available edge flags.
- SELECT - selected.
- EDGEDRAW - edge is drawn out of edition mode.
- SEAM - edge is a seam for UV unwrapping
- FGON - edge is part of a F-Gon.
"""
def Col(col = [255, 255, 255, 255]):
"""
Get a new mesh rgba color.
@type col: list
@param col: A list [red, green, blue, alpha] of integer values in [0, 255].
@rtype: NMCol
@return: A new NMCol (mesh rgba color) object.
"""
def Vert(x = 0, y = 0, z = 0):
"""
Get a new vertex object.
@type x: float
@type y: float
@type z: float
@param x: The x coordinate of the vertex.
@param y: The y coordinate of the vertex.
@param z: The z coordinate of the vertex.
@rtype: NMVert
@return: A new NMVert object.
"""
def Face(vertexList = None):
"""
Get a new face object.
@type vertexList: list
@param vertexList: A list of B{up to 4} NMVerts (mesh vertex
objects).
@rtype: NMFace
@return: A new NMFace object.
"""
def New(name = 'Mesh'):
"""
Create a new mesh object.
@type name: string
@param name: An optional name for the created mesh.
rtype: NMesh
@return: A new (B{empty}) NMesh object.
"""
def GetRaw(name = None):
"""
Get the mesh data object called I{name} from Blender.
@type name: string
@param name: The name of the mesh data object.
@rtype: NMesh
@return: It depends on the 'name' parameter:
- (name) - The NMesh wrapper of the mesh called I{name},
None if not found.
- () - A new (empty) NMesh object.
"""
def GetNames():
"""
Get a list with the names of all available meshes in Blender.
@rtype: list of strings
@return: a list of mesh names.
@note: to get actual mesh data, pass a mesh name to L{GetRaw}.
"""
def GetRawFromObject(name):
"""
Get the raw mesh data object from the Object in Blender called I{name}.\n
Note: The mesh coordinates are in local space, not the world space of its Object.\n
For world space vertex coordinates, each vertex location must be multiplied by the object's 4x4 matrix.
This function support all the geometry based objects: Mesh, Text, Surface, Curve, Meta.
@type name: string
@param name: The name of an Object.
@rtype: NMesh
@return: The NMesh wrapper of the mesh data from the Object called I{name}.
@note: For "subsurfed" meshes, it's the B{display} level of subdivision that
matters, the rendering one is only processed at the rendering pre-stage
and is not available for scripts. This is not a problem at all, since
you can get and set the subdivision levels via scripting, too (see
L{NMesh.NMesh.getSubDivLevels}, L{NMesh.NMesh.setSubDivLevels}).
@note: Meshes extracted from curve based objects (Font/2D filled curves)
contain both the filled surfaces and the outlines of the shapes.
@warn: This function gets I{deformed} mesh data, already modified for
displaying (think "display list"). It also doesn't let you overwrite the
original mesh in Blender, so if you try to update it, a new mesh will
be created.
@warn: For Meta Object's, this function will only return a NMesh with some geometry
when called on the base element (the one with the shortest name).
"""
def PutRaw(nmesh, name = None, recalc_normals = 1, store_edges = 0):
"""
Put a BPython NMesh object as a mesh data object in Blender.
@note: if there is already a mesh with the given 'name', its contents are
freed and the new data is put in it. Also, if this mesh is not linked to any
object, a new object for it is created. Reminder: in Blender an object is
composed of the base object and linked object data (mesh, metaball, camera,
etc. etc).
@type nmesh: NMesh
@type name: string
@type recalc_normals: int
@type store_edges: int
@param name: The name of the mesh data object in Blender which will receive
this nmesh data. It can be an existing mesh data object or a new one.
@param recalc_normals: If non-zero, the vertex normals for the mesh will
be recalculated.
@param store_edges: deprecated, edges are always stored now.
@rtype: None or Object
@return: It depends on the 'name' parameter:
- I{name} refers to an existing mesh data obj already linked to an
object: return None.
- I{name} refers to a new mesh data obj or an unlinked (no users) one:
return the created Blender Object wrapper.
"""
class NMCol:
"""
The NMCol object
================
This object is a list of ints: [r, g, b, a] representing an
rgba color.
@ivar r: The Red component in [0, 255].
@ivar g: The Green component in [0, 255].
@ivar b: The Blue component in [0, 255].
@ivar a: The Alpha (transparency) component in [0, 255].
"""
class NMVert:
"""
The NMVert object
=================
This object holds mesh vertex data.
@type co: 3D Vector object. (WRAPPED DATA)
@ivar co: The vertex coordinates (x, y, z).
@type no: 3D Vector object. (unit length) (WRAPPED DATA)
@ivar no: The vertex normal vector (x, y, z).
@type uvco: 3D Vector object. (WRAPPED DATA)
@ivar uvco: The vertex texture "sticky" coordinates. The Z value of the Vector is ignored.
@type index: int
@ivar index: The vertex index, if owned by a mesh.
@type sel: int
@ivar sel: The selection state (selected:1, unselected:0) of this vertex.\n
Note: An NMesh will return the selection state of the mesh when EditMod was last exited. A python script operating in EditMode must exit edit mode, before getting the current selection state of the mesh.
@warn: There are two kinds of uv texture coordinates in Blender: per vertex
("sticky") and per face vertex (uv in L{NMFace}). In the first, there's
only one uv pair of coordinates for each vertex in the mesh. In the
second, for each face it belongs to, a vertex can have different uv
coordinates. This makes the per face option more flexible, since two
adjacent faces won't have to be mapped to a continuous region in an image:
each face can be independently mapped to any part of its texture.
"""
class NMEdge:
"""
The NMEdge object
=================
This object holds mesh edge data.
@type v1: NMVert
@ivar v1: The first vertex of the edge.
@type v2: NMVert
@ivar v2: The second vertex of the edge.
@type crease: int
@ivar crease: The crease value of the edge. It is in the range [0,255].
@type flag: int
@ivar flag: The bitmask describing edge properties. See L{NMesh.EdgeFlags<EdgeFlags>}.
"""
class NMFace:
"""
The NMFace object
=================
This object holds mesh face data.
Example::
import Blender
from Blender import NMesh, Window
in_emode = Window.EditMode()
if in_emode: Window.EditMode(0)
me = NMesh.GetRaw("Mesh")
faces = me.faces
## Example for editmode faces selection:
selected_faces = []
for f in faces:
if f.sel:
selected_faces.append(f)
# ... unselect selected and select all the others:
for f in faces:
f.sel = 1 - f.sel # 1 becomes 0, 0 becomes 1
## Example for uv textured faces selection:
selected_faces = []
SEL = NMesh.FaceFlags['SELECT']
# get selected faces:
for f in faces:
if f.flag & SEL:
selected_faces.append(f)
# ... unselect selected and select all the others:
for f in faces:
if f.flag & SEL:
f.flag &=~SEL # unselect these
else: f.flag |= SEL # and select these
me.update()
if in_emode: Window.EditMode(1)
Blender.Redraw()
@type v: list
@ivar v: The list of face vertices (B{up to 4}).
@type sel: bool
@ivar sel: The selection state (1: selected, 0: unselected) of this NMesh's
faces *in edit mode*. This is not the same as the selection state of
the textured faces (see L{flag}).
@type hide: bool
@ivar hide: The visibility state (1: hidden, 0: visible) of this NMesh's
faces *in edit mode*. This is not the same as the visibility state of
the textured faces (see L{flag}).
@ivar col: The list of vertex colors.
@ivar mat: Same as I{materialIndex} below.
@ivar materialIndex: The index of this face's material in its NMesh materials
list.
@ivar smooth: If non-zero, the vertex normals are averaged to make this
face look smooth.
@ivar image: The Image used as a texture for this face.
@ivar mode: The display mode (see L{Mesh.FaceModes<FaceModes>})
@ivar flag: Bit vector specifying selection / visibility flags for uv
textured faces (visible in Face Select mode, see
L{NMesh.FaceFlags<FaceFlags>}).
@ivar transp: Transparency mode bit vector
(see L{NMesh.FaceTranspModes<FaceTranspModes>}).
@ivar uv: List of per-face UV coordinates: [(u0, v0), (u1, v1), ...].
@ivar normal: (or just B{no}) The normal vector for this face: [x,y,z].
@note: there are normal faces and textured faces in Blender, both currently
with their own selection and visibility states, due to a mix of old and new
code. To (un)select or (un)hide normal faces (visible in editmode), use
L{sel} and L{hide} variables. For textured faces (Face Select
mode in Blender) use the old L{flag} bitflag. Also check the
example above and note L{Window.EditMode}.
@note: Assigning uv textures to mesh faces in Blender works like this:
1. Select your mesh.
2. Enter face select mode (press f) and select at least some face(s).
3. In the UV/Image Editor window, load / select an image.
4. Play in both windows (better split the screen to see both at the same
time) until the uv coordinates are where you want them. Hint: in the
3d window, the 'u' key opens a menu of default uv choices and the 'r'
key lets you rotate the uv coordinates.
5. Leave face select mode (press f).
"""
def append(vertex):
"""
Append a vertex to this face's vertex list.
@type vertex: NMVert
@param vertex: An NMVert object.
"""
from IDProp import IDGroup, IDArray
class NMesh:
"""
The NMesh Data object
=====================
This object gives access to mesh data in Blender. We refer to mesh as the
object in Blender and NMesh as its Python counterpart.
@ivar properties: Returns an L{IDGroup<IDProp.IDGroup>} reference to this
object's ID Properties.
@type properties: L{IDGroup<IDProp.IDGroup>}
@ivar name: The NMesh name. It's common to use this field to store extra
data about the mesh (to be exported to another program, for example).
@ivar materials: The list of materials used by this NMesh. See
L{getMaterials} for important details.
@ivar verts: The list of NMesh vertices (NMVerts).
@ivar users: The number of Objects using (linked to) this mesh.
@ivar faces: The list of NMesh faces (NMFaces).
@ivar edges: A list of L{NMEdge} edges.
@ivar mode: The mode flags for this mesh. See L{setMode}.
@ivar subDivLevels: The [display, rendering] subdivision levels in [1, 6].
@ivar maxSmoothAngle: The max angle for auto smoothing. See L{setMode}.
@cvar key: The L{Key.Key} object attached to this mesh, if any.
"""
def addEdge(v1, v2):
"""
Create an edge between two vertices.
If an edge already exists between those vertices, it is returned.
Created edge is automatically added to edges list.
You can only call this method if mesh has edge data.
@note: In Blender only zero or one edge can link two vertices.
@type v1: NMVert
@param v1: the first vertex of the edge.
@type v2: NMVert
@param v2: the second vertex of the edge.
@rtype: NMEdge
@return: The created or already existing edge.
"""
def findEdge(v1, v2):
"""
Try to find an edge between two vertices.
If no edge exists between v1 and v2, None is returned.
You can only call this method if mesh has edge data.
@type v1: NMVert
@param v1: the first vertex of the edge.
@type v2: NMVert
@param v2: the second vertex of the edge.
@rtype: NMEdge
@return: The found edge. None if no edge was found.
"""
def removeEdge(v1, v2):
"""
Remove an edge between two vertices.
All faces using this edge are removed from faces list.
You can only call this method if mesh has edge data.
@type v1: NMVert
@param v1: the first vertex of the edge.
@type v2: NMVert
@param v2: the second vertex of the edge.
"""
def addFace(face):
"""
Add a face to face list and add to edge list (if edge data exists) necessary edges.
@type face: NMFace
@param face: the face to add to the mesh.
@rtype: list of NMEdge
@return: If mesh has edge data, return the list of face edges.
"""
def removeFace(face):
"""
Remove a face for face list and remove edges no more used by any other face (if edge data exists).
@type face: NMFace
@param face: the face to add to the mesh.
"""
def addMaterial(material):
"""
Add a new material to this NMesh's list of materials. This method is the
slower but safer way to add materials, since it checks if the argument
given is really a material, imposes a limit of 16 materials and only adds
the material if it wasn't already in the list.
@type material: Blender Material
@param material: A Blender Material.
"""
def getMaterials(what = -1):
"""
Get this NMesh's list of materials.
@type what: int
@param what: determines the list's contents:
- -1: return the current NMesh's list;
- 0: retrieve a fresh list from the Blender mesh -- eventual
modifications made by the script not included, unless
L{update} is called before this method;
- 1: like 0, but empty slots are not ignored, they are returned as
None's.
@note: what >= 0 also updates nmesh.materials attribute.
@rtype: list of materials
@return: the requested list of materials.
@note: if a user goes to the material buttons window and removes some
mesh's link to a material, that material slot becomes empty.
Previously such materials were ignored.
@note: L{Object.colbits<Object.Object.colbits>} needs to be set correctly
for each object in order for these materials to be used instead of
the object's materials.
"""
def setMaterials(matlist):
"""
Set this NMesh's list of materials. This method checks the consistency of
the passed list: must only have materials or None's and can't contain more
than 16 entries.
@type matlist: list of materials
@param matlist: a list with materials, None's also accepted (they become
empty material slots in Blender.
@note: L{Object.colbits<Object.Object.colbits>} needs to be set correctly
for each object in order for these materials to be used instead of
the object's materials.
"""
def hasVertexColours(flag = None):
"""
Get (and optionally set) if this NMesh has vertex colors.
@type flag: int
@param flag: If given and non-zero, the "vertex color" flag for this NMesh
is turned I{on}.
@rtype: bool
@return: The current value of the "vertex color" flag.
@warn: If a mesh has both vertex colors and textured faces, this function
will return False. This is due to the way Blender deals internally with
the vertex colors array (if there are textured faces, it is copied to
the textured face structure and the original array is freed/deleted).
If you want to know if a mesh has both textured faces and vertex
colors, set *in Blender* the "VCol Paint" flag for each material that
covers an area that was also vertex painted and then check in your
Python script if that material flag is set. Of course also tell others
who use your script to do the same. The "VCol Paint" material mode flag
is the way to tell Blender itself to render with vertex colors, too, so
it's a natural solution.
"""
def hasFaceUV(flag = None):
"""
Get (and optionally set) if this NMesh has UV-mapped textured faces.
@type flag: int
@param flag: If given and non-zero, the "textured faces" flag for this
NMesh is turned I{on}.
@rtype: bool
@return: The current value of the "textured faces" flag.
"""
def hasVertexUV(flag = None):
"""
Get (and optionally set) the "sticky" flag that controls if a mesh has
per vertex UV coordinates.
@type flag: int
@param flag: If given and non-zero, the "sticky" flag for this NMesh is
turned I{on}.
@rtype: bool
@return: The current value of the "sticky" flag.
"""
def getActiveFace():
"""
Get the index of the active face.
@rtype: int
@return: The index of the active face.
"""
def getSelectedFaces(flag = None):
"""
Get list of selected faces.
@type flag: int
@param flag: If given and non-zero, the list will have indices instead of
the NMFace objects themselves.
@rtype: list
@return: It depends on the I{flag} parameter:
- if None or zero: List of NMFace objects.
- if non-zero: List of indices to NMFace objects.
@warn: this method exists to speed up retrieving of selected faces from
the actual mesh in Blender. So, if you make changes to the nmesh, you
need to L{update} it before using this method.
"""
def getVertexInfluences(index):
"""
Get influences of bones in a specific vertex.
@type index: int
@param index: The index of a vertex.
@rtype: list of lists
@return: List of pairs (name, weight), where name is the bone name (string)
and its weight is a float value.
"""
def getKey():
"""
Get the Key object representing the Vertex Keys (absolute or
relative) assigned to this mesh.
@rtype: L{Key.Key} object or None
"""
def insertKey(frame = None, type = 'relative'):
"""
Insert a mesh key at the given frame. Remember to L{update} the nmesh
before doing this, or changes in the vertices won't be updated in the
Blender mesh.
@type frame: int
@type type: string
@param frame: The Scene frame where the mesh key should be inserted. If
None, the current frame is used.
@param type: The mesh key type: 'relative' or 'absolute'. This is only
relevant on the first call to insertKey for each nmesh (and after all
keys were removed with L{removeAllKeys}, of course).
@warn: This and L{removeAllKeys} were included in this release only to
make accessing vertex keys possible, but may not be a proper solution
and may be substituted by something better later. For example, it
seems that 'frame' should be kept in the range [1, 100]
(the curves can be manually tweaked in the Ipo Curve Editor window in
Blender itself later).
"""
def removeAllKeys():
"""
Remove all mesh keys stored in this mesh.
@rtype: bool
@return: True if successful or False if this NMesh wasn't linked to a real
Blender Mesh yet (or was, but the Mesh had no keys).
@warn: Currently the mesh keys from meshes that are grabbed with
NMesh.GetRaw() or .GetRawFromObject() are preserved, so if you want to
clear them or don't want them at all, remember to call this method. Of
course NMeshes created with NMesh.New() don't have mesh keys until you
add them.
"""
def update(recalc_normals = 0, store_edges = 0, vertex_shade = 0):
"""
Update the mesh in Blender. The changes made are put back to the mesh in
Blender, if available, or put in a newly created mesh if this NMesh wasn't
already linked to one.
@type recalc_normals: int (bool)
@param recalc_normals: if nonzero the vertex normals are recalculated.
@type store_edges: int (bool)
@param store_edges: deprecated, edges are always stored now.
@type vertex_shade: int (bool)
@param vertex_shade: if nonzero vertices are colored based on the
current lighting setup, like when there are no vertex colors and no
textured faces and a user enters Vertex Paint Mode in Blender (only
lamps in visible layers account). To use this functionality, be out of
edit mode or else an error will be returned.
@warn: edit mesh and normal mesh are two different structures in Blender,
synchronized upon leaving or entering edit mode. Always remember to
leave edit mode (L{Window.EditMode}) before calling this update
method, or your changes will be lost. Even better: for the same reason
programmers should leave EditMode B{before} getting a mesh, or changes
made to the editmesh in Blender may not be visible to your script
(check the example at the top of NMesh module doc).
@warn: unlike the L{PutRaw} function, this method doesn't check validity of
vertex, face and material lists, because it is meant to be as fast as
possible (and already performs many tasks). So programmers should make
sure they only feed proper data to the nmesh -- a good general
recommendation, of course. It's also trivial to write code to check
all data before updating, for example by comparing each item's type
with the actual L{Types}, if you need to.
@note: this method also redraws the 3d view and -- if 'vertex_shade' is
nonzero -- the edit buttons window.
@note: if your mesh disappears after it's updated, try
L{Object.Object.makeDisplayList}. 'Subsurf' meshes (see L{getMode},
L{setMode}) need their display lists updated, too.
"""
def transform(matrix, recalc_normals = False):
"""
Transforms the mesh by the specified 4x4 matrix, as returned by
L{Object.Object.getMatrix}, though this will work with any invertible 4x4
matrix type. Ideal usage for this is exporting to an external file where
global vertex locations are required for each object.
Sometimes external renderers or file formats do not use vertex normals.
In this case, you can skip transforming the vertex normals by leaving
the optional parameter recalc_normals as False or 0 ( the default value ).
Example::
# This script outputs deformed meshes worldspace vertex locations
# for a selected object
import Blender
from Blender import NMesh, Object
ob = Object.GetSelected()[0] # Get the first selected object
me = NMesh.GetRawFromObject(ob.name) # Get the objects deformed mesh data
me.transform(ob.matrix)
for v in me.verts:
print 'worldspace vert', v.co
@type matrix: Py_Matrix
@param matrix: 4x4 Matrix which can contain location, scale and rotation.
@type recalc_normals: int (bool)
@param recalc_normals: if True or 1, transform normals as well as vertex coordinates.
@warn: if you call this method and later L{update} the mesh, the new
vertex positions will be passed back to Blender, but the object
matrix of each object linked to this mesh won't be automatically
updated. You need to set the object transformations (rotation,
translation and scaling) to identities, then, or the mesh data will
be changed ("transformed twice").
"""
def getMode():
"""
Get this mesh's mode flags.
@rtype: int
@return: ORed value. See L{Modes}.
"""
def setMode(m=None, m1=None, m2=None):
"""
Set the mode flags for this mesh. Given mode strings turn the mode "on".
Modes not passed in are turned "off", so setMode() (without arguments)
unsets all mode flags.
@type m: string or int (bitflag)
@param m: mode string or int. An int (see L{Modes}) or from none to 3
strings can be given:
- "NoVNormalsFlip"
- "TwoSided"
- "AutoSmooth"
"""
def addVertGroup(group):
"""
Add a named and empty vertex (deform) group to the object this nmesh is
linked to. If this nmesh was newly created or accessed with GetRaw, it must
first be linked to an object (with object.link or NMesh.PutRaw) so the
method knows which object to update.\n
This is because vertex groups in Blender are stored in I{the object} --
not in the mesh, which may be linked to more than one object. For this
reason, it's better to use "mesh = object.getData()" than
"mesh = NMesh.GetRaw(meshName)" to access an existing mesh.
@type group: string
@param group: the name for the new group.
"""
def removeVertGroup(group):
"""
Remove a named vertex (deform) group from the object linked to this nmesh.
All vertices assigned to the group will be removed (just from the group,
not deleted from the mesh), if any. If this nmesh was newly created, it
must first be linked to an object (read the comment in L{addVertGroup} for
more info).
@type group: string
@param group: the name of a vertex group.
"""
def assignVertsToGroup(group, vertList, weight, assignmode = 'replace'):
"""
Adds an array (a python list) of vertex points to a named vertex group
associated with a mesh. The vertex list is a list of vertex indices from
the mesh. You should assign vertex points to groups only when the mesh has
all its vertex points added to it and is already linked to an object.
I{B{Example:}}
The example here adds a new set of vertex indices to a sphere primitive::
import Blender
sphere = Blender.Object.Get('Sphere')
mesh = sphere.getData()
mesh.addVertGroup('firstGroup')
vertList = []
for x in range(300):
if x % 3 == 0:
vertList.append(x)
mesh.assignVertsToGroup('firstGroup', vertList, 0.5, 'add')
@type group: string
@param group: the name of the group.
@type vertList: list of ints
@param vertList: a list of vertex indices.
@type weight: float
@param weight: the deform weight for (which means: the amount of influence
the group has over) the given vertices. It should be in the range
[0.0, 1.0]. If weight <= 0, the given vertices are removed from the
group. If weight > 1, it is clamped.
@type assignmode: string
@param assignmode: Three choices:
- 'add'
- 'subtract'
- 'replace'\n
'B{add}': if the vertex in the list is not assigned to the group
already, this creates a new association between this vertex and the
group with the weight specified, otherwise the weight given is added to
the current weight of an existing association between the vertex and
group.\n
'B{subtract}' will attempt to subtract the weight passed from a vertex
already associated with a group, else it does nothing.\n
'B{replace}' attempts to replace a weight with the new weight value
for an already associated vertex/group, else it does nothing.
"""
def removeVertsFromGroup(group, vertList = None):
"""
Remove a list of vertices from the given group. If this nmesh was newly
created, it must first be linked to an object (check L{addVertGroup}).
@type group: string
@param group: the name of a vertex group
@type vertList: list of ints
@param vertList: a list of vertex indices to be removed from the given
'group'. If None, all vertices are removed -- the group is emptied.
"""
def getVertsFromGroup(group, weightsFlag = 0, vertList = None):
"""
Return a list of vertex indices associated with the passed group. This
method can be used to test whether a vertex index is part of a group and
if so, what its weight is.
I{B{Example:}}
Append this to the example from L{assignVertsToGroup}::
# ...
print "Vertex indices from group %s :" % groupName
print mesh.getVertsFromGroup('firstGroup')
print "Again, with weights:"
print mesh.getVertsFromGroup('firstGroup',1)
print "Again, with weights and restricted to the given indices:"
print mesh.getVertsFromGroup('firstGroup',1,[1,2,3,4,5,6])
@type group: string
@param group: the group name.
@type weightsFlag: bool
@param weightsFlag: if 1, the weight is returned along with the index.
@type vertList: list of ints
@param vertList: if given, only those vertex points that are both in the
list and group passed in are returned.
"""
def renameVertGroup(groupName, newName):
"""
Renames a vertex group.
@type groupName: string
@param groupName: the vertex group name to be renamed.
@type newName: string
@param newName: the name to replace the old name.
"""
def getVertGroupNames():
"""
Return a list of all vertex group names.
@rtype: list of strings
@return: returns a list of strings representing all vertex group
associated with the mesh's object
"""
def getMaxSmoothAngle():
"""
Get the max angle for auto smoothing.
Note: This will only affect smoothing generated at render time.
Smoothing can also be set per face which is visible in Blenders 3D View.
@return: The value in degrees.
"""
def setMaxSmoothAngle(angle):
"""
Set the max angle for auto smoothing.
@type angle: int
@param angle: The new value in degrees -- it's clamped to [1, 80].
"""
def getSubDivLevels():
"""
Get the mesh subdivision levels for realtime display and rendering.
@return: list of ints: [display, render].
"""
def setSubDivLevels(subdiv):
"""
Set the mesh subdivision levels for realtime display and rendering.
@type subdiv: list of 2 ints
@param subdiv: new subdiv levels: [display, render]. Both are clamped to
lie in the range [1, 6].
"""

View File

@@ -0,0 +1,300 @@
# Blender.Noise submodule
"""
The Blender.Noise submodule.
Noise and Turbulence
====================
This module can be used to generate noise of various types. This can be used
for terrain generation, to create textures, make animations more 'animated',
object deformation, etc. As an example, this code segment when scriptlinked
to a framechanged event, will make the camera sway randomly about, by changing
parameters this can look like anything from an earthquake to a very nervous or
maybe even drunk cameraman... (the camera needs an ipo with at least one Loc &
Rot key for this to work!):
Example::
from Blender import Get, Scene, Noise
####################################################
# This controls jitter speed
sl = 0.025
# This controls the amount of position jitter
sp = 0.1
# This controls the amount of rotation jitter
sr = 0.25
####################################################
time = Get('curtime')
ob = Scene.GetCurrent().getCurrentCamera()
ps = (sl*time, sl*time, sl*time)
# To add jitter only when the camera moves, use this next line instead
#ps = (sl*ob.LocX, sl*ob.LocY, sl*ob.LocZ)
rv = Noise.vTurbulence(ps, 3, 0, Noise.NoiseTypes.NEWPERLIN)
ob.dloc = (sp*rv[0], sp*rv[1], sp*rv[2])
ob.drot = (sr*rv[0], sr*rv[1], sr*rv[2])
@type NoiseTypes: readonly dictionary
@var NoiseTypes: The available noise types.
- BLENDER
- STDPERLIN
- NEWPERLIN
- VORONOI_F1
- VORONOI_F2
- VORONOI_F3
- VORONOI_F4
- VORONOI_F2F1
- VORONOI_CRACKLE
- CELLNOISE
@type DistanceMetrics: readonly dictionary
@var DistanceMetrics: The available distance metrics values for Voronoi.
- DISTANCE
- DISTANCE_SQUARED
- MANHATTAN
- CHEBYCHEV
- MINKOVSKY_HALF
- MINKOVSKY_FOUR
- MINKOVISKY
"""
NoiseTypes = {'BLENDER':0, 'STDPERLIN':1}
DistanceMetrics = {'DISTANCE':0}
def random ():
"""
Returns a random floating point number."
@rtype: float
@return: a random number in [0, 1).
"""
def randuvec ():
"""
Returns a random unit vector.
@rtype: 3-float list
@return: a list of three floats.
"""
def setRandomSeed (seed):
"""
Initializes the random number generator.
@type seed: int
@param seed: the seed for the random number generator. If seed = 0, the
current time will be used as seed, instead.
"""
def noise (xyz, type = NoiseTypes['STDPERLIN']):
"""
Returns general noise of the optional specified type.
@type xyz: tuple of 3 floats
@param xyz: (x,y,z) float values.
@type type: int
@param type: the type of noise to return. See L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def vNoise (xyz, type = NoiseTypes['STDPERLIN']):
"""
Returns noise vector of the optional specified type.
@type xyz: tuple of 3 floats
@param xyz: (x,y,z) float values.
@type type: int
@param type: the type of noise to return. See L{NoiseTypes}.
@rtype: 3-float list
@return: the generated noise vector.
"""
def turbulence (xyz, octaves, hard, basis = NoiseTypes['STDPERLIN'],
ampscale = 0.5, freqscale = 2.0):
"""
Returns general turbulence value using the optional specified noise 'basis'
function.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type octaves: int
@param octaves: number of noise values added.
@type hard: bool
@param hard: noise hardness: 0 - soft noise; 1 - hard noise. (Returned value
is always positive.)
@type basis: int
@param basis: type of noise used for turbulence, see L{NoiseTypes}.
@type ampscale: float
@param ampscale: amplitude scale value of the noise frequencies added.
@type freqscale: float
@param freqscale: frequency scale factor.
@rtype: float
@return: the generated turbulence value.
"""
def vTurbulence (xyz, octaves, hard, basis = NoiseTypes['STDPERLIN'],
ampscale = 0.5, freqscale = 2.0):
"""
Returns general turbulence vector using the optional specified noise basis
function.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type octaves: int
@param octaves: number of noise values added.
@type hard: bool
@param hard: noise hardness: 0 - soft noise; 1 - hard noise. (Returned
vector is always positive.)
@type basis: int
@param basis: type of noise used for turbulence, see L{NoiseTypes}.
@type ampscale: float
@param ampscale: amplitude scale value of the noise frequencies added.
@type freqscale: float
@param freqscale: frequency scale factor.
@rtype: 3-float list
@return: the generated turbulence vector.
"""
def fBm (xyz, H, lacunarity, octaves, basis = NoiseTypes['STDPERLIN']):
"""
Returns Fractal Brownian Motion noise value (fBm).
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: the fractal increment parameter.
@type lacunarity: float
@param lacunarity: the gap between successive frequencies.
@type octaves: float
@param octaves: the number of frequencies in the fBm.
@type basis: int
@param basis: type of noise used for the turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def multiFractal (xyz, H, lacunarity, octaves, basis = NoiseTypes['STDPERLIN']):
"""
Returns Multifractal noise value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: the highest fractal dimension.
@type lacunarity: float
@param lacunarity: the gap between successive frequencies.
@type octaves: float
@param octaves: the number of frequencies in the fBm.
@type basis: int
@param basis: type of noise used for the turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated noise value.
"""
def vlNoise (xyz, distortion, type1 = NoiseTypes['STDPERLIN'],
type2 = NoiseTypes['STDPERLIN']):
"""
Returns Variable Lacunarity Noise value, a distorted variety of noise.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type distortion: float
@param distortion: the amount of distortion.
@type type1: int
@type type2: int
@param type1: sets the noise type to distort.
@param type2: sets the noise type used for the distortion.
@rtype: float
@return: the generated noise value.
"""
def heteroTerrain (xyz, H, lacunarity, octaves, offset,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Heterogeneous Terrain value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def hybridMFractal (xyz, H, lacunarity, octaves, offset, gain,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Hybrid Multifractal value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type gain: float
@param gain: scale factor.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def ridgedMFractal (xyz, H, lacunarity, octaves, offset, gain,
basis = NoiseTypes['STDPERLIN']):
"""
Returns Ridged Multifractal value.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type H: float
@param H: fractal dimension of the roughest areas.
@type lacunarity: float
@param lacunarity: gap between successive frequencies.
@type octaves: float
@param octaves: number of frequencies in the fBm.
@type offset: float
@param offset: it raises the terrain from 'sea level'.
@type gain: float
@param gain: scale factor.
@type basis: int
@param basis: noise basis determines the type of noise used for the
turbulence, see L{NoiseTypes}.
@rtype: float
@return: the generated value.
"""
def voronoi(xyz, distance_metric = DistanceMetrics['DISTANCE'], exponent = 2.5):
"""
Returns Voronoi diagrams-related data.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@type distance_metric: int
@param distance_metric: see L{DistanceMetrics}
@type exponent: float
@param exponent: only used with MINKOVSKY, default is 2.5.
@rtype: list
@return: a list containing a list of distances in order of closest feature,
and a list containing the positions of the four closest features.
"""
def cellNoise (xyz):
"""
Returns cellnoise.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@rtype: float
@return: the generated value.
"""
def cellNoiseV (xyz):
"""
Returns cellnoise vector/point/color.
@type xyz: 3-float tuple
@param xyz: (x,y,z) float values.
@rtype: 3-float list
@return: the generated vector.
"""

View File

@@ -0,0 +1,1754 @@
# Blender.Object module and the Object PyType object
"""
The Blender.Object submodule
B{New}:
- Addition of attributes for particle deflection, softbodies, and
rigidbodies.
- Objects now increment the Blender user count when they are created and
decremented it when they are destroyed. This means Python scripts can
keep the object "alive" if it is deleted in the Blender GUI.
- L{Object.getData} now accepts two optional bool keyword argument to
define (1) if the user wants the data object or just its name
and (2) if a mesh object should use NMesh or Mesh.
- L{Object.clearScriptLinks} accepts a parameter now.
- Object attributes: renamed Layer to L{Layers<Object.Object.Layers>} and
added the easier L{layers<Object.Object.layers>}. The old form "Layer"
will continue to work.
Object
======
This module provides access to the B{Objects} in Blender.
Example::
import Blender
scn = Blender.Scene.GetCurrent() # get the current scene
cam = Blender.Camera.New('ortho') # make ortho camera data object
ob = scn.objects.new(cam) # make a new object in this scene using the camera data
ob.setLocation (0.0, -5.0, 1.0) # position the object in the scene
Blender.Redraw() # redraw the scene to show the updates.
@type DrawModes: readonly dictionary
@var DrawModes: Constant dict used for with L{Object.drawMode} bitfield
attribute. Values can be ORed together. Individual bits can also
be set/cleared with boolean attributes.
- AXIS: Enable display of active object's center and axis.
- TEXSPACE: Enable display of active object's texture space.
- NAME: Enable display of active object's name.
- WIRE: Enable the active object's wireframe over solid drawing.
- XRAY: Enable drawing the active object in front of others.
- TRANSP: Enable transparent materials for the active object (mesh only).
@type DrawTypes: readonly dictionary
@var DrawTypes: Constant dict used for with L{Object.drawType} attribute.
Only one type can be selected at a time.
- BOUNDBOX: Only draw object with bounding box
- WIRE: Draw object in wireframe
- SOLID: Draw object in solid
- SHADED: Draw object with shaded or textured
@type ParentTypes: readonly dictionary
@var ParentTypes: Constant dict used for with L{Object.parentType} attribute.
- OBJECT: Object parent type.
- CURVE: Curve deform parent type.
- LATTICE: Lattice deform parent type. Note: This is the same as ARMATURE, 2.43 was released with LATTICE as an invalid value.
- ARMATURE: Armature deform parent type.
- VERT1: 1 mesh vert parent type.
- VERT3: 1 mesh verts parent type.
- BONE: Armature bone parent type.
@type ProtectFlags: readonly dictionary
@var ProtectFlags: Constant dict used for with L{Object.protectFlags} attribute.
Values can be ORed together.
- LOCX, LOCY, LOCZ: lock x, y or z location individually
- ROTX, ROTY, ROTZ: lock x, y or z rotation individually
- SCALEX, SCALEY, SCALEZ: lock x, y or z scale individually
- LOC, ROT, SCALE: lock all 3 attributes for location, rotation or scale
@type PITypes: readonly dictionary
@var PITypes: Constant dict used for with L{Object.piType} attribute.
Only one type can be selected at a time.
- NONE: No force influence on particles
- FORCE: Object center attracts or repels particles ("Spherical")
- VORTEX: Particles swirl around Z-axis of the object
- WIND: Constant force applied in direction of object Z axis
- GUIDE: Use a Curve Path to guide particles
@type RBFlags: readonly dictionary
@var RBFlags: Constant dict used for with L{Object.rbFlags} attribute.
Values can be ORed together.
- SECTOR: All game elements should be in the Sector boundbox
- PROP: An Object fixed within a sector
- BOUNDS: Specify a bounds object for physics
- ACTOR: Enables objects that are evaluated by the engine
- DYNAMIC: Enables motion defined by laws of physics (requires ACTOR)
- GHOST: Enable objects that don't restitute collisions (requires ACTOR)
- MAINACTOR: Enables MainActor (requires ACTOR)
- RIGIDBODY: Enable rolling physics (requires ACTOR, DYNAMIC)
- COLLISION_RESPONSE: Disable auto (de)activation (requires ACTOR, DYNAMIC)
- USEFH: Use Fh settings in Materials (requires ACTOR, DYNAMIC)
- ROTFH: Use face normal to rotate Object (requires ACTOR, DYNAMIC)
- ANISOTROPIC: Enable anisotropic friction (requires ACTOR, DYNAMIC)
- CHILD: reserved
@type IpoKeyTypes: readonly dictionary
@var IpoKeyTypes: Constant dict used for with L{Object.insertIpoKey} attribute.
Values can be ORed together.
- LOC
- ROT
- SIZE
- LOCROT
- LOCROTSIZE
- PI_STRENGTH
- PI_FALLOFF
- PI_SURFACEDAMP
- PI_RANDOMDAMP
- PI_PERM
@type RBShapes: readonly dictionary
@var RBShapes: Constant dict used for with L{Object.rbShapeBoundType}
attribute. Only one type can be selected at a time. Values are
BOX, SPHERE, CYLINDER, CONE, and POLYHEDERON
"""
def New (type, name='type'):
"""
Creates a new Object. Deprecated; instead use Scene.objects.new().
@type type: string
@param type: The Object type: 'Armature', 'Camera', 'Curve', 'Lamp', 'Lattice',
'Mball', 'Mesh', 'Surf' or 'Empty'.
@type name: string
@param name: The name of the object. By default, the name will be the same
as the object type.
If the name is already in use, this new object will have a number at the end of the name.
@return: The created Object.
I{B{Example:}}
The example below creates a new Lamp object and puts it at the default
location (0, 0, 0) in the current scene::
import Blender
object = Blender.Object.New('Lamp')
lamp = Blender.Lamp.New('Spot')
object.link(lamp)
sce = Blender.Scene.GetCurrent()
sce.link(object)
Blender.Redraw()
@Note: if an object is created but is not linked to object data, and the
object is not linked to a scene, it will be deleted when the Python
object is deallocated. This is because Blender does not allow objects
to exist without object data unless they are Empty objects. Scene.link()
will automatically create object data for an object if it has none.
"""
def Get (name = None):
"""
Get the Object from Blender.
@type name: string
@param name: The name of the requested Object.
@return: It depends on the 'name' parameter:
- (name): The Object with the given name;
- (): A list with all Objects in the current scene.
I{B{Example 1:}}
The example below works on the default scene. The script returns the plane object and prints the location of the plane::
import Blender
object = Blender.Object.Get ('plane')
print object.getLocation()
I{B{Example 2:}}
The example below works on the default scene. The script returns all objects
in the scene and prints the list of object names::
import Blender
objects = Blender.Object.Get ()
print objects
@note: Get will return objects from all scenes.
Most user tools should only operate on objects from the current scene - Blender.Scene.GetCurrent().getChildren()
"""
def GetSelected ():
"""
Get the user selection. If no objects are selected, an empty list will be returned.
@return: A list of all selected Objects in the current scene.
I{B{Example:}}
The example below works on the default scene. Select one or more objects and
the script will print the selected objects::
import Blender
objects = Blender.Object.GetSelected()
print objects
@note: The active object will always be the first object in the list (if selected).
@note: The user selection is made up of selected objects from Blender's current scene only.
@note: The user selection is limited to objects on visible layers;
if the user's last active 3d view is in localview then the selection will be limited to the objects in that localview.
"""
def Duplicate (mesh=0, surface=0, curve=0, text=0, metaball=0, armature=0, lamp=0, material=0, texture=0, ipo=0):
"""
Duplicate selected objects on visible layers from Blenders current scene,
de-selecting the currently visible, selected objects and making a copy where all new objects are selected.
By default no data linked to the object is duplicated; use the keyword arguments to change this.
L{Object.GetSelected()<GetSelected>} will return the list of objects resulting from duplication.
B{Note}: This command will raise an error if used from the command line (background mode) because it uses the 3D view context.
@type mesh: bool
@param mesh: When non-zero, mesh object data will be duplicated with the objects.
@type surface: bool
@param surface: When non-zero, surface object data will be duplicated with the objects.
@type curve: bool
@param curve: When non-zero, curve object data will be duplicated with the objects.
@type text: bool
@param text: When non-zero, text object data will be duplicated with the objects.
@type metaball: bool
@param metaball: When non-zero, metaball object data will be duplicated with the objects.
@type armature: bool
@param armature: When non-zero, armature object data will be duplicated with the objects.
@type lamp: bool
@param lamp: When non-zero, lamp object data will be duplicated with the objects.
@type material: bool
@param material: When non-zero, materials used by the object or its object data will be duplicated with the objects.
@type texture: bool
@param texture: When non-zero, texture data used by the object's materials will be duplicated with the objects.
@type ipo: bool
@param ipo: When non-zero, Ipo data linked to the object will be duplicated with the objects.
I{B{Example:}}
The example below creates duplicates the active object 10 times
and moves each object 1.0 on the X axis::
import Blender
scn = Scene.GetCurrent()
ob_act = scn.objects.active
# Unselect all
scn.objects.selected = []
ob_act.sel = 1
for x in xrange(10):
Blender.Object.Duplicate() # Duplicate linked
ob_act = scn.objects.active
ob_act.LocX += 1
Blender.Redraw()
"""
from IDProp import IDGroup, IDArray
class Object:
"""
The Object object
=================
This object gives access to generic data from all objects in Blender.
B{Note}:
When dealing with properties and functions such as LocX/RotY/getLocation(), getSize() and getEuler(),
keep in mind that these transformation properties are relative to the object's parent (if any).
To get these values in worldspace (taking into account vertex parents, constraints, etc.)
pass the argument 'worldspace' to these functions.
@ivar restrictDisplay: Don't display this object in the 3D view: disabled by default, use the outliner to toggle.
@type restrictDisplay: bool
@ivar restrictSelect: Don't select this object in the 3D view: disabled by default, use the outliner to toggle.
@type restrictSelect: bool
@ivar restrictRender: Don't render this object: disabled by default, use the outliner to toggle.
@type restrictRender: bool
@ivar LocX: The X location coordinate of the object.
@type LocX: float
@ivar LocY: The Y location coordinate of the object.
@type LocY: float
@ivar LocZ: The Z location coordinate of the object.
@type LocZ: float
@ivar loc: The (X,Y,Z) location coordinates of the object.
@type loc: tuple of 3 floats
@ivar dLocX: The delta X location coordinate of the object.
This variable applies to IPO Objects only.
@type dLocX: float
@ivar dLocY: The delta Y location coordinate of the object.
This variable applies to IPO Objects only.
@type dLocY: float
@ivar dLocZ: The delta Z location coordinate of the object.
This variable applies to IPO Objects only.
@type dLocZ: float
@ivar dloc: The delta (X,Y,Z) location coordinates of the object (vector).
This variable applies to IPO Objects only.
@type dloc: tuple of 3 floats
@ivar RotX: The X rotation angle (in radians) of the object.
@type RotX: float
@ivar RotY: The Y rotation angle (in radians) of the object.
@type RotY: float
@ivar RotZ: The Z rotation angle (in radians) of the object.
@type RotZ: float
@ivar rot: The (X,Y,Z) rotation angles (in radians) of the object.
@type rot: euler (Py_WRAPPED)
@ivar dRotX: The delta X rotation angle (in radians) of the object.
This variable applies to IPO Objects only.
@type dRotX: float
@ivar dRotY: The delta Y rotation angle (in radians) of the object.
This variable applies to IPO Objects only.
@type dRotY: float
@ivar dRotZ: The delta Z rotation angle (in radians) of the object.
This variable applies to IPO Objects only.
@type dRotZ: float
@ivar drot: The delta (X,Y,Z) rotation angles (in radians) of the object.
This variable applies to IPO Objects only.
@type drot: tuple of 3 floats
@ivar SizeX: The X size of the object.
@type SizeX: float
@ivar SizeY: The Y size of the object.
@type SizeY: float
@ivar SizeZ: The Z size of the object.
@type SizeZ: float
@ivar size: The (X,Y,Z) size of the object.
@type size: tuple of 3 floats
@ivar dSizeX: The delta X size of the object.
@type dSizeX: float
@ivar dSizeY: The delta Y size of the object.
@type dSizeY: float
@ivar dSizeZ: The delta Z size of the object.
@type dSizeZ: float
@ivar dsize: The delta (X,Y,Z) size of the object.
@type dsize: tuple of 3 floats
@ivar Layers: The object layers (also check the newer attribute
L{layers<layers>}). This value is a bitmask with at
least one position set for the 20 possible layers starting from the low
order bit. The easiest way to deal with these values in in hexadecimal
notation.
Example::
ob.Layer = 0x04 # sets layer 3 ( bit pattern 0100 )
After setting the Layer value, call Blender.Redraw( -1 ) to update
the interface.
@type Layers: integer (bitmask)
@type layers: list of integers
@ivar layers: The layers this object is visible in (also check the older
attribute L{Layers<Layers>}). This returns a list of
integers in the range [1, 20], each number representing the respective
layer. Setting is done by passing a list of ints or an empty list for
no layers.
Example::
ob.layers = [] # object won't be visible
ob.layers = [1, 4] # object visible only in layers 1 and 4
ls = o.layers
ls.append([10])
o.layers = ls
print ob.layers # will print: [1, 4, 10]
B{Note}: changes will only be visible after the screen (at least
the 3d View and Buttons windows) is redrawn.
@ivar parent: The parent object of the object (if defined). Read-only.
@type parent: Object or None
@ivar data: The Datablock object linked to this object. Read-only.
@type data: varies
@ivar ipo: Contains the Ipo if one is assigned to the object, B{None}
otherwise. Setting to B{None} clears the current Ipo.
@type ipo: Ipo
@ivar mat: The matrix of the object in world space (absolute, takes vertex parents, tracking
and Ipos into account). Read-only.
@type mat: Matrix
@ivar matrix: Same as L{mat}. Read-only.
@type matrix: Matrix
@ivar matrixLocal: The matrix of the object relative to its parent; if there is no parent,
returns the world matrix (L{matrixWorld<Object.Object.matrixWorld>}).
@type matrixLocal: Matrix
@ivar matrixParentInverse: The inverse if the parents local matrix, set when the objects parent is set (wrapped).
@type matrixParentInverse: Matrix
@ivar matrixOldWorld: Old-type worldspace matrix (prior to Blender 2.34).
Read-only.
@type matrixOldWorld: Matrix
@ivar matrixWorld: Same as L{mat}. Read-only.
@type matrixWorld: Matrix
@ivar colbits: The Material usage mask. A set bit #n means: the Material
#n in the Object's material list is used. Otherwise, the Material #n
of the Objects Data material list is displayed.
Example::
object.colbits = (1<<0) + (1<<5) # use mesh materials 0 (1<<0) and 5 (1<<5)
# use object materials for all others
@ivar sel: The selection state of the object in the current scene.
True is selected, False is unselected. Setting makes the object active.
@type sel: boolean
@ivar effects: The list of particle effects associated with the object.
Read-only.
@type effects: list of Effect objects
@ivar parentbonename: The string name of the parent bone (if defined).
This can be set to another bone in the armature if the object already has a bone parent.
@type parentbonename: string or None
@ivar protectFlags: The "transform locking" bitfield flags for the object.
See L{ProtectFlags} const dict for values.
@type protectFlags: int
@ivar DupGroup: The DupliGroup Animation Property. Assign a group to
DupGroup to make this object an instance of that group.
This does not enable or disable the DupliGroup option, for that use
L{enableDupGroup}.
The attribute returns None when this object does not have a dupliGroup,
and setting the attrbute to None deletes the object from the group.
@type DupGroup: Group or None
@ivar DupObjects: The Dupli object instances. Read-only.
Returns of list of tuples for object duplicated
by dupliframe, dupliverts dupligroups and other animation properties.
The first tuple item is the original object that is duplicated,
the second is the 4x4 worldspace dupli-matrix.
Example::
import Blender
from Blender import Object, Scene, Mathutils
ob= Object.Get('Cube')
dupe_obs= ob.DupObjects
scn= Scene.GetCurrent()
for dupe_ob, dupe_matrix in dupe_obs:
print dupe_ob.name
empty_ob = scn.objects.new('Empty')
empty_ob.setMatrix(dupe_matrix)
Blender.Redraw()
@type DupObjects: list of tuples containing (object, matrix)
@ivar enableNLAOverride: Whether the object uses NLA or active Action for animation.
@type enableNLAOverride: boolean
@ivar enableDupVerts: The DupliVerts status of the object.
Does not indicate that this object has any dupliVerts,
(as returned by L{DupObjects}) just that dupliVerts are enabled.
@type enableDupVerts: boolean
@ivar enableDupFaces: The DupliFaces status of the object.
Does not indicate that this object has any dupliFaces,
(as returned by L{DupObjects}) just that dupliFaces are enabled.
@type enableDupFaces: boolean
@ivar enableDupFacesScale: The DupliFacesScale status of the object.
@type enableDupFacesScale: boolean
@ivar enableDupFrames: The DupliFrames status of the object.
Does not indicate that this object has any dupliFrames,
(as returned by L{DupObjects}) just that dupliFrames are enabled.
@type enableDupFrames: boolean
@ivar enableDupGroup: The DupliGroup status of the object.
Set True to make this object an instance of the object's L{DupGroup},
and set L{DupGroup} to a group for this to take effect,
Use L{DupObjects} to get the object data from this instance.
@type enableDupGroup: boolean
@ivar enableDupRot: The DupliRot status of the object.
Use with L{enableDupVerts} to rotate each instance
by the vertex normal.
@type enableDupRot: boolean
@ivar enableDupNoSpeed: The DupliNoSpeed status of the object.
Use with L{enableDupFrames} to ignore dupliFrame speed.
@type enableDupNoSpeed: boolean
@ivar DupSta: The DupliFrame starting frame. Use with L{enableDupFrames}.
Value clamped to [1,32767].
@type DupSta: int
@ivar DupEnd: The DupliFrame end frame. Use with L{enableDupFrames}.
Value clamped to [1,32767].
@type DupEnd: int
@ivar DupOn: The DupliFrames in succession between DupOff frames.
Value is clamped to [1,1500].
Use with L{enableDupFrames} and L{DupOff} > 0.
@type DupOn: int
@ivar DupOff: The DupliFrame removal of every Nth frame for this object.
Use with L{enableDupFrames}. Value is clamped to [0,1500].
@type DupOff: int
@ivar passIndex: Index # for the IndexOB render pass.
Value is clamped to [0,1000].
@type passIndex: int
@ivar activeMaterial: The active material index for this object.
The active index is used to select the material to edit in the material buttons,
new data created will also use the active material.
Value is clamped to [1,len(ob.materials)]. - [0,0] when there is no materials applied to the object.
@type activeMaterial: int
@ivar activeShape: The active shape key index for this object.
The active index is used to select the material to edit in the material buttons,
new data created will also use the active material.
Value is clamped to [1,len(ob.data.key.blocks)]. - [0,0] when there are no keys.
@type activeShape: int
@ivar pinShape: If True, only the activeShape will be displayed.
@type pinShape: bool
@ivar drawSize: The size to display the Empty.
Value clamped to [0.01,10.0].
@type drawSize: float
@ivar modifiers: The modifiers associated with the object.
Example::
# copy the active objects modifiers to all other visible selected objects
from Blender import *
scn = Scene.GetCurrent()
ob_act = scn.objects.active
for ob in scn.objects.context:
# Cannot copy modifiers to an object of a different type
if ob.type == ob_act.type:
ob.modifiers = ob_act.modifiers
@type modifiers: L{Modifier Sequence<Modifier.ModSeq>}
@ivar constraints: a L{sequence<Constraint.Constraints>} of
L{constraints<Constraint.Constraint>} for the object. Read-only.
@type constraints: Constraint Sequence
@ivar actionStrips: a L{sequence<NLA.ActionStrips>} of
L{action strips<NLA.ActionStrip>} for the object. Read-only.
@type actionStrips: BPy_ActionStrips
@ivar action: The action associated with this object (if defined).
@type action: L{Action<NLA.Action>} or None
@ivar oopsLoc: Object's (X,Y) OOPs location. Returns None if object
is not found in list.
@type oopsLoc: tuple of 2 floats
@ivar oopsSel: Object OOPs selection flag.
@type oopsSel: boolean
@ivar game_properties: The object's properties. Read-only.
@type game_properties: list of Properties.
@ivar timeOffset: The time offset of the object's animation.
Value clamped to [-300000.0,300000.0].
@type timeOffset: float
@ivar track: The object's tracked object. B{None} is returned if no
object is tracked. Also, assigning B{None} clear the tracked object.
@type track: Object or None
@ivar type: The object's type. Read-only.
@type type: string
@ivar boundingBox: The bounding box of this object. Read-only.
@type boundingBox: list of 8 3D vectors
@ivar drawType: The object's drawing type.
See L{DrawTypes} constant dict for values.
@type drawType: int
@ivar parentType: The object's parent type. Read-only.
See L{ParentTypes} constant dict for values.
@type parentType: int
@ivar axis: Enable display of active object's center and axis.
Also see B{AXIS} bit in L{drawMode} attribute.
@type axis: boolean
@ivar texSpace: Enable display of active object's texture space.
Also see B{TEXSPACE} bit in L{drawMode} attribute.
@type texSpace: boolean
@ivar nameMode: Enable display of active object's name.
Also see B{NAME} bit in L{drawMode} attribute.
@type nameMode: boolean
@ivar wireMode: Enable the active object's wireframe over solid drawing.
Also see B{WIRE} bit in L{drawMode} attribute.
@type wireMode: boolean
@ivar xRay: Enable drawing the active object in front of others.
Also see B{XRAY} bit in L{drawMode} attribute.
@type xRay: boolean
@ivar transp: Enable transparent materials for the active object
(mesh only). Also see B{TRANSP} bit in L{drawMode} attribute.
@type transp: boolean
@ivar drawMode: The object's drawing mode bitfield.
See L{DrawModes} constant dict for values.
@type drawMode: int
@ivar piType: Type of particle interaction.
See L{PITypes} constant dict for values.
@type piType: int
@ivar piFalloff: The particle interaction falloff power.
Value clamped to [0.0,10.0].
@type piFalloff: float
@ivar piMaxDist: Max distance for the particle interaction field to work.
Value clamped to [0.0,1000.0].
@type piMaxDist: float
@ivar piPermeability: Probability that a particle will pass through the
mesh. Value clamped to [0.0,1.0].
@type piPermeability: float
@ivar piRandomDamp: Random variation of particle interaction damping.
Value clamped to [0.0,1.0].
@type piRandomDamp: float
@ivar piSoftbodyDamp: Damping factor for softbody deflection.
Value clamped to [0.0,1.0].
@type piSoftbodyDamp: float
@ivar piSoftbodyIThick: Inner face thickness for softbody deflection.
Value clamped to [0.001,1.0].
@type piSoftbodyIThick: float
@ivar piSoftbodyOThick: Outer face thickness for softbody deflection.
Value clamped to [0.001,1.0].
@type piSoftbodyOThick: float
@ivar piStrength: Particle interaction force field strength.
Value clamped to [0.0,1000.0].
@type piStrength: float
@ivar piSurfaceDamp: Amount of damping during particle collision.
Value clamped to [0.0,1.0].
@type piSurfaceDamp: float
@ivar piUseMaxDist: Use a maximum distance for the field to work.
@type piUseMaxDist: boolean
@ivar isSoftBody: True if object is a soft body. Read-only.
@type isSoftBody: boolean
@ivar SBDefaultGoal: Default softbody goal value, when no vertex group used.
Value clamped to [0.0,1.0].
@type SBDefaultGoal: float
@ivar SBErrorLimit: Softbody Runge-Kutta ODE solver error limit (low values give more precision).
Value clamped to [0.01,1.0].
@type SBErrorLimit: float
@ivar SBFriction: General media friction for softbody point movements.
Value clamped to [0.0,10.0].
@type SBFriction: float
@ivar SBGoalFriction: Softbody goal (vertex target position) friction.
Value clamped to [0.0,10.0].
@type SBGoalFriction: float
@ivar SBGoalSpring: Softbody goal (vertex target position) spring stiffness.
Value clamped to [0.0,0.999].
@type SBGoalSpring: float
@ivar SBGrav: Apply gravitation to softbody point movement.
Value clamped to [0.0,10.0].
@type SBGrav: float
@ivar SBInnerSpring: Softbody edge spring stiffness.
Value clamped to [0.0,0.999].
@type SBInnerSpring: float
@ivar SBInnerSpringFrict: Softbody edge spring friction.
Value clamped to [0.0,10.0].
@type SBInnerSpringFrict: float
@ivar SBMass: Softbody point mass (heavier is slower).
Value clamped to [0.001,50.0].
@type SBMass: float
@ivar SBMaxGoal: Softbody goal maximum (vertex group weights scaled to
match this range). Value clamped to [0.0,1.0].
@type SBMaxGoal: float
@ivar SBMinGoal: Softbody goal minimum (vertex group weights scaled to
match this range). Value clamped to [0.0,1.0].
@type SBMinGoal: float
@ivar SBSpeed: Tweak timing for physics to control softbody frequency and
speed. Value clamped to [0.0,10.0].
@type SBSpeed: float
@ivar SBStiffQuads: Softbody adds diagonal springs on 4-gons enabled.
@type SBStiffQuads: boolean
@ivar SBUseEdges: Softbody use edges as springs enabled.
@type SBUseEdges: boolean
@ivar SBUseGoal: Softbody forces for vertices to stick to animated position enabled.
@type SBUseGoal: boolean
@ivar rbFlags: Rigid body bitfield. See L{RBFlags} for valid values.
@type rbFlags: int
@ivar rbMass: Rigid body mass. Must be a positive value.
@type rbMass: float
@ivar rbRadius: Rigid body bounding sphere size. Must be a positive
value.
@type rbRadius: float
@ivar rbShapeBoundType: Rigid body shape bound type. See L{RBShapes}
const dict for values.
@type rbShapeBoundType: int
"""
def buildParts():
"""
Recomputes the particle system. This method only applies to an Object of
the type Effect.
"""
def insertShapeKey():
"""
Insert a Shape Key in the current object. It applies to Objects of
the type Mesh, Lattice, or Curve.
"""
def getPose():
"""
Gets the current Pose of the object.
@rtype: Pose object
@return: the current pose object
"""
def evaluatePose(framenumber):
"""
Evaluates the Pose based on its currently bound action at a certain frame.
@type framenumber: Int
@param framenumber: The frame number to evaluate to.
"""
def clearIpo():
"""
Unlinks the ipo from this object.
@return: True if there was an ipo linked or False otherwise.
"""
def clrParent(mode = 0, fast = 0):
"""
Clears parent object.
@type mode: Integer
@type fast: Integer
@param mode: A mode flag. If mode flag is 2, then the object transform will
be kept. Any other value, or no value at all will update the object
transform.
@param fast: If the value is 0, the scene hierarchy will not be updated. Any
other value, or no value at all will update the scene hierarchy.
"""
def getData(name_only=False, mesh=False):
"""
Returns the Datablock object (Mesh, Lamp, Camera, etc.) linked to this
Object. If the keyword parameter B{name_only} is True, only the Datablock
name is returned as a string. It the object is of type Mesh, then the
B{mesh} keyword can also be used; the data return is a Mesh object if
True, otherwise it is an NMesh object (the default).
The B{mesh} keyword is ignored for non-mesh objects.
@type name_only: bool
@param name_only: This is a keyword parameter. If True (or nonzero),
only the name of the data object is returned.
@type mesh: bool
@param mesh: This is a keyword parameter. If True (or nonzero),
a Mesh data object is returned.
@rtype: specific Object type or string
@return: Depends on the type of Datablock linked to the Object. If
B{name_only} is True, it returns a string.
@note: Mesh is faster than NMesh because Mesh is a thin wrapper.
@note: This function is different from L{NMesh.GetRaw} and L{Mesh.Get}
because it keeps a link to the original mesh, which is needed if you are
dealing with Mesh weight groups.
@note: Make sure the object you are getting the data from isn't in
EditMode before calling this function; otherwise you'll get the data
before entering EditMode. See L{Window.EditMode}.
"""
def getParentBoneName():
"""
Returns None, or the 'sub-name' of the parent (eg. Bone name)
@return: string
"""
def getDeltaLocation():
"""
Returns the object's delta location in a list (x, y, z)
@rtype: A vector triple
@return: (x, y, z)
"""
def getDrawMode():
"""
Returns the object draw mode.
@rtype: Integer
@return: a sum of the following:
- 2 - axis
- 4 - texspace
- 8 - drawname
- 16 - drawimage
- 32 - drawwire
- 64 - xray
"""
def getDrawType():
"""
Returns the object draw type
@rtype: Integer
@return: One of the following:
- 1 - Bounding box
- 2 - Wire
- 3 - Solid
- 4 - Shaded
- 5 - Textured
"""
def getEuler(space):
"""
@type space: string
@param space: The desired space for the size:
- localspace: (default) relative to the object's parent;
- worldspace: absolute, taking vertex parents, tracking and
Ipo's into account;
Returns the object's localspace rotation as Euler rotation vector (rotX, rotY, rotZ). Angles are in radians.
@rtype: Py_Euler
@return: A python Euler. Data is wrapped when euler is present.
"""
def getInverseMatrix():
"""
Returns the object's inverse matrix.
@rtype: Py_Matrix
@return: A python matrix 4x4
"""
def getIpo():
"""
Returns the Ipo associated to this object or None if there's no linked ipo.
@rtype: Ipo
@return: the wrapped ipo or None.
"""
def isSelected():
"""
Returns the objects selection state in the current scene as a boolean value True or False.
@rtype: Boolean
@return: Selection state as True or False
"""
def getLocation(space):
"""
@type space: string
@param space: The desired space for the location:
- localspace: (default) relative to the object's parent;
- worldspace: absolute, taking vertex parents, tracking and
Ipo's into account;
Returns the object's location (x, y, z).
@return: (x, y, z)
I{B{Example:}}
The example below works on the default scene. It retrieves all objects in
the scene and prints the name and location of each object::
import Blender
sce = Blender.Scene.GetCurrent()
for ob in sce.objects:
print obj.name
print obj.loc
@note: the worldspace location is the same as ob.matrixWorld[3][0:3]
"""
def getAction():
"""
Returns an action if one is associated with this object (only useful for armature types).
@rtype: Py_Action
@return: a python action.
"""
def getMaterials(what = 0):
"""
Returns a list of materials assigned to the object.
@type what: int
@param what: if nonzero, empty slots will be returned as None's instead
of being ignored (default way). See L{NMesh.NMesh.getMaterials}.
@rtype: list of Material Objects
@return: list of Material Objects assigned to the object.
"""
def getMatrix(space = 'worldspace'):
"""
Returns the object matrix.
@type space: string
@param space: The desired matrix:
- worldspace (default): absolute, taking vertex parents, tracking and
Ipo's into account;
- localspace: relative to the object's parent (returns worldspace
matrix if the object doesn't have a parent);
- old_worldspace: old behavior, prior to Blender 2.34, where eventual
changes made by the script itself were not taken into account until
a redraw happened, either called by the script or upon its exit.
Returns the object matrix.
@rtype: Py_Matrix (WRAPPED DATA)
@return: a python 4x4 matrix object. Data is wrapped for 'worldspace'
"""
def getName():
"""
Returns the name of the object
@return: The name of the object
I{B{Example:}}
The example below works on the default scene. It retrieves all objects in
the scene and prints the name of each object::
import Blender
sce= Blender.Scene.GetCurrent()
for ob in sce.objects:
print ob.getName()
"""
def getParent():
"""
Returns the object's parent object.
@rtype: Object
@return: The parent object of the object. If not available, None will be
returned.
"""
def getSize(space):
"""
@type space: string
@param space: The desired space for the size:
- localspace: (default) relative to the object's parent;
- worldspace: absolute, taking vertex parents, tracking and
Ipo's into account;
Returns the object's size.
@return: (SizeX, SizeY, SizeZ)
@note: the worldspace size will not return negative (flipped) scale values.
"""
def getParentBoneName():
"""
Returns the object's parent object's sub name, or None.
For objects parented to bones, this is the name of the bone.
@rtype: String
@return: The parent object sub-name of the object.
If not available, None will be returned.
"""
def getTimeOffset():
"""
Returns the time offset of the object's animation.
@return: TimeOffset
"""
def getTracked():
"""
Returns the object's tracked object.
@rtype: Object
@return: The tracked object of the object. If not available, None will be
returned.
"""
def getType():
"""
Returns the type of the object in 'Armature', 'Camera', 'Curve', 'Lamp', 'Lattice',
'Mball', 'Mesh', 'Surf', 'Empty', 'Wave' (deprecated) or 'unknown' in exceptional cases.
I{B{Example:}}
The example below works on the default scene. It retrieves all objects in
the scene and updates the location and rotation of the camera. When run,
the camera will rotate 180 degrees and moved to the opposite side of the X
axis. Note that the number 'pi' in the example is an approximation of the
true number 'pi'. A better, less error-prone value of pi is math.pi from the python math module.::
import Blender
sce = Blender.Scene.GetCurrent()
for obj in sce.objects:
if obj.type == 'Camera':
obj.LocY = -obj.LocY
obj.RotZ = 3.141592 - obj.RotZ
Blender.Redraw()
@return: The type of object.
@rtype: String
"""
def insertIpoKey(keytype):
"""
Inserts keytype values in object ipo at curframe.
@type keytype: int
@param keytype: A constant from L{IpoKeyTypes<Object.IpoKeyTypes>}
@return: None
"""
def link(datablock):
"""
Links Object with ObData datablock provided in the argument. The data must match the
Object's type, so you cannot link a Lamp to a Mesh type object.
@type datablock: Blender ObData datablock
@param datablock: A Blender datablock matching the objects type.
"""
def makeParent(objects, noninverse = 0, fast = 0):
"""
Makes the object the parent of the objects provided in the argument which
must be a list of valid Objects.
@type objects: Sequence of Blender Object
@param objects: The children of the parent
@type noninverse: Integer
@param noninverse:
0 - make parent with inverse
1 - make parent without inverse
@type fast: Integer
@param fast:
0 - update scene hierarchy automatically
1 - don't update scene hierarchy (faster). In this case, you must
explicitely update the Scene hierarchy.
@warn: objects must first be linked to a scene before they can become
parents of other objects. Calling this makeParent method for an
unlinked object will result in an error.
"""
def join(objects):
"""
Uses the object as a base for all of the objects in the provided list to join into.
@type objects: Sequence of Blender Object
@param objects: A list of objects matching the object's type.
@note: Objects in the list will not be removed from the scene.
To avoid overlapping data you may want to remove them manually after joining.
@note: Join modifies the base object's data in place so that
other objects are joined into it. No new object or data is created.
@note: Join will only work for object types Mesh, Armature, Curve and Surface;
an excption will be raised if the object is not of these types.
@note: Objects in the list will be ignored if they to not match the base object.
@note: The base object must be in the current scene to be joined.
@note: This function will not work in background mode (no user interface).
@note: An error in the function input will raise a TypeError or AttributeError,
otherwise an error in the data input will raise a RuntimeError.
For situations where you don't have tight control on the data that is being joined,
you should handle the RuntimeError error, letting the user know the data can't be joined.
"""
def makeParentDeform(objects, noninverse = 0, fast = 0):
"""
Makes the object the deformation parent of the objects provided in the argument
which must be a list of valid Objects.
The parent object must be a Curve or Armature.
@type objects: Sequence of Blender Object
@param objects: The children of the parent
@type noninverse: Integer
@param noninverse:
0 - make parent with inverse
1 - make parent without inverse
@type fast: Integer
@param fast:
0 - update scene hierarchy automatically
1 - don't update scene hierarchy (faster). In this case, you must
explicitely update the Scene hierarchy.
@warn: objects must first be linked to a scene before they can become
parents of other objects. Calling this makeParent method for an
unlinked object will result in an error.
@warn: child objects must be of mesh type to deform correctly. Other object
types will fall back to normal parenting silently.
"""
def makeParentVertex(objects, indices, noninverse = 0, fast = 0):
"""
Makes the object the vertex parent of the objects provided in the argument
which must be a list of valid Objects.
The parent object must be a Mesh, Curve or Surface.
@type objects: Sequence of Blender Object
@param objects: The children of the parent
@type indices: Tuple of Integers
@param indices: The indices of the vertices you want to parent to (1 or 3 values)
@type noninverse: Integer
@param noninverse:
0 - make parent with inverse
1 - make parent without inverse
@type fast: Integer
@param fast:
0 - update scene hierarchy automatically
1 - don't update scene hierarchy (faster). In this case, you must
explicitely update the Scene hierarchy.
@warn: objects must first be linked to a scene before they can become
parents of other objects. Calling this makeParent method for an
unlinked object will result in an error.
"""
def makeParentBone(objects, bonename, noninverse = 0, fast = 0):
"""
Makes one of the object's bones the parent of the objects provided in the argument
which must be a list of valid objects. The parent object must be an Armature.
@type objects: Sequence of Blender Object
@param objects: The children of the parent
@type bonename: string
@param bonename: a valid bone name from the armature
@type noninverse: integer
@param noninverse:
0 - make parent with inverse
1 - make parent without inverse
@type fast: integer
@param fast:
0 - update scene hierarchy automatically
1 - don't update scene hierarchy (faster). In this case, you must
explicitly update the Scene hierarchy.
@warn: Objects must first be linked to a scene before they can become
parents of other objects. Calling this method for an
unlinked object will result in an exception.
"""
def setDeltaLocation(delta_location):
"""
Sets the object's delta location which must be a vector triple.
@type delta_location: A vector triple
@param delta_location: A vector triple (x, y, z) specifying the new
location.
"""
def setDrawMode(drawmode):
"""
Sets the object's drawing mode. The drawing mode can be a mix of modes. To
enable these, add up the values.
@type drawmode: Integer
@param drawmode: A sum of the following:
- 2 - axis
- 4 - texspace
- 8 - drawname
- 16 - drawimage
- 32 - drawwire
- 64 - xray
"""
def setDrawType(drawtype):
"""
Sets the object's drawing type.
@type drawtype: Integer
@param drawtype: One of the following:
- 1 - Bounding box
- 2 - Wire
- 3 - Solid
- 4 - Shaded
- 5 - Textured
"""
def setEuler(euler):
"""
Sets the object's localspace rotation according to the specified Euler angles.
@type euler: Py_Euler or a list of floats
@param euler: a python Euler or x,y,z rotations as floats
"""
def setIpo(ipo):
"""
Links an ipo to this object.
@type ipo: Blender Ipo
@param ipo: an object type ipo.
"""
def setLocation(x, y, z):
"""
Sets the object's location relative to the parent object (if any).
@type x: float
@param x: The X coordinate of the new location.
@type y: float
@param y: The Y coordinate of the new location.
@type z: float
@param z: The Z coordinate of the new location.
"""
def setMaterials(materials):
"""
Sets the materials. The argument must be a list 16 items or less. Each
list element is either a Material or None. Also see L{colbits}.
@type materials: Materials list
@param materials: A list of Blender material objects.
@note: Materials are assigned to the object's data by default. Unless
you know the material is applied to the object or are changing the
object's L{colbits}, you need to look at the object data's materials.
"""
def setMatrix(matrix):
"""
Sets the object's matrix and updates its transformation. If the object
has a parent, the matrix transform is relative to the parent.
@type matrix: Py_Matrix 3x3 or 4x4
@param matrix: a 3x3 or 4x4 Python matrix. If a 3x3 matrix is given,
it is extended to a 4x4 matrix.
@Note: This method is "bad": when called it changes the location,
rotation and size attributes of the object (since Blender uses these
values to calculate the object's transformation matrix). Ton is
not happy having a method which "pretends" to do a matrix operation.
In the future, this method may be replaced with other methods which
make it easier for the user to determine the correct loc/rot/size values
for necessary for the object.
"""
def setName(name):
"""
Sets the name of the object. A string longer than 20 characters will be shortened.
@type name: String
@param name: The new name for the object.
"""
def setSize(x, y, z):
"""
Sets the object's size, relative to the parent object (if any), clamped
@type x: float
@param x: The X size multiplier.
@type y: float
@param y: The Y size multiplier.
@type z: float
@param z: The Z size multiplier.
"""
def setTimeOffset(timeOffset):
"""
Sets the time offset of the object's animation.
@type timeOffset: float
@param timeOffset: The new time offset for the object's animation.
"""
def shareFrom(object):
"""
Link data of a specified argument with this object. This works only
if both objects are of the same type.
@type object: Blender Object
@param object: A Blender Object of the same type.
@note: This function is faster than using L{getData()} and setData()
because it skips making a Python object from the object's data.
"""
def select(boolean):
"""
Sets the object's selection state in the current scene.
setting the selection will make this object the active object of this scene.
@type boolean: Integer
@param boolean:
- 0 - unselected
- 1 - selected
"""
def getBoundBox():
"""
Returns the worldspace bounding box of this object. This works for meshes (out of
edit mode) and curves.
@rtype: list of 8 (x,y,z) float coordinate vectors (WRAPPED DATA)
@return: The coordinates of the 8 corners of the bounding box. Data is wrapped when
bounding box is present.
"""
def makeDisplayList():
"""
Updates this object's display list. Blender uses display lists to store
already transformed data (like a mesh with its vertices already modified
by coordinate transformations and armature deformation). If the object
isn't modified, there's no need to recalculate this data. This method is
here for the *few cases* where a script may need it, like when toggling
the "SubSurf" mode for a mesh:
Example::
import Blender
scn = Blender.Scene.GetCurrent()
object = scn.objects.active
object.modifiers.append(Blender.Modifier.Type.SUBSURF)
object.makeDisplayList()
Blender.Window.RedrawAll()
If you try this example without the line to update the display list, the
object will disappear from the screen until you press "SubSurf".
@warn: If after running your script objects disappear from the screen or
are not displayed correctly, try this method function. But if the script
works properly without it, there's no reason to use it.
"""
def getScriptLinks (event):
"""
Get a list with this Object's script links of type 'event'.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this Object. If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this Object.
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
"""
def makeTrack (tracked, fast = 0):
"""
Make this Object track another.
@type tracked: Blender Object
@param tracked: the object to be tracked.
@type fast: int (bool)
@param fast: if zero, the scene hierarchy is updated automatically. If
you set 'fast' to a nonzero value, don't forget to update the scene
yourself (see L{Scene.Scene.update}).
@note: you also need to clear the rotation (L{setEuler}) of this object
if it was not (0,0,0) already.
"""
def clearTrack (mode = 0, fast = 0):
"""
Make this Object not track another anymore.
@type mode: int (bool)
@param mode: if nonzero the matrix transformation used for tracking is kept.
@type fast: int (bool)
@param fast: if zero, the scene hierarchy is updated automatically. If
you set 'fast' to a nonzero value, don't forget to update the scene
yourself (see L{Scene.Scene.update}).
"""
def getAllProperties ():
"""
Return a list of all game properties from this object.
@rtype: PyList
@return: List of Property objects.
"""
def getProperty (name):
"""
Return a game property from this object matching the name argument.
@type name: string
@param name: the name of the property to get.
@rtype: Property object
@return: The first property that matches name.
"""
def addProperty (name_or_property, data, type):
"""
Add or create a game property for an object. If called with only a
property object, the property is assigned to the object. If called
with a property name string and data object, a new property is
created and added to the object.
@type name_or_property: string or Property object
@param name_or_property: the property name, or a property object.
@type data: string, int or float
@param data: Only valid when I{name_or_property} is a string.
Value depends on what is passed in:
- string: string type property
- int: integer type property
- float: float type property
@type type: string (optional)
@param type: Only valid when I{name_or_property} is a string.
Can be the following:
- 'BOOL'
- 'INT'
- 'FLOAT'
- 'TIME'
- 'STRING'
@warn: If a type is not declared string data will
become string type, int data will become int type
and float data will become float type. Override type
to declare bool type, and time type.
@warn: A property object can be added only once to an object;
you must remove the property from an object to add it elsewhere.
"""
def removeProperty (property):
"""
Remove a game property from an object.
@type property: Property object or string
@param property: Property object or property name to be removed.
"""
def removeAllProperties():
"""
Removes all game properties from an object.
"""
def copyAllPropertiesTo (object):
"""
Copies all game properties from one object to another.
@type object: Object object
@param object: Object that will receive the properties.
"""
def getPIStregth():
"""
Get the Object's Particle Interaction Strength.
@rtype: float
"""
def setPIStrength(strength):
"""
Set the Object's Particle Interaction Strength.
Values between -1000.0 to 1000.0
@rtype: None
@type strength: float
@param strength: the Object's Particle Interaction New Strength.
"""
def getPIFalloff():
"""
Get the Object's Particle Interaction falloff.
@rtype: float
"""
def setPIFalloff(falloff):
"""
Set the Object's Particle Interaction falloff.
Values between 0 to 10.0
@rtype: None
@type falloff: float
@param falloff: the Object's Particle Interaction New falloff.
"""
def getPIMaxDist():
"""
Get the Object's Particle Interaction MaxDist.
@rtype: float
"""
def setPIMaxDist(MaxDist):
"""
Set the Object's Particle Interaction MaxDist.
Values between 0 to 1000.0
@rtype: None
@type MaxDist: float
@param MaxDist: the Object's Particle Interaction New MaxDist.
"""
def getPIType():
"""
Get the Object's Particle Interaction Type.
@rtype: int
"""
def setPIType(type):
"""
Set the Object's Particle Interaction type.
Use Module Constants
- NONE
- WIND
- FORCE
- VORTEX
- MAGNET
@rtype: None
@type type: int
@param type: the Object's Particle Interaction Type.
"""
def getPIUseMaxDist():
"""
Get the Object's Particle Interaction if using MaxDist.
@rtype: int
"""
def setPIUseMaxDist(status):
"""
Set the Object's Particle Interaction MaxDist.
0 = Off, 1 = on
@rtype: None
@type status: int
@param status: the new status
"""
def getPIDeflection():
"""
Get the Object's Particle Interaction Deflection Setting.
@rtype: int
"""
def setPIDeflection(status):
"""
Set the Object's Particle Interaction Deflection Setting.
0 = Off, 1 = on
@rtype: None
@type status: int
@param status: the new status
"""
def getPIPermf():
"""
Get the Object's Particle Interaction Permeability.
@rtype: float
"""
def setPIPerm(perm):
"""
Set the Object's Particle Interaction Permeability.
Values between 0 to 10.0
@rtype: None
@type perm: float
@param perm: the Object's Particle Interaction New Permeability.
"""
def getPIRandomDamp():
"""
Get the Object's Particle Interaction RandomDamp.
@rtype: float
"""
def setPIRandomDamp(damp):
"""
Set the Object's Particle Interaction RandomDamp.
Values between 0 to 10.0
@rtype: None
@type damp: float
@param damp: the Object's Particle Interaction New RandomDamp.
"""
def getPISurfaceDamp():
"""
Get the Object's Particle Interaction SurfaceDamp.
@rtype: float
"""
def setPISurfaceDamp(damp):
"""
Set the Object's Particle Interaction SurfaceDamp.
Values between 0 to 10.0
@rtype: None
@type damp: float
@param damp: the Object's Particle Interaction New SurfaceDamp.
"""
def getSBMass():
"""
Get the Object's SoftBody Mass.
@rtype: float
"""
def setSBMass(mass):
"""
Set the Object's SoftBody Mass.
Values between 0 to 50.0
@rtype: None
@type mass: float
@param mass: the Object's SoftBody New mass.
"""
def getSBGravity():
"""
Get the Object's SoftBody Gravity.
@rtype: float
"""
def setSBGravity(grav):
"""
Set the Object's SoftBody Gravity.
Values between 0 to 10.0
@rtype: None
@type grav: float
@param grav: the Object's SoftBody New Gravity.
"""
def getSBFriction():
"""
Get the Object's SoftBody Friction.
@rtype: float
"""
def setSBFriction(frict):
"""
Set the Object's SoftBody Friction.
Values between 0 to 10.0
@rtype: None
@type frict: float
@param frict: the Object's SoftBody New Friction.
"""
def getSBErrorLimit():
"""
Get the Object's SoftBody ErrorLimit.
@rtype: float
"""
def setSBErrorLimit(err):
"""
Set the Object's SoftBody ErrorLimit.
Values between 0 to 1.0
@rtype: None
@type err: float
@param err: the Object's SoftBody New ErrorLimit.
"""
def getSBGoalSpring():
"""
Get the Object's SoftBody GoalSpring.
@rtype: float
"""
def setSBGoalSpring(gs):
"""
Set the Object's SoftBody GoalSpring.
Values between 0 to 0.999
@rtype: None
@type gs: float
@param gs: the Object's SoftBody New GoalSpring.
"""
def getSBGoalFriction():
"""
Get the Object's SoftBody GoalFriction.
@rtype: float
"""
def setSBGoalFriction(gf):
"""
Set the Object's SoftBody GoalFriction.
Values between 0 to 10.0
@rtype: None
@type gf: float
@param gf: the Object's SoftBody New GoalFriction.
"""
def getSBMinGoal():
"""
Get the Object's SoftBody MinGoal.
@rtype: float
"""
def setSBMinGoal(mg):
"""
Set the Object's SoftBody MinGoal.
Values between 0 to 1.0
@rtype: None
@type mg: float
@param mg: the Object's SoftBody New MinGoal.
"""
def getSBMaxGoal():
"""
Get the Object's SoftBody MaxGoal.
@rtype: float
"""
def setSBMaxGoal(mg):
"""
Set the Object's SoftBody MaxGoal.
Values between 0 to 1.0
@rtype: None
@type mg: float
@param mg: the Object's SoftBody New MaxGoal.
"""
def getSBInnerSpring():
"""
Get the Object's SoftBody InnerSpring.
@rtype: float
"""
def setSBInnerSpring(sprr):
"""
Set the Object's SoftBody InnerSpring.
Values between 0 to 0.999
@rtype: None
@type sprr: float
@param sprr: the Object's SoftBody New InnerSpring.
"""
def getSBInnerSpringFriction():
"""
Get the Object's SoftBody InnerSpringFriction.
@rtype: float
"""
def setSBInnerSpringFriction(sprf):
"""
Set the Object's SoftBody InnerSpringFriction.
Values between 0 to 10.0
@rtype: None
@type sprf: float
@param sprf: the Object's SoftBody New InnerSpringFriction.
"""
def getSBDefaultGoal():
"""
Get the Object's SoftBody DefaultGoal.
@rtype: float
"""
def setSBDefaultGoal(goal):
"""
Set the Object's SoftBody DefaultGoal.
Values between 0 to 1.0
@rtype: None
@type goal: float
@param goal: the Object's SoftBody New DefaultGoal.
"""
def isSB():
"""
Returns the Object's SoftBody enabled state.
@rtype: boolean
"""
def getSBPostDef():
"""
get SoftBodies PostDef option
@rtype: int
"""
def setSBPostDef(switch):
"""
Enable / Disable SoftBodies PostDef option
1: on
0: off
@rtype: None
@type switch: int
@param switch: the Object's SoftBody New PostDef Value.
"""
def getSBUseGoal():
"""
get SoftBodies UseGoal option
@rtype: int
"""
def setSBUseGoal(switch):
"""
Enable / Disable SoftBodies UseGoal option
1: on
0: off
@rtype: None
@type switch: int
@param switch: the Object's SoftBody New UseGoal Value.
"""
def getSBUseEdges():
"""
get SoftBodies UseEdges option
@rtype: int
"""
def setSBUseEdges(switch):
"""
Enable / Disable SoftBodies UseEdges option
1: on
0: off
@rtype: None
@type switch: int
@param switch: the Object's SoftBody New UseEdges Value.
"""
def getSBStiffQuads():
"""
get SoftBodies StiffQuads option
@rtype: int
"""
def setSBStiffQuads(switch):
"""
Enable / Disable SoftBodies StiffQuads option
1: on
0: off
@rtype: None
@type switch: int
@param switch: the Object's SoftBody New StiffQuads Value.
"""
class Property:
"""
The Property object
===================
This property gives access to object property data in Blender, used by the game engine.
@ivar name: The property name.
@ivar data: Data for this property. Depends on property type.
@ivar type: The property type.
@warn: Comparisons between properties will only be true when
both the name and data pairs are the same.
"""
def getName ():
"""
Get the name of this property.
@rtype: string
@return: The property name.
"""
def setName (name):
"""
Set the name of this property.
@type name: string
@param name: The new name of the property
"""
def getData():
"""
Get the data for this property.
@rtype: string, int, or float
"""
def setData(data):
"""
Set the data for this property.
@type data: string, int, or float
@param data: The data to set for this property.
@warn: See object.setProperty(). Changing data
which is of a different type then the property is
set to (i.e. setting an int value to a float type'
property) will change the type of the property
automatically.
"""
def getType ():
"""
Get the type for this property.
@rtype: string
"""
import id_generics
Object.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,245 @@
# Blender.Object.Pose module
"""
The Blender.Object.Pose submodule.
Pose
====
This module provides access to B{Pose} objects in Blender. This Pose is the
current object-level (as opposed to armature-data level) transformation.
Example::
import Blender
from Blender import *
scn= Scene.GetCurrent()
# New Armature
arm_data= Armature.New('myArmature')
print arm_data
arm_ob = scn.objects.new(arm_data)
arm_data.makeEditable()
# Add 4 bones
ebones = [Armature.Editbone(), Armature.Editbone(), Armature.Editbone(), Armature.Editbone()]
# Name the editbones
ebones[0].name = 'Bone.001'
ebones[1].name = 'Bone.002'
ebones[2].name = 'Bone.003'
ebones[3].name = 'Bone.004'
# Assign the editbones to the armature
for eb in ebones:
arm_data.bones[eb.name]= eb
# Set the locations of the bones
ebones[0].head= Mathutils.Vector(0,0,0)
ebones[0].tail= Mathutils.Vector(0,0,1)
ebones[1].head= Mathutils.Vector(0,0,1)
ebones[1].tail= Mathutils.Vector(0,0,2)
ebones[2].head= Mathutils.Vector(0,0,2)
ebones[2].tail= Mathutils.Vector(0,0,3)
ebones[3].head= Mathutils.Vector(0,0,3)
ebones[3].tail= Mathutils.Vector(0,0,4)
ebones[1].parent= ebones[0]
ebones[2].parent= ebones[1]
ebones[3].parent= ebones[2]
arm_data.update()
# Done with editing the armature
# Assign the pose animation
pose = arm_ob.getPose()
act = arm_ob.getAction()
if not act: # Add a pose action if we dont have one
act = Armature.NLA.NewAction()
act.setActive(arm_ob)
xbones=arm_ob.data.bones.values()
pbones = pose.bones.values()
print xbones
print pbones
frame = 1
for pbone in pbones: # set bones to no rotation
pbone.quat[:] = 1.000,0.000,0.000,0.0000
pbone.insertKey(arm_ob, frame, Object.Pose.ROT)
# Set a different rotation at frame 25
pbones[0].quat[:] = 1.000,0.1000,0.2000,0.20000
pbones[1].quat[:] = 1.000,0.6000,0.5000,0.40000
pbones[2].quat[:] = 1.000,0.1000,0.3000,0.40000
pbones[3].quat[:] = 1.000,-0.2000,-0.3000,0.30000
frame = 25
for i in xrange(4):
pbones[i].insertKey(arm_ob, frame, Object.Pose.ROT)
pbones[0].quat[:] = 1.000,0.000,0.000,0.0000
pbones[1].quat[:] = 1.000,0.000,0.000,0.0000
pbones[2].quat[:] = 1.000,0.000,0.000,0.0000
pbones[3].quat[:] = 1.000,0.000,0.000,0.0000
frame = 50
for pbone in pbones: # set bones to no rotation
pbone.quat[:] = 1.000,0.000,0.000,0.0000
pbone.insertKey(arm_ob, frame, Object.Pose.ROT)
@var ROT:
@type ROT: Constant
@var LOC:
@type LOC: Constant
@var SIZE:
@type SIZE: Constant
"""
class Pose:
"""
The Pose object
===============
This object gives access to Pose-specific data in Blender.
@ivar bones: A Dictionary of PosePoseBones (PoseDict) that make up this Pose.
@type bones: PoseDict Object
"""
def update():
"""
Save all changes and update the Pose.
@rtype: None
"""
class PoseBonesDict:
"""
The PoseBonesDict object
========================
This object gives dictionary like access to the PoseBones in a Pose.
It is internal to blender but is called as 'Pose.bones'
"""
def items():
"""
Return the key, value pairs in this dictionary
@rtype: string, PosePoseBone
@return: All strings, and PosePoseBones in the Pose (in that order)
"""
def keys():
"""
Return the keys in this dictionary
@rtype: string
@return: All strings representing the PosePoseBone names
"""
def values():
"""
Return the values in this dictionary
@rtype: BPy_PoseBone
@return: All PosePoseBones in this dictionary
"""
class PoseBone:
"""
The PoseBone object
===================
This object gives access to PoseBone-specific data in Blender.
@ivar name: The name of this PoseBone.
@type name: String
@ivar loc: The change in location for this PoseBone. this is the equivilent of bone.getLoc() in the old 2.3x python api.
@type loc: Vector object
@ivar size: The change in size for this PoseBone (no change is 1,1,1)
@type size: Vector object
@ivar quat: The change in rotation for this PoseBone.
@type quat: Quaternion object
@ivar head: The final head location for this PoseBone. (not settable)
@type head: Vector object
@ivar tail: The final tail location for this PoseBone. (not settable)
@type tail: Vector object
@ivar sel: The selection state of this bone
@type sel: Boolean
@ivar parent: The parent of this posebone (not settable)
@type parent: posebone or None
@ivar displayObject: The object to display in place of the bone. (custom bones)
@type displayObject: Object or None
@ivar localMatrix: The matrix combination of rot/size/loc.
@type localMatrix: Matrix object
@ivar poseMatrix: The total transformation of this PoseBone including constraints.
This matrix is in armature space, for the current worldspace location of this pose bone, multiply
it with its objects worldspace matrix.
eg. pose_bone.poseMatrix * object.matrixWorld
Setting the poseMatrix only sets the loc/size/rot, before constraints are applied (similar to actions).
After setting pose matrix, run pose.update() to re-evaluate the pose and see the changes in the 3d view.
@type poseMatrix: Matrix object
@type constraints: BPy_ConstraintSeq
@ivar constraints: a sequence of constraints for the object
@type limitmin: 3-item sequence
@ivar limitmin: The x,y,z minimum limits on rotation when part of an IK
@type limitmax: 3-item sequence
@ivar limitmax: The x,y,z maximum limits on rotation when part of an IK
@type hasIK: bool
@ivar hasIK: True if this pose bone is a part of an IK (readonly), when False, other IK related values have no affect.
@type stretch: float
@ivar stretch: The amount to stretch to the ik target when part of an IK [0.0 - 1.0]
@type stiffX: float
@ivar stiffX: The x stiffness when part of an IK [0.0 - 0.990]
@type stiffY: float
@ivar stiffY: The x stiffness when part of an IK [0.0 - 0.990]
@type stiffZ: float
@ivar stiffZ: The x stiffness when part of an IK [0.0 - 0.990]
@type limitX: bool
@ivar limitX: Limit rotation over X axis when part of an IK.
@type limitY: bool
@ivar limitY: Limit rotation over Y axis when part of an IK.
@type limitZ: bool
@ivar limitZ: Limit rotation over Z axis when part of an IK.
@type lockXRot: bool
@ivar lockXRot: Disable X DoF when part of an IK.
@type lockYRot: bool
@ivar lockYRot: Disable Y DoF when part of an IK.
@type lockZRot: bool
@ivar lockZRot: Disable Z DoF when part of an IK.
@ivar layerMask: Layer bitmask
Example::
# set bone to layers 14 and 16
bone.layerMask = (1<<13) + (1<<15)
@type layerMask: Int
"""
def insertKey(parentObject, frameNumber, type = "[Pose.LOC, Pose.ROT, Pose.SIZE]", fast = False):
"""
Insert a pose key for this PoseBone at a frame.
@type parentObject: Object object
@param parentObject: The object the pose came from.
@type frameNumber: integer
@param frameNumber: The frame number to insert the pose key on.
@type type: Constant object
@param type: Optional argumentm.
Can be any combination of 3 Module constants:
- Pose.LOC
- Pose.ROT (This adds keyframes to the quat ipo, since quaternions are used for pose bone rotation)
- Pose.SIZE
If this argument is omitted all keys will be added.
@type fast: Bool
@param fast: If enabled, the IPOs will not be recalculated, speeds up adding many keyframes at once.
@rtype: None
"""

View File

@@ -0,0 +1,351 @@
# Blender.Scene.Radio module and the Radiosity PyType object
"""
The Blender.Scene.Radio submodule.
Radio
=====
This module gives access to B{Scene Radiosity Contexts} in Blender.
Example::
import Blender
from Blender import Scene
# Only the current scene has a radiosity context.
# Naturally, any scene can be made the current one
# with scene.makeCurrent()
scn = Scene.GetCurrent()
# this is the only way to access the radiosity object:
radio = scn.getRadiosityContext()
radio.setDrawType('Gouraud')
radio.setMode('ShowLimits', 'Z')
radio.collectMeshes() # prepare patches
radio.go() # calculate radiosity
Blender.Redraw(-1)
@type Modes: readonly dictionary
@var Modes:
- ShowLimits
- Z
@type DrawTypes: readonly dictionary
@var DrawTypes:
- Wire
- Solid
- Gouraud
"""
class Radio:
"""
The Radiosity object
====================
This object wraps the current Scene's radiosity context in Blender.
"""
def go():
"""
Start the radiosity simulation. It is necessary to call L{collectMeshes}
first.
"""
def collectMeshes():
"""
Convert B{selected} visible meshes to patches for radiosity calculation.
@note: L{Object.Object.select} can be used to (un)select objects via
bpython.
"""
def freeData():
"""
Release all memory used by radiosity.
"""
def addMesh():
"""
Add the new mesh created by the radiosity simulation (see L{go}) to
Blender. The radiosity results are stored in this mesh's vertex colors.
@note: see L{replaceMeshes} for a destructive alternative.
"""
def replaceMeshes():
"""
Replace the original input meshes with the B{one} calculated by the
radiosity simulation. The radiosity results are stored in this mesh's
vertex colors.
@note: see L{addMesh} for a non-destructive alternative.
"""
def limitSubdivide():
"""
Subdivide patches (optional, it may improve results).
"""
def filterFaces():
"""
Force an extra smoothing. This method can be called only after the
simulation has been calculated (L{go}).
"""
def filterElems():
"""
Filter elements to remove aliasing artifacts. This method can be called
only after the simulation has been calculated (L{go}).
"""
def subdividePatches():
"""
Pre-subdivision: detect high-energy patches and subdivide them
(optional, it may improve results).
"""
def subdivideElems():
"""
Pre-subdivision: detect high-energy elements (nodes) and subdivide them
(optional, it may improve results).
"""
def removeDoubles():
"""
Join elements (nodes) which differ less than the defined element limit.
This method can be called only after the simulation has been calculated
(L{go}).
"""
def getHemiRes():
"""
Get hemicube size.
@rtype: int
@return: the current hemicube size.
"""
def setHemiRes(ival):
"""
Set hemicube size. The range is [100, 1000].
@type ival: int
@param ival: the new size.
"""
def getMaxIter():
"""
Get maximum number of radiosity rounds.
@rtype: int
@return: the current maxiter value.
"""
def setMaxIter(ival):
"""
Set maximum number of radiosity rounds. The range is [0, 10000].
@type ival: int
@param ival: the maxiter new value.
"""
def getSubShPatch():
"""
Get maximum number of times the environment is tested to detect patches.
@rtype: int
@return: the current value.
"""
def setSubShPatch(ival):
"""
Set the maximum number of times the environment is tested to detect
patches. The range is [0, 10].
@type ival: int
@param ival: the new value.
"""
def getSubShElem():
"""
Get the number of times the environment is tested to detect elements.
@rtype: int
@return: the current value.
"""
def setSubShElem(ival):
"""
Set number of times the environment is tested to detect elements. The
range is [0, 10].
@type ival: int
@param ival: the new value.
"""
def getElemLimit():
"""
Get the range for removing doubles.
@rtype: int
@return: the current value.
"""
def setElemLimit(ival):
"""
Set the range for removing doubles. The range is [0, 50].
@type ival: int
@param ival: the new value.
"""
def getMaxSubdivSh():
"""
Get the maximum number of initial shoot patches evaluated.
@rtype: int
@return: the current value.
"""
def setMaxSubdivSh(ival):
"""
Set the maximum number of initial shoot patches evaluated. The range is
[1, 250].
@type ival: int
@param ival: the new value.
"""
def getPatchMax():
"""
Get the maximum size of a patch.
@rtype: int
@return: the current value.
"""
def setPatchMax(ival):
"""
Set the maximum size of a patch. The range is [10, 1000].
@type ival: int
@param ival: the new value.
"""
def getPatchMin():
"""
Get the minimum size of a patch.
@rtype: int
@return: the current value.
"""
def setPatchMin(ival):
"""
Set the minimum size of a patch. The range is [10, 1000].
@type ival: int
@param ival: the new value.
"""
def getElemMax():
"""
Get the maximum size of an element.
@rtype: int
@return: the current value.
"""
def setElemMax(ival):
"""
Set the maximum size of an element. The range is [1, 100].
@type ival: int
@param ival: the new value.
"""
def getElemMin():
"""
Get the minimum size of an element. The range is [1, 100].
@rtype: int
@return: the current value.
"""
def setElemMin(ival):
"""
Set the minimum size of an element. The range is [1, 100].
@type ival: int
@param ival: the new value.
"""
def getMaxElems():
"""
Get the maximum number of elements.
@rtype: int
@return: the current value.
"""
def setMaxElems(ival):
"""
Set the maximum number of elements. The range is [1, 250000].
@type ival: int
@param ival: the new value.
"""
def getConvergence():
"""
Get lower thresholdo of unshot energy.
@rtype: float
@return: the current value.
"""
def setConvergence(fval):
"""
Set lower threshold of unshot energy. The range is [0.0, 1.0].
@type fval: float
@param fval: the new value.
"""
def getMult():
"""
Get the energy value multiplier.
@rtype: float
@return: the current value.
"""
def setMult (fval):
"""
Set the energy value multiplier. The range is [0.001, 250.0].
@type fval: float
@param fval: the new value.
"""
def getGamma():
"""
Get change in the contrast of energy values.
@rtype: float
@return: the current value.
"""
def setGamma (fval):
"""
Set change in the contrast of energy values. The range is [0.2, 10.0].
@type fval: float
@param fval: the new value.
"""
def getDrawType():
"""
Get the draw type: Wire, Solid or Gouraud as an int value, see L{DrawTypes}.
@rtype: int
@return: the current draw type.
"""
def setDrawType (dt):
"""
Set the draw type.
@type dt: string or int
@param dt: either 'Wire', 'Solid' or 'Gouraud' or the equivalent entry in
the L{DrawTypes} dictionary.
"""
def getMode():
"""
Get mode as an int (or'ed bitflags), see L{Modes} dictionary.
@rtype: int
@return: the current value.
"""
def setMode (mode1 = None, mode2 = None):
"""
Set mode flags as strings: 'ShowLimits' and 'Z'. To set one give it as
only argument. Strings not passed in are unset, so setMode() unsets
both.
@type mode1: string
@param mode1: optional mode string.
@type mode2: string
@param mode2: optional mode string.
"""

View File

@@ -0,0 +1,122 @@
# Blender.Registry module
"""
The Blender.Registry submodule.
B{New}: L{GetKey} and L{SetKey} have been updated to save and load scripts
*configuration data* to files.
Registry
========
This module provides a way to create, retrieve and edit B{persistent data} in
Blender.
When a script is executed it has its own private global dictionary,
which is deleted when the script exits. This is done to avoid problems with
name clashes and garbage collecting. But because of this, the data created by
a script isn't kept after it leaves: the data is not persistent. The Registry
module was created to give programmers a way around this limitation.
Possible uses:
- saving arbitrary data from a script that itself or another one will need
to access later.
- saving configuration data for a script: users can view and edit this data
using the "Scripts Configuration Editor" script.
- saving the current state of a script's GUI (its button values) to restore it
when the script is executed again.
Example::
import Blender
from Blender import Registry
# this function updates the Registry when we need to:
def update_Registry():
d = {}
d['myvar1'] = myvar1
d['myvar2'] = myvar2
d['mystr'] = mystr
# cache = True: data is also saved to a file
Blender.Registry.SetKey('MyScript', d, True)
# first declare global variables that should go to the Registry:
myvar1 = 0
myvar2 = 3.2
mystr = "hello"
# then check if they are already there (saved on a
# previous execution of this script):
rdict = Registry.GetKey('MyScript', True) # True to check on disk also
if rdict: # if found, get the values saved there
try:
myvar1 = rdict['myvar1']
myvar2 = rdict['myvar2']
mystr = rdict['mystr']
except: update_Registry() # if data isn't valid rewrite it
# ...
# here goes the main part of the script ...
# ...
# if at some point the data is changed, we update the Registry:
update_Registry()
@note: In Python terms, the Registry holds a dictionary of dictionaries.
Technically any Python or BPython object can be stored: there are no
restrictions, but ...
@note: We have a few recommendations:
Data saved to the Registry is kept in memory, so if you decide to store large
amounts your script users should be clearly informed about it --
always keep in mind that you have no idea about their resources and the
applications they are running at a given time (unless you are the only
user), so let them decide.
There are restrictions to the data that gets automatically saved to disk by
L{SetKey}(keyname, dict, True): this feature is only meant for simple data
(bools, ints, floats, strings and dictionaries or sequences of these types).
For more demanding needs, it's of course trivial to save data to another
file or to a L{Blender Text<Text>}.
"""
def Keys ():
"""
Get all keys currently in the Registry's dictionary.
"""
def GetKey (key, cached = False):
"""
Get key 'key' from the Registry.
@type key: string
@param key: a key from the Registry dictionary.
@type cached: bool
@param cached: if True and the requested key isn't already loaded in the
Registry, it will also be searched on the user or default scripts config
data dir (config subdir in L{Blender.Get}('datadir')).
@return: the dictionary called 'key'.
"""
def SetKey (key, dict, cache = False):
"""
Store a new entry in the Registry.
@type key: string
@param key: the name of the new entry, tipically your script's name.
@type dict: dictionary
@param dict: a dict with all data you want to save in the Registry.
@type cache: bool
@param cache: if True the given key data will also be saved as a file
in the config subdir of the scripts user or default data dir (see
L{Blender.Get}).
@warn: as stated in the notes above, there are restrictions to what can
be automatically stored in config files.
"""
def RemoveKey (key):
"""
Remove the dictionary with key 'key' from the Registry.
@type key: string
@param key: the name of an existing Registry key.
"""

View File

@@ -0,0 +1,1192 @@
# Blender.Scene.Render module and the RenderData PyType object
"""
The Blender.Scene.Render submodule.
Scene.Render
============
This module provides access to B{Scene Rendering Contexts} in Blender.
Example::
import Blender
from Blender import *
from Blender.Scene import Render
scn = Scene.GetCurrent()
context = scn.getRenderingContext()
Render.EnableDispWin()
context.extensions = True
context.renderPath = "//myRenderdir/"
context.sizePreset(Render.PC)
context.imageType = Render.AVIRAW
context.sFrame = 2
context.eFrame = 10
context.renderAnim()
context.imageType = Render.TARGA
context.fps = 15
context.sFrame = 15
context.eFrame = 22
context.renderAnim()
Render.CloseRenderWindow()
print context.fps
print context.cFrame
@type Modes: readonly dictionary
@var Modes: Constant dict used for with L{RenderData.mode} bitfield attribute.
Values can be ORed together. Individual bits can also be set/cleared with
boolean attributes.
- OSA: Oversampling (anti-aliasing) enabled
- SHADOW: Shadow calculation enabled
- GAMMA: Gamma correction enabled
- ENVMAP: Environment map rendering enabled
- TOONSHADING: Toon edge shading enabled
- FIELDRENDER: Field rendering enabled
- FIELDTIME: Time difference in field calculations I{disabled}
- RADIOSITY: Radiosity rendering enabled
- BORDER_RENDER: Small cut-out rendering enabled
- PANORAMA: Panorama rendering enabled
- CROP: Crop image during border renders
- ODDFIELD: Odd field first rendering enabled
- MBLUR: Motion blur enabled
- UNIFIED: Unified Renderer enabled
- RAYTRACING: Ray tracing enabled
- THREADS: Render in two threads enabled (Deprecated, use L{RenderData.threads})
@type SceModes: readonly dictionary
@var SceModes: Constant dict used for with L{RenderData.sceneMode} bitfield attribute.
Values can be ORed together. Individual bits can also be set/cleared with
boolean attributes.
- SEQUENCER: Enables sequencer output rendering.
- EXTENSION: Adds extensions to the output when rendering animations.
- SAVE_BUFFERS: Save render tiles to disk to save memory.
- FREE_IMAGES: Free images used by textures after each render.
@type FramingModes: readonly dictionary
@var FramingModes: Constant dict used for with L{RenderData.gameFrame}
attribute. One of the following modes can be active:
- BARS: Show the entire viewport in the display window, using bar
horizontally or vertically.
- EXTEND: Show the entire viewport in the display window, viewing more
horizontally or vertically
- SCALE: Stretch or squeeze the viewport to fill the display window.
@var INTERNAL: The internal rendering engine. Use with setRenderer()
@var YAFRAY: Yafray rendering engine. Use with setRenderer()
@var AVIRAW: Output format. Use with renderdata.imageType / setImageType()
@var AVIJPEG: Output format. Use with renderdata.imageType / setImageType()
@var AVICODEC: Output format. Use with renderdata.imageType / setImageType()
@var QUICKTIME: Output format. Use with renderdata.imageType / setImageType()
@var TARGA: Output format. Use with renderdata.imageType / setImageType()
@var RAWTGA: Output format. Use with renderdata.imageType / setImageType()
@var HDR: Output format. Use with renderdata.imageType / setImageType()
@var PNG: Output format. Use with renderdata.imageType / setImageType()
@var BMP: Output format. Use with renderdata.imageType / setImageType()
@var JPEG: Output format. Use with renderdata.imageType / setImageType()
@var HAMX: Output format. Use with renderdata.imageType / setImageType()
@var IRIS: Output format. Use with renderdata.imageType / setImageType()
@var IRISZ: Output format. Use with renderdata.imageType / setImageType()
@var FTYPE: Output format. Use with renderdata.imageType / setImageType()
@var OPENEXR: Output format. Use with renderdata.imageType / setImageType()
@var TIFF: Output format. Use with renderdata.imageType / setImageType()
@var FFMPEG: Output format. Use with renderdata.imageType / setImageType()
@var CINEON: Output format. Use with renderdata.imageType / setImageType()
@var DPX: Output format. Use with renderdata.imageType / setImageType()
@var PAL: Output format. Use with renderdata.sizePreset()
@var NTSC: Output format. Use with renderdata.sizePreset()
@var DEFAULT: Output format. Use with renderdata.sizePreset()
@var PREVIEW: Output format. Use with renderdata.sizePreset()
@var PC: Output format. Use with renderdata.sizePreset()
@var PAL169: Output format. Use with renderdata.sizePreset()
@var B_PR_FULL: Output format. Use with renderdata.sizePreset()
@var NONE: Yafray GI Quality / Method. Use with renderdata.setYafrayGIQuality()
@var LOW: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var MEDIUM: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var HIGH: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var HIGHER: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var BEST: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var USEAOSETTINGS: Yafray GI Quality. Use with renderdata.setYafrayGIQuality()
@var SKYDOME: Yafray GI Method. Use with renderdata.setYafrayGIMethod()
@var GIFULL: Yafray GI Method. Use with renderdata.setYafrayGIMethod()
"""
def CloseRenderWindow():
"""
Closes the rendering window.
"""
def EnableDispView():
"""
Render in the 3d View area. B{Note} this method is deprecated;
use the l{displayMode} attribute instead.
"""
def EnableDispWin():
"""
Render in Render window.
B{Note} this method is deprecated; use the l{displayMode} attribute instead.
"""
def SetRenderWinPos(locationList):
"""
Set the position of the Render window on the screen.
Possible values are:
- S = south
- N = north
- W = west
- E = east
- C = center
- ne = northeast
- nw = northwest
- se = southeast
- sw = southwest
@type locationList: PyList of strings
@param locationList: a list of strings that together define
the location of the Render window on the screen.
"""
def EnableEdgeShift():
"""
Globally with the unified renderer enabled the outlines of the render
are shifted a bit.
"""
def EnableEdgeAll():
"""
Globally consider transparent faces for edge-rendering with the unified renderer.
"""
class RenderData:
"""
The RenderData object
=====================
This object gives access to Scene rendering contexts in Blender.
@ivar unified: Unified Renderer enabled.
Also see B{UNIFIED} in L{Modes} constant dict.
@type unified: boolean
@ivar renderwinSize: Size of the rendering window. Valid values are 25, 50,
75, or 100.
@type renderwinSize: int
@ivar xParts: Number of horizontal parts for image render.
Values are clamped to the range [2,512].
@type xParts: int
@ivar fieldRendering: Field rendering enabled.
Also see B{FIELDRENDER} in L{Modes} constant dict.
@type fieldRendering: boolean
@ivar gammaCorrection: Gamma correction enabled.
Also see B{GAMMA} in L{Modes} constant dict.
@type gammaCorrection: boolean
@ivar eFrame: Ending frame for rendering.
Values are clamped to the range [1,MAXFRAME].
@type eFrame: int
@ivar radiosityRender: Radiosity rendering enabled.
@type radiosityRender: boolean
@ivar sizeX: Image width (in pixels).
Values are clamped to the range [4,10000].
@type sizeX: int
@ivar shadow: Shadow calculation enabled.
Also see B{SHADOW} in L{Modes} constant dict.
@type shadow: boolean
@ivar aspectX: Horizontal aspect ratio.
Values are clamped to the range [1,200].
@type aspectX: int
@ivar mode: Mode bitfield. See L{Modes} constant dict for values.
@type mode: bitfield
@ivar fieldTimeDisable: Time difference in field calculations I{disabled}.
@type fieldTimeDisable: int
@ivar cFrame: The current frame for rendering.
Values are clamped to the range [1,MAXFRAME].
@type cFrame: int
@ivar crop: Crop image during border renders.
Also see B{CROP} in L{Modes} constant dict.
@type crop: boolean
@ivar sFrame: Starting frame for rendering.
Values are clamped to the range [1,MAXFRAME].
@type sFrame: int
@ivar backbuf: Backbuffer image enabled.
@type backbuf: boolean
@ivar OSALevel: Oversampling (anti-aliasing) level. Valid values are
5, 8, 11, or 16.
@type OSALevel: int
@ivar displayMode: Render output in separate window or 3D view.
Valid values are 0 (display in image editor view), 1 (display in render
window), or 2 (display full screen).
@type displayMode: int
@ivar threads: Number of threads to render, clamed [1-8]
@type threads: int
@ivar backbufPath: Path to a background image (setting loads image).
@type backbufPath: string
@ivar toonShading: Toon edge shading enabled.
Also see B{TOONSHADING} in L{Modes} constant dict.
@type toonShading: boolean
@ivar sceneMode: Scene mode bitfield. See L{SceModes} constant dict for
values.
@type sceneMode: bitfield
@ivar gameFrameColor: RGB color triplet for bars.
Values are clamped in the range [0.0,1.0].
@type gameFrameColor: list of RGB 3 floats
@ivar sizeY: Image height (in pixels).
Values are clamped to the range [4,10000].
@type sizeY: int
@ivar renderer: Rendering engine choice.
Valid values are 0 (internal) or 1 (Yafray).
@type renderer: int
@ivar sequencer: Enables sequencer output rendering.
Also see B{SEQUENCER} in L{SceModes} constant dict.
@type sequencer: boolean
@ivar extensions: Add extensions to output (when rendering animations).
Also see B{EXTENSION} in L{SceModes} constant dict.
@type extensions: boolean
@ivar compositor: 'Do Compositor' enabled.
@type compositor: boolean
@ivar freeImages: 'Do Compositor' enabled.
@type freeImages: boolean
@ivar singleLayer: Only render the active layer.
@type singleLayer: boolean
@ivar saveBuffers: Save render buffers to disk while rendering, saves memory.
@type saveBuffers: boolean
@ivar compositeFree: Free nodes that are not used while composite.
@type compositeFree: boolean
@ivar panorama: Panorama rendering enabled.
Also see B{PANORAMA} in L{Modes} constant dict.
@type panorama: boolean
@ivar rayTracing: Ray tracing enabled.
Also see B{RAYTRACING} in L{Modes} constant dict.
@type rayTracing: boolean
@ivar renderPath: The path to output the rendered images.
@type renderPath: string
@ivar gameFrame: Game framing type. See L{FramingModes} constant dict.
@type gameFrame: int
@ivar aspectY: Vertical aspect ratio.
Values are clamped to the range [1,200].
@type aspectY: int
@ivar imageType: File format for saving images. See the module's constants
for values.
@type imageType: int
@ivar ftypePath: The path to Ftype file.
@type ftypePath: string
@ivar border: The border for border rendering. The format is
[xmin,ymin,xmax,ymax]. Values are clamped to [0.0,1.0].
@type border: list of 4 floats.
@ivar edgeColor: RGB color triplet for edges in Toon shading (unified
renderer).
Values are clamped in the range [0.0,1.0].
@type edgeColor: list of 3 RGB floats
@ivar yParts: Number of vertical parts for image render.
Values are clamped to the range [2,512].
@type yParts: int
@ivar imagePlanes: Image depth in bits. Valid values are 8, 24, or 32.
@type imagePlanes: int
@ivar borderRender: Small cut-out rendering enabled.
Also see B{BORDER_RENDER} in L{Modes} constant dict.
@type borderRender: boolean
@ivar oversampling: Oversampling (anti-aliasing) enabled.
Also see B{OSA} in L{Modes} constant dict.
@type oversampling: boolean
@ivar fps: Frames per second.
Values are clamped to the range [1,120].
@ivar fps_base: Frames per second base: used to generate fractional frames
per second values. For example, setting fps to 30 and fps_base to 1.001
will approximate the NTSC frame rate of 29.97 fps.
Values are clamped to the range [1,120].
@type fps_base: float
@ivar timeCode: Get the current frame in HH:MM:SS:FF format. Read-only.
@type timeCode: string
@ivar environmentMap: Environment map rendering enabled.
Also see B{ENVMAP} in L{Modes} constant dict.
@type environmentMap: boolean
@ivar motionBlur: Motion blur enabled.
Also see B{MBLUR} in L{Modes} constant dict.
@type motionBlur: boolean
@ivar oddFieldFirst: Odd field first rendering enabled.
Also see B{ODDFIELD} in L{Modes} constant dict.
@type oddFieldFirst: boolean
@ivar alphaMode: Setting for sky/background. Valid values are 0 (fill
background with sky), 1 (multiply alpha in advance), or 2 (alpha and color
values remain unchanged).
@type alphaMode: int
@ivar gaussFilter: Gauss filter size.
Values are clamped to the range [0.5,1.5].
@type gaussFilter: float
@ivar mblurFactor: Motion blur factor.
Values are clamped to the range [0.01,5.0].
@type mblurFactor: float
@ivar mapOld: Number of frames the Map Old will last
Values are clamped to the range [1,900].
@type mapOld: int
@ivar mapNew: New mapping value (in frames).
Values are clamped to the range [1,900].
@type mapNew: int
@ivar set: The scene linked as a set to this scene. Values are an existing
scene or None (setting to None clears the set). The scene argument cannot
cause a circular link.
@type set: BPy_Scene or None
@ivar yafrayGIMethod: Global Illumination method.
Valid values are NONE (0), SKYDOME (1) or FULL (2).
@type yafrayGIMethod: int {NONE (0), SKYDOME (1), GIFULL (2)}
@ivar yafrayGIQuality: Global Illumination quality.
@type yafrayGIQuality: int {NONE (0), LOW (1), MEDIUM (2), HIGH (3), HIGHER (4), BEST (5), USEAOSETTINGS (6)}
@ivar yafrayExportToXML: If true export to an xml file and call yafray instead of plugin.
@type yafrayExportToXML: boolean
@ivar yafrayAutoAntiAliasing: Automatic anti-aliasing enabled/disabled.
@type yafrayAutoAntiAliasing: boolean
@ivar yafrayClampRGB: Clamp RGB enabled/disabled.
@type yafrayClampRGB: boolean
@ivar yafrayAntiAliasingPasses: Number of anti-aliasing passes (0 is no Anti-Aliasing).
@type yafrayAntiAliasingPasses: int [0, 64]
@ivar yafrayAntiAliasingSamples: Number of samples per pass.
@type yafrayAntiAliasingSamples: int [0, 2048]
@ivar yafrayAntiAliasingPixelSize: Anti-aliasing pixel filter size.
@type yafrayAntiAliasingPixelSize: float [1.0, 2.0]
@ivar yafrayAntiAliasingThreshold: Anti-aliasing threshold.
@type yafrayAntiAliasingThreshold: float [0.05, 1.0]
@ivar yafrayNumberOfProcessors: Number of processors to use.
@type yafrayNumberOfProcessors: int [1, 8]
@ivar yafrayGICache: Cache occlusion/irradiance samples (faster).
@type yafrayGICache: boolean
@ivar yafrayGICacheBumpNormals: Enable/disable bumpnormals for cache.
@type yafrayGICacheBumpNormals: boolean
@ivar yafrayGICacheShadowQuality: Shadow quality, keep it under 0.95 :-).
@type yafrayGICacheShadowQuality: float [0.01, 1.0]
@ivar yafrayGICachePixelsPerSample: Maximum number of pixels without samples, the lower the better and slower.
@type yafrayGICachePixelsPerSample: int [1, 50]
@ivar yafrayGICacheRefinement: Threshold to refine shadows EXPERIMENTAL. 1 = no refinement.
@type yafrayGICacheRefinement: float [0.001, 1.0]
@ivar yafrayGIPhotons: Enable/disable use of global photons to help in GI.
@type yafrayGIPhotons: boolean
@ivar yafrayGITunePhotons: If true the photonmap is shown directly in the render for tuning.
@type yafrayGITunePhotons: boolean
"""
def currentFrame(frame = None):
"""
Get/set the current frame.
@type frame: int (optional)
@param frame: must be between 1 - 30000
@rtype: int (if prototype is empty)
@return: Current frame for the scene.
"""
def render():
"""
Render the scene.
"""
def renderAnim():
"""
Render a series of frames to an output directory.
"""
def saveRenderedImage(filename, zbuffer=0):
"""
Saves the image rendered using RenderData.render() to the filename and path
given in the variable 'filename'.
Make sure the filename you provide makes a valid path when added to the "render path"
(setRenderPath/getRenderPath) to make up the absolute path.
If you want to render to a new absolute path just set the renderpath to an
empty string and use the absolute path as the filename.
@param filename: The path+filename for the rendered image.
@type zbuffer: int
@param zbuffer: Whether or not to render the zbuffer along with the image.
@type filename: string
@since: 2.40
@requires: You must have an image currently rendered before calling this method
"""
def play():
"""
play animation of rendered images/avi (searches Pics: field).
"""
def getTimeCode():
"""
Get the current frame as a string in HH:MM:SS:FF format
@rtype: string
@return: current frame as a string in HH:MM:SS:FF format
"""
def setRenderPath(path):
"""
Set the path to where the renderer will write to.
@type path: string
@param path: A directory for that the renderer searches for
both playback and output from the renderAnim function.
"""
def getRenderPath():
"""
Get the path to where the renderer will write to.
@rtype: string
@return: Returns the directory that is used to playback and store rendered
sequences.
"""
def setBackbufPath(path):
"""
Set the path to a background image and load it.
@type path: string
@param path: The path to a background image for loading.
"""
def getBackbufPath():
"""
Get the path to the background image.
@rtype: string
@return: The path to a background image.
"""
def enableBackbuf(toggle):
"""
Enable/disable the backbuf image.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setFtypePath(path):
"""
Set the path to Ftype file.
@type path: string
@param path: Path to Ftype Image type.
"""
def getFtypePath():
"""
Get the path to the Ftype file
@rtype: string
@return: Path to FtypeImage type.
"""
def enableExtensions(toggle):
"""
Enable/disable windows extensions for output files.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableSequencer(toggle):
"""
Enable/disable Do Sequence.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableRenderDaemon(toggle):
"""
Enable/disable Scene daemon.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableToonShading(toggle):
"""
Enable/disable Edge rendering.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def edgeIntensity(intensity = None):
"""
Get/set edge intensity for toon shading.
@type intensity: int (optional)
@param intensity: must be between 0 - 255
@rtype: int (if prototype is empty)
@return: Current edge intensity for the scene.
"""
def setEdgeColor(red, green, blue):
"""
Set the edge color for toon shading.
@type red: float
@param red: must be between 0 - 1.0
@type green: float
@param green: must be between 0 - 1.0
@type blue: float
@param blue: must be between 0 - 1.0
"""
def getEdgeColor():
"""
Get the edge color for toon shading.
@rtype: string
@return: A string representing the edge color.
"""
def edgeAntiShift(intensity = None):
"""
With the unified renderer, reduce intensity on boundaries.
@type intensity: int (optional)
@param intensity: must be between 0 - 255
@rtype: int (if prototype is empty)
@return: Current edge antishift for the scene.
"""
def enableOversampling(toggle):
"""
Enable/disable oversampling (anti-aliasing).
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setOversamplingLevel(level):
"""
Set the level of over-sampling (anti-aliasing).
@type level: int
@param level: can be either 5, 8, 11, or 16
"""
def enableMotionBlur(toggle):
"""
Enable/disable MBlur.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def motionBlurLevel(level = None):
"""
Get/set the length of shutter time for motion blur.
@type level: float (optional)
@param level: must be between 0.01 - 5.0
@rtype: float (if prototype is empty)
@return: Current MBlur for the scene.
"""
def partsX(parts = None):
"""
Get/set the number of parts to divide the render in the X direction.
@type parts: int (optional)
@param parts: must be between 1 - 64
@rtype: int (if prototype is empty)
@return: Current number of parts in the X for the scene.
"""
def partsY(parts = None):
"""
Get/set the number of parts to divide the render in the Y direction.
@type parts: int (optional)
@param parts: must be between 1 - 64
@rtype: int (if prototype is empty)
@return: Current number of parts in the Y for the scene.
"""
def enableSky():
"""
Enable render background with sky.
"""
def enablePremultiply():
"""
Enable premultiply alpha.
"""
def enableKey():
"""
Enable alpha and color values remain unchanged.
"""
def enableShadow(toggle):
"""
Enable/disable shadow calculation.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableEnvironmentMap(toggle):
"""
Enable/disable environment map rendering.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableRayTracing(toggle):
"""
Enable/disable ray tracing.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableRadiosityRender(toggle):
"""
Enable/disable radiosity rendering.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enablePanorama(toggle):
"""
Enable/disable panorama rendering (output width is multiplied by Xparts).
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setRenderWinSize(size):
"""
Set the size of the render window.
@type size: int
@param size: can be 25, 50, 75 or 100 (percent).
"""
def getRenderWinSize():
"""
Get the size of the render window.
@rtype: int
@return: window size; can be 25, 50, 75 or 100 (percent).
"""
def enableFieldRendering(toggle):
"""
Enable/disable field rendering
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableOddFieldFirst(toggle):
"""
Enable/disable Odd field first rendering (Default: Even field).
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableFieldTimeDisable(toggle):
"""
Enable/disable time difference in field calculations.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableGaussFilter(toggle):
"""
Enable/disable Gauss sampling filter for anti-aliasing.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableBorderRender(toggle):
"""
Enable/disable small cut-out rendering.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setBorder(left,bottom,right,top):
"""
Set a border for rendering from cameras in the scene.
The left,bottom coordinates and right,top coordinates
define the size of the border. (0,0,1,1) will set the border
to the whole camera. (0,0) lower left and (1,1) upper right.
@type left: float
@param left: float between 0 and 1
@type right: float
@param right: float between 0 and 1
@type bottom: float
@param bottom: float between 0 and 1
@type top: float
@param top: float between 0 and 1
"""
def enableGammaCorrection(toggle):
"""
Enable/disable gamma correction.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def gaussFilterSize(size = None):
"""
Get/sets the Gauss filter size.
@type size: float (optional)
@param size: must be between 0.5 - 1.5
@rtype: float (if prototype is empty)
@return: Current gauss filter size for the scene.
"""
def startFrame(frame = None):
"""
Get/set the starting frame for sequence rendering.
@type frame: int (optional)
@param frame: must be between 1 - 18000
@rtype: int (if prototype is empty)
@return: Current starting frame for the scene.
"""
def endFrame(frame = None):
"""
Get/set the ending frame for sequence rendering.
@type frame: int (optional)
@param frame: must be between 1 - 18000
@rtype: int (if prototype is empty)
@return: Current ending frame for the scene.
"""
def imageSizeX(size = None):
"""
Get/set the image width in pixels.
@type size: int (optional)
@param size: must be between 4 - 10000
@rtype: int (if prototype is empty)
@return: Current image width for the scene.
"""
def imageSizeY(size = None):
"""
Get/set the image height in pixels.
@type size: int (optional)
@param size: must be between 4 - 10000
@rtype: int (if prototype is empty)
@return: Current image height for the scene.
"""
def aspectRatioX(ratio = None):
"""
Get/set the horizontal aspect ratio.
@type ratio: int (optional)
@param ratio: must be between 1 - 200
@rtype: int (if prototype is empty)
@return: Current horizontal aspect ratio for the scene.
"""
def aspectRatioY(ratio = None):
"""
Get/set the vertical aspect ratio.
@type ratio: int (optional)
@param ratio: must be between 1 - 200
@rtype: int (if prototype is empty)
@return: Current vertical aspect ratio for the scene.
"""
def setRenderer(type):
"""
Get/set which renderer to render the output.
@type type: enum constant
@param type: must be one of 2 constants:
- INTERN: Blender's internal renderer
- YAFRAY: Yafray renderer
"""
def enableCropping(toggle):
"""
Enable/disable exclusion of border rendering from total image.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setImageType(type):
"""
Set the type of image to output from the render.
@type type: enum constant
@param type: must be one of 13 constants:
- AVIRAW: Uncompressed AVI files. AVI is a commonly used format on Windows platforms
- AVIJPEG: AVI movie w/ JPEG images
- AVICODEC: AVI using win32 codec
- QUICKTIME: Quicktime movie (if enabled)
- TARGA: Targa files
- RAWTGA: Raw Targa files
- PNG: Png files
- BMP: Bitmap files
- JPEG90: JPEG files
- HAMX: Hamx files
- IRIS: Iris files
- IRIZ: Iris + z-buffer files
- FTYPE: Ftype file
"""
def quality(qual = None):
"""
Get/set quality get/setting for JPEG images, AVI JPEG and SGI movies.
@type qual: int (optional)
@param qual: must be between 10 - 100
@rtype: int (if prototype is empty)
@return: Current image quality for the scene.
"""
def framesPerSec(qual = None):
"""
Get/set frames per second.
@type qual: int (optional)
@param qual: must be between 1 - 120
@rtype: int (if prototype is empty)
@return: Current frames per second for the scene.
"""
def enableGrayscale():
"""
Images are saved with black and white (grayscale) data.
"""
def enableRGBColor():
"""
Images are saved with RGB (color) data.
"""
def enableRGBAColor():
"""
Images are saved with RGB and Alpha data (if supported).
"""
def sizePreset(type):
"""
Set the renderer to one of a few presets.
@type type: enum constant
@param type: must be one of 8 constants:
- PAL: The European video standard: 720 x 576 pixels, 54 x 51 aspect.
- FULL: For large screens: 1280 x 1024 pixels.
- PREVIEW: For preview rendering: 320 x 256 pixels.
- PAL169: Wide-screen PAL.
- DEFAULT: Like "PAL", but here the render settings are also set.
- PANO: Panorama render.
- NTSC: For TV playback.
- PC: For standard PC graphics: 640 x 480 pixels.
"""
def enableUnifiedRenderer(toggle):
"""
Use the unified renderer.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def setYafrayGIQuality(type):
"""
Set yafray global Illumination quality.
@type type: enum constant
@param type: must be one of 6 constants:
- NONE
- LOW
- MEDIUM
- HIGH
- HIGHER
- BEST
- USEAOSETTINGS
"""
def getYafrayGIQuality():
"""
Get yafray global Illumination quality.
@rtype: enum constant
@return: one of 6 constants:
- NONE
- LOW
- MEDIUM
- HIGH
- HIGHER
- BEST
- USEAOSETTINGS
"""
def setYafrayGIMethod(type):
"""
Set yafray global Illumination method.
@type type: enum constant
@param type: must be one of 3 constants:
- NONE: Do not use GI illumination
- SKYDOME: Use Skydome method
- GIFULL: Use Full method
"""
def getYafrayGIMethod():
# (dietrich) 2007/06/01
"""
Get yafray global Illumination method.
@rtype: enum constant -
@return: Current yafray global illumination method:
- NONE: Do not use GI illumination
- SKYDOME: Use Skydome method
- GIFULL: Use Full method
"""
def yafrayGIPower(power = None):
"""
Get/set GI lighting intensity scale.
YafrayMethod must be either SKYDOME or GIFULL.
@type power: float (optional)
@param power: must be between 0.01 - 100.0
@rtype: float (if prototype is empty)
@return: Current yafray global illumination intensity for the scene.
"""
def yafrayGIIndirPower(power = None):
"""
Get/set GI indirect lighting intensity scale.
@type power: float (optional)
@param power: must be between 0.01 - 100.0
@rtype: float (if prototype is empty)
@return: Current yafray indirect illumination intensity for the scene.
"""
def yafrayGIDepth(depth = None):
"""
Get/set number of bounces of the indirect light.
YafrayMethod must be GIFULL.
@type depth: int (optional)
@param depth: must be between 1 - 8
@rtype: int (if prototype is empty)
@return: Current yafray global illumination light bounces for the scene.
"""
def yafrayGICDepth(depth = None):
"""
Get/set number of bounces inside objects (for caustics).
YafrayMethod must be GIFULL.
@type depth: int (optional)
@param depth: must be between 1 - 8
@rtype: int (if prototype is empty)
@return: Current yafray global illumination inside light bounces for the scene.
"""
def enableYafrayGICache(toggle):
"""
Enable/disable cache irradiance samples (faster).
YafrayMethod must be GIFULL.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def enableYafrayGIPhotons(toggle):
"""
Enable/disable use of global photons to help in GI.
YafrayMethod must be GIFULL.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def yafrayGIPhotonCount(count = None):
"""
Get/set number of photons to shoot.
YafrayMethod must be GIFULL and Photons enabled.
@type count: int (optional)
@param count: must be between 0 - 10000000
@rtype: int (if prototype is empty)
@return: Current number of photons to shoot for the scene.
"""
def yafrayGIPhotonRadius(radius = None):
"""
Get/set radius to search for photons to mix (blur).
YafrayMethod must be GIFULL and Photons enabled.
@type radius: float (optional)
@param radius: must be between 0.00001 - 100.0
@rtype: float (if prototype is empty)
@return: Current photon search radius for the scene.
"""
def yafrayGIPhotonMixCount(count = None):
"""
Get/set number of photons to keep inside radius.
YafrayMethod must be GIFULL and Photons enabled.
@type count: int (optional)
@param count: must be between 0 - 1000
@rtype: int (if prototype is empty)
@return: Current number of photons to keep inside radius for the scene.
"""
def enableYafrayGITunePhotons(toggle):
"""
Enable/disable show the photon map directly in the render for tuning.
YafrayMethod must be GIFULL and Photons enabled.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def yafrayGIShadowQuality(qual = None):
"""
Get/set the shadow quality, keep it under 0.95.
YafrayMethod must be GIFULL and Cache enabled.
@type qual: float (optional)
@param qual: must be between 0.01 - 1.0
@rtype: float (if prototype is empty)
@return: Current shadow quality for the scene.
"""
def yafrayGIPixelsPerSample(pixels = None):
"""
Get/set maximum number of pixels without samples, the lower the better and slower.
YafrayMethod must be GIFULL and Cache enabled.
@type pixels: int (optional)
@param pixels: must be between 1 - 50
@rtype: int (if prototype is empty)
@return: Current number of pixels without samples for the scene.
"""
def enableYafrayGIGradient(toggle):
"""
Enable/disable try to smooth lighting using a gradient.
YafrayMethod must be GIFULL and Cache enabled.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def yafrayGIRefinement(refine = None):
"""
Get/set threshold to refine shadows EXPERIMENTAL. 1 = no refinement.
YafrayMethod must be GIFULL and Cache enabled.
@type refine: float (optional)
@param refine: must be between 0.001 - 1.0
@rtype: float (if prototype is empty)
@return: Current threshold to refine shadows for the scene.
"""
def yafrayRayBias(bias = None):
"""
Get/set shadow ray bias to avoid self shadowing.
@type bias: float (optional)
@param bias: must be between 0 - 10.0
@rtype: float (if prototype is empty)
@return: Current ray bias for the scene.
"""
def yafrayRayDepth(depth = None):
"""
Get/set maximum render ray depth from the camera.
@type depth: int (optional)
@param depth: must be between 1 - 80
@rtype: int (if prototype is empty)
@return: Current ray depth for the scene.
"""
def yafrayGamma(gamma = None):
"""
Get/set gamma correction, 1 is off.
@type gamma: float (optional)
@param gamma: must be between 0.001 - 5.0
@rtype: float (if prototype is empty)
@return: Current gamma correction for the scene.
"""
def yafrayExposure(expose = None):
"""
Get/set exposure adjustment, 0 is off.
@type expose: float (optional)
@param expose: must be between 0 - 10.0
@rtype: float (if prototype is empty)
@return: Current exposure adjustment for the scene.
"""
def yafrayProcessorCount(count = None):
"""
Get/set number of processors to use.
@type count: int (optional)
@param count: must be between 1 - 8
@rtype: int (if prototype is empty)
@return: Current number of processors for the scene.
"""
def enableGameFrameStretch():
"""
Enable stretch or squeeze the viewport to fill the display window.
"""
def enableGameFrameExpose():
"""
Enable show the entire viewport in the display window, viewing more
horizontally or vertically.
"""
def enableGameFrameBars():
"""
Enable show the entire viewport in the display window, using bar
horizontally or vertically.
"""
def setGameFrameColor(red, green, blue):
"""
Set the red, green, blue component of the bars.
@type red: float
@param red: must be between 0 - 1.0
@type green: float
@param green: must be between 0 - 1.0
@type blue: float
@param blue: must be between 0 - 1.0
"""
def getGameFrameColor():
"""
Set the red, green, blue component of the bars.
@rtype: string
@return: A string representing the color component of the bars.
"""
def gammaLevel(level = None):
"""
Get/set the gamma value for blending oversampled images (1.0 = no correction).
Unified renderer must be enabled.
@type level: float (optional)
@param level: must be between 0.2 - 5.0
@rtype: float (if prototype is empty)
@return: Current gamma value for the scene.
"""
def postProcessAdd(add = None):
"""
Get/set post processing add.
Unified renderer must be enabled.
@type add: float (optional)
@param add: must be between -1.0 - 1.0
@rtype: float (if prototype is empty)
@return: Current processing add value for the scene.
"""
def postProcessMultiply(mult = None):
"""
Get/set post processing multiply.
Unified renderer must be enabled.
@type mult: float (optional)
@param mult: must be between 0.01 - 4.0
@rtype: float (if prototype is empty)
@return: Current processing multiply value for the scene.
"""
def postProcessGamma(gamma = None):
"""
Get/set post processing gamma.
Unified renderer must be enabled.
@type gamma: float (optional)
@param gamma: must be between 0.2 - 2.0
@rtype: float (if prototype is empty)
@return: Current processing gamma value for the scene.
"""
def SGIMaxsize(size = None):
"""
Get/set maximum size per frame to save in an SGI movie.
SGI must be defined on your machine.
@type size: int (optional)
@param size: must be between 0 - 500
@rtype: int (if prototype is empty)
@return: Current SGI maximum size per frame for the scene.
"""
def enableSGICosmo(toggle):
"""
Enable/disable attempt to save SGI movies using Cosmo hardware
SGI must be defined on your machine.
@type toggle: int
@param toggle: pass 1 for on / 0 for off
"""
def oldMapValue(value = None):
"""
Get/set specify old map value in frames.
@type value: int (optional)
@param value: must be between 1 - 900
@rtype: int (if prototype is empty)
@return: Current old map value for the scene.
"""
def newMapValue(value = None):
"""
Get/set specify new map value in frames.
@type value: int (optional)
@param value: must be between 1 - 900
@rtype: int (if prototype is empty)
@return: Current new map value for the scene.
"""

View File

@@ -0,0 +1,392 @@
# Blender.Scene module and the Scene PyType object
"""
The Blender.Scene submodule.
B{New}:
- L{Scene.clearScriptLinks<Scene.Scene.clearScriptLinks>} accepts a parameter now.
- acess methods L{Scene.getLayers<Scene.Scene.getLayers>}, L{Scene.setLayers<Scene.Scene.setLayers>} via lists to complement the layers and
Layers Scene attributes which use bitmasks.
Scene
=====
This module provides access to B{Scenes} in Blender.
Example::
import Blender
from Blender import Scene, Object, Camera
#
camdata = Camera.New('persp') # create new camera data
camdata.name = 'newCam'
camdata.lens = 16.0
scene = Scene.New('NewScene') # create a new scene
scene.objects.new(camdata,'Camera') # add a new object to the scene with newly-created data
scene.makeCurrent() # make this the current scene
@warn: B{scene.objects.new} is the preferred way to add new objects to a scene.
The older way is to create an object with B{Object.New()}, link the
data to the new object, then link the object to the scene. This way is
not recommended since a forgotten step or run-time error in the script can
cause bad things to be done to Blender's database.
If you use this older method, it's recommended to always perform the
operations in this order. This is because if
there is no object data linked to an object B{ob}, B{scene.link(ob)} will
automatically create the missing data. This is OK on its own, but I{if
after that} object B{ob} is linked to obdata, the automatically created one
will be discarded -- as expected -- but will stay in Blender's memory
space until the program is exited, since Blender doesn't really get rid of
most kinds of data. So first linking ObData to object, then object to
scene is a tiny tiny bit faster than the other way around and also saves
some realtime memory (if many objects are created from scripts, the
savings become important).
"""
def New (name = 'Scene'):
"""
Create a new Scene in Blender.
@type name: string
@param name: The Scene name.
@rtype: Blender Scene
@return: The created Scene.
"""
def Get (name = None):
"""
Get the Scene(s) from Blender.
@type name: string
@param name: The name of a Scene.
@rtype: Blender Scene or a list of Blender Scenes
@return: It depends on the I{name} parameter:
- (name): The Scene with the given I{name};
- (): A list with all Scenes currently in Blender.
"""
def GetCurrent():
"""
Get the currently active Scene in Blender.
@rtype: Blender Scene
@return: The currently active Scene.
"""
def Unlink(scene):
"""
Unlink (delete) a Scene from Blender.
@type scene: Blender Scene
@param scene: The Scene to be unlinked.
"""
from IDProp import IDGroup, IDArray
class Scene:
"""
The Scene object
================
This object gives access to Scene data in Blender.
@type Layers: integer (bitmask)
@ivar Layers: The Scene layers (check also the easier to use
L{layers}). This value is a bitmask with at least
one position set for the 20 possible layers starting from the low order
bit. The easiest way to deal with these values in in hexadecimal
notation.
Example::
scene.Layers = 0x04 # sets layer 3 ( bit pattern 0100 )
scene.Layers |= 0x01
print scene.Layers # will print: 5 ( meaning bit pattern 0101)
After setting the Layers value, the interface (at least the 3d View and
the Buttons window) needs to be redrawn to show the changes.
@type layers: list of integers
@ivar layers: The Scene layers (check also L{Layers}).
This attribute accepts and returns a list of integer values in the
range [1, 20].
Example::
scene.layers = [3] # set layer 3
scene.layers = scene.layers.append(1)
print scene.layers # will print: [1, 3]
@type objects: sequence of objects
@ivar objects: The scene's objects. The sequence supports the methods .link(ob), .unlink(ob), and .new(obdata), and can be iterated over.
@type cursor: Vector (wrapped)
@ivar cursor: the 3d cursor location for this scene.
@type camera: Camera or None
@ivar camera: The active camera for this scene (can be set)
@type world: World or None
@ivar world: The world that this scene uses (if any)
@type timeline: Timeline
@ivar timeline: The L{timeline<TimeLine.TimeLine>} for this scene, named markers are stored here. (read only)
@type render: RenderData
@ivar render: The scenes L{render<Render.RenderData>} settings. (read only)
@type radiosity: RenderData
@ivar radiosity: The scenes L{radiosity<Radio>} settings. (read only)
"""
def getName():
"""
Get the name of this Scene.
@rtype: string
"""
def setName(name):
"""
Set the name of this Scene.
@type name: string
@param name: The new name.
"""
def getLayers():
"""
Get the layers set for this Scene.
@rtype: list of integers
@return: a list where each number means the layer with that number is set.
"""
def setLayers(layers):
"""
Set the visible layers for this scene.
@type layers: list of integers
@param layers: a list of integers in the range [1, 20], where each available
index makes the layer with that number visible.
@note: if this Scene is the current one, the 3D View layers are also
updated, but the screen needs to be redrawn (at least 3D Views and
Buttons windows) for the changes to be seen.
"""
def copy(duplicate_objects = 1):
"""
Make a copy of this Scene.
@type duplicate_objects: int
@param duplicate_objects: Defines how the Scene children are duplicated:
- 0: Link Objects;
- 1: Link Object Data;
- 2: Full copy.
@rtype: Scene
@return: The copied Blender Scene.
"""
def makeCurrent():
"""
Make this Scene the currently active one in Blender.
"""
def update(full = 0):
"""
Update this Scene in Blender.
@type full: int
@param full: A bool to control the level of updating:
- 0: sort the base list of objects.
- 1: sort and also regroup, do ipos, keys, script links, etc.
@warn: When in doubt, try with I{full = 0} first, since it is faster.
The "full" update is a recent addition to this method.
"""
def getRenderingContext():
"""
Get the rendering context for this scene, see L{Render}.
@rtype: RenderData
@return: the render data object for this scene.
"""
def getRadiosityContext():
"""
Get the radiosity context for this scene, see L{Radio}.
@rtype: Blender Radiosity
@return: the radiosity object for this scene.
@note: only the current scene can return a radiosity context.
"""
def getChildren():
"""
Get all objects linked to this Scene. (B{deprecated}). B{Note}: new scripts
should use the L{objects} attribute instead. In cases where a list is
required use list(scn.objects).
@rtype: list of Blender Objects
@return: A list with all Blender Objects linked to this Scene.
@note: L{Object.Get} will return all objects currently in Blender, which
means all objects from all available scenes. In most cases (exporter
scripts, for example), it's probably better to use this
scene.GetChildren instead, since it will only access objects from this
particular scene.
@warn: Depricated! use scene.objects instead.
"""
def getActiveObject():
"""
Get this scene's active object.
@note: the active object, if selected, can also be retrieved with
L{Object.GetSelected} -- it is the first item in the returned
list. But even when no object is selected in Blender, there can be
an active one (if the user enters editmode, for example, this is the
object that should become available for edition). So what makes this
scene method different from C{Object.GetSelected()[0]} is that it can
return the active object even when no objects are selected.
@rtype: Blender Object or None
@return: the active object or None if not available.
@warn: Depricated! use scene.objects.active instead.
"""
def getCurrentCamera():
"""
Get the currently active Camera for this Scene.
@note: The active camera can be any object type, not just a camera object.
@rtype: Blender Object
@return: The currently active Camera object.
"""
def setCurrentCamera(camera):
"""
Set the currently active Camera in this Scene.
@type camera: Blender Camera
@param camera: The new active Camera.
"""
def link(object):
"""
Link an Object to this Scene.
@type object: Blender Object
@param object: A Blender Object.
"""
def unlink(object):
"""
Unlink an Object from this Scene.
@type object: Blender Object
@param object: A Blender Object.
@rtype: boolean
@return: true if object was found in the scene.
"""
def getScriptLinks (event):
"""
Get a list with this Scene's script links of type 'event'.
@type event: string
@param event: "FrameChanged", "OnLoad", "OnSave", "Redraw" or "Render".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this Scene. If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this Scene.
Using OpenGL functions within a scene ScriptLink will draw graphics over the 3D view.
There is an issue with the zoom of the floating panels also scaling graphics drawn by your scriptlink.
This makes matching OpenGL graphics to mouse location impossible.
Make sure that you use floating point for operations that you would usually use int functions for: glRasterPos2f rather then glRasterPos2i.
The following example shows how you can use the OpenGL model view matrix to obtain the scale value.
Example::
from Blender import BGL
view_matrix = BGL.Buffer(BGL.GL_FLOAT, 16)
BGL.glGetFloatv(BGL.GL_MODELVIEW_MATRIX, view_matrix)
gl_scale = 1/viewMatrix[0]
# Now that we have the scale we can draw to the correct scale.
BGL.glRect2f(10*gl_scale, 10*gl_scale, 110*gl_scale, 110*gl_scale)
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged", "OnLoad", "OnSave", "Redraw" or "Render".
"""
def play (mode = 0, win = '<VIEW3D>'):
"""
Play a realtime animation. This is the "Play Back Animation" function in
Blender, different from playing a sequence of rendered images (for that
check L{Render.RenderData.play}).
@type mode: int
@param mode: controls playing:
- 0: keep playing in the biggest 'win' window;
- 1: keep playing in all 'win', VIEW3D and SEQ windows;
- 2: play once in the biggest VIEW3D;
- 3: play once in all 'win', VIEW3D and SEQ windows.
@type win: int
@param win: window type, see L{Window.Types}. Only some of them are
meaningful here: VIEW3D, SEQ, IPO, ACTION, NLA, SOUND. But the others
are also accepted, since this function can be used simply as an
interruptible timer. If 'win' is not visible or invalid, VIEW3D is
tried, then any bigger visible window.
@rtype: bool
@return: 0 on normal exit or 1 when play back is canceled by user input.
"""
import id_generics
Scene.__doc__ += id_generics.attributes
class SceneObjects:
"""
The SceneObjects (Scene ObjectSeq) object
=========================================
This object gives access to the Objects in a Scene in Blender.
Example::
from Blender import Scene
scn = Scene.GetCurrent()
scn.objects.selected = [] # select none
scn.objects.selected = scn.objects # select all
scn.objects.context = scn.objects # select all and move into the scenes display layer
# get a list of mesh objects
obs = [ob for ob in scn.objects if ob.type == 'Mesh']
# Select only these mesh objects
scn.objects.selected = obs
# print all object names
for ob in scn.objects: print ob.name
# make a list of objects that you can add and remove to
# will not affect the current scene
scene_obs = list(scn.objects)
@ivar selected: an iterator over all the selected objects in a scene.
@type selected: sequence of L{Object}
@ivar context: an iterator over all the visible selected objects in a scene.
@type context: sequence of L{Object}
@ivar active: the active object in the scene.
@type active: L{Object}
@ivar camera: the active camera in the scene.
@type camera: L{Object}
"""
def new(data):
"""
Adds a new object to the scene. Data is either object data such as a
L{Mesh} or L{Curve}, or the string "Empty" for an Empty object. The
type of the object is determined by the type of the data.
@type data: string or object data
@param data: the object data for the new object
@return: the new object.
@rtype: L{Object}
"""
def link(object):
"""
Adds an existing object to the scene. If the object is already linked
to the scene, no action is taken and no exception is raised.
@type object: L{Object}
@param object: the object
@rtype: None
"""
def unlink(object):
"""
Removes an object from the scene. If the object is not linked
to the scene, no action is taken and no exception is raised.
@type object: L{Object}
@param object: the object
@rtype: None
"""

View File

@@ -0,0 +1,147 @@
# Blender.Sound module and the Sound PyType object
"""
The Blender.Sound submodule.
Sound
=====
This module provides access to B{Sound} objects in Blender.
Example::
import Blender
from Blender import Sound
#
sound = Sound.Load("/path/to/my/sound.wav") # load a sound file
print "Sound from", sound.filename,
print "loaded to obj", sound.name
print "All Sounds available now:", Sound.Get()
No way to get the actual audio data is provided by this library,
but it is included in the Python standard library (module audioop).
Note that using that module requires a full/normal Python installation.
"""
def Load (filename):
"""
Load the sound called 'filename' into a Sound object.
@type filename: string
@param filename: The full path to the sound file.
@rtype: Blender Sound
@return: A Blender Sound object with the data from I{filename}.
"""
def Get (name = None):
"""
Get the Sound object(s) from Blender.
@type name: string
@param name: The name of the Sound object.
@rtype: Blender Sound or a list of Blender Sounds
@return: It depends on the I{name} parameter:
- (name): The Sound object called I{name}, None if not found;
- (): A list with all Sound objects in the current scene.
"""
class Sound:
"""
The Sound object
================
This object gives access to Sounds in Blender.
@ivar filename: The filename (path) to the sound file loaded into this Sound
@ivar packed: Boolean, True when the sample is packed (readonly).
"""
def getName():
"""
Get the name of this Sound object.
@rtype: string
"""
def getFilename():
"""
Get the filename of the sound file loaded into this Sound object.
@rtype: string
"""
def setName():
"""
Set the name of this Sound object.
@rtype: None
"""
def setFilename():
"""
Set the filename of the sound file loaded into this Sound object.
@rtype: None
"""
def setCurrent():
"""
Make this the active sound in the sound buttons window (also redraws).
"""
def play():
"""
Play this sound.
"""
def getVolume():
"""
Get this sound's volume.
rtype: float
"""
def setVolume(f):
"""
Set this sound's volume.
@type f: float
@param f: the new volume value in the range [0.0, 1.0].
"""
def getAttenuation():
"""
Get this sound's attenuation value.
rtype: float
"""
def setAttenuation(f):
"""
Set this sound's attenuation.
@type f: float
@param f: the new attenuation value in the range [0.0, 5.0].
"""
def getPitch():
"""
Get this sound's pitch value.
rtype: float
"""
def setPitch(f):
"""
Set this sound's pitch.
@type f: float
@param f: the new pitch value in the range [-12.0, 12.0].
"""
def pack():
"""
Packs the sound into the current blend file.
@note: An error will be raised if the sound is already packed or the filename path does not exist.
@returns: nothing
@rtype: none
"""
def unpack(mode):
"""
Unpacks the sound to the samples filename.
@param mode: One of the values in Blender.Unpackmodes dict.
@note: An error will be raised if the sound is not packed or the filename path does not exist.
@returns: nothing
@rtype: none
@type mode: int
"""
import id_generics
Sound.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,167 @@
# Blender.sys module
"""
The Blender.sys submodule.
sys
===
B{New}: L{expandpath}.
This module provides a minimal set of helper functions and data. Its purpose
is to avoid the need for the standard Python module 'os', in special 'os.path',
though it is only meant for the simplest cases.
Example::
import Blender
filename = ""
def f(name): # file selector callback
global filename
filename = name
Blender.Window.FileSelector(f)
if filename:
print 'basename:', Blender.sys.basename(filename)
print 'dirname:', Blender.sys.dirname(filename)
print 'splitext:', Blender.sys.splitext(filename)
# what would basename(splitext(filename)[0]) print?
@type sep: char
@var sep: the platform-specific dir separator for this Blender: '/'
everywhere, except on Win systems, that use '\\'.
@type dirsep: char
@var dirsep: same as L{sep}.
@type progname: string
@var progname: the Blender executable (argv[0]).
@attention: The module is called sys, not Sys.
"""
def basename (path):
"""
Get the base name (filename stripped from dir info) of 'path'.
@type path: string
@param path: a path name
@rtype: string
@return: the base name
"""
def dirname (path):
"""
Get the dir name (dir path stripped from filename) of 'path'.
@type path: string
@param path: a path name
@rtype: string
@return: the dir name
"""
def join (dir, file):
"""
Join the given dir and file paths, using the proper separator for each
platform.
@type dir: string
@type file: string
@param dir: the dir name, like returned from L{dirname}.
@param file: the bare filename, like returned from L{basename}.
@rtype: string
@return: the resulting filename.
@warn: this simple function isn't intended to be a complete replacement for
the standard os.path.join() one, which handles more general cases.
"""
def splitext (path):
"""
Split 'path' into (root, ext), where 'ext' is a file extension including the full stop.
Example::
import Blender
file, ext= Blender.sys.splitext('/tmp/foobar.blend')
print file, ext
# ('/tmp/foobar', '.blend')
@type path: string
@param path: a path name
@rtype: tuple of two strings
@return: (root, ext)
@note: This function will raise an error if the path is longer then 80 characters.
"""
def makename (path = "Blender.Get('filename')", ext = "", strip = 0):
"""
Remove extension from 'path', append extension 'ext' (if given)
to the result and return it. If 'strip' is non-zero, also remove
dirname from path.
Example::
import Blender
from Blender.sys import *
print makename('/path/to/myfile.txt','.abc', 1) # returns 'myfile.abc'
print makename('/path/to/myfile.obj', '-01.obj') # '/path/to/myfile-01.obj'
print makename('/path/to/myfile.txt', strip = 1) # 'myfile'
# note that:
print makename(ext = '.txt')
# is equivalent to:
print sys.splitext(Blender.Get('filename'))[0]) + '.txt'
@type path: string
@param path: a path name or Blender.Get('filename'), if not given.
@type ext: string
@param ext: an extension to append. For flexibility, a dot ('.') is
not automatically included.
@rtype: string
@return: the resulting string
"""
def exists(path):
"""
Tell if the given pathname (file or dir) exists.
@rtype: int
@return:
- 0: path does not exist;
- 1: path is an existing filename;
- 2: path is an existing dirname;
- -1: path exists but is neither a regular file nor a dir.
"""
def time ():
"""
Get the current time in seconds since a fixed value. Successive calls to
this function are guaranteed to return values greater than the previous call.
@rtype: float
@return: the elapsed time in seconds.
"""
def sleep (millisecs = 10):
"""
Sleep for the specified amount of time.
@type millisecs: int
@param millisecs: the amount of time in milliseconds to sleep. The default
is 10 which is 0.1 seconds.
"""
def expandpath (path):
"""
Expand the given Blender 'path' into an absolute and valid path.
Internally, Blender recognizes two special character sequences in paths:
- '//' (used at the beginning): means base path -- the current .blend file's
dir;
- '#' (used at the end): means current frame number.
The expanded string can be passed to generic python functions that don't
understand Blender's internal relative paths.
@note: this function is also useful for obtaining the name of the image
that will be saved when rendered.
@note: if the passed string doesn't contain the special characters it is
returned unchanged.
@type path: string
@param path: a path name.
@rtype: string
@return: the expanded (if necessary) path.
"""

View File

@@ -0,0 +1,129 @@
# Blender.Text module and the Text PyType object
"""
The Blender.Text submodule.
Text Objects
============
This module provides access to B{Text} objects in Blender.
Example::
import Blender
from Blender import Text
#
txt = Text.New("MyText") # create a new Text object
print Text.Get() # current list of Texts in Blender
txt.write("Appending some ") # appending text
txt.write("text to my\\n") # '\\n' inserts new-line markers
txt.write("text buffer.")
print txt.asLines() # retrieving the buffer as a list of lines
Text.unlink(txt) # removing a Text object
"""
def New (name = None, follow_cursor = 0):
"""
Create a new Text object.
@type name: string
@param name: The Text name.
@type follow_cursor: int
@param follow_cursor: The text follow flag: if 1, the text display always
follows the cursor.
@rtype: Blender Text
@return: The created Text Data object.
"""
def Get (name = None):
"""
Get the Text object(s) from Blender.
@type name: string
@param name: The name of the Text object.
@rtype: Blender Text or a list of Blender Texts
@return: It depends on the 'name' parameter:
- (name): The Text object with the given name;
- (): A list with all Text objects in the current scene.
"""
def Load (filename):
"""
Load a file into a Blender Text object.
@type filename: string
@param filename: The name of the file to load.
@rtype: Blender Text
@return: A Text object with the contents of the loaded file.
"""
def unlink(textobj):
"""
Unlink (remove) the given Text object from Blender.
@type textobj: Blender Text
@param textobj: The Text object to be deleted.
"""
class Text:
"""
The Text object
===============
This object gives access to Texts in Blender.
@ivar filename: The filename of the file loaded into this Text.
@ivar mode: The follow_mode flag: if 1 it is 'on'; if 0, 'off'.
@ivar nlines: The number of lines in this Text.
"""
def getName():
"""
Get the name of this Text object.
@rtype: string
"""
def setName(name):
"""
Set the name of this Text object.
@type name: string
@param name: The new name.
"""
def getFilename():
"""
Get the filename of the file loaded into this Text object.
@rtype: string
"""
def getNLines():
"""
Get the number of lines in this Text buffer.
@rtype: int
"""
def clear():
"""
Clear this Text object: its buffer becomes empty.
"""
def set(attribute, value):
"""
Set this Text's attributes.
@type attribute: string
@param attribute: The attribute to change:
currently, 'follow_cursor' is the only one available. It can be
turned 'on' with value = 1 and 'off' with value = 0.
@type value: int
@param value: The new attribute value.
"""
def write(data):
"""
Append a string to this Text buffer.
@type data: string
@param data: The string to append to the text buffer.
"""
def asLines():
"""
Retrieve the contents of this Text buffer as a list of strings.
@rtype: list of strings
@return: A list of strings, one for each line in the buffer
"""
import id_generics
Text.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,302 @@
# Blender.Text3d module and the Text3d PyType object
"""
The Blender.Text3d submodule.
Text3d Objects
==============
This module provides access to B{Font} objects in Blender.
Example::
import Blender
from Blender import Curve, Object, Scene, Text3d
txt = Text3d.New("MyText") # create a new Text3d object called MyText
scn = Scene.GetCurrent() # get current scene
ob = scn.objects.new(txt) # create an object from the obdata in the current scene
ob.makeDisplayList() # rebuild the display list for this object
Window.RedrawAll()
"""
def New (name = None):
"""
Create a new Text3d object.
@type name: string
@param name: The name for the new object..
@rtype: Blender Text3d
@return: The created Text3d Data object.
"""
def Get (name = None):
"""
Get the Text3d object(s) from Blender.
@type name: string
@param name: The name of the Text3d object.
@rtype: Blender Text3d or a list of Blender Text3d's
@return: It depends on the 'name' parameter:
- (name): The Text3d object with the given name;
- (): A list with all Text3d objects in the current scene.
"""
class Text3d:
"""
The Text3d object
=================
This object gives access Blender's B{Font} objects
@ivar frameWidth: The width of the active frame [0.0 - 50.0]
@ivar frameHeight: The height of the active frame [0.0 - 50.0]
@ivar frameX: The X position of the active frame [0.0 - 50.0]
@ivar frameY: The Y position of the active frame [0.0 - 50.0]
@ivar totalFrames: The total number of text frames (read only)
@ivar activeFrame: The active frame for this text data.
"""
def getName():
"""
Get the name of this Text3d object.
@rtype: string
"""
def setName( name ):
"""
Set the name of this Text3d object.
@type name: string
@param name: The new name.
@returns: None
"""
def getText():
"""
Get text string for this object
@rtype: string
"""
def setText( name ):
"""
Set the text string in this Text3d object
@type name: string
@param name: The new text string for this object.
@returns: None
"""
def getDrawMode():
"""
Get the drawing mode (3d, front, and/or back)
Gets the text3d's drawing modes. Uses module constants
- DRAW3D : "3D" is set
- DRAWFRONT : "Front" is set
- DRAWBACK : "Back" is set
@rtype: tuple of module constants
"""
def setDrawMode(val):
"""
Set the text3d's drawing mode. Uses module constants
- DRAW3D
- DRAWFRONT
- DRAWBACK
@rtype: None
@type val: single module constant or tuple of module constants
@param val : The Text3d's modes. See L{getDrawMode} for the meaning of
the constants.
"""
def getUVordco():
"""
Return whether UV coords are used for Texture mapping
"""
def setUVordco(val):
"""
Set the font to use UV coords for Texture mapping
"""
def getBevelAmount():
"""
Get the Text3d's bevel resolution value.
@rtype: float
"""
def setBevelAmount(bevelresol):
"""
Set the Text3d's bevel resolution value.
@rtype: None
@type bevelresol: float
@param bevelresol: The new Curve's bevel resolution value.
"""
def getDefaultResolution():
"""
Return Default text resolution.
@rtype: float
"""
def setDefaultResolution(resolu):
"""
Sets Default text Resolution.
@rtype: None
@type resolu: float
@param resolu: The new Curve's U-resolution value.
"""
def getWidth():
"""
Get the Text3d's width value.
@rtype: float
"""
def setWidth(width):
"""
Set the Text3d's width value.
@rtype: None
@type width: float
@param width: The new text3d's width value.
"""
def getgetExtrudeDepth():
"""
Get the text3d's ext1 value.
@rtype: float
"""
def setgetExtrudeDepth(ext1):
"""
Set the text3d's ext1 value.
@rtype: None
@type ext1: float
@param ext1: The new text3d's ext1 value.
"""
def getExtrudeBevelDepth():
"""
Get the text3d's ext2 value.
@rtype: float
"""
def setExtrudeBevelDepth(ext2):
"""
Set the text3d's ext2 value.
@rtype: None
@type ext2: float
@param ext2: The new text3d's ext2 value.
"""
def getShear():
"""
Get the text3d's shear value.
@rtype: float
"""
def setShear(shear):
"""
Set the text3d's shear value.
@rtype: None
@type shear: float
@param shear: The new text3d's shear value.
"""
def getSize():
"""
Get the text3d's size value.
@rtype: float
"""
def setSize(size):
"""
Set the text3d's size value.
@rtype: None
@type size: float
@param size: The new text3d's size value.
"""
def getLineSeparation():
"""
Get the text3d's ext2 value.
@rtype: float
"""
def setLineSeparation(sep):
"""
Set the text3d's ext2 value.
@rtype: None
@type sep: float
@param sep: The new text3d's separation value.
"""
def getSpacing():
"""
Get the text3d's spacing value.
@rtype: float
"""
def setSpacing(spacing):
"""
Set the text3d's spacing value.
@rtype: None
@type spacing: float
@param spacing: The new text3d's spacing value.
"""
def getXoffset():
"""
Get the text3d's Xoffset value.
@rtype: float
"""
def setXoffset(xof):
"""
Set the text3d's Xoffset value.
@rtype: None
@type xof: float
@param xof: The new text3d's Xoffset value.
"""
def getYoffset():
"""
Get the text3d's Yoffset value.
@rtype: float
"""
def setYoffset(yof):
"""
Set the text3d's Yoffset value.
@rtype: None
@type yof: float
@param yof: The new text3d's Yoffset value.
"""
def getAlignment():
"""
Get the text3d's alignment value. Uses module constants
- LEFT
- RIGHT
- MIDDLE
- FLUSH
@rtype: module constant
"""
def setAlignment(align):
"""
Set the text3d's Alignment value. Uses module constants
- LEFT
- RIGHT
- MIDDLE
- FLUSH
@rtype: None
@type align: module constant
@param align: The new text3d's Alignment value.
"""
def addFrame():
"""
Adds a text frame. maximum number of frames is 255.
@rtype: None
"""
def removeFrame(index):
"""
Removed the frame at this index
@rtype: None
"""
import id_generics
Text3d.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,555 @@
#
# Blender.Texture module and the Texture PyType object
#
# Written by Alex Mole
#
"""
The Blender.Texture submodule.
B{New}:
- many new attributes in L{MTex} submodule
- new dictionaries (L{Texture.BlendModes}, L{Texture.Mappings}, L{Texture.Proj}) to use for the values of some of the new L{MTex} attributes.
Texture
=======
This module provides access to B{Texture} objects in Blender.
Example::
from Blender import Texture,Image,Material
footex = Texture.Get('foo') # get texture named 'foo'
footex.setType('Image') # make foo be an image texture
img = Image.Load('test.png') # load an image
footex.image = img # link the image to the texture
mat = Material.Get('bar') # get a material
mtextures = mat.getTextures() # get a list of the MTex objects
for mtex in mtextures:
if mtex.tex.type == Texture.Types.IMAGE:
print mtex.tex.image.filename # print the filenames of all the
# images in textures linked to "bar"
mat.setTexture(0, footex) # set the material's first texture
# to be our texture
@type Types: readonly dictionary
@var Types: The available texture types:
- NONE - No texture
- CLOUDS - Clouds texture
- WOOD - Wood texture
- MARBLE - Marble texture
- MAGIC - Magic texture
- BLEND - Blend texture
- STUCCI - Stucci texture
- NOISE - Noise texture
- IMAGE - Image texture
- PLUGIN - Plugin texture
- ENVMAP - EnvMap texture
- MUSGRAVE - Musgrave procedural texture
- VORONOI - Voronoi procedural texture
- DISTNOISE - Distorted noise texture
@type Flags: readonly dictionary
@var Flags: The available Texture flags:
- FLIPBLEND - Flips the blend texture's X and Y directions
- NEGALPHA - Reverse the alpha value
- CHECKER_ODD - Fill the "odd" checkerboard tiles
- CHECKER_EVEN - Fill the "even" checkerboard tiles
- COLORBAND - Enable colorband for this texture
- PREVIEW_ALPHA - Show alpha in preview
- REPEAT_XMIR - Mirrors X direction repeat
- REPEAT_YMIR - Mirrors Y direction repeat
@type ImageFlags: readonly dictionary
@var ImageFlags: The available image flags for Texture.imageFlags:
- INTERPOL - Interpolate pixels of the image
- USEALPHA - Use the alpha layer
- MIPMAP - Enable mipmapping [cannot be used with FIELDS]
- FIELDS - Work with field images [cannot be used with MIPMAP]
- ROT90 - Rotate the image 90 degrees when rendering
- CALCALPHA - Calculate an alpha from the RGB
- STFIELD - Denotes this is a standard field
- MOVIE - Use a movie for an image
- CYCLIC - Repeat animation image
- ANTI - Use anti-aliasing
- NORMALMAP - Use image RGB values for normal mapping
@type ExtendModes: readonly dictionary
@var ExtendModes: Extend, clip, repeat or checker modes for image textures
- EXTEND - Extends the colour of the edge
- CLIP - Return alpha 0.0 outside image
- CLIPCUBE - Return alpha 0.0 around cube-shaped area around image
- REPEAT - Repeat image vertically and horizontally
- CHECKER - Repeat image in checkerboard pattern
@type Noise: readonly dictionary
@var Noise: Noise types and bases. SINE, SAW and TRI are only used for
marble and wood textures, while the remainder are used for all textures
which has a noise basis function (for these textures, the constant should
be used with the second noise basis setting).
- SINE - Produce bands using sine wave (marble, wood textures)
- SAW - Produce bands using saw wave (marble, wood textures)
- TRI - Produce bands using triangle wave (marble, wood textures)
- BLENDER - Original Blender algorithm
- PERLIN - Ken Perlin's original (1985) algorithm
- IMPROVEDPERLIN - Ken Perlin's newer (2002) algorithm
- VORONOIF1 - none
- VORONOIF2 - none
- VORONOIF3 - none
- VORONOIF4 - none
- VORONOIF2F1 - none
- VORONOICRACKLE - none
- CELLNOISE - Steven Worley's cellular basis algorithm (1996)
@type BlendModes: readonly dictionary
@var BlendModes: The available texture blending modes:
- MIX - mix texture with value
- MULTIPLY - multiply texture with value
- ADD - add texture to value
- SUBTRACT - subtract texture from value
- DIVIDE - divide value by texture
- DARKEN - replace value with texture if texture is darker
- DIFFERENCE - difference of texture from value
- LIGHTEN - replace value with texture if texture is lighter
- SCREEN - 'screen' mode
@type Mappings: readonly dictionary
@var Mappings: The available 2D texture coordinate mappings for images:
- FLAT - flat projection
- CUBE - cube projection
- TUBE - cylindrical projection
- SPHERE - spherical projection
@type Proj: readonly dictionary
@var Proj: The available projections per axis:
- NONE - axis isn't used
- X - axis is used as final x axis
- Y - axis is used as final y axis
- Z - axis is used as final z axis
@type STypes: readonly dictionary
@var STypes: Texture-type specific data. Depending on the value of
Texture.type, certain groups will make sense. For instance, when a texture
is of type CLOUD, the CLD_xxx stypes can be used. Note that the first
value in each group is the default.
1. Clouds type
- CLD_DEFAULT - Monochromatic noise
- CLD_COLOR - RGB noise
2. Wood type
- WOD_BANDS - Use standard wood texture
- WOD_RINGS - Use wood rings
- WOD_BANDNOISE - Add noise to standard wood
- WOD_RINGNOISE - Add noise to rings
3. Magic type
- MAG_DEFAULT - Magic has no STypes
4. Marble type
- MBL_SOFT - Use soft marble
- MBL_SHARP - Use more clearly defined marble
- MBL_SHARPER - Use very clearly dfefined marble
5. Blend type
- BLN_LIN - Use a linear progression
- BLN_QUAD - Use a quadratic progression
- BLN_EASE - Uses a more complicated blend function
- BLN_DIAG - Use a diagonal progression
- BLN_SPHERE - Use a progression with the shape of a sphere
- BLN_HALO - Use a quadratic progression with the shape of a sphere
6. Stucci type
- STC_PLASTIC - Standard stucci
- STC_WALLIN - Creates dimples
- STC_WALLOUT - Creates ridges
7. Noise type
- NSE_DEFAULT - Noise has no STypes
8. Image type
- IMG_DEFAULT - Image has no STypes
9. Plugin type
- PLG_DEFAULT - Plugin has no STypes
10. Envmap type
- ENV_STATIC - Calculate map only once
- ENV_ANIM - Calculate map each rendering
- ENV_LOAD - Load map from disk
11. Musgrave type
- MUS_MFRACTAL - Hetero Multifractal
- MUS_RIDGEDMF - Ridged Multifractal
- MUS_HYBRIDMF - Hybrid Multifractal
- MUS_FBM - Fractal Brownian Motion
- MUS_HTERRAIN - Hetero Terrain
12. Voronoi type
- VN_INT - Only calculate intensity
- VN_COL1 - Color cells by position
- VN_COL2 - Same as Col1 plus outline based on F2-F1
- VN_COL3 - Same as Col2 multiplied by intensity
13. Distorted noise type
- DN_BLENDER - Original Blender algorithm
- DN_PERLIN - Ken Perlin's original (1985) algorithm
- DN_IMPROVEDPERLIN - Ken Perlin's newer (2002) algorithm
- DN_VORONOIF1 - none
- DN_VORONOIF2 - none
- DN_VORONOIF3 - none
- DN_VORONOIF4 - none
- DN_VORONOIF2F1 - none
- DN_VORONOICRACKLE - none
- DN_CELLNOISE - Steven Worley's cellular basis algorithm (1996)
@var TexCo: Flags for MTex.texco.
- ORCO - Use the original coordinates of the mesh
- REFL - Use reflection vector as texture coordinates
- NOR - Use normal vector as texture coordinates
- GLOB - Use global coordinates for the texture coordinates
- UV - Use UV coordinates for texture coordinates
- OBJECT - Use linked object's coordinates for texture coordinates
- WIN - Use screen coordinates as texture coordinates
- VIEW - Pass camera view vector on to the texture (World texture only!)
- STICK - Use mesh sticky coordinates for the texture coordinates
- STRESS - Use mesh stress coordinates for the texture coordinates
- TANGENT - Use mesh tangent coordinates for the texture coordinates
@type TexCo: readonly dictionary
@var MapTo: Flags for MTex.mapto.
- COL - Make the texture affect the basic colour of the material
- NOR - Make the texture affect the rendered normal
- CSP - Make the texture affect the specularity colour
- CMIR - Make the texture affect the mirror colour
- REF - Make the texture affect the diffuse reflectivity value
- SPEC - Make the texture affect the specularity value
- HARD - Make the texture affect the hardness value
- ALPHA - Make the texture affect the alpha value
- EMIT - Make the texture affect the emit value
- RAYMIR - Make the texture affect the mirror reflectivity value
- DISP - Make the texture displace the mesh
- TRANSLU - Make the texture affect the translucency value
- AMB - Make the texture affect the ambient value
- WARP - Make the texture affect texture coordinates for the following textures
@type MapTo: readonly dictionary
"""
def New (name = 'Tex'):
"""
Create a new Texture object.
@type name: string
@param name: The Texture name.
@rtype: Blender Texture
@return: The created Texture object.
"""
def Get (name = None):
"""
Get the Texture object(s) from Blender.
@type name: string
@param name: The name of the Texture.
@rtype: Blender Texture or a list of Blender Textures
@return: It depends on the I{name} parameter:
- (name): The Texture object with the given I{name};
- (): A list with all Texture objects in the current scene.
"""
from IDProp import IDGroup, IDArray
class Texture:
"""
The Texture object
==================
This object gives access to Texture-specific data in Blender.
Note that many of the attributes of this object are only relevant for
specific texture types.
@ivar animFrames: Number of frames of a movie to use.
Value is clamped to the range [0,300000].
@type animFrames: int
@ivar animOffset: Offsets the number of the first movie frame to use.
Value is clamped to the range [-300000,300000].
@type animOffset: int
@ivar animStart: Starting frame of the movie to use.
Value is clamped to the range [1,300000].
@type animStart: int
@ivar anti: Image anti-aliasing enabled. Also see L{ImageFlags}.
@type anti: int
@ivar brightness: Changes the brightness of a texture's color.
Value is clamped to the range [0.0,2.0].
@type brightness: float
@ivar calcAlpha: Calculation of image's alpha channel enabled. Also see L{ImageFlags}.
@type calcAlpha: int
@ivar contrast: Changes the contrast of a texture's color.
Value is clamped to the range [0.01,5.0].
@type contrast: float
@ivar crop: Sets the cropping extents (for image textures).
@type crop: tuple of 4 ints
@ivar cyclic: Looping of animated frames enabled. Also see L{ImageFlags}.
@type cyclic: boolean
@ivar distAmnt: Amount of distortion (for distorted noise textures).
Value is clamped to the range [0.0,10.0].
@type distAmnt: float
@ivar distMetric: The distance metric (for Voronoi textures).
@type distMetric: int
@ivar exp: Minkovsky exponent (for Minkovsky Voronoi textures).
Value is clamped to the range [0.01,10.0].
@type exp: float
@ivar extend: Texture's 'Extend' mode (for image textures). See L{ExtendModes}.
@type extend: int
@ivar fields: Use of image's fields enabled. Also see L{ImageFlags}.
@type fields: int
@ivar fieldsPerImage: Number of fields per rendered frame.
Value is clamped to the range [1,200].
@type fieldsPerImage: int
@ivar filterSize: The filter size (for image and envmap textures).
Value is clamped to the range [0.1,25.0].
@type filterSize: float
@ivar flags: Texture's 'Flag' bitfield. See L{Flags}.
bitmask.
@type flags: int
@ivar hFracDim: Highest fractional dimension (for Musgrave textures).
Value is clamped to the range [0.0001,2.0].
@type hFracDim: float
@ivar iScale: Intensity output scale (for Musgrave and Voronoi textures).
Value is clamped to the range [0.0,10.0].
@type iScale: float
@ivar image: Texture's image object.
@type image: Blender Image (or None)
@ivar imageFlags: Texture's 'ImageFlags' bits.
@type imageFlags: int
@ivar interpol: Interpolate image's pixels to fit texture mapping enabled. Also see L{ImageFlags}.
@type interpol: int
@ivar ipo: Texture Ipo data.
Contains the Ipo if one is assigned to the object, B{None} otherwise. Setting to B{None} clears the current Ipo..
@type ipo: Blender Ipo
@ivar lacunarity: Gap between succesive frequencies (for Musgrave textures).
Value is clamped to the range [0.0,6.0].
@type lacunarity: float
@ivar mipmap: Mipmaps enabled. Also see L{ImageFlags}.
@type mipmap: int
@ivar movie: Movie frames as images enabled. Also see L{ImageFlags}.
@type movie: int
@ivar noiseBasis: Noise basis type (wood, stucci, marble, clouds,
Musgrave, distorted). See L{Noise} dictionary.
@type noiseBasis: int
@ivar noiseBasis2: Additional noise basis type (wood, marble, distorted
noise). See L{Noise} dictionary.
@type noiseBasis2: int
@ivar noiseDepth: Noise depth (magic, marble, clouds).
Value is clamped to the range [0,6].
@type noiseDepth: int
@ivar noiseSize: Noise size (wood, stucci, marble, clouds, Musgrave,
distorted noise).
Value is clamped to the range [0.0001,2.0].
@type noiseSize: float
@ivar noiseType: Noise type (for wood, stucci, marble, clouds textures). Valid values are 'hard' or 'soft'.
@type noiseType: string
@ivar normalMap: Use of image RGB values for normal mapping enabled.
Also see L{ImageFlags}.
@type normalMap: int
@ivar octs: Number of frequencies (for Musgrave textures).
Value is clamped to the range [0.0,8.0].
@type octs: float
@ivar repeat: Repetition multiplier (for image textures).
@type repeat: tuple of 2 ints
@ivar rgbCol: RGB color tuple.
@type rgbCol: tuple of 3 floats
@ivar rot90: X/Y flip for rendering enabled. Also see L{ImageFlags}.
@type rot90: int
@ivar saw: Produce bands using saw wave (marble, wood textures). Also see L{Noise}.
@type saw: int
@ivar sine: Produce bands using sine wave (marble, wood textures). Also see L{Noise}.
@type sine: int
@ivar stField: Standard field deinterlacing enabled. Also see L{ImageFlags}.
@type stField: int
@ivar stype: Texture's 'SType' mode. See L{STypes}.
@type stype: int
@ivar tri: Produce bands using triangle wave (marble, wood textures). Also see L{Noise}.
@type tri: int
@ivar turbulence: Turbulence (for magic, wood, stucci, marble textures).
Value is clamped to the range [0.0,200.0].
@type turbulence: float
@ivar type: Texture's 'Type' mode. See L{Types}.
Value must be in the range [0,13].
@type type: int
@ivar useAlpha: Use of image's alpha channel enabled. Also see L{ImageFlags}.
@type useAlpha: int
@ivar weight1: Weight 1 (for Voronoi textures).
Value is clamped to the range [-2.0,2.0].
@type weight1: float
@ivar weight2: Weight 2 (for Voronoi textures).
Value is clamped to the range [-2.0,2.0].
@type weight2: float
@ivar weight3: Weight 3 (for Voronoi textures).
Value is clamped to the range [-2.0,2.0].
@type weight3: float
@ivar weight4: Weight 4 (for Voronoi textures).
Value is clamped to the range [-2.0,2.0].
@type weight4: float
@ivar colorband: Texture colorband, a list of colors,
each color a list of 5 floats [0 - 1], [r,g,b,a,pos].
The colorband can have between 1 and 31 colors.
@type colorband: list
@ivar autoRefresh: Refresh image on frame changes enabled.
@type autoRefresh: boolean
"""
def getExtend():
"""
Get the extend mode of the texture. See L{setExtend}.
@rtype: string.
"""
def getImage():
"""
Get the Image associated with this texture (or None).
@rtype: Blender Image
"""
def getName():
"""
Get the name of this Texture object.
@rtype: string
"""
def getType():
"""
Get this Texture's type. See L{setType}.
@rtype: string
"""
def setExtend(extendmode):
"""
Set the extend mode of this texture (only used for IMAGE textures)
@param extendmode: The new extend mode. One of:
'Extend', 'Clip', 'ClipCube' and 'Repeat'
@type extendmode: string
"""
def setFlags(f1=None, f2=None, f3=None, f4=None):
"""
Set this object's flags.
@param f1,f2,f3,f4: Flags to be set (omitted flags are cleared). Can be any of
'FlipBlendXY', 'NegAlpha', 'CheckerOdd', and 'CheckerEven'
@type f1,f2,f3,f4: string
"""
def setImage(image):
"""
Set the Image of this texture.
@param image: The new Image.
@type image: Blender Image
@warning: This sets the texture's type to 'Image' if it is not already.
"""
def setImageFlags(f1=None, f2=None, f3=None, etc=None):
"""
Set the Image flags (only makes sense for IMAGE textures). Omitted
flags are cleared.
@param f1, f2, f3, etc: Flag to set. See L{ImageFlags} for their meanings. Can be
any of: 'InterPol', 'UseAlpha', 'MipMap', 'Fields', 'Rot90',
'CalcAlpha', 'Cyclic', 'Movie', 'StField', 'Anti' and 'NormalMap'
@type f1, f2, f3, etc: string
"""
def setName(name):
"""
Set the name of this Texture object.
@param name: The new name.
@type name: string
"""
def setSType(stype):
"""
Set the SType.
@param stype: The new stype. This can be any of the values listed in
L{STypes} or 'Default' which sets the stype to the default value.
@type stype: string
@note: the set of valid parameters is dependent on the current
texture type. Be sure to always set the texture type B{before}
setting the texture's stype; otherwise an exception might occur.
"""
def setType(type):
"""
Set this Texture's type.
@param type: The new type. Possible options are:
'None', 'Clouds', 'Wood', 'Marble', 'Magic', 'Blend', 'Stucci',
'Noise', 'Image', 'Plugin', 'EnvMap', 'Musgrave', 'Voronoi'
and 'DistNoise'
@type type: string
"""
def evaluate(coord):
"""
Evaluates the texture at this location and returns the result.
The return value is a 4D vector where (x,y,z,w) are (red, green, blue, intensity)
For greyscale textures, often intensity only will be used.
@type coord: vector
"""
import id_generics
Texture.__doc__ += id_generics.attributes
class MTex:
"""
The MTex Object
===============
This object links a material to a texture. It allows the same texture to be
used in several different ways.
@ivar tex: The Texture this is linked to.
@type tex: Blender Texture
@ivar texco: Texture coordinates ("Map input"). See L{TexCo}
@ivar mapto: "Map to" field of texture. OR'd values of L{MapTo}
@ivar object: Object whose space to use when texco is Object
@type object: Blender Object
@ivar col: Color that the texture blends with
@ivar dvar: Value that the texture blends with when not blending colors
@ivar blendmode: Texture blending mode. L{BlendModes}
@ivar colfac: Factor by which texture affects color
@ivar norfac: Factor by which texture affects normal
@ivar varfac: Factor by which texture affects most variables
@ivar dispfac: Factor by which texture affects displacement
@ivar warpfac: Factor by which texture affects warp
@ivar ofs: Offset to adjust texture space
@ivar size: Size to scale texture space
@ivar mapping: Mapping of texture coordinates (flat, cube, etc.). L{Mappings}
@ivar stencil: Stencil mode
@ivar neg: Negate texture values mode
@ivar noRGB: Convert texture RGB values to intensity values
@ivar correctNor: Correct normal mapping for Texture space and Object space
@ivar xproj: Projection of X axis to Texture space. L{Proj}
@ivar yproj: Projection of Y axis to Texture space. L{Proj}
@ivar zproj: Projection of Z axis to Texture space. L{Proj}
@ivar mtCol: How texture maps to color
@ivar mtNor: How texture maps to normals
@ivar mtCsp: How texture maps to specularity color
@ivar mtCmir: How texture maps to mirror color
@ivar mtRef: How texture maps to reflectivity
@ivar mtSpec: How texture maps to specularity
@ivar mtEmit: How texture maps to emit value
@ivar mtAlpha: How texture maps to alpha value
@ivar mtHard: How texture maps to hardness
@ivar mtRayMir: How texture maps to RayMir value
@ivar mtTranslu: How texture maps to translucency
@ivar mtAmb: How texture maps to ambient value
@ivar mtDisp: How texture maps to displacement
@ivar mtWarp: How texture maps to warp
"""
def getIpo():
"""
Get the Ipo associated with this texture object, if any.
@rtype: Ipo
@return: the wrapped ipo or None.
"""
def setIpo(ipo):
"""
Link an ipo to this texture object.
@type ipo: Blender Ipo
@param ipo: a "texture data" ipo.
"""
def clearIpo():
"""
Unlink the ipo from this texture object.
@return: True if there was an ipo linked or False otherwise.
"""

View File

@@ -0,0 +1,211 @@
# Blender.Window.Theme submodule and the Theme PyType object
"""
The Blender.Window.Theme submodule.
Theme
=====
This module provides access to B{Theme} objects in Blender.
Example::
# this is a simplified version of the save_theme.py script
# shipped with Blender:
import Blender
from Blender.Window import Theme, FileSelector
theme = Theme.Get()[0] # get current theme
def write_theme(filename):
"Write the current theme as a BPython script"
f = file(filename, "w")
f.write("import Blender")
f.write("from Blender.Window import Theme")
f.write("theme = Theme.New('%s')" % theme.name)
for tsp in theme.get(): # write each theme space
command = "\\n%s = theme.get('%s')" % (tsp, tsp)
f.write(command + "\\n")
exec(command)
exec("vars = dir(%s)" % tsp)
vars.remove('theme')
for var in vars: # write each variable from each theme space
v = "%s.%s" % (tsp, var)
exec("value = %s" % v)
f.write("%s = %s\\n" % (v, value))
f.write('\\nBlender.Redraw(-1)') # redraw to update the screen
f.close()
FileSelector(write_theme, "Save Current Theme", default_fname)
"""
def New (name = "New Theme", theme = '<default>'):
"""
Create a new Theme object.
@type name: string
@param name: The name of the new theme.
@type theme: Blender Theme
@param theme: a base theme to copy all data from. It defaults to the current
one.
@rtype: Blender Theme
@return: A new Blender Theme object.
"""
def Get (name = None):
"""
Get the Theme object(s) from Blender.
@type name: string
@param name: The name of the Theme object.
@rtype: Blender Theme or a list of Blender Themes
@return: It depends on the I{name} parameter:
- (name): The Theme object called I{name}, None if not found;
- (): A list with all Theme objects currently in Blender.
"""
class Theme:
"""
The Theme object
================
This object gives access to Themes in Blender. Each Theme object is
composed of one UI (Use Interface) theme and many Space themes
(3d view, Text Editor, Buttons window, etc).
@ivar name: The name of this Theme object.
"""
def getName():
"""
Get the name of this Theme object.
@rtype: string
@return: the name of this Theme object.
"""
def setName(s):
"""
Rename this theme.
@type s: string
@param s: the new name.
"""
def get(t = None):
"""
Get a space or the ui (sub)theme from this Theme.
@type t: string, int or None
@param t: the wanted sub-theme as either:
- int: -1 for UI or the types in L{Window.Types<Window.Types>} for the others;
- string: use get() to know them (they are case insensitive);
- nothing: as written above, get() returns a list of names.
@rtype: Blender ThemeSpace or ThemeUI or list of sub-theme types as strings.
@return: It depends on the given parameter:
- (): a list with all available types, as strings;
- (type): the chosen sub-theme.
"""
class ThemeUI:
"""
The User Interface sub-theme
============================
This can be accessed with theme.get(t), where t can be 'ui' or -1.
The available variables follow the internal (C coded) ThemeUI struct in
Blender. Most of them represent rgba (red, green, blue, alpha) colors,
with each component in the range [0, 255]. There is more than one way to
access them.
Examples::
print outline.R
outline.r = 180 # it's case insensitive
outline[0] = 94 # 0 for red, 1 for green, ...
outline = [200, 200, 200, 255] # setting all components at once
@type theme: string
@ivar theme: the parent Theme for this object.
@ivar outline: theme rgba var.
@ivar neutral: theme rgba var.
@ivar action: theme rgba var.
@ivar setting: theme rgba var.
@ivar setting1: theme rgba var.
@ivar setting2: theme rgba var.
@ivar num: theme rgba var.
@ivar textfield: theme rgba var.
@ivar textfield_hi: theme rgba var.
@ivar popup: theme rgba var.
@ivar text: theme rgba var.
@ivar text_hi: theme rgba var.
@ivar menu_back: theme rgba var.
@ivar menu_item: theme rgba var.
@ivar menu_hilite: theme rgba var.
@ivar menu_text: theme rgba var.
@ivar menu_text_hi: theme rgba var.
@type drawType: int
@ivar drawType: the draw type (minimal, rounded, etc) in the range [1, 4].
@type iconTheme: string
@ivar iconTheme: the filename (without path) for the icon theme PNG in .blender/icons/
"""
class ThemeSpace:
"""
The Space sub-themes
====================
There is a sub-theme for each space in Blender (except for the Scripts
window, but it will be added soon). Please read the information about
L{Theme.ThemeUI}, since it is also relevant here. In Blender,
all theme spaces share the same C structure. For this reason, all of
them here share the same variables, event though some spaces only use
a few of them. This lower-level access is acceptable because generally
users will prefer to use the interface to change single theme options
and only use scripting to save or restore themes. But anyway, checking
the Themes tab in the User Preferences space in Blender and using the
bundled "Save current theme" script (or its simplified version written
on the top of this page) can help you finding out any specific info you
may need.
@type theme: string
@ivar theme: the parent Theme for this object.
@ivar back: theme rgba var.
@ivar text: theme rgba var.
@ivar text_hi: theme rgba var.
@ivar header: theme rgba var.
@ivar panel: theme rgba var.
@ivar shade1: theme rgba var.
@ivar shade2: theme rgba var.
@ivar hilite: theme rgba var.
@ivar grid: theme rgba var.
@ivar wire: theme rgba var.
@ivar select: theme rgba var.
@ivar active: theme rgba var.
@ivar transform: theme rgba var.
@ivar vertex: theme rgba var.
@ivar vertex_select: theme rgba var.
@ivar edge: theme rgba var.
@ivar edge_select: theme rgba var.
@ivar edge_seam: theme rgba var.
@ivar edge_facesel: theme rgba var.
@ivar face: theme rgba var.
@ivar face_select: theme rgba var.
@ivar face_dot: theme rgba var.
@ivar normal: theme rgba var.
@ivar bone_solid: theme rgba var.
@ivar bon_pose: theme rgba var.
@ivar strip: theme rgba var.
@ivar strip_select: theme rgba var.
@ivar syntaxl: theme rgba var.
@ivar syntaxn: theme rgba var.
@ivar syntaxb: theme rgba var.
@ivar syntaxv: theme rgba var.
@ivar syntaxc: theme rgba var.
@ivar movie: theme rgba var.
@ivar image: theme rgba var.
@ivar scene: theme rgba var.
@ivar audio: theme rgba var.
@ivar effect: theme rgba var.
@ivar plugin: theme rgba var.
@ivar transition: theme rgba var.
@ivar meta: theme rgba var.
@type vertex_size: int
@ivar vertex_size: size of the vertices dots on screen in the range [1, 10].
@type facedot_size: int
@ivar facedot_size: size of the face dots on screen in the range [1, 10].
"""

View File

@@ -0,0 +1,80 @@
# Blender.Scene.TimeLine module
"""
The Blender.Scene.TimeLine submodule.
TimeLine
========
This module gives access to B{Scene TimeLine Contexts} in Blender.
Example::
import Blender
from Blender import Scene
# Only the current scene has a radiosity context.
# Naturally, any scene can be made the current one
# with scene.makeCurrent()
scn = Scene.GetCurrent()
# this is the only way to access the radiosity object:
time_line = scn.getTimeLine ()
time_line.add (50)
time_line.add (100)
time_line.setName (50, 'first')
time_line.setName (100, 'second')
Blender.Redraw(-1)
"""
class TimeLine:
"""
The TimeLine object
===================
This object wraps the current Scene's time line context in Blender.
"""
def add(ival):
"""
add new marker to time line
@type ival: int
@param ival: the frame number.
"""
def delete(ival):
"""
delete frame.
@type ival: int
@param ival: the frame number.
"""
def setName(ival, sval):
"""
set name of frame.
@type ival: int
@type sval: string
@param ival: the frame number.
@param sval: the frame name.
"""
def getName(ival):
"""
Get name of frame.
@type ival: int
@param ival: the frame number.
@rtype: string
@return: the frame name.
"""
def getMarked(ival):
"""
Get name of frame.
@type ival: int
@param ival: the frame number.
@rtype: int|string
@return: the list of frame number or name.
"""

View File

@@ -0,0 +1,70 @@
# The Blender.Types submodule
"""
The Blender.Types submodule
===========================
This module is a dictionary of Blender Python types, for type checking.
Example::
import Blender
from Blender import Types, Object, NMesh, Camera, Lamp
#
objs = Object.Get() # a list of all objects in the current scene
for o in objs:
print
print o, type(o)
data = o.getData()
print type(data)
if type(data) == Types.NMeshType:
if len(data.verts):
print "its vertices are obviously of type:", type(data.verts[0])
print "and its faces:", Types.NMFaceType
elif type(data) == Types.CameraType:
print "It's a Camera."
elif type(data) == Types.LampType:
print "Let there be light!"
@var ObjectType: Blender Object. The base object, linked to its specific data
at its .data member variable.
@var GroupType: Blender Group. A Group that references a list of objects that are a part of this group.
@var NMeshType: Blender NMesh. The mesh structure.
@var NMFaceType: Blender NMFace. A mesh face, with one (a point), two (an edge),
three (a triangular face) or four (a quad face) vertices.
@var NMVertType: Blender NMVert. A mesh vertex.
@var NMColType: Blender NMCol. A mesh rgba color.
@var MeshType: Blender Mesh. The mesh structure.
@var MFaceType: Blender MFace. A mesh face, with
three (a triangular face) or four (a quad face) vertices.
@var MEdgeType: Blender MEdge. A mesh edge, with two vertices
@var MVertType: Blender MVert. A mesh vertex which wraps a Blender mesh vertex
(typically an object returned from the mesh.verts sequence).
@var PVertType: Blender MVert. A mesh vertex which does not wrap a Blender
mesh vertex (returned from L{Blender.Mesh.MVert()<Mesh.MVert.__init__>}).
@var MColType: Blender MCol. A mesh rgba color.
@var ArmatureType: Blender Armature. The "skeleton", for animating and deforming
objects.
@var BoneType: Blender Bone. Bones are, obviously, the "pieces" of an Armature.
@var CurveType: Blender Curve.
@var IpoType: Blender Ipo.
@var MetaballType: Blender Metaball.
@var CameraType: Blender Camera.
@var ImageType: Blender Image.
@var LampType: Blender Lamp.
@var TextType: Blender Text.
@var Text3dType: Blender Text3d.
@var MaterialType: Blender Material.
@var SceneType: A Blender Scene. Container of all other objects.
@var ButtonType: Blender Button. One of the Draw widgets.
@var vectorType: Blender vector. Used in NMesh, Mesh and elsewhere.
@var matrix_Type: Blender matrix.
@var quaternionType: Blender quaternion. Used in armatures.
@var eulerType: Blender euler.
@var bufferType: Blender buffer. A contiguous piece of storage, used in BGL.
@var constantType: Blender constant. A constant dictionary.
@var rgbTupleType: Blender rgbTuple. A (red, green, blue) triplet.
@var TextureType: Blender Texture.
@var MTexType: Blender MTex. Links materials to a texture.
@var IDGroupType: Blender IDProperty Group type.
@var IDArrayType: Blender IDProperty Array type.
"""

View File

@@ -0,0 +1,524 @@
# Blender.Window module and the Window PyType object
"""
The Blender.Window submodule.
B{New}: renamed ViewLayer to L{ViewLayers} (actually added an alias, so both
forms will work).
Window
======
This module provides access to B{Window} functions in Blender.
Example:
--------
FileSelector::
import Blender
from Blender import Window
#
def my_callback(filename): # callback for the FileSelector
print "You chose the file:", filename # do something with the chosen file
#
Window.FileSelector (my_callback, "Choose one!")
Example:
--------
DrawProgressBar::
import Blender
from Blender.Window import DrawProgressBar
#
# substitute the bogus_*() function calls for your own, of course.
#
DrawProgressBar (0.0, "Importing data ...")
bogus_importData()
DrawProgressBar (0.3, "Building something")
bogus_build()
DrawProgressBar (0.8, "Updating Blender")
bogus_update()
DrawProgressBar (1.0, "Finished")
#
# another example:
#
number = 1
while number < 20:
file = filename + "00%d" % number
DrawProgressBar (number / 20.0, "Loading texture: %s" % file)
Blender.Image.Load(file)
number += 1
DrawProgressBar (1.0, "Finished loading")
@type Types: readonly dictionary
@var Types: The available Window Types.
- ACTION
- BUTS
- FILE
- IMAGE
- IMASEL
- INFO
- IPO
- NLA
- OOPS
- SCRIPT
- SEQ
- SOUND
- TEXT
- VIEW3D
@type Qual: readonly dictionary
@var Qual: Qualifier keys (shift, control, alt) bitmasks.
- LALT: left ALT key
- RALT: right ALT key
- ALT: any ALT key, ...
- LCTRL
- RCTRL
- CTRL
- LSHIFT
- RSHIFT
- SHIFT
@type MButs: readonly dictionary
@var MButs: Mouse buttons.
- L: left mouse button
- M: middle mouse button
- R: right mouse button
@warn: The event system in Blender needs a rewrite, though we don't know when that will happen. Until then, event related functions here (L{QAdd}, L{QRead},
L{QHandle}, etc.) can be used, but they are actually experimental and can be
substituted for a better method when the rewrite happens. In other words, use
them at your own risk, because though they should work well and allow many
interesting and powerful possibilities, they can be deprecated in some future
version of Blender / Blender Python.
"""
def Redraw (spacetype = '<Types.VIEW3D>'):
"""
Force a redraw of a specific space type.
@type spacetype: int
@param spacetype: the space type, see L{Types}. By default the 3d Views are
redrawn. If spacetype < 0, all currently visible spaces are redrawn.
"""
def RedrawAll ():
"""
Redraw all windows.
"""
def QRedrawAll ():
"""
Redraw all windows by queue event.
"""
def FileSelector (callback, title = 'SELECT FILE', filename = '<default>'):
"""
Open the file selector window in Blender. After the user selects a filename,
it is passed as parameter to the function callback given to FileSelector().
Example::
import Blender
#
def my_function(filename):
print 'The selected file was:', filename
#
Blender.Window.FileSelector (my_function, 'SAVE FILE')
@type callback: function that accepts a string: f(str)
@param callback: The function that must be provided to FileSelector() and
will receive the selected filename as parameter.
@type title: string
@param title: The string that appears in the button to confirm the selection
and return from the file selection window.
@type filename: string
@param filename: A filename. This defaults to Blender.Get('filename').
@warn: script links are not allowed to call the File / Image Selectors. This
is because script links global dictionaries are removed when they finish
execution and the File Selector needs the passed callback to stay around.
An alternative is calling the File Selector from another script (see
L{Blender.Run}).
"""
def ImageSelector (callback, title = 'SELECT IMAGE', filename = '<default>'):
"""
Open the image selector window in Blender. After the user selects a filename,
it is passed as parameter to the function callback given to ImageSelector().
Example::
import Blender
#
def my_function(imagename):
print 'The selected image was:', imagename
#
Blender.Window.ImageSelector (my_function, 'LOAD IMAGE')
@type callback: function that accepts a string: f(str)
@param callback: The function that must be provided to ImageSelector() and
will receive the selected filename as parameter.
@type title: string
@param title: The string that appears in the button to confirm the selection
and return from the image selection window.
@type filename: string
@param filename: A filename. This defaults to L{Blender.Get}('filename').
@warn: script links are not allowed to call the File / Image Selectors. This
is because script links global dictionaries are removed when they finish
execution and the File Selector needs the passed callback to stay around.
An alternative is calling the File Selector from another script (see
L{Blender.Run}).
"""
def DrawProgressBar (done, text):
"""
Draw a progress bar in the upper right corner of the screen. To cancel it
prematurely, users can press the "Esc" key. Start it with done = 0 and end
it with done = 1.
@type done: float
@param done: A float in [0.0, 1.0] that tells the advance in the progress
bar.
@type text: string
@param text: Info about what is currently being done "behind the scenes".
"""
def GetCursorPos ():
"""
Get the current 3d cursor position.
@rtype: list of three floats
@return: the current position: [x, y, z].
"""
def GetActiveLayer ():
"""
Get the bitmask for the active layer.
@note: if there is no 3d view it will return zero.
@rtype: int
@return: layer bitmask
"""
def SetActiveLayer(layermask):
"""
Set the bitmask for the active layer.
@type layermask: int
@param layermask: An integer bitmask, to use humanly readable values do (1<<0) for the first layer, (1<<19) for the last layer.
"""
def SetCursorPos (coords):
"""
Change the 3d cursor position.
@type coords: 3 floats or a list of 3 floats
@param coords: The new x, y, z coordinates.
@note: if visible, the 3d View must be redrawn to display the change. This
can be done with L{Redraw}.
"""
def WaitCursor (bool):
"""
Set cursor to wait or back to normal mode.
Example::
Blender.Window.WaitCursor(1)
Blender.sys.sleep(2000) # do something that takes some time
Blender.Window.WaitCursor(0) # back
@type bool: int (bool)
@param bool: if nonzero the cursor is set to wait mode, otherwise to normal
mode.
@note: when the script finishes execution, the cursor is set to normal by
Blender itself.
"""
def GetViewVector ():
"""
Get the current 3d view vector.
@rtype: list of three floats
@return: the current vector: [x, y, z].
"""
def GetViewMatrix ():
"""
Get the current 3d view matrix.
@rtype: 4x4 float matrix (WRAPPED DATA)
@return: the current matrix.
"""
def GetPerspMatrix ():
"""
Get the current 3d perspective matrix.
@rtype: 4x4 float matrix (WRAPPED DATA)
@return: the current matrix.
"""
def EditMode(enable = -1, undo_msg = 'From script', undo = 1):
"""
Get and optionally set the current edit mode status: in or out.
Example::
in_editmode = Window.EditMode()
# MUST leave edit mode before changing an active mesh:
if in_editmode: Window.EditMode(0)
# ...
# make changes to the mesh
# ...
# be nice to the user and return things to how they were:
if in_editmode: Window.EditMode(1)
@type enable: int
@param enable: get/set current status:
- -1: just return current status (default);
- 0: leave edit mode;
- 1: enter edit mode.
It's not an error to try to change to a state that is already the
current one, the function simply ignores the request.
@type undo_msg: string
@param undo_msg: only needed when exiting edit mode (EditMode(0)). This
string is used as the undo message in the Mesh->Undo History submenu in
the 3d view header. Max length is 63, strings longer than that get
clamped.
@param undo: don't save Undo information (only needed when exiting edit
mode).
@type undo: int
@rtype: int (bool)
@return: 0 if Blender is not in edit mode right now, 1 otherwise.
@warn: this is an important function. NMesh operates on normal Blender
meshes, not edit mode ones. If a script changes an active mesh while in
edit mode, when the user leaves the mode the changes will be lost,
because the normal mesh will be rebuilt based on its unchanged edit mesh.
"""
def PoseMode(enable = -1):
"""
Get and optionally set the current pose mode status: in or out.
@type enable: int
@param enable: get/set current status:
- -1: just return current status (default);
- 0: leave edit mode;
- 1: enter edit mode.
@return: 0 if Blender is not in edit mode right now, 1 otherwise.
@warn: This uses the active armature objects posemode status, enabling pose
mode for non armature objects will always fail.
"""
def ViewLayers (layers = [], winid = None):
"""
Get and optionally set the currently visible layers in all 3d Views.
@type layers: list of ints
@param layers: a list with indexes of the layers that will be visible. Each
index must be in the range [1, 20]. If not given or equal to [], the
function simply returns the visible ones without changing anything.
@type winid: window id from as redurned by GetScreenInfo
@param winid: An optional argument to set the layer of a window
rather then setting the scene layers. For this to display in the 3d view
the layer lock must be disabled (unlocked).
@rtype: list of ints
@return: the currently visible layers.
"""
def GetViewQuat ():
"""
Get the current VIEW3D view quaternion values.
@rtype: list of floats
@return: the quaternion as a list of four float values.
"""
def SetViewQuat (quat):
"""
Set the current VIEW3D view quaternion.
@type quat: floats or list of floats
@param quat: four floats or a list of four floats.
"""
def GetViewOffset ():
"""
Get the current VIEW3D offset values.
@rtype: list of floats
@return: a list with three floats: [x,y,z].
@note: The 3 values returned are flipped in comparison object locations.
"""
def SetViewOffset (ofs):
"""
Set the current VIEW3D offset values.
@type ofs: 3 floats or list of 3 floats
@param ofs: the new view offset values.
@note: The value you give flipped in comparison object locations.
"""
def CameraView (camtov3d = 0):
"""
Set the current VIEW3D view to the active camera's view. If there's no
active object or it is not of type 'Camera', the active camera for the
current scene is used instead.
@type camtov3d: int (bool)
@param camtov3d: if nonzero it's the camera that gets positioned at the
current view, instead of the view being changed to that of the camera.
"""
def QTest ():
"""
Check if there are pending events in the event queue.
@rtype: int
@return: 0 if there are no pending events, non-zero otherwise.
"""
def QRead ():
"""
Get the next pending event from the event queue.
Example::
# let's catch all events and move the 3D Cursor when user presses
# the left mouse button.
from Blender import Draw, Window
v3d = Window.GetScreenInfo(Window.Types.VIEW3D)
id = v3d[0]['id'] # get the (first) VIEW3D's id
done = 0
while not done: # enter a 'get event' loop
evt, val = Window.QRead() # catch next event
if evt in [Draw.MOUSEX, Draw.MOUSEY]:
continue # speeds things up, ignores mouse movement
elif evt in [Draw.ESCKEY, Draw.QKEY]: done = 1 # end loop
elif evt == Draw.SPACEKEY:
Draw.PupMenu("Hey!|What did you expect?")
elif evt == Draw.Redraw: # catch redraw events to handle them
Window.RedrawAll() # redraw all areas
elif evt == Draw.LEFTMOUSE: # left button pressed
Window.QAdd(id, evt, 1) # add the caught mouse event to our v3d
# actually we should check if the event happened inside that area,
# using Window.GetMouseCoords() and v3d[0]['vertices'] values.
Window.QHandle(id) # process the event
# do something fancy like putting some object where the
# user positioned the 3d cursor, then:
Window.Redraw() # show the change in the VIEW3D areas.
@rtype: list
@return: [event, val], where:
- event: int - the key or mouse event (see L{Draw});
- val: int - 1 for a key press, 0 for a release, new x or y coordinates
for mouse movement events.
"""
def QAdd (win, event, val, after = 0):
"""
Add an event to some window's (actually called areas in Blender) event queue.
@type win: int
@param win: the window id, see L{GetScreenInfo}.
@type event: positive int
@param event: the event to add, see events in L{Draw}.
@type val: int
@param val: 1 for a key press, 0 for a release.
@type after: int (bool)
@param after: if nonzero the event is put after the current queue and added
later.
"""
def QHandle (winId):
"""
Process immediately all pending events for the given window (area).
@type winId: int
@param winId: the window id, see L{GetScreenInfo}.
@note: see L{QAdd} for how to send events to a particular window.
"""
def GetMouseCoords ():
"""
Get mouse's current screen coordinates.
@rtype: list with two ints
@return: a [x, y] list with the coordinates.
"""
def SetMouseCoords (coords):
"""
Set mouse's current screen coordinates.
@type coords: (list of) two ints
@param coords: can be passed as x, y or [x, y] and are clamped to stay inside
the screen. If not given they default to the coordinates of the middle
of the screen.
"""
def GetMouseButtons ():
"""
Get the current mouse button state (see / compare against L{MButs}).
@rtype: int
@return: an OR'ed flag with the currently pressed buttons.
"""
def GetKeyQualifiers ():
"""
Get the current qualifier keys state (see / compare against L{Qual}).
@rtype: int
@return: an OR'ed combination of values in L{Qual}.
"""
def SetKeyQualifiers (qual):
"""
Fake qualifier keys state. This is useful because some key events require
one or more qualifiers to be active (see L{QAdd}).
@type qual: int
@param qual: an OR'ed combination of values in L{Qual}.
@rtype: int
@return: the current state, that should be equal to 'qual'.
@warn: remember to reset the qual keys to 0 once they are not necessary
anymore.
"""
def GetAreaID ():
"""
Get the current area's ID.
"""
def GetAreaSize ():
"""
Get the current area's size.
@rtype: list with two ints
@return: a [width, height] list.
@note: the returned values are 1 pixel bigger than what L{GetScreenInfo}
returns for the 'vertices' of the same area.
"""
def GetScreenSize ():
"""
Get Blender's screen size.
@rtype: list with two ints
@return: a [width, height] list.
"""
def GetScreens ():
"""
Get the names of all available screens.
@rtype: list of strings
@return: a list of names that can be passed to L{SetScreen}.
"""
def SetScreen (name):
"""
Set as current screen the one with the given name.
@type name: string
@param name: the name of an existing screen. Use L{GetScreens} to get
a list with all screen names.
"""
def GetScreenInfo (type = -1, rect = 'win', screen = ''):
"""
Get info about the current screen setup.
@type type: int
@param type: the space type (see L{Types}) to restrict the
results to. If -1 (the default), info is reported about all available
areas.
@type rect: string
@param rect: the rectangle of interest. This defines if the corner
coordinates returned will refer to:
- the whole area: 'total'
- only the header: 'header'
- only the window content part (default): 'win'
@type screen: string
@param screen: the name of an available screen. The current one is used by
default.
@rtype: list of dictionaries
@return: a list of dictionaries, one for each area in the screen. Each
dictionary has these keys (all values are ints):
- 'vertices': [xmin, ymin, xmax, ymax] area corners;
- 'win': window type, see L{Types};
- 'id': this area's id.
"""

View File

@@ -0,0 +1,351 @@
# Blender.World module and the World PyType
"""
The Blender.World submodule
B{New}: L{World.clearScriptLinks} accepts a parameter now.
World
=====
The module world allows you to access all the data of a Blender World.
Example::
import Blender
w = Blender.Get('World') #assume there exists a world named "world"
print w.getName()
w.hor = [1,1,.2]
print w.getHor()
Example::
import Blender
from Blender import *
AllWorlds = Blender.World.Get() # returns a list of created world objects
AvailWorlds = len(AllWorlds) # returns the number of available world objects
PropWorld = dir(AllWorlds[0]) # returns the properties of the class world
NameWorld = AllWorlds[0].getName() # get name of the first world object
MiType = AllWorlds[0].getMistype() # get kind of mist from the first world object
MiParam = AllWorlds[0].getMist() # get the parameters intensity, start, end and height of the mist
HorColor = AllWorlds[0].getHor() # horizon color of the first world object
HorColorR = HorColor[0] # get the red channel (RGB) of the horizon color
ZenColor = AllWorlds[0].getZen() # zenith color of the first world object
ZenColorB = ZenColor[2] # get the blue channel (RGB) of the Zenith color
blending = AllWorlds[0].getSkytype() # get the blending modes (real, blend, paper) of the first world object
"""
def New (name):
"""
Creates a new World.
@type name: string
@param name: World's name (optional).
@rtype: Blender World
@return: The created World. If the "name" parameter has not been provided, it will be automatically be set by blender.
"""
def Get (name):
"""
Get an World from Blender.
@type name: string
@param name: The name of the world to retrieve.
@rtype: Blender World or a list of Blender Worlds
@return:
- (name): The World corresponding to the name
- (): A list with all Worlds in the current scene.
"""
def GetCurrent ():
"""
Get the active world of the scene.
@rtype: Blender World or None
"""
class World:
"""
The World object
================
This object gives access to generic data from all worlds in Blender.
Its attributes depend upon its type.
@ivar skytype: type of the sky. Bit 0 : Blend; Bit 1 : Real; Bit 2 : paper.
@ivar mode:
@ivar mistype: type of mist : O : quadratic; 1 : linear; 2 : square
@ivar hor: the horizon color of a world object.
@ivar zen: the zenith color of a world object.
@ivar amb: the ambient color of a world object.
@ivar star: the star parameters of a world object. See getStar for the semantics of these parameters.
@ivar mist: the mist parameters of a world object. See getMist for the semantics of these parameters.
@type ipo: Blender Ipo
@ivar ipo: The world type ipo linked to this world object.
"""
def getRange():
"""
Retrieves the range parameter of a world object.
@rtype: float
@return: the range
"""
def setRange(range):
"""
Sets the range parameter of a world object.
@type range: float
@param range: the new range parameter
@rtype: None
@return: None
"""
def getName():
"""
Retrieves the name of a world object
@rtype: string
@return: the name of the world object.
"""
def setName(name):
"""
Sets the name of a world object.
@type name: string
@param name : the new name.
@rtype: None
@return: None
"""
def getIpo():
"""
Get the Ipo associated with this world object, if any.
@rtype: Ipo
@return: the wrapped ipo or None.
"""
def setIpo(ipo):
"""
Link an ipo to this world object.
@type ipo: Blender Ipo
@param ipo: a "camera data" ipo.
"""
def clearIpo():
"""
Unlink the ipo from this world object.
@return: True if there was an ipo linked or False otherwise.
"""
def getSkytype():
"""
Retrieves the skytype of a world object.
The skytype is a combination of 3 bits : Bit 0 : Blend; Bit 1 : Real; Bit 2 : paper.
@rtype: int
@return: the skytype of the world object.
"""
def setSkytype(skytype):
"""
Sets the skytype of a world object.
See getSkytype for the semantics of the parameter.
@type skytype: int
@param skytype : the new skytype.
@rtype: None
@return: None
"""
def getMode():
"""
Retrieves the mode of a world object.
The mode is a combination of 5 bits:
- Bit 0 : mist simulation
- Bit 1 : starfield simulation
- Bit 2,3 : reserved
- Bit 4 : ambient occlusion
@rtype: int
@return: the mode of the world object.
"""
def setMode(mode):
"""
Sets the mode of a world object.
See getMode for the semantics of the parameter.
@type mode: int
@param mode : the new mode.
@rtype: None
@return: None
"""
def getMistype():
"""
Retrieves the mist type of a world object.
The mist type is an integer 0 : quadratic; 1 : linear; 2 : square.
@rtype: int
@return: the mistype of the world object.
"""
def setMistype(mistype):
"""
Sets the mist type of a world object.
See getMistype for the semantics of the parameter.
@type mistype: int
@param mistype : the new mist type.
@rtype: None
@return: None
"""
def getHor():
"""
Retrieves the horizon color of a world object.
This color is a list of 3 floats.
@rtype: list of three floats
@return: the horizon color of the world object.
"""
def setHor(hor):
"""
Sets the horizon color of a world object.
@type hor: list of three floats
@param hor : the new hor.
@rtype: None
@return: None
"""
def getZen():
"""
Retrieves the zenith color of a world object.
This color is a list of 3 floats.
@rtype: list of three floats
@return: the zenith color of the world object.
"""
def setZen(zen):
"""
Sets the zenith color of a world object.
@type zen: list of three floats
@param zen : the new zenith color.
@rtype: None
@return: None
"""
def getAmb():
"""
Retrieves the ambient color of a world object.
This color is a list of 3 floats.
@rtype: list of three floats
@return: the ambient color of the world object.
"""
def setAmb(amb):
"""
Sets the ambient color of a world object.
@type amb: list of three floats
@param amb : the new ambient color.
@rtype: None
@return: None
"""
def getStar():
"""
Retrieves the star parameters of a world object.
It is a list of nine floats :
red component of the color
green component of the color
blue component of the color
size of the stars
minimal distance between the stars
average distance between the stars
variations of the stars color
@rtype: list of nine floats
@return: the star parameters
"""
def setStar(star):
"""
Sets the star parameters of a world object.
See getStar for the semantics of the parameter.
@type star: list of 9 floats
@param star : the new star parameters.
@rtype: None
@return: None
"""
def getMist():
"""
Retrieves the mist parameters of a world object.
It is a list of four floats :
intensity of the mist
start of the mist
end of the mist
height of the mist
@rtype: list of four floats
@return: the mist parameters
"""
def setMist(mist):
"""
Sets the mist parameters of a world object.
See getMist for the semantics of the parameter.
@type mist: list of 4 floats
@param mist : the new mist parameters.
@rtype: None
@return: None
"""
def getScriptLinks (event):
"""
Get a list with this World's script links of type 'event'.
@type event: string
@param event: "FrameChanged", "Redraw", "Render".
@rtype: list
@return: a list with Blender L{Text} names (the script links of the given
'event' type) or None if there are no script links at all.
"""
def clearScriptLinks (links = None):
"""
Delete script links from this World :). If no list is specified, all
script links are deleted.
@type links: list of strings
@param links: None (default) or a list of Blender L{Text} names.
"""
def addScriptLink (text, event):
"""
Add a new script link to this World.
@type text: string
@param text: the name of an existing Blender L{Text}.
@type event: string
@param event: "FrameChanged", "Redraw" or "Render".
"""
def setCurrent ():
"""
Make this world active in the current scene.
@rtype: None
@return: None
"""
def insertIpoKey(keytype):
"""
Inserts keytype values in world ipo at curframe. Uses module constants.
@type keytype: Integer
@param keytype:
-ZENTIH
-HORIZON
-MIST
-STARS
-OFFSET
-SIZE
@return: py_none
"""
def __copy__ ():
"""
Make a copy of this world
@rtype: World
@return: a copy of this world
"""
import id_generics
World.__doc__ += id_generics.attributes

View File

@@ -0,0 +1,55 @@
METABALL Module documentation
INTRODUCTION
The metaball module effect allows you to access all the data of an metaball.
A metaball consists of several (maybe only one) metaelems, which are spheres, interacting with each other, thus creating soft organic volumes.
functions of the module :
New(name) : creates ans returns a metaball object.
Get(opt : name) : if the parameter name is given, returns the metaball object whose name has been passed, or Py_None, if no such metaball exists in the current scene. If no parameter is given, returns a list of all the metaballs in the current scene.
get : alias for Get
Metaball object member functions :
getName()Return Metaball name
setName(string newname) - Sets Metaball name
getWiresize() - Return Metaball wire size
setWiresize(float val) - Sets Metaball wire size
getRendersize() - Return Metaball render size
setRendersize(float newval- Sets Metaball render size
getThresh()- Return Metaball threshold
setThresh(float newval)- Sets Metaball threshold
getBbox,- Return Metaball bounding box(a list of eight lists of three elements)
getNMetaElems() Returns the number of Metaelems (basic spheres)
getMetatype(int num_metaelem): returns the type of the metaelem number num_metaelem.
0 : ball
1 : tubex
2 : tubey
3 : tubez
setMetatype(int num_metaelem,int newtype) : sets the type of the metaelem number num_metaelem.
getMetadata(field_name,int num_metaelem) gets Metaball MetaData. Explained later.
setMetadata(field_name,int num_metaelem,newval) sets Metaball MetaData. Explained later.
getMetalay(int num_metaelem)
getMetax(int num_metaelem) : gets the x coordinate of the metaelement
setMetax(int num_metaelem,float newval) : sets the x coordinate of the metaelement
getMetay(int num_metaelem) : gets the y coordinate of the metaelement
setMetay(int num_metaelem,float newval) : sets the y coordinate of the metaelement
getMetaz(int num_metaelem) : gets the z coordinate of the metaelement
setMetaz(int num_metaelem,float newval) : sets the z coordinate of the metaelement
getMetas(int num_metaelem) : gets the s coordinate of the metaelement
setMetas(int num_metaelem,float newval) : sets the s coordinate of the metaelement
getMetalen(int num_metaelem) : gets the length of the metaelement. Important for tubes.
setMetalen(int num_metaelem,float newval) : sets the length of the metaelement. Important for tubes.
getloc, - Gets Metaball loc values
setloc, (f f f) - Sets Metaball loc values
getrot, () - Gets Metaball rot values
setrot,, (f f f) - Sets Metaball rot values
getsize,() - Gets Metaball size values
setsize,(f f f) - Sets Metaball size values
The Object.attribute syntax
The attribute can take these values : seed,nabla,sta,end,lifetime,normfac,obfac,randfac,texfac,randlife,vectsize,totpart,force,mult,life,child,mat,defvec.

View File

@@ -0,0 +1,12 @@
# epy_docgen.sh
# generates blender python doc using epydoc
# requires epydoc in your PATH.
# run from the doc directory containing the .py files
# usage: sh epy_docgen.sh
# set posix locale so regex works properly for [A-Z]*.py
LC_ALL=POSIX
epydoc -o BPY_API --url "http://www.blender.org" --top API_intro \
--name "Blender" --no-private --no-frames \
$( ls [A-Z]*.py )

View File

@@ -0,0 +1,12 @@
# epy_docgen.sh
# generates blender python doc using epydoc
# requires epydoc in your PATH.
# run from the doc directory containing the .py files
# usage: sh epy_docgen.sh
# set posix locale so regex works properly for [A-Z]*.py
LC_ALL=POSIX
epydoc -o BPY_API --url "http://www.blender.org" -t API_intro.py \
-n "Blender" --no-private --no-frames \
$( ls [A-Z]*.py )

View File

@@ -0,0 +1,30 @@
attributes = """
@ivar name: unique name within each blend file.
The name is case sensitive and 21 characters maximum length.
B{Note}: a blend file may have naming collisions when external library data is used,
be sure to check the value of L{lib}.
B{Note}: Setting a value longer then 21 characters will be shortened
@type name: string
@ivar lib: path to the blend file this datablock is stored in (readonly).
lib will be None unless you are using external blend files with (File, Append/Link)
B{Note}: the path may be relative, to get the full path use L{Blender.sys.expandpath<Sys.expandpath>}
@type lib: string or None
@ivar fakeUser: When set to True, this datablock wont be removed, even if nothing is using it.
All data has this disabled by default except for Actions.
@type fakeUser: bool
@ivar tag: A temporary tag that to flag data as being used within a loop.
always set all tags to True or False before using since blender uses this flag for its own internal operations.
@type tag: bool
@ivar users: The number of users this datablock has. (readonly)
Zero user datablocks are de-allocated after reloading and saving.
@type users: int
@ivar properties: Returns an L{IDGroup<IDProp.IDGroup>} reference to this
datablocks's ID Properties.
@type properties: L{IDGroup<IDProp.IDGroup>}
"""

View File

@@ -0,0 +1,45 @@
# Testing the BGL module
import Blender
from Blender.BGL import *
from Blender import Draw
R = G = B = 0
A = 1
instructions = "Hold mouse buttons to change the background color."
quitting = " Press ESC or q to quit."
def show_win():
glClearColor(R,G,B,A) # define color used to clear buffers
glClear(GL_COLOR_BUFFER_BIT) # use it to clear the color buffer
glColor3f(1,1,1) # change default color
glRasterPos2i(50,100) # move cursor to x = 50, y = 100
Draw.Text("Testing BGL + Draw") # draw this text there
glRasterPos2i(350,20) # move cursor again
Draw.Text(instructions + quitting) # draw another msg
glBegin(GL_LINE_LOOP) # begin a vertex-data list
glVertex2i(46,92)
glVertex2i(120,92)
glVertex2i(120,115)
glVertex2i(46,115)
glEnd() # close this list
glColor3f(0.35,0.18,0.92) # change default color again
glBegin(GL_POLYGON) # another list, for a polygon
glVertex2i(315, 292)
glVertex2i(412, 200)
glVertex2i(264, 256)
glEnd()
Draw.Redraw(1) # make changes visible.
def ev(evt, val): # this is a callback for Draw.Register()
global R,G,B,A # it handles input events
if evt == Draw.ESCKEY or evt == Draw.QKEY:
Draw.Exit() # this quits the script
elif evt == Draw.LEFTMOUSE: R = 1 - R
elif evt == Draw.MIDDLEMOUSE: G = 1 - G
elif evt == Draw.RIGHTMOUSE: B = 1 - B
else:
Draw.Register(show_win, ev, None)
Draw.Register(show_win, ev, None) # start the main loop

View File

@@ -0,0 +1,137 @@
# Blender.Camera module and Camera PyType test file
# This also works with Lamp and Material, simply uncomment the right
# line below
MODULE = "Camera"
#MODULE = "Lamp"
#MODULE = "Material"
BPY_OBJECT = MODULE
LONG_STRING = "Supercalifragilisticspialidous"
import types, sys
import Blender
exec ("from Blender import %s" % MODULE)
def PRINT_HEADER(header, sep):
print "\n", sep * 79
print header
print sep * 79
def PRINT_UNDERLINED(str):
print "\n", str
print "-" * len(str)
def PRINT_AND_RM(arg, branch, d):
for a in arg:
if a in d:
d.remove(a)
print "\n%s.%s:" % (branch, a),
exec("print %s.%s" % (branch, a))
PRINT_HEADER("Testing the Blender.%s module" % MODULE, '=')
exec ("Module_dir = dir (%s)" % MODULE)
print "\ndir (%s):" % MODULE
print Module_dir
PRINT_AND_RM (["__name__", "__doc__"], MODULE, Module_dir)
for item in Module_dir:
hooked = 0
branch = "%s.%s" % (MODULE, item)
PRINT_HEADER(branch, "-")
exec ("item_type = type (%s)" % branch)
print item_type
exec ("sub_dir = dir(%s)" % branch)
PRINT_AND_RM (["__name__", "__doc__"], branch, sub_dir)
if item_type == types.BuiltinFunctionType:
PRINT_UNDERLINED ("Executing %s:" % branch)
exec ("result = %s()" % branch)
print "Returned value is: ", result
if item in ["Get", "get"] and not hooked:
if len(result):
obj = result[0]
hooked = 1
if hooked:
PRINT_HEADER(obj, "=")
exec ("obj_dir = dir(obj)")
print "\ndir():"
print obj_dir
methods = []
member_vars = []
for item in obj_dir:
exec ("item_type = type (obj.%s)" % item)
if item_type == types.BuiltinMethodType:
methods.append(item)
else:
member_vars.append(item)
PRINT_HEADER("%s Methods" % BPY_OBJECT, '-')
if methods: print methods
else: print "XXX No methods found in %s" % BPY_OBJECT
PRINT_HEADER("%s Member Variables" % BPY_OBJECT, '-')
if member_vars:
for m in member_vars:
PRINT_UNDERLINED(m)
exec ("mvalue = obj.%s" % m)
exec ("mtype = type (obj.%s)" % m)
mtype = str(mtype).split("'")[1]
print "%s: %s" % (mtype, mvalue)
M = m[0].upper() + m[1:]
setM = "set%s" % M
getM = "get%s" % M
if setM in methods:
print "There is a .%s() method." % setM
methods.remove(setM)
if mtype == 'str':
try:
print "Trying to set string to %s" % LONG_STRING
exec("obj.%s('%s')" % (setM, LONG_STRING))
exec("get_str = obj.%s()" % getM)
print "It returned:", get_str
len_str = len(get_str)
if len_str < 100:
print "It correctly clamped the string to %s chars." % len_str
except:
PRINT_HEADER("FAILED in .%s()" % setM, "X")
print sys.exc_info()[0]
elif mtype == 'float':
try:
exec("obj.%s(%d)" % (setM, -999999))
exec("result = obj.%s()" % getM)
print "%s's minimum value is %f" % (m, result)
exec("obj.%s(%d)" % (setM, 999999))
exec("result = obj.%s()" % getM)
print "%s's maximum value is %f" % (m, result)
except:
PRINT_HEADER("FAILED in %s or %s" % (setM, getM), "X")
print sys.exc_info()[0]
elif mtype == 'int':
try:
dict = M+"s"
if dict in member_vars:
exec("key = obj.%s.keys()[1]" % dict)
exec("obj.%s('%s')" % (setM, key))
exec("result = obj.%s()" % getM)
except:
PRINT_HEADER("FAILED in %s or %s" % (setM, getM), "X")
print sys.exc_info()[0]
if getM in methods:
print "There is a .%s() method." % getM,
methods.remove(getM)
exec("result = obj.%s()" % getM)
print "It returned:", result
else: print "XXX No member variables found in %s" % BPY_OBJECT
else: # the module .Get() function found nothing
PRINT_HEADER("Failed trying to %s.Get() a %s object"
% (MODULE, BPY_OBJECT), 'X')

View File

@@ -0,0 +1,20 @@
import Blender
list = Blender.Curve.Get()
print list
cur = Blender.Curve.Get('Curve')
for prop in ["Name","PathLen","Totcol","Flag","Bevresol","Resolu","Resolv","Width","Ext1","Ext2","Loc","Rot","Size"]:
value = eval("cur.get%s()"%prop)
print prop,"-->",value
exec("cur.set%s(value)"%prop)
for attr in [ "name","pathlen","totcol","flag","bevresol","resolu","resolv","width","ext1","ext2","loc","rot","size"]:
value = eval("cur.%s"%attr)
exec("cur.%s = value"%attr)

View File

@@ -0,0 +1,65 @@
import Blender
################## WARNING ########################
#
# this script tests the Effect module, and its submodules : Wave, Build and Particle
# an object name "Plane" must be created, with three effects attached to it.
# the first effect must be a "Build" effect
# the second effect must be a "Wave" effect
# the third effect must be a "Particle" effect
#
########################################################
effect = Blender.Effect.New()
print effect
build = Blender.Effect.Get('Plane',0)
for param in ['Type','Flag','Len','Sfra'] :
value = eval("build.get%s()"%param)
print param,value
value1 = eval("build.set%s(%s)"%(param,value))
print value1
for param in ["sfra","len"]:
str = "build.%s"%param
value = eval(str)
print str,value
exec("build.%s = value"%param)
wave = Blender.Effect.Get('Plane',1)
for param in ['Type','Flag','Startx','Starty','Height', 'Width', 'Narrow', 'Speed', 'Minfac', 'Damp', 'Timeoffs' ,'Lifetime'] :
value = eval("wave.get%s()"%param)
print param,value
value1 = eval("wave.set%s(%s)"%(param,value))
print value1
for param in ["lifetime","timeoffs","damp","minfac","speed","narrow","width","height","startx","starty"]:
str = "wave.%s"%param
value = eval(str)
print str,value
exec("wave.%s = value"%param)
particle = Blender.Effect.Get('Plane',2)
for param in ['Type','Flag','StartTime','EndTime','Lifetime','Normfac','Obfac','Randfac','Texfac','Randlife','Nabla','Totpart','Totkey','Seed','Force','Mult','Life','Child','Mat','Defvec'] :
value = eval("particle.get%s()"%param)
print param,value
value1 = eval("particle.set%s(%s)"%(param,value))
print value1
for param in ['seed','nabla','sta','end','lifetime','normfac','obfac','randfac','texfac','randlife','vectsize','totpart','force','mult','life','child','mat','defvec']:
str = "particle.%s"%param
value = eval(str)
print str,value
exec("particle.%s = value"%param)

View File

@@ -0,0 +1,24 @@
import Blender
ipo = Blender.Ipo.Get()
print "Available ipos : ",ipo
ipo = Blender.Ipo.Get('ObIpo')# hope there is an ipo named "ObIpo"...
for prop in ["Name","Blocktype","Showkey","Pad","Rctf"]:
val = eval("ipo.get%s()"%prop)
print prop,"-->",val
#exec("ipo.set%s(%s)"%(prop,val))
try :
val = ipo.getCurveBP(0)
print "CurveBP -->",val
except : print "error BP"
val = ipo.getNcurves()
print "NCurves -->",val
curvebeztriple = ipo.getCurveBeztriple(0,0)
print "curvebeztriple",curvebeztriple
ipo.setCurveBeztriple(0,0,[1,2,3,4,5,6,7,8,9])
print ipo.getCurveBeztriple(0,0)

View File

@@ -0,0 +1,37 @@
import Blender
d = Blender.Metaball.Get('Meta')
for prop in ["Name","Wiresize","Thresh","Rendersize","loc","rot","size"]:
str = "d.get%s()"%prop
val = eval(str)
print str,"-->",val
str1 = "d.set%s(%s)"%(prop,repr(val))
val1 = eval(str1)
print str1,"-->",val1
nelem = d.getNMetaElems()
print "getNMetaElems",nelem
for prop in ['lay','type','selcol','flag','pad','x','y','z','expx','expy','expz','rad','rad2','s','len','maxrad2']:
str = "d.getMeta%s(0)"%prop
value = eval(str)
print str,"-->",value
str1 = "d.setMeta%s(0,%s)"%(prop,repr(value))
value1 = eval(str1)
print str1,"-->",value1
print;print
for field in ["name","loc","rot","size"]:
str = "d.%s"%field
val = eval(str)
print str,"-->",val
exec("d.%s = val"%field)

View File

@@ -0,0 +1,29 @@
# Test Blender.Text
import Blender
from Blender import Text
txt = Text.New("MyText")
all_texts = Text.Get()
for i in [1,4,7]:
txt.write("%d\n%d\n%d little indians\n" % (i, i+1, i+2))
x = txt.getNLines()
txt.write("%d little indian boys!" % x)
lines = txt.asLines()
txt.clear()
txt.write("... Yo-ho-ho! And a bottle of rum!")
for s in lines:
print s
print all_texts
print txt.asLines()
Text.unlink(txt)
print all_texts

View File

@@ -0,0 +1,21 @@
import Blender
#testfile
list = Blender.World.Get()
print "available worlds",list
w = Blender.World.Get("World")
for param in ["Name","Colormodel","Fastcol","Skytype","Mode","Totex","Texact","Mistype","Hor","Zen","Amb","Star","Dof","Mist"]:
val = eval("w.get%s()"%param)
print param,val
val1 = eval("w.set%s(val)"%param)
print val1
for param in ["name","colormodel","fastcol","skytype","mode","totex","texact","mistype","hor","zen","amb","star","dof","mist"]:
exec("val = w.%s"%param)
print param,val
exec ("w.%s = val"%param)