Skip to content
Snippets Groups Projects
utils.py 59.4 KiB
Newer Older
  • Learn to ignore specific revisions
  •             name = arm.rigify_layers[i].name
                row = arm.rigify_layers[i].row
    
                set = arm.rigify_layers[i].set
                group = arm.rigify_layers[i].group
    
                code.append('    arm.rigify_layers[' + str(i) + '].name = "' + name + '"')
                code.append('    arm.rigify_layers[' + str(i) + '].row = ' + str(row))
    
                code.append('    arm.rigify_layers[' + str(i) + '].set = ' + str(set))
                code.append('    arm.rigify_layers[' + str(i) + '].group = ' + str(group))
    
        # write parents first
        bones = [(len(bone.parent_recursive), bone.name) for bone in arm.edit_bones]
        bones.sort(key=lambda item: item[0])
        bones = [item[1] for item in bones]
    
        code.append("\n    bones = {}\n")
    
        for bone_name in bones:
            bone = arm.edit_bones[bone_name]
    
            code.append("    bone = arm.edit_bones.new(%r)" % bone.name)
    
            code.append("    bone.head[:] = %.4f, %.4f, %.4f" % bone.head.to_tuple(4))
            code.append("    bone.tail[:] = %.4f, %.4f, %.4f" % bone.tail.to_tuple(4))
            code.append("    bone.roll = %.4f" % bone.roll)
            code.append("    bone.use_connect = %s" % str(bone.use_connect))
            if bone.parent:
    
                code.append("    bone.parent = arm.edit_bones[bones[%r]]" % bone.parent.name)
            code.append("    bones[%r] = bone.name" % bone.name)
    
    
        bpy.ops.object.mode_set(mode='OBJECT')
        code.append("")
        code.append("    bpy.ops.object.mode_set(mode='OBJECT')")
    
        # Rig type and other pose properties
        for bone_name in bones:
            pbone = obj.pose.bones[bone_name]
    
    
            code.append("    pbone = obj.pose.bones[bones[%r]]" % bone_name)
            code.append("    pbone.rigify_type = %r" % pbone.rigify_type)
    
            code.append("    pbone.lock_location = %s" % str(tuple(pbone.lock_location)))
            code.append("    pbone.lock_rotation = %s" % str(tuple(pbone.lock_rotation)))
            code.append("    pbone.lock_rotation_w = %s" % str(pbone.lock_rotation_w))
            code.append("    pbone.lock_scale = %s" % str(tuple(pbone.lock_scale)))
    
            code.append("    pbone.rotation_mode = %r" % pbone.rotation_mode)
    
            if layers:
                code.append("    pbone.bone.layers = %s" % str(list(pbone.bone.layers)))
            # Rig type parameters
    
    Nathan Vegdahl's avatar
    Nathan Vegdahl committed
            for param_name in pbone.rigify_parameters.keys():
    
                param = getattr(pbone.rigify_parameters, param_name, '')
    
    Nathan Vegdahl's avatar
    Nathan Vegdahl committed
                if str(type(param)) == "<class 'bpy_prop_array'>":
                    param = list(param)
                if type(param) == str:
                    param = '"' + param + '"'
                code.append("    try:")
                code.append("        pbone.rigify_parameters.%s = %s" % (param_name, str(param)))
                code.append("    except AttributeError:")
                code.append("        pass")
    
    
        code.append("\n    bpy.ops.object.mode_set(mode='EDIT')")
        code.append("    for bone in arm.edit_bones:")
        code.append("        bone.select = False")
        code.append("        bone.select_head = False")
        code.append("        bone.select_tail = False")
    
        code.append("    for b in bones:")
        code.append("        bone = arm.edit_bones[bones[b]]")
        code.append("        bone.select = True")
        code.append("        bone.select_head = True")
        code.append("        bone.select_tail = True")
        code.append("        arm.edit_bones.active = bone")
    
    
        # Set appropriate layers visible
        if layers:
            # Find what layers have bones on them
            active_layers = []
            for bone_name in bones:
                bone = obj.data.bones[bone_name]
                for i in range(len(bone.layers)):
                    if bone.layers[i]:
                        if i not in active_layers:
                            active_layers.append(i)
            active_layers.sort()
    
            code.append("\n    arm.layers = [(x in " + str(active_layers) + ") for x in range(" + str(len(arm.layers)) + ")]")
    
        code.append('\nif __name__ == "__main__":')
        code.append("    " + func_name + "(bpy.context.active_object)")
    
    
        return "\n".join(code)
    
    
    
    def write_widget(obj):
        """ Write a mesh object as a python script for widget use.
        """
        script = ""
        script += "def create_thing_widget(rig, bone_name, size=1.0, bone_transform_name=None):\n"
        script += "    obj = create_widget(rig, bone_name, bone_transform_name)\n"
    
        script += "    if obj != None:\n"
    
    
        # Vertices
        if len(obj.data.vertices) > 0:
            script += "        verts = ["
            for v in obj.data.vertices:
                script += "(" + str(v.co[0]) + "*size, " + str(v.co[1]) + "*size, " + str(v.co[2]) + "*size), "
            script += "]\n"
    
        # Edges
        if len(obj.data.edges) > 0:
            script += "        edges = ["
            for e in obj.data.edges:
                script += "(" + str(e.vertices[0]) + ", " + str(e.vertices[1]) + "), "
            script += "]\n"
    
        # Faces
        if len(obj.data.polygons) > 0:
            script += "        faces = ["
            for f in obj.data.polygons:
                script += "("
                for v in f.vertices:
                    script += str(v) + ", "
                script += "), "
            script += "]\n"
    
        # Build mesh
        script += "\n        mesh = obj.data\n"
        script += "        mesh.from_pydata(verts, edges, faces)\n"
        script += "        mesh.update()\n"
        script += "        mesh.update()\n"
        script += "        return obj\n"
        script += "    else:\n"
        script += "        return None\n"
    
        return script
    
    
    
    def random_id(length=8):
    
        """ Generates a random alphanumeric id string.
        """
        tlength = int(length / 2)
        rlength = int(length / 2) + int(length % 2)
    
    
        chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
        text = ""
    
        for i in range(0, rlength):
            text += random.choice(chars)
        text += str(hex(int(time.time())))[2:][-tlength:].rjust(tlength, '0')[::-1]
    
        return text
    
    
    
    #=============================================
    # Color correction functions
    #=============================================
    
    def linsrgb_to_srgb (linsrgb):
        """Convert physically linear RGB values into sRGB ones. The transform is
        uniform in the components, so *linsrgb* can be of any shape.
    
        *linsrgb* values should range between 0 and 1, inclusively.
    
        """
        # From Wikipedia, but easy analogue to the above.
        gamma = 1.055 * linsrgb**(1./2.4) - 0.055
        scale = linsrgb * 12.92
        # return np.where (linsrgb > 0.0031308, gamma, scale)
        if linsrgb > 0.0031308:
            return gamma
        return scale
    
    
    def gamma_correct(color):
    
        corrected_color = Color()
        for i, component in enumerate(color):
            corrected_color[i] = linsrgb_to_srgb(color[i])
        return corrected_color