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