Thursday, March 27, 2008

DNA script


After writing the script I posted in the previous blog, it occurred to me that I should be able to create all the nucleotides with a script, not just color them. So I poked around in the Blender Python APIs and came up with the following:
import random, math
import Blender
from Blender import Object, Scene, Material

scn = Scene.GetCurrent()
colors1 = [Material.Get("G_Nucleotide"), Material.Get("C_Nucleotide")]
colors2 = [Material.Get("A_Nucleotide"), Material.Get("T_Nucleotide")]
groups = [colors1, colors2]
for i in range(0, 90):
rot = i*.125*math.pi
o = scn.objects.new(Object.Get("nucleotide").getData())
o.colbits = 1
o.modifiers = Object.Get("nucleotide").modifiers
o2 = scn.objects.new(Object.Get("nucleotide").getData())
o2.colbits = 1
o2.modifiers = Object.Get("nucleotide").modifiers
groupNum = random.choice([0,1])
firstColorNum = random.choice([0,1])
if firstColorNum == 0:
secondColorNum = 1
else:
secondColorNum = 0
firstColor = groups[groupNum][firstColorNum]
secondColor = groups[groupNum][secondColorNum]
o.LocZ = i*.2
o.RotZ = rot
o.setMaterials([firstColor])
o2.LocZ = i*.2
o2.RotZ = rot + math.pi
o2.setMaterials([secondColor])
scn.update()

Python is one of the more unique languages I've worked with. After my initial shock at being forced to indent, I've now found I like it. I'd do it anyway, but now it is sure to be done and done consistently. It makes for reading my code and others' code much nicer. As I get used to syntax and familiar with the Python and Blender APIs, I find I am looking for more excuses to use it. :)

For one of my future courses, I'd like to teach how to program... using Python as the language and Blender as the environment. This would be for folks who want to learn to program, but haven't a clue were to start. It's nice to be able to solve some of the more tedious tasks (like creating and coloring nucleotides) programmatically.

Another course I'd like to teach is one on the Blender Game Engine. With the logic bricks, you can do a lot of programming logic without getting into the syntax issues you get in a language. A cool thing in Blender is you can extend the logic bricks by calling Python scripts.

About the image: The image above has over 1200 objects, but only one mesh. Each object reference the same mesh (making changes easy). I applied the Material color to the object (not the mesh, which is the default). By using a script, I was able to apply the colors randomly but following the rules that the A color had to go with T (or T with A) and the G color had to go with C (or C with G). Since all the nucleotides of the same color share the same Material, color and texture changes are also easy.

No comments:

Post a Comment