Cleanup: Moar G.main removal of Hell.
[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 int 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 int 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 int 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 int 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)
942 {
943         /* Create persistent sculpt mode data */
944         BKE_sculpt_toolsettings_data_ensure(scene);
945
946         if (ob->sculpt == NULL) {
947                 ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
948                 BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, false, false);
949         }
950 }
951
952 static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob)
953 {
954         /* Create maps */
955         struct SculptVertexPaintGeomMap *gmap = NULL;
956         const Brush *brush = NULL;
957         if (ob->mode == OB_MODE_VERTEX_PAINT) {
958                 gmap = &ob->sculpt->mode.vpaint.gmap;
959                 brush = BKE_paint_brush(&ts->vpaint->paint);
960                 ob->sculpt->mode_type = OB_MODE_VERTEX_PAINT;
961         }
962         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
963                 gmap = &ob->sculpt->mode.wpaint.gmap;
964                 brush = BKE_paint_brush(&ts->wpaint->paint);
965                 ob->sculpt->mode_type = OB_MODE_WEIGHT_PAINT;
966         }
967         else {
968                 ob->sculpt->mode_type = 0;
969                 BLI_assert(0);
970                 return;
971         }
972
973         Mesh *me = ob->data;
974
975         if (gmap->vert_to_loop == NULL) {
976                 gmap->vert_map_mem = NULL;
977                 gmap->vert_to_loop = NULL;
978                 gmap->poly_map_mem = NULL;
979                 gmap->vert_to_poly = NULL;
980                 BKE_mesh_vert_loop_map_create(
981                         &gmap->vert_to_loop,
982                         &gmap->vert_map_mem,
983                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
984                 BKE_mesh_vert_poly_map_create(
985                         &gmap->vert_to_poly,
986                         &gmap->poly_map_mem,
987                         me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
988         }
989
990         /* Create average brush arrays */
991         if (ob->mode == OB_MODE_VERTEX_PAINT) {
992                 if (!brush_use_accumulate(brush)) {
993                         if (ob->sculpt->mode.vpaint.previous_color == NULL) {
994                                 ob->sculpt->mode.vpaint.previous_color =
995                                         MEM_callocN(me->totloop * sizeof(uint), __func__);
996                         }
997                 }
998                 else {
999                         MEM_SAFE_FREE(ob->sculpt->mode.vpaint.previous_color);
1000                 }
1001         }
1002         else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
1003                 if (!brush_use_accumulate(brush)) {
1004                         if (ob->sculpt->mode.wpaint.alpha_weight == NULL) {
1005                                 ob->sculpt->mode.wpaint.alpha_weight =
1006                                         MEM_callocN(me->totvert * sizeof(float), __func__);
1007                         }
1008                         if (ob->sculpt->mode.wpaint.dvert_prev == NULL) {
1009                                 ob->sculpt->mode.wpaint.dvert_prev =
1010                                         MEM_callocN(me->totvert * sizeof(MDeformVert), __func__);
1011                                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1012                                 for (int i = 0; i < me->totvert; i++, dv++) {
1013                                         /* Use to show this isn't initialized, never apply to the mesh data. */
1014                                         dv->flag = 1;
1015                                 }
1016                         }
1017                 }
1018                 else {
1019                         MEM_SAFE_FREE(ob->sculpt->mode.wpaint.alpha_weight);
1020                         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1021                                 BKE_defvert_array_free_elems(ob->sculpt->mode.wpaint.dvert_prev, me->totvert);
1022                                 MEM_freeN(ob->sculpt->mode.wpaint.dvert_prev);
1023                                 ob->sculpt->mode.wpaint.dvert_prev = NULL;
1024                         }
1025                 }
1026         }
1027
1028 }
1029
1030 /* -------------------------------------------------------------------- */
1031 /** \name Enter Vertex/Weight Paint Mode
1032  * \{ */
1033
1034 static void ed_vwpaintmode_enter_generic(
1035         Main *bmain,
1036         wmWindowManager *wm,
1037         Scene *scene,
1038         Object *ob, const eObjectMode mode_flag)
1039 {
1040         ob->mode |= mode_flag;
1041         Mesh *me = BKE_mesh_from_object(ob);
1042
1043         if (mode_flag == OB_MODE_VERTEX_PAINT) {
1044                 const ePaintMode paint_mode = ePaintVertex;
1045                 ED_mesh_color_ensure(me, NULL);
1046
1047                 if (scene->toolsettings->vpaint == NULL) {
1048                         scene->toolsettings->vpaint = new_vpaint();
1049                 }
1050
1051                 Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
1052                 paint_cursor_start_explicit(paint, wm, vertex_paint_poll);
1053                 BKE_paint_init(bmain, scene, paint_mode, PAINT_CURSOR_VERTEX_PAINT);
1054         }
1055         else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1056                 const  ePaintMode paint_mode = ePaintWeight;
1057
1058                 if (scene->toolsettings->wpaint == NULL) {
1059                         scene->toolsettings->wpaint = new_vpaint();
1060                 }
1061
1062                 Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
1063                 paint_cursor_start_explicit(paint, wm, weight_paint_poll);
1064                 BKE_paint_init(bmain, scene, paint_mode, PAINT_CURSOR_WEIGHT_PAINT);
1065
1066                 /* weight paint specific */
1067                 ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
1068                 ED_vgroup_sync_from_pose(ob);
1069         }
1070         else {
1071                 BLI_assert(0);
1072         }
1073
1074         /* Create vertex/weight paint mode session data */
1075         if (ob->sculpt) {
1076                 if (ob->sculpt->cache) {
1077                         sculpt_cache_free(ob->sculpt->cache);
1078                         ob->sculpt->cache = NULL;
1079                 }
1080                 BKE_sculptsession_free(ob);
1081         }
1082
1083         vertex_paint_init_session(scene, ob);
1084 }
1085
1086 void ED_object_vpaintmode_enter_ex(
1087         Main *bmain, wmWindowManager *wm,
1088         Scene *scene, Object *ob)
1089 {
1090         ed_vwpaintmode_enter_generic(
1091                 bmain, wm, scene, ob, OB_MODE_VERTEX_PAINT);
1092 }
1093 void ED_object_vpaintmode_enter(struct bContext *C)
1094 {
1095         Main *bmain = CTX_data_main(C);
1096         wmWindowManager *wm = CTX_wm_manager(C);
1097         Scene *scene = CTX_data_scene(C);
1098         Object *ob = CTX_data_active_object(C);
1099         ED_object_vpaintmode_enter_ex(bmain, wm, scene, ob);
1100 }
1101
1102 void ED_object_wpaintmode_enter_ex(
1103         Main *bmain, wmWindowManager *wm,
1104         Scene *scene, Object *ob)
1105 {
1106         ed_vwpaintmode_enter_generic(
1107                 bmain, wm, scene, ob, OB_MODE_WEIGHT_PAINT);
1108 }
1109 void ED_object_wpaintmode_enter(struct bContext *C)
1110 {
1111         Main *bmain = CTX_data_main(C);
1112         wmWindowManager *wm = CTX_wm_manager(C);
1113         Scene *scene = CTX_data_scene(C);
1114         Object *ob = CTX_data_active_object(C);
1115         ED_object_wpaintmode_enter_ex(bmain, wm, scene, ob);
1116 }
1117
1118 /** \} */
1119
1120 /* -------------------------------------------------------------------- */
1121 /** \name Exit Vertex/Weight Paint Mode
1122  * \{ */
1123
1124 static void ed_vwpaintmode_exit_generic(
1125         Object *ob, const eObjectMode mode_flag)
1126 {
1127         Mesh *me = BKE_mesh_from_object(ob);
1128         ob->mode &= ~mode_flag;
1129
1130         if (mode_flag == OB_MODE_VERTEX_PAINT) {
1131                 if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1132                         BKE_mesh_flush_select_from_polys(me);
1133                 }
1134                 else if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1135                         BKE_mesh_flush_select_from_verts(me);
1136                 }
1137         }
1138         else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1139                 if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
1140                         BKE_mesh_flush_select_from_verts(me);
1141                 }
1142                 else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
1143                         BKE_mesh_flush_select_from_polys(me);
1144                 }
1145         }
1146         else {
1147                 BLI_assert(0);
1148         }
1149
1150         /* If the cache is not released by a cancel or a done, free it now. */
1151         if (ob->sculpt && ob->sculpt->cache) {
1152                 sculpt_cache_free(ob->sculpt->cache);
1153                 ob->sculpt->cache = NULL;
1154         }
1155
1156         BKE_sculptsession_free(ob);
1157
1158         paint_cursor_delete_textures();
1159
1160         if (mode_flag == OB_MODE_WEIGHT_PAINT) {
1161                 ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
1162                 ED_mesh_mirror_topo_table(NULL, NULL, 'e');
1163         }
1164 }
1165
1166 void ED_object_vpaintmode_exit_ex(Object *ob)
1167 {
1168         ed_vwpaintmode_exit_generic(ob, OB_MODE_VERTEX_PAINT);
1169 }
1170 void ED_object_vpaintmode_exit(struct bContext *C)
1171 {
1172         Object *ob = CTX_data_active_object(C);
1173         ED_object_vpaintmode_exit_ex(ob);
1174 }
1175
1176 void ED_object_wpaintmode_exit_ex(Object *ob)
1177 {
1178         ed_vwpaintmode_exit_generic(ob, OB_MODE_WEIGHT_PAINT);
1179 }
1180 void ED_object_wpaintmode_exit(struct bContext *C)
1181 {
1182         Object *ob = CTX_data_active_object(C);
1183         ED_object_wpaintmode_exit_ex(ob);
1184 }
1185
1186 /** \} */
1187
1188 /* *************** set wpaint operator ****************** */
1189
1190 /**
1191  * \note Keep in sync with #vpaint_mode_toggle_exec
1192  */
1193 static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
1194 {
1195         Main *bmain = CTX_data_main(C);
1196         Object *ob = CTX_data_active_object(C);
1197         const int mode_flag = OB_MODE_WEIGHT_PAINT;
1198         const bool is_mode_set = (ob->mode & mode_flag) != 0;
1199         Scene *scene = CTX_data_scene(C);
1200
1201         if (!is_mode_set) {
1202                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
1203                         return OPERATOR_CANCELLED;
1204                 }
1205         }
1206
1207         Mesh *me = BKE_mesh_from_object(ob);
1208
1209         if (is_mode_set) {
1210                 ED_object_wpaintmode_exit_ex(ob);
1211         }
1212         else {
1213                 wmWindowManager *wm = CTX_wm_manager(C);
1214                 ED_object_wpaintmode_enter_ex(bmain, wm, scene, ob);
1215         }
1216
1217         /* Weightpaint works by overriding colors in mesh,
1218          * so need to make sure we recalc on enter and
1219          * exit (exit needs doing regardless because we
1220          * should redeform).
1221          */
1222         DAG_id_tag_update(&me->id, 0);
1223
1224         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
1225
1226         return OPERATOR_FINISHED;
1227 }
1228
1229 /* for switching to/from mode */
1230 static int paint_poll_test(bContext *C)
1231 {
1232         Object *ob = CTX_data_active_object(C);
1233         if (ob == NULL || ob->type != OB_MESH)
1234                 return 0;
1235         if (!ob->data || ID_IS_LINKED(ob->data))
1236                 return 0;
1237         if (CTX_data_edit_object(C))
1238                 return 0;
1239         return 1;
1240 }
1241
1242 void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
1243 {
1244
1245         /* identifiers */
1246         ot->name = "Weight Paint Mode";
1247         ot->idname = "PAINT_OT_weight_paint_toggle";
1248         ot->description = "Toggle weight paint mode in 3D view";
1249
1250         /* api callbacks */
1251         ot->exec = wpaint_mode_toggle_exec;
1252         ot->poll = paint_poll_test;
1253
1254         /* flags */
1255         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
1256 }
1257
1258 /* ************ weight paint operator ********** */
1259
1260 struct WPaintData {
1261         ViewContext vc;
1262         struct NormalAnglePrecalc normal_angle_precalc;
1263
1264         struct WeightPaintGroupData active, mirror;
1265
1266         /* variables for auto normalize */
1267         const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
1268         const bool *lock_flags;
1269
1270         /* variables for multipaint */
1271         const bool *defbase_sel;      /* set of selected groups */
1272         int defbase_tot_sel;          /* number of selected groups */
1273         bool do_multipaint;           /* true if multipaint enabled and multiple groups selected */
1274
1275         int defbase_tot;
1276
1277         /* original weight values for use in blur/smear */
1278         float *precomputed_weight;
1279         bool precomputed_weight_ready;
1280 };
1281
1282 /* Initialize the stroke cache invariants from operator properties */
1283 static void vwpaint_update_cache_invariants(
1284         bContext *C, const VPaint *vp, SculptSession *ss, wmOperator *op, const float mouse[2])
1285 {
1286         StrokeCache *cache;
1287         Scene *scene = CTX_data_scene(C);
1288         UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1289         const Brush *brush = vp->paint.brush;
1290         ViewContext *vc = paint_stroke_view_context(op->customdata);
1291         Object *ob = CTX_data_active_object(C);
1292         float mat[3][3];
1293         float view_dir[3] = {0.0f, 0.0f, 1.0f};
1294         int mode;
1295
1296         /* VW paint needs to allocate stroke cache before update is called. */
1297         if (!ss->cache) {
1298                 cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
1299                 ss->cache = cache;
1300         }
1301         else {
1302                 cache = ss->cache;
1303         }
1304
1305         /* Initial mouse location */
1306         if (mouse)
1307                 copy_v2_v2(cache->initial_mouse, mouse);
1308         else
1309                 zero_v2(cache->initial_mouse);
1310
1311         mode = RNA_enum_get(op->ptr, "mode");
1312         cache->invert = mode == BRUSH_STROKE_INVERT;
1313         cache->alt_smooth = mode == BRUSH_STROKE_SMOOTH;
1314         /* not very nice, but with current events system implementation
1315          * we can't handle brush appearance inversion hotkey separately (sergey) */
1316         if (cache->invert) ups->draw_inverted = true;
1317         else ups->draw_inverted = false;
1318
1319         copy_v2_v2(cache->mouse, cache->initial_mouse);
1320         /* Truly temporary data that isn't stored in properties */
1321         cache->vc = vc;
1322         cache->brush = brush;
1323         cache->first_time = 1;
1324
1325         /* cache projection matrix */
1326         ED_view3d_ob_project_mat_get(cache->vc->rv3d, ob, cache->projection_mat);
1327
1328         invert_m4_m4(ob->imat, ob->obmat);
1329         copy_m3_m4(mat, cache->vc->rv3d->viewinv);
1330         mul_m3_v3(mat, view_dir);
1331         copy_m3_m4(mat, ob->imat);
1332         mul_m3_v3(mat, view_dir);
1333         normalize_v3_v3(cache->true_view_normal, view_dir);
1334
1335         copy_v3_v3(cache->view_normal, cache->true_view_normal);
1336         cache->bstrength = BKE_brush_alpha_get(scene, brush);
1337         cache->is_last_valid = false;
1338 }
1339
1340 /* Initialize the stroke cache variants from operator properties */
1341 static void vwpaint_update_cache_variants(bContext *C, VPaint *vp, Object *ob, PointerRNA *ptr)
1342 {
1343         Scene *scene = CTX_data_scene(C);
1344         SculptSession *ss = ob->sculpt;
1345         StrokeCache *cache = ss->cache;
1346         Brush *brush = BKE_paint_brush(&vp->paint);
1347
1348         /* This effects the actual brush radius, so things farther away
1349          * are compared with a larger radius and vise versa. */
1350         if (cache->first_time) {
1351                 RNA_float_get_array(ptr, "location", cache->true_location);
1352         }
1353
1354         RNA_float_get_array(ptr, "mouse", cache->mouse);
1355
1356         /* XXX: Use pressure value from first brush step for brushes which don't
1357          * support strokes (grab, thumb). They depends on initial state and
1358          * brush coord/pressure/etc.
1359          * It's more an events design issue, which doesn't split coordinate/pressure/angle
1360          * changing events. We should avoid this after events system re-design */
1361         if (paint_supports_dynamic_size(brush, ePaintSculpt) || cache->first_time) {
1362                 cache->pressure = RNA_float_get(ptr, "pressure");
1363         }
1364
1365         /* Truly temporary data that isn't stored in properties */
1366         if (cache->first_time) {
1367                 if (!BKE_brush_use_locked_size(scene, brush)) {
1368                         cache->initial_radius = paint_calc_object_space_radius(
1369                                 cache->vc, cache->true_location, BKE_brush_size_get(scene, brush));
1370                         BKE_brush_unprojected_radius_set(scene, brush, cache->initial_radius);
1371                 }
1372                 else {
1373                         cache->initial_radius = BKE_brush_unprojected_radius_get(scene, brush);
1374                 }
1375         }
1376
1377         if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, ePaintSculpt)) {
1378                 cache->radius = cache->initial_radius * cache->pressure;
1379         }
1380         else {
1381                 cache->radius = cache->initial_radius;
1382         }
1383
1384         cache->radius_squared = cache->radius * cache->radius;
1385
1386         if (ss->pbvh) {
1387                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateRedraw, NULL);
1388                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB, NULL);
1389         }
1390 }
1391
1392 static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
1393 {
1394         Scene *scene = CTX_data_scene(C);
1395         struct PaintStroke *stroke = op->customdata;
1396         ToolSettings *ts = scene->toolsettings;
1397         Object *ob = CTX_data_active_object(C);
1398         Mesh *me = BKE_mesh_from_object(ob);
1399         struct WPaintData *wpd;
1400         struct WPaintVGroupIndex vgroup_index;
1401         int defbase_tot, defbase_tot_sel;
1402         bool *defbase_sel;
1403         SculptSession *ss = ob->sculpt;
1404         VPaint *vp = CTX_data_tool_settings(C)->wpaint;
1405
1406         if (ED_wpaint_ensure_data(C, op->reports, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
1407                 return false;
1408         }
1409
1410         {
1411                 /* check if we are attempting to paint onto a locked vertex group,
1412                  * and other options disallow it from doing anything useful */
1413                 bDeformGroup *dg;
1414                 dg = BLI_findlink(&ob->defbase, vgroup_index.active);
1415                 if (dg->flag & DG_LOCK_WEIGHT) {
1416                         BKE_report(op->reports, RPT_WARNING, "Active group is locked, aborting");
1417                         return false;
1418                 }
1419                 if (vgroup_index.mirror != -1) {
1420                         dg = BLI_findlink(&ob->defbase, vgroup_index.mirror);
1421                         if (dg->flag & DG_LOCK_WEIGHT) {
1422                                 BKE_report(op->reports, RPT_WARNING, "Mirror group is locked, aborting");
1423                                 return false;
1424                         }
1425                 }
1426         }
1427
1428         /* check that multipaint groups are unlocked */
1429         defbase_tot = BLI_listbase_count(&ob->defbase);
1430         defbase_sel = BKE_object_defgroup_selected_get(ob, defbase_tot, &defbase_tot_sel);
1431
1432         if (ts->multipaint && defbase_tot_sel > 1) {
1433                 int i;
1434                 bDeformGroup *dg;
1435
1436                 if (me->editflag & ME_EDIT_MIRROR_X) {
1437                         BKE_object_defgroup_mirror_selection(ob, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
1438                 }
1439
1440                 for (i = 0; i < defbase_tot; i++) {
1441                         if (defbase_sel[i]) {
1442                                 dg = BLI_findlink(&ob->defbase, i);
1443                                 if (dg->flag & DG_LOCK_WEIGHT) {
1444                                         BKE_report(op->reports, RPT_WARNING, "Multipaint group is locked, aborting");
1445                                         MEM_freeN(defbase_sel);
1446                                         return false;
1447                                 }
1448                         }
1449                 }
1450         }
1451
1452         /* ALLOCATIONS! no return after this line */
1453         /* make mode data storage */
1454         wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
1455         paint_stroke_set_mode_data(stroke, wpd);
1456         ED_view3d_viewcontext_init(C, &wpd->vc);
1457         view_angle_limits_init(&wpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
1458                                (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
1459
1460         wpd->active.index = vgroup_index.active;
1461         wpd->mirror.index = vgroup_index.mirror;
1462
1463         /* multipaint */
1464         wpd->defbase_tot = defbase_tot;
1465         wpd->defbase_sel = defbase_sel;
1466         wpd->defbase_tot_sel = defbase_tot_sel > 1 ? defbase_tot_sel : 1;
1467         wpd->do_multipaint = (ts->multipaint && defbase_tot_sel > 1);
1468
1469         /* set up auto-normalize, and generate map for detecting which
1470          * vgroups affect deform bones */
1471         wpd->lock_flags = BKE_object_defgroup_lock_flags_get(ob, wpd->defbase_tot);
1472         if (ts->auto_normalize || ts->multipaint || wpd->lock_flags) {
1473                 wpd->vgroup_validmap = BKE_object_defgroup_validmap_get(ob, wpd->defbase_tot);
1474         }
1475
1476         if (wpd->do_multipaint && ts->auto_normalize) {
1477                 bool *tmpflags;
1478                 tmpflags = MEM_mallocN(sizeof(bool) * defbase_tot, __func__);
1479                 if (wpd->lock_flags) {
1480                         BLI_array_binary_or(tmpflags, wpd->defbase_sel, wpd->lock_flags, wpd->defbase_tot);
1481                 }
1482                 else {
1483                         memcpy(tmpflags, wpd->defbase_sel, sizeof(*tmpflags) * wpd->defbase_tot);
1484                 }
1485                 wpd->active.lock = tmpflags;
1486         }
1487         else if (ts->auto_normalize) {
1488                 bool *tmpflags;
1489
1490                 tmpflags = wpd->lock_flags ?
1491                         MEM_dupallocN(wpd->lock_flags) :
1492                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1493                 tmpflags[wpd->active.index] = true;
1494                 wpd->active.lock = tmpflags;
1495
1496                 tmpflags = wpd->lock_flags ?
1497                         MEM_dupallocN(wpd->lock_flags) :
1498                         MEM_callocN(sizeof(bool) * defbase_tot, __func__);
1499                 tmpflags[(wpd->mirror.index != -1) ? wpd->mirror.index : wpd->active.index] = true;
1500                 wpd->mirror.lock = tmpflags;
1501         }
1502
1503         if (ELEM(vp->paint.brush->vertexpaint_tool, PAINT_BLEND_SMEAR, PAINT_BLEND_BLUR)) {
1504                 wpd->precomputed_weight = MEM_mallocN(sizeof(float) * me->totvert, __func__);
1505         }
1506
1507         /* If not previously created, create vertex/weight paint mode session data */
1508         vertex_paint_init_session(scene, ob);
1509         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
1510         vertex_paint_init_session_data(ts, ob);
1511
1512         if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
1513                 MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
1514                 for (int i = 0; i < me->totvert; i++, dv++) {
1515                         /* Use to show this isn't initialized, never apply to the mesh data. */
1516                         dv->flag = 1;
1517                 }
1518         }
1519
1520         return true;
1521 }
1522
1523 static float dot_vf3vs3(const float brushNormal[3], const short vertexNormal[3])
1524 {
1525         float normal[3];
1526         normal_short_to_float_v3(normal, vertexNormal);
1527         return dot_v3v3(brushNormal, normal);
1528 }
1529
1530 static void get_brush_alpha_data(
1531         const Scene *scene, const SculptSession *ss, const Brush *brush,
1532         float *r_brush_size_pressure, float *r_brush_alpha_value, float *r_brush_alpha_pressure)
1533 {
1534         *r_brush_size_pressure =
1535                 BKE_brush_size_get(scene, brush) *
1536                 (BKE_brush_use_size_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1537         *r_brush_alpha_value =
1538                 BKE_brush_alpha_get(scene, brush);
1539         *r_brush_alpha_pressure =
1540                 (BKE_brush_use_alpha_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
1541 }
1542
1543 static float wpaint_get_active_weight(const MDeformVert *dv, const WeightPaintInfo *wpi)
1544 {
1545         if (wpi->do_multipaint) {
1546                 float weight = BKE_defvert_multipaint_collective_weight(
1547                      dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
1548
1549                 CLAMP(weight, 0.0f, 1.0f);
1550                 return weight;
1551         }
1552         else {
1553                 return defvert_find_weight(dv, wpi->active.index);
1554         }
1555 }
1556
1557 static void do_wpaint_precompute_weight_cb_ex(
1558         void *__restrict userdata,
1559         const int n,
1560         const ParallelRangeTLS *__restrict UNUSED(tls))
1561 {
1562         SculptThreadedTaskData *data = userdata;
1563         const MDeformVert *dv = &data->me->dvert[n];
1564
1565         data->wpd->precomputed_weight[n] = wpaint_get_active_weight(dv, data->wpi);
1566 }
1567
1568 static void precompute_weight_values(
1569         bContext *C, Object *ob, Brush *brush, struct WPaintData *wpd, WeightPaintInfo *wpi, Mesh *me)
1570 {
1571         if (wpd->precomputed_weight_ready && !brush_use_accumulate(brush))
1572                 return;
1573
1574         /* threaded loop over vertices */
1575         SculptThreadedTaskData data = {
1576                 .C = C, .ob = ob, .wpd = wpd, .wpi = wpi, .me = me,
1577         };
1578
1579         ParallelRangeSettings settings;
1580         BLI_parallel_range_settings_defaults(&settings);
1581         BLI_task_parallel_range(
1582                 0, me->totvert,
1583                 &data,
1584                 do_wpaint_precompute_weight_cb_ex,
1585                 &settings);
1586
1587         wpd->precomputed_weight_ready = true;
1588 }
1589
1590 static void do_wpaint_brush_blur_task_cb_ex(
1591         void *__restrict userdata,
1592         const int n,
1593         const ParallelRangeTLS *__restrict UNUSED(tls))
1594 {
1595         SculptThreadedTaskData *data = userdata;
1596         SculptSession *ss = data->ob->sculpt;
1597         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1598         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1599
1600         const Brush *brush = data->brush;
1601         const StrokeCache *cache = ss->cache;
1602         Scene *scene = CTX_data_scene(data->C);
1603
1604         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1605         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1606         const bool use_normal = vwpaint_use_normal(data->vp);
1607         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1608         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1609
1610         SculptBrushTest test;
1611         SculptBrushTestFn sculpt_brush_test_sq_fn =
1612                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1613         const float *sculpt_normal_frontface =
1614                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1615
1616         /* For each vertex */
1617         PBVHVertexIter vd;
1618         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1619         {
1620                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1621                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1622                         /* For grid based pbvh, take the vert whose loop coopresponds to the current grid.
1623                          * Otherwise, take the current vert. */
1624                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1625                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1626                         const char v_flag = data->me->mvert[v_index].flag;
1627                         /* If the vertex is selected */
1628                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1629                                 /* Get the average poly weight */
1630                                 int total_hit_loops = 0;
1631                                 float weight_final = 0.0f;
1632                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1633                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1634                                         const MPoly *mp = &data->me->mpoly[p_index];
1635
1636                                         total_hit_loops += mp->totloop;
1637                                         for (int k = 0; k < mp->totloop; k++) {
1638                                                 const int l_index = mp->loopstart + k;
1639                                                 const MLoop *ml = &data->me->mloop[l_index];
1640                                                 weight_final += data->wpd->precomputed_weight[ml->v];
1641                                         }
1642                                 }
1643
1644                                 /* Apply the weight to the vertex. */
1645                                 if (total_hit_loops != 0) {
1646                                         float brush_strength = cache->bstrength;
1647                                         const float angle_cos = (use_normal && vd.no) ?
1648                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1649                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1650                                              (angle_cos > 0.0f)) &&
1651                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1652                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1653                                         {
1654                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1655                                                 const float final_alpha =
1656                                                         brush_fade * brush_strength *
1657                                                         grid_alpha * brush_alpha_pressure;
1658
1659                                                 if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1660                                                         if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1661                                                                 ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1662                                                         }
1663                                                         else {
1664                                                                 continue;
1665                                                         }
1666                                                 }
1667
1668                                                 weight_final /= total_hit_loops;
1669                                                 /* Only paint visable verts */
1670                                                 do_weight_paint_vertex(
1671                                                         data->vp, data->ob, data->wpi,
1672                                                         v_index, final_alpha, weight_final);
1673                                         }
1674                                 }
1675                         }
1676                 }
1677         }
1678         BKE_pbvh_vertex_iter_end;
1679 }
1680
1681 static void do_wpaint_brush_smear_task_cb_ex(
1682         void *__restrict userdata,
1683         const int n,
1684         const ParallelRangeTLS *__restrict UNUSED(tls))
1685 {
1686         SculptThreadedTaskData *data = userdata;
1687         SculptSession *ss = data->ob->sculpt;
1688         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1689         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
1690
1691         const Brush *brush = data->brush;
1692         const Scene *scene = CTX_data_scene(data->C);
1693         const StrokeCache *cache = ss->cache;
1694         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1695         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1696         const bool use_normal = vwpaint_use_normal(data->vp);
1697         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1698         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1699         float brush_dir[3];
1700
1701         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
1702         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
1703
1704         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
1705
1706                 SculptBrushTest test;
1707                 SculptBrushTestFn sculpt_brush_test_sq_fn =
1708                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1709                 const float *sculpt_normal_frontface =
1710                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1711
1712                 /* For each vertex */
1713                 PBVHVertexIter vd;
1714                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1715                 {
1716                         /* Test to see if the vertex coordinates are within the spherical brush region. */
1717                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1718                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
1719                                  * Otherwise, take the current vert. */
1720                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1721                                 const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1722                                 const MVert *mv_curr = &data->me->mvert[v_index];
1723
1724                                 /* If the vertex is selected */
1725                                 if (!(use_face_sel || use_vert_sel) || mv_curr->flag & SELECT) {
1726                                         float brush_strength = cache->bstrength;
1727                                         const float angle_cos = (use_normal && vd.no) ?
1728                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1729                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1730                                              (angle_cos > 0.0f)) &&
1731                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1732                                              view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1733                                         {
1734                                                 bool do_color = false;
1735                                                 /* Minimum dot product between brush direction and current
1736                                                  * to neighbor direction is 0.0, meaning orthogonal. */
1737                                                 float stroke_dot_max = 0.0f;
1738
1739                                                 /* Get the color of the loop in the opposite direction of the brush movement
1740                                                  * (this callback is specifically for smear.) */
1741                                                 float weight_final = 0.0;
1742                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
1743                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
1744                                                         const MPoly *mp = &data->me->mpoly[p_index];
1745                                                         const MLoop *ml_other = &data->me->mloop[mp->loopstart];
1746                                                         for (int k = 0; k < mp->totloop; k++, ml_other++) {
1747                                                                 const uint v_other_index = ml_other->v;
1748                                                                 if (v_other_index != v_index) {
1749                                                                         const MVert *mv_other = &data->me->mvert[v_other_index];
1750
1751                                                                         /* Get the direction from the selected vert to the neighbor. */
1752                                                                         float other_dir[3];
1753                                                                         sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
1754                                                                         project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
1755
1756                                                                         normalize_v3(other_dir);
1757
1758                                                                         const float stroke_dot = dot_v3v3(other_dir, brush_dir);
1759
1760                                                                         if (stroke_dot > stroke_dot_max) {
1761                                                                                 stroke_dot_max = stroke_dot;
1762                                                                                 weight_final = data->wpd->precomputed_weight[v_other_index];
1763                                                                                 do_color = true;
1764                                                                         }
1765                                                                 }
1766                                                         }
1767                                                 }
1768                                                 /* Apply weight to vertex */
1769                                                 if (do_color) {
1770                                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1771                                                         const float final_alpha =
1772                                                                 brush_fade * brush_strength *
1773                                                                 grid_alpha * brush_alpha_pressure;
1774
1775                                                         if (final_alpha <= 0.0f)
1776                                                                 continue;
1777
1778                                                         do_weight_paint_vertex(
1779                                                                 data->vp, data->ob, data->wpi,
1780                                                                 v_index, final_alpha, (float)weight_final);
1781                                                 }
1782                                         }
1783                                 }
1784                         }
1785                 }
1786                 BKE_pbvh_vertex_iter_end;
1787         }
1788 }
1789
1790 static void do_wpaint_brush_draw_task_cb_ex(
1791         void *__restrict userdata,
1792         const int n,
1793         const ParallelRangeTLS *__restrict UNUSED(tls))
1794 {
1795         SculptThreadedTaskData *data = userdata;
1796         SculptSession *ss = data->ob->sculpt;
1797         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1798         const Scene *scene = CTX_data_scene(data->C);
1799
1800         const Brush *brush = data->brush;
1801         const StrokeCache *cache = ss->cache;
1802         /* note: normally `BKE_brush_weight_get(scene, brush)` is used,
1803          * however in this case we calculate a new weight each time. */
1804         const float paintweight = data->strength;
1805         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
1806         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
1807         const bool use_normal = vwpaint_use_normal(data->vp);
1808         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1809         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1810
1811         SculptBrushTest test;
1812         SculptBrushTestFn sculpt_brush_test_sq_fn =
1813                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1814         const float *sculpt_normal_frontface =
1815                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1816
1817         /* For each vertex */
1818         PBVHVertexIter vd;
1819         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1820         {
1821                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1822                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1823                         /* Note: grids are 1:1 with corners (aka loops).
1824                          * For multires, take the vert whose loop cooresponds to the current grid.
1825                          * Otherwise, take the current vert. */
1826                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1827                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1828
1829                         const char v_flag = data->me->mvert[v_index].flag;
1830                         /* If the vertex is selected */
1831                         if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1832                                 float brush_strength = cache->bstrength;
1833                                 const float angle_cos = (use_normal && vd.no) ?
1834                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1835                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
1836                                      (angle_cos > 0.0f)) &&
1837                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
1838                                      view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
1839                                 {
1840                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
1841                                         const float final_alpha = brush_fade * brush_strength * grid_alpha * brush_alpha_pressure;
1842
1843                                         if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
1844                                                 if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
1845                                                         ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
1846                                                 }
1847                                                 else {
1848                                                         continue;
1849                                                 }
1850                                         }
1851
1852                                         do_weight_paint_vertex(
1853                                                 data->vp, data->ob, data->wpi,
1854                                                 v_index, final_alpha, paintweight);
1855                                 }
1856                         }
1857                 }
1858         }
1859         BKE_pbvh_vertex_iter_end;
1860 }
1861
1862 static void do_wpaint_brush_calc_average_weight_cb_ex(
1863         void *__restrict userdata,
1864         const int n,
1865         const ParallelRangeTLS *__restrict UNUSED(tls))
1866 {
1867         SculptThreadedTaskData *data = userdata;
1868         SculptSession *ss = data->ob->sculpt;
1869         StrokeCache *cache = ss->cache;
1870         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
1871
1872         const bool use_normal = vwpaint_use_normal(data->vp);
1873         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
1874         const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
1875
1876         struct WPaintAverageAccum *accum = (struct WPaintAverageAccum *)data->custom_data + n;
1877         accum->len = 0;
1878         accum->value = 0.0;
1879
1880         SculptBrushTest test;
1881         SculptBrushTestFn sculpt_brush_test_sq_fn =
1882                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
1883         const float *sculpt_normal_frontface =
1884                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
1885
1886         /* For each vertex */
1887         PBVHVertexIter vd;
1888         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1889         {
1890                 /* Test to see if the vertex coordinates are within the spherical brush region. */
1891                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
1892                         const float angle_cos = (use_normal && vd.no) ?
1893                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
1894                         if (angle_cos > 0.0 && BKE_brush_curve_strength(data->brush, sqrtf(test.dist), cache->radius) > 0.0) {
1895                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
1896                                 // const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
1897                                 const char v_flag = data->me->mvert[v_index].flag;
1898
1899                                 /* If the vertex is selected. */
1900                                 if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
1901                                         const MDeformVert *dv = &data->me->dvert[v_index];
1902                                         accum->len += 1;
1903                                         accum->value += wpaint_get_active_weight(dv, data->wpi);
1904                                 }
1905                         }
1906                 }
1907         }
1908         BKE_pbvh_vertex_iter_end;
1909 }
1910
1911 static void calculate_average_weight(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
1912 {
1913         struct WPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
1914         data->custom_data = accum;
1915
1916         ParallelRangeSettings settings;
1917         BLI_parallel_range_settings_defaults(&settings);
1918         settings.use_threading = ((data->sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
1919         BLI_task_parallel_range(
1920                 0, totnode,
1921                 data,
1922                 do_wpaint_brush_calc_average_weight_cb_ex,
1923                 &settings);
1924
1925         uint accum_len = 0;
1926         double accum_weight = 0.0;
1927         for (int i = 0; i < totnode; i++) {
1928                 accum_len += accum[i].len;
1929                 accum_weight += accum[i].value;
1930         }
1931         if (accum_len != 0) {
1932                 accum_weight /= accum_len;
1933                 data->strength = (float)accum_weight;
1934         }
1935
1936         MEM_SAFE_FREE(data->custom_data);  /* 'accum' */
1937 }
1938
1939
1940 static void wpaint_paint_leaves(
1941         bContext *C, Object *ob, Sculpt *sd, VPaint *vp, struct WPaintData *wpd, WeightPaintInfo *wpi,
1942         Mesh *me, PBVHNode **nodes, int totnode)
1943 {
1944         Scene *scene = CTX_data_scene(C);
1945         const Brush *brush = ob->sculpt->cache->brush;
1946
1947         /* threaded loop over nodes */
1948         SculptThreadedTaskData data = {
1949                 .sd = sd, .ob = ob, .brush = brush, .nodes = nodes, .vp = vp, .wpd = wpd, .wpi = wpi, .me = me, .C = C,
1950         };
1951
1952         /* Use this so average can modify its weight without touching the brush. */
1953         data.strength = BKE_brush_weight_get(scene, brush);
1954
1955         ParallelRangeSettings settings;
1956         BLI_parallel_range_settings_defaults(&settings);
1957         /* NOTE: current mirroring code cannot be run in parallel */
1958         settings.use_threading = !(me->editflag & ME_EDIT_MIRROR_X);
1959
1960         switch (brush->vertexpaint_tool) {
1961                 case PAINT_BLEND_AVERAGE:
1962                         calculate_average_weight(&data, nodes, totnode);
1963                         BLI_task_parallel_range(
1964                                 0, totnode,
1965                                 &data,
1966                                 do_wpaint_brush_draw_task_cb_ex,
1967                                 &settings);
1968                         break;
1969                 case PAINT_BLEND_SMEAR:
1970                         BLI_task_parallel_range(
1971                                 0, totnode,
1972                                 &data,
1973                                 do_wpaint_brush_smear_task_cb_ex,
1974                                 &settings);
1975                         break;
1976                 case PAINT_BLEND_BLUR:
1977                         BLI_task_parallel_range(
1978                                 0, totnode,
1979                                 &data,
1980                                 do_wpaint_brush_blur_task_cb_ex,
1981                                 &settings);
1982                         break;
1983                 default:
1984                         BLI_task_parallel_range(
1985                                 0, totnode,
1986                                 &data,
1987                                 do_wpaint_brush_draw_task_cb_ex,
1988                                 &settings);
1989                         break;
1990         }
1991 }
1992
1993 static PBVHNode **vwpaint_pbvh_gather_generic(
1994         Object *ob, VPaint *wp, Sculpt *sd, Brush *brush, int *r_totnode)
1995 {
1996         SculptSession *ss = ob->sculpt;
1997         const bool use_normal = vwpaint_use_normal(wp);
1998         PBVHNode **nodes = NULL;
1999
2000         /* Build a list of all nodes that are potentially within the brush's area of influence */
2001         if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
2002                 SculptSearchSphereData data = {
2003                         .ss = ss,
2004                         .sd = sd,
2005                         .radius_squared = ss->cache->radius_squared,
2006                         .original = true,
2007                 };
2008                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
2009                 if (use_normal) {
2010                         sculpt_pbvh_calc_area_normal(brush, ob, nodes, *r_totnode, true, ss->cache->sculpt_normal_symm);
2011                 }
2012                 else {
2013                         zero_v3(ss->cache->sculpt_normal_symm);
2014                 }
2015         }
2016         else {
2017                 struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
2018                 dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
2019                 SculptSearchCircleData data = {
2020                         .ss = ss,
2021                         .sd = sd,
2022                         .radius_squared = ss->cache->radius_squared,
2023                         .original = true,
2024                         .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
2025                 };
2026                 BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
2027                 if (use_normal) {
2028                         copy_v3_v3(ss->cache->sculpt_normal_symm, ss->cache->view_normal);
2029                 }
2030                 else {
2031                         zero_v3(ss->cache->sculpt_normal_symm);
2032                 }
2033         }
2034         return nodes;
2035 }
2036
2037 static void wpaint_do_paint(
2038         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
2039         Mesh *me, Brush *brush, const char symm, const int axis, const int i, const float angle)
2040 {
2041         SculptSession *ss = ob->sculpt;
2042         ss->cache->radial_symmetry_pass = i;
2043         sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
2044
2045         int totnode;
2046         PBVHNode **nodes = vwpaint_pbvh_gather_generic(ob, wp, sd, brush, &totnode);
2047
2048         wpaint_paint_leaves(C, ob, sd, wp, wpd, wpi, me, nodes, totnode);
2049
2050         if (nodes)
2051                 MEM_freeN(nodes);
2052 }
2053
2054 static void wpaint_do_radial_symmetry(
2055         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
2056         Mesh *me, Brush *brush, const char symm, const int axis)
2057 {
2058         for (int i = 1; i < wp->radial_symm[axis - 'X']; i++) {
2059                 const float angle = (2.0 * M_PI) * i / wp->radial_symm[axis - 'X'];
2060                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, symm, axis, i, angle);
2061         }
2062 }
2063
2064 /* near duplicate of: sculpt.c's, 'do_symmetrical_brush_actions' and 'vpaint_do_symmetrical_brush_actions'. */
2065 static void wpaint_do_symmetrical_brush_actions(
2066         bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi)
2067 {
2068         Brush *brush = BKE_paint_brush(&wp->paint);
2069         Mesh *me = ob->data;
2070         SculptSession *ss = ob->sculpt;
2071         StrokeCache *cache = ss->cache;
2072         const char symm = wp->paint.symmetry_flags & PAINT_SYMM_AXIS_ALL;
2073         int i = 0;
2074
2075         /* initial stroke */
2076         wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X', 0, 0);
2077         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X');
2078         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Y');
2079         wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Z');
2080
2081         cache->symmetry = symm;
2082
2083         /* 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 */
2084         for (i = 1; i <= symm; i++) {
2085                 if ((symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
2086                         cache->mirror_symmetry_pass = i;
2087                         cache->radial_symmetry_pass = 0;
2088                         sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
2089
2090                         if (i & (1 << 0)) {
2091                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X', 0, 0);
2092                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X');
2093                         }
2094                         if (i & (1 << 1)) {
2095                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y', 0, 0);
2096                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y');
2097                         }
2098                         if (i & (1 << 2)) {
2099                                 wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z', 0, 0);
2100                                 wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z');
2101                         }
2102                 }
2103         }
2104         copy_v3_v3(cache->true_last_location, cache->true_location);
2105         cache->is_last_valid = true;
2106 }
2107
2108 static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
2109 {
2110         Scene *scene = CTX_data_scene(C);
2111         ToolSettings *ts = CTX_data_tool_settings(C);
2112         VPaint *wp = ts->wpaint;
2113         Brush *brush = BKE_paint_brush(&wp->paint);
2114         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2115         ViewContext *vc;
2116         Object *ob = CTX_data_active_object(C);
2117
2118         SculptSession *ss = ob->sculpt;
2119         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
2120
2121         vwpaint_update_cache_variants(C, wp, ob, itemptr);
2122
2123         float mat[4][4];
2124         float mval[2];
2125
2126         const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
2127
2128         /* intentionally don't initialize as NULL, make sure we initialize all members below */
2129         WeightPaintInfo wpi;
2130
2131         /* cannot paint if there is no stroke data */
2132         if (wpd == NULL) {
2133                 /* XXX: force a redraw here, since even though we can't paint,
2134                  * at least view won't freeze until stroke ends */
2135                 ED_region_tag_redraw(CTX_wm_region(C));
2136                 return;
2137         }
2138
2139         vc = &wpd->vc;
2140         ob = vc->obact;
2141
2142         view3d_operator_needs_opengl(C);
2143         ED_view3d_init_mats_rv3d(ob, vc->rv3d);
2144
2145         /* load projection matrix */
2146         mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
2147
2148
2149         /* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
2150         wpi.defbase_tot =        wpd->defbase_tot;
2151         wpi.defbase_sel =        wpd->defbase_sel;
2152         wpi.defbase_tot_sel =    wpd->defbase_tot_sel;
2153
2154         wpi.defbase_tot_unsel =  wpi.defbase_tot - wpi.defbase_tot_sel;
2155         wpi.active =             wpd->active;
2156         wpi.mirror =             wpd->mirror;
2157         wpi.lock_flags =         wpd->lock_flags;
2158         wpi.vgroup_validmap =    wpd->vgroup_validmap;
2159         wpi.do_flip =            RNA_boolean_get(itemptr, "pen_flip");
2160         wpi.do_multipaint =      wpd->do_multipaint;
2161         wpi.do_auto_normalize =  ((ts->auto_normalize != 0) && (wpi.vgroup_validmap != NULL));
2162         wpi.brush_alpha_value =  brush_alpha_value;
2163         /* *** done setting up WeightPaintInfo *** */
2164
2165         if (wpd->precomputed_weight) {
2166                 precompute_weight_values(C, ob, brush, wpd, &wpi, ob->data);
2167         }
2168
2169         wpaint_do_symmetrical_brush_actions(C, ob, wp, sd, wpd, &wpi);
2170
2171         swap_m4m4(vc->rv3d->persmat, mat);
2172
2173         /* calculate pivot for rotation around seletion if needed */
2174         /* also needed for "View Selected" on last stroke */
2175         paint_last_stroke_update(scene, vc->ar, mval);
2176
2177         DAG_id_tag_update(ob->data, 0);
2178         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2179         swap_m4m4(wpd->vc.rv3d->persmat, mat);
2180
2181         rcti r;
2182         if (sculpt_get_redraw_rect(vc->ar, CTX_wm_region_view3d(C), ob, &r)) {
2183                 if (ss->cache) {
2184                         ss->cache->current_r = r;
2185                 }
2186
2187                 /* previous is not set in the current cache else
2188                  * the partial rect will always grow */
2189                 if (ss->cache) {
2190                         if (!BLI_rcti_is_empty(&ss->cache->previous_r))
2191                                 BLI_rcti_union(&r, &ss->cache->previous_r);
2192                 }
2193
2194                 r.xmin += vc->ar->winrct.xmin - 2;
2195                 r.xmax += vc->ar->winrct.xmin + 2;
2196                 r.ymin += vc->ar->winrct.ymin - 2;
2197                 r.ymax += vc->ar->winrct.ymin + 2;
2198
2199                 ss->partial_redraw = 1;
2200         }
2201         ED_region_tag_redraw_partial(vc->ar, &r);
2202 }
2203
2204 static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
2205 {
2206         Object *ob = CTX_data_active_object(C);
2207         struct WPaintData *wpd = paint_stroke_mode_data(stroke);
2208
2209         if (wpd) {
2210                 if (wpd->defbase_sel)
2211                         MEM_freeN((void *)wpd->defbase_sel);
2212                 if (wpd->vgroup_validmap)
2213                         MEM_freeN((void *)wpd->vgroup_validmap);
2214                 if (wpd->lock_flags)
2215                         MEM_freeN((void *)wpd->lock_flags);
2216                 if (wpd->active.lock)
2217                         MEM_freeN((void *)wpd->active.lock);
2218                 if (wpd->mirror.lock)
2219                         MEM_freeN((void *)wpd->mirror.lock);
2220                 if (wpd->precomputed_weight)
2221                         MEM_freeN(wpd->precomputed_weight);
2222
2223                 MEM_freeN(wpd);
2224         }
2225
2226         /* and particles too */
2227         if (ob->particlesystem.first) {
2228                 ParticleSystem *psys;
2229                 int i;
2230
2231                 for (psys = ob->particlesystem.first; psys; psys = psys->next) {
2232                         for (i = 0; i < PSYS_TOT_VG; i++) {
2233                                 if (psys->vgroup[i] == ob->actdef) {
2234                                         psys->recalc |= PSYS_RECALC_RESET;
2235                                         break;
2236                                 }
2237                         }
2238                 }
2239         }
2240
2241         DAG_id_tag_update(ob->data, 0);
2242
2243         WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
2244
2245         sculpt_cache_free(ob->sculpt->cache);
2246         ob->sculpt->cache = NULL;
2247 }
2248
2249
2250 static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2251 {
2252         int retval;
2253
2254         op->customdata = paint_stroke_new(
2255                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2256                 wpaint_stroke_update_step, NULL,
2257                 wpaint_stroke_done, event->type);
2258
2259         if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
2260                 paint_stroke_data_free(op);
2261                 return OPERATOR_FINISHED;
2262         }
2263         /* add modal handler */
2264         WM_event_add_modal_handler(C, op);
2265
2266         OPERATOR_RETVAL_CHECK(retval);
2267         BLI_assert(retval == OPERATOR_RUNNING_MODAL);
2268
2269         return OPERATOR_RUNNING_MODAL;
2270 }
2271
2272 static int wpaint_exec(bContext *C, wmOperator *op)
2273 {
2274         op->customdata = paint_stroke_new(
2275                 C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
2276                 wpaint_stroke_update_step, NULL,
2277                 wpaint_stroke_done, 0);
2278
2279         /* frees op->customdata */
2280         paint_stroke_exec(C, op);
2281
2282         return OPERATOR_FINISHED;
2283 }
2284
2285 static void wpaint_cancel(bContext *C, wmOperator *op)
2286 {
2287         Object *ob = CTX_data_active_object(C);
2288         if (ob->sculpt->cache) {
2289                 sculpt_cache_free(ob->sculpt->cache);
2290                 ob->sculpt->cache = NULL;
2291         }
2292
2293         paint_stroke_cancel(C, op);
2294 }
2295
2296 void PAINT_OT_weight_paint(wmOperatorType *ot)
2297 {
2298         /* identifiers */
2299         ot->name = "Weight Paint";
2300         ot->idname = "PAINT_OT_weight_paint";
2301         ot->description = "Paint a stroke in the current vertex group's weights";
2302
2303         /* api callbacks */
2304         ot->invoke = wpaint_invoke;
2305         ot->modal = paint_stroke_modal;
2306         ot->exec = wpaint_exec;
2307         ot->poll = weight_paint_poll;
2308         ot->cancel = wpaint_cancel;
2309
2310         /* flags */
2311         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2312
2313         paint_stroke_operator_properties(ot);
2314 }
2315
2316 /* ************ set / clear vertex paint mode ********** */
2317
2318 /**
2319  * \note Keep in sync with #wpaint_mode_toggle_exec
2320  */
2321 static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
2322 {
2323         Main *bmain = CTX_data_main(C);
2324         Object *ob = CTX_data_active_object(C);
2325         const int mode_flag = OB_MODE_VERTEX_PAINT;
2326         const bool is_mode_set = (ob->mode & mode_flag) != 0;
2327         Scene *scene = CTX_data_scene(C);
2328
2329         if (!is_mode_set) {
2330                 if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
2331                         return OPERATOR_CANCELLED;
2332                 }
2333         }
2334
2335         Mesh *me = BKE_mesh_from_object(ob);
2336
2337         /* toggle: end vpaint */
2338         if (is_mode_set) {
2339                 ED_object_vpaintmode_exit_ex(ob);
2340         }
2341         else {
2342                 wmWindowManager *wm = CTX_wm_manager(C);
2343                 ED_object_vpaintmode_enter_ex(bmain, wm, scene, ob);
2344         }
2345
2346         /* update modifier stack for mapping requirements */
2347         DAG_id_tag_update(&me->id, 0);
2348
2349         WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
2350
2351         return OPERATOR_FINISHED;
2352 }
2353
2354 void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
2355 {
2356         /* identifiers */
2357         ot->name = "Vertex Paint Mode";
2358         ot->idname = "PAINT_OT_vertex_paint_toggle";
2359         ot->description = "Toggle the vertex paint mode in 3D view";
2360
2361         /* api callbacks */
2362         ot->exec = vpaint_mode_toggle_exec;
2363         ot->poll = paint_poll_test;
2364
2365         /* flags */
2366         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
2367 }
2368
2369
2370
2371 /* ********************** vertex paint operator ******************* */
2372
2373 /* Implementation notes:
2374  *
2375  * Operator->invoke()
2376  * - validate context (add mcol)
2377  * - create customdata storage
2378  * - call paint once (mouse click)
2379  * - add modal handler
2380  *
2381  * Operator->modal()
2382  * - for every mousemove, apply vertex paint
2383  * - exit on mouse release, free customdata
2384  *   (return OPERATOR_FINISHED also removes handler and operator)
2385  *
2386  * For future:
2387  * - implement a stroke event (or mousemove with past positons)
2388  * - revise whether op->customdata should be added in object, in set_vpaint
2389  */
2390
2391 typedef struct PolyFaceMap {
2392         struct PolyFaceMap *next, *prev;
2393         int facenr;
2394 } PolyFaceMap;
2395
2396 struct VPaintData {
2397         ViewContext vc;
2398         struct NormalAnglePrecalc normal_angle_precalc;
2399
2400         uint paintcol;
2401
2402         struct VertProjHandle *vp_handle;
2403         struct DMCoNo *vertexcosnos;
2404
2405         /* modify 'me->mcol' directly, since the derived mesh is drawing from this
2406          * array, otherwise we need to refresh the modifier stack */
2407         bool use_fast_update;
2408
2409         /* loops tagged as having been painted, to apply shared vertex color
2410          * blending only to modified loops */
2411         bool *mlooptag;
2412
2413         bool is_texbrush;
2414
2415         /* Special storage for smear brush, avoid feedback loop - update each step. */
2416         struct {
2417                 uint *color_prev;
2418                 uint *color_curr;
2419         } smear;
2420 };
2421
2422 static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float mouse[2])
2423 {
2424         Scene *scene = CTX_data_scene(C);
2425         ToolSettings *ts = scene->toolsettings;
2426         struct PaintStroke *stroke = op->customdata;
2427         VPaint *vp = ts->vpaint;
2428         Brush *brush = BKE_paint_brush(&vp->paint);
2429         struct VPaintData *vpd;
2430         Object *ob = CTX_data_active_object(C);
2431         Mesh *me;
2432         SculptSession *ss = ob->sculpt;
2433
2434         /* context checks could be a poll() */
2435         me = BKE_mesh_from_object(ob);
2436         if (me == NULL || me->totpoly == 0)
2437                 return false;
2438
2439         ED_mesh_color_ensure(me, NULL);
2440         if (me->mloopcol == NULL)
2441                 return false;
2442
2443         /* make mode data storage */
2444         vpd = MEM_callocN(sizeof(*vpd), "VPaintData");
2445         paint_stroke_set_mode_data(stroke, vpd);
2446         ED_view3d_viewcontext_init(C, &vpd->vc);
2447         view_angle_limits_init(&vpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
2448                                (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
2449
2450         vpd->paintcol = vpaint_get_current_col(scene, vp);
2451
2452         vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
2453                            brush->mtex.tex;
2454
2455         /* are we painting onto a modified mesh?,
2456          * if not we can skip face map trickiness */
2457         if (vertex_paint_use_fast_update_check(ob)) {
2458                 vpd->use_fast_update = true;
2459 /*              printf("Fast update!\n");*/
2460         }
2461         else {
2462                 vpd->use_fast_update = false;
2463 /*              printf("No fast update!\n");*/
2464         }
2465
2466         /* to keep tracked of modified loops for shared vertex color blending */
2467         if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
2468                 vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
2469         }
2470
2471         if (brush->vertexpaint_tool == PAINT_BLEND_SMEAR) {
2472                 vpd->smear.color_prev = MEM_mallocN(sizeof(uint) * me->totloop, __func__);
2473                 memcpy(vpd->smear.color_prev, me->mloopcol, sizeof(uint) * me->totloop);
2474                 vpd->smear.color_curr = MEM_dupallocN(vpd->smear.color_prev);
2475         }
2476
2477         /* Create projection handle */
2478         if (vpd->is_texbrush) {
2479                 ob->sculpt->building_vp_handle = true;
2480                 vpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &vpd->vertexcosnos);
2481                 ob->sculpt->building_vp_handle = false;
2482         }
2483
2484         /* If not previously created, create vertex/weight paint mode session data */
2485         vertex_paint_init_session(scene, ob);
2486         vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
2487         vertex_paint_init_session_data(ts, ob);
2488
2489         if (ob->sculpt->mode.vpaint.previous_color != NULL) {
2490                 memset(ob->sculpt->mode.vpaint.previous_color, 0, sizeof(uint) * me->totloop);
2491         }
2492
2493         return 1;
2494 }
2495
2496 static void do_vpaint_brush_calc_average_color_cb_ex(
2497         void *__restrict userdata,
2498         const int n,
2499         const ParallelRangeTLS *__restrict UNUSED(tls))
2500 {
2501         SculptThreadedTaskData *data = userdata;
2502         SculptSession *ss = data->ob->sculpt;
2503         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2504         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2505
2506         StrokeCache *cache = ss->cache;
2507         uint *lcol = data->lcol;
2508         char *col;
2509         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2510
2511         struct VPaintAverageAccum *accum = (struct VPaintAverageAccum *)data->custom_data + n;
2512         accum->len = 0;
2513         memset(accum->value, 0, sizeof(accum->value));
2514
2515         SculptBrushTest test;
2516         SculptBrushTestFn sculpt_brush_test_sq_fn =
2517                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2518
2519         /* For each vertex */
2520         PBVHVertexIter vd;
2521         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2522         {
2523                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2524                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2525                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2526                         if (BKE_brush_curve_strength(data->brush, 0.0, cache->radius) > 0.0) {
2527                                 /* If the vertex is selected for painting. */
2528                                 const MVert *mv = &data->me->mvert[v_index];
2529                                 if (!use_vert_sel || mv->flag & SELECT) {
2530                                         accum->len += gmap->vert_to_loop[v_index].count;
2531                                         /* if a vertex is within the brush region, then add it's color to the blend. */
2532                                         for (int j = 0; j < gmap->vert_to_loop[v_index].count; j++) {
2533                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2534                                                 col = (char *)(&lcol[l_index]);
2535                                                 /* Color is squared to compensate the sqrt color encoding. */
2536                                                 accum->value[0] += col[0] * col[0];
2537                                                 accum->value[1] += col[1] * col[1];
2538                                                 accum->value[2] += col[2] * col[2];
2539                                         }
2540                                 }
2541                         }
2542                 }
2543         }
2544         BKE_pbvh_vertex_iter_end;
2545 }
2546
2547 static float tex_color_alpha_ubyte(
2548         SculptThreadedTaskData *data, const float v_co[3],
2549         uint *r_color)
2550 {
2551         float rgba[4];
2552         float rgba_br[3];
2553         tex_color_alpha(data->vp, &data->vpd->vc, v_co, rgba);
2554         rgb_uchar_to_float(rgba_br, (const uchar *)&data->vpd->paintcol);
2555         mul_v3_v3(rgba_br, rgba);
2556         rgb_float_to_uchar((uchar *)r_color, rgba_br);
2557         return rgba[3];
2558 }
2559
2560 static void do_vpaint_brush_draw_task_cb_ex(
2561         void *__restrict userdata,
2562         const int n,
2563         const ParallelRangeTLS *__restrict UNUSED(tls))
2564 {
2565         SculptThreadedTaskData *data = userdata;
2566         SculptSession *ss = data->ob->sculpt;
2567         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2568         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2569
2570         const Brush *brush = data->brush;
2571         const StrokeCache *cache = ss->cache;
2572         uint *lcol = data->lcol;
2573         const Scene *scene = CTX_data_scene(data->C);
2574         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2575         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2576         const bool use_normal = vwpaint_use_normal(data->vp);
2577         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2578         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2579
2580         SculptBrushTest test;
2581         SculptBrushTestFn sculpt_brush_test_sq_fn =
2582                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2583         const float *sculpt_normal_frontface =
2584                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2585
2586         /* For each vertex */
2587         PBVHVertexIter vd;
2588         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2589         {
2590                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2591                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2592                         /* Note: Grids are 1:1 with corners (aka loops).
2593                          * For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2594                          * Otherwise, take the current vert. */
2595                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2596                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2597                         const MVert *mv = &data->me->mvert[v_index];
2598
2599                         /* If the vertex is selected for painting. */
2600                         if (!use_vert_sel || mv->flag & SELECT) {
2601                                 /* Calc the dot prod. between ray norm on surf and current vert
2602                                  * (ie splash prevention factor), and only paint front facing verts. */
2603                                 float brush_strength = cache->bstrength;
2604                                 const float angle_cos = (use_normal && vd.no) ?
2605                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2606                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2607                                      (angle_cos > 0.0f)) &&
2608                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2609                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2610                                 {
2611                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2612                                         uint color_final = data->vpd->paintcol;
2613
2614                                         /* If we're painting with a texture, sample the texture color and alpha. */
2615                                         float tex_alpha = 1.0;
2616                                         if (data->vpd->is_texbrush) {
2617                                                 /* Note: we may want to paint alpha as vertex color alpha. */
2618                                                 tex_alpha = tex_color_alpha_ubyte(
2619                                                         data, data->vpd->vertexcosnos[v_index].co,
2620                                                         &color_final);
2621                                         }
2622                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2623                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2624                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2625                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2626                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2627                                                 const MPoly *mp = &data->me->mpoly[p_index];
2628                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2629                                                         uint color_orig = 0;  /* unused when array is NULL */
2630                                                         if (ss->mode.vpaint.previous_color != NULL) {
2631                                                                 /* Get the previous loop color */
2632                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2633                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2634                                                                 }
2635                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2636                                                         }
2637                                                         const float final_alpha =
2638                                                                 255 * brush_fade * brush_strength *
2639                                                                 tex_alpha * brush_alpha_pressure * grid_alpha;
2640
2641                                                         /* Mix the new color with the original based on final_alpha. */
2642                                                         lcol[l_index] = vpaint_blend(
2643                                                                 data->vp, lcol[l_index], color_orig, color_final,
2644                                                                 final_alpha, 255 * brush_strength);
2645                                                 }
2646                                         }
2647                                 }
2648                         }
2649                 }
2650         }
2651         BKE_pbvh_vertex_iter_end;
2652 }
2653
2654 static void do_vpaint_brush_blur_task_cb_ex(
2655         void *__restrict userdata,
2656         const int n,
2657         const ParallelRangeTLS *__restrict UNUSED(tls))
2658 {
2659         SculptThreadedTaskData *data = userdata;
2660         SculptSession *ss = data->ob->sculpt;
2661         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2662
2663         Scene *scene = CTX_data_scene(data->C);
2664         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2665         const Brush *brush = data->brush;
2666         const StrokeCache *cache = ss->cache;
2667         uint *lcol = data->lcol;
2668         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2669         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2670         const bool use_normal = vwpaint_use_normal(data->vp);
2671         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2672         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2673
2674         SculptBrushTest test;
2675         SculptBrushTestFn sculpt_brush_test_sq_fn =
2676                 sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2677         const float *sculpt_normal_frontface =
2678                 sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2679
2680         /* For each vertex */
2681         PBVHVertexIter vd;
2682         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2683         {
2684                 /* Test to see if the vertex coordinates are within the spherical brush region. */
2685                 if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2686                         /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2687                          * Otherwise, take the current vert. */
2688                         const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2689                         const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2690                         const MVert *mv = &data->me->mvert[v_index];
2691
2692                         /* If the vertex is selected for painting. */
2693                         if (!use_vert_sel || mv->flag & SELECT) {
2694                                 float brush_strength = cache->bstrength;
2695                                 const float angle_cos = (use_normal && vd.no) ?
2696                                         dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2697                                 if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2698                                      (angle_cos > 0.0f)) &&
2699                                     ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2700                                      view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2701                                 {
2702                                         const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2703
2704                                         /* Get the average poly color */
2705                                         uint color_final = 0;
2706                                         int total_hit_loops = 0;
2707                                         uint blend[4] = {0};
2708                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2709                                                 int p_index = gmap->vert_to_poly[v_index].indices[j];
2710                                                 const MPoly *mp = &data->me->mpoly[p_index];
2711                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2712                                                         total_hit_loops += mp->totloop;
2713                                                         for (int k = 0; k < mp->totloop; k++) {
2714                                                                 const uint l_index = mp->loopstart + k;
2715                                                                 const char *col = (const char *)(&lcol[l_index]);
2716                                                                 /* Color is squared to compensate the sqrt color encoding. */
2717                                                                 blend[0] += (uint)col[0] * (uint)col[0];
2718                                                                 blend[1] += (uint)col[1] * (uint)col[1];
2719                                                                 blend[2] += (uint)col[2] * (uint)col[2];
2720                                                                 blend[3] += (uint)col[3] * (uint)col[3];
2721                                                         }
2722                                                 }
2723                                         }
2724                                         if (total_hit_loops != 0) {
2725                                                 /* Use rgb^2 color averaging. */
2726                                                 char *col = (char *)(&color_final);
2727                                                 col[0] = round_fl_to_uchar(sqrtf(divide_round_i(blend[0], total_hit_loops)));
2728                                                 col[1] = round_fl_to_uchar(sqrtf(divide_round_i(blend[1], total_hit_loops)));
2729                                                 col[2] = round_fl_to_uchar(sqrtf(divide_round_i(blend[2], total_hit_loops)));
2730                                                 col[3] = round_fl_to_uchar(sqrtf(divide_round_i(blend[3], total_hit_loops)));
2731
2732                                                 /* For each poly owning this vert, paint each loop belonging to this vert. */
2733                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2734                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2735                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2736                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2737                                                         const MPoly *mp = &data->me->mpoly[p_index];
2738                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2739                                                                 uint color_orig = 0;  /* unused when array is NULL */
2740                                                                 if (ss->mode.vpaint.previous_color != NULL) {
2741                                                                         /* Get the previous loop color */
2742                                                                         if (ss->mode.vpaint.previous_color[l_index] == 0) {
2743                                                                                 ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2744                                                                         }
2745                                                                         color_orig = ss->mode.vpaint.previous_color[l_index];
2746                                                                 }
2747                                                                 const float final_alpha =
2748                                                                         255 * brush_fade * brush_strength *
2749                                                                         brush_alpha_pressure * grid_alpha;
2750                                                                 /* Mix the new color with the original
2751                                                                  * based on the brush strength and the curve. */
2752                                                                 lcol[l_index] = vpaint_blend(
2753                                                                         data->vp, lcol[l_index], color_orig, *((uint *)col),
2754                                                                         final_alpha, 255 * brush_strength);
2755                                                         }
2756                                                 }
2757                                         }
2758                                 }
2759                         }
2760                 }
2761         }
2762         BKE_pbvh_vertex_iter_end;
2763 }
2764
2765 static void do_vpaint_brush_smear_task_cb_ex(
2766         void *__restrict userdata,
2767         const int n,
2768         const ParallelRangeTLS *__restrict UNUSED(tls))
2769 {
2770         SculptThreadedTaskData *data = userdata;
2771         SculptSession *ss = data->ob->sculpt;
2772         CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
2773
2774         Scene *scene = CTX_data_scene(data->C);
2775         const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
2776         const Brush *brush = data->brush;
2777         const StrokeCache *cache = ss->cache;
2778         uint *lcol = data->lcol;
2779         float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
2780         get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
2781         float brush_dir[3];
2782         const bool use_normal = vwpaint_use_normal(data->vp);
2783         const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
2784         const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
2785
2786         sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
2787         project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
2788
2789         if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
2790
2791                 SculptBrushTest test;
2792                 SculptBrushTestFn sculpt_brush_test_sq_fn =
2793                         sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
2794                 const float *sculpt_normal_frontface =
2795                         sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
2796
2797                 /* For each vertex */
2798                 PBVHVertexIter vd;
2799                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2800                 {
2801                         /* Test to see if the vertex coordinates are within the spherical brush region. */
2802                         if (sculpt_brush_test_sq_fn(&test, vd.co)) {
2803                                 /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
2804                                  * Otherwise, take the current vert. */
2805                                 const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
2806                                 const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
2807                                 const MVert *mv_curr = &data->me->mvert[v_index];
2808
2809                                 /* if the vertex is selected for painting. */
2810                                 if (!use_vert_sel || mv_curr->flag & SELECT) {
2811                                         /* Calc the dot prod. between ray norm on surf and current vert
2812                                          * (ie splash prevention factor), and only paint front facing verts. */
2813                                         float brush_strength = cache->bstrength;
2814                                         const float angle_cos = (use_normal && vd.no) ?
2815                                                 dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
2816                                         if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
2817                                              (angle_cos > 0.0f)) &&
2818                                             ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
2819                                              view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
2820                                         {
2821                                                 const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
2822
2823                                                 bool do_color = false;
2824                                                 /* Minimum dot product between brush direction and current
2825                                                  * to neighbor direction is 0.0, meaning orthogonal. */
2826                                                 float stroke_dot_max = 0.0f;
2827
2828                                                 /* Get the color of the loop in the opposite direction of the brush movement */
2829                                                 uint color_final = 0;
2830                                                 for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2831                                                         const int p_index = gmap->vert_to_poly[v_index].indices[j];
2832                                                         const int l_index = gmap->vert_to_loop[v_index].indices[j];
2833                                                         BLI_assert(data->me->mloop[l_index].v == v_index);
2834                                                         UNUSED_VARS_NDEBUG(l_index);
2835                                                         const MPoly *mp = &data->me->mpoly[p_index];
2836                                                         if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2837                                                                 const MLoop *ml_other = &data->me->mloop[mp->loopstart];
2838                                                                 for (int k = 0; k < mp->totloop; k++, ml_other++) {
2839                                                                         const uint v_other_index = ml_other->v;
2840                                                                         if (v_other_index != v_index) {
2841                                                                                 const MVert *mv_other = &data->me->mvert[v_other_index];
2842
2843                                                                                 /* Get the direction from the selected vert to the neighbor. */
2844                                                                                 float other_dir[3];
2845                                                                                 sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
2846                                                                                 project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
2847
2848                                                                                 normalize_v3(other_dir);
2849
2850                                                                                 const float stroke_dot = dot_v3v3(other_dir, brush_dir);
2851
2852                                                                                 if (stroke_dot > stroke_dot_max) {
2853                                                                                         stroke_dot_max = stroke_dot;
2854                                                                                         color_final = data->vpd->smear.color_prev[mp->loopstart + k];
2855                                                                                         do_color = true;
2856                                                                                 }
2857                                                                         }
2858                                                                 }
2859                                                         }
2860                                                 }
2861
2862                                                 if (do_color) {
2863                                                         const float final_alpha =
2864                                                                 255 * brush_fade * brush_strength *
2865                                                                 brush_alpha_pressure * grid_alpha;
2866
2867                                                         /* For each poly owning this vert, paint each loop belonging to this vert. */
2868                                                         for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
2869                                                                 const int p_index = gmap->vert_to_poly[v_index].indices[j];
2870                                                                 const int l_index = gmap->vert_to_loop[v_index].indices[j];
2871                                                                 BLI_assert(data->me->mloop[l_index].v == v_index);
2872                                                                 const MPoly *mp = &data->me->mpoly[p_index];
2873                                                                 if (!use_face_sel || mp->flag & ME_FACE_SEL) {
2874                                                                         /* Get the previous loop color */
2875                                                                         uint color_orig = 0;  /* unused when array is NULL */
2876                                                                         if (ss->mode.vpaint.previous_color != NULL) {
2877                                                                                 /* Get the previous loop color */
2878                                                                                 if (ss->mode.vpaint.previous_color[l_index] == 0) {
2879                                                                                         ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
2880                                                                                 }
2881                                                                                 color_orig = ss->mode.vpaint.previous_color[l_index];
2882                                                                         }
2883                                                                         /* Mix the new color with the original
2884                                                                          * based on the brush strength and the curve. */
2885                                                                         lcol[l_index] = vpaint_blend(
2886                                                                                 data->vp, lcol[l_index], color_orig, color_final,
2887                                                                                 final_alpha, 255 * brush_strength);
2888
2889                                                                         data->vpd->smear.color_curr[l_index] = lcol[l_index];
2890                                                                 }
2891                                                         }
2892                                                 }
2893                                         }
2894                                 }
2895                         }
2896                 }
2897                 BKE_pbvh_vertex_iter_end;
2898         }
2899 }
2900
2901 static void calculate_average_color(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
2902 {
2903         struct VPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
2904         data->custom_data = accum;
2905
2906         ParallelRangeSettings settings;
2907         BLI_parallel_range_settings_defaults(&settings);
2908         BLI_task_parallel_range(
2909                 0, totnode,
2910                 data,
2911                 do_vpaint_brush_calc_average_color_cb_ex,
2912                 &settings);
2913
2914         uint accum_len = 0;
2915         uint accum_value[3] = {0};
2916         uchar blend[4] = {0};
2917         for (int i = 0; i < totnode; i++) {
2918                 accum_len += accum[i].len;