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