729dd9dc57b57274ff138d63668831e390115931
[blender.git] / source / blender / editors / sculpt_paint / paint_vertex.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/sculpt_paint/paint_vertex.c
29  *  \ingroup edsculpt
30  */
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_blenlib.h"
35 #include "BLI_math.h"
36 #include "BLI_array_utils.h"
37 #include "BLI_bitmap.h"
38 #include "BLI_stack.h"
39 #include "BLI_string_utils.h"
40
41 #include "IMB_imbuf.h"
42 #include "IMB_imbuf_types.h"
43 #include "IMB_colormanagement.h"
44
45 #include "DNA_armature_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_particle_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_brush_types.h"
50 #include "DNA_object_types.h"
51
52 #include "RNA_access.h"
53 #include "RNA_define.h"
54 #include "RNA_enum_types.h"
55
56 #include "BKE_DerivedMesh.h"
57 #include "BKE_action.h"
58 #include "BKE_brush.h"
59 #include "BKE_context.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_deform.h"
62 #include "BKE_mesh.h"
63 #include "BKE_mesh_mapping.h"
64 #include "BKE_modifier.h"
65 #include "BKE_object_deform.h"
66 #include "BKE_paint.h"
67 #include "BKE_report.h"
68 #include "BKE_colortools.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73 #include "ED_armature.h"
74 #include "ED_object.h"
75 #include "ED_mesh.h"
76 #include "ED_screen.h"
77 #include "ED_view3d.h"
78
79 #include "paint_intern.h"  /* own include */
80
81 /* small structure to defer applying weight-paint results */
82 struct WPaintDefer {
83         int index;
84         float alpha, weight;
85 };
86
87 /* check if we can do partial updates and have them draw realtime
88  * (without rebuilding the 'derivedFinal') */
89 static bool vertex_paint_use_fast_update_check(Object *ob)
90 {
91         DerivedMesh *dm = ob->derivedFinal;
92
93         if (dm) {
94                 Mesh *me = BKE_mesh_from_object(ob);
95                 if (me && me->mloopcol) {
96                         return (me->mloopcol == CustomData_get_layer(&dm->loopData, CD_MLOOPCOL));
97                 }
98         }
99
100         return false;
101 }
102
103 static void paint_last_stroke_update(Scene *scene, ARegion *ar, const float mval[2])
104 {
105         const int mval_i[2] = {mval[0], mval[1]};
106         float world[3];
107
108         if (ED_view3d_autodist_simple(ar, mval_i, world, 0, NULL)) {
109                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
110                 ups->average_stroke_counter++;
111                 add_v3_v3(ups->average_stroke_accum, world);
112                 ups->last_stroke_valid = true;
113         }
114 }
115
116 /* polling - retrieve whether cursor should be set or operator should be done */
117
118 /* Returns true if vertex paint mode is active */
119 int vertex_paint_mode_poll(bContext *C)
120 {
121         Object *ob = CTX_data_active_object(C);
122
123         return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
124 }
125
126 int vertex_paint_poll(bContext *C)
127 {
128         if (vertex_paint_mode_poll(C) && 
129             BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
130         {
131                 ScrArea *sa = CTX_wm_area(C);
132                 if (sa && sa->spacetype == SPACE_VIEW3D) {
133                         ARegion *ar = CTX_wm_region(C);
134                         if (ar->regiontype == RGN_TYPE_WINDOW)
135                                 return 1;
136                 }
137         }
138         return 0;
139 }
140
141 int weight_paint_mode_poll(bContext *C)
142 {
143         Object *ob = CTX_data_active_object(C);
144
145         return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
146 }
147
148 int weight_paint_poll(bContext *C)
149 {
150         Object *ob = CTX_data_active_object(C);
151         ScrArea *sa;
152
153         if ((ob != NULL) &&
154             (ob->mode & OB_MODE_WEIGHT_PAINT) &&
155             (BKE_paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
156             (sa = CTX_wm_area(C)) &&
157             (sa->spacetype == SPACE_VIEW3D))
158         {
159                 ARegion *ar = CTX_wm_region(C);
160                 if (ar->regiontype == RGN_TYPE_WINDOW) {
161                         return 1;
162                 }
163         }
164         return 0;
165 }
166
167 static VPaint *new_vpaint(int wpaint)
168 {
169         VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
170         
171         vp->flag = (wpaint) ? 0 : VP_SPRAY;
172         vp->paint.flags |= PAINT_SHOW_BRUSH;
173
174         return vp;
175 }
176
177 static int *get_indexarray(Mesh *me)
178 {
179         return MEM_mallocN(sizeof(int) * (me->totpoly + 1), "vertexpaint");
180 }
181
182 unsigned int vpaint_get_current_col(Scene *scene, VPaint *vp)
183 {
184         Brush *brush = BKE_paint_brush(&vp->paint);
185         unsigned char col[4];
186         rgb_float_to_uchar(col, BKE_brush_color_get(scene, brush));
187         col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
188         return *(unsigned int *)col;
189 }
190
191 static void do_shared_vertexcol(Mesh *me, bool *mlooptag)
192 {
193         const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
194         MPoly *mp;
195         int (*scol)[4];
196         int i, j;
197         bool has_shared = false;
198
199         /* if no mloopcol: do not do */
200         /* if mtexpoly: only the involved faces, otherwise all */
201
202         if (me->mloopcol == NULL || me->totvert == 0 || me->totpoly == 0) return;
203
204         scol = MEM_callocN(sizeof(int) * me->totvert * 5, "scol");
205
206         for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
207                 if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
208                         MLoop *ml = me->mloop + mp->loopstart;
209                         MLoopCol *lcol = me->mloopcol + mp->loopstart;
210                         for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
211                                 scol[ml->v][0] += lcol->r;
212                                 scol[ml->v][1] += lcol->g;
213                                 scol[ml->v][2] += lcol->b;
214                                 scol[ml->v][3] += 1;
215                                 has_shared = 1;
216                         }
217                 }
218         }
219
220         if (has_shared) {
221                 for (i = 0; i < me->totvert; i++) {
222                         if (scol[i][3] != 0) {
223                                 scol[i][0] = divide_round_i(scol[i][0], scol[i][3]);
224                                 scol[i][1] = divide_round_i(scol[i][1], scol[i][3]);
225                                 scol[i][2] = divide_round_i(scol[i][2], scol[i][3]);
226                         }
227                 }
228
229                 for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
230                         if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
231                                 MLoop *ml = me->mloop + mp->loopstart;
232                                 MLoopCol *lcol = me->mloopcol + mp->loopstart;
233                                 for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
234                                         if (mlooptag[mp->loopstart + j]) {
235                                                 lcol->r = scol[ml->v][0];
236                                                 lcol->g = scol[ml->v][1];
237                                                 lcol->b = scol[ml->v][2];
238                                         }
239                                 }
240                         }
241                 }
242         }
243
244         MEM_freeN(scol);
245 }
246
247 static bool make_vertexcol(Object *ob)  /* single ob */
248 {
249         Mesh *me;
250
251         if (ID_IS_LINKED_DATABLOCK(ob) ||
252             ((me = BKE_mesh_from_object(ob)) == NULL) ||
253             (me->totpoly == 0) ||
254             (me->edit_btmesh))
255         {
256                 return false;
257         }
258
259         /* copies from shadedisplist to mcol */
260         if (!me->mloopcol && me->totloop) {
261                 CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
262                 BKE_mesh_update_customdata_pointers(me, true);
263         }
264
265         DAG_id_tag_update(&me->id, 0);
266         
267         return (me->mloopcol != NULL);
268 }
269
270 /* mirror_vgroup is set to -1 when invalid */
271 static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
272 {
273         bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
274
275         if (defgroup) {
276                 int mirrdef;
277                 char name_flip[MAXBONENAME];
278
279                 BLI_string_flip_side_name(name_flip, defgroup->name, false, sizeof(name_flip));
280                 mirrdef = defgroup_name_index(ob, name_flip);
281                 if (mirrdef == -1) {
282                         if (BKE_defgroup_new(ob, name_flip)) {
283                                 mirrdef = BLI_listbase_count(&ob->defbase) - 1;
284                         }
285                 }
286
287                 /* curdef should never be NULL unless this is
288                  * a  lamp and BKE_object_defgroup_add_name fails */
289                 return mirrdef;
290         }
291
292         return -1;
293 }
294
295 static void free_vpaint_prev(VPaint *vp)
296 {
297         if (vp->vpaint_prev) {
298                 MEM_freeN(vp->vpaint_prev);
299                 vp->vpaint_prev = NULL;
300                 vp->tot = 0;
301         }
302 }
303
304 static void free_wpaint_prev(VPaint *vp)
305 {
306         if (vp->wpaint_prev) {
307                 BKE_defvert_array_free(vp->wpaint_prev, vp->tot);
308                 vp->wpaint_prev = NULL;
309                 vp->tot = 0;
310         }
311 }
312
313 static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
314 {
315         free_vpaint_prev(vp);
316
317         vp->tot = tot;
318         
319         if (lcol == NULL || tot == 0) return;
320         
321         vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
322         memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
323         
324 }
325
326 static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
327 {
328         free_wpaint_prev(wp);
329         
330         if (dverts && dcount) {
331                 
332                 wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
333                 wp->tot = dcount;
334                 BKE_defvert_array_copy(wp->wpaint_prev, dverts, dcount);
335         }
336 }
337
338 bool ED_vpaint_fill(Object *ob, unsigned int paintcol)
339 {
340         Mesh *me;
341         MPoly *mp;
342         int i, j;
343         bool selected;
344
345         if (((me = BKE_mesh_from_object(ob)) == NULL) ||
346             (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
347         {
348                 return false;
349         }
350
351         selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
352
353         mp = me->mpoly;
354         for (i = 0; i < me->totpoly; i++, mp++) {
355                 MLoopCol *lcol = me->mloopcol + mp->loopstart;
356
357                 if (selected && !(mp->flag & ME_FACE_SEL))
358                         continue;
359
360                 for (j = 0; j < mp->totloop; j++, lcol++) {
361                         *(int *)lcol = paintcol;
362                 }
363         }
364         
365         /* remove stale me->mcol, will be added later */
366         BKE_mesh_tessface_clear(me);
367
368         DAG_id_tag_update(&me->id, 0);
369
370         return true;
371 }
372
373
374 /* fills in the selected faces with the current weight and vertex group */
375 bool ED_wpaint_fill(VPaint *wp, Object *ob, float paintweight)
376 {
377         Mesh *me = ob->data;
378         MPoly *mp;
379         MDeformWeight *dw, *dw_prev;
380         int vgroup_active, vgroup_mirror = -1;
381         unsigned int index;
382         const bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
383
384         /* mutually exclusive, could be made into a */
385         const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
386
387         if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) {
388                 return false;
389         }
390         
391         vgroup_active = ob->actdef - 1;
392
393         /* if mirror painting, find the other group */
394         if (me->editflag & ME_EDIT_MIRROR_X) {
395                 vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, vgroup_active);
396         }
397         
398         copy_wpaint_prev(wp, me->dvert, me->totvert);
399         
400         for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
401                 unsigned int fidx = mp->totloop - 1;
402
403                 if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
404                         continue;
405                 }
406
407                 do {
408                         unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
409
410                         if (!me->dvert[vidx].flag) {
411                                 if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
412                                         continue;
413                                 }
414
415                                 dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
416                                 if (dw) {
417                                         dw_prev = defvert_verify_index(wp->wpaint_prev + vidx, vgroup_active);
418                                         dw_prev->weight = dw->weight; /* set the undo weight */
419                                         dw->weight = paintweight;
420
421                                         if (me->editflag & ME_EDIT_MIRROR_X) {  /* x mirror painting */
422                                                 int j = mesh_get_x_mirror_vert(ob, NULL, vidx, topology);
423                                                 if (j >= 0) {
424                                                         /* copy, not paint again */
425                                                         if (vgroup_mirror != -1) {
426                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
427                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_mirror);
428                                                         }
429                                                         else {
430                                                                 dw = defvert_verify_index(me->dvert + j, vgroup_active);
431                                                                 dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
432                                                         }
433                                                         dw_prev->weight = dw->weight; /* set the undo weight */
434                                                         dw->weight = paintweight;
435                                                 }
436                                         }
437                                 }
438                                 me->dvert[vidx].flag = 1;
439                         }
440
441                 } while (fidx--);
442         }
443
444         {
445                 MDeformVert *dv = me->dvert;
446                 for (index = me->totvert; index != 0; index--, dv++) {
447                         dv->flag = 0;
448                 }
449         }
450
451         copy_wpaint_prev(wp, NULL, 0);
452
453         DAG_id_tag_update(&me->id, 0);
454
455         return true;
456 }
457
458 bool ED_vpaint_smooth(Object *ob)
459 {
460         Mesh *me;
461         MPoly *mp;
462
463         int i, j;
464
465         bool *mlooptag;
466         bool selected;
467
468         if (((me = BKE_mesh_from_object(ob)) == NULL) ||
469             (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
470         {
471                 return false;
472         }
473
474         selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
475
476         mlooptag = MEM_callocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
477
478         /* simply tag loops of selected faces */
479         mp = me->mpoly;
480         for (i = 0; i < me->totpoly; i++, mp++) {
481                 MLoop *ml = me->mloop + mp->loopstart;
482                 int ml_index = mp->loopstart;
483
484                 if (selected && !(mp->flag & ME_FACE_SEL))
485                         continue;
486
487                 for (j = 0; j < mp->totloop; j++, ml_index++, ml++) {
488                         mlooptag[ml_index] = true;
489                 }
490         }
491
492         /* remove stale me->mcol, will be added later */
493         BKE_mesh_tessface_clear(me);
494
495         do_shared_vertexcol(me, mlooptag);
496
497         MEM_freeN(mlooptag);
498
499         DAG_id_tag_update(&me->id, 0);
500
501         return true;
502 }
503
504 /**
505  * Apply callback to each vertex of the active vertex color layer.
506  */
507 bool ED_vpaint_color_transform(
508         struct Object *ob,
509         VPaintTransform_Callback vpaint_tx_fn,
510         const void *user_data)
511 {
512         Mesh *me;
513         const MPoly *mp;
514
515         if (((me = BKE_mesh_from_object(ob)) == NULL) ||
516             (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
517         {
518                 return false;
519         }
520
521         const bool do_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
522         mp = me->mpoly;
523
524         for (int i = 0; i < me->totpoly; i++, mp++) {
525                 MLoopCol *lcol = &me->mloopcol[mp->loopstart];
526
527                 if (do_face_sel && !(mp->flag & ME_FACE_SEL)) {
528                         continue;
529                 }
530
531                 for (int j = 0; j < mp->totloop; j++, lcol++) {
532                         float col[3];
533                         rgb_uchar_to_float(col, &lcol->r);
534
535                         vpaint_tx_fn(col, user_data, col);
536
537                         rgb_float_to_uchar(&lcol->r, col);
538                 }
539         }
540
541         /* remove stale me->mcol, will be added later */
542         BKE_mesh_tessface_clear(me);
543
544         DAG_id_tag_update(&me->id, 0);
545
546         return true;
547 }
548
549 /* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
550 #if 0
551 void vpaint_dogamma(Scene *scene)
552 {
553         VPaint *vp = scene->toolsettings->vpaint;
554         Mesh *me;
555         Object *ob;
556         float igam, fac;
557         int a, temp;
558         unsigned char *cp, gamtab[256];
559
560         ob = OBACT;
561         me = BKE_mesh_from_object(ob);
562
563         if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
564         if (me == 0 || me->mcol == 0 || me->totface == 0) return;
565
566         igam = 1.0 / vp->gamma;
567         for (a = 0; a < 256; a++) {
568
569                 fac = ((float)a) / 255.0;
570                 fac = vp->mul * pow(fac, igam);
571
572                 temp = 255.9 * fac;
573
574                 if (temp <= 0) gamtab[a] = 0;
575                 else if (temp >= 255) gamtab[a] = 255;
576                 else gamtab[a] = temp;
577         }
578
579         a = 4 * me->totface;
580         cp = (unsigned char *)me->mcol;
581         while (a--) {
582
583                 cp[1] = gamtab[cp[1]];
584                 cp[2] = gamtab[cp[2]];
585                 cp[3] = gamtab[cp[3]];
586
587                 cp += 4;
588         }
589 }
590 #endif
591
592 BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
593 {
594         unsigned char *cp1, *cp2, *cp;
595         int mfac;
596         unsigned int col = 0;
597
598         if (fac == 0) {
599                 return col1;
600         }
601
602         if (fac >= 255) {
603                 return col2;
604         }
605
606         mfac = 255 - fac;
607
608         cp1 = (unsigned char *)&col1;
609         cp2 = (unsigned char *)&col2;
610         cp  = (unsigned char *)&col;
611
612         cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
613         cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
614         cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
615         cp[3] = 255;
616
617         return col;
618 }
619
620 BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
621 {
622         unsigned char *cp1, *cp2, *cp;
623         int temp;
624         unsigned int col = 0;
625
626         if (fac == 0) {
627                 return col1;
628         }
629
630         cp1 = (unsigned char *)&col1;
631         cp2 = (unsigned char *)&col2;
632         cp  = (unsigned char *)&col;
633
634         temp = cp1[0] + divide_round_i((fac * cp2[0]), 255);
635         cp[0] = (temp > 254) ? 255 : temp;
636         temp = cp1[1] + divide_round_i((fac * cp2[1]), 255);
637         cp[1] = (temp > 254) ? 255 : temp;
638         temp = cp1[2] + divide_round_i((fac * cp2[2]), 255);
639         cp[2] = (temp > 254) ? 255 : temp;
640         cp[3] = 255;
641         
642         return col;
643 }
644
645 BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
646 {
647         unsigned char *cp1, *cp2, *cp;
648         int temp;
649         unsigned int col = 0;
650
651         if (fac == 0) {
652                 return col1;
653         }
654
655         cp1 = (unsigned char *)&col1;
656         cp2 = (unsigned char *)&col2;
657         cp  = (unsigned char *)&col;
658
659         temp = cp1[0] - divide_round_i((fac * cp2[0]), 255);
660         cp[0] = (temp < 0) ? 0 : temp;
661         temp = cp1[1] - divide_round_i((fac * cp2[1]), 255);
662         cp[1] = (temp < 0) ? 0 : temp;
663         temp = cp1[2] - divide_round_i((fac * cp2[2]), 255);
664         cp[2] = (temp < 0) ? 0 : temp;
665         cp[3] = 255;
666
667         return col;
668 }
669
670 BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
671 {
672         unsigned char *cp1, *cp2, *cp;
673         int mfac;
674         unsigned int col = 0;
675
676         if (fac == 0) {
677                 return col1;
678         }
679
680         mfac = 255 - fac;
681
682         cp1 = (unsigned char *)&col1;
683         cp2 = (unsigned char *)&col2;
684         cp  = (unsigned char *)&col;
685
686         /* first mul, then blend the fac */
687         cp[0] = divide_round_i(mfac * cp1[0] * 255 + fac * cp2[0] * cp1[0], 255 * 255);
688         cp[1] = divide_round_i(mfac * cp1[1] * 255 + fac * cp2[1] * cp1[1], 255 * 255);
689         cp[2] = divide_round_i(mfac * cp1[2] * 255 + fac * cp2[2] * cp1[2], 255 * 255);
690         cp[3] = 255;
691
692         return col;
693 }
694
695 BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
696 {
697         unsigned char *cp1, *cp2, *cp;
698         int mfac;
699         unsigned int col = 0;
700
701         if (fac == 0) {
702                 return col1;
703         }
704         else if (fac >= 255) {
705                 return col2;
706         }
707
708         mfac = 255 - fac;
709
710         cp1 = (unsigned char *)&col1;
711         cp2 = (unsigned char *)&col2;
712         cp  = (unsigned char *)&col;
713
714         /* See if are lighter, if so mix, else don't do anything.
715          * if the paint col is darker then the original, then ignore */
716         if (IMB_colormanagement_get_luminance_byte(cp1) > IMB_colormanagement_get_luminance_byte(cp2)) {
717                 return col1;
718         }
719
720         cp[0] = divide_round_i(mfac * cp1[0] + fac * cp2[0], 255);
721         cp[1] = divide_round_i(mfac * cp1[1] + fac * cp2[1], 255);
722         cp[2] = divide_round_i(mfac * cp1[2] + fac * cp2[2], 255);
723         cp[3] = 255;
724
725         return col;
726 }
727
728 BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
729 {
730         unsigned char *cp1, *cp2, *cp;
731         int mfac;
732         unsigned int col = 0;
733
734         if (fac == 0) {
735                 return col1;
736         }
737         else if (fac >= 255) {
738                 return col2;
739         }
740
741         mfac = 255 - fac;
742
743         cp1 = (unsigned char *)&col1;
744         cp2 = (unsigned char *)&col2;
745         cp  = (unsigned char *)&col;
746
747         /* See if were darker, if so mix, else don't do anything.
748          * if the paint col is brighter then the original, then ignore */
749         if (IMB_colormanagement_get_luminance_byte(cp1) < IMB_colormanagement_get_luminance_byte(cp2)) {
750                 return col1;
751         }
752
753         cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
754         cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
755         cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
756         cp[3] = 255;
757         return col;
758 }
759
760 /* wpaint has 'wpaint_blend_tool' */
761 static unsigned int vpaint_blend_tool(const int tool, const unsigned int col,
762                                       const unsigned int paintcol, const int alpha_i)
763 {
764         switch (tool) {
765                 case PAINT_BLEND_MIX:
766                 case PAINT_BLEND_BLUR:     return mcol_blend(col, paintcol, alpha_i);
767                 case PAINT_BLEND_ADD:      return mcol_add(col, paintcol, alpha_i);
768                 case PAINT_BLEND_SUB:      return mcol_sub(col, paintcol, alpha_i);
769                 case PAINT_BLEND_MUL:      return mcol_mul(col, paintcol, alpha_i);
770                 case PAINT_BLEND_LIGHTEN:  return mcol_lighten(col, paintcol, alpha_i);
771                 case PAINT_BLEND_DARKEN:   return mcol_darken(col, paintcol, alpha_i);
772                 default:
773                         BLI_assert(0);
774                         return 0;
775         }
776 }
777
778 /* wpaint has 'wpaint_blend' */
779 static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colorig, const
780                                  unsigned int paintcol, const int alpha_i,
781                                  /* pre scaled from [0-1] --> [0-255] */
782                                  const int brush_alpha_value_i)
783 {
784         Brush *brush = BKE_paint_brush(&vp->paint);
785         const int tool = brush->vertexpaint_tool;
786
787         col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
788
789         /* if no spray, clip color adding with colorig & orig alpha */
790         if ((vp->flag & VP_SPRAY) == 0) {
791                 unsigned int testcol, a;
792                 char *cp, *ct, *co;
793                 
794                 testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
795                 
796                 cp = (char *)&col;
797                 ct = (char *)&testcol;
798                 co = (char *)&colorig;
799                 
800                 for (a = 0; a < 4; a++) {
801                         if (ct[a] < co[a]) {
802                                 if (cp[a] < ct[a]) cp[a] = ct[a];
803                                 else if (cp[a] > co[a]) cp[a] = co[a];
804                         }
805                         else {
806                                 if (cp[a] < co[a]) cp[a] = co[a];
807                                 else if (cp[a] > ct[a]) cp[a] = ct[a];
808                         }
809                 }
810         }
811
812         return col;
813 }
814
815
816 static int sample_backbuf_area(ViewContext *vc, int *indexar, int totpoly, int x, int y, float size)
817 {
818         struct ImBuf *ibuf;
819         int a, tot = 0, index;
820         
821         /* brecht: disabled this because it obviously fails for
822          * brushes with size > 64, why is this here? */
823         /*if (size > 64.0) size = 64.0;*/
824         
825         ibuf = ED_view3d_backbuf_read(vc, x - size, y - size, x + size, y + size);
826         if (ibuf) {
827                 unsigned int *rt = ibuf->rect;
828
829                 memset(indexar, 0, sizeof(int) * (totpoly + 1));
830                 
831                 size = ibuf->x * ibuf->y;
832                 while (size--) {
833                                 
834                         if (*rt) {
835                                 index = *rt;
836                                 if (index > 0 && index <= totpoly) {
837                                         indexar[index] = 1;
838                                 }
839                         }
840                 
841                         rt++;
842                 }
843                 
844                 for (a = 1; a <= totpoly; a++) {
845                         if (indexar[a]) {
846                                 indexar[tot++] = a;
847                         }
848                 }
849
850                 IMB_freeImBuf(ibuf);
851         }
852         
853         return tot;
854 }
855
856 /* whats _dl mean? */
857 static float calc_vp_strength_col_dl(VPaint *vp, ViewContext *vc, const float co[3],
858                                  const float mval[2], const float brush_size_pressure, float rgba[4])
859 {
860         float co_ss[2];  /* screenspace */
861
862         if (ED_view3d_project_float_object(vc->ar,
863                                            co, co_ss,
864                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
865         {
866                 const float dist_sq = len_squared_v2v2(mval, co_ss);
867
868                 if (dist_sq <= SQUARE(brush_size_pressure)) {
869                         Brush *brush = BKE_paint_brush(&vp->paint);
870                         const float dist = sqrtf(dist_sq);
871                         float factor;
872
873                         if (brush->mtex.tex && rgba) {
874                                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
875                                         BKE_brush_sample_tex_3D(vc->scene, brush, co, rgba, 0, NULL);
876                                 }
877                                 else {
878                                         const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f};  /* we need a 3rd empty value */
879                                         BKE_brush_sample_tex_3D(vc->scene, brush, co_ss_3d, rgba, 0, NULL);
880                                 }
881                                 factor = rgba[3];
882                         }
883                         else {
884                                 factor = 1.0f;
885                         }
886                         return factor * BKE_brush_curve_strength_clamped(brush, dist, brush_size_pressure);
887                 }
888         }
889         if (rgba)
890                 zero_v4(rgba);
891         return 0.0f;
892 }
893
894 static float calc_vp_alpha_col_dl(VPaint *vp, ViewContext *vc,
895                               float vpimat[3][3], const DMCoNo *v_co_no,
896                               const float mval[2],
897                               const float brush_size_pressure, const float brush_alpha_pressure, float rgba[4])
898 {
899         float strength = calc_vp_strength_col_dl(vp, vc, v_co_no->co, mval, brush_size_pressure, rgba);
900
901         if (strength > 0.0f) {
902                 float alpha = brush_alpha_pressure * strength;
903
904                 if (vp->flag & VP_NORMALS) {
905                         float dvec[3];
906
907                         /* transpose ! */
908                         dvec[2] = dot_v3v3(vpimat[2], v_co_no->no);
909                         if (dvec[2] > 0.0f) {
910                                 dvec[0] = dot_v3v3(vpimat[0], v_co_no->no);
911                                 dvec[1] = dot_v3v3(vpimat[1], v_co_no->no);
912
913                                 alpha *= dvec[2] / len_v3(dvec);
914                         }
915                         else {
916                                 return 0.0f;
917                         }
918                 }
919
920                 return alpha;
921         }
922
923         return 0.0f;
924 }
925
926
927 BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
928 {
929         const float talpha = min_ff(alpha, 1.0f);  /* blending with values over 1 doesn't make sense */
930         return (paintval * talpha) + (weight * (1.0f - talpha));
931 }
932 BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
933 {
934         return weight + (paintval * alpha);
935 }
936 BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
937 {
938         return weight - (paintval * alpha);
939 }
940 BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
941 {   /* first mul, then blend the fac */
942         return ((1.0f - alpha) + (alpha * paintval)) * weight;
943 }
944 BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
945 {
946         return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
947 }
948 BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
949 {
950         return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
951 }
952
953
954 /* vpaint has 'vpaint_blend_tool' */
955 /* result is not clamped from [0-1] */
956 static float wpaint_blend_tool(const int tool,
957                                /* dw->weight */
958                                const float weight,
959                                const float paintval, const float alpha)
960 {
961         switch (tool) {
962                 case PAINT_BLEND_MIX:
963                 case PAINT_BLEND_BLUR:     return wval_blend(weight, paintval, alpha);
964                 case PAINT_BLEND_ADD:      return wval_add(weight, paintval, alpha);
965                 case PAINT_BLEND_SUB:      return wval_sub(weight, paintval, alpha);
966                 case PAINT_BLEND_MUL:      return wval_mul(weight, paintval, alpha);
967                 case PAINT_BLEND_LIGHTEN:  return wval_lighten(weight, paintval, alpha);
968                 case PAINT_BLEND_DARKEN:   return wval_darken(weight, paintval, alpha);
969                 default:
970                         BLI_assert(0);
971                         return 0.0f;
972         }
973 }
974
975 /* vpaint has 'vpaint_blend' */
976 static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
977                           const float alpha, float paintval,
978                           const float brush_alpha_value,
979                           const short do_flip)
980 {
981         Brush *brush = BKE_paint_brush(&wp->paint);
982         int tool = brush->vertexpaint_tool;
983
984         if (do_flip) {
985                 switch (tool) {
986                         case PAINT_BLEND_MIX:
987                                 paintval = 1.f - paintval; break;
988                         case PAINT_BLEND_ADD:
989                                 tool = PAINT_BLEND_SUB; break;
990                         case PAINT_BLEND_SUB:
991                                 tool = PAINT_BLEND_ADD; break;
992                         case PAINT_BLEND_LIGHTEN:
993                                 tool = PAINT_BLEND_DARKEN; break;
994                         case PAINT_BLEND_DARKEN:
995                                 tool = PAINT_BLEND_LIGHTEN; break;
996                 }
997         }
998         
999         weight = wpaint_blend_tool(tool, weight, paintval, alpha);
1000
1001         CLAMP(weight, 0.0f, 1.0f);
1002         
1003         /* if no spray, clip result with orig weight & orig alpha */
1004         if ((wp->flag & VP_SPRAY) == 0) {
1005                 float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
1006
1007                 CLAMP(testw, 0.0f, 1.0f);
1008                 if (testw < weight_prev) {
1009                         if (weight < testw) weight = testw;
1010                         else if (weight > weight_prev) weight = weight_prev;
1011                 }
1012                 else {
1013                         if (weight > testw) weight = testw;
1014                         else if (weight < weight_prev) weight = weight_prev;
1015                 }
1016         }
1017
1018         return weight;
1019 }
1020
1021 /* ----------------------------------------------------- */
1022
1023
1024 /* sets wp->weight to the closest weight value to vertex */
1025 /* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
1026 static int weight_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1027 {
1028         ViewContext vc;
1029         Mesh *me;
1030         bool changed = false;
1031
1032         view3d_set_viewcontext(C, &vc);
1033         me = BKE_mesh_from_object(vc.obact);
1034
1035         if (me && me->dvert && vc.v3d && vc.rv3d && (vc.obact->actdef != 0)) {
1036                 const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1037                 int v_idx_best = -1;
1038                 unsigned int index;
1039
1040                 view3d_operator_needs_opengl(C);
1041                 ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
1042
1043                 if (use_vert_sel) {
1044                         if (ED_mesh_pick_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
1045                                 v_idx_best = index;
1046                         }
1047                 }
1048                 else {
1049                         if (ED_mesh_pick_face_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1050                                 v_idx_best = index;
1051                         }
1052                         else if (ED_mesh_pick_face(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1053                                 /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
1054                                 BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
1055                         }
1056                 }
1057
1058                 if (v_idx_best != -1) { /* should always be valid */
1059                         ToolSettings *ts = vc.scene->toolsettings;
1060                         Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
1061                         const int vgroup_active = vc.obact->actdef - 1;
1062                         float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
1063
1064                         /* use combined weight in multipaint mode, since that's what is displayed to the user in the colors */
1065                         if (ts->multipaint) {
1066                                 int defbase_tot_sel;
1067                                 const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
1068                                 bool *defbase_sel = BKE_object_defgroup_selected_get(vc.obact, defbase_tot, &defbase_tot_sel);
1069
1070                                 if (defbase_tot_sel > 1) {
1071                                         if (me->editflag & ME_EDIT_MIRROR_X) {
1072                                                 BKE_object_defgroup_mirror_selection(
1073                                                         vc.obact, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1074                                         }
1075
1076                                         vgroup_weight = BKE_defvert_multipaint_collective_weight(
1077                                                 &me->dvert[v_idx_best], defbase_tot, defbase_sel, defbase_tot_sel, ts->auto_normalize);
1078
1079                                         /* if autonormalize is enabled, but weights are not normalized, the value can exceed 1 */
1080                                         CLAMP(vgroup_weight, 0.0f, 1.0f);
1081                                 }
1082
1083                                 MEM_freeN(defbase_sel);
1084                         }
1085
1086                         BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
1087                         changed = true;
1088                 }
1089         }
1090
1091         if (changed) {
1092                 /* not really correct since the brush didnt change, but redraws the toolbar */
1093                 WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
1094
1095                 return OPERATOR_FINISHED;
1096         }
1097         else {
1098                 return OPERATOR_CANCELLED;
1099         }
1100 }
1101
1102 void PAINT_OT_weight_sample(wmOperatorType *ot)
1103 {
1104         /* identifiers */
1105         ot->name = "Weight Paint Sample Weight";
1106         ot->idname = "PAINT_OT_weight_sample";
1107         ot->description = "Use the mouse to sample a weight in the 3D view";
1108
1109         /* api callbacks */
1110         ot->invoke = weight_sample_invoke;
1111         ot->poll = weight_paint_mode_poll;
1112
1113         /* flags */
1114         ot->flag = OPTYPE_UNDO;
1115 }
1116
1117 /* samples cursor location, and gives menu with vertex groups to activate */
1118 static bool weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
1119 {
1120         /* this func fills in used vgroup's */
1121         bool found = false;
1122         int i = dvert->totweight;
1123         MDeformWeight *dw;
1124         for (dw = dvert->dw; i > 0; dw++, i--) {
1125                 if (dw->def_nr < defbase_tot) {
1126                         groups[dw->def_nr] = true;
1127                         found = true;
1128                 }
1129         }
1130         return found;
1131 }
1132 static EnumPropertyItem *weight_paint_sample_enum_itemf(
1133         bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
1134 {
1135         if (C) {
1136                 wmWindow *win = CTX_wm_window(C);
1137                 if (win && win->eventstate) {
1138                         ViewContext vc;
1139                         Mesh *me;
1140
1141                         view3d_set_viewcontext(C, &vc);
1142                         me = BKE_mesh_from_object(vc.obact);
1143
1144                         if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
1145                                 const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
1146                                 const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1147                                 int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
1148                                 bool found = false;
1149                                 unsigned int index;
1150
1151                                 const int mval[2] = {
1152                                     win->eventstate->x - vc.ar->winrct.xmin,
1153                                     win->eventstate->y - vc.ar->winrct.ymin,
1154                                 };
1155
1156                                 view3d_operator_needs_opengl(C);
1157                                 ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
1158
1159                                 if (use_vert_sel) {
1160                                         if (ED_mesh_pick_vert(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
1161                                                 MDeformVert *dvert = &me->dvert[index];
1162                                                 found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1163                                         }
1164                                 }
1165                                 else {
1166                                         if (ED_mesh_pick_face(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
1167                                                 MPoly *mp = &me->mpoly[index];
1168                                                 unsigned int fidx = mp->totloop - 1;
1169
1170                                                 do {
1171                                                         MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
1172                                                         found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
1173                                                 } while (fidx--);
1174                                         }
1175                                 }
1176
1177                                 if (found == false) {
1178                                         MEM_freeN(groups);
1179                                 }
1180                                 else {
1181                                         EnumPropertyItem *item = NULL, item_tmp = {0};
1182                                         int totitem = 0;
1183                                         int i = 0;
1184                                         bDeformGroup *dg;
1185                                         for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
1186                                                 if (groups[i]) {
1187                                                         item_tmp.identifier = item_tmp.name = dg->name;
1188                                                         item_tmp.value = i;
1189                                                         RNA_enum_item_add(&item, &totitem, &item_tmp);
1190                                                 }
1191                                         }
1192
1193                                         RNA_enum_item_end(&item, &totitem);
1194                                         *r_free = true;
1195
1196                                         MEM_freeN(groups);
1197                                         return item;
1198                                 }
1199                         }
1200                 }
1201         }
1202
1203         return DummyRNA_NULL_items;
1204 }
1205
1206 static int weight_sample_group_exec(bContext *C, wmOperator *op)
1207 {
1208         int type = RNA_enum_get(op->ptr, "group");
1209         ViewContext vc;
1210         view3d_set_viewcontext(C, &vc);
1211
1212         BLI_assert(type + 1 >= 0);
1213         vc.obact->actdef = type + 1;
1214
1215         DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
1216         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
1217         return OPERATOR_FINISHED;
1218 }
1219
1220 /* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
1221 void PAINT_OT_weight_sample_group(wmOperatorType *ot)
1222 {
1223         PropertyRNA *prop = NULL;
1224
1225         /* identifiers */
1226         ot->name = "Weight Paint Sample Group";
1227         ot->idname = "PAINT_OT_weight_sample_group";
1228         ot->description = "Select one of the vertex groups available under current mouse position";
1229
1230         /* api callbacks */
1231         ot->exec = weight_sample_group_exec;
1232         ot->invoke = WM_menu_invoke;
1233         ot->poll = weight_paint_mode_poll;
1234
1235         /* flags */
1236         ot->flag = OPTYPE_UNDO;
1237
1238         /* keyingset to use (dynamic enum) */
1239         prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
1240         RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
1241         RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
1242         ot->prop = prop;
1243 }
1244
1245 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap)
1246 {
1247         float sum = 0.0f, fac;
1248         unsigned int i, tot = 0;
1249         MDeformWeight *dw;
1250
1251         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1252                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1253                         tot++;
1254                         sum += dw->weight;
1255                 }
1256         }
1257
1258         if ((tot == 0) || (sum == 1.0f)) {
1259                 return;
1260         }
1261
1262         if (sum != 0.0f) {
1263                 fac = 1.0f / sum;
1264
1265                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1266                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1267                                 dw->weight *= fac;
1268                         }
1269                 }
1270         }
1271         else {
1272                 /* hrmf, not a factor in this case */
1273                 fac = 1.0f / tot;
1274
1275                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1276                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1277                                 dw->weight = fac;
1278                         }
1279                 }
1280         }
1281 }
1282
1283 /**
1284  * A version of #do_weight_paint_normalize_all that includes locked weights
1285  * but only changes unlocked weights.
1286  */
1287 static bool do_weight_paint_normalize_all_locked(
1288         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
1289         const bool *lock_flags)
1290 {
1291         float sum = 0.0f, fac;
1292         float sum_unlock = 0.0f;
1293         float lock_weight = 0.0f;
1294         unsigned int i, tot = 0;
1295         MDeformWeight *dw;
1296
1297         if (lock_flags == NULL) {
1298                 do_weight_paint_normalize_all(dvert, defbase_tot, vgroup_validmap);
1299                 return true;
1300         }
1301
1302         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1303                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1304                         sum += dw->weight;
1305
1306                         if (lock_flags[dw->def_nr]) {
1307                                 lock_weight += dw->weight;
1308                         }
1309                         else {
1310                                 tot++;
1311                                 sum_unlock += dw->weight;
1312                         }
1313                 }
1314         }
1315
1316         if (sum == 1.0f) {
1317                 return true;
1318         }
1319
1320         if (tot == 0) {
1321                 return false;
1322         }
1323
1324         if (lock_weight >= 1.0f) {
1325                 /* locked groups make it impossible to fully normalize,
1326                  * zero out what we can and return false */
1327                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1328                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1329                                 if (lock_flags[dw->def_nr] == false) {
1330                                         dw->weight = 0.0f;
1331                                 }
1332                         }
1333                 }
1334
1335                 return (lock_weight == 1.0f);
1336         }
1337         else if (sum_unlock != 0.0f) {
1338                 fac = (1.0f - lock_weight) / sum_unlock;
1339
1340                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1341                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1342                                 if (lock_flags[dw->def_nr] == false) {
1343                                         dw->weight *= fac;
1344                                         /* paranoid but possibly with float error */
1345                                         CLAMP(dw->weight, 0.0f, 1.0f);
1346                                 }
1347                         }
1348                 }
1349         }
1350         else {
1351                 /* hrmf, not a factor in this case */
1352                 fac = (1.0f - lock_weight) / tot;
1353                 /* paranoid but possibly with float error */
1354                 CLAMP(fac, 0.0f, 1.0f);
1355
1356                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1357                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
1358                                 if (lock_flags[dw->def_nr] == false) {
1359                                         dw->weight = fac;
1360                                 }
1361                         }
1362                 }
1363         }
1364
1365         return true;
1366 }
1367
1368 /**
1369  * \note same as function above except it does a second pass without active group
1370  * if normalize fails with it.
1371  */
1372 static void do_weight_paint_normalize_all_locked_try_active(
1373         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
1374         const bool *lock_flags, const bool *lock_with_active)
1375 {
1376         /* first pass with both active and explicitly locked groups restricted from change */
1377
1378         bool success = do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_with_active);
1379
1380         if (!success) {
1381                 /**
1382                  * Locks prevented the first pass from full completion, so remove restriction on active group; e.g:
1383                  *
1384                  * - With 1.0 weight painted into active:
1385                  *   nonzero locked weight; first pass zeroed out unlocked weight; scale 1 down to fit.
1386                  * - With 0.0 weight painted into active:
1387                  *   no unlocked groups; first pass did nothing; increase 0 to fit.
1388                  */
1389                 do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_flags);
1390         }
1391 }
1392
1393 #if 0 /* UNUSED */
1394 static bool has_unselected_unlocked_bone_group(int defbase_tot, bool *defbase_sel, int selected,
1395                                                const bool *lock_flags, const bool *vgroup_validmap)
1396 {
1397         int i;
1398         if (defbase_tot == selected) {
1399                 return false;
1400         }
1401         for (i = 0; i < defbase_tot; i++) {
1402                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
1403                         return true;
1404                 }
1405         }
1406         return false;
1407 }
1408 #endif
1409
1410 static void multipaint_clamp_change(
1411         MDeformVert *dvert, const int defbase_tot, const bool *defbase_sel,
1412         float *change_p)
1413 {
1414         int i;
1415         MDeformWeight *dw;
1416         float val;
1417         float change = *change_p;
1418
1419         /* verify that the change does not cause values exceeding 1 and clamp it */
1420         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1421                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1422                         if (dw->weight) {
1423                                 val = dw->weight * change;
1424                                 if (val > 1) {
1425                                         change = 1.0f / dw->weight;
1426                                 }
1427                         }
1428                 }
1429         }
1430
1431         *change_p = change;
1432 }
1433
1434 static bool multipaint_verify_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
1435 {
1436         int i;
1437         MDeformWeight *dw;
1438         float val;
1439
1440         /* in case the change is reduced, you need to recheck
1441          * the earlier values to make sure they are not 0
1442          * (precision error) */
1443         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1444                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1445                         if (dw->weight) {
1446                                 val = dw->weight * change;
1447                                 /* the value should never reach zero while multi-painting if it
1448                                  * was nonzero beforehand */
1449                                 if (val <= 0) {
1450                                         return false;
1451                                 }
1452                         }
1453                 }
1454         }
1455
1456         return true;
1457 }
1458
1459 static void multipaint_apply_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
1460 {
1461         int i;
1462         MDeformWeight *dw;
1463
1464         /* apply the valid change */
1465         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
1466                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
1467                         if (dw->weight) {
1468                                 dw->weight = dw->weight * change;
1469                                 CLAMP(dw->weight, 0.0f, 1.0f);
1470                         }
1471                 }
1472         }
1473 }
1474
1475 /**
1476  * Variables stored both for 'active' and 'mirror' sides.
1477  */
1478 struct WeightPaintGroupData {
1479         /** index of active group or its mirror 
1480          *
1481          * - 'active' is always `ob->actdef`.
1482          * - 'mirror' is -1 when 'ME_EDIT_MIRROR_X' flag id disabled,
1483          *   otherwise this will be set to the mirror or the active group (if the group isn't mirrored).
1484          */
1485         int index;
1486         /** lock that includes the 'index' as locked too
1487          *
1488          * - 'active' is set of locked or active/selected groups
1489          * - 'mirror' is set of locked or mirror groups
1490          */
1491         const bool *lock;
1492 };
1493
1494 /* struct to avoid passing many args each call to do_weight_paint_vertex()
1495  * this _could_ be made a part of the operators 'WPaintData' struct, or at
1496  * least a member, but for now keep its own struct, initialized on every
1497  * paint stroke update - campbell */
1498 typedef struct WeightPaintInfo {
1499
1500         int defbase_tot;
1501
1502         /* both must add up to 'defbase_tot' */
1503         int defbase_tot_sel;
1504         int defbase_tot_unsel;
1505
1506         struct WeightPaintGroupData active, mirror;
1507
1508         const bool *lock_flags;  /* boolean array for locked bones,
1509                                   * length of defbase_tot */
1510         const bool *defbase_sel; /* boolean array for selected bones,
1511                                   * length of defbase_tot, cant be const because of how its passed */
1512
1513         const bool *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
1514                                       * only added here for convenience */
1515
1516         bool do_flip;
1517         bool do_multipaint;
1518         bool do_auto_normalize;
1519
1520         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
1521 } WeightPaintInfo;
1522
1523 static void do_weight_paint_vertex_single(
1524         /* vars which remain the same for every vert */
1525         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1526         /* vars which change on each stroke */
1527         const unsigned int index, float alpha, float paintweight
1528         )
1529 {
1530         Mesh *me = ob->data;
1531         MDeformVert *dv = &me->dvert[index];
1532         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1533         
1534         MDeformWeight *dw, *dw_prev;
1535
1536         /* mirror vars */
1537         int index_mirr;
1538         int vgroup_mirr;
1539
1540         MDeformVert *dv_mirr;
1541         MDeformWeight *dw_mirr;
1542
1543         if (wp->flag & VP_ONLYVGROUP) {
1544                 dw = defvert_find_index(dv, wpi->active.index);
1545                 dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->active.index);
1546         }
1547         else {
1548                 dw = defvert_verify_index(dv, wpi->active.index);
1549                 dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->active.index);
1550         }
1551
1552         if (dw == NULL || dw_prev == NULL) {
1553                 return;
1554         }
1555
1556
1557         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1558         if (me->editflag & ME_EDIT_MIRROR_X) {
1559                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
1560                 vgroup_mirr = wpi->mirror.index;
1561
1562                 /* another possible error - mirror group _and_ active group are the same (which is fine),
1563                  * but we also are painting onto a center vertex - this would paint the same weight twice */
1564                 if (index_mirr == index && vgroup_mirr == wpi->active.index) {
1565                         index_mirr = vgroup_mirr = -1;
1566                 }
1567         }
1568         else {
1569                 index_mirr = vgroup_mirr = -1;
1570         }
1571
1572
1573         /* get the mirror def vars */
1574         if (index_mirr != -1) {
1575                 dv_mirr = &me->dvert[index_mirr];
1576                 if (wp->flag & VP_ONLYVGROUP) {
1577                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
1578
1579                         if (dw_mirr == NULL) {
1580                                 index_mirr = vgroup_mirr = -1;
1581                                 dv_mirr = NULL;
1582                         }
1583                 }
1584                 else {
1585                         if (index != index_mirr) {
1586                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1587                         }
1588                         else {
1589                                 /* dv and dv_mirr are the same */
1590                                 int totweight_prev = dv_mirr->totweight;
1591                                 int dw_offset = (int)(dw - dv_mirr->dw);
1592                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
1593
1594                                 /* if we added another, get our old one back */
1595                                 if (totweight_prev != dv_mirr->totweight) {
1596                                         dw = &dv_mirr->dw[dw_offset];
1597                                 }
1598                         }
1599                 }
1600         }
1601         else {
1602                 dv_mirr = NULL;
1603                 dw_mirr = NULL;
1604         }
1605
1606         /* If there are no normalize-locks or multipaint,
1607          * then there is no need to run the more complicated checks */
1608
1609         {
1610                 dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
1611                                           wpi->brush_alpha_value, wpi->do_flip);
1612
1613                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
1614                  * can give wrong results [#26193], least confusing if normalize is done last */
1615
1616                 /* apply mirror */
1617                 if (index_mirr != -1) {
1618                         /* copy, not paint again */
1619                         dw_mirr->weight = dw->weight;
1620                 }
1621
1622                 /* apply normalize */
1623                 if (wpi->do_auto_normalize) {
1624                         /* note on normalize - this used to be applied after painting and normalize all weights,
1625                          * in some ways this is good because there is feedback where the more weights involved would
1626                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
1627                          *
1628                          * However this gave a problem since applying mirror, then normalize both verts
1629                          * the resulting weight wont match on both sides.
1630                          *
1631                          * If this 'resisting', slower normalize is nicer, we could call
1632                          * do_weight_paint_normalize_all() and only use...
1633                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
1634                          * - campbell
1635                          */
1636                         do_weight_paint_normalize_all_locked_try_active(
1637                                 dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1638
1639                         if (index_mirr != -1) {
1640                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
1641                                 if (index != index_mirr) {
1642                                         do_weight_paint_normalize_all_locked_try_active(
1643                                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->mirror.lock);
1644                                 }
1645                                 else {
1646                                         /* this case accounts for...
1647                                          * - painting onto a center vertex of a mesh
1648                                          * - x mirror is enabled
1649                                          * - auto normalize is enabled
1650                                          * - the group you are painting onto has a L / R version
1651                                          *
1652                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
1653                                          * We _could_ have special check for that, but this would need its own normalize function which
1654                                          * holds 2 groups from changing at once.
1655                                          *
1656                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
1657                                          *
1658                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
1659                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
1660                                          * - campbell */
1661                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
1662                                 }
1663                         }
1664                 }
1665         }
1666 }
1667
1668 static void do_weight_paint_vertex_multi(
1669         /* vars which remain the same for every vert */
1670         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1671         /* vars which change on each stroke */
1672         const unsigned int index, float alpha, float paintweight)
1673 {
1674         Mesh *me = ob->data;
1675         MDeformVert *dv = &me->dvert[index];
1676         MDeformVert *dv_prev = &wp->wpaint_prev[index];
1677         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
1678
1679         /* mirror vars */
1680         int index_mirr = -1;
1681         MDeformVert *dv_mirr = NULL;
1682
1683         /* weights */
1684         float oldw, curw, neww, change, curw_mirr, change_mirr;
1685
1686         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
1687         if (me->editflag & ME_EDIT_MIRROR_X) {
1688                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
1689
1690                 if (index_mirr != -1 && index_mirr != index) {
1691                         dv_mirr = &me->dvert[index_mirr];
1692                 }
1693         }
1694
1695         /* compute weight change by applying the brush to average or sum of group weights */
1696         oldw = BKE_defvert_multipaint_collective_weight(
1697                 dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1698         curw = BKE_defvert_multipaint_collective_weight(
1699                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1700
1701         if (curw == 0.0f) {
1702                 /* note: no weight to assign to this vertex, could add all groups? */
1703                 return;
1704         }
1705
1706         neww = wpaint_blend(wp, curw, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
1707
1708         change = neww / curw;
1709
1710         /* verify for all groups that 0 < result <= 1 */
1711         multipaint_clamp_change(dv, wpi->defbase_tot, wpi->defbase_sel, &change);
1712
1713         if (dv_mirr != NULL) {
1714                 curw_mirr = BKE_defvert_multipaint_collective_weight(
1715                         dv_mirr, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1716
1717                 if (curw_mirr == 0.0f) {
1718                         /* can't mirror into a zero weight vertex */
1719                         dv_mirr = NULL;
1720                 }
1721                 else {
1722                         /* mirror is changed to achieve the same collective weight value */
1723                         float orig = change_mirr = curw * change / curw_mirr;
1724
1725                         multipaint_clamp_change(dv_mirr, wpi->defbase_tot, wpi->defbase_sel, &change_mirr);
1726
1727                         if (!multipaint_verify_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel)) {
1728                                 return;
1729                         }
1730
1731                         change *= change_mirr / orig;
1732                 }
1733         }
1734
1735         if (!multipaint_verify_change(dv, wpi->defbase_tot, change, wpi->defbase_sel)) {
1736                 return;
1737         }
1738
1739         /* apply validated change to vertex and mirror */
1740         multipaint_apply_change(dv, wpi->defbase_tot, change, wpi->defbase_sel);
1741
1742         if (dv_mirr != NULL) {
1743                 multipaint_apply_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel);
1744         }
1745
1746         /* normalize */
1747         if (wpi->do_auto_normalize) {
1748                 do_weight_paint_normalize_all_locked_try_active(
1749                         dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1750
1751                 if (dv_mirr != NULL) {
1752                         do_weight_paint_normalize_all_locked_try_active(
1753                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
1754                 }
1755         }
1756 }
1757
1758 static void do_weight_paint_vertex(
1759         /* vars which remain the same for every vert */
1760         VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
1761         /* vars which change on each stroke */
1762         const unsigned int index, float alpha, float paintweight)
1763 {
1764         if (wpi->do_multipaint) {
1765                 do_weight_paint_vertex_multi(wp, ob, wpi, index, alpha, paintweight);
1766         }
1767         else {
1768                 do_weight_paint_vertex_single(wp, ob, wpi, index, alpha, paintweight);
1769         }
1770 }
1771
1772 /* *************** set wpaint operator ****************** */
1773
1774 /**
1775  * \note Keep in sync with #vpaint_mode_toggle_exec
1776  */
1777 static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
1778 {               
1779         Object *ob = CTX_data_active_object(C);
1780         const int mode_flag = OB_MODE_WEIGHT_PAINT;
1781         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1782         Scene *scene = CTX_data_scene(C);
1783         VPaint *wp = scene->toolsettings->wpaint;
1784         Mesh *me;
1785
1786         if (!is_mode_set) {
1787                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1788                         return OPERATOR_CANCELLED;
1789                 }
1790         }
1791
1792         me = BKE_mesh_from_object(ob);
1793
1794         if (ob->mode & mode_flag) {
1795                 ob->mode &= ~mode_flag;
1796
1797                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1798                         BKE_mesh_flush_select_from_verts(me);
1799                 }
1800                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1801                         BKE_mesh_flush_select_from_polys(me);
1802                 }
1803
1804                 /* weight paint specific */
1805                 ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
1806                 ED_mesh_mirror_topo_table(NULL, NULL, 'e');
1807
1808                 paint_cursor_delete_textures();
1809         }
1810         else {
1811                 ob->mode |= mode_flag;
1812
1813                 if (wp == NULL)
1814                         wp = scene->toolsettings->wpaint = new_vpaint(1);
1815
1816                 paint_cursor_start(C, weight_paint_poll);
1817
1818                 BKE_paint_init(scene, ePaintWeight, PAINT_CURSOR_WEIGHT_PAINT);
1819
1820                 /* weight paint specific */
1821                 ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
1822                 ED_vgroup_sync_from_pose(ob);
1823         }
1824         
1825         /* Weightpaint works by overriding colors in mesh,
1826          * so need to make sure we recalc on enter and
1827          * exit (exit needs doing regardless because we
1828          * should redeform).
1829          */
1830         DAG_id_tag_update(&me->id, 0);
1831
1832         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1833
1834         return OPERATOR_FINISHED;
1835 }
1836
1837 /* for switching to/from mode */
1838 static int paint_poll_test(bContext *C)
1839 {
1840         Object *ob = CTX_data_active_object(C);
1841         if (ob == NULL || ob->type != OB_MESH)
1842                 return 0;
1843         if (!ob->data || ID_IS_LINKED_DATABLOCK(ob->data))
1844                 return 0;
1845         if (CTX_data_edit_object(C))
1846                 return 0;
1847         return 1;
1848 }
1849
1850 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1851 {
1852         
1853         /* identifiers */
1854         ot->name = "Weight Paint Mode";
1855         ot->idname = "PAINT_OT_weight_paint_toggle";
1856         ot->description = "Toggle weight paint mode in 3D view";
1857         
1858         /* api callbacks */
1859         ot->exec = wpaint_mode_toggle_exec;
1860         ot->poll = paint_poll_test;
1861         
1862         /* flags */
1863         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1864         
1865 }
1866
1867 /* ************ weight paint operator ********** */
1868
1869 enum eWPaintFlag {
1870         WPAINT_ENSURE_MIRROR = (1 << 0),
1871 };
1872
1873 struct WPaintVGroupIndex {
1874         int active;
1875         int mirror;
1876 };
1877
1878 struct WPaintData {
1879         ViewContext vc;
1880         int *indexar;
1881
1882         struct WeightPaintGroupData active, mirror;
1883
1884         void *vp_handle;
1885         DMCoNo *vertexcosnos;
1886
1887         float wpimat[3][3];
1888
1889         /* variables for auto normalize */
1890         const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
1891         const bool *lock_flags;
1892
1893         /* variables for multipaint */
1894         const bool *defbase_sel;      /* set of selected groups */
1895         int defbase_tot_sel;          /* number of selected groups */
1896         bool do_multipaint;           /* true if multipaint enabled and multiple groups selected */
1897
1898         /* variables for blur */
1899         struct {
1900                 MeshElemMap *vmap;
1901                 int *vmap_mem;
1902         } blur_data;
1903
1904         BLI_Stack *accumulate_stack;  /* for reuse (WPaintDefer) */
1905
1906         int defbase_tot;
1907 };
1908
1909 /* ensure we have data on wpaint start, add if needed */
1910 static bool wpaint_ensure_data(
1911         bContext *C, wmOperator *op,
1912         enum eWPaintFlag flag, struct WPaintVGroupIndex *vgroup_index)
1913 {
1914         Scene *scene = CTX_data_scene(C);
1915         Object *ob = CTX_data_active_object(C);
1916         Mesh *me = BKE_mesh_from_object(ob);
1917
1918         if (vgroup_index) {
1919                 vgroup_index->active = -1;
1920                 vgroup_index->mirror = -1;
1921         }
1922
1923         if (scene->obedit) {
1924                 return false;
1925         }
1926
1927         if (me == NULL || me->totpoly == 0) {
1928                 return false;
1929         }
1930
1931         /* if nothing was added yet, we make dverts and a vertex deform group */
1932         if (!me->dvert) {
1933                 BKE_object_defgroup_data_create(&me->id);
1934                 WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
1935         }
1936
1937         /* this happens on a Bone select, when no vgroup existed yet */
1938         if (ob->actdef <= 0) {
1939                 Object *modob;
1940                 if ((modob = modifiers_isDeformedByArmature(ob))) {
1941                         Bone *actbone = ((bArmature *)modob->data)->act_bone;
1942                         if (actbone) {
1943                                 bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
1944
1945                                 if (pchan) {
1946                                         bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
1947                                         if (dg == NULL) {
1948                                                 dg = BKE_object_defgroup_add_name(ob, pchan->name);  /* sets actdef */
1949                                         }
1950                                         else {
1951                                                 int actdef = 1 + BLI_findindex(&ob->defbase, dg);
1952                                                 BLI_assert(actdef >= 0);
1953                                                 ob->actdef = actdef;
1954                                         }
1955                                 }
1956                         }
1957                 }
1958         }
1959         if (BLI_listbase_is_empty(&ob->defbase)) {
1960                 BKE_object_defgroup_add(ob);
1961         }
1962
1963         /* ensure we don't try paint onto an invalid group */
1964         if (ob->actdef <= 0) {
1965                 BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
1966                 return false;
1967         }
1968
1969         if (vgroup_index) {
1970                 vgroup_index->active = ob->actdef - 1;
1971         }
1972
1973         if (flag & WPAINT_ENSURE_MIRROR) {
1974                 if (me->editflag & ME_EDIT_MIRROR_X) {
1975                         int mirror = wpaint_mirror_vgroup_ensure(ob, ob->actdef - 1);
1976                         if (vgroup_index) {
1977                                 vgroup_index->mirror = mirror;
1978                         }
1979                 }
1980         }
1981
1982         return true;
1983 }
1984
1985 static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
1986 {
1987         Scene *scene = CTX_data_scene(C);
1988         struct PaintStroke *stroke = op->customdata;
1989         ToolSettings *ts = scene->toolsettings;
1990         VPaint *wp = ts->wpaint;
1991         Object *ob = CTX_data_active_object(C);
1992         Mesh *me = BKE_mesh_from_object(ob);
1993         struct WPaintData *wpd;
1994         struct WPaintVGroupIndex vgroup_index;
1995         int defbase_tot, defbase_tot_sel;
1996         bool *defbase_sel;
1997         const Brush *brush = BKE_paint_brush(&wp->paint);
1998
1999         float mat[4][4], imat[4][4];
2000
2001         if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
2002                 return false;
2003         }
2004
2005         {
2006                 /* check if we are attempting to paint onto a locked vertex group,
2007                  * and other options disallow it from doing anything useful */
2008                 bDeformGroup *dg;
2009                 dg = BLI_findlink(&ob->defbase, vgroup_index.active);
2010                 if (dg->flag & DG_LOCK_WEIGHT) {
2011                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
2012                         return false;
2013                 }
2014                 if (vgroup_index.mirror != -1) {
2015                         dg = BLI_findlink(&ob->defbase, vgroup_index.mirror);
2016                         if (dg->flag & DG_LOCK_WEIGHT) {
2017                                 BKE_report(op->reports, RPT_WARNING, "Mirror group is locked, aborting");
2018                                 return false;
2019                         }
2020                 }
2021         }
2022
2023         /* check that multipaint groups are unlocked */
2024         defbase_tot = BLI_listbase_count(&ob->defbase);
2025         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_tot_sel);
2026
2027         if (ts->multipaint && defbase_tot_sel > 1) {
2028                 int i;
2029                 bDeformGroup *dg;
2030
2031                 if (me->editflag & ME_EDIT_MIRROR_X) {
2032                         BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
2033                 }
2034
2035                 for (i = 0; i < defbase_tot; i++) {
2036                         if (defbase_sel[i]) {
2037                                 dg = BLI_findlink(&ob->defbase, i);
2038                                 if (dg->flag & DG_LOCK_WEIGHT) {
2039                                         BKE_report(op->reports, RPT_WARNING, "Multipaint group is locked, aborting");
2040                                         MEM_freeN(defbase_sel);
2041                                         return false;
2042                                 }
2043                         }
2044                 }
2045         }
2046
2047         /* ALLOCATIONS! no return after this line */
2048         /* make mode data storage */
2049         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
2050         paint_stroke_set_mode_data(stroke, wpd);
2051         view3d_set_viewcontext(C, &wpd->vc);
2052
2053         wpd->active.index = vgroup_index.active;
2054         wpd->mirror.index = vgroup_index.mirror;
2055
2056         /* multipaint */
2057         wpd->defbase_tot = defbase_tot;
2058         wpd->defbase_sel = defbase_sel;
2059         wpd->defbase_tot_sel = defbase_tot_sel > 1 ? defbase_tot_sel : 1;
2060         wpd->do_multipaint = (ts->multipaint && defbase_tot_sel > 1);
2061
2062         /* set up auto-normalize, and generate map for detecting which
2063          * vgroups affect deform bones */
2064         wpd->lock_flags = BKE_object_defgroup_lock_flags_get(ob, wpd->defbase_tot);
2065         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
2066                 wpd->vgroup_validmap = BKE_object_defgroup_validmap_get(ob, wpd->defbase_tot);
2067         }
2068
2069         if (wpd->do_multipaint && ts->auto_normalize) {
2070                 bool *tmpflags;
2071                 tmpflags = MEM_mallocN(sizeof(bool) * defbase_tot, __func__);
2072                 if (wpd->lock_flags) {
2073                         BLI_array_binary_or(tmpflags, wpd->defbase_sel, wpd->lock_flags, wpd->defbase_tot);
2074                 }
2075                 else {
2076                         memcpy(tmpflags, wpd->defbase_sel, sizeof(*tmpflags) * wpd->defbase_tot);
2077                 }
2078                 wpd->active.lock = tmpflags;
2079         }
2080         else if (ts->auto_normalize) {
2081                 bool *tmpflags;
2082
2083                 tmpflags = wpd->lock_flags ?
2084                         MEM_dupallocN(wpd->lock_flags) :
2085                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
2086                 tmpflags[wpd->active.index] = true;
2087                 wpd->active.lock = tmpflags;
2088
2089                 tmpflags = wpd->lock_flags ?
2090                         MEM_dupallocN(wpd->lock_flags) :
2091                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
2092                 tmpflags[(wpd->mirror.index != -1) ? wpd->mirror.index : wpd->active.index] = true;
2093                 wpd->mirror.lock = tmpflags;
2094         }
2095
2096         /* painting on subsurfs should give correct points too, this returns me->totvert amount */
2097         wpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &wpd->vertexcosnos);
2098
2099         wpd->indexar = get_indexarray(me);
2100         copy_wpaint_prev(wp, me->dvert, me->totvert);
2101
2102         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2103                 BKE_mesh_vert_edge_vert_map_create(
2104                         &wpd->blur_data.vmap, &wpd->blur_data.vmap_mem,
2105                         me->medge, me->totvert, me->totedge);
2106         }
2107
2108         if ((brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2109             (brush->flag & BRUSH_ACCUMULATE))
2110         {
2111                 wpd->accumulate_stack = BLI_stack_new(sizeof(struct WPaintDefer), __func__);
2112         }
2113
2114         /* imat for normals */
2115         mul_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
2116         invert_m4_m4(imat, mat);
2117         copy_m3_m4(wpd->wpimat, imat);
2118
2119         return true;
2120 }
2121
2122 static float wpaint_blur_weight_single(const MDeformVert *dv, const WeightPaintInfo *wpi)
2123 {
2124         return defvert_find_weight(dv, wpi->active.index);
2125 }
2126
2127 static float wpaint_blur_weight_multi(const MDeformVert *dv, const WeightPaintInfo *wpi)
2128 {
2129         float weight = BKE_defvert_multipaint_collective_weight(
2130                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
2131         CLAMP(weight, 0.0f, 1.0f);
2132         return weight;
2133 }
2134
2135 static float wpaint_blur_weight_calc_from_connected(
2136         const MDeformVert *dvert, WeightPaintInfo *wpi, struct WPaintData *wpd, const unsigned int vidx,
2137         float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *))
2138 {
2139         const MeshElemMap *map = &wpd->blur_data.vmap[vidx];
2140         float paintweight;
2141         if (map->count != 0) {
2142                 paintweight = 0.0f;
2143                 for (int j = 0; j < map->count; j++) {
2144                         paintweight += blur_weight_func(&dvert[map->indices[j]], wpi);
2145                 }
2146                 paintweight /= map->count;
2147         }
2148         else {
2149                 paintweight = blur_weight_func(&dvert[vidx], wpi);
2150         }
2151
2152         return paintweight;
2153 }
2154
2155 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2156 {
2157         Scene *scene = CTX_data_scene(C);
2158         ToolSettings *ts = CTX_data_tool_settings(C);
2159         VPaint *wp = ts->wpaint;
2160         Brush *brush = BKE_paint_brush(&wp->paint);
2161         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2162         ViewContext *vc;
2163         Object *ob;
2164         Mesh *me;
2165         float mat[4][4];
2166         float paintweight;
2167         int *indexar;
2168         unsigned int index, totindex;
2169         float mval[2];
2170         const bool use_blur = (brush->vertexpaint_tool == PAINT_BLEND_BLUR);
2171         bool use_vert_sel;
2172         bool use_face_sel;
2173         bool use_depth;
2174
2175         const float pressure = RNA_float_get(itemptr, "pressure");
2176         const float brush_size_pressure =
2177                 BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2178         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2179         const float brush_alpha_pressure =
2180                 brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2181
2182         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2183         WeightPaintInfo wpi;
2184
2185         /* cannot paint if there is no stroke data */
2186         if (wpd == NULL) {
2187                 /* XXX: force a redraw here, since even though we can't paint,
2188                  * at least view won't freeze until stroke ends */
2189                 ED_region_tag_redraw(CTX_wm_region(C));
2190                 return;
2191         }
2192
2193         float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *) =
2194                 wpd->do_multipaint ? wpaint_blur_weight_multi : wpaint_blur_weight_single;
2195
2196         vc = &wpd->vc;
2197         ob = vc->obact;
2198         me = ob->data;
2199         indexar = wpd->indexar;
2200         
2201         view3d_operator_needs_opengl(C);
2202         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2203
2204         /* load projection matrix */
2205         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2206
2207         RNA_float_get_array(itemptr, "mouse", mval);
2208
2209         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2210         wpi.defbase_tot =        wpd->defbase_tot;
2211         wpi.defbase_sel =        wpd->defbase_sel;
2212         wpi.defbase_tot_sel =    wpd->defbase_tot_sel;
2213
2214         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2215         wpi.active =             wpd->active;
2216         wpi.mirror =             wpd->mirror;
2217         wpi.lock_flags =         wpd->lock_flags;
2218         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2219         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2220         wpi.do_multipaint =      wpd->do_multipaint;
2221         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2222         wpi.brush_alpha_value =  brush_alpha_value;
2223         /* *** done setting up WeightPaintInfo *** */
2224
2225
2226
2227         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2228
2229         use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
2230         use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2231         use_depth = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
2232
2233         /* which faces are involved */
2234         if (use_depth) {
2235                 char editflag_prev = me->editflag;
2236
2237                 /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
2238                 me->editflag &= ~ME_EDIT_PAINT_VERT_SEL;
2239                 if (use_vert_sel) {
2240                         /* Ugly x2, we need this so hidden faces don't draw */
2241                         me->editflag |= ME_EDIT_PAINT_FACE_SEL;
2242                 }
2243                 totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2244                 me->editflag = editflag_prev;
2245
2246                 if (use_face_sel && me->totpoly) {
2247                         MPoly *mpoly = me->mpoly;
2248                         for (index = 0; index < totindex; index++) {
2249                                 if (indexar[index] && indexar[index] <= me->totpoly) {
2250                                         MPoly *mp = &mpoly[indexar[index] - 1];
2251
2252                                         if ((mp->flag & ME_FACE_SEL) == 0) {
2253                                                 indexar[index] = 0;
2254                                         }
2255                                 }
2256                         }
2257                 }
2258         }
2259         else {
2260                 indexar = NULL;
2261         }
2262
2263         /* incase we have modifiers */
2264         ED_vpaint_proj_handle_update(wpd->vp_handle, vc->ar, mval);
2265
2266         /* make sure each vertex gets treated only once */
2267         /* and calculate filter weight */
2268         paintweight = BKE_brush_weight_get(scene, brush);
2269
2270         if (use_depth) {
2271                 for (index = 0; index < totindex; index++) {
2272                         if (indexar[index] && indexar[index] <= me->totpoly) {
2273                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2274                                 MLoop *ml = me->mloop + mpoly->loopstart;
2275                                 int i;
2276
2277                                 if (use_vert_sel) {
2278                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2279                                                 me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
2280                                         }
2281                                 }
2282                                 else {
2283                                         for (i = 0; i < mpoly->totloop; i++, ml++) {
2284                                                 me->dvert[ml->v].flag = 1;
2285                                         }
2286                                 }
2287                         }
2288                 }
2289         }
2290         else {
2291                 const unsigned int totvert = me->totvert;
2292                 unsigned int       i;
2293
2294                 /* in the case of face selection we need to flush */
2295                 if (use_vert_sel || use_face_sel) {
2296                         for (i = 0; i < totvert; i++) {
2297                                 me->dvert[i].flag = me->mvert[i].flag & SELECT;
2298                         }
2299                 }
2300                 else {
2301                         for (i = 0; i < totvert; i++) {
2302                                 me->dvert[i].flag = SELECT;
2303                         }
2304                 }
2305         }
2306
2307         /* accumulate means we refer to the previous,
2308          * which is either the last update, or when we started painting */
2309         BLI_Stack *accumulate_stack = wpd->accumulate_stack;
2310         const bool use_accumulate = (accumulate_stack != NULL);
2311         BLI_assert(accumulate_stack == NULL || BLI_stack_is_empty(accumulate_stack));
2312
2313         const MDeformVert *dvert_prev = use_accumulate ? me->dvert : wp->wpaint_prev;
2314
2315 #define WP_PAINT(v_idx_var)  \
2316         { \
2317                 unsigned int vidx = v_idx_var; \
2318                 if (me->dvert[vidx].flag) { \
2319                         const float alpha = calc_vp_alpha_col_dl( \
2320                                 wp, vc, wpd->wpimat, &wpd->vertexcosnos[vidx], \
2321                                 mval, brush_size_pressure, brush_alpha_pressure, NULL); \
2322                         if (alpha) { \
2323                                 if (use_blur) { \
2324                                         paintweight = wpaint_blur_weight_calc_from_connected( \
2325                                                 dvert_prev, &wpi, wpd, vidx, blur_weight_func); \
2326                                 } \
2327                                 if (use_accumulate) { \
2328                                         struct WPaintDefer *dweight = BLI_stack_push_r(accumulate_stack); \
2329                                         dweight->index = vidx; \
2330                                         dweight->alpha = alpha; \
2331                                         dweight->weight = paintweight; \
2332                                 } \
2333                                 else { \
2334                                         do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight); \
2335                                 } \
2336                         } \
2337                         me->dvert[vidx].flag = 0; \
2338                 } \
2339         } (void)0
2340
2341         if (use_depth) {
2342                 for (index = 0; index < totindex; index++) {
2343
2344                         if (indexar[index] && indexar[index] <= me->totpoly) {
2345                                 MPoly *mpoly = me->mpoly + (indexar[index] - 1);
2346                                 MLoop *ml = me->mloop + mpoly->loopstart;
2347                                 int i;
2348
2349                                 for (i = 0; i < mpoly->totloop; i++, ml++) {
2350                                         WP_PAINT(ml->v);
2351                                 }
2352                         }
2353                 }
2354         }
2355         else {
2356                 const unsigned int totvert = me->totvert;
2357                 unsigned int       i;
2358
2359                 for (i = 0; i < totvert; i++) {
2360                         WP_PAINT(i);
2361                 }
2362         }
2363 #undef WP_PAINT
2364
2365         if (use_accumulate) {
2366                 unsigned int defer_count = BLI_stack_count(accumulate_stack);
2367                 while (defer_count--) {
2368                         struct WPaintDefer *dweight = BLI_stack_peek(accumulate_stack);
2369                         do_weight_paint_vertex(wp, ob, &wpi, dweight->index, dweight->alpha, dweight->weight);
2370                         BLI_stack_discard(accumulate_stack);
2371                 }
2372         }
2373
2374
2375         /* *** free wpi members */
2376         /* *** done freeing wpi members */
2377
2378
2379         swap_m4m4(vc->rv3d->persmat, mat);
2380
2381         /* calculate pivot for rotation around seletion if needed */
2382         /* also needed for "View Selected" on last stroke */
2383         paint_last_stroke_update(scene, vc->ar, mval);
2384
2385         DAG_id_tag_update(ob->data, 0);
2386         ED_region_tag_redraw(vc->ar);
2387 }
2388
2389 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2390 {
2391         ToolSettings *ts = CTX_data_tool_settings(C);
2392         Object *ob = CTX_data_active_object(C);
2393         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2394         
2395         if (wpd) {
2396                 ED_vpaint_proj_handle_free(wpd->vp_handle);
2397                 MEM_freeN(wpd->indexar);
2398                 
2399                 if (wpd->defbase_sel)
2400                         MEM_freeN((void *)wpd->defbase_sel);
2401                 if (wpd->vgroup_validmap)
2402                         MEM_freeN((void *)wpd->vgroup_validmap);
2403                 if (wpd->lock_flags)
2404                         MEM_freeN((void *)wpd->lock_flags);
2405                 if (wpd->active.lock)
2406                         MEM_freeN((void *)wpd->active.lock);
2407                 if (wpd->mirror.lock)
2408                         MEM_freeN((void *)wpd->mirror.lock);
2409
2410                 if (wpd->blur_data.vmap) {
2411                         MEM_freeN(wpd->blur_data.vmap);
2412                 }
2413                 if (wpd->blur_data.vmap_mem) {
2414                         MEM_freeN(wpd->blur_data.vmap_mem);
2415                 }
2416
2417                 if (wpd->accumulate_stack) {
2418                         BLI_stack_free(wpd->accumulate_stack);
2419                 }
2420
2421                 MEM_freeN(wpd);
2422         }
2423         
2424         /* frees prev buffer */
2425         copy_wpaint_prev(ts->wpaint, NULL, 0);
2426         
2427         /* and particles too */
2428         if (ob->particlesystem.first) {
2429                 ParticleSystem *psys;
2430                 int i;
2431                 
2432                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2433                         for (i = 0; i < PSYS_TOT_VG; i++) {
2434                                 if (psys->vgroup[i] == ob->actdef) {
2435                                         psys->recalc |= PSYS_RECALC_RESET;
2436                                         break;
2437                                 }
2438                         }
2439                 }
2440         }
2441
2442         DAG_id_tag_update(ob->data, 0);
2443
2444         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2445 }
2446
2447
2448 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2449 {
2450         int retval;
2451
2452         op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
2453                                           wpaint_stroke_update_step, NULL,
2454                                           wpaint_stroke_done, event->type);
2455         
2456         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2457                 paint_stroke_data_free(op);
2458                 return OPERATOR_FINISHED;
2459         }
2460         /* add modal handler */
2461         WM_event_add_modal_handler(C, op);
2462
2463         OPERATOR_RETVAL_CHECK(retval);
2464         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2465         
2466         return OPERATOR_RUNNING_MODAL;
2467 }
2468
2469 static int wpaint_exec(bContext *C, wmOperator *op)
2470 {
2471         op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
2472                                           wpaint_stroke_update_step, NULL,
2473                                           wpaint_stroke_done, 0);
2474
2475         /* frees op->customdata */
2476         paint_stroke_exec(C, op);
2477
2478         return OPERATOR_FINISHED;
2479 }
2480
2481 static void wpaint_cancel(bContext *C, wmOperator *op)
2482 {
2483         paint_stroke_cancel(C, op);
2484 }
2485
2486 void PAINT_OT_weight_paint(wmOperatorType *ot)
2487 {
2488         
2489         /* identifiers */
2490         ot->name = "Weight Paint";
2491         ot->idname = "PAINT_OT_weight_paint";
2492         ot->description = "Paint a stroke in the current vertex group's weights";
2493         
2494         /* api callbacks */
2495         ot->invoke = wpaint_invoke;
2496         ot->modal = paint_stroke_modal;
2497         ot->exec = wpaint_exec;
2498         ot->poll = weight_paint_poll;
2499         ot->cancel = wpaint_cancel;
2500         
2501         /* flags */
2502         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2503         
2504         paint_stroke_operator_properties(ot);
2505 }
2506
2507 static int weight_paint_set_exec(bContext *C, wmOperator *op)
2508 {
2509         struct Scene *scene = CTX_data_scene(C);
2510         Object *obact = CTX_data_active_object(C);
2511         ToolSettings *ts = CTX_data_tool_settings(C);
2512         Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
2513         float vgroup_weight = BKE_brush_weight_get(scene, brush);
2514
2515         if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, NULL) == false) {
2516                 return OPERATOR_CANCELLED;
2517         }
2518
2519         if (ED_wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight)) {
2520                 ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
2521                 return OPERATOR_FINISHED;
2522         }
2523         else {
2524                 return OPERATOR_CANCELLED;
2525         }
2526 }
2527
2528 void PAINT_OT_weight_set(wmOperatorType *ot)
2529 {
2530         /* identifiers */
2531         ot->name = "Set Weight";
2532         ot->idname = "PAINT_OT_weight_set";
2533         ot->description = "Fill the active vertex group with the current paint weight";
2534
2535         /* api callbacks */
2536         ot->exec = weight_paint_set_exec;
2537         ot->poll = mask_paint_poll;
2538
2539         /* flags */
2540         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2541 }
2542
2543 /* ************ set / clear vertex paint mode ********** */
2544
2545 /**
2546  * \note Keep in sync with #wpaint_mode_toggle_exec
2547  */
2548 static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
2549 {       
2550         Object *ob = CTX_data_active_object(C);
2551         const int mode_flag = OB_MODE_VERTEX_PAINT;
2552         const bool is_mode_set = (ob->mode & mode_flag) != 0;
2553         Scene *scene = CTX_data_scene(C);
2554         VPaint *vp = scene->toolsettings->vpaint;
2555         Mesh *me;
2556
2557         if (!is_mode_set) {
2558                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
2559                         return OPERATOR_CANCELLED;
2560                 }
2561         }
2562
2563         me = BKE_mesh_from_object(ob);
2564         
2565         /* toggle: end vpaint */
2566         if (is_mode_set) {
2567                 ob->mode &= ~mode_flag;
2568
2569                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
2570                         BKE_mesh_flush_select_from_polys(me);
2571                 }
2572
2573                 paint_cursor_delete_textures();
2574         }
2575         else {
2576                 ob->mode |= mode_flag;
2577
2578                 if (me->mloopcol == NULL) {
2579                         make_vertexcol(ob);
2580                 }
2581
2582                 if (vp == NULL)
2583                         vp = scene->toolsettings->vpaint = new_vpaint(0);
2584                 
2585                 paint_cursor_start(C, vertex_paint_poll);
2586
2587                 BKE_paint_init(scene, ePaintVertex, PAINT_CURSOR_VERTEX_PAINT);
2588         }
2589         
2590         /* update modifier stack for mapping requirements */
2591         DAG_id_tag_update(&me->id, 0);
2592         
2593         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2594         
2595         return OPERATOR_FINISHED;
2596 }
2597
2598 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2599 {
2600         
2601         /* identifiers */
2602         ot->name = "Vertex Paint Mode";
2603         ot->idname = "PAINT_OT_vertex_paint_toggle";
2604         ot->description = "Toggle the vertex paint mode in 3D view";
2605         
2606         /* api callbacks */
2607         ot->exec = vpaint_mode_toggle_exec;
2608         ot->poll = paint_poll_test;
2609         
2610         /* flags */
2611         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2612 }
2613
2614
2615
2616 /* ********************** vertex paint operator ******************* */
2617
2618 /* Implementation notes:
2619  *
2620  * Operator->invoke()
2621  * - validate context (add mcol)
2622  * - create customdata storage
2623  * - call paint once (mouse click)
2624  * - add modal handler 
2625  *
2626  * Operator->modal()
2627  * - for every mousemove, apply vertex paint
2628  * - exit on mouse release, free customdata
2629  *   (return OPERATOR_FINISHED also removes handler and operator)
2630  *
2631  * For future:
2632  * - implement a stroke event (or mousemove with past positons)
2633  * - revise whether op->customdata should be added in object, in set_vpaint
2634  */
2635
2636 typedef struct PolyFaceMap {
2637         struct PolyFaceMap *next, *prev;
2638         int facenr;
2639 } PolyFaceMap;
2640
2641 typedef struct VPaintData {
2642         ViewContext vc;
2643         unsigned int paintcol;
2644         int *indexar;
2645
2646         struct VertProjHandle *vp_handle;
2647         DMCoNo *vertexcosnos;
2648
2649         float vpimat[3][3];
2650
2651         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2652          * array, otherwise we need to refresh the modifier stack */
2653         bool use_fast_update;
2654
2655         /* loops tagged as having been painted, to apply shared vertex color
2656          * blending only to modified loops */
2657         bool *mlooptag;
2658
2659         bool is_texbrush;
2660 } VPaintData;
2661
2662 static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
2663 {
2664         Scene *scene = CTX_data_scene(C);
2665         ToolSettings *ts = scene->toolsettings;
2666         struct PaintStroke *stroke = op->customdata;
2667         VPaint *vp = ts->vpaint;
2668         Brush *brush = BKE_paint_brush(&vp->paint);
2669         struct VPaintData *vpd;
2670         Object *ob = CTX_data_active_object(C);
2671         Mesh *me;
2672         float mat[4][4], imat[4][4];
2673
2674         /* context checks could be a poll() */
2675         me = BKE_mesh_from_object(ob);
2676         if (me == NULL || me->totpoly == 0)
2677                 return false;
2678         
2679         if (me->mloopcol == NULL)
2680                 make_vertexcol(ob);
2681         if (me->mloopcol == NULL)
2682                 return false;
2683
2684         /* make mode data storage */
2685         vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
2686         paint_stroke_set_mode_data(stroke, vpd);
2687         view3d_set_viewcontext(C, &vpd->vc);
2688         
2689         vpd->vp_handle = ED_vpaint_proj_handle_create(vpd->vc.scene, ob, &vpd->vertexcosnos);
2690
2691         vpd->indexar = get_indexarray(me);
2692         vpd->paintcol = vpaint_get_current_col(scene, vp);
2693
2694         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2695                            brush->mtex.tex;
2696
2697         /* are we painting onto a modified mesh?,
2698          * if not we can skip face map trickiness */
2699         if (vertex_paint_use_fast_update_check(ob)) {
2700                 vpd->use_fast_update = true;
2701 /*              printf("Fast update!\n");*/
2702         }
2703         else {
2704                 vpd->use_fast_update = false;
2705 /*              printf("No fast update!\n");*/
2706         }
2707
2708         /* to keep tracked of modified loops for shared vertex color blending */
2709         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2710                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2711         }
2712
2713         /* for filtering */
2714         copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
2715         
2716         /* some old cruft to sort out later */
2717         mul_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
2718         invert_m4_m4(imat, mat);
2719         copy_m3_m4(vpd->vpimat, imat);
2720
2721         return 1;
2722 }
2723
2724 static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Mesh *me,
2725                               const unsigned int index, const float mval[2],
2726                               const float brush_size_pressure, const float brush_alpha_pressure)
2727 {
2728         ViewContext *vc = &vpd->vc;
2729         Brush *brush = BKE_paint_brush(&vp->paint);
2730         MPoly *mpoly = &me->mpoly[index];
2731         MLoop *ml;
2732         unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
2733         unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
2734         bool *mlooptag = (vpd->mlooptag) ? vpd->mlooptag + mpoly->loopstart : NULL;
2735         float alpha;
2736         int i, j;
2737         int totloop = mpoly->totloop;
2738
2739         int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
2740
2741         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2742                 unsigned int blend[4] = {0};
2743                 unsigned int tcol;
2744                 char *col;
2745
2746                 for (j = 0; j < totloop; j++) {
2747                         col = (char *)(lcol + j);
2748                         blend[0] += col[0];
2749                         blend[1] += col[1];
2750                         blend[2] += col[2];
2751                         blend[3] += col[3];
2752                 }
2753
2754                 blend[0] = divide_round_i(blend[0], totloop);
2755                 blend[1] = divide_round_i(blend[1], totloop);
2756                 blend[2] = divide_round_i(blend[2], totloop);
2757                 blend[3] = divide_round_i(blend[3], totloop);
2758                 col = (char *)&tcol;
2759                 col[0] = blend[0];
2760                 col[1] = blend[1];
2761                 col[2] = blend[2];
2762                 col[3] = blend[3];
2763
2764                 vpd->paintcol = *((unsigned int *)col);
2765         }
2766
2767         ml = me->mloop + mpoly->loopstart;
2768         for (i = 0; i < totloop; i++, ml++) {
2769                 float rgba[4];
2770                 unsigned int paintcol;
2771                 alpha = calc_vp_alpha_col_dl(vp, vc, vpd->vpimat,
2772                                          &vpd->vertexcosnos[ml->v], mval,
2773                                          brush_size_pressure, brush_alpha_pressure, rgba);
2774
2775                 if (vpd->is_texbrush) {
2776                         float rgba_br[3];
2777                         rgb_uchar_to_float(rgba_br, (const unsigned char *)&vpd->paintcol);
2778                         mul_v3_v3(rgba_br, rgba);
2779                         rgb_float_to_uchar((unsigned char *)&paintcol, rgba_br);
2780                 }
2781                 else
2782                         paintcol = vpd->paintcol;
2783
2784                 if (alpha > 0.0f) {
2785                         const int alpha_i = (int)(alpha * 255.0f);
2786                         lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], paintcol, alpha_i, brush_alpha_pressure_i);
2787
2788                         if (mlooptag) mlooptag[i] = 1;
2789                 }
2790         }
2791 }
2792
2793 static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2794 {
2795         Scene *scene = CTX_data_scene(C);
2796         ToolSettings *ts = CTX_data_tool_settings(C);
2797         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2798         VPaint *vp = ts->vpaint;
2799         Brush *brush = BKE_paint_brush(&vp->paint);
2800         ViewContext *vc = &vpd->vc;
2801         Object *ob = vc->obact;
2802         Mesh *me = ob->data;
2803         float mat[4][4];
2804         int *indexar = vpd->indexar;
2805         int totindex, index;
2806         float mval[2];
2807
2808         const float pressure = RNA_float_get(itemptr, "pressure");
2809         const float brush_size_pressure =
2810                 BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
2811         const float brush_alpha_pressure =
2812                 BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
2813
2814         RNA_float_get_array(itemptr, "mouse", mval);
2815
2816         view3d_operator_needs_opengl(C);
2817         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2818
2819         /* load projection matrix */
2820         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2821
2822         /* which faces are involved */
2823         totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
2824
2825         if ((me->editflag & ME_EDIT_PAINT_FACE_SEL) && me->mpoly) {
2826                 for (index = 0; index < totindex; index++) {
2827                         if (indexar[index] && indexar[index] <= me->totpoly) {
2828                                 const MPoly *mpoly = &me->mpoly[indexar[index] - 1];
2829
2830                                 if ((mpoly->flag & ME_FACE_SEL) == 0)
2831                                         indexar[index] = 0;
2832                         }
2833                 }
2834         }
2835         
2836         swap_m4m4(vc->rv3d->persmat, mat);
2837
2838         /* incase we have modifiers */
2839         ED_vpaint_proj_handle_update(vpd->vp_handle, vc->ar, mval);
2840
2841         /* clear modified tag for blur tool */
2842         if (vpd->mlooptag)
2843                 memset(vpd->mlooptag, 0, sizeof(bool) * me->totloop);
2844
2845         for (index = 0; index < totindex; index++) {
2846                 if (indexar[index] && indexar[index] <= me->totpoly) {
2847                         vpaint_paint_poly(vp, vpd, me, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
2848                 }
2849         }
2850                 
2851         swap_m4m4(vc->rv3d->persmat, mat);
2852
2853         /* was disabled because it is slow, but necessary for blur */
2854         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2855                 do_shared_vertexcol(me, vpd->mlooptag);
2856         }
2857
2858         /* calculate pivot for rotation around seletion if needed */
2859         /* also needed for "View Selected" on last stroke */
2860         paint_last_stroke_update(scene, vc->ar, mval);
2861
2862         ED_region_tag_redraw(vc->ar);
2863
2864         if (vpd->use_fast_update == false) {
2865                 /* recalculate modifier stack to get new colors, slow,
2866                  * avoid this if we can! */
2867                 DAG_id_tag_update(ob->data, 0);
2868         }
2869         else {
2870                 /* If using new VBO drawing, mark mcol as dirty to force colors gpu buffer refresh! */
2871                 ob->derivedFinal->dirty |= DM_DIRTY_MCOL_UPDATE_DRAW;
2872         }
2873 }
2874
2875 static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2876 {
2877         ToolSettings *ts = CTX_data_tool_settings(C);
2878         struct VPaintData *vpd = paint_stroke_mode_data(stroke);
2879         ViewContext *vc = &vpd->vc;
2880         Object *ob = vc->obact;
2881         Mesh *me = ob->data;
2882
2883         ED_vpaint_proj_handle_free(vpd->vp_handle);
2884         MEM_freeN(vpd->indexar);
2885         
2886         /* frees prev buffer */
2887         copy_vpaint_prev(ts->vpaint, NULL, 0);
2888
2889         if (vpd->mlooptag)
2890                 MEM_freeN(vpd->mlooptag);
2891
2892         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2893         DAG_id_tag_update(&me->id, 0);
2894
2895         MEM_freeN(vpd);
2896 }
2897
2898 static int vpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2899 {
2900         int retval;
2901
2902         op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
2903                                           vpaint_stroke_update_step, NULL,
2904                                           vpaint_stroke_done, event->type);
2905         
2906         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2907                 paint_stroke_data_free(op);
2908                 return OPERATOR_FINISHED;
2909         }
2910
2911         /* add modal handler */
2912         WM_event_add_modal_handler(C, op);
2913
2914         OPERATOR_RETVAL_CHECK(retval);
2915         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2916         
2917         return OPERATOR_RUNNING_MODAL;
2918 }
2919
2920 static int vpaint_exec(bContext *C, wmOperator *op)
2921 {
2922         op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
2923                                           vpaint_stroke_update_step, NULL,
2924                                           vpaint_stroke_done, 0);
2925
2926         /* frees op->customdata */
2927         paint_stroke_exec(C, op);
2928
2929         return OPERATOR_FINISHED;
2930 }
2931
2932 static void vpaint_cancel(bContext *C, wmOperator *op)
2933 {
2934         paint_stroke_cancel(C, op);
2935 }
2936
2937 void PAINT_OT_vertex_paint(wmOperatorType *ot)
2938 {
2939         /* identifiers */
2940         ot->name = "Vertex Paint";
2941         ot->idname = "PAINT_OT_vertex_paint";
2942         ot->description = "Paint a stroke in the active vertex color layer";
2943         
2944         /* api callbacks */
2945         ot->invoke = vpaint_invoke;
2946         ot->modal = paint_stroke_modal;
2947         ot->exec = vpaint_exec;
2948         ot->poll = vertex_paint_poll;
2949         ot->cancel = vpaint_cancel;
2950         
2951         /* flags */
2952         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2953
2954         paint_stroke_operator_properties(ot);
2955 }
2956
2957 /* ********************** weight from bones operator ******************* */
2958
2959 static int weight_from_bones_poll(bContext *C)
2960 {
2961         Object *ob = CTX_data_active_object(C);
2962
2963         return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
2964 }
2965
2966 static int weight_from_bones_exec(bContext *C, wmOperator *op)
2967 {
2968         Scene *scene = CTX_data_scene(C);
2969         Object *ob = CTX_data_active_object(C);
2970         Object *armob = modifiers_isDeformedByArmature(ob);
2971         Mesh *me = ob->data;
2972         int type = RNA_enum_get(op->ptr, "type");
2973
2974         create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
2975
2976         DAG_id_tag_update(&me->id, 0);
2977         WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
2978
2979         return OPERATOR_FINISHED;
2980 }
2981
2982 void PAINT_OT_weight_from_bones(wmOperatorType *ot)
2983 {
2984         static EnumPropertyItem type_items[] = {
2985                 {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
2986                 {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
2987                 {0, NULL, 0, NULL, NULL}};
2988
2989         /* identifiers */
2990         ot->name = "Weight from Bones";
2991         ot->idname = "PAINT_OT_weight_from_bones";
2992         ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
2993                           "using the distance between the vertices and the bones";
2994         
2995         /* api callbacks */
2996         ot->exec = weight_from_bones_exec;
2997         ot->invoke = WM_menu_invoke;
2998         ot->poll = weight_from_bones_poll;
2999         
3000         /* flags */
3001         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
3002
3003         /* properties */
3004         ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
3005 }
3006
3007 /* *** VGroups Gradient *** */
3008 typedef struct DMGradient_vertStore {
3009         float sco[2];
3010         float weight_orig;
3011         enum {
3012                 VGRAD_STORE_NOP      = 0,
3013                 VGRAD_STORE_DW_EXIST = (1 << 0)
3014         } flag;
3015 } DMGradient_vertStore;
3016
3017 typedef struct DMGradient_userData {
3018         struct ARegion *ar;
3019         Scene *scene;
3020         Mesh *me;
3021         Brush *brush;
3022         const float *sco_start;     /* [2] */
3023         const float *sco_end;       /* [2] */
3024         float        sco_line_div;  /* store (1.0f / len_v2v2(sco_start, sco_end)) */
3025         int def_nr;
3026         bool is_init;
3027         DMGradient_vertStore *vert_cache;
3028         /* only for init */
3029         BLI_bitmap *vert_visit;
3030
3031         /* options */
3032         short use_select;
3033         short type;
3034         float weightpaint;
3035 } DMGradient_userData;
3036
3037 static void gradientVert_update(DMGradient_userData *grad_data, int index)
3038 {
3039         Mesh *me = grad_data->me;
3040         DMGradient_vertStore *vs = &grad_data->vert_cache[index];
3041         float alpha;
3042
3043         if (grad_data->type == WPAINT_GRADIENT_TYPE_LINEAR) {
3044                 alpha = line_point_factor_v2(vs->sco, grad_data->sco_start, grad_data->sco_end);
3045         }
3046         else {
3047                 BLI_assert(grad_data->type == WPAINT_GRADIENT_TYPE_RADIAL);
3048                 alpha = len_v2v2(grad_data->sco_start, vs->sco) * grad_data->sco_line_div;
3049         }
3050         /* no need to clamp 'alpha' yet */
3051
3052         /* adjust weight */
3053         alpha = BKE_brush_curve_strength_clamped(grad_data->brush, alpha, 1.0f);
3054
3055         if (alpha != 0.0f) {
3056                 MDeformVert *dv = &me->dvert[index];
3057                 MDeformWeight *dw = defvert_verify_index(dv, grad_data->def_nr);
3058                 // dw->weight = alpha; // testing
3059                 int tool = grad_data->brush->vertexpaint_tool;
3060                 float testw;
3061
3062                 /* init if we just added */
3063                 testw = wpaint_blend_tool(tool, vs->weight_orig, grad_data->weightpaint, alpha * grad_data->brush->alpha);
3064                 CLAMP(testw, 0.0f, 1.0f);
3065                 dw->weight = testw;
3066         }
3067         else {
3068                 MDeformVert *dv = &me->dvert[index];
3069                 if (vs->flag & VGRAD_STORE_DW_EXIST) {
3070                         /* normally we NULL check, but in this case we know it exists */
3071                         MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
3072                         dw->weight = vs->weight_orig;
3073                 }
3074                 else {
3075                         /* wasn't originally existing, remove */
3076                         MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
3077                         if (dw) {
3078                                 defvert_remove_group(dv, dw);
3079                         }
3080                 }
3081         }
3082 }
3083
3084 static void gradientVertUpdate__mapFunc(
3085         void *userData, int index, const float UNUSED(co[3]),
3086         const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
3087 {
3088         DMGradient_userData *grad_data = userData;
3089         Mesh *me = grad_data->me;
3090         if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
3091                 DMGradient_vertStore *vs = &grad_data->vert_cache[index];
3092                 if (vs->sco[0] != FLT_MAX) {
3093                         gradientVert_update(grad_data, index);
3094                 }
3095         }
3096 }
3097
3098 static void gradientVertInit__mapFunc(
3099         void *userData, int index, const float co[3],
3100         const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
3101 {
3102         DMGradient_userData *grad_data = userData;
3103         Mesh *me = grad_data->me;
3104
3105         if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
3106                 /* run first pass only,
3107                  * the screen coords of the verts need to be cached because
3108                  * updating the mesh may move them about (entering feedback loop) */
3109
3110                 if (BLI_BITMAP_TEST(grad_data->vert_visit, index) == 0) {
3111                         DMGradient_vertStore *vs = &grad_data->vert_cache[index];
3112                         if (ED_view3d_project_float_object(grad_data->ar,
3113                                                            co, vs->sco,
3114                                                            V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
3115                         {
3116                                 /* ok */
3117                                 MDeformVert *dv = &me->dvert[index];
3118                                 MDeformWeight *dw;
3119                                 dw = defvert_find_index(dv, grad_data->def_nr);
3120                                 if (dw) {
3121                                         vs->weight_orig = dw->weight;
3122                                         vs->flag = VGRAD_STORE_DW_EXIST;
3123                                 }
3124                                 else {
3125                                         vs->weight_orig = 0.0f;
3126                                         vs->flag = VGRAD_STORE_NOP;
3127                                 }
3128