d35ab5906205a64da3b324939f509e6150e41a40
[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  * Used for vertex color & weight paint and mode switching.
32  *
33  * \note This file is already big,
34  * use `paint_vertex_color_ops.c` & `paint_vertex_weight_ops.c` for general purpose operators.
35  */
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_listbase.h"
40 #include "BLI_rect.h"
41 #include "BLI_math.h"
42 #include "BLI_array_utils.h"
43 #include "BLI_task.h"
44
45 #include "DNA_armature_types.h"
46 #include "DNA_mesh_types.h"
47 #include "DNA_particle_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_brush_types.h"
50 #include "DNA_object_types.h"
51
52 #include "RNA_access.h"
53 #include "RNA_define.h"
54
55 #include "BKE_brush.h"
56 #include "BKE_context.h"
57 #include "BKE_depsgraph.h"
58 #include "BKE_deform.h"
59 #include "BKE_main.h"
60 #include "BKE_mesh.h"
61 #include "BKE_mesh_mapping.h"
62 #include "BKE_object_deform.h"
63 #include "BKE_paint.h"
64 #include "BKE_report.h"
65 #include "BKE_subsurf.h"
66
67 #include "WM_api.h"
68 #include "WM_types.h"
69
70 #include "ED_object.h"
71 #include "ED_mesh.h"
72 #include "ED_screen.h"
73 #include "ED_view3d.h"
74
75 #include "bmesh.h"
76 #include "BKE_ccg.h"
77
78 #include "sculpt_intern.h"
79 #include "paint_intern.h"  /* own include */
80
81 /* Use for 'blur' brush, align with PBVH nodes, created and freed on each update. */
82 struct VPaintAverageAccum {
83         uint len;
84         uint value[3];
85 };
86
87 struct WPaintAverageAccum {
88         uint len;
89         double value;
90 };
91
92 struct NormalAnglePrecalc {
93         bool do_mask_normal;
94         /* what angle to mask at */
95         float angle;
96         /* cos(angle), faster to compare */
97         float angle__cos;
98         float angle_inner;
99         float angle_inner__cos;
100         /* difference between angle and angle_inner, for easy access */
101         float angle_range;
102 };
103
104
105 static void view_angle_limits_init(
106         struct NormalAnglePrecalc *a, float angle, bool do_mask_normal)
107 {
108         angle = RAD2DEGF(angle);
109         a->do_mask_normal = do_mask_normal;
110         if (do_mask_normal) {
111                 a->angle_inner = angle;
112                 a->angle = (a->angle_inner + 90.0f) * 0.5f;
113         }
114         else {
115                 a->angle_inner = a->angle = angle;
116         }
117
118         a->angle_inner *=   (float)(M_PI_2 / 90);
119         a->angle *=         (float)(M_PI_2 / 90);
120         a->angle_range = a->angle - a->angle_inner;
121
122         if (a->angle_range <= 0.0f) {
123                 a->do_mask_normal = false;  /* no need to do blending */
124         }
125
126         a->angle__cos       = cosf(a->angle);
127         a->angle_inner__cos = cosf(a->angle_inner);
128 }
129
130 static float view_angle_limits_apply_falloff(
131         const struct NormalAnglePrecalc *a, float angle_cos, float *mask_p)
132 {
133         if (angle_cos <= a->angle__cos) {
134                 /* outsize the normal limit */
135                 return false;
136         }
137         else if (angle_cos < a->angle_inner__cos) {
138                 *mask_p *= (a->angle - acosf(angle_cos)) / a->angle_range;
139                 return true;
140         }
141         else {
142                 return true;
143         }
144 }
145
146 static bool vwpaint_use_normal(const VPaint *vp)
147 {
148         return ((vp->paint.brush->flag & BRUSH_FRONTFACE) != 0) ||
149                ((vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
150 }
151
152 static bool brush_use_accumulate(const Brush *brush)
153 {
154         return (brush->flag & BRUSH_ACCUMULATE) != 0 || brush->vertexpaint_tool == PAINT_BLEND_SMEAR;
155 }
156
157 static MDeformVert *defweight_prev_init(MDeformVert *dvert_prev, MDeformVert *dvert_curr, int index)
158 {
159         MDeformVert *dv_curr = &dvert_curr[index];
160         MDeformVert *dv_prev = &dvert_prev[index];
161         if (dv_prev->flag == 1) {
162                 dv_prev->flag = 0;
163                 defvert_copy(dv_prev, dv_curr);
164         }
165         return dv_prev;
166 }
167
168 /* check if we can do partial updates and have them draw realtime
169  * (without rebuilding the 'derivedFinal') */
170 static bool vertex_paint_use_fast_update_check(Object *ob)
171 {
172         DerivedMesh *dm = ob->derivedFinal;
173
174         if (dm) {
175                 Mesh *me = BKE_mesh_from_object(ob);
176                 if (me && me->mloopcol) {
177                         return (me->mloopcol == CustomData_get_layer(&dm->loopData, CD_MLOOPCOL));
178                 }
179         }
180
181         return false;
182 }
183
184 static void paint_last_stroke_update(Scene *scene, ARegion *ar, const float mval[2])
185 {
186         const int mval_i[2] = {mval[0], mval[1]};
187         float world[3];
188
189         if (ED_view3d_autodist_simple(ar, mval_i, world, 0, NULL)) {
190                 UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
191                 ups->average_stroke_counter++;
192                 add_v3_v3(ups->average_stroke_accum, world);
193                 ups->last_stroke_valid = true;
194         }
195 }
196
197 /* polling - retrieve whether cursor should be set or operator should be done */
198
199 /* Returns true if vertex paint mode is active */
200 bool vertex_paint_mode_poll(bContext *C)
201 {
202         Object *ob = CTX_data_active_object(C);
203
204         return ob && ob->mode == OB_MODE_VERTEX_PAINT && ((Mesh *)ob->data)->totpoly;
205 }
206
207 bool vertex_paint_poll(bContext *C)
208 {
209         if (vertex_paint_mode_poll(C) &&
210             BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
211         {
212                 ScrArea *sa = CTX_wm_area(C);
213                 if (sa && sa->spacetype == SPACE_VIEW3D) {
214                         ARegion *ar = CTX_wm_region(C);
215                         if (ar->regiontype == RGN_TYPE_WINDOW)
216                                 return 1;
217                 }
218         }
219         return 0;
220 }
221
222 bool weight_paint_mode_poll(bContext *C)
223 {
224         Object *ob = CTX_data_active_object(C);
225
226         return ob && ob->mode == OB_MODE_WEIGHT_PAINT && ((Mesh *)ob->data)->totpoly;
227 }
228
229 bool weight_paint_poll(bContext *C)
230 {
231         Object *ob = CTX_data_active_object(C);
232         ScrArea *sa;
233
234         if ((ob != NULL) &&
235             (ob->mode & OB_MODE_WEIGHT_PAINT) &&
236             (BKE_paint_brush(&CTX_data_tool_settings(C)->wpaint->paint) != NULL) &&
237             (sa = CTX_wm_area(C)) &&
238             (sa->spacetype == SPACE_VIEW3D))
239         {
240                 ARegion *ar = CTX_wm_region(C);
241                 if (ar->regiontype == RGN_TYPE_WINDOW) {
242                         return 1;
243                 }
244         }
245         return 0;
246 }
247
248 static VPaint *new_vpaint(void)
249 {
250         VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
251
252         vp->paint.flags |= PAINT_SHOW_BRUSH;
253
254         return vp;
255 }
256
257 uint vpaint_get_current_col(Scene *scene, VPaint *vp)
258 {
259         Brush *brush = BKE_paint_brush(&vp->paint);
260         uchar col[4];
261         rgb_float_to_uchar(col, BKE_brush_color_get(scene, brush));
262         col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
263         return *(uint *)col;
264 }
265
266 /* wpaint has 'wpaint_blend' */
267 static uint vpaint_blend(
268         const VPaint *vp, uint color_curr, uint color_orig,
269         uint color_paint, const int alpha_i,
270         /* pre scaled from [0-1] --> [0-255] */
271         const int brush_alpha_value_i)
272 {
273         const Brush *brush = vp->paint.brush;
274         const int tool = brush->vertexpaint_tool;
275
276         uint color_blend = ED_vpaint_blend_tool(tool, color_curr, color_paint, alpha_i);
277
278         /* if no accumulate, clip color adding with colorig & orig alpha */
279         if (!brush_use_accumulate(brush)) {
280                 uint color_test, a;
281                 char *cp, *ct, *co;
282
283                 color_test = ED_vpaint_blend_tool(tool, color_orig, color_paint, brush_alpha_value_i);
284
285                 cp = (char *)&color_blend;
286                 ct = (char *)&color_test;
287                 co = (char *)&color_orig;
288
289                 for (a = 0; a < 4; a++) {
290                         if (ct[a] < co[a]) {
291                                 if (cp[a] < ct[a]) cp[a] = ct[a];
292                                 else if (cp[a] > co[a]) cp[a] = co[a];
293                         }
294                         else {
295                                 if (cp[a] < co[a]) cp[a] = co[a];
296                                 else if (cp[a] > ct[a]) cp[a] = ct[a];
297                         }
298                 }
299         }
300
301         if ((brush->flag & BRUSH_LOCK_ALPHA) &&
302             !ELEM(tool, PAINT_BLEND_ALPHA_SUB, PAINT_BLEND_ALPHA_ADD))
303         {
304                 char *cp, *cc;
305                 cp = (char *)&color_blend;
306                 cc = (char *)&color_curr;
307                 cp[3] = cc[3];
308         }
309
310         return color_blend;
311 }
312
313 static void tex_color_alpha(
314         VPaint *vp, const ViewContext *vc, const float co[3],
315         float r_rgba[4])
316 {
317         const Brush *brush = BKE_paint_brush(&vp->paint);
318         BLI_assert(brush->mtex.tex != NULL);
319         if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
320                 BKE_brush_sample_tex_3d(vc->scene, brush, co, r_rgba, 0, NULL);
321         }
322         else {
323                 float co_ss[2];  /* screenspace */
324                 if (ED_view3d_project_float_object(
325                         vc->ar,
326                         co, co_ss,
327                         V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
328                 {
329                         const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f};  /* we need a 3rd empty value */
330                         BKE_brush_sample_tex_3d(vc->scene, brush, co_ss_3d, r_rgba, 0, NULL);
331                 }
332                 else {
333                         zero_v4(r_rgba);
334                 }
335         }
336 }
337
338 /* vpaint has 'vpaint_blend' */
339 static float wpaint_blend(
340         const VPaint *wp, float weight,
341         const float alpha, float paintval,
342         const float UNUSED(brush_alpha_value),
343         const short do_flip)
344 {
345         const Brush *brush = wp->paint.brush;
346         int tool = brush->vertexpaint_tool;
347
348         if (do_flip) {
349                 switch (tool) {
350                         case PAINT_BLEND_MIX:
351                                 paintval = 1.f - paintval; break;
352                         case PAINT_BLEND_ADD:
353                                 tool = PAINT_BLEND_SUB; break;
354                         case PAINT_BLEND_SUB:
355                                 tool = PAINT_BLEND_ADD; break;
356                         case PAINT_BLEND_LIGHTEN:
357                                 tool = PAINT_BLEND_DARKEN; break;
358                         case PAINT_BLEND_DARKEN:
359                                 tool = PAINT_BLEND_LIGHTEN; break;
360                 }
361         }
362
363         weight = ED_wpaint_blend_tool(tool, weight, paintval, alpha);
364
365         CLAMP(weight, 0.0f, 1.0f);
366
367         return weight;
368 }
369
370 static float wpaint_clamp_monotonic(float oldval, float curval, float newval)
371 {
372         if (newval < oldval)
373                 return MIN2(newval, curval);
374         else if (newval > oldval)
375                 return MAX2(newval, curval);
376         else
377                 return newval;
378 }
379
380 /* ----------------------------------------------------- */
381
382 static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap)
383 {
384         float sum = 0.0f, fac;
385         uint i, tot = 0;
386         MDeformWeight *dw;
387
388         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
389                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
390                         tot++;
391                         sum += dw->weight;
392                 }
393         }
394
395         if ((tot == 0) || (sum == 1.0f)) {
396                 return;
397         }
398
399         if (sum != 0.0f) {
400                 fac = 1.0f / sum;
401
402                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
403                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
404                                 dw->weight *= fac;
405                         }
406                 }
407         }
408         else {
409                 /* hrmf, not a factor in this case */
410                 fac = 1.0f / tot;
411
412                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
413                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
414                                 dw->weight = fac;
415                         }
416                 }
417         }
418 }
419
420 /**
421  * A version of #do_weight_paint_normalize_all that includes locked weights
422  * but only changes unlocked weights.
423  */
424 static bool do_weight_paint_normalize_all_locked(
425         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
426         const bool *lock_flags)
427 {
428         float sum = 0.0f, fac;
429         float sum_unlock = 0.0f;
430         float lock_weight = 0.0f;
431         uint i, tot = 0;
432         MDeformWeight *dw;
433
434         if (lock_flags == NULL) {
435                 do_weight_paint_normalize_all(dvert, defbase_tot, vgroup_validmap);
436                 return true;
437         }
438
439         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
440                 if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
441                         sum += dw->weight;
442
443                         if (lock_flags[dw->def_nr]) {
444                                 lock_weight += dw->weight;
445                         }
446                         else {
447                                 tot++;
448                                 sum_unlock += dw->weight;
449                         }
450                 }
451         }
452
453         if (sum == 1.0f) {
454                 return true;
455         }
456
457         if (tot == 0) {
458                 return false;
459         }
460
461         if (lock_weight >= 1.0f) {
462                 /* locked groups make it impossible to fully normalize,
463                  * zero out what we can and return false */
464                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
465                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
466                                 if (lock_flags[dw->def_nr] == false) {
467                                         dw->weight = 0.0f;
468                                 }
469                         }
470                 }
471
472                 return (lock_weight == 1.0f);
473         }
474         else if (sum_unlock != 0.0f) {
475                 fac = (1.0f - lock_weight) / sum_unlock;
476
477                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
478                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
479                                 if (lock_flags[dw->def_nr] == false) {
480                                         dw->weight *= fac;
481                                         /* paranoid but possibly with float error */
482                                         CLAMP(dw->weight, 0.0f, 1.0f);
483                                 }
484                         }
485                 }
486         }
487         else {
488                 /* hrmf, not a factor in this case */
489                 fac = (1.0f - lock_weight) / tot;
490                 /* paranoid but possibly with float error */
491                 CLAMP(fac, 0.0f, 1.0f);
492
493                 for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
494                         if (dw->def_nr < defbase_tot && vgroup_validmap[dw->def_nr]) {
495                                 if (lock_flags[dw->def_nr] == false) {
496                                         dw->weight = fac;
497                                 }
498                         }
499                 }
500         }
501
502         return true;
503 }
504
505 /**
506  * \note same as function above except it does a second pass without active group
507  * if normalize fails with it.
508  */
509 static void do_weight_paint_normalize_all_locked_try_active(
510         MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap,
511         const bool *lock_flags, const bool *lock_with_active)
512 {
513         /* first pass with both active and explicitly locked groups restricted from change */
514
515         bool success = do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_with_active);
516
517         if (!success) {
518                 /**
519                  * Locks prevented the first pass from full completion, so remove restriction on active group; e.g:
520                  *
521                  * - With 1.0 weight painted into active:
522                  *   nonzero locked weight; first pass zeroed out unlocked weight; scale 1 down to fit.
523                  * - With 0.0 weight painted into active:
524                  *   no unlocked groups; first pass did nothing; increase 0 to fit.
525                  */
526                 do_weight_paint_normalize_all_locked(dvert, defbase_tot, vgroup_validmap, lock_flags);
527         }
528 }
529
530 #if 0 /* UNUSED */
531 static bool has_unselected_unlocked_bone_group(
532         int defbase_tot, bool *defbase_sel, int selected,
533         const bool *lock_flags, const bool *vgroup_validmap)
534 {
535         int i;
536         if (defbase_tot == selected) {
537                 return false;
538         }
539         for (i = 0; i < defbase_tot; i++) {
540                 if (vgroup_validmap[i] && !defbase_sel[i] && !lock_flags[i]) {
541                         return true;
542                 }
543         }
544         return false;
545 }
546 #endif
547
548 static void multipaint_clamp_change(
549         MDeformVert *dvert, const int defbase_tot, const bool *defbase_sel,
550         float *change_p)
551 {
552         int i;
553         MDeformWeight *dw;
554         float val;
555         float change = *change_p;
556
557         /* verify that the change does not cause values exceeding 1 and clamp it */
558         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
559                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
560                         if (dw->weight) {
561                                 val = dw->weight * change;
562                                 if (val > 1) {
563                                         change = 1.0f / dw->weight;
564                                 }
565                         }
566                 }
567         }
568
569         *change_p = change;
570 }
571
572 static bool multipaint_verify_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
573 {
574         int i;
575         MDeformWeight *dw;
576         float val;
577
578         /* in case the change is reduced, you need to recheck
579          * the earlier values to make sure they are not 0
580          * (precision error) */
581         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
582                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
583                         if (dw->weight) {
584                                 val = dw->weight * change;
585                                 /* the value should never reach zero while multi-painting if it
586                                  * was nonzero beforehand */
587                                 if (val <= 0) {
588                                         return false;
589                                 }
590                         }
591                 }
592         }
593
594         return true;
595 }
596
597 static void multipaint_apply_change(MDeformVert *dvert, const int defbase_tot, float change, const bool *defbase_sel)
598 {
599         int i;
600         MDeformWeight *dw;
601
602         /* apply the valid change */
603         for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
604                 if (dw->def_nr < defbase_tot && defbase_sel[dw->def_nr]) {
605                         if (dw->weight) {
606                                 dw->weight = dw->weight * change;
607                                 CLAMP(dw->weight, 0.0f, 1.0f);
608                         }
609                 }
610         }
611 }
612
613 /**
614  * Variables stored both for 'active' and 'mirror' sides.
615  */
616 struct WeightPaintGroupData {
617         /** index of active group or its mirror
618          *
619          * - 'active' is always `ob->actdef`.
620          * - 'mirror' is -1 when 'ME_EDIT_MIRROR_X' flag id disabled,
621          *   otherwise this will be set to the mirror or the active group (if the group isn't mirrored).
622          */
623         int index;
624         /** lock that includes the 'index' as locked too
625          *
626          * - 'active' is set of locked or active/selected groups
627          * - 'mirror' is set of locked or mirror groups
628          */
629         const bool *lock;
630 };
631
632 /* struct to avoid passing many args each call to do_weight_paint_vertex()
633  * this _could_ be made a part of the operators 'WPaintData' struct, or at
634  * least a member, but for now keep its own struct, initialized on every
635  * paint stroke update - campbell */
636 typedef struct WeightPaintInfo {
637
638         int defbase_tot;
639
640         /* both must add up to 'defbase_tot' */
641         int defbase_tot_sel;
642         int defbase_tot_unsel;
643
644         struct WeightPaintGroupData active, mirror;
645
646         /* boolean array for locked bones,
647          * length of defbase_tot */
648         const bool *lock_flags;
649         /* boolean array for selected bones,
650          * length of defbase_tot, cant be const because of how its passed */
651         const bool *defbase_sel;
652         /* same as WeightPaintData.vgroup_validmap,
653          * only added here for convenience */
654         const bool *vgroup_validmap;
655
656         bool do_flip;
657         bool do_multipaint;
658         bool do_auto_normalize;
659
660         float brush_alpha_value;  /* result of BKE_brush_alpha_get() */
661 } WeightPaintInfo;
662
663 static void do_weight_paint_vertex_single(
664         /* vars which remain the same for every vert */
665         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
666         /* vars which change on each stroke */
667         const uint index, float alpha, float paintweight)
668 {
669         Mesh *me = ob->data;
670         MDeformVert *dv = &me->dvert[index];
671         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
672
673         MDeformWeight *dw;
674         float weight_prev;
675
676         /* mirror vars */
677         int index_mirr;
678         int vgroup_mirr;
679
680         MDeformVert *dv_mirr;
681         MDeformWeight *dw_mirr;
682
683         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
684         if (me->editflag & ME_EDIT_MIRROR_X) {
685                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
686                 vgroup_mirr = wpi->mirror.index;
687
688                 /* another possible error - mirror group _and_ active group are the same (which is fine),
689                  * but we also are painting onto a center vertex - this would paint the same weight twice */
690                 if (index_mirr == index && vgroup_mirr == wpi->active.index) {
691                         index_mirr = vgroup_mirr = -1;
692                 }
693         }
694         else {
695                 index_mirr = vgroup_mirr = -1;
696         }
697
698         if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
699                 dw = defvert_find_index(dv, wpi->active.index);
700         }
701         else {
702                 dw = defvert_verify_index(dv, wpi->active.index);
703         }
704
705         if (dw == NULL) {
706                 return;
707         }
708
709         /* get the mirror def vars */
710         if (index_mirr != -1) {
711                 dv_mirr = &me->dvert[index_mirr];
712                 if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
713                         dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
714
715                         if (dw_mirr == NULL) {
716                                 index_mirr = vgroup_mirr = -1;
717                                 dv_mirr = NULL;
718                         }
719                 }
720                 else {
721                         if (index != index_mirr) {
722                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
723                         }
724                         else {
725                                 /* dv and dv_mirr are the same */
726                                 int totweight_prev = dv_mirr->totweight;
727                                 int dw_offset = (int)(dw - dv_mirr->dw);
728                                 dw_mirr = defvert_verify_index(dv_mirr, vgroup_mirr);
729
730                                 /* if we added another, get our old one back */
731                                 if (totweight_prev != dv_mirr->totweight) {
732                                         dw = &dv_mirr->dw[dw_offset];
733                                 }
734                         }
735                 }
736         }
737         else {
738                 dv_mirr = NULL;
739                 dw_mirr = NULL;
740         }
741
742         if (!brush_use_accumulate(wp->paint.brush)) {
743                 MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
744                 MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
745                 if (index_mirr != -1) {
746                         defweight_prev_init(dvert_prev, me->dvert, index_mirr);
747                 }
748
749                 weight_prev = defvert_find_weight(dv_prev, wpi->active.index);
750         }
751         else {
752                 weight_prev = dw->weight;
753         }
754
755         /* If there are no normalize-locks or multipaint,
756          * then there is no need to run the more complicated checks */
757
758         {
759                 float new_weight = wpaint_blend(
760                         wp, weight_prev, alpha, paintweight,
761                         wpi->brush_alpha_value, wpi->do_flip);
762
763                 dw->weight = wpaint_clamp_monotonic(weight_prev, dw->weight, new_weight);
764
765                 /* WATCH IT: take care of the ordering of applying mirror -> normalize,
766                  * can give wrong results [#26193], least confusing if normalize is done last */
767
768                 /* apply mirror */
769                 if (index_mirr != -1) {
770                         /* copy, not paint again */
771                         dw_mirr->weight = dw->weight;
772                 }
773
774                 /* apply normalize */
775                 if (wpi->do_auto_normalize) {
776                         /* note on normalize - this used to be applied after painting and normalize all weights,
777                          * in some ways this is good because there is feedback where the more weights involved would
778                          * 'resist' so you couldn't instantly zero out other weights by painting 1.0 on the active.
779                          *
780                          * However this gave a problem since applying mirror, then normalize both verts
781                          * the resulting weight wont match on both sides.
782                          *
783                          * If this 'resisting', slower normalize is nicer, we could call
784                          * do_weight_paint_normalize_all() and only use...
785                          * do_weight_paint_normalize_all_active() when normalizing the mirror vertex.
786                          * - campbell
787                          */
788                         do_weight_paint_normalize_all_locked_try_active(
789                                 dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
790
791                         if (index_mirr != -1) {
792                                 /* only normalize if this is not a center vertex, else we get a conflict, normalizing twice */
793                                 if (index != index_mirr) {
794                                         do_weight_paint_normalize_all_locked_try_active(
795                                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->mirror.lock);
796                                 }
797                                 else {
798                                         /* this case accounts for...
799                                          * - painting onto a center vertex of a mesh
800                                          * - x mirror is enabled
801                                          * - auto normalize is enabled
802                                          * - the group you are painting onto has a L / R version
803                                          *
804                                          * We want L/R vgroups to have the same weight but this cant be if both are over 0.5,
805                                          * We _could_ have special check for that, but this would need its own normalize function which
806                                          * holds 2 groups from changing at once.
807                                          *
808                                          * So! just balance out the 2 weights, it keeps them equal and everything normalized.
809                                          *
810                                          * While it wont hit the desired weight immediately as the user waggles their mouse,
811                                          * constant painting and re-normalizing will get there. this is also just simpler logic.
812                                          * - campbell */
813                                         dw_mirr->weight = dw->weight = (dw_mirr->weight + dw->weight) * 0.5f;
814                                 }
815                         }
816                 }
817         }
818 }
819
820 static void do_weight_paint_vertex_multi(
821         /* vars which remain the same for every vert */
822         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
823         /* vars which change on each stroke */
824         const uint index, float alpha, float paintweight)
825 {
826         Mesh *me = ob->data;
827         MDeformVert *dv = &me->dvert[index];
828         bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
829
830         /* mirror vars */
831         int index_mirr = -1;
832         MDeformVert *dv_mirr = NULL;
833
834         /* weights */
835         float curw, oldw, neww, change, curw_mirr, change_mirr;
836
837         /* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
838         if (me->editflag & ME_EDIT_MIRROR_X) {
839                 index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
840
841                 if (index_mirr != -1 && index_mirr != index) {
842                         dv_mirr = &me->dvert[index_mirr];
843                 }
844                 else {
845                         index_mirr = -1;
846                 }
847         }
848
849         /* compute weight change by applying the brush to average or sum of group weights */
850         curw = BKE_defvert_multipaint_collective_weight(
851                 dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
852
853         if (curw == 0.0f) {
854                 /* note: no weight to assign to this vertex, could add all groups? */
855                 return;
856         }
857
858         if (!brush_use_accumulate(wp->paint.brush)) {
859                 MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
860                 MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
861                 if (index_mirr != -1) {
862                         defweight_prev_init(dvert_prev, me->dvert, index_mirr);
863                 }
864
865                 oldw = BKE_defvert_multipaint_collective_weight(
866                         dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
867         }
868         else {
869                 oldw = curw;
870         }
871
872         neww = wpaint_blend(wp, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
873         neww = wpaint_clamp_monotonic(oldw, curw, neww);
874
875         change = neww / curw;
876
877         /* verify for all groups that 0 < result <= 1 */
878         multipaint_clamp_change(dv, wpi->defbase_tot, wpi->defbase_sel, &change);
879
880         if (dv_mirr != NULL) {
881                 curw_mirr = BKE_defvert_multipaint_collective_weight(
882                         dv_mirr, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
883
884                 if (curw_mirr == 0.0f) {
885                         /* can't mirror into a zero weight vertex */
886                         dv_mirr = NULL;
887                 }
888                 else {
889                         /* mirror is changed to achieve the same collective weight value */
890                         float orig = change_mirr = curw * change / curw_mirr;
891
892                         multipaint_clamp_change(dv_mirr, wpi->defbase_tot, wpi->defbase_sel, &change_mirr);
893
894                         if (!multipaint_verify_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel)) {
895                                 return;
896                         }
897
898                         change *= change_mirr / orig;
899                 }
900         }
901
902         if (!multipaint_verify_change(dv, wpi->defbase_tot, change, wpi->defbase_sel)) {
903                 return;
904         }
905
906         /* apply validated change to vertex and mirror */
907         multipaint_apply_change(dv, wpi->defbase_tot, change, wpi->defbase_sel);
908
909         if (dv_mirr != NULL) {
910                 multipaint_apply_change(dv_mirr, wpi->defbase_tot, change_mirr, wpi->defbase_sel);
911         }
912
913         /* normalize */
914         if (wpi->do_auto_normalize) {
915                 do_weight_paint_normalize_all_locked_try_active(
916                         dv, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
917
918                 if (dv_mirr != NULL) {
919                         do_weight_paint_normalize_all_locked_try_active(
920                                 dv_mirr, wpi->defbase_tot, wpi->vgroup_validmap, wpi->lock_flags, wpi->active.lock);
921                 }
922         }
923 }
924
925 static void do_weight_paint_vertex(
926         /* vars which remain the same for every vert */
927         const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
928         /* vars which change on each stroke */
929         const uint index, float alpha, float paintweight)
930 {
931         if (wpi->do_multipaint) {
932                 do_weight_paint_vertex_multi(wp, ob, wpi, index, alpha, paintweight);
933         }
934         else {
935                 do_weight_paint_vertex_single(wp, ob, wpi, index, alpha, paintweight);
936         }
937 }
938
939
940 /* Toggle operator for turning vertex paint mode on or off (copied from sculpt.c) */
941 static void vertex_paint_init_session(Scene *scene, Object *ob, eObjectMode object_mode)
942 {
943         /* Create persistent sculpt mode data */
944         BKE_sculpt_toolsettings_data_ensure(scene);
945
946         BLI_assert(ob->sculpt == NULL);
947         ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
948         ob->sculpt->mode_type = object_mode;
949         BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
950 }
951
952 static void vertex_paint_init_stroke(Scene *scene, Object *ob)
953 {
954         BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
955 }
956
957 static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob)
958 {
959         /* Create maps */
960         struct SculptVertexPaintGeomMap *gmap = NULL;
961         const Brush *brush = NULL;
962         if (ob->mode == OB_MODE_VERTEX_PAINT) {
963                 gmap = &ob->sculpt->mode.vpaint.gmap;
964                 brush = BKE_paint_brush(&ts->vpaint->paint);
965                 BLI_assert(ob->sculpt->mode_type == OB_MODE_VERTEX_PAINT);
966         }
967         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
968                 gmap = &ob->sculpt->mode.wpaint.gmap;
969                 brush = BKE_paint_brush(&ts->wpaint->paint);
970                 BLI_assert(ob->sculpt->mode_type == OB_MODE_WEIGHT_PAINT);
971         }
972         else {
973                 ob->sculpt->mode_type = 0;
974                 BLI_assert(0);
975                 return;
976         }
977
978         Mesh *me = ob->data;
979
980         if (gmap->vert_to_loop == NULL) {
981                 gmap->vert_map_mem = NULL;
982                 gmap->vert_to_loop = NULL;
983                 gmap->poly_map_mem = NULL;
984                 gmap->vert_to_poly = NULL;
985                 BKE_mesh_vert_loop_map_create(
986                         &gmap->vert_to_loop,
987                         &gmap->vert_map_mem,
988                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
989                 BKE_mesh_vert_poly_map_create(
990                         &gmap->vert_to_poly,
991                         &gmap->poly_map_mem,
992                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
993         }
994
995         /* Create average brush arrays */
996         if (ob->mode == OB_MODE_VERTEX_PAINT) {
997                 if (!brush_use_accumulate(brush)) {
998                         if (ob->sculpt->mode.vpaint.previous_color == NULL) {
999                                 ob->sculpt->mode.vpaint.previous_color =
1000                                         MEM_callocN(me->totloop * sizeof(uint), __func__);
1001                         }
1002                 }
1003                 else {
1004                         MEM_SAFE_FREE(ob->sculpt->mode.vpaint.previous_color);
1005                 }
1006         }
1007         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
1008                 if (!brush_use_accumulate(brush)) {
1009                         if (ob->sculpt->mode.wpaint.alpha_weight == NULL) {
1010                                 ob->sculpt->mode.wpaint.alpha_weight =
1011                                         MEM_callocN(me->totvert * sizeof(float), __func__);
1012                         }
1013                         if (ob->sculpt->mode.wpaint.dvert_prev == NULL) {
1014                                 ob->sculpt->mode.wpaint.dvert_prev =
1015                                         MEM_callocN(me->totvert * sizeof(MDeformVert), __func__);
1016                                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1017                                 for (int i = 0; i < me->totvert; i++, dv++) {
1018                                         /* Use to show this isn't initialized, never apply to the mesh data. */
1019                                         dv->flag = 1;
1020                                 }
1021                         }
1022                 }
1023                 else {
1024                         MEM_SAFE_FREE(ob->sculpt->mode.wpaint.alpha_weight);
1025                         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1026                                 BKE_defvert_array_free_elems(ob->sculpt->mode.wpaint.dvert_prev, me->totvert);
1027                                 MEM_freeN(ob->sculpt->mode.wpaint.dvert_prev);
1028                                 ob->sculpt->mode.wpaint.dvert_prev = NULL;
1029                         }
1030                 }
1031         }
1032
1033 }
1034
1035 /* -------------------------------------------------------------------- */
1036 /** \name Enter Vertex/Weight Paint Mode
1037  * \{ */
1038
1039 static void ed_vwpaintmode_enter_generic(
1040         Main *bmain,
1041         wmWindowManager *wm,
1042         Scene *scene,
1043         Object *ob, const eObjectMode mode_flag)
1044 {
1045         ob->mode |= mode_flag;
1046         Mesh *me = BKE_mesh_from_object(ob);
1047
1048         if (mode_flag == OB_MODE_VERTEX_PAINT) {
1049                 const ePaintMode paint_mode = ePaintVertex;
1050                 ED_mesh_color_ensure(me, NULL);
1051
1052                 if (scene->toolsettings->vpaint == NULL) {
1053                         scene->toolsettings->vpaint = new_vpaint();
1054                 }
1055
1056                 Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
1057                 paint_cursor_start_explicit(paint, wm, vertex_paint_poll);
1058                 BKE_paint_init(bmain, scene, paint_mode, PAINT_CURSOR_VERTEX_PAINT);
1059         }
1060         else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1061                 const  ePaintMode paint_mode = ePaintWeight;
1062
1063                 if (scene->toolsettings->wpaint == NULL) {
1064                         scene->toolsettings->wpaint = new_vpaint();
1065                 }
1066
1067                 Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
1068                 paint_cursor_start_explicit(paint, wm, weight_paint_poll);
1069                 BKE_paint_init(bmain, scene, paint_mode, PAINT_CURSOR_WEIGHT_PAINT);
1070
1071                 /* weight paint specific */
1072                 ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
1073                 ED_vgroup_sync_from_pose(ob);
1074         }
1075         else {
1076                 BLI_assert(0);
1077         }
1078
1079         /* Create vertex/weight paint mode session data */
1080         if (ob->sculpt) {
1081                 if (ob->sculpt->cache) {
1082                         sculpt_cache_free(ob->sculpt->cache);
1083                         ob->sculpt->cache = NULL;
1084                 }
1085                 BKE_sculptsession_free(ob);
1086         }
1087
1088         vertex_paint_init_session(scene, ob, mode_flag);
1089 }
1090
1091 void ED_object_vpaintmode_enter_ex(
1092         Main *bmain, wmWindowManager *wm,
1093         Scene *scene, Object *ob)
1094 {
1095         ed_vwpaintmode_enter_generic(
1096                 bmain, wm, scene, ob, OB_MODE_VERTEX_PAINT);
1097 }
1098 void ED_object_vpaintmode_enter(struct bContext *C)
1099 {
1100         Main *bmain = CTX_data_main(C);
1101         wmWindowManager *wm = CTX_wm_manager(C);
1102         Scene *scene = CTX_data_scene(C);
1103         Object *ob = CTX_data_active_object(C);
1104         ED_object_vpaintmode_enter_ex(bmain, wm, scene, ob);
1105 }
1106
1107 void ED_object_wpaintmode_enter_ex(
1108         Main *bmain, wmWindowManager *wm,
1109         Scene *scene, Object *ob)
1110 {
1111         ed_vwpaintmode_enter_generic(
1112                 bmain, wm, scene, ob, OB_MODE_WEIGHT_PAINT);
1113 }
1114 void ED_object_wpaintmode_enter(struct bContext *C)
1115 {
1116         Main *bmain = CTX_data_main(C);
1117         wmWindowManager *wm = CTX_wm_manager(C);
1118         Scene *scene = CTX_data_scene(C);
1119         Object *ob = CTX_data_active_object(C);
1120         ED_object_wpaintmode_enter_ex(bmain, wm, scene, ob);
1121 }
1122
1123 /** \} */
1124
1125 /* -------------------------------------------------------------------- */
1126 /** \name Exit Vertex/Weight Paint Mode
1127  * \{ */
1128
1129 static void ed_vwpaintmode_exit_generic(
1130         Object *ob, const eObjectMode mode_flag)
1131 {
1132         Mesh *me = BKE_mesh_from_object(ob);
1133         ob->mode &= ~mode_flag;
1134
1135         if (mode_flag == OB_MODE_VERTEX_PAINT) {
1136                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1137                         BKE_mesh_flush_select_from_polys(me);
1138                 }
1139                 else if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1140                         BKE_mesh_flush_select_from_verts(me);
1141                 }
1142         }
1143         else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1144                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1145                         BKE_mesh_flush_select_from_verts(me);
1146                 }
1147                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1148                         BKE_mesh_flush_select_from_polys(me);
1149                 }
1150         }
1151         else {
1152                 BLI_assert(0);
1153         }
1154
1155         /* If the cache is not released by a cancel or a done, free it now. */
1156         if (ob->sculpt && ob->sculpt->cache) {
1157                 sculpt_cache_free(ob->sculpt->cache);
1158                 ob->sculpt->cache = NULL;
1159         }
1160
1161         BKE_sculptsession_free(ob);
1162
1163         paint_cursor_delete_textures();
1164
1165         if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1166                 ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
1167                 ED_mesh_mirror_topo_table(NULL, NULL, 'e');
1168         }
1169 }
1170
1171 void ED_object_vpaintmode_exit_ex(Object *ob)
1172 {
1173         ed_vwpaintmode_exit_generic(ob, OB_MODE_VERTEX_PAINT);
1174 }
1175 void ED_object_vpaintmode_exit(struct bContext *C)
1176 {
1177         Object *ob = CTX_data_active_object(C);
1178         ED_object_vpaintmode_exit_ex(ob);
1179 }
1180
1181 void ED_object_wpaintmode_exit_ex(Object *ob)
1182 {
1183         ed_vwpaintmode_exit_generic(ob, OB_MODE_WEIGHT_PAINT);
1184 }
1185 void ED_object_wpaintmode_exit(struct bContext *C)
1186 {
1187         Object *ob = CTX_data_active_object(C);
1188         ED_object_wpaintmode_exit_ex(ob);
1189 }
1190
1191 /** \} */
1192
1193 /* *************** set wpaint operator ****************** */
1194
1195 /**
1196  * \note Keep in sync with #vpaint_mode_toggle_exec
1197  */
1198 static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
1199 {
1200         Main *bmain = CTX_data_main(C);
1201         Object *ob = CTX_data_active_object(C);
1202         const int mode_flag = OB_MODE_WEIGHT_PAINT;
1203         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1204         Scene *scene = CTX_data_scene(C);
1205
1206         if (!is_mode_set) {
1207                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1208                         return OPERATOR_CANCELLED;
1209                 }
1210         }
1211
1212         Mesh *me = BKE_mesh_from_object(ob);
1213
1214         if (is_mode_set) {
1215                 ED_object_wpaintmode_exit_ex(ob);
1216         }
1217         else {
1218                 wmWindowManager *wm = CTX_wm_manager(C);
1219                 ED_object_wpaintmode_enter_ex(bmain, wm, scene, ob);
1220         }
1221
1222         /* Weightpaint works by overriding colors in mesh,
1223          * so need to make sure we recalc on enter and
1224          * exit (exit needs doing regardless because we
1225          * should redeform).
1226          */
1227         DAG_id_tag_update(&me->id, 0);
1228
1229         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1230
1231         return OPERATOR_FINISHED;
1232 }
1233
1234 /* for switching to/from mode */
1235 static bool paint_poll_test(bContext *C)
1236 {
1237         Object *ob = CTX_data_active_object(C);
1238         if (ob == NULL || ob->type != OB_MESH)
1239                 return 0;
1240         if (!ob->data || ID_IS_LINKED(ob->data))
1241                 return 0;
1242         if (CTX_data_edit_object(C))
1243                 return 0;
1244         return 1;
1245 }
1246
1247 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1248 {
1249
1250         /* identifiers */
1251         ot->name = "Weight Paint Mode";
1252         ot->idname = "PAINT_OT_weight_paint_toggle";
1253         ot->description = "Toggle weight paint mode in 3D view";
1254
1255         /* api callbacks */
1256         ot->exec = wpaint_mode_toggle_exec;
1257         ot->poll = paint_poll_test;
1258
1259         /* flags */
1260         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1261 }
1262
1263 /* ************ weight paint operator ********** */
1264
1265 struct WPaintData {
1266         ViewContext vc;
1267         struct NormalAnglePrecalc normal_angle_precalc;
1268
1269         struct WeightPaintGroupData active, mirror;
1270
1271         /* variables for auto normalize */
1272         const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
1273         const bool *lock_flags;
1274
1275         /* variables for multipaint */
1276         const bool *defbase_sel;      /* set of selected groups */
1277         int defbase_tot_sel;          /* number of selected groups */
1278         bool do_multipaint;           /* true if multipaint enabled and multiple groups selected */
1279
1280         int defbase_tot;
1281
1282         /* original weight values for use in blur/smear */
1283         float *precomputed_weight;
1284         bool precomputed_weight_ready;
1285 };
1286
1287 /* Initialize the stroke cache invariants from operator properties */
1288 static void vwpaint_update_cache_invariants(
1289         bContext *C, const VPaint *vp, SculptSession *ss, wmOperator *op, const float mouse[2])
1290 {
1291         StrokeCache *cache;
1292         Scene *scene = CTX_data_scene(C);
1293         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1294         const Brush *brush = vp->paint.brush;
1295         ViewContext *vc = paint_stroke_view_context(op->customdata);
1296         Object *ob = CTX_data_active_object(C);
1297         float mat[3][3];
1298         float view_dir[3] = {0.0f, 0.0f, 1.0f};
1299         int mode;
1300
1301         /* VW paint needs to allocate stroke cache before update is called. */
1302         if (!ss->cache) {
1303                 cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
1304                 ss->cache = cache;
1305         }
1306         else {
1307                 cache = ss->cache;
1308         }
1309
1310         /* Initial mouse location */
1311         if (mouse)
1312                 copy_v2_v2(cache->initial_mouse, mouse);
1313         else
1314                 zero_v2(cache->initial_mouse);
1315
1316         mode = RNA_enum_get(op->ptr, "mode");
1317         cache->invert = mode == BRUSH_STROKE_INVERT;
1318         cache->alt_smooth = mode == BRUSH_STROKE_SMOOTH;
1319         /* not very nice, but with current events system implementation
1320          * we can't handle brush appearance inversion hotkey separately (sergey) */
1321         if (cache->invert) ups->draw_inverted = true;
1322         else ups->draw_inverted = false;
1323
1324         copy_v2_v2(cache->mouse, cache->initial_mouse);
1325         /* Truly temporary data that isn't stored in properties */
1326         cache->vc = vc;
1327         cache->brush = brush;
1328         cache->first_time = 1;
1329
1330         /* cache projection matrix */
1331         ED_view3d_ob_project_mat_get(cache->vc->rv3d, ob, cache->projection_mat);
1332
1333         invert_m4_m4(ob->imat, ob->obmat);
1334         copy_m3_m4(mat, cache->vc->rv3d->viewinv);
1335         mul_m3_v3(mat, view_dir);
1336         copy_m3_m4(mat, ob->imat);
1337         mul_m3_v3(mat, view_dir);
1338         normalize_v3_v3(cache->true_view_normal, view_dir);
1339
1340         copy_v3_v3(cache->view_normal, cache->true_view_normal);
1341         cache->bstrength = BKE_brush_alpha_get(scene, brush);
1342         cache->is_last_valid = false;
1343 }
1344
1345 /* Initialize the stroke cache variants from operator properties */
1346 static void vwpaint_update_cache_variants(bContext *C, VPaint *vp, Object *ob, PointerRNA *ptr)
1347 {
1348         Scene *scene = CTX_data_scene(C);
1349         SculptSession *ss = ob->sculpt;
1350         StrokeCache *cache = ss->cache;
1351         Brush *brush = BKE_paint_brush(&vp->paint);
1352
1353         /* This effects the actual brush radius, so things farther away
1354          * are compared with a larger radius and vice versa. */
1355         if (cache->first_time) {
1356                 RNA_float_get_array(ptr, "location", cache->true_location);
1357         }
1358
1359         RNA_float_get_array(ptr, "mouse", cache->mouse);
1360
1361         /* XXX: Use pressure value from first brush step for brushes which don't
1362          * support strokes (grab, thumb). They depends on initial state and
1363          * brush coord/pressure/etc.
1364          * It's more an events design issue, which doesn't split coordinate/pressure/angle
1365          * changing events. We should avoid this after events system re-design */
1366         if (paint_supports_dynamic_size(brush, ePaintSculpt) || cache->first_time) {
1367                 cache->pressure = RNA_float_get(ptr, "pressure");
1368         }
1369
1370         /* Truly temporary data that isn't stored in properties */
1371         if (cache->first_time) {
1372                 if (!BKE_brush_use_locked_size(scene, brush)) {
1373                         cache->initial_radius = paint_calc_object_space_radius(
1374                                 cache->vc, cache->true_location, BKE_brush_size_get(scene, brush));
1375                         BKE_brush_unprojected_radius_set(scene, brush, cache->initial_radius);
1376                 }
1377                 else {
1378                         cache->initial_radius = BKE_brush_unprojected_radius_get(scene, brush);
1379                 }
1380         }
1381
1382         if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, ePaintSculpt)) {
1383                 cache->radius = cache->initial_radius * cache->pressure;
1384         }
1385         else {
1386                 cache->radius = cache->initial_radius;
1387         }
1388
1389         cache->radius_squared = cache->radius * cache->radius;
1390
1391         if (ss->pbvh) {
1392                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateRedraw, NULL);
1393                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB, NULL);
1394         }
1395 }
1396
1397 static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
1398 {
1399         Scene *scene = CTX_data_scene(C);
1400         struct PaintStroke *stroke = op->customdata;
1401         ToolSettings *ts = scene->toolsettings;
1402         Object *ob = CTX_data_active_object(C);
1403         Mesh *me = BKE_mesh_from_object(ob);
1404         struct WPaintData *wpd;
1405         struct WPaintVGroupIndex vgroup_index;
1406         int defbase_tot, defbase_tot_sel;
1407         bool *defbase_sel;
1408         SculptSession *ss = ob->sculpt;
1409         VPaint *vp = CTX_data_tool_settings(C)->wpaint;
1410
1411         if (ED_wpaint_ensure_data(C, op->reports, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
1412                 return false;
1413         }
1414
1415         {
1416                 /* check if we are attempting to paint onto a locked vertex group,
1417                  * and other options disallow it from doing anything useful */
1418                 bDeformGroup *dg;
1419                 dg = BLI_findlink(&ob->defbase, vgroup_index.active);
1420                 if (dg->flag & DG_LOCK_WEIGHT) {
1421                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
1422                         return false;
1423                 }
1424                 if (vgroup_index.mirror != -1) {
1425                         dg = BLI_findlink(&ob->defbase, vgroup_index.mirror);
1426                         if (dg->flag & DG_LOCK_WEIGHT) {
1427                                 BKE_report(op->reports, RPT_WARNING, "Mirror group is locked, aborting");
1428                                 return false;
1429                         }
1430                 }
1431         }
1432
1433         /* check that multipaint groups are unlocked */
1434         defbase_tot = BLI_listbase_count(&ob->defbase);
1435         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_tot_sel);
1436
1437         if (ts->multipaint && defbase_tot_sel > 1) {
1438                 int i;
1439                 bDeformGroup *dg;
1440
1441                 if (me->editflag & ME_EDIT_MIRROR_X) {
1442                         BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1443                 }
1444
1445                 for (i = 0; i < defbase_tot; i++) {
1446                         if (defbase_sel[i]) {
1447                                 dg = BLI_findlink(&ob->defbase, i);
1448                                 if (dg->flag & DG_LOCK_WEIGHT) {
1449                                         BKE_report(op->reports, RPT_WARNING, "Multipaint group is locked, aborting");
1450                                         MEM_freeN(defbase_sel);
1451                                         return false;
1452                                 }
1453                         }
1454                 }
1455         }
1456
1457         /* ALLOCATIONS! no return after this line */
1458         /* make mode data storage */
1459         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1460         paint_stroke_set_mode_data(stroke, wpd);
1461         ED_view3d_viewcontext_init(C, &wpd->vc);
1462         view_angle_limits_init(
1463                 &wpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
1464                 (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
1465
1466         wpd->active.index = vgroup_index.active;
1467         wpd->mirror.index = vgroup_index.mirror;
1468
1469         /* multipaint */
1470         wpd->defbase_tot = defbase_tot;
1471         wpd->defbase_sel = defbase_sel;
1472         wpd->defbase_tot_sel = defbase_tot_sel > 1 ? defbase_tot_sel : 1;
1473         wpd->do_multipaint = (ts->multipaint && defbase_tot_sel > 1);
1474
1475         /* set up auto-normalize, and generate map for detecting which
1476          * vgroups affect deform bones */
1477         wpd->lock_flags = BKE_object_defgroup_lock_flags_get(ob, wpd->defbase_tot);
1478         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
1479                 wpd->vgroup_validmap = BKE_object_defgroup_validmap_get(ob, wpd->defbase_tot);
1480         }
1481
1482         if (wpd->do_multipaint && ts->auto_normalize) {
1483                 bool *tmpflags;
1484                 tmpflags = MEM_mallocN(sizeof(bool) * defbase_tot, __func__);
1485                 if (wpd->lock_flags) {
1486                         BLI_array_binary_or(tmpflags, wpd->defbase_sel, wpd->lock_flags, wpd->defbase_tot);
1487                 }
1488                 else {
1489                         memcpy(tmpflags, wpd->defbase_sel, sizeof(*tmpflags) * wpd->defbase_tot);
1490                 }
1491                 wpd->active.lock = tmpflags;
1492         }
1493         else if (ts->auto_normalize) {
1494                 bool *tmpflags;
1495
1496                 tmpflags = wpd->lock_flags ?
1497                         MEM_dupallocN(wpd->lock_flags) :
1498                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1499                 tmpflags[wpd->active.index] = true;
1500                 wpd->active.lock = tmpflags;
1501
1502                 tmpflags = wpd->lock_flags ?
1503                         MEM_dupallocN(wpd->lock_flags) :
1504                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1505                 tmpflags[(wpd->mirror.index != -1) ? wpd->mirror.index : wpd->active.index] = true;
1506                 wpd->mirror.lock = tmpflags;
1507         }
1508
1509         if (ELEM(vp->paint.brush->vertexpaint_tool, PAINT_BLEND_SMEAR, PAINT_BLEND_BLUR)) {
1510                 wpd->precomputed_weight = MEM_mallocN(sizeof(float) * me->totvert, __func__);
1511         }
1512
1513         /* If not previously created, create vertex/weight paint mode session data */
1514         vertex_paint_init_stroke(scene, ob);
1515         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
1516         vertex_paint_init_session_data(ts, ob);
1517
1518         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1519                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1520                 for (int i = 0; i < me->totvert; i++, dv++) {
1521                         /* Use to show this isn't initialized, never apply to the mesh data. */
1522                         dv->flag = 1;
1523                 }
1524         }
1525
1526         return true;
1527 }
1528
1529 static float dot_vf3vs3(const float brushNormal[3], const short vertexNormal[3])
1530 {
1531         float normal[3];
1532         normal_short_to_float_v3(normal, vertexNormal);
1533         return dot_v3v3(brushNormal, normal);
1534 }
1535
1536 static void get_brush_alpha_data(
1537         const Scene *scene, const SculptSession *ss, const Brush *brush,
1538         float *r_brush_size_pressure, float *r_brush_alpha_value, float *r_brush_alpha_pressure)
1539 {
1540         *r_brush_size_pressure =
1541                 BKE_brush_size_get(scene, brush) *
1542                 (BKE_brush_use_size_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1543         *r_brush_alpha_value =
1544                 BKE_brush_alpha_get(scene, brush);
1545         *r_brush_alpha_pressure =
1546                 (BKE_brush_use_alpha_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1547 }
1548
1549 static float wpaint_get_active_weight(const MDeformVert *dv, const WeightPaintInfo *wpi)
1550 {
1551         if (wpi->do_multipaint) {
1552                 float weight = BKE_defvert_multipaint_collective_weight(
1553                      dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1554
1555                 CLAMP(weight, 0.0f, 1.0f);
1556                 return weight;
1557         }
1558         else {
1559                 return defvert_find_weight(dv, wpi->active.index);
1560         }
1561 }
1562
1563 static void do_wpaint_precompute_weight_cb_ex(
1564         void *__restrict userdata,
1565         const int n,
1566         const ParallelRangeTLS *__restrict UNUSED(tls))
1567 {
1568         SculptThreadedTaskData *data = userdata;
1569         const MDeformVert *dv = &data->me->dvert[n];
1570
1571         data->wpd->precomputed_weight[n] = wpaint_get_active_weight(dv, data->wpi);
1572 }
1573
1574 static void precompute_weight_values(
1575         bContext *C, Object *ob, Brush *brush, struct WPaintData *wpd, WeightPaintInfo *wpi, Mesh *me)
1576 {
1577         if (wpd->precomputed_weight_ready && !brush_use_accumulate(brush))
1578                 return;
1579
1580         /* threaded loop over vertices */
1581         SculptThreadedTaskData data = {
1582                 .C = C, .ob = ob, .wpd = wpd, .wpi = wpi, .me = me,
1583         };
1584
1585         ParallelRangeSettings settings;
1586         BLI_parallel_range_settings_defaults(&settings);
1587         BLI_task_parallel_range(
1588                 0, me->totvert,
1589                 &data,
1590                 do_wpaint_precompute_weight_cb_ex,
1591                 &settings);
1592
1593         wpd->precomputed_weight_ready = true;
1594 }
1595
1596 static void do_wpaint_brush_blur_task_cb_ex(
1597         void *__restrict userdata,
1598         const int n,
1599         const ParallelRangeTLS *__restrict UNUSED(tls))
1600 {
1601         SculptThreadedTaskData *data = userdata;
1602         SculptSession *ss = data->ob->sculpt;
1603         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
1604         const bool has_grids = (pbvh_type == PBVH_GRIDS);
1605         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1606
1607         const Brush *brush = data->brush;
1608         const StrokeCache *cache = ss->cache;
1609         Scene *scene = CTX_data_scene(data->C);
1610
1611         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1612         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1613         const bool use_normal = vwpaint_use_normal(data->vp);
1614         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1615         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1616
1617         SculptBrushTest test;
1618         SculptBrushTestFn sculpt_brush_test_sq_fn =
1619                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1620         const float *sculpt_normal_frontface =
1621                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1622
1623         /* For each vertex */
1624         PBVHVertexIter vd;
1625         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1626         {
1627                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1628                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1629                         /* For grid based pbvh, take the vert whose loop coopresponds to the current grid.
1630                          * Otherwise, take the current vert. */
1631                         const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1632                         const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
1633                         const char v_flag = data->me->mvert[v_index].flag;
1634                         /* If the vertex is selected */
1635                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1636                                 /* Get the average poly weight */
1637                                 int total_hit_loops = 0;
1638                                 float weight_final = 0.0f;
1639                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1640                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1641                                         const MPoly *mp = &data->me->mpoly[p_index];
1642
1643                                         total_hit_loops += mp->totloop;
1644                                         for (int k = 0; k < mp->totloop; k++) {
1645                                                 const int l_index = mp->loopstart + k;
1646                                                 const MLoop *ml = &data->me->mloop[l_index];
1647                                                 weight_final += data->wpd->precomputed_weight[ml->v];
1648                                         }
1649                                 }
1650
1651                                 /* Apply the weight to the vertex. */
1652                                 if (total_hit_loops != 0) {
1653                                         float brush_strength = cache->bstrength;
1654                                         const float angle_cos = (use_normal && vd.no) ?
1655                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1656                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1657                                              (angle_cos > 0.0f)) &&
1658                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1659                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1660                                         {
1661                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1662                                                 const float final_alpha =
1663                                                         brush_fade * brush_strength *
1664                                                         grid_alpha * brush_alpha_pressure;
1665
1666                                                 if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1667                                                         if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1668                                                                 ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1669                                                         }
1670                                                         else {
1671                                                                 continue;
1672                                                         }
1673                                                 }
1674
1675                                                 weight_final /= total_hit_loops;
1676                                                 /* Only paint visible verts */
1677                                                 do_weight_paint_vertex(
1678                                                         data->vp, data->ob, data->wpi,
1679                                                         v_index, final_alpha, weight_final);
1680                                         }
1681                                 }
1682                         }
1683                 }
1684         }
1685         BKE_pbvh_vertex_iter_end;
1686 }
1687
1688 static void do_wpaint_brush_smear_task_cb_ex(
1689         void *__restrict userdata,
1690         const int n,
1691         const ParallelRangeTLS *__restrict UNUSED(tls))
1692 {
1693         SculptThreadedTaskData *data = userdata;
1694         SculptSession *ss = data->ob->sculpt;
1695         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
1696         const bool has_grids = (pbvh_type == PBVH_GRIDS);
1697         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1698
1699         const Brush *brush = data->brush;
1700         const Scene *scene = CTX_data_scene(data->C);
1701         const StrokeCache *cache = ss->cache;
1702         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1703         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1704         const bool use_normal = vwpaint_use_normal(data->vp);
1705         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1706         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1707         float brush_dir[3];
1708
1709         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
1710         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
1711
1712         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
1713
1714                 SculptBrushTest test;
1715                 SculptBrushTestFn sculpt_brush_test_sq_fn =
1716                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1717                 const float *sculpt_normal_frontface =
1718                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1719
1720                 /* For each vertex */
1721                 PBVHVertexIter vd;
1722                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1723                 {
1724                         /* Test to see if the vertex coordinates are within the spherical brush region. */
1725                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1726                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
1727                                  * Otherwise, take the current vert. */
1728                                 const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1729                                 const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
1730                                 const MVert *mv_curr = &data->me->mvert[v_index];
1731
1732                                 /* If the vertex is selected */
1733                                 if (!(use_face_sel || use_vert_sel) || mv_curr->flag & SELECT) {
1734                                         float brush_strength = cache->bstrength;
1735                                         const float angle_cos = (use_normal && vd.no) ?
1736                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1737                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1738                                              (angle_cos > 0.0f)) &&
1739                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1740                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1741                                         {
1742                                                 bool do_color = false;
1743                                                 /* Minimum dot product between brush direction and current
1744                                                  * to neighbor direction is 0.0, meaning orthogonal. */
1745                                                 float stroke_dot_max = 0.0f;
1746
1747                                                 /* Get the color of the loop in the opposite direction of the brush movement
1748                                                  * (this callback is specifically for smear.) */
1749                                                 float weight_final = 0.0;
1750                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1751                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1752                                                         const MPoly *mp = &data->me->mpoly[p_index];
1753                                                         const MLoop *ml_other = &data->me->mloop[mp->loopstart];
1754                                                         for (int k = 0; k < mp->totloop; k++, ml_other++) {
1755                                                                 const uint v_other_index = ml_other->v;
1756                                                                 if (v_other_index != v_index) {
1757                                                                         const MVert *mv_other = &data->me->mvert[v_other_index];
1758
1759                                                                         /* Get the direction from the selected vert to the neighbor. */
1760                                                                         float other_dir[3];
1761                                                                         sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
1762                                                                         project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
1763
1764                                                                         normalize_v3(other_dir);
1765
1766                                                                         const float stroke_dot = dot_v3v3(other_dir, brush_dir);
1767
1768                                                                         if (stroke_dot > stroke_dot_max) {
1769                                                                                 stroke_dot_max = stroke_dot;
1770                                                                                 weight_final = data->wpd->precomputed_weight[v_other_index];
1771                                                                                 do_color = true;
1772                                                                         }
1773                                                                 }
1774                                                         }
1775                                                 }
1776                                                 /* Apply weight to vertex */
1777                                                 if (do_color) {
1778                                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1779                                                         const float final_alpha =
1780                                                                 brush_fade * brush_strength *
1781                                                                 grid_alpha * brush_alpha_pressure;
1782
1783                                                         if (final_alpha <= 0.0f)
1784                                                                 continue;
1785
1786                                                         do_weight_paint_vertex(
1787                                                                 data->vp, data->ob, data->wpi,
1788                                                                 v_index, final_alpha, (float)weight_final);
1789                                                 }
1790                                         }
1791                                 }
1792                         }
1793                 }
1794                 BKE_pbvh_vertex_iter_end;
1795         }
1796 }
1797
1798 static void do_wpaint_brush_draw_task_cb_ex(
1799         void *__restrict userdata,
1800         const int n,
1801         const ParallelRangeTLS *__restrict UNUSED(tls))
1802 {
1803         SculptThreadedTaskData *data = userdata;
1804         SculptSession *ss = data->ob->sculpt;
1805         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
1806         const bool has_grids = (pbvh_type == PBVH_GRIDS);
1807         const Scene *scene = CTX_data_scene(data->C);
1808
1809         const Brush *brush = data->brush;
1810         const StrokeCache *cache = ss->cache;
1811         /* note: normally `BKE_brush_weight_get(scene, brush)` is used,
1812          * however in this case we calculate a new weight each time. */
1813         const float paintweight = data->strength;
1814         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1815         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1816         const bool use_normal = vwpaint_use_normal(data->vp);
1817         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1818         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1819
1820         SculptBrushTest test;
1821         SculptBrushTestFn sculpt_brush_test_sq_fn =
1822                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1823         const float *sculpt_normal_frontface =
1824                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1825
1826         /* For each vertex */
1827         PBVHVertexIter vd;
1828         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1829         {
1830                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1831                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1832                         /* Note: grids are 1:1 with corners (aka loops).
1833                          * For multires, take the vert whose loop cooresponds to the current grid.
1834                          * Otherwise, take the current vert. */
1835                         const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1836                         const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
1837
1838                         const char v_flag = data->me->mvert[v_index].flag;
1839                         /* If the vertex is selected */
1840                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1841                                 float brush_strength = cache->bstrength;
1842                                 const float angle_cos = (use_normal && vd.no) ?
1843                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1844                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1845                                      (angle_cos > 0.0f)) &&
1846                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1847                                      view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1848                                 {
1849                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1850                                         const float final_alpha = brush_fade * brush_strength * grid_alpha * brush_alpha_pressure;
1851
1852                                         if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1853                                                 if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1854                                                         ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1855                                                 }
1856                                                 else {
1857                                                         continue;
1858                                                 }
1859                                         }
1860
1861                                         do_weight_paint_vertex(
1862                                                 data->vp, data->ob, data->wpi,
1863                                                 v_index, final_alpha, paintweight);
1864                                 }
1865                         }
1866                 }
1867         }
1868         BKE_pbvh_vertex_iter_end;
1869 }
1870
1871 static void do_wpaint_brush_calc_average_weight_cb_ex(
1872         void *__restrict userdata,
1873         const int n,
1874         const ParallelRangeTLS *__restrict UNUSED(tls))
1875 {
1876         SculptThreadedTaskData *data = userdata;
1877         SculptSession *ss = data->ob->sculpt;
1878         StrokeCache *cache = ss->cache;
1879         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
1880         const bool has_grids = (pbvh_type == PBVH_GRIDS);
1881
1882         const bool use_normal = vwpaint_use_normal(data->vp);
1883         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1884         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1885
1886         struct WPaintAverageAccum *accum = (struct WPaintAverageAccum *)data->custom_data + n;
1887         accum->len = 0;
1888         accum->value = 0.0;
1889
1890         SculptBrushTest test;
1891         SculptBrushTestFn sculpt_brush_test_sq_fn =
1892                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1893         const float *sculpt_normal_frontface =
1894                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1895
1896         /* For each vertex */
1897         PBVHVertexIter vd;
1898         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1899         {
1900                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1901                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1902                         const float angle_cos = (use_normal && vd.no) ?
1903                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1904                         if (angle_cos > 0.0 && BKE_brush_curve_strength(data->brush, sqrtf(test.dist), cache->radius) > 0.0) {
1905                                 const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1906                                 // const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
1907                                 const char v_flag = data->me->mvert[v_index].flag;
1908
1909                                 /* If the vertex is selected. */
1910                                 if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1911                                         const MDeformVert *dv = &data->me->dvert[v_index];
1912                                         accum->len += 1;
1913                                         accum->value += wpaint_get_active_weight(dv, data->wpi);
1914                                 }
1915                         }
1916                 }
1917         }
1918         BKE_pbvh_vertex_iter_end;
1919 }
1920
1921 static void calculate_average_weight(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
1922 {
1923         struct WPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
1924         data->custom_data = accum;
1925
1926         ParallelRangeSettings settings;
1927         BLI_parallel_range_settings_defaults(&settings);
1928         settings.use_threading = ((data->sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
1929         BLI_task_parallel_range(
1930                 0, totnode,
1931                 data,
1932                 do_wpaint_brush_calc_average_weight_cb_ex,
1933                 &settings);
1934
1935         uint accum_len = 0;
1936         double accum_weight = 0.0;
1937         for (int i = 0; i < totnode; i++) {
1938                 accum_len += accum[i].len;
1939                 accum_weight += accum[i].value;
1940         }
1941         if (accum_len != 0) {
1942                 accum_weight /= accum_len;
1943                 data->strength = (float)accum_weight;
1944         }
1945
1946         MEM_SAFE_FREE(data->custom_data);  /* 'accum' */
1947 }
1948
1949
1950 static void wpaint_paint_leaves(
1951         bContext *C, Object *ob, Sculpt *sd, VPaint *vp, struct WPaintData *wpd, WeightPaintInfo *wpi,
1952         Mesh *me, PBVHNode **nodes, int totnode)
1953 {
1954         Scene *scene = CTX_data_scene(C);
1955         const Brush *brush = ob->sculpt->cache->brush;
1956
1957         /* threaded loop over nodes */
1958         SculptThreadedTaskData data = {
1959                 .sd = sd, .ob = ob, .brush = brush, .nodes = nodes, .vp = vp, .wpd = wpd, .wpi = wpi, .me = me, .C = C,
1960         };
1961
1962         /* Use this so average can modify its weight without touching the brush. */
1963         data.strength = BKE_brush_weight_get(scene, brush);
1964
1965         ParallelRangeSettings settings;
1966         BLI_parallel_range_settings_defaults(&settings);
1967         /* NOTE: current mirroring code cannot be run in parallel */
1968         settings.use_threading = !(me->editflag & ME_EDIT_MIRROR_X);
1969
1970         switch (brush->vertexpaint_tool) {
1971                 case PAINT_BLEND_AVERAGE:
1972                         calculate_average_weight(&data, nodes, totnode);
1973                         BLI_task_parallel_range(
1974                                 0, totnode,
1975                                 &data,
1976                                 do_wpaint_brush_draw_task_cb_ex,
1977                                 &settings);
1978                         break;
1979                 case PAINT_BLEND_SMEAR:
1980                         BLI_task_parallel_range(
1981                                 0, totnode,
1982                                 &data,
1983                                 do_wpaint_brush_smear_task_cb_ex,
1984                                 &settings);
1985                         break;
1986                 case PAINT_BLEND_BLUR:
1987                         BLI_task_parallel_range(
1988                                 0, totnode,
1989                                 &data,
1990                                 do_wpaint_brush_blur_task_cb_ex,
1991                                 &settings);
1992                         break;
1993                 default:
1994                         BLI_task_parallel_range(
1995                                 0, totnode,
1996                                 &data,
1997                                 do_wpaint_brush_draw_task_cb_ex,
1998                                 &settings);
1999                         break;
2000         }
2001 }
2002
2003 static PBVHNode **vwpaint_pbvh_gather_generic(
2004         Object *ob, VPaint *wp, Sculpt *sd, Brush *brush, int *r_totnode)
2005 {
2006         SculptSession *ss = ob->sculpt;
2007         const bool use_normal = vwpaint_use_normal(wp);
2008         PBVHNode **nodes = NULL;
2009
2010         /* Build a list of all nodes that are potentially within the brush's area of influence */
2011         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
2012                 SculptSearchSphereData data = {
2013                         .ss = ss,
2014                         .sd = sd,
2015                         .radius_squared = ss->cache->radius_squared,
2016                         .original = true,
2017                 };
2018                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
2019                 if (use_normal) {
2020                         sculpt_pbvh_calc_area_normal(brush, ob, nodes, *r_totnode, true, ss->cache->sculpt_normal_symm);
2021                 }
2022                 else {
2023                         zero_v3(ss->cache->sculpt_normal_symm);
2024                 }
2025         }
2026         else {
2027                 struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
2028                 dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
2029                 SculptSearchCircleData data = {
2030                         .ss = ss,
2031                         .sd = sd,
2032                         .radius_squared = ss->cache->radius_squared,
2033                         .original = true,
2034                         .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
2035                 };
2036                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
2037                 if (use_normal) {
2038                         copy_v3_v3(ss->cache->sculpt_normal_symm, ss->cache->view_normal);
2039                 }
2040                 else {
2041                         zero_v3(ss->cache->sculpt_normal_symm);
2042                 }
2043         }
2044         return nodes;
2045 }
2046
2047 static void wpaint_do_paint(
2048         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
2049         Mesh *me, Brush *brush, const char symm, const int axis, const int i, const float angle)
2050 {
2051         SculptSession *ss = ob->sculpt;
2052         ss->cache->radial_symmetry_pass = i;
2053         sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
2054
2055         int totnode;
2056         PBVHNode **nodes = vwpaint_pbvh_gather_generic(ob, wp, sd, brush, &totnode);
2057
2058         wpaint_paint_leaves(C, ob, sd, wp, wpd, wpi, me, nodes, totnode);
2059
2060         if (nodes)
2061                 MEM_freeN(nodes);
2062 }
2063
2064 static void wpaint_do_radial_symmetry(
2065         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
2066         Mesh *me, Brush *brush, const char symm, const int axis)
2067 {
2068         for (int i = 1; i < wp->radial_symm[axis - 'X']; i++) {
2069                 const float angle = (2.0 * M_PI) * i / wp->radial_symm[axis - 'X'];
2070                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, symm, axis, i, angle);
2071         }
2072 }
2073
2074 /* near duplicate of: sculpt.c's, 'do_symmetrical_brush_actions' and 'vpaint_do_symmetrical_brush_actions'. */
2075 static void wpaint_do_symmetrical_brush_actions(
2076         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi)
2077 {
2078         Brush *brush = BKE_paint_brush(&wp->paint);
2079         Mesh *me = ob->data;
2080         SculptSession *ss = ob->sculpt;
2081         StrokeCache *cache = ss->cache;
2082         const char symm = wp->paint.symmetry_flags & PAINT_SYMM_AXIS_ALL;
2083         int i = 0;
2084
2085         /* initial stroke */
2086         wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X', 0, 0);
2087         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X');
2088         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Y');
2089         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Z');
2090
2091         cache->symmetry = symm;
2092
2093         /* symm is a bit combination of XYZ - 1 is mirror X; 2 is Y; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
2094         for (i = 1; i <= symm; i++) {
2095                 if ((symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
2096                         cache->mirror_symmetry_pass = i;
2097                         cache->radial_symmetry_pass = 0;
2098                         sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
2099
2100                         if (i & (1 << 0)) {
2101                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X', 0, 0);
2102                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X');
2103                         }
2104                         if (i & (1 << 1)) {
2105                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y', 0, 0);
2106                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y');
2107                         }
2108                         if (i & (1 << 2)) {
2109                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z', 0, 0);
2110                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z');
2111                         }
2112                 }
2113         }
2114         copy_v3_v3(cache->true_last_location, cache->true_location);
2115         cache->is_last_valid = true;
2116 }
2117
2118 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2119 {
2120         Scene *scene = CTX_data_scene(C);
2121         ToolSettings *ts = CTX_data_tool_settings(C);
2122         VPaint *wp = ts->wpaint;
2123         Brush *brush = BKE_paint_brush(&wp->paint);
2124         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2125         ViewContext *vc;
2126         Object *ob = CTX_data_active_object(C);
2127
2128         SculptSession *ss = ob->sculpt;
2129         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
2130
2131         vwpaint_update_cache_variants(C, wp, ob, itemptr);
2132
2133         float mat[4][4];
2134         float mval[2];
2135
2136         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2137
2138         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2139         WeightPaintInfo wpi;
2140
2141         /* cannot paint if there is no stroke data */
2142         if (wpd == NULL) {
2143                 /* XXX: force a redraw here, since even though we can't paint,
2144                  * at least view won't freeze until stroke ends */
2145                 ED_region_tag_redraw(CTX_wm_region(C));
2146                 return;
2147         }
2148
2149         vc = &wpd->vc;
2150         ob = vc->obact;
2151
2152         view3d_operator_needs_opengl(C);
2153         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2154
2155         /* load projection matrix */
2156         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2157
2158
2159         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2160         wpi.defbase_tot =        wpd->defbase_tot;
2161         wpi.defbase_sel =        wpd->defbase_sel;
2162         wpi.defbase_tot_sel =    wpd->defbase_tot_sel;
2163
2164         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2165         wpi.active =             wpd->active;
2166         wpi.mirror =             wpd->mirror;
2167         wpi.lock_flags =         wpd->lock_flags;
2168         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2169         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2170         wpi.do_multipaint =      wpd->do_multipaint;
2171         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2172         wpi.brush_alpha_value =  brush_alpha_value;
2173         /* *** done setting up WeightPaintInfo *** */
2174
2175         if (wpd->precomputed_weight) {
2176                 precompute_weight_values(C, ob, brush, wpd, &wpi, ob->data);
2177         }
2178
2179         wpaint_do_symmetrical_brush_actions(C, ob, wp, sd, wpd, &wpi);
2180
2181         swap_m4m4(vc->rv3d->persmat, mat);
2182
2183         /* calculate pivot for rotation around seletion if needed */
2184         /* also needed for "View Selected" on last stroke */
2185         paint_last_stroke_update(scene, vc->ar, mval);
2186
2187         DAG_id_tag_update(ob->data, 0);
2188         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2189         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2190
2191         rcti r;
2192         if (sculpt_get_redraw_rect(vc->ar, CTX_wm_region_view3d(C), ob, &r)) {
2193                 if (ss->cache) {
2194                         ss->cache->current_r = r;
2195                 }
2196
2197                 /* previous is not set in the current cache else
2198                  * the partial rect will always grow */
2199                 if (ss->cache) {
2200                         if (!BLI_rcti_is_empty(&ss->cache->previous_r))
2201                                 BLI_rcti_union(&r, &ss->cache->previous_r);
2202                 }
2203
2204                 r.xmin += vc->ar->winrct.xmin - 2;
2205                 r.xmax += vc->ar->winrct.xmin + 2;
2206                 r.ymin += vc->ar->winrct.ymin - 2;
2207                 r.ymax += vc->ar->winrct.ymin + 2;
2208
2209                 ss->partial_redraw = 1;
2210         }
2211         ED_region_tag_redraw_partial(vc->ar, &r);
2212 }
2213
2214 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2215 {
2216         Object *ob = CTX_data_active_object(C);
2217         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2218
2219         if (wpd) {
2220                 if (wpd->defbase_sel)
2221                         MEM_freeN((void *)wpd->defbase_sel);
2222                 if (wpd->vgroup_validmap)
2223                         MEM_freeN((void *)wpd->vgroup_validmap);
2224                 if (wpd->lock_flags)
2225                         MEM_freeN((void *)wpd->lock_flags);
2226                 if (wpd->active.lock)
2227                         MEM_freeN((void *)wpd->active.lock);
2228                 if (wpd->mirror.lock)
2229                         MEM_freeN((void *)wpd->mirror.lock);
2230                 if (wpd->precomputed_weight)
2231                         MEM_freeN(wpd->precomputed_weight);
2232
2233                 MEM_freeN(wpd);
2234         }
2235
2236         /* and particles too */
2237         if (ob->particlesystem.first) {
2238                 ParticleSystem *psys;
2239                 int i;
2240
2241                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2242                         for (i = 0; i < PSYS_TOT_VG; i++) {
2243                                 if (psys->vgroup[i] == ob->actdef) {
2244                                         psys->recalc |= PSYS_RECALC_RESET;
2245                                         break;
2246                                 }
2247                         }
2248                 }
2249         }
2250
2251         DAG_id_tag_update(ob->data, 0);
2252
2253         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2254
2255         sculpt_cache_free(ob->sculpt->cache);
2256         ob->sculpt->cache = NULL;
2257 }
2258
2259
2260 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2261 {
2262         int retval;
2263
2264         op->customdata = paint_stroke_new(
2265                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2266                 wpaint_stroke_update_step, NULL,
2267                 wpaint_stroke_done, event->type);
2268
2269         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2270                 paint_stroke_data_free(op);
2271                 return OPERATOR_FINISHED;
2272         }
2273         /* add modal handler */
2274         WM_event_add_modal_handler(C, op);
2275
2276         OPERATOR_RETVAL_CHECK(retval);
2277         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2278
2279         return OPERATOR_RUNNING_MODAL;
2280 }
2281
2282 static int wpaint_exec(bContext *C, wmOperator *op)
2283 {
2284         op->customdata = paint_stroke_new(
2285                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2286                 wpaint_stroke_update_step, NULL,
2287                 wpaint_stroke_done, 0);
2288
2289         /* frees op->customdata */
2290         paint_stroke_exec(C, op);
2291
2292         return OPERATOR_FINISHED;
2293 }
2294
2295 static void wpaint_cancel(bContext *C, wmOperator *op)
2296 {
2297         Object *ob = CTX_data_active_object(C);
2298         if (ob->sculpt->cache) {
2299                 sculpt_cache_free(ob->sculpt->cache);
2300                 ob->sculpt->cache = NULL;
2301         }
2302
2303         paint_stroke_cancel(C, op);
2304 }
2305
2306 void PAINT_OT_weight_paint(wmOperatorType *ot)
2307 {
2308         /* identifiers */
2309         ot->name = "Weight Paint";
2310         ot->idname = "PAINT_OT_weight_paint";
2311         ot->description = "Paint a stroke in the current vertex group's weights";
2312
2313         /* api callbacks */
2314         ot->invoke = wpaint_invoke;
2315         ot->modal = paint_stroke_modal;
2316         ot->exec = wpaint_exec;
2317         ot->poll = weight_paint_poll;
2318         ot->cancel = wpaint_cancel;
2319
2320         /* flags */
2321         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2322
2323         paint_stroke_operator_properties(ot);
2324 }
2325
2326 /* ************ set / clear vertex paint mode ********** */
2327
2328 /**
2329  * \note Keep in sync with #wpaint_mode_toggle_exec
2330  */
2331 static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
2332 {
2333         Main *bmain = CTX_data_main(C);
2334         Object *ob = CTX_data_active_object(C);
2335         const int mode_flag = OB_MODE_VERTEX_PAINT;
2336         const bool is_mode_set = (ob->mode & mode_flag) != 0;
2337         Scene *scene = CTX_data_scene(C);
2338
2339         if (!is_mode_set) {
2340                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
2341                         return OPERATOR_CANCELLED;
2342                 }
2343         }
2344
2345         Mesh *me = BKE_mesh_from_object(ob);
2346
2347         /* toggle: end vpaint */
2348         if (is_mode_set) {
2349                 ED_object_vpaintmode_exit_ex(ob);
2350         }
2351         else {
2352                 wmWindowManager *wm = CTX_wm_manager(C);
2353                 ED_object_vpaintmode_enter_ex(bmain, wm, scene, ob);
2354         }
2355
2356         /* update modifier stack for mapping requirements */
2357         DAG_id_tag_update(&me->id, 0);
2358
2359         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2360
2361         return OPERATOR_FINISHED;
2362 }
2363
2364 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2365 {
2366         /* identifiers */
2367         ot->name = "Vertex Paint Mode";
2368         ot->idname = "PAINT_OT_vertex_paint_toggle";
2369         ot->description = "Toggle the vertex paint mode in 3D view";
2370
2371         /* api callbacks */
2372         ot->exec = vpaint_mode_toggle_exec;
2373         ot->poll = paint_poll_test;
2374
2375         /* flags */
2376         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2377 }
2378
2379
2380
2381 /* ********************** vertex paint operator ******************* */
2382
2383 /* Implementation notes:
2384  *
2385  * Operator->invoke()
2386  * - validate context (add mcol)
2387  * - create customdata storage
2388  * - call paint once (mouse click)
2389  * - add modal handler
2390  *
2391  * Operator->modal()
2392  * - for every mousemove, apply vertex paint
2393  * - exit on mouse release, free customdata
2394  *   (return OPERATOR_FINISHED also removes handler and operator)
2395  *
2396  * For future:
2397  * - implement a stroke event (or mousemove with past positions)
2398  * - revise whether op->customdata should be added in object, in set_vpaint
2399  */
2400
2401 typedef struct PolyFaceMap {
2402         struct PolyFaceMap *next, *prev;
2403         int facenr;
2404 } PolyFaceMap;
2405
2406 struct VPaintData {
2407         ViewContext vc;
2408         struct NormalAnglePrecalc normal_angle_precalc;
2409
2410         uint paintcol;
2411
2412         struct VertProjHandle *vp_handle;
2413         struct DMCoNo *vertexcosnos;
2414
2415         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2416          * array, otherwise we need to refresh the modifier stack */
2417         bool use_fast_update;
2418
2419         /* loops tagged as having been painted, to apply shared vertex color
2420          * blending only to modified loops */
2421         bool *mlooptag;
2422
2423         bool is_texbrush;
2424
2425         /* Special storage for smear brush, avoid feedback loop - update each step. */
2426         struct {
2427                 uint *color_prev;
2428                 uint *color_curr;
2429         } smear;
2430 };
2431
2432 static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float mouse[2])
2433 {
2434         Scene *scene = CTX_data_scene(C);
2435         ToolSettings *ts = scene->toolsettings;
2436         struct PaintStroke *stroke = op->customdata;
2437         VPaint *vp = ts->vpaint;
2438         Brush *brush = BKE_paint_brush(&vp->paint);
2439         struct VPaintData *vpd;
2440         Object *ob = CTX_data_active_object(C);
2441         Mesh *me;
2442         SculptSession *ss = ob->sculpt;
2443
2444         /* context checks could be a poll() */
2445         me = BKE_mesh_from_object(ob);
2446         if (me == NULL || me->totpoly == 0)
2447                 return false;
2448
2449         ED_mesh_color_ensure(me, NULL);
2450         if (me->mloopcol == NULL)
2451                 return false;
2452
2453         /* make mode data storage */
2454         vpd = MEM_callocN(sizeof(*vpd), "VPaintData");
2455         paint_stroke_set_mode_data(stroke, vpd);
2456         ED_view3d_viewcontext_init(C, &vpd->vc);
2457         view_angle_limits_init(
2458                 &vpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
2459                 (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
2460
2461         vpd->paintcol = vpaint_get_current_col(scene, vp);
2462
2463         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) && brush->mtex.tex;
2464
2465         /* are we painting onto a modified mesh?,
2466          * if not we can skip face map trickiness */
2467         if (vertex_paint_use_fast_update_check(ob)) {
2468                 vpd->use_fast_update = true;
2469 /*              printf("Fast update!\n");*/
2470         }
2471         else {
2472                 vpd->use_fast_update = false;
2473 /*              printf("No fast update!\n");*/
2474         }
2475
2476         /* to keep tracked of modified loops for shared vertex color blending */
2477         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2478                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2479         }
2480
2481         if (brush->vertexpaint_tool == PAINT_BLEND_SMEAR) {
2482                 vpd->smear.color_prev = MEM_mallocN(sizeof(uint) * me->totloop, __func__);
2483                 memcpy(vpd->smear.color_prev, me->mloopcol, sizeof(uint) * me->totloop);
2484                 vpd->smear.color_curr = MEM_dupallocN(vpd->smear.color_prev);
2485         }
2486
2487         /* Create projection handle */
2488         if (vpd->is_texbrush) {
2489                 ob->sculpt->building_vp_handle = true;
2490                 vpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &vpd->vertexcosnos);
2491                 ob->sculpt->building_vp_handle = false;
2492         }
2493
2494         /* If not previously created, create vertex/weight paint mode session data */
2495         vertex_paint_init_stroke(scene, ob);
2496         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
2497         vertex_paint_init_session_data(ts, ob);
2498
2499         if (ob->sculpt->mode.vpaint.previous_color != NULL) {
2500                 memset(ob->sculpt->mode.vpaint.previous_color, 0, sizeof(uint) * me->totloop);
2501         }
2502
2503         return 1;
2504 }
2505
2506 static void do_vpaint_brush_calc_average_color_cb_ex(
2507         void *__restrict userdata,
2508         const int n,
2509         const ParallelRangeTLS *__restrict UNUSED(tls))
2510 {
2511         SculptThreadedTaskData *data = userdata;
2512         SculptSession *ss = data->ob->sculpt;
2513         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
2514         const bool has_grids = (pbvh_type == PBVH_GRIDS);
2515         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2516
2517         StrokeCache *cache = ss->cache;
2518         uint *lcol = data->lcol;
2519         char *col;
2520         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2521
2522         struct VPaintAverageAccum *accum = (struct VPaintAverageAccum *)data->custom_data + n;
2523         accum->len = 0;
2524         memset(accum->value, 0, sizeof(accum->value));
2525
2526         SculptBrushTest test;
2527         SculptBrushTestFn sculpt_brush_test_sq_fn =
2528                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2529
2530         /* For each vertex */
2531         PBVHVertexIter vd;
2532         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2533         {
2534                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2535                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2536                         const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2537                         if (BKE_brush_curve_strength(data->brush, 0.0, cache->radius) > 0.0) {
2538                                 /* If the vertex is selected for painting. */
2539                                 const MVert *mv = &data->me->mvert[v_index];
2540                                 if (!use_vert_sel || mv->flag & SELECT) {
2541                                         accum->len += gmap->vert_to_loop[v_index].count;
2542                                         /* if a vertex is within the brush region, then add it's color to the blend. */
2543                                         for (int j = 0; j < gmap->vert_to_loop[v_index].count; j++) {
2544                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2545                                                 col = (char *)(&lcol[l_index]);
2546                                                 /* Color is squared to compensate the sqrt color encoding. */
2547                                                 accum->value[0] += col[0] * col[0];
2548                                                 accum->value[1] += col[1] * col[1];
2549                                                 accum->value[2] += col[2] * col[2];
2550                                         }
2551                                 }
2552                         }
2553                 }
2554         }
2555         BKE_pbvh_vertex_iter_end;
2556 }
2557
2558 static float tex_color_alpha_ubyte(
2559         SculptThreadedTaskData *data, const float v_co[3],
2560         uint *r_color)
2561 {
2562         float rgba[4];
2563         float rgba_br[3];
2564         tex_color_alpha(data->vp, &data->vpd->vc, v_co, rgba);
2565         rgb_uchar_to_float(rgba_br, (const uchar *)&data->vpd->paintcol);
2566         mul_v3_v3(rgba_br, rgba);
2567         rgb_float_to_uchar((uchar *)r_color, rgba_br);
2568         return rgba[3];
2569 }
2570
2571 static void do_vpaint_brush_draw_task_cb_ex(
2572         void *__restrict userdata,
2573         const int n,
2574         const ParallelRangeTLS *__restrict UNUSED(tls))
2575 {
2576         SculptThreadedTaskData *data = userdata;
2577         SculptSession *ss = data->ob->sculpt;
2578         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
2579         const bool has_grids = (pbvh_type == PBVH_GRIDS);
2580         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2581
2582         const Brush *brush = data->brush;
2583         const StrokeCache *cache = ss->cache;
2584         uint *lcol = data->lcol;
2585         const Scene *scene = CTX_data_scene(data->C);
2586         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2587         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2588         const bool use_normal = vwpaint_use_normal(data->vp);
2589         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2590         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2591
2592         SculptBrushTest test;
2593         SculptBrushTestFn sculpt_brush_test_sq_fn =
2594                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2595         const float *sculpt_normal_frontface =
2596                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2597
2598         /* For each vertex */
2599         PBVHVertexIter vd;
2600         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2601         {
2602                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2603                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2604                         /* Note: Grids are 1:1 with corners (aka loops).
2605                          * For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2606                          * Otherwise, take the current vert. */
2607                         const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2608                         const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
2609                         const MVert *mv = &data->me->mvert[v_index];
2610
2611                         /* If the vertex is selected for painting. */
2612                         if (!use_vert_sel || mv->flag & SELECT) {
2613                                 /* Calc the dot prod. between ray norm on surf and current vert
2614                                  * (ie splash prevention factor), and only paint front facing verts. */
2615                                 float brush_strength = cache->bstrength;
2616                                 const float angle_cos = (use_normal && vd.no) ?
2617                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2618                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2619                                      (angle_cos > 0.0f)) &&
2620                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2621                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2622                                 {
2623                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2624                                         uint color_final = data->vpd->paintcol;
2625
2626                                         /* If we're painting with a texture, sample the texture color and alpha. */
2627                                         float tex_alpha = 1.0;
2628                                         if (data->vpd->is_texbrush) {
2629                                                 /* Note: we may want to paint alpha as vertex color alpha. */
2630                                                 tex_alpha = tex_color_alpha_ubyte(
2631                                                         data, data->vpd->vertexcosnos[v_index].co,
2632                                                         &color_final);
2633                                         }
2634                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2635                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2636                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2637                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2638                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2639                                                 const MPoly *mp = &data->me->mpoly[p_index];
2640                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2641                                                         uint color_orig = 0;  /* unused when array is NULL */
2642                                                         if (ss->mode.vpaint.previous_color != NULL) {
2643                                                                 /* Get the previous loop color */
2644                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2645                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2646                                                                 }
2647                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2648                                                         }
2649                                                         const float final_alpha =
2650                                                                 255 * brush_fade * brush_strength *
2651                                                                 tex_alpha * brush_alpha_pressure * grid_alpha;
2652
2653                                                         /* Mix the new color with the original based on final_alpha. */
2654                                                         lcol[l_index] = vpaint_blend(
2655                                                                 data->vp, lcol[l_index], color_orig, color_final,
2656                                                                 final_alpha, 255 * brush_strength);
2657                                                 }
2658                                         }
2659                                 }
2660                         }
2661                 }
2662         }
2663         BKE_pbvh_vertex_iter_end;
2664 }
2665
2666 static void do_vpaint_brush_blur_task_cb_ex(
2667         void *__restrict userdata,
2668         const int n,
2669         const ParallelRangeTLS *__restrict UNUSED(tls))
2670 {
2671         SculptThreadedTaskData *data = userdata;
2672         SculptSession *ss = data->ob->sculpt;
2673         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
2674         const bool has_grids = (pbvh_type == PBVH_GRIDS);
2675
2676         Scene *scene = CTX_data_scene(data->C);
2677         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2678         const Brush *brush = data->brush;
2679         const StrokeCache *cache = ss->cache;
2680         uint *lcol = data->lcol;
2681         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2682         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2683         const bool use_normal = vwpaint_use_normal(data->vp);
2684         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2685         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2686
2687         SculptBrushTest test;
2688         SculptBrushTestFn sculpt_brush_test_sq_fn =
2689                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2690         const float *sculpt_normal_frontface =
2691                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2692
2693         /* For each vertex */
2694         PBVHVertexIter vd;
2695         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2696         {
2697                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2698                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2699                         /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2700                          * Otherwise, take the current vert. */
2701                         const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2702                         const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
2703                         const MVert *mv = &data->me->mvert[v_index];
2704
2705                         /* If the vertex is selected for painting. */
2706                         if (!use_vert_sel || mv->flag & SELECT) {
2707                                 float brush_strength = cache->bstrength;
2708                                 const float angle_cos = (use_normal && vd.no) ?
2709                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2710                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2711                                      (angle_cos > 0.0f)) &&
2712                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2713                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2714                                 {
2715                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2716
2717                                         /* Get the average poly color */
2718                                         uint color_final = 0;
2719                                         int total_hit_loops = 0;
2720                                         uint blend[4] = {0};
2721                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2722                                                 int p_index = gmap->vert_to_poly[v_index].indices[j];
2723                                                 const MPoly *mp = &data->me->mpoly[p_index];
2724                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2725                                                         total_hit_loops += mp->totloop;
2726                                                         for (int k = 0; k < mp->totloop; k++) {
2727                                                                 const uint l_index = mp->loopstart + k;
2728                                                                 const char *col = (const char *)(&lcol[l_index]);
2729                                                                 /* Color is squared to compensate the sqrt color encoding. */
2730                                                                 blend[0] += (uint)col[0] * (uint)col[0];
2731                                                                 blend[1] += (uint)col[1] * (uint)col[1];
2732                                                                 blend[2] += (uint)col[2] * (uint)col[2];
2733                                                                 blend[3] += (uint)col[3] * (uint)col[3];
2734                                                         }
2735                                                 }
2736                                         }
2737                                         if (total_hit_loops != 0) {
2738                                                 /* Use rgb^2 color averaging. */
2739                                                 char *col = (char *)(&color_final);
2740                                                 col[0] = round_fl_to_uchar(sqrtf(divide_round_i(blend[0], total_hit_loops)));
2741                                                 col[1] = round_fl_to_uchar(sqrtf(divide_round_i(blend[1], total_hit_loops)));
2742                                                 col[2] = round_fl_to_uchar(sqrtf(divide_round_i(blend[2], total_hit_loops)));
2743                                                 col[3] = round_fl_to_uchar(sqrtf(divide_round_i(blend[3], total_hit_loops)));
2744
2745                                                 /* For each poly owning this vert, paint each loop belonging to this vert. */
2746                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2747                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2748                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2749                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2750                                                         const MPoly *mp = &data->me->mpoly[p_index];
2751                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2752                                                                 uint color_orig = 0;  /* unused when array is NULL */
2753                                                                 if (ss->mode.vpaint.previous_color != NULL) {
2754                                                                         /* Get the previous loop color */
2755                                                                         if (ss->mode.vpaint.previous_color[l_index] == 0) {
2756                                                                                 ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2757                                                                         }
2758                                                                         color_orig = ss->mode.vpaint.previous_color[l_index];
2759                                                                 }
2760                                                                 const float final_alpha =
2761                                                                         255 * brush_fade * brush_strength *
2762                                                                         brush_alpha_pressure * grid_alpha;
2763                                                                 /* Mix the new color with the original
2764                                                                  * based on the brush strength and the curve. */
2765                                                                 lcol[l_index] = vpaint_blend(
2766                                                                         data->vp, lcol[l_index], color_orig, *((uint *)col),
2767                                                                         final_alpha, 255 * brush_strength);
2768                                                         }
2769                                                 }
2770                                         }
2771                                 }
2772                         }
2773                 }
2774         }
2775         BKE_pbvh_vertex_iter_end;
2776 }
2777
2778 static void do_vpaint_brush_smear_task_cb_ex(
2779         void *__restrict userdata,
2780         const int n,
2781         const ParallelRangeTLS *__restrict UNUSED(tls))
2782 {
2783         SculptThreadedTaskData *data = userdata;
2784         SculptSession *ss = data->ob->sculpt;
2785         const PBVHType pbvh_type = BKE_pbvh_type(ss->pbvh);
2786         const bool has_grids = (pbvh_type == PBVH_GRIDS);
2787
2788         Scene *scene = CTX_data_scene(data->C);
2789         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2790         const Brush *brush = data->brush;
2791         const StrokeCache *cache = ss->cache;
2792         uint *lcol = data->lcol;
2793         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2794         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2795         float brush_dir[3];
2796         const bool use_normal = vwpaint_use_normal(data->vp);
2797         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2798         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2799
2800         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
2801         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
2802
2803         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
2804
2805                 SculptBrushTest test;
2806                 SculptBrushTestFn sculpt_brush_test_sq_fn =
2807                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2808                 const float *sculpt_normal_frontface =
2809                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2810
2811                 /* For each vertex */
2812                 PBVHVertexIter vd;
2813                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2814                 {
2815                         /* Test to see if the vertex coordinates are within the spherical brush region. */
2816                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2817                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2818                                  * Otherwise, take the current vert. */
2819                                 const int v_index = has_grids ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2820                                 const float grid_alpha = has_grids ? 1.0f / vd.gridsize : 1.0f;
2821                                 const MVert *mv_curr = &data->me->mvert[v_index];
2822
2823                                 /* if the vertex is selected for painting. */
2824                                 if (!use_vert_sel || mv_curr->flag & SELECT) {
2825                                         /* Calc the dot prod. between ray norm on surf and current vert
2826                                          * (ie splash prevention factor), and only paint front facing verts. */
2827                                         float brush_strength = cache->bstrength;
2828                                         const float angle_cos = (use_normal && vd.no) ?
2829                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2830                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2831                                              (angle_cos > 0.0f)) &&
2832                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2833                                              view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2834                                         {
2835                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2836
2837                                                 bool do_color = false;
2838                                                 /* Minimum dot product between brush direction and current
2839                                                  * to neighbor direction is 0.0, meaning orthogonal. */
2840                                                 float stroke_dot_max = 0.0f;
2841
2842                                                 /* Get the color of the loop in the opposite direction of the brush movement */
2843                                                 uint color_final = 0;
2844                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2845                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2846                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2847                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2848                                                         UNUSED_VARS_NDEBUG(l_index);
2849                                                         const MPoly *mp = &data->me->mpoly[p_index];
2850                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2851                                                                 const MLoop *ml_other = &data->me->mloop[mp->loopstart];
2852                                                                 for (int k = 0; k < mp->totloop; k++, ml_other++) {
2853                                                                         const uint v_other_index = ml_other->v;
2854                                                                         if (v_other_index != v_index) {
2855                                                                                 const MVert *mv_other = &data->me->mvert[v_other_index];
2856
2857                                                                                 /* Get the direction from the selected vert to the neighbor. */
2858                                                                                 float other_dir[3];
2859                                                                                 sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
2860                                                                                 project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
2861
2862                                                                                 normalize_v3(other_dir);
2863
2864                                                                                 const float stroke_dot = dot_v3v3(other_dir, brush_dir);
2865
2866                                                                                 if (stroke_dot > stroke_dot_max) {
2867                                                                                         stroke_dot_max = stroke_dot;
2868                                                                                         color_final = data->vpd->smear.color_prev[mp->loopstart + k];
2869                                                                                         do_color = true;
2870                                                                                 }
2871                                                                         }
2872                                                                 }
2873                                                         }
2874                                                 }
2875
2876                                                 if (do_color) {
2877                                                         const float final_alpha =
2878                                                                 255 * brush_fade * brush_strength *
2879                                                                 brush_alpha_pressure * grid_alpha;
2880
2881                                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2882                                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2883                                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2884                                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2885                                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2886                                                                 const MPoly *mp = &data->me->mpoly[p_index];
2887                                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2888                                                                         /* Get the previous loop color */
2889                                                                         uint color_orig = 0;  /* unused when array is NULL */
2890                                                                         if (ss->mode.vpaint.previous_color != NULL) {
2891                                                                                 /* Get the previous loop color */
2892                                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2893                                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2894                                                                                 }
2895                                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2896                                                                         }
2897                                                                         /* Mix the new color with the original
2898                                                                          * based on the brush strength and the curve. */
2899                                                                         lcol[l_index] = vpaint_blend(
2900                                                                                 data->vp, lcol[l_index], color_orig, color_final,
2901                                                                                 final_alpha, 255 * brush_strength);
2902
2903                                                                         data->vpd->smear.color_curr[l_index] = lcol[l_index];
2904                                                                 }
2905                                                         }
2906                                                 }
2907                                         }
2908                                 }
2909                         }
2910                 }
2911                 BKE_pbvh_vertex_iter_end;
2912         }
2913 }