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