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