Blender 3D: Blending Into Python/Cookbook

= Image Functions =

Edit Image in External Program
This runs in linux (probably any unix), and launches The Gimp. It could probably be modified to launch Photoshop in windows. In Gnome, KDE and Mac OS X, you can use a command to open documents using the default or a specified application. Win32 has some open command too, maybe somebody could add this in.
 * KDE: kfmclient openURL 
 * Gnome: gnome-open 
 * Mac OS X: open [-a ]

Find Images
This script recursively searches for images that have broken files references. It works by giving the user a root path, then finds and re-links all images within that path. Its very useful when migrating projects to different computers.

Remove Double Images
This script finds images that are referenced more than once, and looks through all meshes texface's, and assigns only one of the images. If a face has no users the image is removed. This is useful because when an image is loaded more than once, it's also loaded into system memory and graphics card memory more than once, wasting resources. Support for image type textures still needs doing.

= Material Functions =

Toon Material Batch Conversion Script
this script changes *all* materials in your currently open blend file to toon materials. after executing, check the blender console for script output.

as this script alters *all* of your material settings in your currently opened blend file, you should *not* run it on a project that has not been saved yet! changes made to materials while using this script cannot be undone!

note: changes are not permanently committed to your blend file unless you choose to save your file after executing this script.

= Curve Functions =

Length of a curve
This function gets the combined length of all edges. Most useful to get the length of a curve. Be careful, because it will get the length of every curve in a curve object!

Note that this function doesn't take the object's transformation into account when getting the length.

= Text Functions =

Paste Text in Unix
Paste text in X11, requires uclip []

Save all Texts as files
Saves all text editor texts as files in the current working directory. WARNING: This will overwrite files with those names!

= Mesh Functions = Examples and functions for Blenders NMesh, GMesh and new Mesh module.

Mesh tool template
Use this to base your editmode mesh tool on.

Desaturate Meshes VertCol
Uses the new Mesh module. In Blender 2.4 only. Desaturates using the same weighting as Photoshop uses.

Point inside a Mesh
This function returns 1/0 depending on whether the provided point is inside a mesh. It relies on the mesh having a continuous skin, no holes in it. (Otherwise the problem doesn't make sense.)

It uses the method of seeing how many face intersections there are along a line segment between that point, and a point somewhere outside the meshs bounds.

An even number of intersections means it's outside, an odd for inside. Hence we return len(intersections) % 2 where intersections generates a list of intersections.

This function uses a Z direction vector so we can save some CPU cycles by first doing an X/Y bounds test to see if the points could intersect, before doing a full ray intersection.

Scanfill for importers
This function takes a mesh and a list of vert indicies representing an ngon. It returns a list of tri indicies that make up the scanfilled face. This is much more useful for importers.

it also handles cases where scanfill does not work by returning a triangle fan.

It may be faster then using the mesh.fill function on your original mesh because cycling editmode can be slow on a lot of data. Another advantage with this function over simply using fill is you can be sure the faces will be flipped the right way, according to the order of the indicies.

Triangulate NMesh
This is a function to be used by other scripts, its useful if you want to make your life simpler by only dealing with triangles. The shortest edge method is used for dividing the quad into 2 tri's.

Fix vertex winding in "bowtie" quads
Sometimes you may encounter quad faces which, although correctly coplanar, aren't quite "full". This comes from the vertices being in the wrong order, and causes the face to overlap itself, often leaving undesired holes and black areas where the normals point the wrong way. To see what this all means, just make a plane and switch places for the vertices at any edge. The connecting edges will then cross. Since the normals of the face don't make sense in this situation, the script can't guarantee that the normal points outwards after finishing.

Remove Verts Without removing entire faces
Script that uses the mesh template above. removes verts but surrounding quads will be converted to tri's. Note This only works with NMesh.

GMesh AutoSmooth Mesh
This function uses GMesh to autosmooth manifold meshes, it requires the GMesh module.

Be careful because it will smooth your mesh in place, so make a copy of your original object if you don't want it modified.

ScanFill
To simulate typing "Shift F" in blender to create scanfill selected edge loop (edit mode only)

This will only work if the 3D view is open.

Expanded Scanfill function
Self contained scanfill function, based on the code above. Note, this function needs a 3D view to be available Example function usage.

Copy NMesh Face
Returns a new face that has the same properties as the original face but with no verts

Returns the Faces centre as a Vector
Note, Blenders Mesh API now has face.cent access

Take 1 NMFace and return a vector as its centre, will use an existing vector object "cent" if provided.

Flip Faces Up
I used this script to flip all faces in many terrain meshes to point up. It uses Mesh as opposed to NMesh.

Scale UVs
Scales all uv coords for selected mesh objects.

Find a material in all Meshes in all Scenes
Sometimes You have a lot of mesh object and materials you don't want any of them to use. This script can help you find those objects.

Faces share an edge
The 2 faces share an edge, its best to make sure your not comparing the same faces, and remove the first 'if'.

Get Edge Angles
Returns a list of angles, the combine angle difference of all faces that use the edges. the angles returned are in sync with mesh.edges. Edges with 0 or 1 faces will have Zero angle.

This function uses Blender.Mesh not Blender.NMesh mesh data.

Mesh Ray Intersect
Intersect a ray with a mesh, Assume the mesh has no loc/size/rot.

Copy Vertex UV to Face UV
Copies the Vertex UV coordinates (Sticky) to face UV coordinates (TexFace).

= Math Functions = Here is the place to add math examples, they can be blender specific or generic python math functions.

Changing Rotation Axis Order
If you ever have trouble converting between different rotation systems its possible that the order of rotations is the problem.

Get Angle between 3 points
Get the angle between line AB and BC where b is the elbow.

Point inside a tri (2D)
Returns True if pt is inside the triangle. only gives a correct answer when pt lies on the triangles plane.

Apply Matrix
Applys a 4x4 transformation as returned by object.getMatrix, to a vector (3d point in space)

This is useful for finding out the position of a vertex in worldspace.

Blender 2.43 supports this simply by doing "newvwec = vec*matrix" but its good to know how to do it manually

2D Line Intersection
Intersect 2 lines, if so where.

If there is no intersection the retured X value will be None and the y will be an error code.

The first line is (x1,y1, x2,y2), the second (_x1,_y1, _x2,_y2)

Round to power of 2
This function takes any number and rounds it to the nearest power of 2 value (2,4,8,16,32,64,128,256,512,1024,2048, 4096...) This is useful for rounding textures to sized that load into graphics card memory.

It returns 3 values. rounded down, round closest, rounded up.

Closest Point (snapping)
Returns the vector that is closest to point. Good for snapping.

= Blender Object Scripts =

Linked Duplicate Object
There is no function in B:Python to make a linked duplicate of an object (Alt+D) so here is a function that does it for you.

Note Since this was written Blender.Object.Duplicate has been added as well as object.copy

Select Double Objects
Finds double object- objects that have the same dataname, type and loc/size/rot

NLA strips Examples
Example code for manipulating NLA strips and action strips

= Blender Windowing and User Interface Scripts =

Auto Buttons
Auto Buttons is a really easy way to add a stack of buttons into any script. Add the AutoButtons text to the bottom of any script and any function ending with _bgui will have a button that calls it.

An example of a function that could use this

Popup Menu Wrapper
This script takes a string that you would normally give to Draw.PupMenu splitting up the menus by the groupsize.

= General Python = Here add general python code, useful when Python scripting.

Benchmark Script
Script that times different functions.

Iterate Multiple Lists
Sometimes you want to loop over more than 1 list at once. if the lists your dealing with are large then creating a new list for the purpose can be slow and use too much memory. This class takes multiple lists and treats them like 1 big list. without having to make a new list.

Some examples Another example that takes verts from 3 meshes and adds them to 1 mesh using this iterator and list comprehension.

Binary Conversion (Without Struct)
Thanks to SJH 07/29/2004 20:26:03

Randomize List
Returns a randomized list. Note if you can import random, use random.shuffle(ls) instead.

Remove Doubles in List
Removes doubles in a list, modifying the original list. (will use an objects cmp function)

Remove Doubles in List (Hash)
Return a new list with no doubles.

Get flag properties of a sum
A lot of properties in Blender are flags and stored in a sum of exponentials of 2. To find out that a specific flag is set and it is included in the sum try this function:

Call the function in that way:

Fraction Data Type
Allows creation of fraction data and all operations on them within the real number system.

Get a name with sane chars
This function can be used when you are making a filename from an object/mesh/scene... name. Blender supports many characters in a name that a filesystem may not.

saneFilechars replaces these characters with "_"

= Colour Scripts = A place for scripts that deal with colours.

RGB to HSV
Convert Red/Green/Blue to Hue/Saturation/Value

r,g,b values are from 0.0 to 1.0

h = [0,360], s = [0,1], v = [0,1]

if s == 0, then h = -1 (undefined)

''The Hue/Saturation/Value model was created by A. R. Smith in 1978. It is based on such intuitive color characteristics as tint, shade and tone (or family, purety and intensity). The coordinate system is cylindrical, and the colors are defined inside a hexcone. The hue value H runs from 0 to 360º. The saturation S is the degree of strength or purity and is from 0 to 1. Purity is how much white is added to the color, so S=1 makes the purest color (no white). Brightness V also ranges from 0 to 1, where 0 is the black.''

HSV to RGB
Convert Hue/Saturation/Value to Red/Green/Blue

=Interactive Tools=

Freehand Polyline Draw Tool
=Render Functions=

Render from all cameras
This script renders an animation from all cameras in a scene, it makes a new name from the camera and leaves the scene as it was originally.

Be sure to use useful camera names.

=Scriptlinks=

Monitor Image
This Script needs to be used as a redraw scriptlink. It checks the date of the current image and attempts to reload the image, and if successful it redraws the image.

Dynamic Text
This script needs to be used as a FrameChanged script linked to a Text object. Change the Years.append line to choice the years of the timeline.

=External Utils=

Compress All Blend files (Unix Only)
Sine blender 2.41, support for GZip compression has been integrated into blender. So you can gzip all blend files and they will still open as expected.

This utility searches your hard-disk for blend files and gzips them if they are not already compressed.

Note: python3 required.