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