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