Merged revision(s) 57908-57978 from trunk/blender into soc-2013-dingto.
[blender.git] / source / blender / editors / object / object_vgroup.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Ove M Henriksen.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_vgroup.c
29  *  \ingroup edobj
30  */
31
32 #include <string.h>
33 #include <stddef.h>
34 #include <math.h>
35 #include <assert.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "DNA_cloth_types.h"
40 #include "DNA_curve_types.h"
41 #include "DNA_lattice_types.h"
42 #include "DNA_meshdata_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_modifier_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_object_force.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_particle_types.h"
49
50 #include "BLI_array.h"
51 #include "BLI_math.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_utildefines.h"
54
55 #include "BLF_translation.h"
56
57 #include "BKE_context.h"
58 #include "BKE_customdata.h"
59 #include "BKE_deform.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_global.h"
62 #include "BKE_mesh.h"
63 #include "BKE_editmesh.h"
64 #include "BKE_report.h"
65 #include "BKE_DerivedMesh.h"
66 #include "BKE_object_deform.h"
67 #include "BKE_object.h"
68 #include "BKE_lattice.h"
69
70 #include "DNA_armature_types.h"
71 #include "RNA_access.h"
72 #include "RNA_define.h"
73 #include "RNA_enum_types.h"
74
75 #include "WM_api.h"
76 #include "WM_types.h"
77
78 #include "ED_object.h"
79 #include "ED_mesh.h"
80
81 #include "UI_resources.h"
82
83 #include "object_intern.h"
84
85 /************************ Exported Functions **********************/
86 static void vgroup_remap_update_users(Object *ob, int *map);
87 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *defgroup);
88 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg);
89 static void vgroup_delete_all(Object *ob);
90 static bool ED_vgroup_give_parray(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, const bool use_vert_sel);
91
92 static bool vertex_group_use_vert_sel(Object *ob)
93 {
94         if (ob->mode == OB_MODE_EDIT) {
95                 return true;
96         }
97         else if (ob->type == OB_MESH && ((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) {
98                 return true;
99         }
100         else {
101                 return false;
102         }
103 }
104
105 static Lattice *vgroup_edit_lattice(Object *ob)
106 {
107         Lattice *lt = ob->data;
108         BLI_assert(ob->type == OB_LATTICE);
109         return (lt->editlatt) ? lt->editlatt->latt : lt;
110 }
111
112 bool ED_vgroup_object_is_edit_mode(Object *ob)
113 {
114         if (ob->type == OB_MESH)
115                 return (BKE_editmesh_from_object(ob) != NULL);
116         else if (ob->type == OB_LATTICE)
117                 return (((Lattice *)ob->data)->editlatt != NULL);
118
119         return false;
120 }
121
122 bDeformGroup *ED_vgroup_add_name(Object *ob, const char *name)
123 {
124         bDeformGroup *defgroup;
125
126         if (!ob || !OB_TYPE_SUPPORT_VGROUP(ob->type))
127                 return NULL;
128         
129         defgroup = MEM_callocN(sizeof(bDeformGroup), "add deformGroup");
130
131         BLI_strncpy(defgroup->name, name, sizeof(defgroup->name));
132
133         BLI_addtail(&ob->defbase, defgroup);
134         defgroup_unique_name(defgroup, ob);
135
136         ob->actdef = BLI_countlist(&ob->defbase);
137
138         return defgroup;
139 }
140
141 bDeformGroup *ED_vgroup_add(Object *ob) 
142 {
143         return ED_vgroup_add_name(ob, DATA_("Group"));
144 }
145
146 void ED_vgroup_delete(Object *ob, bDeformGroup *defgroup) 
147 {
148         BLI_assert(BLI_findindex(&ob->defbase, defgroup) != -1);
149
150         if (ED_vgroup_object_is_edit_mode(ob))
151                 vgroup_delete_edit_mode(ob, defgroup);
152         else
153                 vgroup_delete_object_mode(ob, defgroup);
154 }
155
156 void ED_vgroup_clear(Object *ob)
157 {
158         bDeformGroup *dg = (bDeformGroup *)ob->defbase.first;
159         int edit_mode = ED_vgroup_object_is_edit_mode(ob);
160
161         while (dg) {
162                 bDeformGroup *next_dg = dg->next;
163
164                 if (edit_mode)
165                         vgroup_delete_edit_mode(ob, dg);
166                 else
167                         vgroup_delete_object_mode(ob, dg);
168
169                 dg = next_dg;
170         }
171 }
172
173 bool ED_vgroup_data_create(ID *id)
174 {
175         /* create deform verts */
176
177         if (GS(id->name) == ID_ME) {
178                 Mesh *me = (Mesh *)id;
179                 me->dvert = CustomData_add_layer(&me->vdata, CD_MDEFORMVERT, CD_CALLOC, NULL, me->totvert);
180                 return true;
181         }
182         else if (GS(id->name) == ID_LT) {
183                 Lattice *lt = (Lattice *)id;
184                 lt->dvert = MEM_callocN(sizeof(MDeformVert) * lt->pntsu * lt->pntsv * lt->pntsw, "lattice deformVert");
185                 return true;
186         }
187         else {
188                 return false;
189         }
190 }
191
192 /**
193  * Removes out of range MDeformWeights
194  */
195 void ED_vgroup_data_clamp_range(ID *id, const int total)
196 {
197         MDeformVert **dvert_arr;
198         int dvert_tot;
199
200         if (ED_vgroup_give_parray(id, &dvert_arr, &dvert_tot, false)) {
201                 int i;
202                 for (i = 0; i < dvert_tot; i++) {
203                         MDeformVert *dv = dvert_arr[i];
204                         int j;
205                         for (j = 0; j < dv->totweight; j++) {
206                                 if (dv->dw[j].def_nr >= total) {
207                                         defvert_remove_group(dv, &dv->dw[j]);
208                                         j--;
209                                 }
210                         }
211                 }
212         }
213 }
214
215 static bool ED_vgroup_give_parray(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, const bool use_vert_sel)
216 {
217         *dvert_tot = 0;
218         *dvert_arr = NULL;
219
220         if (id) {
221                 switch (GS(id->name)) {
222                         case ID_ME:
223                         {
224                                 Mesh *me = (Mesh *)id;
225
226                                 if (me->edit_btmesh) {
227                                         BMEditMesh *em = me->edit_btmesh;
228                                         BMesh *bm = em->bm;
229                                         const int cd_dvert_offset  = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
230                                         BMIter iter;
231                                         BMVert *eve;
232                                         int i;
233
234                                         if (cd_dvert_offset == -1) {
235                                                 return false;
236                                         }
237
238                                         i = em->bm->totvert;
239
240                                         *dvert_arr = MEM_mallocN(sizeof(void *) * i, "vgroup parray from me");
241                                         *dvert_tot = i;
242
243                                         i = 0;
244                                         if (use_vert_sel) {
245                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
246                                                         (*dvert_arr)[i] = BM_elem_flag_test(eve, BM_ELEM_SELECT) ?
247                                                                           BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset) : NULL;
248                                                         i++;
249                                                 }
250                                         }
251                                         else {
252                                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
253                                                         (*dvert_arr)[i] = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
254                                                         i++;
255                                                 }
256                                         }
257
258                                         return true;
259                                 }
260                                 else if (me->dvert) {
261                                         MVert *mvert = me->mvert;
262                                         MDeformVert *dvert = me->dvert;
263                                         int i;
264
265                                         *dvert_tot = me->totvert;
266                                         *dvert_arr = MEM_mallocN(sizeof(void *) * me->totvert, "vgroup parray from me");
267
268                                         if (use_vert_sel) {
269                                                 for (i = 0; i < me->totvert; i++) {
270                                                         (*dvert_arr)[i] = (mvert[i].flag & SELECT) ?
271                                                                           &dvert[i] : NULL;
272                                                 }
273                                         }
274                                         else {
275                                                 for (i = 0; i < me->totvert; i++) {
276                                                         (*dvert_arr)[i] = me->dvert + i;
277                                                 }
278                                         }
279
280                                         return true;
281                                 }
282                                 else {
283                                         return false;
284                                 }
285                         }
286                         case ID_LT:
287                         {
288                                 int i = 0;
289
290                                 Lattice *lt = (Lattice *)id;
291                                 lt = (lt->editlatt) ? lt->editlatt->latt : lt;
292
293                                 if (lt->dvert) {
294                                         BPoint *def = lt->def;
295                                         *dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw;
296                                         *dvert_arr = MEM_mallocN(sizeof(void *) * (*dvert_tot), "vgroup parray from me");
297
298                                         if (use_vert_sel) {
299                                                 for (i = 0; i < *dvert_tot; i++) {
300                                                         (*dvert_arr)[i] = (def->f1 & SELECT) ?
301                                                                            &lt->dvert[i] : NULL;
302                                                 }
303                                         }
304                                         else {
305                                                 for (i = 0; i < *dvert_tot; i++) {
306                                                         (*dvert_arr)[i] = lt->dvert + i;
307                                                 }
308                                         }
309
310                                         return true;
311                                 }
312                                 else {
313                                         return false;
314                                 }
315                         }
316                 }
317         }
318
319         return false;
320 }
321
322 /* returns true if the id type supports weights */
323 bool ED_vgroup_give_array(ID *id, MDeformVert **dvert_arr, int *dvert_tot)
324 {
325         if (id) {
326                 switch (GS(id->name)) {
327                         case ID_ME:
328                         {
329                                 Mesh *me = (Mesh *)id;
330                                 *dvert_arr = me->dvert;
331                                 *dvert_tot = me->totvert;
332                                 return true;
333                         }
334                         case ID_LT:
335                         {
336                                 Lattice *lt = (Lattice *)id;
337                                 lt = (lt->editlatt) ? lt->editlatt->latt : lt;
338                                 *dvert_arr = lt->dvert;
339                                 *dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw;
340                                 return true;
341                         }
342                 }
343         }
344
345         *dvert_arr = NULL;
346         *dvert_tot = 0;
347         return false;
348 }
349
350 /* matching index only */
351 bool ED_vgroup_copy_array(Object *ob, Object *ob_from)
352 {
353         MDeformVert **dvert_array_from, **dvf;
354         MDeformVert **dvert_array, **dv;
355         int dvert_tot_from;
356         int dvert_tot;
357         int i;
358         int defbase_tot_from = BLI_countlist(&ob_from->defbase);
359         int defbase_tot = BLI_countlist(&ob->defbase);
360         bool new_vgroup = false;
361
362         ED_vgroup_give_parray(ob_from->data, &dvert_array_from, &dvert_tot_from, false);
363         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
364
365         if ((dvert_array == NULL) && (dvert_array_from != NULL) && ED_vgroup_data_create(ob->data)) {
366                 ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
367                 new_vgroup = true;
368         }
369
370         if (ob == ob_from || dvert_tot == 0 || (dvert_tot != dvert_tot_from) || dvert_array_from == NULL || dvert_array == NULL) {
371                 if (dvert_array) MEM_freeN(dvert_array);
372                 if (dvert_array_from) MEM_freeN(dvert_array_from);
373
374                 if (new_vgroup == true) {
375                         /* free the newly added vgroup since it wasn't compatible */
376                         vgroup_delete_all(ob);
377                 }
378                 return false;
379         }
380
381         /* do the copy */
382         BLI_freelistN(&ob->defbase);
383         BLI_duplicatelist(&ob->defbase, &ob_from->defbase);
384         ob->actdef = ob_from->actdef;
385
386         if (defbase_tot_from < defbase_tot) {
387                 /* correct vgroup indices because the number of vgroups is being reduced. */
388                 int *remap = MEM_mallocN(sizeof(int) * (defbase_tot + 1), __func__);
389                 for (i = 0; i <= defbase_tot_from; i++) remap[i] = i;
390                 for (; i <= defbase_tot; i++) remap[i] = 0;  /* can't use these, so disable */
391
392                 vgroup_remap_update_users(ob, remap);
393                 MEM_freeN(remap);
394         }
395
396         dvf = dvert_array_from;
397         dv = dvert_array;
398
399         for (i = 0; i < dvert_tot; i++, dvf++, dv++) {
400                 if ((*dv)->dw)
401                         MEM_freeN((*dv)->dw);
402
403                 *(*dv) = *(*dvf);
404
405                 if ((*dv)->dw)
406                         (*dv)->dw = MEM_dupallocN((*dv)->dw);
407         }
408
409         MEM_freeN(dvert_array);
410         MEM_freeN(dvert_array_from);
411
412         return true;
413 }
414
415 /* TODO, cache flip data to speedup calls within a loop. */
416 static void mesh_defvert_mirror_update_internal(Object *ob,
417                                                 MDeformVert *dvert_dst, MDeformVert *dvert_src,
418                                                 const int def_nr)
419 {
420         if (def_nr == -1) {
421                 /* all vgroups, add groups where neded  */
422                 int flip_map_len;
423                 int *flip_map = defgroup_flip_map(ob, &flip_map_len, true);
424                 defvert_sync_mapped(dvert_dst, dvert_src, flip_map, flip_map_len, true);
425                 MEM_freeN(flip_map);
426         }
427         else {
428                 /* single vgroup */
429                 MDeformWeight *dw = defvert_verify_index(dvert_dst, defgroup_flip_index(ob, def_nr, 1));
430                 if (dw) {
431                         dw->weight = defvert_find_weight(dvert_src, def_nr);
432                 }
433         }
434 }
435
436 static void ED_mesh_defvert_mirror_update_em(Object *ob, BMVert *eve, int def_nr, int vidx,
437                                              const int cd_dvert_offset)
438 {
439         Mesh *me = ob->data;
440         BMEditMesh *em = me->edit_btmesh;
441         BMVert *eve_mirr;
442         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
443
444         eve_mirr = editbmesh_get_x_mirror_vert(ob, em, eve, eve->co, vidx, use_topology);
445
446         if (eve_mirr && eve_mirr != eve) {
447                 MDeformVert *dvert_src = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
448                 MDeformVert *dvert_dst = BM_ELEM_CD_GET_VOID_P(eve_mirr, cd_dvert_offset);
449                 mesh_defvert_mirror_update_internal(ob, dvert_dst, dvert_src, def_nr);
450         }
451 }
452
453 static void ED_mesh_defvert_mirror_update_ob(Object *ob, int def_nr, int vidx)
454 {
455         int vidx_mirr;
456         Mesh *me = ob->data;
457         bool use_topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
458
459         if (vidx == -1)
460                 return;
461
462         vidx_mirr = mesh_get_x_mirror_vert(ob, vidx, use_topology);
463
464         if ((vidx_mirr) >= 0 && (vidx_mirr != vidx)) {
465                 MDeformVert *dvert_src = &me->dvert[vidx];
466                 MDeformVert *dvert_dst = &me->dvert[vidx_mirr];
467                 mesh_defvert_mirror_update_internal(ob, dvert_dst, dvert_src, def_nr);
468         }
469 }
470
471 /**
472  * Use when adjusting the active vertex weight and apply to mirror vertices.
473  */
474 void ED_vgroup_vert_active_mirror(Object *ob, int def_nr)
475 {
476         Mesh *me = ob->data;
477         BMEditMesh *em = me->edit_btmesh;
478         MDeformVert *dvert_act;
479
480         if (me->editflag & ME_EDIT_MIRROR_X) {
481                 if (em) {
482                         BMVert *eve_act;
483                         dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
484                         if (dvert_act) {
485                                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
486                                 ED_mesh_defvert_mirror_update_em(ob, eve_act, def_nr, -1, cd_dvert_offset);
487                         }
488                 }
489                 else {
490                         int v_act;
491                         dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
492                         if (dvert_act) {
493                                 ED_mesh_defvert_mirror_update_ob(ob, def_nr, v_act);
494                         }
495                 }
496         }
497 }
498
499 static void vgroup_remove_weight(Object *ob, const int def_nr)
500 {
501         MDeformVert *dvert_act;
502         MDeformWeight *dw;
503
504         dvert_act = ED_mesh_active_dvert_get_only(ob);
505
506         dw = defvert_find_index(dvert_act, def_nr);
507         defvert_remove_group(dvert_act, dw);
508
509 }
510
511 static void vgroup_normalize_active(Object *ob, eVGroupSelect subset_type)
512 {
513         Mesh *me = ob->data;
514         BMEditMesh *em = me->edit_btmesh;
515         BMVert *eve_act;
516         int v_act;
517         MDeformVert *dvert_act;
518         int subset_count, vgroup_tot;
519         const bool *vgroup_validmap;
520
521
522         if (em) {
523                 dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
524         }
525         else {
526                 dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
527         }
528
529         if (dvert_act == NULL) {
530                 return;
531         }
532
533         vgroup_validmap = ED_vgroup_subset_from_select_type(ob, subset_type, &vgroup_tot, &subset_count);
534         defvert_normalize_subset(dvert_act, vgroup_validmap, vgroup_tot);
535         MEM_freeN((void *)vgroup_validmap);
536
537         if (me->editflag & ME_EDIT_MIRROR_X) {
538                 if (em) {
539                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
540                         ED_mesh_defvert_mirror_update_em(ob, eve_act, -1, -1, cd_dvert_offset);
541                 }
542                 else {
543                         int v_act = BKE_mesh_mselect_active_get(me, ME_VSEL);
544                         ED_mesh_defvert_mirror_update_ob(ob, -1, v_act);
545                 }
546         }
547 }
548
549 static void vgroup_copy_active_to_sel(Object *ob, eVGroupSelect subset_type)
550 {
551         Mesh *me = ob->data;
552         BMEditMesh *em = me->edit_btmesh;
553         MDeformVert *dvert_act;
554         int i, vgroup_tot, subset_count;
555         const bool *vgroup_validmap = ED_vgroup_subset_from_select_type(ob, subset_type, &vgroup_tot, &subset_count);
556
557
558         if (em) {
559                 BMIter iter;
560                 BMVert *eve, *eve_act;
561                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
562
563                 dvert_act = ED_mesh_active_dvert_get_em(ob, &eve_act);
564                 if (dvert_act) {
565                         BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
566                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && eve != eve_act) {
567                                         MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
568                                         defvert_copy_subset(dv, dvert_act, vgroup_validmap, vgroup_tot);
569                                         if (me->editflag & ME_EDIT_MIRROR_X) {
570                                                 ED_mesh_defvert_mirror_update_em(ob, eve, -1, i, cd_dvert_offset);
571                                         }
572                                 }
573                         }
574                 }
575         }
576         else {
577                 MDeformVert *dv;
578                 int v_act;
579
580                 dvert_act = ED_mesh_active_dvert_get_ob(ob, &v_act);
581                 if (dvert_act) {
582                         dv  = me->dvert;
583                         for (i = 0; i < me->totvert; i++, dv++) {
584                                 if ((me->mvert[i].flag & SELECT) && dv != dvert_act) {
585                                         defvert_copy_subset(dv, dvert_act, vgroup_validmap, vgroup_tot);
586                                         if (me->editflag & ME_EDIT_MIRROR_X) {
587                                                 ED_mesh_defvert_mirror_update_ob(ob, -1, i);
588                                         }
589                                 }
590                         }
591                 }
592         }
593
594         MEM_freeN((void *)vgroup_validmap);
595 }
596
597 /***********************Start weight transfer (WT)*********************************/
598
599 typedef enum WT_VertexGroupMode {
600         WT_REPLACE_ACTIVE_VERTEX_GROUP = 1,
601         WT_REPLACE_ALL_VERTEX_GROUPS = 2
602 } WT_VertexGroupMode;
603
604 typedef enum WT_Method {
605         WT_BY_INDEX = 1,
606         WT_BY_NEAREST_VERTEX = 2,
607         WT_BY_NEAREST_FACE = 3,
608         WT_BY_NEAREST_VERTEX_IN_FACE = 4
609 } WT_Method;
610
611 typedef enum WT_ReplaceMode {
612         WT_REPLACE_ALL_WEIGHTS = 1,
613         WT_REPLACE_EMPTY_WEIGHTS = 2
614 } WT_ReplaceMode;
615
616 static EnumPropertyItem WT_vertex_group_mode_item[] = {
617         {WT_REPLACE_ACTIVE_VERTEX_GROUP,
618          "WT_REPLACE_ACTIVE_VERTEX_GROUP", 0, "Active", "Transfer active vertex group from selected to active mesh"},
619         {WT_REPLACE_ALL_VERTEX_GROUPS,
620          "WT_REPLACE_ALL_VERTEX_GROUPS", 0, "All", "Transfer all vertex groups from selected to active mesh"},
621         {0, NULL, 0, NULL, NULL}
622 };
623
624 static EnumPropertyItem WT_method_item[] = {
625         {WT_BY_INDEX,
626          "WT_BY_INDEX", 0, "Vertex index", "Copy for identical meshes"},
627         {WT_BY_NEAREST_VERTEX,
628          "WT_BY_NEAREST_VERTEX", 0, "Nearest vertex", "Copy weight from closest vertex"},
629         {WT_BY_NEAREST_FACE,
630          "WT_BY_NEAREST_FACE", 0, "Nearest face", "Barycentric interpolation from nearest face"},
631         {WT_BY_NEAREST_VERTEX_IN_FACE,
632          "WT_BY_NEAREST_VERTEX_IN_FACE", 0, "Nearest vertex in face", "Copy weight from closest vertex in nearest face"},
633         {0, NULL, 0, NULL, NULL}
634 };
635
636 static EnumPropertyItem WT_replace_mode_item[] = {
637         {WT_REPLACE_ALL_WEIGHTS,
638          "WT_REPLACE_ALL_WEIGHTS", 0, "All", "Overwrite all weights"},
639         {WT_REPLACE_EMPTY_WEIGHTS,
640          "WT_REPLACE_EMPTY_WEIGHTS", 0, "Empty", "Add weights to vertices with no weight"},
641         {0, NULL, 0, NULL, NULL}
642 };
643
644 static EnumPropertyItem WT_vertex_group_select_item[] = {
645         {WT_VGROUP_ACTIVE,
646          "ACTIVE", 0, "Active Group", "The active Vertex Group"},
647         {WT_VGROUP_BONE_SELECT,
648          "BONE_SELECT", 0, "Selected Pose Bones", "All Vertex Groups assigned to Selection"},
649         {WT_VGROUP_BONE_DEFORM,
650          "BONE_DEFORM", 0, "Deform Pose Bones", "All Vertex Groups assigned to Deform Bones"},
651         {WT_VGROUP_ALL,
652          "ALL", 0, "All Groups", "All Vertex Groups"},
653         {0, NULL, 0, NULL, NULL}
654 };
655
656 EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
657         const bContext *C, PointerRNA *UNUSED(ptr),
658         PropertyRNA *UNUSED(prop), int *free, const unsigned int selection_mask)
659 {
660         Object *ob;
661         EnumPropertyItem *item = NULL;
662         int totitem = 0;
663
664
665         if (!C) /* needed for docs and i18n tools */
666                 return WT_vertex_group_select_item;
667
668         ob = CTX_data_active_object(C);
669         if (selection_mask & (1 << WT_VGROUP_ACTIVE))
670                 RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_ACTIVE);
671
672         if (BKE_object_pose_armature_get(ob)) {
673                 if (selection_mask & (1 << WT_VGROUP_BONE_SELECT))
674                         RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_BONE_SELECT);
675                 if (selection_mask & (1 << WT_VGROUP_BONE_DEFORM))
676                         RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_BONE_DEFORM);
677         }
678
679         if (selection_mask & (1 << WT_VGROUP_ALL))
680                 RNA_enum_items_add_value(&item, &totitem, WT_vertex_group_select_item, WT_VGROUP_ALL);
681
682         RNA_enum_item_end(&item, &totitem);
683         *free = true;
684
685         return item;
686 }
687
688 static EnumPropertyItem *rna_vertex_group_with_single_itemf(bContext *C, PointerRNA *ptr,
689                                                             PropertyRNA *prop, int *free)
690 {
691         return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, free, WT_VGROUP_MASK_ALL);
692 }
693
694 static EnumPropertyItem *rna_vertex_group_select_itemf(bContext *C, PointerRNA *ptr,
695                                                        PropertyRNA *prop, int *free)
696 {
697         return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, free, WT_VGROUP_MASK_ALL & ~(1 << WT_VGROUP_ACTIVE));
698 }
699
700 static void vgroup_operator_subset_select_props(wmOperatorType *ot, bool use_active)
701 {
702         PropertyRNA *prop;
703
704         prop = RNA_def_enum(ot->srna,
705                             "group_select_mode", DummyRNA_NULL_items,
706                             use_active ? WT_VGROUP_ACTIVE : WT_VGROUP_ALL, "Subset",
707                             "Define which subset of Groups shall be used");
708
709         if (use_active) {
710                 RNA_def_enum_funcs(prop, rna_vertex_group_with_single_itemf);
711         }
712         else {
713                 RNA_def_enum_funcs(prop, rna_vertex_group_select_itemf);
714         }
715         ot->prop = prop;
716 }
717
718 /* Copy weight.*/
719 static void vgroup_transfer_weight(float *r_weight_dst, const float weight_src, const WT_ReplaceMode replace_mode)
720 {
721         switch (replace_mode) {
722                 case WT_REPLACE_ALL_WEIGHTS:
723                         *r_weight_dst = weight_src;
724                         break;
725
726                 case WT_REPLACE_EMPTY_WEIGHTS:
727                         if (*r_weight_dst == 0.0f) {
728                                 *r_weight_dst = weight_src;
729                         }
730                         break;
731
732                 default:
733                         BLI_assert(0);
734                         break;
735         }
736 }
737
738 /* Could be exposed externally by implementing it in header with the rest.
739  * Simple refactoring will break something.
740  * For now, naming is ed_ instead of ED_*/
741 static bool ed_vgroup_transfer_weight(Object *ob_dst, Object *ob_src, bDeformGroup *dg_src, Scene *scene,
742                                       WT_Method method, WT_ReplaceMode replace_mode, wmOperator *op)
743 {
744         bDeformGroup *dg_dst;
745         Mesh *me_dst, *me_src;
746         DerivedMesh *dmesh_src;
747         BVHTreeFromMesh tree_mesh_vertices_src, tree_mesh_faces_src = {NULL};
748         MDeformVert **dv_array_src, **dv_array_dst, **dv_src, **dv_dst;
749         MVert *mv_dst, *mv_src;
750         MFace *mface_src, *mf;
751         BVHTreeNearest nearest;
752         MDeformWeight *dw_dst, *dw_src;
753         int dv_tot_src, dv_tot_dst, i, v_index, index_dst, index_src, index_nearest, index_nearest_vertex;
754         unsigned int f_index;
755         float weight, tmp_weight[4], tmp_co[3], normal[3], tmp_mat[4][4], dist_v1, dist_v2, dist_v3, dist_v4;
756         const int use_vert_sel = vertex_group_use_vert_sel(ob_dst);
757
758         /* Ensure vertex group on target.*/
759         if (!defgroup_find_name(ob_dst, dg_src->name)) {
760                 ED_vgroup_add_name(ob_dst, dg_src->name);
761         }
762
763         /* Get destination deformgroup.*/
764         dg_dst = defgroup_find_name(ob_dst, dg_src->name);
765
766         /* Get meshes.*/
767         dmesh_src = mesh_get_derived_deform(scene, ob_src, CD_MASK_BAREMESH);
768         me_dst = ob_dst->data;
769         me_src = ob_src->data;
770
771         /* Sanity check.*/
772         if (!me_src->dvert) {
773                 BKE_report(op->reports, RPT_ERROR, "Transfer failed (source mesh does not have any vertex groups)");
774                 return false;
775         }
776
777         /* Create data in memory when nothing there.*/
778         if (!me_dst->dvert) ED_vgroup_data_create(ob_dst->data);
779
780         /* Get vertex group arrays.*/
781         ED_vgroup_give_parray(ob_src->data, &dv_array_src, &dv_tot_src, false);
782         ED_vgroup_give_parray(ob_dst->data, &dv_array_dst, &dv_tot_dst, use_vert_sel);
783
784         /* Get indexes of vertex groups.*/
785         index_src = BLI_findindex(&ob_src->defbase, dg_src);
786         index_dst = BLI_findindex(&ob_dst->defbase, dg_dst);
787
788         /* Get vertices.*/
789         mv_dst = me_dst->mvert;
790         mv_src = dmesh_src->getVertArray(dmesh_src);
791
792         /* Prepare transformation matrix.*/
793         invert_m4_m4(ob_src->imat, ob_src->obmat);
794         mul_m4_m4m4(tmp_mat, ob_src->imat, ob_dst->obmat);
795
796         /* Clear weights.*/
797         if (replace_mode == WT_REPLACE_ALL_WEIGHTS) {
798                 for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++) {
799
800                         if (*dv_dst == NULL) continue;
801
802                         dw_dst = defvert_find_index(*dv_dst, index_dst);
803                         /* Remove vertex from group.*/
804                         if (dw_dst) defvert_remove_group(*dv_dst, dw_dst);
805                 }
806         }
807
808         switch (method) {
809
810                 case WT_BY_INDEX:
811                         /* Check if indices are matching, delete and return if not.*/
812                         if (ob_dst == ob_src || dv_tot_dst == 0 || dv_tot_dst != dv_tot_src ||
813                             dv_array_src == NULL || dv_array_dst == NULL)
814                         {
815                                 ED_vgroup_delete(ob_dst, defgroup_find_name(ob_dst, dg_dst->name));
816                                 if (dv_array_src) MEM_freeN(dv_array_src);
817                                 if (dv_array_dst) MEM_freeN(dv_array_dst);
818                                 dmesh_src->release(dmesh_src);
819                                 BKE_report(op->reports, RPT_ERROR, "Transfer failed (indices are not matching)");
820                                 return false;
821                         }
822
823                         /* Loop through the vertices.*/
824                         for (i = 0, dv_src = dv_array_src, dv_dst = dv_array_dst;
825                              i < me_dst->totvert;
826                              i++, dv_dst++, dv_src++, mv_src++, mv_dst++)
827                         {
828
829                                 if (*dv_dst == NULL) {
830                                         continue;
831                                 }
832
833                                 /* Copy weight.*/
834                                 dw_src = defvert_find_index(*dv_src, index_src);
835                                 if (dw_src && dw_src->weight) {
836                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
837                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
838                                 }
839                         }
840                         break;
841
842                 case WT_BY_NEAREST_VERTEX:
843                         /* Make node tree.*/
844                         bvhtree_from_mesh_verts(&tree_mesh_vertices_src, dmesh_src, FLT_EPSILON, 2, 6);
845
846                         /* Loop trough vertices.*/
847                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
848
849                                 if (*dv_dst == NULL) {
850                                         continue;
851                                 }
852
853                                 /* Reset nearest.*/
854                                 nearest.dist = FLT_MAX;
855                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
856                                 nearest.index = -1;
857
858                                 /* Transform into target space.*/
859                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
860
861                                 /* Node tree accelerated search for closest vetex.*/
862                                 BLI_bvhtree_find_nearest(tree_mesh_vertices_src.tree, tmp_co,
863                                                          &nearest, tree_mesh_vertices_src.nearest_callback, &tree_mesh_vertices_src);
864
865                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
866                                  * overwritten prior to this. See the "Clear weights." step above.*/
867                                 dw_src = defvert_find_index(dv_array_src[nearest.index], index_src);
868                                 if (dw_src && dw_src->weight) {
869                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
870                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
871                                 }
872                         }
873
874                         /* Free memory.*/
875                         free_bvhtree_from_mesh(&tree_mesh_vertices_src);
876                         break;
877
878                 case WT_BY_NEAREST_FACE:
879                         /* Get faces.*/
880                         DM_ensure_tessface(dmesh_src);
881                         mface_src = dmesh_src->getTessFaceArray(dmesh_src);
882
883                         /* Make node tree.*/
884                         bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
885
886                         /* Loop through the vertices.*/
887                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
888
889                                 if (*dv_dst == NULL) {
890                                         continue;
891                                 }
892
893                                 /* Reset nearest.*/
894                                 nearest.dist = FLT_MAX;
895                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
896                                 nearest.index = -1;
897
898                                 /* Transform into target space.*/
899                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
900
901                                 /* Node tree accelerated search for closest face.*/
902                                 BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
903                                                          &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
904                                 index_nearest = nearest.index;
905
906                                 /* Project onto face.*/
907                                 mf = &mface_src[index_nearest];
908                                 normal_tri_v3(normal, mv_src[mf->v1].co, mv_src[mf->v2].co, mv_src[mf->v3].co);
909                                 project_v3_plane(tmp_co, normal, mv_src[mf->v1].co);
910
911                                 /* Interpolate weights over face.*/
912                                 f_index = mf->v4 ? 3 : 2;
913                                 if (f_index == 3) {
914                                         interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co,
915                                                                mv_src[mf->v3].co, mv_src[mf->v4].co, tmp_co);
916                                 }
917                                 else {
918                                         interp_weights_face_v3(tmp_weight, mv_src[mf->v1].co, mv_src[mf->v2].co,
919                                                                mv_src[mf->v3].co, NULL, tmp_co);
920                                 }
921
922                                 /* Get weights from face.*/
923                                 weight = 0;
924                                 do {
925                                         v_index = (&mf->v1)[f_index];
926                                         weight += tmp_weight[f_index] * defvert_find_weight(dv_array_src[v_index], index_src);
927                                 } while (f_index--);
928
929                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
930                                  * overwritten prior to this. See the "Clear weights." step above.*/
931                                 if (weight > 0) {
932                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
933                                         vgroup_transfer_weight(&dw_dst->weight, weight, replace_mode);
934                                 }
935                         }
936
937                         /* Free memory.*/
938                         free_bvhtree_from_mesh(&tree_mesh_faces_src);
939                         break;
940
941                 case WT_BY_NEAREST_VERTEX_IN_FACE:
942                         /* Get faces.*/
943                         DM_ensure_tessface(dmesh_src);
944                         mface_src = dmesh_src->getTessFaceArray(dmesh_src);
945
946                         /* Make node tree.*/
947                         bvhtree_from_mesh_faces(&tree_mesh_faces_src, dmesh_src, FLT_EPSILON, 2, 6);
948
949                         /* Loop through the vertices.*/
950                         for (i = 0, dv_dst = dv_array_dst; i < me_dst->totvert; i++, dv_dst++, mv_dst++) {
951
952                                 if (*dv_dst == NULL) {
953                                         continue;
954                                 }
955
956                                 /* Reset nearest.*/
957                                 nearest.dist = FLT_MAX;
958                                 /* It is faster to start searching at the top of the tree instead of previous search result.*/
959                                 nearest.index = -1;
960
961                                 /* Transform into target space.*/
962                                 mul_v3_m4v3(tmp_co, tmp_mat, mv_dst->co);
963
964                                 /* Node tree accelerated search for closest face.*/
965                                 BLI_bvhtree_find_nearest(tree_mesh_faces_src.tree, tmp_co,
966                                                          &nearest, tree_mesh_faces_src.nearest_callback, &tree_mesh_faces_src);
967                                 index_nearest = nearest.index;
968
969                                 /* Get distances.*/
970                                 mf = &mface_src[index_nearest];
971                                 dist_v1 = len_squared_v3v3(tmp_co, mv_src[mf->v1].co);
972                                 dist_v2 = len_squared_v3v3(tmp_co, mv_src[mf->v2].co);
973                                 dist_v3 = len_squared_v3v3(tmp_co, mv_src[mf->v3].co);
974
975                                 /* Get closest vertex.*/
976                                 f_index = mf->v4 ? 3 : 2;
977                                 if (dist_v1 < dist_v2 && dist_v1 < dist_v3) index_nearest_vertex = mf->v1;
978                                 else if (dist_v2 < dist_v3) index_nearest_vertex = mf->v2;
979                                 else index_nearest_vertex = mf->v3;
980                                 if (f_index == 3) {
981                                         dist_v4 = len_squared_v3v3(tmp_co, mv_src[mf->v4].co);
982                                         if (dist_v4 < dist_v1 && dist_v4 < dist_v2 && dist_v4 < dist_v3) {
983                                                 index_nearest_vertex = mf->v4;
984                                         }
985                                 }
986
987                                 /* Copy weight that are not NULL including weight value 0. In relevant cases, existing weights are
988                                  * overwritten prior to this. See the "Clear weights." step above.*/
989                                 dw_src = defvert_find_index(dv_array_src[index_nearest_vertex], index_src);
990                                 if (dw_src && dw_src->weight) {
991                                         dw_dst = defvert_verify_index(*dv_dst, index_dst);
992                                         vgroup_transfer_weight(&dw_dst->weight, dw_src->weight, replace_mode);
993                                 }
994                         }
995
996                         /* Free memory.*/
997                         free_bvhtree_from_mesh(&tree_mesh_faces_src);
998                         break;
999
1000                 default:
1001                         BLI_assert(0);
1002                         break;
1003         }
1004
1005         /* Free memory.*/
1006         if (dv_array_src) MEM_freeN(dv_array_src);
1007         if (dv_array_dst) MEM_freeN(dv_array_dst);
1008         dmesh_src->release(dmesh_src);
1009
1010         return true;
1011 }
1012
1013 /***********************End weight transfer (WT)***********************************/
1014
1015 /* for Mesh in Object mode */
1016 /* allows editmode for Lattice */
1017 static void ED_vgroup_nr_vert_add(Object *ob,
1018                                   const int def_nr, const int vertnum,
1019                                   const float weight, const int assignmode)
1020 {
1021         /* add the vert to the deform group with the
1022          * specified number
1023          */
1024         MDeformVert *dvert = NULL;
1025         int tot;
1026
1027         /* get the vert */
1028         ED_vgroup_give_array(ob->data, &dvert, &tot);
1029         
1030         if (dvert == NULL)
1031                 return;
1032
1033         /* check that vertnum is valid before trying to get the relevant dvert */
1034         if ((vertnum < 0) || (vertnum >= tot))
1035                 return;
1036
1037
1038         if (dvert) {
1039                 MDeformVert *dv = &dvert[vertnum];
1040                 MDeformWeight *dw;
1041
1042                 /* Lets first check to see if this vert is
1043                  * already in the weight group -- if so
1044                  * lets update it
1045                  */
1046
1047                 dw = defvert_find_index(dv, def_nr);
1048
1049                 if (dw) {
1050                         switch (assignmode) {
1051                                 case WEIGHT_REPLACE:
1052                                         dw->weight = weight;
1053                                         break;
1054                                 case WEIGHT_ADD:
1055                                         dw->weight += weight;
1056                                         if (dw->weight >= 1.0f)
1057                                                 dw->weight = 1.0f;
1058                                         break;
1059                                 case WEIGHT_SUBTRACT:
1060                                         dw->weight -= weight;
1061                                         /* if the weight is zero or less then
1062                                          * remove the vert from the deform group
1063                                          */
1064                                         if (dw->weight <= 0.0f) {
1065                                                 defvert_remove_group(dv, dw);
1066                                         }
1067                                         break;
1068                         }
1069                 }
1070                 else {
1071                         /* if the vert wasn't in the deform group then
1072                          * we must take a different form of action ...
1073                          */
1074
1075                         switch (assignmode) {
1076                                 case WEIGHT_SUBTRACT:
1077                                         /* if we are subtracting then we don't
1078                                          * need to do anything
1079                                          */
1080                                         return;
1081
1082                                 case WEIGHT_REPLACE:
1083                                 case WEIGHT_ADD:
1084                                         /* if we are doing an additive assignment, then
1085                                          * we need to create the deform weight
1086                                          */
1087
1088                                         /* we checked if the vertex was added before so no need to test again, simply add */
1089                                         defvert_add_index_notest(dv, def_nr, weight);
1090                         }
1091                 }
1092         }
1093 }
1094
1095 /* called while not in editmode */
1096 void ED_vgroup_vert_add(Object *ob, bDeformGroup *dg, int vertnum, float weight, int assignmode)
1097 {
1098         /* add the vert to the deform group with the
1099          * specified assign mode
1100          */
1101         const int def_nr = BLI_findindex(&ob->defbase, dg);
1102
1103         MDeformVert *dv = NULL;
1104         int tot;
1105
1106         /* get the deform group number, exit if
1107          * it can't be found
1108          */
1109         if (def_nr < 0) return;
1110
1111         /* if there's no deform verts then create some,
1112          */
1113         if (ED_vgroup_give_array(ob->data, &dv, &tot) && dv == NULL)
1114                 ED_vgroup_data_create(ob->data);
1115
1116         /* call another function to do the work
1117          */
1118         ED_vgroup_nr_vert_add(ob, def_nr, vertnum, weight, assignmode);
1119 }
1120
1121 /* mesh object mode, lattice can be in editmode */
1122 void ED_vgroup_vert_remove(Object *ob, bDeformGroup *dg, int vertnum)
1123 {
1124         /* This routine removes the vertex from the specified
1125          * deform group.
1126          */
1127
1128         /* TODO, this is slow in a loop, better pass def_nr directly, but leave for later... - campbell */
1129         const int def_nr = BLI_findindex(&ob->defbase, dg);
1130
1131         if (def_nr != -1) {
1132                 MDeformVert *dvert = NULL;
1133                 int tot;
1134
1135                 /* get the deform vertices corresponding to the
1136                  * vertnum
1137                  */
1138                 ED_vgroup_give_array(ob->data, &dvert, &tot);
1139
1140                 if (dvert) {
1141                         MDeformVert *dv = &dvert[vertnum];
1142                         MDeformWeight *dw;
1143
1144                         dw = defvert_find_index(dv, def_nr);
1145                         defvert_remove_group(dv, dw); /* dw can be NULL */
1146                 }
1147         }
1148 }
1149
1150 static float get_vert_def_nr(Object *ob, const int def_nr, const int vertnum)
1151 {
1152         MDeformVert *dv = NULL;
1153
1154         /* get the deform vertices corresponding to the vertnum */
1155         if (ob->type == OB_MESH) {
1156                 Mesh *me = ob->data;
1157
1158                 if (me->edit_btmesh) {
1159                         BMEditMesh *em = me->edit_btmesh;
1160                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1161                         /* warning, this lookup is _not_ fast */
1162
1163                         if (cd_dvert_offset != -1) {
1164                                 BMVert *eve;
1165                                 EDBM_index_arrays_ensure(em, BM_VERT);
1166                                 eve = EDBM_vert_at_index(em, vertnum);
1167                                 dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1168                         }
1169                         else {
1170                                 return 0.0f;
1171                         }
1172                 }
1173                 else {
1174                         if (me->dvert) {
1175                                 if (vertnum >= me->totvert) {
1176                                         return 0.0f;
1177                                 }
1178                                 dv = &me->dvert[vertnum];
1179                         }
1180                 }
1181         }
1182         else if (ob->type == OB_LATTICE) {
1183                 Lattice *lt = vgroup_edit_lattice(ob);
1184
1185                 if (lt->dvert) {
1186                         if (vertnum >= lt->pntsu * lt->pntsv * lt->pntsw) {
1187                                 return 0.0f;
1188                         }
1189                         dv = &lt->dvert[vertnum];
1190                 }
1191         }
1192         
1193         if (dv) {
1194                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
1195                 if (dw) {
1196                         return dw->weight;
1197                 }
1198         }
1199
1200         return -1;
1201 }
1202
1203 float ED_vgroup_vert_weight(Object *ob, bDeformGroup *dg, int vertnum)
1204 {
1205         const int def_nr = BLI_findindex(&ob->defbase, dg);
1206
1207         if (def_nr == -1) {
1208                 return -1;
1209         }
1210
1211         return get_vert_def_nr(ob, def_nr, vertnum);
1212 }
1213
1214 void ED_vgroup_select_by_name(Object *ob, const char *name)
1215 {   /* note: ob->actdef==0 signals on painting to create a new one, if a bone in posemode is selected */
1216         ob->actdef = defgroup_name_index(ob, name) + 1;
1217 }
1218
1219 /********************** Operator Implementations *********************/
1220
1221 /* only in editmode */
1222 static void vgroup_select_verts(Object *ob, int select)
1223 {
1224         const int def_nr = ob->actdef - 1;
1225
1226         if (!BLI_findlink(&ob->defbase, def_nr)) {
1227                 return;
1228         }
1229
1230         if (ob->type == OB_MESH) {
1231                 Mesh *me = ob->data;
1232
1233                 if (me->edit_btmesh) {
1234                         BMEditMesh *em = me->edit_btmesh;
1235                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
1236
1237                         if (cd_dvert_offset != -1) {
1238                                 BMIter iter;
1239                                 BMVert *eve;
1240
1241                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
1242                                         if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
1243                                                 MDeformVert *dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
1244                                                 if (defvert_find_index(dv, def_nr)) {
1245                                                         BM_vert_select_set(em->bm, eve, select);
1246                                                 }
1247                                         }
1248                                 }
1249
1250                                 /* this has to be called, because this function operates on vertices only */
1251                                 if (select) EDBM_select_flush(em);  /* vertices to edges/faces */
1252                                 else EDBM_deselect_flush(em);
1253                         }
1254                 }
1255                 else {
1256                         if (me->dvert) {
1257                                 MVert *mv;
1258                                 MDeformVert *dv;
1259                                 int i;
1260
1261                                 mv = me->mvert;
1262                                 dv = me->dvert;
1263
1264                                 for (i = 0; i < me->totvert; i++, mv++, dv++) {
1265                                         if (!(mv->flag & ME_HIDE)) {
1266                                                 if (defvert_find_index(dv, def_nr)) {
1267                                                         if (select) mv->flag |=  SELECT;
1268                                                         else mv->flag &= ~SELECT;
1269                                                 }
1270                                         }
1271                                 }
1272
1273                                 paintvert_flush_flags(ob);
1274                         }
1275                 }
1276         }
1277         else if (ob->type == OB_LATTICE) {
1278                 Lattice *lt = vgroup_edit_lattice(ob);
1279                 
1280                 if (lt->dvert) {
1281                         MDeformVert *dv;
1282                         BPoint *bp, *actbp = BKE_lattice_active_point_get(lt);
1283                         int a, tot;
1284                         
1285                         dv = lt->dvert;
1286
1287                         tot = lt->pntsu * lt->pntsv * lt->pntsw;
1288                         for (a = 0, bp = lt->def; a < tot; a++, bp++, dv++) {
1289                                 if (defvert_find_index(dv, def_nr)) {
1290                                         if (select) bp->f1 |=  SELECT;
1291                                         else {
1292                                                 bp->f1 &= ~SELECT;
1293                                                 if (actbp && bp == actbp) lt->actbp = LT_ACTBP_NONE;
1294                                         }
1295                                 }
1296                         }
1297                 }
1298         }
1299 }
1300
1301 static void vgroup_duplicate(Object *ob)
1302 {
1303         bDeformGroup *dg, *cdg;
1304         char name[sizeof(dg->name)];
1305         MDeformWeight *dw_org, *dw_cpy;
1306         MDeformVert **dvert_array = NULL;
1307         int i, idg, icdg, dvert_tot = 0;
1308
1309         dg = BLI_findlink(&ob->defbase, (ob->actdef - 1));
1310         if (!dg)
1311                 return;
1312         
1313         if (!strstr(dg->name, "_copy")) {
1314                 BLI_snprintf(name, sizeof(name), "%s_copy", dg->name);
1315         }
1316         else {
1317                 BLI_strncpy(name, dg->name, sizeof(name));
1318         }
1319
1320         cdg = defgroup_duplicate(dg);
1321         BLI_strncpy(cdg->name, name, sizeof(cdg->name));
1322         defgroup_unique_name(cdg, ob);
1323
1324         BLI_addtail(&ob->defbase, cdg);
1325
1326         idg = (ob->actdef - 1);
1327         ob->actdef = BLI_countlist(&ob->defbase);
1328         icdg = (ob->actdef - 1);
1329
1330         /* TODO, we might want to allow only copy selected verts here? - campbell */
1331         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, false);
1332
1333         if (dvert_array) {
1334                 for (i = 0; i < dvert_tot; i++) {
1335                         MDeformVert *dv = dvert_array[i];
1336                         dw_org = defvert_find_index(dv, idg);
1337                         if (dw_org) {
1338                                 /* defvert_verify_index re-allocs org so need to store the weight first */
1339                                 const float weight = dw_org->weight;
1340                                 dw_cpy = defvert_verify_index(dv, icdg);
1341                                 dw_cpy->weight = weight;
1342                         }
1343                 }
1344
1345                 MEM_freeN(dvert_array);
1346         }
1347 }
1348
1349 /**
1350  * Return the subset type of the Vertex Group Selection
1351  */
1352 bool *ED_vgroup_subset_from_select_type(Object *ob, eVGroupSelect subset_type, int *r_vgroup_tot, int *r_subset_count)
1353 {
1354         bool *vgroup_validmap = NULL;
1355         *r_vgroup_tot = BLI_countlist(&ob->defbase);
1356
1357         switch (subset_type) {
1358                 case WT_VGROUP_ACTIVE:
1359                 {
1360                         const int def_nr_active = ob->actdef - 1;
1361                         vgroup_validmap = MEM_mallocN(*r_vgroup_tot * sizeof(*vgroup_validmap), __func__);
1362                         memset(vgroup_validmap, false, *r_vgroup_tot * sizeof(*vgroup_validmap));
1363                         if (def_nr_active < *r_vgroup_tot) {
1364                                 *r_subset_count = 1;
1365                                 vgroup_validmap[def_nr_active] = true;
1366                         }
1367                         else {
1368                                 *r_subset_count = 0;
1369                         }
1370                         break;
1371                 }
1372                 case WT_VGROUP_BONE_SELECT:
1373                 {
1374                         vgroup_validmap = BKE_objdef_selected_get(ob, *r_vgroup_tot, r_subset_count);
1375                         break;
1376                 }
1377                 case WT_VGROUP_BONE_DEFORM:
1378                 {
1379                         int i;
1380                         vgroup_validmap = BKE_objdef_validmap_get(ob, *r_vgroup_tot);
1381                         *r_subset_count = 0;
1382                         for (i = 0; i < *r_vgroup_tot; i++) {
1383                                 if (vgroup_validmap[i] == true) {
1384                                         *r_subset_count += 1;
1385                                 }
1386                         }
1387                         break;
1388                 }
1389                 case WT_VGROUP_BONE_DEFORM_OFF:
1390                 {
1391                         int i;
1392                         vgroup_validmap = BKE_objdef_validmap_get(ob, *r_vgroup_tot);
1393                         *r_subset_count = 0;
1394                         for (i = 0; i < *r_vgroup_tot; i++) {
1395                                 vgroup_validmap[i] = !vgroup_validmap[i];
1396                                 if (vgroup_validmap[i] == true) {
1397                                         *r_subset_count += 1;
1398                                 }
1399                         }
1400                         break;
1401                 }
1402                 case WT_VGROUP_ALL:
1403                 default:
1404                 {
1405                         vgroup_validmap = MEM_mallocN(*r_vgroup_tot * sizeof(*vgroup_validmap), __func__);
1406                         memset(vgroup_validmap, true, *r_vgroup_tot * sizeof(*vgroup_validmap));
1407                         *r_subset_count = *r_vgroup_tot;
1408                         break;
1409                 }
1410         }
1411
1412         return vgroup_validmap;
1413 }
1414
1415 static void vgroup_normalize(Object *ob)
1416 {
1417         MDeformWeight *dw;
1418         MDeformVert *dv, **dvert_array = NULL;
1419         int i, dvert_tot = 0;
1420         const int def_nr = ob->actdef - 1;
1421
1422         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1423
1424         if (!BLI_findlink(&ob->defbase, def_nr)) {
1425                 return;
1426         }
1427
1428         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1429
1430         if (dvert_array) {
1431                 float weight_max = 0.0f;
1432
1433                 for (i = 0; i < dvert_tot; i++) {
1434
1435                         /* in case its not selected */
1436                         if (!(dv = dvert_array[i])) {
1437                                 continue;
1438                         }
1439
1440                         dw = defvert_find_index(dv, def_nr);
1441                         if (dw) {
1442                                 weight_max = max_ff(dw->weight, weight_max);
1443                         }
1444                 }
1445
1446                 if (weight_max > 0.0f) {
1447                         for (i = 0; i < dvert_tot; i++) {
1448                                 
1449                                 /* in case its not selected */
1450                                 if (!(dv = dvert_array[i])) {
1451                                         continue;
1452                                 }
1453
1454                                 dw = defvert_find_index(dv, def_nr);
1455                                 if (dw) {
1456                                         dw->weight /= weight_max;
1457                                         
1458                                         /* in case of division errors with very low weights */
1459                                         CLAMP(dw->weight, 0.0f, 1.0f);
1460                                 }
1461                         }
1462                 }
1463
1464                 MEM_freeN(dvert_array);
1465         }
1466 }
1467
1468 /* This finds all of the vertices face-connected to vert by an edge and returns a
1469  * MEM_allocated array of indices of size count.
1470  * count is an int passed by reference so it can be assigned the value of the length here. */
1471 static int *getSurroundingVerts(Mesh *me, int vert, int *count)
1472 {
1473         MPoly *mp = me->mpoly;
1474         int i = me->totpoly;
1475         /* Instead of looping twice on all polys and loops, and use a temp array, let's rather
1476          * use a BLI_array, with a reasonable starting/reserved size (typically, there are not
1477          * many vertices face-linked to another one, even 8 might be too high...). */
1478         int *verts = NULL;
1479         BLI_array_declare(verts);
1480
1481         BLI_array_reserve(verts, 8);
1482         while (i--) {
1483                 int j = mp->totloop;
1484                 int first_l = mp->totloop - 1;
1485                 MLoop *ml = &me->mloop[mp->loopstart];
1486                 while (j--) {
1487                         /* XXX This assume a vert can only be once in a poly, even though
1488                          *     it seems logical to me, not totally sure of that. */
1489                         if (ml->v == vert) {
1490                                 int a, b, k;
1491                                 if (j == first_l) {
1492                                         /* We are on the first corner. */
1493                                         a = ml[1].v;
1494                                         b = ml[j].v;
1495                                 }
1496                                 else if (!j) {
1497                                         /* We are on the last corner. */
1498                                         a = (ml - 1)->v;
1499                                         b = me->mloop[mp->loopstart].v;
1500                                 }
1501                                 else {
1502                                         a = (ml - 1)->v;
1503                                         b = (ml + 1)->v;
1504                                 }
1505
1506                                 /* Append a and b verts to array, if not yet present. */
1507                                 k = BLI_array_count(verts);
1508                                 /* XXX Maybe a == b is enough? */
1509                                 while (k-- && !(a == b && a == -1)) {
1510                                         if (verts[k] == a)
1511                                                 a = -1;
1512                                         else if (verts[k] == b)
1513                                                 b = -1;
1514                                 }
1515                                 if (a != -1)
1516                                         BLI_array_append(verts, a);
1517                                 if (b != -1)
1518                                         BLI_array_append(verts, b);
1519
1520                                 /* Vert found in this poly, we can go to next one! */
1521                                 break;
1522                         }
1523                         ml++;
1524                 }
1525                 mp++;
1526         }
1527
1528         /* Do not free the array! */
1529         *count = BLI_array_count(verts);
1530         return verts;
1531 }
1532
1533 /* get a single point in space by averaging a point cloud (vectors of size 3)
1534  * coord is the place the average is stored, points is the point cloud, count is the number of points in the cloud
1535  */
1536 static void getSingleCoordinate(MVert *points, int count, float coord[3])
1537 {
1538         int i;
1539         zero_v3(coord);
1540         for (i = 0; i < count; i++) {
1541                 add_v3_v3(coord, points[i].co);
1542         }
1543         mul_v3_fl(coord, 1.0f / count);
1544 }
1545
1546 /* given a plane and a start and end position,
1547  * compute the amount of vertical distance relative to the plane and store it in dists,
1548  * then get the horizontal and vertical change and store them in changes
1549  */
1550 static void getVerticalAndHorizontalChange(const float norm[3], float d, const float coord[3],
1551                                            const float start[3], float distToStart,
1552                                            float *end, float (*changes)[2], float *dists, int index)
1553 {
1554         /* A = Q - ((Q - P).N)N
1555          * D = (a * x0 + b * y0 +c * z0 + d) */
1556         float projA[3], projB[3];
1557
1558         closest_to_plane_v3(projA, coord, norm, start);
1559         closest_to_plane_v3(projB, coord, norm, end);
1560         /* (vertical and horizontal refer to the plane's y and xz respectively)
1561          * vertical distance */
1562         dists[index] = dot_v3v3(norm, end) + d;
1563         /* vertical change */
1564         changes[index][0] = dists[index] - distToStart;
1565         //printf("vc %f %f\n", distance(end, projB, 3)-distance(start, projA, 3), changes[index][0]);
1566         /* horizontal change */
1567         changes[index][1] = len_v3v3(projA, projB);
1568 }
1569
1570 /* I need the derived mesh to be forgotten so the positions are recalculated
1571  * with weight changes (see dm_deform_recalc) */
1572 static void dm_deform_clear(DerivedMesh *dm, Object *ob)
1573 {
1574         if (ob->derivedDeform && (ob->derivedDeform) == dm) {
1575                 ob->derivedDeform->needsFree = 1;
1576                 ob->derivedDeform->release(ob->derivedDeform);
1577                 ob->derivedDeform = NULL;
1578         }
1579         else if (dm) {
1580                 dm->needsFree = 1;
1581                 dm->release(dm);
1582         }
1583 }
1584
1585 /* recalculate the deformation */
1586 static DerivedMesh *dm_deform_recalc(Scene *scene, Object *ob)
1587 {
1588         return mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1589 }
1590
1591 /* by changing nonzero weights, try to move a vertex in me->mverts with index 'index' to
1592  * distToBe distance away from the provided plane strength can change distToBe so that it moves
1593  * towards distToBe by that percentage cp changes how much the weights are adjusted
1594  * to check the distance
1595  *
1596  * index is the index of the vertex being moved
1597  * norm and d are the plane's properties for the equation: ax + by + cz + d = 0
1598  * coord is a point on the plane
1599  */
1600 static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, int index, float norm[3],
1601                                           float coord[3], float d, float distToBe, float strength, float cp)
1602 {
1603         DerivedMesh *dm;
1604         MDeformWeight *dw;
1605         MVert m;
1606         MDeformVert *dvert = me->dvert + index;
1607         int totweight = dvert->totweight;
1608         float oldw = 0;
1609         float oldPos[3] = {0};
1610         float vc, hc, dist = 0.0f;
1611         int i, k;
1612         float (*changes)[2] = MEM_mallocN(sizeof(float *) * totweight * 2, "vertHorzChange");
1613         float *dists = MEM_mallocN(sizeof(float) * totweight, "distance");
1614
1615         /* track if up or down moved it closer for each bone */
1616         int *upDown = MEM_callocN(sizeof(int) * totweight, "upDownTracker");
1617
1618         int *dwIndices = MEM_callocN(sizeof(int) * totweight, "dwIndexTracker");
1619         float distToStart;
1620         int bestIndex = 0;
1621         bool wasChange;
1622         char wasUp;
1623         int lastIndex = -1;
1624         float originalDistToBe = distToBe;
1625         do {
1626                 wasChange = false;
1627                 dm = dm_deform_recalc(scene, ob);
1628                 dm->getVert(dm, index, &m);
1629                 copy_v3_v3(oldPos, m.co);
1630                 distToStart = dot_v3v3(norm, oldPos) + d;
1631
1632                 if (distToBe == originalDistToBe) {
1633                         distToBe += distToStart - distToStart * strength;
1634                 }
1635                 for (i = 0; i < totweight; i++) {
1636                         dwIndices[i] = i;
1637                         dw = (dvert->dw + i);
1638                         vc = hc = 0;
1639                         if (!dw->weight) {
1640                                 changes[i][0] = 0;
1641                                 changes[i][1] = 0;
1642                                 dists[i] = distToStart;
1643                                 continue;
1644                         }
1645                         for (k = 0; k < 2; k++) {
1646                                 if (dm) {
1647                                         dm_deform_clear(dm, ob); dm = NULL;
1648                                 }
1649                                 oldw = dw->weight;
1650                                 if (k) {
1651                                         dw->weight *= 1 + cp;
1652                                 }
1653                                 else {
1654                                         dw->weight /= 1 + cp;
1655                                 }
1656                                 if (dw->weight == oldw) {
1657                                         changes[i][0] = 0;
1658                                         changes[i][1] = 0;
1659                                         dists[i] = distToStart;
1660                                         break;
1661                                 }
1662                                 if (dw->weight > 1) {
1663                                         dw->weight = 1;
1664                                 }
1665                                 dm = dm_deform_recalc(scene, ob);
1666                                 dm->getVert(dm, index, &m);
1667                                 getVerticalAndHorizontalChange(norm, d, coord, oldPos, distToStart, m.co, changes, dists, i);
1668                                 dw->weight = oldw;
1669                                 if (!k) {
1670                                         vc = changes[i][0];
1671                                         hc = changes[i][1];
1672                                         dist = dists[i];
1673                                 }
1674                                 else {
1675                                         if (fabsf(dist - distToBe) < fabsf(dists[i] - distToBe)) {
1676                                                 upDown[i] = 0;
1677                                                 changes[i][0] = vc;
1678                                                 changes[i][1] = hc;
1679                                                 dists[i] = dist;
1680                                         }
1681                                         else {
1682                                                 upDown[i] = 1;
1683                                         }
1684                                         if (fabsf(dists[i] - distToBe) > fabsf(distToStart - distToBe)) {
1685                                                 changes[i][0] = 0;
1686                                                 changes[i][1] = 0;
1687                                                 dists[i] = distToStart;
1688                                         }
1689                                 }
1690                         }
1691                 }
1692                 /* sort the changes by the vertical change */
1693                 for (k = 0; k < totweight; k++) {
1694                         float tf;
1695                         int ti;
1696                         bestIndex = k;
1697                         for (i = k + 1; i < totweight; i++) {
1698                                 dist = dists[i];
1699
1700                                 if (fabsf(dist) > fabsf(dists[i])) {
1701                                         bestIndex = i;
1702                                 }
1703                         }
1704                         /* switch with k */
1705                         if (bestIndex != k) {
1706                                 ti = upDown[k];
1707                                 upDown[k] = upDown[bestIndex];
1708                                 upDown[bestIndex] = ti;
1709
1710                                 ti = dwIndices[k];
1711                                 dwIndices[k] = dwIndices[bestIndex];
1712                                 dwIndices[bestIndex] = ti;
1713
1714                                 tf = changes[k][0];
1715                                 changes[k][0] = changes[bestIndex][0];
1716                                 changes[bestIndex][0] = tf;
1717
1718                                 tf = changes[k][1];
1719                                 changes[k][1] = changes[bestIndex][1];
1720                                 changes[bestIndex][1] = tf;
1721
1722                                 tf = dists[k];
1723                                 dists[k] = dists[bestIndex];
1724                                 dists[bestIndex] = tf;
1725                         }
1726                 }
1727                 bestIndex = -1;
1728                 /* find the best change with an acceptable horizontal change */
1729                 for (i = 0; i < totweight; i++) {
1730                         if (fabsf(changes[i][0]) > fabsf(changes[i][1] * 2.0f)) {
1731                                 bestIndex = i;
1732                                 break;
1733                         }
1734                 }
1735                 if (bestIndex != -1) {
1736                         wasChange = true;
1737                         /* it is a good place to stop if it tries to move the opposite direction
1738                          * (relative to the plane) of last time */
1739                         if (lastIndex != -1) {
1740                                 if (wasUp != upDown[bestIndex]) {
1741                                         wasChange = false;
1742                                 }
1743                         }
1744                         lastIndex = bestIndex;
1745                         wasUp = upDown[bestIndex];
1746                         dw = (dvert->dw + dwIndices[bestIndex]);
1747                         oldw = dw->weight;
1748                         if (upDown[bestIndex]) {
1749                                 dw->weight *= 1 + cp;
1750                         }
1751                         else {
1752                                 dw->weight /= 1 + cp;
1753                         }
1754                         if (dw->weight > 1) {
1755                                 dw->weight = 1;
1756                         }
1757                         if (oldw == dw->weight) {
1758                                 wasChange = false;
1759                         }
1760                         if (dm) {
1761                                 dm_deform_clear(dm, ob); dm = NULL;
1762                         }
1763                 }
1764         } while (wasChange && ((distToStart - distToBe) / fabsf(distToStart - distToBe) ==
1765                                (dists[bestIndex] - distToBe) / fabsf(dists[bestIndex] - distToBe)));
1766
1767         MEM_freeN(upDown);
1768         MEM_freeN(changes);
1769         MEM_freeN(dists);
1770         MEM_freeN(dwIndices);
1771 }
1772
1773 /* this is used to try to smooth a surface by only adjusting the nonzero weights of a vertex 
1774  * but it could be used to raise or lower an existing 'bump.' */
1775 static void vgroup_fix(Scene *scene, Object *ob, float distToBe, float strength, float cp)
1776 {
1777         int i;
1778
1779         Mesh *me = ob->data;
1780         MVert *mvert = me->mvert;
1781         int *verts = NULL;
1782         if (!(me->editflag & ME_EDIT_PAINT_VERT_SEL))
1783                 return;
1784         for (i = 0; i < me->totvert && mvert; i++, mvert++) {
1785                 if (mvert->flag & SELECT) {
1786                         int count = 0;
1787                         if ((verts = getSurroundingVerts(me, i, &count))) {
1788                                 MVert m;
1789                                 MVert *p = MEM_callocN(sizeof(MVert) * (count), "deformedPoints");
1790                                 int k;
1791
1792                                 DerivedMesh *dm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
1793                                 k = count;
1794                                 while (k--) {
1795                                         dm->getVert(dm, verts[k], &m);
1796                                         p[k] = m;
1797                                 }
1798                                 
1799                                 if (count >= 3) {
1800                                         float d /*, dist */ /* UNUSED */, mag;
1801                                         float coord[3];
1802                                         float norm[3];
1803                                         getSingleCoordinate(p, count, coord);
1804                                         dm->getVert(dm, i, &m);
1805                                         sub_v3_v3v3(norm, m.co, coord);
1806                                         mag = normalize_v3(norm);
1807                                         if (mag) { /* zeros fix */
1808                                                 d = -dot_v3v3(norm, coord);
1809                                                 /* dist = (dot_v3v3(norm, m.co) + d); */ /* UNUSED */
1810                                                 moveCloserToDistanceFromPlane(scene, ob, me, i, norm, coord, d, distToBe, strength, cp);
1811                                         }
1812                                 }
1813
1814                                 MEM_freeN(verts);
1815                                 MEM_freeN(p);
1816                         }
1817                 }
1818         }
1819 }
1820
1821 static void vgroup_levels_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot,
1822                                  const int UNUSED(subset_count),
1823                                  const float offset, const float gain)
1824 {
1825         MDeformWeight *dw;
1826         MDeformVert *dv, **dvert_array = NULL;
1827         int i, dvert_tot = 0;
1828
1829         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1830
1831         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1832
1833         if (dvert_array) {
1834
1835                 for (i = 0; i < dvert_tot; i++) {
1836                         int j;
1837
1838                         /* in case its not selected */
1839                         if (!(dv = dvert_array[i])) {
1840                                 continue;
1841                         }
1842
1843                         j = vgroup_tot;
1844                         while (j--) {
1845                                 if (vgroup_validmap[j]) {
1846                                         dw = defvert_find_index(dv, j);
1847                                         if (dw) {
1848                                                 dw->weight = gain * (dw->weight + offset);
1849
1850                                                 CLAMP(dw->weight, 0.0f, 1.0f);
1851                                         }
1852                                 }
1853                         }
1854                 }
1855
1856                 MEM_freeN(dvert_array);
1857         }
1858 }
1859
1860 static void vgroup_normalize_all(Object *ob, const bool lock_active)
1861 {
1862         MDeformVert *dv, **dvert_array = NULL;
1863         int i, dvert_tot = 0;
1864         const int def_nr = ob->actdef - 1;
1865
1866         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1867
1868         if (lock_active && !BLI_findlink(&ob->defbase, def_nr)) {
1869                 return;
1870         }
1871
1872         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1873
1874         if (dvert_array) {
1875                 const int defbase_tot = BLI_countlist(&ob->defbase);
1876                 bool *lock_flags = BKE_objdef_lock_flags_get(ob, defbase_tot);
1877
1878                 if ((lock_active == true) &&
1879                     (lock_flags != NULL) &&
1880                     (def_nr < defbase_tot))
1881                 {
1882                         lock_flags[def_nr] = true;
1883                 }
1884
1885                 for (i = 0; i < dvert_tot; i++) {
1886                         /* in case its not selected */
1887                         if ((dv = dvert_array[i])) {
1888                                 if (lock_flags) {
1889                                         defvert_normalize_lock_map(dv, lock_flags, defbase_tot);
1890                                 }
1891                                 else if (lock_active) {
1892                                         defvert_normalize_lock_single(dv, def_nr);
1893                                 }
1894                                 else {
1895                                         defvert_normalize(dv);
1896                                 }
1897                         }
1898                 }
1899
1900                 if (lock_flags) {
1901                         MEM_freeN(lock_flags);
1902                 }
1903
1904                 MEM_freeN(dvert_array);
1905         }
1906 }
1907
1908 enum {
1909         VGROUP_TOGGLE,
1910         VGROUP_LOCK,
1911         VGROUP_UNLOCK,
1912         VGROUP_INVERT
1913 };
1914
1915 static EnumPropertyItem vgroup_lock_actions[] = {
1916         {VGROUP_TOGGLE, "TOGGLE", 0, "Toggle", "Unlock all vertex groups if there is at least one locked group, lock all in other case"},
1917         {VGROUP_LOCK, "LOCK", 0, "Lock", "Lock all vertex groups"},
1918         {VGROUP_UNLOCK, "UNLOCK", 0, "Unlock", "Unlock all vertex groups"},
1919         {VGROUP_INVERT, "INVERT", 0, "Invert", "Invert the lock state of all vertex groups"},
1920         {0, NULL, 0, NULL, NULL}
1921 };
1922
1923 static void vgroup_lock_all(Object *ob, int action)
1924 {
1925         bDeformGroup *dg;
1926
1927         if (action == VGROUP_TOGGLE) {
1928                 action = VGROUP_LOCK;
1929                 for (dg = ob->defbase.first; dg; dg = dg->next) {
1930                         if (dg->flag & DG_LOCK_WEIGHT) {
1931                                 action = VGROUP_UNLOCK;
1932                                 break;
1933                         }
1934                 }
1935         }
1936
1937         for (dg = ob->defbase.first; dg; dg = dg->next) {
1938                 switch (action) {
1939                         case VGROUP_LOCK:
1940                                 dg->flag |= DG_LOCK_WEIGHT;
1941                                 break;
1942                         case VGROUP_UNLOCK:
1943                                 dg->flag &= ~DG_LOCK_WEIGHT;
1944                                 break;
1945                         case VGROUP_INVERT:
1946                                 dg->flag ^= DG_LOCK_WEIGHT;
1947                                 break;
1948                 }
1949         }
1950 }
1951
1952 static void vgroup_invert_subset(Object *ob,
1953                                  const bool *vgroup_validmap, const int vgroup_tot,
1954                                  const int UNUSED(subset_count), const bool auto_assign, const bool auto_remove)
1955 {
1956         MDeformWeight *dw;
1957         MDeformVert *dv, **dvert_array = NULL;
1958         int i, dvert_tot = 0;
1959         const int use_vert_sel = vertex_group_use_vert_sel(ob);
1960
1961         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
1962
1963         if (dvert_array) {
1964                 for (i = 0; i < dvert_tot; i++) {
1965                         int j;
1966
1967                         /* in case its not selected */
1968                         if (!(dv = dvert_array[i])) {
1969                                 continue;
1970                         }
1971
1972                         j = vgroup_tot;
1973                         while (j--) {
1974
1975                                 if (vgroup_validmap[j]) {
1976                                         if (auto_assign) {
1977                                                 dw = defvert_verify_index(dv, j);
1978                                         }
1979                                         else {
1980                                                 dw = defvert_find_index(dv, j);
1981                                         }
1982
1983                                         if (dw) {
1984                                                 dw->weight = 1.0f - dw->weight;
1985                                                 if (auto_remove && dw->weight <= 0.0f) {
1986                                                         defvert_remove_group(dv, dw);
1987                                                 }
1988                                         }
1989                                 }
1990                         }
1991                 }
1992
1993                 MEM_freeN(dvert_array);
1994         }
1995 }
1996
1997 static void vgroup_blend(Object *ob, const float fac)
1998 {
1999         MDeformVert *dv;
2000         MDeformWeight *dw;
2001         int i, dvert_tot = 0;
2002         const int def_nr = ob->actdef - 1;
2003
2004         BLI_assert(fac >= 0.0f && fac <= 1.0f);
2005
2006         if (ob->type != OB_MESH) {
2007                 return;
2008         }
2009
2010         if (BLI_findlink(&ob->defbase, def_nr)) {
2011                 const float ifac = 1.0f - fac;
2012
2013                 BMEditMesh *em = BKE_editmesh_from_object(ob);
2014                 BMesh *bm = em ? em->bm : NULL;
2015                 Mesh  *me = em ? NULL   : ob->data;
2016
2017                 /* bmesh only*/
2018                 BMEdge *eed;
2019                 BMVert *eve;
2020                 BMIter iter;
2021
2022                 /* mesh only */
2023                 MDeformVert *dvert_array = NULL;
2024
2025
2026                 float *vg_weights;
2027                 float *vg_users;
2028                 int sel1, sel2;
2029
2030                 if (bm) {
2031                         BM_mesh_elem_index_ensure(bm, BM_VERT);
2032                         dvert_tot = bm->totvert;
2033                 }
2034                 else {
2035                         dvert_tot = me->totvert;
2036                         dvert_array = me->dvert;
2037                 }
2038
2039                 vg_weights = MEM_callocN(sizeof(float) * dvert_tot, "vgroup_blend_f");
2040                 vg_users = MEM_callocN(sizeof(int) * dvert_tot, "vgroup_blend_i");
2041
2042                 if (bm) {
2043                         const int cd_dvert_offset = CustomData_get_offset(&bm->vdata, CD_MDEFORMVERT);
2044
2045                         BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
2046                                 sel1 = BM_elem_flag_test(eed->v1, BM_ELEM_SELECT);
2047                                 sel2 = BM_elem_flag_test(eed->v2, BM_ELEM_SELECT);
2048
2049                                 if (sel1 != sel2) {
2050                                         int i1 /* , i2 */;
2051                                         /* i1 is always the selected one */
2052                                         if (sel1) {
2053                                                 i1 = BM_elem_index_get(eed->v1);
2054                                                 /* i2 = BM_elem_index_get(eed->v2); */ /* UNUSED */
2055                                                 eve = eed->v2;
2056                                         }
2057                                         else {
2058                                                 /* i2 = BM_elem_index_get(eed->v1); */ /* UNUSED */
2059                                                 i1 = BM_elem_index_get(eed->v2);
2060                                                 eve = eed->v1;
2061                                         }
2062
2063                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2064                                         dw = defvert_find_index(dv, def_nr);
2065                                         if (dw) {
2066                                                 vg_weights[i1] += dw->weight;
2067                                         }
2068                                         vg_users[i1]++;
2069                                 }
2070                         }
2071
2072                         BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, i) {
2073                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT) && vg_users[i] > 0) {
2074                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2075
2076                                         dw = defvert_verify_index(dv, def_nr);
2077                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
2078                                         /* in case of division errors */
2079                                         CLAMP(dw->weight, 0.0f, 1.0f);
2080                                 }
2081                         }
2082                 }
2083                 else {
2084                         MEdge *ed = me->medge;
2085                         MVert *mv;
2086
2087                         for (i = 0; i < me->totedge; i++, ed++) {
2088                                 sel1 = me->mvert[ed->v1].flag & SELECT;
2089                                 sel2 = me->mvert[ed->v2].flag & SELECT;
2090
2091                                 if (sel1 != sel2) {
2092                                         int i1, i2;
2093                                         /* i1 is always the selected one */
2094                                         if (sel1) {
2095                                                 i1 = ed->v1;
2096                                                 i2 = ed->v2;
2097                                         }
2098                                         else {
2099                                                 i2 = ed->v1;
2100                                                 i1 = ed->v2;
2101                                         }
2102
2103                                         dv = &dvert_array[i2];
2104                                         dw = defvert_find_index(dv, def_nr);
2105                                         if (dw) {
2106                                                 vg_weights[i1] += dw->weight;
2107                                         }
2108                                         vg_users[i1]++;
2109                                 }
2110                         }
2111
2112                         mv = me->mvert;
2113                         dv = dvert_array;
2114
2115                         for (i = 0; i < dvert_tot; i++, mv++, dv++) {
2116                                 if ((mv->flag & SELECT) && (vg_users[i] > 0)) {
2117                                         dw = defvert_verify_index(dv, def_nr);
2118                                         dw->weight = (fac * (vg_weights[i] / (float)vg_users[i])) + (ifac * dw->weight);
2119
2120                                         /* in case of division errors */
2121                                         CLAMP(dw->weight, 0.0f, 1.0f);
2122                                 }
2123                         }
2124                 }
2125
2126                 MEM_freeN(vg_weights);
2127                 MEM_freeN(vg_users);
2128         }
2129 }
2130
2131 static int inv_cmp_mdef_vert_weights(const void *a1, const void *a2)
2132 {
2133         /* qsort sorts in ascending order.  We want descending order to save a memcopy
2134          * so this compare function is inverted from the standard greater than comparison qsort needs.
2135          * A normal compare function is called with two pointer arguments and should return an integer less than, equal to,
2136          * or greater than zero corresponding to whether its first argument is considered less than, equal to,
2137          * or greater than its second argument.  This does the opposite. */
2138         const struct MDeformWeight *dw1 = a1, *dw2 = a2;
2139
2140         if      (dw1->weight < dw2->weight) return  1;
2141         else if (dw1->weight > dw2->weight) return -1;
2142         else if (&dw1 < &dw2)               return  1; /* compare addresses so we have a stable sort algorithm */
2143         else                                return -1;
2144 }
2145
2146 /* Used for limiting the number of influencing bones per vertex when exporting
2147  * skinned meshes.  if all_deform_weights is True, limit all deform modifiers
2148  * to max_weights regardless of type, otherwise, only limit the number of influencing bones per vertex*/
2149 static int vgroup_limit_total_subset(Object *ob,
2150                                      const bool *vgroup_validmap,
2151                                      const int vgroup_tot,
2152                                      const int subset_count,
2153                                      const int max_weights)
2154 {
2155         MDeformVert *dv, **dvert_array = NULL;
2156         int i, dvert_tot = 0;
2157         const int use_vert_sel = vertex_group_use_vert_sel(ob);
2158         int remove_tot = 0;
2159
2160         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
2161
2162         if (dvert_array) {
2163                 int num_to_drop = 0;
2164
2165                 for (i = 0; i < dvert_tot; i++) {
2166
2167                         MDeformWeight *dw_temp;
2168                         int bone_count = 0, non_bone_count = 0;
2169                         int j;
2170
2171                         /* in case its not selected */
2172                         if (!(dv = dvert_array[i])) {
2173                                 continue;
2174                         }
2175
2176                         num_to_drop = subset_count - max_weights;
2177
2178                         /* first check if we even need to test further */
2179                         if (num_to_drop > 0) {
2180                                 /* re-pack dw array so that non-bone weights are first, bone-weighted verts at end
2181                                  * sort the tail, then copy only the truncated array back to dv->dw */
2182                                 dw_temp = MEM_mallocN(sizeof(MDeformWeight) * dv->totweight, __func__);
2183                                 bone_count = 0; non_bone_count = 0;
2184                                 for (j = 0; j < dv->totweight; j++) {
2185                                         if (LIKELY(dv->dw[j].def_nr < vgroup_tot) &&
2186                                             vgroup_validmap[dv->dw[j].def_nr])
2187                                         {
2188                                                 dw_temp[dv->totweight - 1 - bone_count] = dv->dw[j];
2189                                                 bone_count += 1;
2190                                         }
2191                                         else {
2192                                                 dw_temp[non_bone_count] = dv->dw[j];
2193                                                 non_bone_count += 1;
2194                                         }
2195                                 }
2196                                 BLI_assert(bone_count + non_bone_count == dv->totweight);
2197                                 num_to_drop = bone_count - max_weights;
2198                                 if (num_to_drop > 0) {
2199                                         qsort(&dw_temp[non_bone_count], bone_count, sizeof(MDeformWeight), inv_cmp_mdef_vert_weights);
2200                                         dv->totweight -= num_to_drop;
2201                                         /* Do we want to clean/normalize here? */
2202                                         MEM_freeN(dv->dw);
2203                                         dv->dw = MEM_reallocN(dw_temp, sizeof(MDeformWeight) * dv->totweight);
2204                                         remove_tot += num_to_drop;
2205                                 }
2206                                 else {
2207                                         MEM_freeN(dw_temp);
2208                                 }
2209                         }
2210
2211                 }
2212                 MEM_freeN(dvert_array);
2213
2214         }
2215
2216         return remove_tot;
2217 }
2218
2219
2220 static void vgroup_clean_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
2221                                 const float epsilon, const bool keep_single)
2222 {
2223         MDeformVert **dvert_array = NULL;
2224         int i, dvert_tot = 0;
2225         const int use_vert_sel = vertex_group_use_vert_sel(ob);
2226
2227         ED_vgroup_give_parray(ob->data, &dvert_array, &dvert_tot, use_vert_sel);
2228
2229         if (dvert_array) {
2230                 MDeformVert *dv;
2231                 MDeformWeight *dw;
2232
2233                 for (i = 0; i < dvert_tot; i++) {
2234                         int j;
2235
2236                         /* in case its not selected */
2237                         if (!(dv = dvert_array[i])) {
2238                                 continue;
2239                         }
2240
2241                         j = dv->totweight;
2242
2243                         while (j--) {
2244
2245                                 if (keep_single && dv->totweight == 1)
2246                                         break;
2247
2248                                 dw = dv->dw + j;
2249                                 if ((dw->def_nr < vgroup_tot) && vgroup_validmap[dw->def_nr]) {
2250                                         if (dw->weight <= epsilon) {
2251                                                 defvert_remove_group(dv, dw);
2252                                         }
2253                                 }
2254                         }
2255                 }
2256
2257                 MEM_freeN(dvert_array);
2258         }
2259 }
2260
2261
2262 static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
2263                             const char sel, const char sel_mirr,
2264                             const int *flip_map, const int flip_map_len,
2265                             const bool mirror_weights, const bool flip_vgroups, const bool all_vgroups,
2266                             const int act_vgroup)
2267 {
2268         BLI_assert(sel || sel_mirr);
2269
2270         if (sel_mirr && sel) {
2271                 /* swap */
2272                 if (mirror_weights) {
2273                         if (all_vgroups) {
2274                                 SWAP(MDeformVert, *dvert, *dvert_mirr);
2275                         }
2276                         else {
2277                                 MDeformWeight *dw =      defvert_find_index(dvert, act_vgroup);
2278                                 MDeformWeight *dw_mirr = defvert_find_index(dvert_mirr, act_vgroup);
2279
2280                                 if (dw || dw_mirr) {
2281                                         if (dw_mirr == NULL)
2282                                                 dw_mirr = defvert_verify_index(dvert_mirr, act_vgroup);
2283                                         if (dw == NULL)
2284                                                 dw = defvert_verify_index(dvert, act_vgroup);
2285
2286                                         SWAP(float, dw->weight, dw_mirr->weight);
2287                                 }
2288                         }
2289                 }
2290
2291                 if (flip_vgroups) {
2292                         defvert_flip(dvert, flip_map, flip_map_len);
2293                         defvert_flip(dvert_mirr, flip_map, flip_map_len);
2294                 }
2295         }
2296         else {
2297                 /* dvert should always be the target, only swaps pointer */
2298                 if (sel_mirr) {
2299                         SWAP(MDeformVert *, dvert, dvert_mirr);
2300                 }
2301
2302                 if (mirror_weights) {
2303                         if (all_vgroups) {
2304                                 defvert_copy(dvert, dvert_mirr);
2305                         }
2306                         else {
2307                                 defvert_copy_index(dvert, dvert_mirr, act_vgroup);
2308                         }
2309                 }
2310
2311                 /* flip map already modified for 'all_vgroups' */
2312                 if (flip_vgroups) {
2313                         defvert_flip(dvert, flip_map, flip_map_len);
2314                 }
2315         }
2316 }
2317
2318 /* TODO, vgroup locking */
2319 /* TODO, face masking */
2320 void ED_vgroup_mirror(Object *ob,
2321                       const bool mirror_weights, const bool flip_vgroups,
2322                       const bool all_vgroups, const bool use_topology,
2323                       int *r_totmirr, int *r_totfail)
2324 {
2325
2326 #define VGROUP_MIRR_OP                                                        \
2327         dvert_mirror_op(dvert, dvert_mirr,                                    \
2328                         sel, sel_mirr,                                        \
2329                         flip_map, flip_map_len,                               \
2330                         mirror_weights, flip_vgroups,                         \
2331                         all_vgroups, def_nr                                   \
2332                         )
2333
2334         BMVert *eve, *eve_mirr;
2335         MDeformVert *dvert, *dvert_mirr;
2336         char sel, sel_mirr;
2337         int *flip_map = NULL, flip_map_len;
2338         const int def_nr = ob->actdef - 1;
2339         int totmirr = 0, totfail = 0;
2340
2341         *r_totmirr = *r_totfail = 0;
2342
2343         if ((mirror_weights == false && flip_vgroups == false) ||
2344             (BLI_findlink(&ob->defbase, def_nr) == NULL))
2345         {
2346                 return;
2347         }
2348
2349         if (flip_vgroups) {
2350                 flip_map = all_vgroups ?
2351                            defgroup_flip_map(ob, &flip_map_len, false) :
2352                            defgroup_flip_map_single(ob, &flip_map_len, false, def_nr);
2353
2354                 BLI_assert(flip_map != NULL);
2355
2356                 if (flip_map == NULL) {
2357                         /* something went wrong!, possibly no groups */
2358                         return;
2359                 }
2360         }
2361         else {
2362                 flip_map = NULL;
2363                 flip_map_len = 0;
2364         }
2365
2366         /* only the active group */
2367         if (ob->type == OB_MESH) {
2368                 Mesh *me = ob->data;
2369                 BMEditMesh *em = me->edit_btmesh;
2370
2371                 if (em) {
2372                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2373                         BMIter iter;
2374
2375                         if (cd_dvert_offset == -1) {
2376                                 goto cleanup;
2377                         }
2378
2379                         EDBM_verts_mirror_cache_begin(em, 0, true, false, use_topology);
2380
2381                         /* Go through the list of editverts and assign them */
2382                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2383                                 if ((eve_mirr = EDBM_verts_mirror_get(em, eve))) {
2384                                         if (eve_mirr != eve) {
2385                                                 sel = BM_elem_flag_test(eve, BM_ELEM_SELECT);
2386                                                 sel_mirr = BM_elem_flag_test(eve_mirr, BM_ELEM_SELECT);
2387
2388                                                 if ((sel || sel_mirr) && (eve != eve_mirr)) {
2389                                                         dvert      = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2390                                                         dvert_mirr = BM_ELEM_CD_GET_VOID_P(eve_mirr, cd_dvert_offset);
2391
2392                                                         VGROUP_MIRR_OP;
2393                                                         totmirr++;
2394                                                 }
2395                                         }
2396
2397                                         /* don't use these again */
2398                                         EDBM_verts_mirror_cache_clear(em, eve);
2399                                         EDBM_verts_mirror_cache_clear(em, eve_mirr);
2400                                 }
2401                                 else {
2402                                         totfail++;
2403                                 }
2404                         }
2405                         EDBM_verts_mirror_cache_end(em);
2406                 }
2407                 else {
2408                         /* object mode / weight paint */
2409                         MVert *mv, *mv_mirr;
2410                         int vidx, vidx_mirr;
2411                         const int use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
2412
2413                         if (me->dvert == NULL) {
2414                                 goto cleanup;
2415                         }
2416
2417                         if (!use_vert_sel) {
2418                                 sel = sel_mirr = true;
2419                         }
2420
2421                         /* tag verts we have used */
2422                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2423                                 mv->flag &= ~ME_VERT_TMP_TAG;
2424                         }
2425
2426                         for (vidx = 0, mv = me->mvert; vidx < me->totvert; vidx++, mv++) {
2427                                 if ((mv->flag & ME_VERT_TMP_TAG) == 0) {
2428                                         if ((vidx_mirr = mesh_get_x_mirror_vert(ob, vidx, use_topology)) != -1) {
2429                                                 if (vidx != vidx_mirr) {
2430                                                         mv_mirr = &me->mvert[vidx_mirr];
2431                                                         if ((mv_mirr->flag & ME_VERT_TMP_TAG) == 0) {
2432
2433                                                                 if (use_vert_sel) {
2434                                                                         sel = mv->flag & SELECT;
2435                                                                         sel_mirr = mv_mirr->flag & SELECT;
2436                                                                 }
2437
2438                                                                 if (sel || sel_mirr) {
2439                                                                         dvert = &me->dvert[vidx];
2440                                                                         dvert_mirr = &me->dvert[vidx_mirr];
2441
2442                                                                         VGROUP_MIRR_OP;
2443                                                                         totmirr++;
2444                                                                 }
2445
2446                                                                 mv->flag |= ME_VERT_TMP_TAG;
2447                                                                 mv_mirr->flag |= ME_VERT_TMP_TAG;
2448                                                         }
2449                                                 }
2450                                         }
2451                                         else {
2452                                                 totfail++;
2453                                         }
2454                                 }
2455                         }
2456                 }
2457         }
2458         else if (ob->type == OB_LATTICE) {
2459                 Lattice *lt = vgroup_edit_lattice(ob);
2460                 int i1, i2;
2461                 int u, v, w;
2462                 int pntsu_half;
2463                 /* half but found up odd value */
2464
2465                 if (lt->pntsu == 1 || lt->dvert == NULL) {
2466                         goto cleanup;
2467                 }
2468
2469                 /* unlike editmesh we know that by only looping over the first half of
2470                  * the 'u' indices it will cover all points except the middle which is
2471                  * ok in this case */
2472                 pntsu_half = lt->pntsu / 2;
2473
2474                 for (w = 0; w < lt->pntsw; w++) {
2475                         for (v = 0; v < lt->pntsv; v++) {
2476                                 for (u = 0; u < pntsu_half; u++) {
2477                                         int u_inv = (lt->pntsu - 1) - u;
2478                                         if (u != u_inv) {
2479                                                 BPoint *bp, *bp_mirr;
2480
2481                                                 i1 = BKE_lattice_index_from_uvw(lt, u, v, w);
2482                                                 i2 = BKE_lattice_index_from_uvw(lt, u_inv, v, w);
2483
2484                                                 bp = &lt->def[i1];
2485                                                 bp_mirr = &lt->def[i2];
2486
2487                                                 sel = bp->f1 & SELECT;
2488                                                 sel_mirr = bp_mirr->f1 & SELECT;
2489
2490                                                 if (sel || sel_mirr) {
2491                                                         dvert = &lt->dvert[i1];
2492                                                         dvert_mirr = &lt->dvert[i2];
2493
2494                                                         VGROUP_MIRR_OP;
2495                                                         totmirr++;
2496                                                 }
2497                                         }
2498                                 }
2499                         }
2500                 }
2501         }
2502
2503         /* disabled, confusing when you have an active pose bone */
2504 #if 0
2505         /* flip active group index */
2506         if (flip_vgroups && flip_map[def_nr] >= 0)
2507                 ob->actdef = flip_map[def_nr] + 1;
2508 #endif
2509
2510 cleanup:
2511         *r_totmirr = totmirr;
2512         *r_totfail = totfail;
2513
2514         if (flip_map) MEM_freeN(flip_map);
2515
2516 #undef VGROUP_MIRR_OP
2517
2518 }
2519
2520 static void vgroup_remap_update_users(Object *ob, int *map)
2521 {
2522         ExplodeModifierData *emd;
2523         ModifierData *md;
2524         ParticleSystem *psys;
2525         ClothModifierData *clmd;
2526         ClothSimSettings *clsim;
2527         int a;
2528
2529         /* these cases don't use names to refer to vertex groups, so when
2530          * they get deleted the numbers get out of sync, this corrects that */
2531
2532         if (ob->soft)
2533                 ob->soft->vertgroup = map[ob->soft->vertgroup];
2534
2535         for (md = ob->modifiers.first; md; md = md->next) {
2536                 if (md->type == eModifierType_Explode) {
2537                         emd = (ExplodeModifierData *)md;
2538                         emd->vgroup = map[emd->vgroup];
2539                 }
2540                 else if (md->type == eModifierType_Cloth) {
2541                         clmd = (ClothModifierData *)md;
2542                         clsim = clmd->sim_parms;
2543
2544                         if (clsim) {
2545                                 clsim->vgroup_mass = map[clsim->vgroup_mass];
2546                                 clsim->vgroup_bend = map[clsim->vgroup_bend];
2547                                 clsim->vgroup_struct = map[clsim->vgroup_struct];
2548                         }
2549                 }
2550         }
2551
2552         for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2553                 for (a = 0; a < PSYS_TOT_VG; a++)
2554                         psys->vgroup[a] = map[psys->vgroup[a]];
2555         }
2556 }
2557
2558
2559 static void vgroup_delete_update_users(Object *ob, int id)
2560 {
2561         int i, defbase_tot = BLI_countlist(&ob->defbase) + 1;
2562         int *map = MEM_mallocN(sizeof(int) * defbase_tot, "vgroup del");
2563
2564         map[id] = map[0] = 0;
2565         for (i = 1; i < id; i++) map[i] = i;
2566         for (i = id + 1; i < defbase_tot; i++) map[i] = i - 1;
2567
2568         vgroup_remap_update_users(ob, map);
2569         MEM_freeN(map);
2570 }
2571
2572
2573 static void vgroup_delete_object_mode(Object *ob, bDeformGroup *dg)
2574 {
2575         MDeformVert *dvert_array = NULL;
2576         int dvert_tot = 0;
2577         const int def_nr = BLI_findindex(&ob->defbase, dg);
2578
2579         assert(def_nr > -1);
2580
2581         ED_vgroup_give_array(ob->data, &dvert_array, &dvert_tot);
2582
2583         if (dvert_array) {
2584                 int i, j;
2585                 MDeformVert *dv;
2586                 for (i = 0, dv = dvert_array; i < dvert_tot; i++, dv++) {
2587                         MDeformWeight *dw;
2588
2589                         dw = defvert_find_index(dv, def_nr);
2590                         defvert_remove_group(dv, dw); /* dw can be NULL */
2591
2592                         /* inline, make into a function if anything else needs to do this */
2593                         for (j = 0; j < dv->totweight; j++) {
2594                                 if (dv->dw[j].def_nr > def_nr) {
2595                                         dv->dw[j].def_nr--;
2596                                 }
2597                         }
2598                         /* done */
2599                 }
2600         }
2601
2602         vgroup_delete_update_users(ob, def_nr + 1);
2603
2604         /* Remove the group */
2605         BLI_freelinkN(&ob->defbase, dg);
2606
2607         /* Update the active deform index if necessary */
2608         if (ob->actdef > def_nr)
2609                 ob->actdef--;
2610         if (ob->actdef < 1 && ob->defbase.first)
2611                 ob->actdef = 1;
2612
2613         /* remove all dverts */
2614         if (ob->defbase.first == NULL) {
2615                 if (ob->type == OB_MESH) {
2616                         Mesh *me = ob->data;
2617                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2618                         me->dvert = NULL;
2619                 }
2620                 else if (ob->type == OB_LATTICE) {
2621                         Lattice *lt = ob->data;
2622                         if (lt->dvert) {
2623                                 MEM_freeN(lt->dvert);
2624                                 lt->dvert = NULL;
2625                         }
2626                 }
2627         }
2628 }
2629
2630 /* only in editmode */
2631 /* removes from active defgroup, if allverts==0 only selected vertices */
2632 static bool vgroup_active_remove_verts(Object *ob, const bool allverts, bDeformGroup *dg)
2633 {
2634         MDeformVert *dv;
2635         const int def_nr = BLI_findindex(&ob->defbase, dg);
2636         bool change = false;
2637
2638         if (ob->type == OB_MESH) {
2639                 Mesh *me = ob->data;
2640
2641                 if (me->edit_btmesh) {
2642                         BMEditMesh *em = me->edit_btmesh;
2643                         const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2644
2645                         if (cd_dvert_offset != -1) {
2646                                 BMVert *eve;
2647                                 BMIter iter;
2648
2649                                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2650                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2651
2652                                         if (dv && dv->dw && (allverts || BM_elem_flag_test(eve, BM_ELEM_SELECT))) {
2653                                                 MDeformWeight *dw = defvert_find_index(dv, def_nr);
2654                                                 defvert_remove_group(dv, dw); /* dw can be NULL */
2655                                                 change = true;
2656                                         }
2657                                 }
2658                         }
2659                 }
2660                 else {
2661                         if (me->dvert) {
2662                                 MVert *mv;
2663                                 int i;
2664
2665                                 mv = me->mvert;
2666                                 dv = me->dvert;
2667
2668                                 for (i = 0; i < me->totvert; i++, mv++, dv++) {
2669                                         if (mv->flag & SELECT) {
2670                                                 if (dv->dw && (allverts || (mv->flag & SELECT))) {
2671                                                         MDeformWeight *dw = defvert_find_index(dv, def_nr);
2672                                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2673                                                         change = true;
2674                                                 }
2675                                         }
2676                                 }
2677                         }
2678                 }
2679         }
2680         else if (ob->type == OB_LATTICE) {
2681                 Lattice *lt = vgroup_edit_lattice(ob);
2682                 
2683                 if (lt->dvert) {
2684                         BPoint *bp;
2685                         int i, tot = lt->pntsu * lt->pntsv * lt->pntsw;
2686                                 
2687                         for (i = 0, bp = lt->def; i < tot; i++, bp++) {
2688                                 if (allverts || (bp->f1 & SELECT)) {
2689                                         MDeformWeight *dw;
2690
2691                                         dv = &lt->dvert[i];
2692
2693                                         dw = defvert_find_index(dv, def_nr);
2694                                         defvert_remove_group(dv, dw); /* dw can be NULL */
2695                                         change = true;
2696                                 }
2697                         }
2698                 }
2699         }
2700
2701         return change;
2702 }
2703
2704 static void vgroup_delete_edit_mode(Object *ob, bDeformGroup *dg)
2705 {
2706         int i;
2707         const int dg_index = BLI_findindex(&ob->defbase, dg);
2708
2709         assert(dg_index > -1);
2710
2711         /* Make sure that no verts are using this group */
2712         if (vgroup_active_remove_verts(ob, true, dg) == false) {
2713                 /* do nothing */
2714         }
2715         /* Make sure that any verts with higher indices are adjusted accordingly */
2716         else if (ob->type == OB_MESH) {
2717                 Mesh *me = ob->data;
2718                 BMEditMesh *em = me->edit_btmesh;
2719                 const int cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2720
2721                 BMIter iter;
2722                 BMVert *eve;
2723                 MDeformVert *dvert;
2724
2725                 BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2726                         dvert = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset);
2727
2728                         if (dvert)
2729                                 for (i = 0; i < dvert->totweight; i++)
2730                                         if (dvert->dw[i].def_nr > dg_index)
2731                                                 dvert->dw[i].def_nr--;
2732                 }
2733         }
2734         else if (ob->type == OB_LATTICE) {
2735                 Lattice *lt = vgroup_edit_lattice(ob);
2736                 BPoint *bp;
2737                 MDeformVert *dvert = lt->dvert;
2738                 int a, tot;
2739
2740                 if (dvert) {
2741                         tot = lt->pntsu * lt->pntsv * lt->pntsw;
2742                         for (a = 0, bp = lt->def; a < tot; a++, bp++, dvert++) {
2743                                 for (i = 0; i < dvert->totweight; i++) {
2744                                         if (dvert->dw[i].def_nr > dg_index)
2745                                                 dvert->dw[i].def_nr--;
2746                                 }
2747                         }
2748                 }
2749         }
2750
2751         vgroup_delete_update_users(ob, dg_index + 1);
2752
2753         /* Remove the group */
2754         BLI_freelinkN(&ob->defbase, dg);
2755
2756         /* Update the active deform index if necessary */
2757         if (ob->actdef > dg_index)
2758                 ob->actdef--;
2759         if (ob->actdef < 1 && ob->defbase.first)
2760                 ob->actdef = 1;
2761
2762         /* remove all dverts */
2763         if (ob->defbase.first == NULL) {
2764                 if (ob->type == OB_MESH) {
2765                         Mesh *me = ob->data;
2766                         CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2767                         me->dvert = NULL;
2768                 }
2769                 else if (ob->type == OB_LATTICE) {
2770                         Lattice *lt = vgroup_edit_lattice(ob);
2771                         if (lt->dvert) {
2772                                 MEM_freeN(lt->dvert);
2773                                 lt->dvert = NULL;
2774                         }
2775                 }
2776         }
2777 }
2778
2779 static void vgroup_delete(Object *ob)
2780 {
2781         bDeformGroup *dg = BLI_findlink(&ob->defbase, ob->actdef - 1);
2782         if (!dg)
2783                 return;
2784
2785         if (BKE_object_is_in_editmode_vgroup(ob))
2786                 vgroup_delete_edit_mode(ob, dg);
2787         else
2788                 vgroup_delete_object_mode(ob, dg);
2789 }
2790
2791 static void vgroup_delete_all(Object *ob)
2792 {
2793         /* Remove all DVerts */
2794         if (ob->type == OB_MESH) {
2795                 Mesh *me = ob->data;
2796                 CustomData_free_layer_active(&me->vdata, CD_MDEFORMVERT, me->totvert);
2797                 me->dvert = NULL;
2798         }
2799         else if (ob->type == OB_LATTICE) {
2800                 Lattice *lt = vgroup_edit_lattice(ob);
2801                 if (lt->dvert) {
2802                         MEM_freeN(lt->dvert);
2803                         lt->dvert = NULL;
2804                 }
2805         }
2806         
2807         /* Remove all DefGroups */
2808         BLI_freelistN(&ob->defbase);
2809         
2810         /* Fix counters/indices */
2811         ob->actdef = 0;
2812 }
2813
2814 /* only in editmode */
2815 static void vgroup_assign_verts(Object *ob, const float weight)
2816 {
2817         const int def_nr = ob->actdef - 1;
2818
2819         if (!BLI_findlink(&ob->defbase, def_nr))
2820                 return;
2821
2822         if (ob->type == OB_MESH) {
2823                 Mesh *me = ob->data;
2824
2825                 if (me->edit_btmesh) {
2826                         BMEditMesh *em = me->edit_btmesh;
2827                         int cd_dvert_offset;
2828
2829                         BMIter iter;
2830                         BMVert *eve;
2831
2832                         if (!CustomData_has_layer(&em->bm->vdata, CD_MDEFORMVERT))
2833                                 BM_data_layer_add(em->bm, &em->bm->vdata, CD_MDEFORMVERT);
2834
2835                         cd_dvert_offset = CustomData_get_offset(&em->bm->vdata, CD_MDEFORMVERT);
2836
2837                         /* Go through the list of editverts and assign them */
2838                         BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
2839                                 if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
2840                                         MDeformVert *dv;
2841                                         MDeformWeight *dw;
2842                                         dv = BM_ELEM_CD_GET_VOID_P(eve, cd_dvert_offset); /* can be NULL */
2843                                         dw = defvert_verify_index(dv, def_nr);
2844                                         if (dw) {
2845                                                 dw->weight = weight;
2846                                         }
2847                                 }
2848                         }
2849                 }
2850                 else {
2851                         MVert *mv;
2852                         MDeformVert *dv;
2853                         int i;
2854
2855                         if (!me->dvert) {
2856                                 ED_vgroup_data_create(&me->id);
2857                         }
2858
2859                         mv = me->mvert;
2860                         dv = me->dvert;
2861
2862                         for (i = 0; i < me->totvert; i++, mv++, dv++) {
2863                                 if (mv->flag & SELECT) {
2864                                         MDeformWeight *dw;
2865                                         dw = defvert_verify_index(dv, def_nr);
2866                                         if (dw) {
2867                                                 dw->weight = weight;
2868                                         }
2869                                 }
2870                         }
2871                 }
2872         }
2873         else if (ob->type == OB_LATTICE) {
2874                 Lattice *lt = vgroup_edit_lattice(ob);
2875                 MDeformVert *dv;
2876                 BPoint *bp;
2877                 int a, tot;
2878
2879                 if (lt->dvert == NULL)
2880                         ED_vgroup_data_create(&lt->id);
2881
2882                 dv = lt->dvert;
2883
2884                 tot = lt->pntsu * lt->pntsv * lt->pntsw;
2885                 for (a = 0, bp = lt->def; a < tot; a++, bp++, dv++) {
2886                         if (bp->f1 & SELECT) {
2887                                 MDeformWeight *dw;
2888
2889                                 dw = defvert_verify_index(dv, def_nr);
2890                                 if (dw) {
2891                                         dw->weight = weight;
2892                                 }
2893                         }
2894                 }
2895         }
2896 }
2897
2898 /* only in editmode */
2899 /* removes from all defgroup, if allverts==0 only selected vertices */