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