Encontre seu próximo livro favorito

Torne'se membro hoje e leia gratuitamente por 30 dias.
Blender 2.49 Scripting

Blender 2.49 Scripting

Ler amostra

Blender 2.49 Scripting

578 página
5 horas
Lançado em:
Apr 29, 2010


The focus of the book is on practical problems and how to solve them in Python. The examples given are useful programs that try to solve real-world needs. Each chapter revolves around a single concept giving several examples gradually growing in difficulty. Each section analyses the problem first before diving into coding and gives extensive background information to enable the reader to generalize from the specific problem to a wider range of challenges. The sample code is provided as fully working examples with all key issues extensively highlighted. All sample programs are clear and concise yet nothing essential is left out and the programming style focuses on readability rather than on stylistic rigor or efficiency. This book is for users comfortable with Blender as a modeling and rendering tool who want to expand their skills to include Blender scripting to automate laborious tasks and achieve results otherwise impossible. Blender experience is essential as is some experience in Python programming.
Lançado em:
Apr 29, 2010

Sobre o autor

Relacionado a Blender 2.49 Scripting

Livros relacionados
Artigos relacionados

Amostra do Livro

Blender 2.49 Scripting - Michel J. Anders

Table of Contents

Blender 2.49 Scripting


About the Author

About the Reviewer


What this book covers

What you need for this book

Who is this book for


Reader feedback

Customer support




1. Extending Blender with Python

The Blender API

A lot of power

Some batteries included

Check for a full Python distribution

Installing a full Python distribution

The interactive Python console

Exploring built-in modules, the help() function

Exploring built-in functions, the dir() function

Getting familiar with the built-in editor

An editor example

First steps: Hello world

Integrating a script in Blender's menus

Integrating a script in Blender's help system

Don't get confused, stay objective

Adding different types of object from a script

Adding a mesh object

Distributing scripts

The Blender API

The Blender module

Blender objects

The bpy module

Drawing on the screen



2. Creating and Editing Objects

Creepy crawlies—a GUI to configure objects

Building the user interface

Creating bugs—some assembly required

Creating a user interface

Remembering choices

The full power of Blender graphics

Creating a new Mesh object

Transforming mesh topology

Code outline bridging edge loops

Dazzle your boss—bar charts in Blender style

The bar chart script

Weird faces—selecting and editing faces in meshes

Selecting warped (non-planar) quads

Code outline warp select

Selecting ultra sharp faces

Selecting vertices with many edges

Selecting poles

Selecting poles, again

Determining the volume of a mesh

Determining the centre of mass of a mesh

Some remarks about accuracy

Growing sunflowers—parenting and grouping objects



Growing a sunflower from a seed

Duplication versus instantiation

Growing a sunflower


3. Vertex Groups and Materials

Vertex groups

A weighty issue

Code outline: leftright.py



Converting a Text3d object to a mesh

Extruding an edge loop

Expanding an edge loop

Putting it all together: Engrave.py

Flying sparks

Calculating the local curvature

Code outline: curvature.py

Putting it all together: St. Elmo's fire



Code outline: clock.py

Get a bit of backbone boy!


Object materials versus ObData materials

Assigning materials to parts of an Object

Vertex colors versus face materials

Adding materials to our engraving


4. Pydrivers and Constraints

Getting to grips with animated properties


IPOchannels and IPOCurves


Difference between drivers and constraints

Programming with constraints

Programming with IPOs



Setting the time—one to rule them all


Overcoming limitations: pydrivers.py

Internal combustion—correlating complex changes

More power—combining multiple cylinders to an engine

Adding simple constraints

Defining complex constraints

The Blender constraint template

Do you find me attractive too?

Snapping to mesh vertices

Aligning along a vertex normal

Snap to vertices in a vertex group


5. Acting on Frame Changes

Animating the visibility of objects

Fading a material

Changing layers

Countdown—animating a timer with script links

I'll keep an eye on you

Code outline: AuraSpaceHandler.py

Using themes

Revisiting mesh—making an impression

The user interface

Calculating an impression


6. Shape Keys, IPOs, and Poses

A touchy subject—defining an IPO from scratch

Code outline: orbit.py

A lot to swallow—defining poses

Application of peristaltic.py to an armature

Get down with the beat—syncing shape keys to sound

Manipulating sound files

Code outline: Sound.py

Animating a mesh by a .wav file: the workflow


7. Creating Custom Shaders and Textures with Pynodes

The basics

From nodes to Pynodes

Regular tilings


Indexing a texture by vector

A fresh breeze—textures with normals

Raindrops—animated Pynodes

Render-time parameters

What looks good, is good

Storing expensive results for reuse

Calculating normals

Putting it all together

Wuthering heights—a slope-dependent material

Determining the slope

World space versus camera space

Soap bubbles—a view-dependent shader


8. Rendering and Image Manipulation

A different view—combining multiple camera angles

Code outline—combine.py

Workflow—how to showcase your model

Now, strip—creating a film strip from an animation

Workflow—using strip.py

Rendering billboards

Workflow—using cardboard.py

Generating CAPTCHA challenges

Design of a CAPTCHA server


9. Expanding your Toolset

To the Web and beyond—publish a finished render with FTP

Spring cleaning—archive unused images

Extending the editor—searching with regular expressions

Extending the editor—interacting with Subversion

Committing a file to the repository

Updating a file from the repository

Working with a repository

The need for speed—using Psyco

Enabling Psyco


A. Links and Resources

General Blender-related forums and blogs

Python programming

Blender scripting

External packages used in this book

Other sources of information

B. Common Pitfalls

Read the API documents

The trouble with import

Installing a full Python distribution

C. Future Developments




Blender 2.49 Scripting

Michel J. Anders

Blender 2.49 Scripting

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: April 2010

Production Reference: 1230410

Published by Packt Publishing Ltd.

32 Lincoln Road


Birmingham, B27 6PA, UK.

ISBN 9781849510400


Cover Image by Vinayak Chittar (<vinayak.chittar@gmail.com>)



Michel Anders


Pang Lih-Hern

Acquisition Editor

Sarah Cullington

Development Editor

Mehul Shetty

Technical Editor

Namita Sahni


Hemangini Bari

Rekha Nair

Editorial Team Leader

Akshara Aware

Project Team Leader

Lata Basantani

Project Coordinator

Shubhanjan Chatterjee


Jeff Orloff


Geetanjali Sawant

Production Coordinator

Melwyn D'sa

Cover Work

Melwyn D'sa

About the Author

Michel Anders, after completing his chemistry and physics studies, where he spent more time on computer simulations than on real world experiments, he realized that his real interests lay with IT and Internet technology. He has worked as an IT manager for several different companies, including an Internet provider and a hospital.

Currently he manages the R&D department of Aia Software—a leading developer of document composition software. He lives happily on a small, converted farm with his partner, 3 cats, and 12 goats.

He has been using Blender since version 2.32, although he will be the first one to acknowledge his artwork is naive at best. He loves to help people with Blender and Python-related questions and may be contacted as varkenvarken on blenderartists.org.

First, I would like to thank all the wonderful people at Packt Publishing. Without their help this book would not have been written. Also, I would like to thank my partner and my colleagues at work for putting up with my endless talks about Blender. Finally, I'd like to thank all those people in the Blender community who have together made Blender such a wonderful application.

About the Reviewer

Pang Lih-Hern is a computer game engine programmer with five years of industry experience. He started programming when he was 12, learning the quick Basic language. After graduating with a degree in Software Engineering and Games Design from Multimedia University Malaysia he started his freelancing endeavor that eventually lead him to be part of the core technical team of John Galt Games (Malaysia). He was part of the decision making group in designing and implementing the company's proprietary game engine. Lih-Hern is also actively involved in the open source front, often submitting fixes and features for the popular open source Ogre3D engine. One notable contribution is the Parallel Split Shadow Map feature that enhances the shadow rendering of a 3D scene. He is also a strong advocate of Blender and is currently holding the position of maintaining the Blender exporter to Ogre3D's mesh format.

After leaving John Galt Games (Malaysia), Lih-Hern co-founded Liquid Rock Games with his fellow artist partner Yap Chun Fei. The goal was to create innovative AAA quality games without the need for huge budget cost by the means of using open source technology and tools such as Blender, Gimp, and Ogre3D. As of now, Liquid Rock Games is in the process of developing its first racing title named Aftershock—an online multiplayer post-apocalyptic racing game. The game's artwork is modeled and textured using Blender and Gimp, showing the capability of such tools in the commercial market.

First of all, I would like to thank the publisher, Packt publishing, for giving me the opportunity to review this book. I would also like to thank my family and the co-partner of my company for allowing me the spare time and support to review this book. I hope that the readers will benefit from this book and be inspired to produce more amazing useful tools for Blender.

For Clementine


Blender is no doubt the most powerful, and versatile, open source 3D package available. Its power comes close to, or even surpasses, many professional packages. Blender's built-in Python interpreter plays an important role in tapping this power and allows artists to extend the functionality even further. Yet, mastering a scripting language and getting familiar with the many possibilities that Blender offers through its Python API can be a daunting venture.

This book will show how to get the most out of Blender by showing practical solutions to many realistic problems. Each example is a complete working script, which is explained step-by-step in a very detailed manner.

What this book covers

Chapter 1, Extending Blender with Python, gives you an overview of what can and cannot be accomplished with Python in Blender. It teaches you how to install a full Python distribution and how to use the built-in editor. You also learn how to write and run a simple Python script and how to integrate it in Blender's menu system.

Chapter 2, Creating and Editing Objects, introduces objects and meshes and you will see how to manipulate them programmatically. Specifically, you learn how to create configurable mesh objects, design a graphical user interface, and how to make your script store user choices for later reuse. You also learn how to select vertices and faces in a mesh, parent an object to another, and how to create groups. Finally, this chapter shows how to run Blender from the command line, render in the background, and how to process command-line parameters.

Chapter 3, Vertex Groups and Materials, tells you about the many uses of vertex groups and how versatile they can be. You get to know how to define vertex groups and how to assign vertices to a vertex group. You will also learn how you can use those vertex groups for modifiers and armatures. You also look into the application of different materials to different faces and how to assign vertex colors to vertices.

Chapter 4, Pydrivers and Constraints, shows how you can associate built-in constraints with Blender objects and how to define complex relationships between animated properties by using the so-called pydrivers. You also define new complex constraints that may be used just like the built-in constraints. Specifically, you see how to drive one IPO from another by a Python expression, how to work around some limitations inherent in pydrivers, and how to restrict the motion of objects and bones by adding constraints. This chapter teaches you how to write a constraint in Python that will snap an object to the closest vertex on another object.

Chapter 5, Acting on Frame Changes, focuses on writing scripts that may be used to act on certain events. You can learn what script links and space handlers are and how they can be used to perform activities on each frame change in an animation. You also see how to associate additional information with an object, how to use script links to make an object appear or disappear by changing its layout or changing its transparency, and how to implement a scheme to associate a different mesh with an object on each frame. Finally, you can look into ways to augment the functionality of the 3D view.

Chapter 6, Shape Keys, IPOs, and Poses, discovers that there is more to IPOs that can prove useful in animated scenes. Although IPOs were introduced in Chapter 4, here you learn how to define IPOs on all kinds of objects, associate shape keys with a mesh, and how to define IPOs for those shape keys. You also look into posing armatures and combining poses into actions.

Chapter 7, Creating Custom Shaders and Textures with Pynodes, introduces Pynodes and you get to know how they enable you to define completely new textures and materials. You learn how to write Pynodes that create simple color patterns, Pynodes that produce patterns with normals, and you also learn how to animate Pynodes. This chapter also explains about Pynodes that produce height and slope-dependent materials and even create shaders that react to the angle of incident light.

Chapter 8, Rendering and Image Manipulation, turns to the rendering process as a whole. You can automate this rendering process, combine the resulting images in various ways, and even turn Blender into a specialized web server. Specifically, you learn how to automate the rendering process, create multiple views for product presentations, and create billboards from complex objects. You get to know about ways to enhance Blender with some external libraries to manipulate images, including render results.

Chapter 9, Expanding your Toolset, is less about rendering and more about making life easier for the day-to-day use of Blender by extending its functionality. In this chapter, you learn how to list and archive assets such as image maps, publish a rendered image automatically with FTP, extend the functionality of the built-in editor with regular expression searches, speed up computations by using Psyco—a just-in-time compiler, and add version control to your scripts with Subversion.

Appendix A, Links and Resources, gives you a list of most resources used in this book along with some generally useful information.

Appendix B, Common Pitfalls, highlights some of the common questions that pop up more often than others as do some mistakes.

Appendix C, Future Developments, is the final appendix that tries to show what the future holds in store and how this may affect you as both Blender and Python are constantly developed further.

What you need for this book

All examples in the book use Blender 2.49 (available at www.blender.org) and its built-in Python 2.6.x language. Many examples assume that you have a full Python (www.python.org) distribution. In Chapter 1, Extending Blender with Python, you are shown how to install a full distribution—if you don't have one already. Blender and Python are platform independent and all examples should run equally well on Windows, Linux, and Mac. Some additional modules are used as well and suitable download instructions are provided where appropriate. All examples can be downloaded from the publisher's website (http://www.packtpub.com).

Who is this book for

This book is for users comfortable with Blender as a modeling and rendering tool and who want to expand their skills to include Blender scripting to automate laborious tasks and achieve results otherwise impossible. Blender experience is essential as is some experience in Python programming.


In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: The Python file with the mesh building blocks is called mymesh.py so the first part of our code contains the following import statement.

A block of code is set as follows:

def event(evt, val):

    if evt == Draw.ESCKEY:

      Draw.Exit() # exit when user presses ESC


When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

def error(text):


  Draw.Register(lambda:msg(text), event, button_event)

Any command-line input or output is written as follows:

blender -P /full/path/to/barchart.py

New terms and important words are shown in bold. Words that you see on the screen in menus or dialog boxes, for example, appear in the text like this: Then we can apply this vertex group to the density parameter in the extra panel of the particles context to control the emission.


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail .

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.


Downloading the example code for the book

Visit https://www.packtpub.com//sites/default/files/downloads/0400_Code.zip to directly download the example code.

The downloadable files contain instructions on how to use them.


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.


Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.


You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Extending Blender with Python

Before we start crafting scripts in Blender we must check whether or not we have all the necessary tools available. After that we will have to familiarize ourselves with these tools so that we can use them with confidence. In this chapter, we will look at:

What can and cannot be accomplished with Python in Blender

How to install a full Python distribution

How to use the built-in editor

How to run a Python script

How to explore built-in modules

How to write a simple script that adds an object to a Blender scene

How to register a script in the Blender scripts menu

How to document your script in a user-friendly way

How to distribute a script

With so many things possible there is an awful lot to learn, but fortunately the learning curve is not as steep as it might seem. Let's just type in a quick few lines of Python to put a simple object into our Blender scene, just to prove we can, before we head into deeper waters.

Start Blender with an empty scene.

Open the interactive Python console (refer to the preceding screenshot to see where to find it).

Type in the following lines (end each one with a Enter/Return).

mesh = Mesh.Primitives.Monkey()



Voila! That's all that is needed to add Suzanne, Blender's famous mascot, to the scene.

The Blender API

Almost anything in Blender is accessible from Python scripts but there are some exceptions and limitations. In this section, we illustrate what this means exactly and which notable features are not accessible to Python (for example, fluid dynamics).

The Blender API consists of three major areas of interest:

Access to Blender objects and their properties, for example a Camera object and its angle property or a Scene object and its objects property

Access to operations to perform, for example adding a new Camera or rendering an image

Access to the graphical user interface, either by using simple building blocks or by interacting with the Blender event system

There are also some utilities that do not fit well in any of these categories as they concern themselves with abstractions that have no direct relation to Blender objects as seen by the end user, for example functions to manipulate vectors and matrices.

A lot of power

Taken together this means we can achieve a lot of things from Python scripts. We can:

Create a new Blender object of any type, including cameras, lamps, meshes, and even scenes

Interact with the user with a graphical user interface

Automate common tasks within Blender such as rendering

Automate maintenance tasks outside of Blender such as cleaning up directories

Manipulate any property of a Blender object that is exposed by the API

That last statement shows one of the current weaknesses of the Blender API: any object property that the developers add in the Blender C source must be provided separately in the Python API. There is no automatic conversion from internal structures to the interface available in Python and this means that efforts must be duplicated and may lead to omitted functionality. For instance, in Blender 2.49 it is not possible at all to set up a fluid simulation from a script. Although it is possible to set up a particle system, there is no way to set the behavioral characteristics of a boids particle system.

Another problem of the 2.49 Python API is that many of the actions a user may choose to perform on an object have no equivalent in the API. Setting simple parameters such as the camera angle or performing a rotation of any object is easy and even associating for example, a subsurface modifier to a mesh is just a few lines of code but common actions, especially on mesh objects, such as subdividing selected edges or extruding faces are missing from the API and must be implemented by the script developer.

These problems led the Blender developers to completely redesign the Blender Python API for the 2.5 version, focusing on feature parity (that is, everything possible in Blender should be possible using the Python API). This means that in many situations it will be far easier to get the same results in Blender 2.5.

Finally, Python is used in more places than just standalone scripts: PyDrivers and PyConstraints enable us to control the way Blender objects behave and we will encounter them in later chapters. Python also allows us to write custom textures and shaders as part of the nodes system as we will see in Chapter 7, Creating Custom Shaders and Textures.

Also, it is important to keep in mind that Python offers us far more than just the (already impressive) tools to automate all sorts of tasks in Blender. Python is a general programming language with an extensive library of tools included, so we do not have to resort to external tools for common system tasks such as copying files or archiving (zipping) directories. Even networking tasks can be implemented quite easily as a number of render farm solutions prove.

Some batteries included

When we install Blender, a Python interpreter is already part of the application. This means that it is

Você chegou ao final desta amostra. Inscreva-se para ler mais!
Página 1 de 1


O que as pessoas pensam sobre Blender 2.49 Scripting

0 avaliações / 0 Análises
O que você acha?
Classificação: 0 de 5 estrelas

Avaliações de leitores