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