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