-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap_vertex_groups.py
85 lines (67 loc) · 2.65 KB
/
swap_vertex_groups.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
bl_info = {
"name": "Swap Vertex Group Data",
"description": "Swaps vertex group data between two vertex groups.",
"author": "LQR471814",
"blender": (2, 90, 0),
"category": "Mesh",
}
import bpy
class OPERATOR_OT_SwapVertexGroups(bpy.types.Operator):
bl_idname = "object.swap_vertex_groups"
bl_label = "Swap Vertex Groups"
bl_description = "Swaps vertex group data between two vertex groups."
bl_options = {'REGISTER', 'UNDO'}
g1 : bpy.props.StringProperty(name = "First Vertex Group", default = "")
g2 : bpy.props.StringProperty(name = "Second Vertex Group", default = "")
@classmethod
def poll(cls, context):
return context.active_object is not None
def execute(self, context):
selected = context.selected_objects
for obj in selected:
vg1 = obj.vertex_groups.get(self.g1)
vg2 = obj.vertex_groups.get(self.g2)
if vg1 == None:
self.report({'ERROR'}, "First vertex group does not exist in object!")
return {"CANCELLED"}
elif vg2 == None:
self.report({'ERROR'}, "Second vertex group does not exist in object!")
return {"CANCELLED"}
vg_idx1 = vg1.index
vs1 = getVertexAndWeights(obj, vg_idx1)
vg_idx2 = vg2.index
vs2 = getVertexAndWeights(obj, vg_idx2)
try:
vg1.remove(list(vs1.keys()))
vg2.remove(list(vs2.keys()))
except RuntimeError:
self.report({'ERROR'}, "This action cannot be performed in edit mode!")
return {"CANCELLED"}
for key in list(vs1.keys()):
vg2.add([key], vs1[key], 'REPLACE')
for key in list(vs2.keys()):
vg1.add([key], vs2[key], 'REPLACE')
return {"FINISHED"}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
def getVertexAndWeights(obj, grp_idx):
vs = {}
for v in obj.data.vertices:
try:
if grp_idx in [vg.group for vg in v.groups]:
vs[v.index] = v.groups[0].weight
except RuntimeError:
vs[v.index] = 0
except IndexError:
vs[v.index] = 0
return vs
def menu_func(self, context):
self.layout.operator(OPERATOR_OT_SwapVertexGroups.bl_idname)
def register():
bpy.utils.register_class(OPERATOR_OT_SwapVertexGroups)
bpy.types.TOPBAR_MT_app_system.append(menu_func)
def unregister():
bpy.utils.unregister_class(OPERATOR_OT_SwapVertexGroups)
bpy.types.TOPBAR_MT_app_system.remove(menu_func)
if __name__ == "__main__":
register()