Cookbook

Release:0.9.9983
Date:April 07, 2010

This cookbook has the purpose to provide a great collection of useful examples. Feel free to use the code-snippets in your code and if you have any sourcecode you want to share, please post it.

Linked recipes

Usefull snippets are stored in classes of the Py4D SDK.

  1. Browse through a document: browsing
  2. Play the animation and cache stuff: Document Caching
  3. Overview of all predefined Noise Types: Noise Types

Code snippets

Common Recipes

The following code-snippets will help you to get some workarounds for everyday stuff.

Get a name with sane chars

This function can be used when you are making a filename from an object/mesh/scene... name. Based on this code

#-*- coding:Utf-8 -*-

def sane_filechars(name):

    for ch in ' /\\~!@#$%^&*()+=[];\':",./<>?\t\r\näüö':
        name = name.replace(ch, '_')
    return name

How to get the active editor/object camera

Sometimes you have to use the editor/object camera. This code returns the current active camera:

def GetCamera(doc):
    """
    Returns the active camera.
    Will never be None.
    """
    bd = doc.GetRenderBaseDraw()
    cp = bd.GetSceneCamera(doc)
    if cp is None: cp = bd.GetEditorCamera()

    return cp

Spanning a Range defined by floats

Although this functionality is not available as a built-in, it’s not hard to code it with a loop. Based on a solution in the cookbook of O’Reilly

def frange(start, end=None, inc=1.0):
    "A range-like function that does accept float increments..."
    if end == None:
        end = start + 0.0 # Ensure a float value for 'end'
        start = 0.0
    assert inc # sanity check
    L = []
    while 1:
        next = start + len(L) * inc
        if inc > 0 and next >= end:
            break
        elif inc < 0 and next <= end:
            break
    L.append(next)
return L

#Example
for x in frange(1.0, 4.8, 0.2):
    print x