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