James Gregson's Website

Aug 14, 2019

Blender Python Integration

Some random stuff for working with blender programmatically:

Switch between object and edit mode

bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')

List selected objects

sel_obj = bpy.context.selected_objects
for obj in sel_obj:
    print( obj.name )

Deselect selected objects

In Object Mode:

for obj in bpy.context.selected_objects:
    obj.select_set(False)

Add IK Constraints & Render

import bpy

def deselect_all():
    for obj in bpy.context.selected_objects:
        obj.select_set(False)

def add_constraint( arm, bname, tname, chain_len, position ):
    # get the bones
    bone = arm.pose.bones[bname]
    targ = arm.pose.bones[tname]

    # create a constraint
    con = bone.constraints.new('IK')
    con.target = arm
    con.subtarget = tname
    con.chain_count = chain_len

    # set the target position
    targ.location = position

    return con    

# switch to object mode
bpy.ops.object.mode_set(mode='OBJECT')

# select the armature    
deselect_all()
arm = bpy.data.objects['Armature']
#arm.select_set(True)

# switch to pose mode
bpy.ops.object.mode_set(mode='POSE')

c = add_constraint( arm, 'larm.L', 'hand_target.L', 3, (0.5,1.25,0) )
# uncomment to disable constraint
#c.mute = True

bpy.context.scene.render.filepath = '/home/james/Documents/blender/out.png'
bpy.ops.render.render(write_still=True)