How can I drive a shape key with a custom property slider using only Python scripting?

I intend to do a facial rig setup based on blendshapes and I want to do all the curves - shape key connections by scripting.


Make an object custom property to drive each shape

From an Old blenderartists thread adds a custom property to context mesh object for each of its mesh data shapekeys, and sets up a driver from property to shapekey.

enter image description here

import bpy

context = bpy.context
scene = context.scene
object = context.object
mesh = object.data
shape_keys = mesh.shape_keys

frame = scene.frame_start
# dictionary of shape_key fcurves keyed by data_path
fcurve_dict = {}
rna = object.get('_RNA_UI', {})
for key, keyblock in shape_keys.key_blocks.items():
    if keyblock == shape_keys.key_blocks[0]:
        print("keyblock %s assumed Basis and ignored" % key)
    # create a custom property for the key

    rna[key] =  {"name": key,
                "min": keyblock.slider_min,
                "max": keyblock.slider_max,
                "description": "Shape Key %s" % key,
                "soft_min": keyblock.slider_min,
                "soft_max": keyblock.slider_max,
    object[key] = keyblock.value
    object["_RNA_UI"] = rna

    # add a driver

    fcurve = shape_keys.driver_add('key_blocks["%s"].value' % key)
    driver = fcurve.driver
    driver.type = 'SCRIPTED'
    driver.expression = "shape"
    var = driver.variables.new()
    var.name = "shape"
    var.type = 'SINGLE_PROP'
    target = var.targets[0]
    target.id_type = "OBJECT"
    target.id = object.id_data
    target.data_path = '["%s"]' % key

If for instance you wish to put properties on the armature

object = bpy.data.objects["Name of Armature Object"]
mesh = bpy.data.meshes["Name of Mesh with Shapekeys"]

Please note old code.. don't use object as a variable name as its a reserved python keyword use ob or obj (for example) instead

  • $\begingroup$ Thanks for your response. Its very helpfull. I have a question. isn't there a simpler code like putting : custom property is = shape key ? $\endgroup$ – Igor Pichardo Jan 24 '20 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.