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