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