Wednesday, August 23, 2023

doodle python lock all but selected bones in Blender 2.79

this doodle locks the vertex groups of all bones except the selected bones - it requires to be in either pose mode or weight paint mode.  could be helpful when painting weights.  tested in Blender 2.79.  There may be bugs so please modify/use at your own risk.


import bpy


def lockAllButSelectedBones():
    """lock all but selected bones. requires to be in pose mode or weight paint mode
    """
    meshName = None
    selectedBones = [obj.name for obj in bpy.context.selected_pose_bones]
    
    if not selectedBones:
        raise RuntimeError("requires at least one bone selected")
        
    #get mesh slightly differently whether in pose mode or weight paint mode
    #if in pose mode
    if bpy.context.mode == 'POSE':
        #get mesh from bone
        armatureName = bpy.context.object.name
        #loop all meshes to find mesh parented to armature
        for ob in bpy.data.objects:
            if ob.type == "MESH" and (ob.parent == bpy.data.objects[armatureName]):
                meshName = ob.name
        print("meshName ", meshName)
        
    elif bpy.context.mode == 'PAINT_WEIGHT':
        #if in weight paint mode
        meshName = bpy.context.object.name
    else:
        raise RuntimeError("requires to be in POSE mode or weight paint mode")
    
    
    #lock all vertex groups
    bpy.data.objects[meshName].select = True
    bpy.context.scene.objects.active = bpy.data.objects[meshName] 
    bpy.ops.object.vertex_group_lock(action='LOCK')
       
    #unlock selected bones
    allVertexGroups = bpy.data.objects[meshName].vertex_groups
    for i in range(0,len(allVertexGroups)):
        if allVertexGroups[i].name in selectedBones:
            allVertexGroups[i].lock_weight = False