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