use new preferences standard and fixes for various blender changes
[blender-addons-contrib.git] / mesh_show_vgroup_weights.py
1 # ***** BEGIN GPL LICENSE BLOCK *****
2 #
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software Foundation,
16 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 #
18 # ***** END GPL LICENCE BLOCK *****
19
20 # <pep8 compliant> (Thanks to CodemanX on IRC)
21
22 bl_info = {
23     "name": "Show Vertex Groups/Weights",
24     "author": "Jason van Gumster (Fweeb), Bartius Crouch",
25     "version": (0, 7, 1),
26     "blender": (2, 62, 0),
27     "location": "3D View > Properties Region > Show Weights",
28     "description": "Finds the vertex groups of a selected vertex and displays the corresponding weights",
29     "warning": "",
30     "wiki_url": "http://wiki.blender.org/index.php/Extensions:2.6/Py/"\
31         "Scripts/Modeling/Show_Vertex_Group_Weights",
32     "tracker_url": "http://projects.blender.org/tracker/index.php?"\
33         "func=detail&aid=30609",
34     "category": "Mesh"}
35
36 #TODO - Add button for selecting vertices with no groups
37
38
39 import bpy, bmesh, bgl, blf, mathutils
40
41
42 # Borrowed/Modified from Bart Crouch's old Index Visualizer add-on
43 def calc_callback(self, context):
44     #polling
45     if context.mode != "EDIT_MESH" or len(context.active_object.vertex_groups) == 0:
46         return
47
48     # get color info from theme
49     acol = context.user_preferences.themes[0].view_3d.editmesh_active
50     tcol = (acol[0] * 0.85, acol[1] * 0.85, acol[2] * 0.85)
51     
52     # get screen information
53     mid_x = context.region.width / 2.0
54     mid_y = context.region.height / 2.0
55     width = context.region.width
56     height = context.region.height
57     
58     # get matrices
59     view_mat = context.space_data.region_3d.perspective_matrix
60     ob_mat = context.active_object.matrix_world
61     total_mat = view_mat * ob_mat
62     
63     # calculate location info
64     texts = []
65     locs = []
66     weights  = []
67     me = context.active_object.data
68     bm = bmesh.from_edit_mesh(me)
69     dvert_lay = bm.verts.layers.deform.active
70
71     for v in bm.verts:
72         if v.select: #XXX Should check v.hide here, but it doesn't work
73             if bm.select_mode == {'VERT'} and bm.select_history.active is not None and bm.select_history.active.index == v.index:
74                 locs.append([acol[0], acol[1], acol[2], v.index, v.co.to_4d()])
75             else:
76                 locs.append([tcol[0], tcol[1], tcol[2], v.index, v.co.to_4d()])
77             dvert = v[dvert_lay]
78             for vgroup in context.active_object.vertex_groups:
79                 if vgroup.index in dvert.keys():
80                     weights += [v.index, vgroup.index, dvert[vgroup.index]]
81
82     for loc in locs:
83         vec = total_mat * loc[4] # order is important
84         # dehomogenise
85         vec = mathutils.Vector((vec[0] / vec[3], vec[1] / vec[3], vec[2] / vec[3]))
86         x = int(mid_x + vec[0] * width / 2.0)
87         y = int(mid_y + vec[1] * height / 2.0)
88         texts += [loc[0], loc[1], loc[2], loc[3], x, y, 0]
89
90     # store as ID property in mesh
91     context.active_object.data["show_vgroup_verts"] = texts
92     context.active_object.data["show_vgroup_weights"] = weights
93
94
95 # draw in 3d-view
96 def draw_callback(self, context):
97     # polling
98     if context.mode != "EDIT_MESH" or len(context.active_object.vertex_groups) == 0:
99         return
100     # retrieving ID property data
101     try:
102         texts = context.active_object.data["show_vgroup_verts"]
103         weights = context.active_object.data["show_vgroup_weights"]
104     except:
105         return
106     if not texts:
107         return
108
109     bm = bmesh.from_edit_mesh(context.active_object.data)
110
111     if bm.select_mode == {'VERT'} and bm.select_history.active is not None:
112         active_vert = bm.select_history.active
113     else:
114         active_vert = None
115
116     # draw
117     blf.size(0, 13, 72)
118     blf.enable(0, blf.SHADOW)
119     blf.shadow(0, 3, 0.0, 0.0, 0.0, 1.0)
120     blf.shadow_offset(0, 2, -2)
121     for i in range(0, len(texts), 7):
122         bgl.glColor3f(texts[i], texts[i+1], texts[i+2])
123         blf.position(0, texts[i+4], texts[i+5], texts[i+6])
124         blf.draw(0, "Vertex " + str(int(texts[i+3])) + ":")
125         font_y = texts[i+5]
126         group_name = ""
127         for j in range(0, len(weights), 3):
128             if int(weights[j]) == int(texts[i+3]):
129                 font_y -= 13
130                 blf.position(0, texts[i+4] + 10, font_y, texts[i+6])
131                 for group in context.active_object.vertex_groups:
132                     if group.index == int(weights[j+1]):
133                         group_name = group.name
134                         break
135                 blf.draw(0, group_name + ": %.3f" % weights[j+2])
136         if group_name == "":
137             font_y -= 13
138             blf.position(0, texts[i+4] + 10, font_y, texts[i+6])
139             blf.draw(0, "No Groups")
140
141     # restore defaults
142     blf.disable(0, blf.SHADOW)
143
144
145 # operator
146 class ShowVGroupWeights(bpy.types.Operator):
147     bl_idname = "view3d.show_vgroup_weights"
148     bl_label = "Show Vertex Group Weights"
149     bl_description = "Toggle the display of the vertex groups and weights for selected vertices"
150     
151     @classmethod
152     def poll(cls, context):
153         return context.mode == 'EDIT_MESH'
154     
155     def __del__(self):
156         bpy.context.scene.display_indices = -1
157         clear_properties(full=False)
158     
159     def modal(self, context, event):
160         if context.area:
161             context.area.tag_redraw()
162
163         # removal of callbacks when operator is called again
164         if context.scene.display_indices == -1:
165             context.region.callback_remove(self.handle1)
166             context.region.callback_remove(self.handle2)
167             context.scene.display_indices = 0
168             return {'CANCELLED'}
169         
170         return {'PASS_THROUGH'}
171     
172     def invoke(self, context, event):
173         if context.area.type == 'VIEW_3D':
174             if context.scene.display_indices < 1:
175                 # operator is called for the first time, start everything
176                 context.scene.display_indices = 1
177                 self.handle1 = context.region.callback_add(calc_callback,
178                     (self, context), 'POST_VIEW')
179                 self.handle2 = context.region.callback_add(draw_callback,
180                     (self, context), 'POST_PIXEL')
181                 context.window_manager.modal_handler_add(self)
182                 return {'RUNNING_MODAL'}
183             else:
184                 # operator is called again, stop displaying
185                 context.scene.display_indices = -1
186                 clear_properties(full=False)
187                 return {'RUNNING_MODAL'}
188         else:
189             self.report({'WARNING'}, "View3D not found, can't run operator")
190             return {'CANCELLED'}
191
192
193 # removal of ID-properties when script is disabled
194 def clear_properties(full=True):
195     # can happen on reload
196     if bpy.context.scene is None:
197         return
198     
199     if "show_vgroup_verts" in bpy.context.active_object.data.keys():
200         del bpy.context.active_object.data["show_vgroup_verts"]
201     if "show_vgroup_weights" in bpy.context.active_object.data.keys():
202         del bpy.context.active_object.data["show_vgroup_weights"]
203     if full:
204         props = ["display_indices"]
205         for p in props:
206             if p in bpy.types.Scene.bl_rna.properties:
207                 exec("del bpy.types.Scene." + p)
208             if p in bpy.context.scene.keys():
209                 del bpy.context.scene[p]
210
211
212 class AssignVertexWeight(bpy.types.Operator):
213     bl_idname = "mesh.vertex_group_assign"
214     bl_label = "Assign Weights"
215     bl_description = "Assign weights for all of the groups on a specific vertex"
216
217     vgroup_weights = bpy.props.StringProperty(name = "Vertex Group Weights")
218
219     @classmethod
220     def poll(cls, context):
221         return context.mode == 'EDIT_MESH'
222
223     def execute(self, context):
224         me = context.active_object.data
225         bm = bmesh.from_edit_mesh(me)
226         dvert_lay = bm.verts.layers.deform.active
227         weights = eval(self.vgroup_weights) #XXX Would be nice if I didn't have to use an eval
228
229         for v in bm.verts:
230             if v.index == weights["__index__"]:
231                 del weights["__index__"]
232                 dvert = v[dvert_lay]
233                 for vgroup in dvert.keys():
234                     dvert[vgroup] = weights[vgroup]
235                 break
236
237         return {'FINISHED'}
238
239
240 class RemoveFromVertexGroup(bpy.types.Operator):
241     bl_idname = "mesh.vertex_group_remove"
242     bl_label = "Remove Vertex from Group"
243     bl_description = "Remove a specific vertex from a specific vertex group"
244
245     #XXX abusing vector props here a bit; the first element is the vert index and the second is the group index
246     vert_and_group = bpy.props.IntVectorProperty(name = "Vertex and Group to remove", size = 2)
247
248     @classmethod
249     def poll(cls, context):
250         return context.mode == 'EDIT_MESH'
251
252     def execute(self, context):
253         ob = context.active_object
254         me = ob.data
255         bm = bmesh.from_edit_mesh(me)
256
257         # Save current selection
258         selected_verts = []
259         for v in bm.verts:
260             if v.select is True:
261                 selected_verts.append(v.index)
262                 if v.index != self.vert_and_group[0]:
263                     v.select = False
264
265         ob.vertex_groups.active_index = self.vert_and_group[1]
266         bpy.ops.object.vertex_group_remove_from()
267
268         # Re-select vertices
269         for v in bm.verts:
270             if v.index in selected_verts:
271                 v.select = True
272
273         #XXX Hacky, but there's no other way to update the UI panels
274         bpy.ops.object.editmode_toggle()
275         bpy.ops.object.editmode_toggle()
276         return {'FINISHED'}
277
278
279 class AddToVertexGroup(bpy.types.Operator):
280     bl_idname = "mesh.vertex_group_add"
281     bl_label = "Add Vertex to Group"
282     bl_description = "Add a specific vertex to a specific vertex group"
283
284     def avail_vgroups(self, context):
285         ob = context.active_object
286         bm = bmesh.from_edit_mesh(ob.data)
287         dvert_lay = bm.verts.layers.deform.active
288         items = []
289         self.vertex = bm.select_history.active.index
290
291         dvert = bm.select_history.active[dvert_lay]
292
293         items.append(("-1", "New Vertex Group", "-1", -1))
294
295         for i in ob.vertex_groups:
296             if i.index not in dvert.keys():
297                 items.append((i.name, i.name, str(i.index), i.index))
298
299         return items
300
301     vertex = bpy.props.IntProperty()
302     available_vgroups = bpy.props.EnumProperty(items = avail_vgroups, name = "Available Groups")
303
304     @classmethod
305     def poll(cls, context):
306         return context.mode == 'EDIT_MESH'
307
308     def execute(self, context):
309         ob = context.active_object
310         me = ob.data
311         bm = bmesh.from_edit_mesh(me)
312         #print(self.available_vgroups)
313
314         # Save current selection
315         selected_verts = []
316         for v in bm.verts:
317             if v.select is True:
318                 selected_verts.append(v.index)
319                 if v.index != self.vertex:
320                     v.select = False
321
322         weight = context.tool_settings.vertex_group_weight
323         context.tool_settings.vertex_group_weight = 1.0
324         if self.available_vgroups == "-1":
325             bpy.ops.object.vertex_group_assign(new = True) #XXX Assumes self.vertex is the active vertex
326         else:
327             bpy.ops.object.vertex_group_set_active(group = self.available_vgroups)
328             bpy.ops.object.vertex_group_assign() #XXX Assumes self.vertex is the active vertex
329         context.tool_settings.vertex_group_weight = weight
330
331         # Re-select vertices
332         for v in bm.verts:
333             if v.index in selected_verts:
334                 v.select = True
335
336         #XXX Hacky, but there's no other way to update the UI panels
337         bpy.ops.object.editmode_toggle()
338         bpy.ops.object.editmode_toggle()
339         return {'FINISHED'}
340
341
342 class PanelShowWeights(bpy.types.Panel):
343     bl_label = "Show Weights"
344     bl_space_type = "VIEW_3D"
345     bl_region_type = "UI"
346     bl_options = {'DEFAULT_CLOSED'}
347
348     @classmethod
349     def poll(cls, context):
350         return context.mode == 'EDIT_MESH'
351
352     def draw(self, context):
353         layout = self.layout
354         ob = context.active_object
355         me = ob.data
356         bm = bmesh.from_edit_mesh(me)
357         dvert_lay = bm.verts.layers.deform.active
358
359         if context.scene.display_indices < 1:
360             layout.operator(ShowVGroupWeights.bl_idname, text = "Show Weights Overlay")
361         else:
362             layout.operator(ShowVGroupWeights.bl_idname, text = "Hide Weights Overlay")
363
364         if len(ob.vertex_groups) > 0:
365             # Active vertex
366             active_vert = bm.select_history.active
367             sub = layout.box()
368             col = sub.column(align = True)
369             if bm.select_mode == {'VERT'} and active_vert is not None:
370                 col.label(text = "Active Vertex")
371                 row = col.row()
372                 row.label(text = "Vertex " + str(active_vert.index) + ":")
373                 row.operator_menu_enum("mesh.vertex_group_add", "available_vgroups", text = "Add Group", icon = 'GROUP_VERTEX')
374                 has_groups = False
375                 vgroup_weights = {}
376
377                 for i in me.vertices:
378                     if i.index == active_vert.index:
379                         vgroup_weights["__index__"] = i.index
380                         for j in range(len(i.groups)):
381                             for k in ob.vertex_groups:
382                                 if k.index == i.groups[j].group:
383                                     has_groups = True
384                                     split = col.split(percentage = 0.90, align = True)
385                                     vgroup_weights[k.index] = i.groups[j].weight
386                                     row = split.row(align = True)
387                                     row.prop(i.groups[j], "weight", text = k.name, slider = True, emboss = not k.lock_weight)
388                                     row = split.row(align = True)
389                                     row.operator("mesh.vertex_group_remove", text = "R").vert_and_group = (i.index, k.index)
390                 
391                 if not has_groups:
392                     col.label(text = "    No Groups")
393                 else:
394                     col.operator("mesh.vertex_group_assign").vgroup_weights = str(vgroup_weights)
395                 layout.separator()
396             else:
397                 col.label(text = "No Active Vertex")
398             layout.prop(context.window_manager, "show_vgroups_show_all", toggle = True)
399             # All selected vertices (except for the active vertex)
400             if context.window_manager.show_vgroups_show_all:
401                 for v in bm.verts:
402                     if v.select:
403                         if active_vert is not None and v.index == active_vert.index:
404                             continue
405                         sub = layout.box()
406                         col = sub.column(align = True)
407                         col.label(text = "Vertex " + str(v.index) + ":")
408                         has_groups = False
409                         vgroup_weights = {}
410                         for i in me.vertices:
411                             if i.index == v.index:
412                                 vgroup_weights["__index__"] = i.index
413                                 for j in range(len(i.groups)):
414                                     for k in ob.vertex_groups:
415                                         if k.index == i.groups[j].group:
416                                             has_groups = True
417                                             split = col.split(percentage = 0.90, align = True)
418                                             vgroup_weights[k.index] = i.groups[j].weight
419                                             row = split.row(align = True)
420                                             row.prop(i.groups[j], "weight", text = k.name, slider = True, emboss = not k.lock_weight)
421                                             row = split.row(align = True)
422                                             row.operator("mesh.vertex_group_remove", text = "R").vert_and_group = (i.index, k.index)
423                         if not has_groups:
424                             col.label(text = "    No Groups")
425                         else:
426                             col.operator("mesh.vertex_group_assign").vgroup_weights = str(vgroup_weights)
427         else:
428             layout.label(text = "No Groups")
429
430
431 def register():
432     bpy.types.WindowManager.show_vgroups_show_all = bpy.props.BoolProperty(
433         name = "Show All Selected Vertices",
434         description = "Show all vertices with vertex groups assigned to them",
435         default = False)
436     bpy.types.Mesh.assign_vgroup = bpy.props.StringProperty()
437     bpy.utils.register_class(ShowVGroupWeights)
438     bpy.types.Scene.display_indices = bpy.props.IntProperty(
439         name="Display indices",
440         default=0)
441     bpy.utils.register_class(AssignVertexWeight)
442     bpy.utils.register_class(RemoveFromVertexGroup)
443     bpy.utils.register_class(AddToVertexGroup)
444     bpy.utils.register_class(PanelShowWeights)
445     
446
447 def unregister():
448     bpy.utils.unregister_class(ShowVGroupWeights)
449     clear_properties()
450     bpy.utils.unregister_class(AssignVertexWeight)
451     bpy.utils.unregister_class(RemoveFromVertexGroup)
452     bpy.utils.unregister_class(AddToVertexGroup)
453     bpy.utils.unregister_class(PanelShowWeights)
454     del bpy.types.WindowManager.show_vgroups_show_all
455     del bpy.types.Mesh.assign_vgroup
456
457 if __name__ == "__main__":
458     register()