BMesh: make toolflags optional
[blender.git] / source / blender / editors / sculpt_paint / sculpt.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) 2006 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Jason Wilkins, Tom Musgrove.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  * Implements the Sculpt Mode tools
28  *
29  */
30
31 /** \file blender/editors/sculpt_paint/sculpt.c
32  *  \ingroup edsculpt
33  */
34
35
36 #include "MEM_guardedalloc.h"
37
38 #include "BLI_math.h"
39 #include "BLI_blenlib.h"
40 #include "BLI_dial.h"
41 #include "BLI_task.h"
42 #include "BLI_threads.h"
43 #include "BLI_utildefines.h"
44 #include "BLI_ghash.h"
45
46 #include "BLT_translation.h"
47
48 #include "DNA_customdata_types.h"
49 #include "DNA_mesh_types.h"
50 #include "DNA_meshdata_types.h"
51 #include "DNA_node_types.h"
52 #include "DNA_object_types.h"
53 #include "DNA_scene_types.h"
54 #include "DNA_brush_types.h"
55
56 #include "BKE_pbvh.h"
57 #include "BKE_brush.h"
58 #include "BKE_ccg.h"
59 #include "BKE_context.h"
60 #include "BKE_depsgraph.h"
61 #include "BKE_global.h"
62 #include "BKE_image.h"
63 #include "BKE_key.h"
64 #include "BKE_library.h"
65 #include "BKE_mesh.h"
66 #include "BKE_mesh_mapping.h"
67 #include "BKE_modifier.h"
68 #include "BKE_multires.h"
69 #include "BKE_paint.h"
70 #include "BKE_report.h"
71 #include "BKE_node.h"
72 #include "BKE_object.h"
73 #include "BKE_subsurf.h"
74 #include "BKE_colortools.h"
75
76 #include "WM_api.h"
77 #include "WM_types.h"
78
79 #include "ED_sculpt.h"
80 #include "ED_object.h"
81 #include "ED_screen.h"
82 #include "ED_view3d.h"
83 #include "paint_intern.h"
84 #include "sculpt_intern.h"
85
86 #include "RNA_access.h"
87 #include "RNA_define.h"
88
89 #include "GPU_buffers.h"
90 #include "GPU_extensions.h"
91
92 #include "UI_interface.h"
93 #include "UI_resources.h"
94
95 #include "bmesh.h"
96 #include "bmesh_tools.h"
97
98 #include <math.h>
99 #include <stdlib.h>
100 #include <string.h>
101
102 /** \name Tool Capabilities
103  *
104  * Avoid duplicate checks, internal logic only,
105  * share logic with #rna_def_sculpt_capabilities where possible.
106  *
107  * \{ */
108
109 /* Check if there are any active modifiers in stack (used for flushing updates at enter/exit sculpt mode) */
110 static bool sculpt_has_active_modifiers(Scene *scene, Object *ob)
111 {
112         ModifierData *md;
113         VirtualModifierData virtualModifierData;
114
115         md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
116
117         /* exception for shape keys because we can edit those */
118         for (; md; md = md->next) {
119                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime))
120                         return 1;
121         }
122
123         return 0;
124 }
125
126 static bool sculpt_tool_needs_original(const char sculpt_tool)
127 {
128         return ELEM(sculpt_tool,
129                     SCULPT_TOOL_GRAB,
130                     SCULPT_TOOL_ROTATE,
131                     SCULPT_TOOL_THUMB,
132                     SCULPT_TOOL_LAYER);
133 }
134
135 static bool sculpt_tool_is_proxy_used(const char sculpt_tool)
136 {
137         return ELEM(sculpt_tool,
138                     SCULPT_TOOL_SMOOTH,
139                     SCULPT_TOOL_LAYER);
140 }
141
142 /**
143  * Test whether the #StrokeCache.sculpt_normal needs update in #do_brush_action
144  */
145 static int sculpt_brush_needs_normal(const Brush *brush, float normal_weight)
146 {
147         return ((SCULPT_TOOL_HAS_NORMAL_WEIGHT(brush->sculpt_tool) &&
148                  (normal_weight > 0.0f)) ||
149
150                 ELEM(brush->sculpt_tool,
151                      SCULPT_TOOL_BLOB,
152                      SCULPT_TOOL_CREASE,
153                      SCULPT_TOOL_DRAW,
154                      SCULPT_TOOL_LAYER,
155                      SCULPT_TOOL_NUDGE,
156                      SCULPT_TOOL_ROTATE,
157                      SCULPT_TOOL_THUMB) ||
158
159                 (brush->mtex.brush_map_mode == MTEX_MAP_MODE_AREA));
160 }
161 /** \} */
162
163 static bool sculpt_brush_needs_rake_rotation(const Brush *brush)
164 {
165         return SCULPT_TOOL_HAS_RAKE(brush->sculpt_tool) && (brush->rake_factor != 0.0f);
166 }
167
168 /* Factor of brush to have rake point following behind
169  * (could be configurable but this is reasonable default). */
170 #define SCULPT_RAKE_BRUSH_FACTOR 0.25f
171
172 struct SculptRakeData {
173         float follow_dist;
174         float follow_co[3];
175 };
176
177 typedef enum StrokeFlags {
178         CLIP_X = 1,
179         CLIP_Y = 2,
180         CLIP_Z = 4
181 } StrokeFlags;
182
183 /* Cache stroke properties. Used because
184  * RNA property lookup isn't particularly fast.
185  *
186  * For descriptions of these settings, check the operator properties.
187  */
188 typedef struct StrokeCache {
189         /* Invariants */
190         float initial_radius;
191         float scale[3];
192         int flag;
193         float clip_tolerance[3];
194         float initial_mouse[2];
195
196         /* Variants */
197         float radius;
198         float radius_squared;
199         float true_location[3];
200         float location[3];
201
202         bool pen_flip;
203         bool invert;
204         float pressure;
205         float mouse[2];
206         float bstrength;
207         float normal_weight;  /* from brush (with optional override) */
208
209         /* The rest is temporary storage that isn't saved as a property */
210
211         bool first_time; /* Beginning of stroke may do some things special */
212
213         /* from ED_view3d_ob_project_mat_get() */
214         float projection_mat[4][4];
215
216         /* Clean this up! */
217         ViewContext *vc;
218         Brush *brush;
219
220         float special_rotation;
221         float grab_delta[3], grab_delta_symmetry[3];
222         float old_grab_location[3], orig_grab_location[3];
223
224         /* screen-space rotation defined by mouse motion */
225         float   rake_rotation[4], rake_rotation_symmetry[4];
226         bool is_rake_rotation_valid;
227         struct SculptRakeData rake_data;
228
229         int symmetry; /* Symmetry index between 0 and 7 bit combo 0 is Brush only;
230                        * 1 is X mirror; 2 is Y mirror; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
231         int mirror_symmetry_pass; /* the symmetry pass we are currently on between 0 and 7*/
232         float true_view_normal[3];
233         float view_normal[3];
234
235         /* sculpt_normal gets calculated by calc_sculpt_normal(), then the
236          * sculpt_normal_symm gets updated quickly with the usual symmetry
237          * transforms */
238         float sculpt_normal[3];
239         float sculpt_normal_symm[3];
240
241         /* Used for area texture mode, local_mat gets calculated by
242          * calc_brush_local_mat() and used in tex_strength(). */
243         float brush_local_mat[4][4];
244         
245         float plane_offset[3]; /* used to shift the plane around when doing tiled strokes */
246         int tile_pass;
247
248         float last_center[3];
249         int radial_symmetry_pass;
250         float symm_rot_mat[4][4];
251         float symm_rot_mat_inv[4][4];
252         bool original;
253         float anchored_location[3];
254
255         float vertex_rotation; /* amount to rotate the vertices when using rotate brush */
256         Dial *dial;
257         
258         char saved_active_brush_name[MAX_ID_NAME];
259         char saved_mask_brush_tool;
260         int saved_smooth_size; /* smooth tool copies the size of the current tool */
261         bool alt_smooth;
262
263         float plane_trim_squared;
264
265         bool supports_gravity;
266         float true_gravity_direction[3];
267         float gravity_direction[3];
268
269         rcti previous_r; /* previous redraw rectangle */
270         rcti current_r; /* current redraw rectangle */
271 } StrokeCache;
272
273 /************** Access to original unmodified vertex data *************/
274
275 typedef struct {
276         BMLog *bm_log;
277
278         SculptUndoNode *unode;
279         float (*coords)[3];
280         short (*normals)[3];
281         const float *vmasks;
282
283         /* Original coordinate, normal, and mask */
284         const float *co;
285         const short *no;
286         float mask;
287 } SculptOrigVertData;
288
289
290 /* Initialize a SculptOrigVertData for accessing original vertex data;
291  * handles BMesh, mesh, and multires */
292 static void sculpt_orig_vert_data_unode_init(SculptOrigVertData *data,
293                                              Object *ob,
294                                              SculptUndoNode *unode)
295 {
296         SculptSession *ss = ob->sculpt;
297         BMesh *bm = ss->bm;
298
299         memset(data, 0, sizeof(*data));
300         data->unode = unode;
301
302         if (bm) {
303                 data->bm_log = ss->bm_log;
304         }
305         else {
306                 data->coords = data->unode->co;
307                 data->normals = data->unode->no;
308                 data->vmasks = data->unode->mask;
309         }
310 }
311
312 /* Initialize a SculptOrigVertData for accessing original vertex data;
313  * handles BMesh, mesh, and multires */
314 static void sculpt_orig_vert_data_init(SculptOrigVertData *data,
315                                        Object *ob,
316                                        PBVHNode *node)
317 {
318         SculptUndoNode *unode;
319         unode = sculpt_undo_push_node(ob, node, SCULPT_UNDO_COORDS);
320         sculpt_orig_vert_data_unode_init(data, ob, unode);
321 }
322
323 /* Update a SculptOrigVertData for a particular vertex from the PBVH
324  * iterator */
325 static void sculpt_orig_vert_data_update(SculptOrigVertData *orig_data,
326                                          PBVHVertexIter *iter)
327 {
328         if (orig_data->unode->type == SCULPT_UNDO_COORDS) {
329                 if (orig_data->bm_log) {
330                         BM_log_original_vert_data(
331                                 orig_data->bm_log, iter->bm_vert,
332                                 &orig_data->co, &orig_data->no);
333                 }
334                 else {
335                         orig_data->co = orig_data->coords[iter->i];
336                         orig_data->no = orig_data->normals[iter->i];
337                 }
338         }
339         else if (orig_data->unode->type == SCULPT_UNDO_MASK) {
340                 if (orig_data->bm_log) {
341                         orig_data->mask = BM_log_original_mask(orig_data->bm_log, iter->bm_vert);
342                 }
343                 else {
344                         orig_data->mask = orig_data->vmasks[iter->i];
345                 }
346         }
347 }
348
349 static void sculpt_rake_data_update(struct SculptRakeData *srd, const float co[3])
350 {
351         float rake_dist = len_v3v3(srd->follow_co, co);
352         if (rake_dist > srd->follow_dist) {
353                 interp_v3_v3v3(srd->follow_co, srd->follow_co, co, rake_dist - srd->follow_dist);
354         }
355 }
356
357
358 static void sculpt_rake_rotate(
359         const SculptSession *ss, const float sculpt_co[3], const float v_co[3], float factor, float r_delta[3])
360 {
361         float vec_rot[3];
362
363 #if 0
364         /* lerp */
365         sub_v3_v3v3(vec_rot, v_co, sculpt_co);
366         mul_qt_v3(ss->cache->rake_rotation_symmetry, vec_rot);
367         add_v3_v3(vec_rot, sculpt_co);
368         sub_v3_v3v3(r_delta, vec_rot, v_co);
369         mul_v3_fl(r_delta, factor);
370 #else
371         /* slerp */
372         float q_interp[4];
373         sub_v3_v3v3(vec_rot, v_co, sculpt_co);
374
375         copy_qt_qt(q_interp, ss->cache->rake_rotation_symmetry);
376         mul_fac_qt_fl(q_interp, factor);
377         mul_qt_v3(q_interp, vec_rot);
378
379         add_v3_v3(vec_rot, sculpt_co);
380         sub_v3_v3v3(r_delta, vec_rot, v_co);
381 #endif
382
383 }
384
385 /**
386  * Align the grab delta to the brush normal.
387  *
388  * \param grab_delta: Typically from `ss->cache->grab_delta_symmetry`.
389  */
390 static void sculpt_project_v3_normal_align(SculptSession *ss, const float normal_weight, float grab_delta[3])
391 {
392         /* signed to support grabbing in (to make a hole) as well as out. */
393         const float len_signed = dot_v3v3(ss->cache->sculpt_normal_symm, grab_delta);
394
395         /* this scale effectively projects the offset so dragging follows the cursor,
396          * as the normal points towards the view, the scale increases. */
397         float len_view_scale;
398         {
399                 float view_aligned_normal[3];
400                 project_plane_v3_v3v3(view_aligned_normal, ss->cache->sculpt_normal_symm, ss->cache->view_normal);
401                 len_view_scale = fabsf(dot_v3v3(view_aligned_normal, ss->cache->sculpt_normal_symm));
402                 len_view_scale = (len_view_scale > FLT_EPSILON) ? 1.0f / len_view_scale : 1.0f;
403         }
404
405         mul_v3_fl(grab_delta, 1.0f - normal_weight);
406         madd_v3_v3fl(grab_delta, ss->cache->sculpt_normal_symm, (len_signed * normal_weight) * len_view_scale);
407 }
408
409
410 /** \name SculptProjectVector
411  *
412  * Fast-path for #project_plane_v3_v3v3
413  *
414  * \{ */
415
416 typedef struct SculptProjectVector {
417         float plane[3];
418         float len_sq;
419         float len_sq_inv_neg;
420         bool  is_valid;
421
422 } SculptProjectVector;
423
424 /**
425  * \param plane  Direction, can be any length.
426  */
427 static void sculpt_project_v3_cache_init(
428         SculptProjectVector *spvc, const float plane[3])
429 {
430         copy_v3_v3(spvc->plane, plane);
431         spvc->len_sq = len_squared_v3(spvc->plane);
432         spvc->is_valid = (spvc->len_sq > FLT_EPSILON);
433         spvc->len_sq_inv_neg = (spvc->is_valid) ? -1.0f / spvc->len_sq : 0.0f;
434 }
435
436 /**
437  * Calculate the projection.
438  */
439 static void sculpt_project_v3(
440         const SculptProjectVector *spvc, const float vec[3],
441         float r_vec[3])
442 {
443 #if 0
444         project_plane_v3_v3v3(r_vec, vec, spvc->plane);
445 #else
446         /* inline the projection, cache `-1.0 / dot_v3_v3(v_proj, v_proj)` */
447         madd_v3_v3fl(r_vec, spvc->plane, dot_v3v3(vec, spvc->plane) * spvc->len_sq_inv_neg);
448 #endif
449 }
450
451 /** \} */
452
453
454 /**********************************************************************/
455
456 /* Returns true if the stroke will use dynamic topology, false
457  * otherwise.
458  *
459  * Factors: some brushes like grab cannot do dynamic topology.
460  * Others, like smooth, are better without. Same goes for alt-
461  * key smoothing. */
462 static bool sculpt_stroke_is_dynamic_topology(
463         const SculptSession *ss, const Brush *brush)
464 {
465         return ((BKE_pbvh_type(ss->pbvh) == PBVH_BMESH) &&
466
467                 (!ss->cache || (!ss->cache->alt_smooth)) &&
468
469                 /* Requires mesh restore, which doesn't work with
470                  * dynamic-topology */
471                 !(brush->flag & BRUSH_ANCHORED) &&
472                 !(brush->flag & BRUSH_DRAG_DOT) &&
473
474                 SCULPT_TOOL_HAS_DYNTOPO(brush->sculpt_tool));
475 }
476
477 /*** paint mesh ***/
478
479 /* Single struct used by all BLI_task threaded callbacks, let's avoid adding 10's of those... */
480 typedef struct SculptThreadedTaskData {
481         Sculpt *sd;
482         Object *ob;
483         Brush *brush;
484         PBVHNode **nodes;
485         int totnode;
486
487         /* Data specific to some callbacks. */
488         /* Note: even if only one or two of those are used at a time, keeping them separated, names help figuring out
489          *       what it is, and memory overhead is ridiculous anyway... */
490         float flippedbstrength;
491         float angle;
492         float strength;
493         bool smooth_mask;
494         bool has_bm_orco;
495
496         SculptProjectVector *spvc;
497         float *offset;
498         float *grab_delta;
499         float *cono;
500         float *area_no;
501         float *area_no_sp;
502         float *area_co;
503         float (*mat)[4];
504         float (*vertCos)[3];
505
506         /* 0=towards view, 1=flipped */
507         float (*area_cos)[3];
508         float (*area_nos)[3];
509         int *count;
510
511         ThreadMutex mutex;
512 } SculptThreadedTaskData;
513
514 static void paint_mesh_restore_co_task_cb(void *userdata, const int n)
515 {
516         SculptThreadedTaskData *data = userdata;
517         SculptSession *ss = data->ob->sculpt;
518
519         SculptUndoNode *unode;
520         SculptUndoType type = (data->brush->sculpt_tool == SCULPT_TOOL_MASK ? SCULPT_UNDO_MASK : SCULPT_UNDO_COORDS);
521
522         if (ss->bm) {
523                 unode = sculpt_undo_push_node(data->ob, data->nodes[n], type);
524         }
525         else {
526                 unode = sculpt_undo_get_node(data->nodes[n]);
527         }
528
529         if (unode) {
530                 PBVHVertexIter vd;
531                 SculptOrigVertData orig_data;
532
533                 sculpt_orig_vert_data_unode_init(&orig_data, data->ob, unode);
534
535                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
536                 {
537                         sculpt_orig_vert_data_update(&orig_data, &vd);
538
539                         if (orig_data.unode->type == SCULPT_UNDO_COORDS) {
540                                 copy_v3_v3(vd.co, orig_data.co);
541                                 if (vd.no)
542                                         copy_v3_v3_short(vd.no, orig_data.no);
543                                 else
544                                         normal_short_to_float_v3(vd.fno, orig_data.no);
545                         }
546                         else if (orig_data.unode->type == SCULPT_UNDO_MASK) {
547                                 *vd.mask = orig_data.mask;
548                         }
549
550                         if (vd.mvert)
551                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
552                 }
553                 BKE_pbvh_vertex_iter_end;
554
555                 BKE_pbvh_node_mark_update(data->nodes[n]);
556         }
557 }
558
559 static void paint_mesh_restore_co(Sculpt *sd, Object *ob)
560 {
561         SculptSession *ss = ob->sculpt;
562         Brush *brush = BKE_paint_brush(&sd->paint);
563
564         PBVHNode **nodes;
565         int totnode;
566
567         BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
568
569         /* Disable OpenMP when dynamic-topology is enabled. Otherwise, new entries might be inserted by
570          * sculpt_undo_push_node() into the GHash used internally by BM_log_original_vert_co() by a different thread.
571          * See T33787. */
572         SculptThreadedTaskData data = {
573                 .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
574         };
575
576         BLI_task_parallel_range(
577                     0, totnode, &data, paint_mesh_restore_co_task_cb,
578                     ((sd->flags & SCULPT_USE_OPENMP) && !ss->bm && totnode > SCULPT_THREADED_LIMIT));
579
580         if (nodes)
581                 MEM_freeN(nodes);
582 }
583
584 /*** BVH Tree ***/
585
586 static void sculpt_extend_redraw_rect_previous(Object *ob, rcti *rect)
587 {
588         /* expand redraw rect with redraw rect from previous step to
589          * prevent partial-redraw issues caused by fast strokes. This is
590          * needed here (not in sculpt_flush_update) as it was before
591          * because redraw rectangle should be the same in both of
592          * optimized PBVH draw function and 3d view redraw (if not -- some
593          * mesh parts could disappear from screen (sergey) */
594         SculptSession *ss = ob->sculpt;
595
596         if (ss->cache) {
597                 if (!BLI_rcti_is_empty(&ss->cache->previous_r))
598                         BLI_rcti_union(rect, &ss->cache->previous_r);
599         }
600 }
601
602 /* Get a screen-space rectangle of the modified area */
603 static bool sculpt_get_redraw_rect(ARegion *ar, RegionView3D *rv3d,
604                                    Object *ob, rcti *rect)
605 {
606         PBVH *pbvh = ob->sculpt->pbvh;
607         float bb_min[3], bb_max[3];
608
609         if (!pbvh)
610                 return 0;
611
612         BKE_pbvh_redraw_BB(pbvh, bb_min, bb_max);
613
614         /* convert 3D bounding box to screen space */
615         if (!paint_convert_bb_to_rect(rect,
616                                       bb_min,
617                                       bb_max,
618                                       ar,
619                                       rv3d,
620                                       ob))
621         {
622                 return 0;
623         }
624
625
626         return 1;
627 }
628
629 void ED_sculpt_redraw_planes_get(float planes[4][4], ARegion *ar,
630                                  RegionView3D *rv3d, Object *ob)
631 {
632         PBVH *pbvh = ob->sculpt->pbvh;
633         /* copy here, original will be used below */
634         rcti rect = ob->sculpt->cache->current_r;
635
636         sculpt_extend_redraw_rect_previous(ob, &rect);
637
638         paint_calc_redraw_planes(planes, ar, rv3d, ob, &rect);
639
640         /* we will draw this rect, so now we can set it as the previous partial rect.
641          * Note that we don't update with the union of previous/current (rect), only with
642          * the current. Thus we avoid the rectangle needlessly growing to include
643          * all the stroke area */
644         ob->sculpt->cache->previous_r = ob->sculpt->cache->current_r;
645
646         /* clear redraw flag from nodes */
647         if (pbvh)
648                 BKE_pbvh_update(pbvh, PBVH_UpdateRedraw, NULL);
649 }
650
651 /************************ Brush Testing *******************/
652
653 typedef struct SculptBrushTest {
654         float radius_squared;
655         float location[3];
656         float dist;
657         int mirror_symmetry_pass;
658
659         /* View3d clipping - only set rv3d for clipping */
660         RegionView3D *clip_rv3d;
661 } SculptBrushTest;
662
663 static void sculpt_brush_test_init(SculptSession *ss, SculptBrushTest *test)
664 {
665         RegionView3D *rv3d = ss->cache->vc->rv3d;
666
667         test->radius_squared = ss->cache->radius_squared;
668         copy_v3_v3(test->location, ss->cache->location);
669         test->dist = 0.0f;   /* just for initialize */
670
671         test->mirror_symmetry_pass = ss->cache->mirror_symmetry_pass;
672
673         if (rv3d->rflag & RV3D_CLIPPING) {
674                 test->clip_rv3d = rv3d;
675         }
676         else {
677                 test->clip_rv3d = NULL;
678         }
679 }
680
681 BLI_INLINE bool sculpt_brush_test_clipping(const SculptBrushTest *test, const float co[3])
682 {
683         RegionView3D *rv3d = test->clip_rv3d;
684         if (!rv3d) {
685                 return false;
686         }
687         float symm_co[3];
688         flip_v3_v3(symm_co, co, test->mirror_symmetry_pass);
689         return ED_view3d_clipping_test(rv3d, symm_co, true);
690 }
691
692 static bool sculpt_brush_test(SculptBrushTest *test, const float co[3])
693 {
694         float distsq = len_squared_v3v3(co, test->location);
695
696         if (distsq <= test->radius_squared) {
697                 if (sculpt_brush_test_clipping(test, co)) {
698                         return 0;
699                 }
700                 test->dist = sqrtf(distsq);
701                 return 1;
702         }
703         else {
704                 return 0;
705         }
706 }
707
708 static bool sculpt_brush_test_sq(SculptBrushTest *test, const float co[3])
709 {
710         float distsq = len_squared_v3v3(co, test->location);
711
712         if (distsq <= test->radius_squared) {
713                 if (sculpt_brush_test_clipping(test, co)) {
714                         return 0;
715                 }
716                 test->dist = distsq;
717                 return 1;
718         }
719         else {
720                 return 0;
721         }
722 }
723
724 static bool sculpt_brush_test_fast(const SculptBrushTest *test, const float co[3])
725 {
726         if (sculpt_brush_test_clipping(test, co)) {
727                 return 0;
728         }
729         return len_squared_v3v3(co, test->location) <= test->radius_squared;
730 }
731
732 static bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], float local[4][4])
733 {
734         float side = M_SQRT1_2;
735         float local_co[3];
736
737         if (sculpt_brush_test_clipping(test, co)) {
738                 return 0;
739         }
740
741         mul_v3_m4v3(local_co, local, co);
742
743         local_co[0] = fabsf(local_co[0]);
744         local_co[1] = fabsf(local_co[1]);
745         local_co[2] = fabsf(local_co[2]);
746
747         if (local_co[0] <= side && local_co[1] <= side && local_co[2] <= side) {
748                 float p = 4.0f;
749                 
750                 test->dist = ((powf(local_co[0], p) +
751                                powf(local_co[1], p) +
752                                powf(local_co[2], p)) / powf(side, p));
753
754                 return 1;
755         }
756         else {
757                 return 0;
758         }
759 }
760
761 static float frontface(Brush *br, const float sculpt_normal[3],
762                        const short no[3], const float fno[3])
763 {
764         if (br->flag & BRUSH_FRONTFACE) {
765                 float dot;
766
767                 if (no) {
768                         float tmp[3];
769
770                         normal_short_to_float_v3(tmp, no);
771                         dot = dot_v3v3(tmp, sculpt_normal);
772                 }
773                 else {
774                         dot = dot_v3v3(fno, sculpt_normal);
775                 }
776                 return dot > 0 ? dot : 0;
777         }
778         else {
779                 return 1;
780         }
781 }
782
783 #if 0
784
785 static bool sculpt_brush_test_cyl(SculptBrushTest *test, float co[3], float location[3], const float area_no[3])
786 {
787         if (sculpt_brush_test_fast(test, co)) {
788                 float t1[3], t2[3], t3[3], dist;
789
790                 sub_v3_v3v3(t1, location, co);
791                 sub_v3_v3v3(t2, x2, location);
792
793                 cross_v3_v3v3(t3, area_no, t1);
794
795                 dist = len_v3(t3) / len_v3(t2);
796
797                 test->dist = dist;
798
799                 return 1;
800         }
801
802         return 0;
803 }
804
805 #endif
806
807 /* ===== Sculpting =====
808  *
809  */
810 static void flip_v3(float v[3], const char symm)
811 {
812         flip_v3_v3(v, v, symm);
813 }
814
815 static float calc_overlap(StrokeCache *cache, const char symm, const char axis, const float angle)
816 {
817         float mirror[3];
818         float distsq;
819         
820         /* flip_v3_v3(mirror, cache->traced_location, symm); */
821         flip_v3_v3(mirror, cache->true_location, symm);
822
823         if (axis != 0) {
824                 float mat[4][4];
825                 unit_m4(mat);
826                 rotate_m4(mat, axis, angle);
827                 mul_m4_v3(mat, mirror);
828         }
829
830         /* distsq = len_squared_v3v3(mirror, cache->traced_location); */
831         distsq = len_squared_v3v3(mirror, cache->true_location);
832
833         if (distsq <= 4.0f * (cache->radius_squared))
834                 return (2.0f * (cache->radius) - sqrtf(distsq)) / (2.0f * (cache->radius));
835         else
836                 return 0;
837 }
838
839 static float calc_radial_symmetry_feather(Sculpt *sd, StrokeCache *cache, const char symm, const char axis)
840 {
841         int i;
842         float overlap;
843
844         overlap = 0;
845         for (i = 1; i < sd->radial_symm[axis - 'X']; ++i) {
846                 const float angle = 2 * M_PI * i / sd->radial_symm[axis - 'X'];
847                 overlap += calc_overlap(cache, symm, axis, angle);
848         }
849
850         return overlap;
851 }
852
853 static float calc_symmetry_feather(Sculpt *sd, StrokeCache *cache)
854 {
855         if (sd->paint.symmetry_flags & PAINT_SYMMETRY_FEATHER) {
856                 float overlap;
857                 int symm = cache->symmetry;
858                 int i;
859
860                 overlap = 0;
861                 for (i = 0; i <= symm; i++) {
862                         if (i == 0 || (symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
863
864                                 overlap += calc_overlap(cache, i, 0, 0);
865
866                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'X');
867                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Y');
868                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Z');
869                         }
870                 }
871
872                 return 1 / overlap;
873         }
874         else {
875                 return 1;
876         }
877 }
878
879 /** \name Calculate Normal and Center
880  *
881  * Calculate geometry surrounding the brush center.
882  * (optionally using original coordinates).
883  *
884  * Functions are:
885  * - #calc_area_center
886  * - #calc_area_normal
887  * - #calc_area_normal_and_center
888  *
889  * \note These are all _very_ similar, when changing one, check others.
890  * \{ */
891
892 static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
893 {
894         SculptThreadedTaskData *data = userdata;
895         SculptSession *ss = data->ob->sculpt;
896         float (*area_nos)[3] = data->area_nos;
897         float (*area_cos)[3] = data->area_cos;
898
899         PBVHVertexIter vd;
900         SculptBrushTest test;
901         SculptUndoNode *unode;
902
903         float private_co[2][3] = {{0.0f}};
904         float private_no[2][3] = {{0.0f}};
905         int   private_count[2] = {0};
906         bool use_original;
907
908         unode = sculpt_undo_push_node(data->ob, data->nodes[n], SCULPT_UNDO_COORDS);
909         sculpt_brush_test_init(ss, &test);
910
911         use_original = (ss->cache->original && (unode->co || unode->bm_entry));
912
913         /* when the mesh is edited we can't rely on original coords
914          * (original mesh may not even have verts in brush radius) */
915         if (use_original && data->has_bm_orco) {
916                 float (*orco_coords)[3];
917                 int   (*orco_tris)[3];
918                 int     orco_tris_num;
919                 int i;
920
921                 BKE_pbvh_node_get_bm_orco_data(data->nodes[n], &orco_tris, &orco_tris_num, &orco_coords);
922
923                 for (i = 0; i < orco_tris_num; i++) {
924                         const float *co_tri[3] = {
925                             orco_coords[orco_tris[i][0]],
926                             orco_coords[orco_tris[i][1]],
927                             orco_coords[orco_tris[i][2]],
928                         };
929                         float co[3];
930
931                         closest_on_tri_to_point_v3(co, test.location, UNPACK3(co_tri));
932
933                         if (sculpt_brush_test_fast(&test, co)) {
934                                 float no[3];
935                                 int flip_index;
936
937                                 normal_tri_v3(no, UNPACK3(co_tri));
938
939                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
940                                 if (area_cos)
941                                         add_v3_v3(private_co[flip_index], co);
942                                 if (area_nos)
943                                         add_v3_v3(private_no[flip_index], no);
944                                 private_count[flip_index] += 1;
945                         }
946                 }
947         }
948         else {
949                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
950                 {
951                         const float *co;
952                         const short *no_s;  /* bm_vert only */
953
954                         if (use_original) {
955                                 if (unode->bm_entry) {
956                                         BM_log_original_vert_data(ss->bm_log, vd.bm_vert, &co, &no_s);
957                                 }
958                                 else {
959                                         co = unode->co[vd.i];
960                                         no_s = unode->no[vd.i];
961                                 }
962                         }
963                         else {
964                                 co = vd.co;
965                         }
966
967                         if (sculpt_brush_test_fast(&test, co)) {
968                                 float no_buf[3];
969                                 const float *no;
970                                 int flip_index;
971
972                                 if (use_original) {
973                                         normal_short_to_float_v3(no_buf, no_s);
974                                         no = no_buf;
975                                 }
976                                 else {
977                                         if (vd.no) {
978                                                 normal_short_to_float_v3(no_buf, vd.no);
979                                                 no = no_buf;
980                                         }
981                                         else {
982                                                 no = vd.fno;
983                                         }
984                                 }
985
986                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
987                                 if (area_cos)
988                                         add_v3_v3(private_co[flip_index], co);
989                                 if (area_nos)
990                                         add_v3_v3(private_no[flip_index], no);
991                                 private_count[flip_index] += 1;
992                         }
993                 }
994                 BKE_pbvh_vertex_iter_end;
995         }
996
997         BLI_mutex_lock(&data->mutex);
998
999         /* for flatten center */
1000         if (area_cos) {
1001                 add_v3_v3(area_cos[0], private_co[0]);
1002                 add_v3_v3(area_cos[1], private_co[1]);
1003         }
1004
1005         /* for area normal */
1006         if (area_nos) {
1007                 add_v3_v3(area_nos[0], private_no[0]);
1008                 add_v3_v3(area_nos[1], private_no[1]);
1009         }
1010
1011         /* weights */
1012         data->count[0] += private_count[0];
1013         data->count[1] += private_count[1];
1014
1015         BLI_mutex_unlock(&data->mutex);
1016 }
1017
1018 static void calc_area_center(
1019         Sculpt *sd, Object *ob,
1020         PBVHNode **nodes, int totnode,
1021         float r_area_co[3])
1022 {
1023         const Brush *brush = BKE_paint_brush(&sd->paint);
1024         SculptSession *ss = ob->sculpt;
1025         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1026         int n;
1027
1028         /* 0=towards view, 1=flipped */
1029         float area_cos[2][3] = {{0.0f}};
1030
1031         int count[2] = {0};
1032
1033         SculptThreadedTaskData data = {
1034                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1035                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = NULL, .count = count,
1036         };
1037         BLI_mutex_init(&data.mutex);
1038
1039         BLI_task_parallel_range(
1040                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1041                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1042
1043         BLI_mutex_end(&data.mutex);
1044
1045         /* for flatten center */
1046         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
1047                 if (count[n] != 0) {
1048                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
1049                         break;
1050                 }
1051         }
1052         if (n == 2) {
1053                 zero_v3(r_area_co);
1054         }
1055 }
1056
1057
1058 static void calc_area_normal(
1059         Sculpt *sd, Object *ob,
1060         PBVHNode **nodes, int totnode,
1061         float r_area_no[3])
1062 {
1063         const Brush *brush = BKE_paint_brush(&sd->paint);
1064         SculptSession *ss = ob->sculpt;
1065         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1066         int n;
1067
1068         /* 0=towards view, 1=flipped */
1069         float area_nos[2][3] = {{0.0f}};
1070
1071         int count[2] = {0};
1072
1073         SculptThreadedTaskData data = {
1074                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1075                 .has_bm_orco = has_bm_orco, .area_cos = NULL, .area_nos = area_nos, .count = count,
1076         };
1077         BLI_mutex_init(&data.mutex);
1078
1079         BLI_task_parallel_range(
1080                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1081                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1082
1083         BLI_mutex_end(&data.mutex);
1084
1085         /* for area normal */
1086         for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
1087                 if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
1088                         break;
1089                 }
1090         }
1091 }
1092
1093 /* this calculates flatten center and area normal together,
1094  * amortizing the memory bandwidth and loop overhead to calculate both at the same time */
1095 static void calc_area_normal_and_center(
1096         Sculpt *sd, Object *ob,
1097         PBVHNode **nodes, int totnode,
1098         float r_area_no[3], float r_area_co[3])
1099 {
1100         const Brush *brush = BKE_paint_brush(&sd->paint);
1101         SculptSession *ss = ob->sculpt;
1102         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1103         int n;
1104
1105         /* 0=towards view, 1=flipped */
1106         float area_cos[2][3] = {{0.0f}};
1107         float area_nos[2][3] = {{0.0f}};
1108
1109         int count[2] = {0};
1110
1111         SculptThreadedTaskData data = {
1112                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1113                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = area_nos, .count = count,
1114         };
1115         BLI_mutex_init(&data.mutex);
1116
1117         BLI_task_parallel_range(
1118                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1119                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1120
1121         BLI_mutex_end(&data.mutex);
1122
1123         /* for flatten center */
1124         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
1125                 if (count[n] != 0) {
1126                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
1127                         break;
1128                 }
1129         }
1130         if (n == 2) {
1131                 zero_v3(r_area_co);
1132         }
1133
1134         /* for area normal */
1135         for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
1136                 if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
1137                         break;
1138                 }
1139         }
1140 }
1141
1142 /** \} */
1143
1144
1145 /* Return modified brush strength. Includes the direction of the brush, positive
1146  * values pull vertices, negative values push. Uses tablet pressure and a
1147  * special multiplier found experimentally to scale the strength factor. */
1148 static float brush_strength(const Sculpt *sd, const StrokeCache *cache, const float feather, const UnifiedPaintSettings *ups)
1149 {
1150         const Scene *scene = cache->vc->scene;
1151         const Brush *brush = BKE_paint_brush((Paint *)&sd->paint);
1152
1153         /* Primary strength input; square it to make lower values more sensitive */
1154         const float root_alpha = BKE_brush_alpha_get(scene, brush);
1155         float alpha        = root_alpha * root_alpha;
1156         float dir          = (brush->flag & BRUSH_DIR_IN) ? -1 : 1;
1157         float pressure     = BKE_brush_use_alpha_pressure(scene, brush) ? cache->pressure : 1;
1158         float pen_flip     = cache->pen_flip ? -1 : 1;
1159         float invert       = cache->invert ? -1 : 1;
1160         float overlap       = ups->overlap_factor;
1161         /* spacing is integer percentage of radius, divide by 50 to get
1162          * normalized diameter */
1163
1164         float flip         = dir * invert * pen_flip;
1165
1166         switch (brush->sculpt_tool) {
1167                 case SCULPT_TOOL_CLAY:
1168                 case SCULPT_TOOL_CLAY_STRIPS:
1169                 case SCULPT_TOOL_DRAW:
1170                 case SCULPT_TOOL_LAYER:
1171                         return alpha * flip * pressure * overlap * feather;
1172                         
1173                 case SCULPT_TOOL_MASK:
1174                         overlap = (1 + overlap) / 2;
1175                         switch ((BrushMaskTool)brush->mask_tool) {
1176                                 case BRUSH_MASK_DRAW:
1177                                         return alpha * flip * pressure * overlap * feather;
1178                                 case BRUSH_MASK_SMOOTH:
1179                                         return alpha * pressure * feather;
1180                         }
1181
1182                 case SCULPT_TOOL_CREASE:
1183                 case SCULPT_TOOL_BLOB:
1184                         return alpha * flip * pressure * overlap * feather;
1185
1186                 case SCULPT_TOOL_INFLATE:
1187                         if (flip > 0) {
1188                                 return 0.250f * alpha * flip * pressure * overlap * feather;
1189                         }
1190                         else {
1191                                 return 0.125f * alpha * flip * pressure * overlap * feather;
1192                         }
1193
1194                 case SCULPT_TOOL_FILL:
1195                 case SCULPT_TOOL_SCRAPE:
1196                 case SCULPT_TOOL_FLATTEN:
1197                         if (flip > 0) {
1198                                 overlap = (1 + overlap) / 2;
1199                                 return alpha * flip * pressure * overlap * feather;
1200                         }
1201                         else {
1202                                 /* reduce strength for DEEPEN, PEAKS, and CONTRAST */
1203                                 return 0.5f * alpha * flip * pressure * overlap * feather; 
1204                         }
1205
1206                 case SCULPT_TOOL_SMOOTH:
1207                         return alpha * pressure * feather;
1208
1209                 case SCULPT_TOOL_PINCH:
1210                         if (flip > 0) {
1211                                 return alpha * flip * pressure * overlap * feather;
1212                         }
1213                         else {
1214                                 return 0.25f * alpha * flip * pressure * overlap * feather;
1215                         }
1216
1217                 case SCULPT_TOOL_NUDGE:
1218                         overlap = (1 + overlap) / 2;
1219                         return alpha * pressure * overlap * feather;
1220
1221                 case SCULPT_TOOL_THUMB:
1222                         return alpha * pressure * feather;
1223
1224                 case SCULPT_TOOL_SNAKE_HOOK:
1225                         return root_alpha * feather;
1226
1227                 case SCULPT_TOOL_GRAB:
1228                         return root_alpha * feather;
1229
1230                 case SCULPT_TOOL_ROTATE:
1231                         return alpha * pressure * feather;
1232
1233                 default:
1234                         return 0;
1235         }
1236 }
1237
1238 /* Return a multiplier for brush strength on a particular vertex. */
1239 static float tex_strength(SculptSession *ss, Brush *br,
1240                           const float point[3],
1241                           const float len,
1242                           const short vno[3],
1243                           const float fno[3],
1244                           const float mask,
1245                           const int thread_id)
1246 {
1247         StrokeCache *cache = ss->cache;
1248         const Scene *scene = cache->vc->scene;
1249         MTex *mtex = &br->mtex;
1250         float avg = 1;
1251         float rgba[4];
1252
1253         if (!mtex->tex) {
1254                 avg = 1;
1255         }
1256         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
1257                 /* Get strength by feeding the vertex 
1258                  * location directly into a texture */
1259                 avg = BKE_brush_sample_tex_3D(scene, br, point, rgba, 0, ss->tex_pool);
1260         }
1261         else if (ss->texcache) {
1262                 float symm_point[3], point_2d[2];
1263                 float x = 0.0f, y = 0.0f; /* Quite warnings */
1264
1265                 /* if the active area is being applied for symmetry, flip it
1266                  * across the symmetry axis and rotate it back to the original
1267                  * position in order to project it. This insures that the 
1268                  * brush texture will be oriented correctly. */
1269
1270                 flip_v3_v3(symm_point, point, cache->mirror_symmetry_pass);
1271
1272                 if (cache->radial_symmetry_pass)
1273                         mul_m4_v3(cache->symm_rot_mat_inv, symm_point);
1274
1275                 ED_view3d_project_float_v2_m4(cache->vc->ar, symm_point, point_2d, cache->projection_mat);
1276
1277                 /* still no symmetry supported for other paint modes.
1278                  * Sculpt does it DIY */
1279                 if (mtex->brush_map_mode == MTEX_MAP_MODE_AREA) {
1280                         /* Similar to fixed mode, but projects from brush angle
1281                          * rather than view direction */
1282
1283                         mul_m4_v3(cache->brush_local_mat, symm_point);
1284
1285                         x = symm_point[0];
1286                         y = symm_point[1];
1287
1288                         x *= br->mtex.size[0];
1289                         y *= br->mtex.size[1];
1290
1291                         x += br->mtex.ofs[0];
1292                         y += br->mtex.ofs[1];
1293
1294                         avg = paint_get_tex_pixel(&br->mtex, x, y, ss->tex_pool, thread_id);
1295
1296                         avg += br->texture_sample_bias;
1297                 }
1298                 else {
1299                         const float point_3d[3] = {point_2d[0], point_2d[1], 0.0f};
1300                         avg = BKE_brush_sample_tex_3D(scene, br, point_3d, rgba, 0, ss->tex_pool);
1301                 }
1302         }
1303
1304         /* Falloff curve */
1305         avg *= BKE_brush_curve_strength(br, len, cache->radius);
1306
1307         avg *= frontface(br, cache->view_normal, vno, fno);
1308
1309         /* Paint mask */
1310         avg *= 1.0f - mask;
1311
1312         return avg;
1313 }
1314
1315 typedef struct {
1316         Sculpt *sd;
1317         SculptSession *ss;
1318         float radius_squared;
1319         bool original;
1320 } SculptSearchSphereData;
1321
1322 /* Test AABB against sphere */
1323 static bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
1324 {
1325         SculptSearchSphereData *data = data_v;
1326         float *center = data->ss->cache->location, nearest[3];
1327         float t[3], bb_min[3], bb_max[3];
1328         int i;
1329
1330         if (data->original)
1331                 BKE_pbvh_node_get_original_BB(node, bb_min, bb_max);
1332         else
1333                 BKE_pbvh_node_get_BB(node, bb_min, bb_max);
1334         
1335         for (i = 0; i < 3; ++i) {
1336                 if (bb_min[i] > center[i])
1337                         nearest[i] = bb_min[i];
1338                 else if (bb_max[i] < center[i])
1339                         nearest[i] = bb_max[i];
1340                 else
1341                         nearest[i] = center[i]; 
1342         }
1343         
1344         sub_v3_v3v3(t, center, nearest);
1345
1346         return len_squared_v3(t) < data->radius_squared;
1347 }
1348
1349 /* Handles clipping against a mirror modifier and SCULPT_LOCK axis flags */
1350 static void sculpt_clip(Sculpt *sd, SculptSession *ss, float co[3], const float val[3])
1351 {
1352         int i;
1353
1354         for (i = 0; i < 3; ++i) {
1355                 if (sd->flags & (SCULPT_LOCK_X << i))
1356                         continue;
1357
1358                 if ((ss->cache->flag & (CLIP_X << i)) && (fabsf(co[i]) <= ss->cache->clip_tolerance[i]))
1359                         co[i] = 0.0f;
1360                 else
1361                         co[i] = val[i];
1362         }
1363 }
1364
1365 /* Calculate primary direction of movement for many brushes */
1366 static void calc_sculpt_normal(
1367         Sculpt *sd, Object *ob,
1368         PBVHNode **nodes, int totnode,
1369         float r_area_no[3])
1370 {
1371         const Brush *brush = BKE_paint_brush(&sd->paint);
1372         const SculptSession *ss = ob->sculpt;
1373
1374         switch (brush->sculpt_plane) {
1375                 case SCULPT_DISP_DIR_VIEW:
1376                         copy_v3_v3(r_area_no, ss->cache->true_view_normal);
1377                         break;
1378
1379                 case SCULPT_DISP_DIR_X:
1380                         ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
1381                         break;
1382
1383                 case SCULPT_DISP_DIR_Y:
1384                         ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
1385                         break;
1386
1387                 case SCULPT_DISP_DIR_Z:
1388                         ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
1389                         break;
1390
1391                 case SCULPT_DISP_DIR_AREA:
1392                         calc_area_normal(sd, ob, nodes, totnode, r_area_no);
1393                         break;
1394
1395                 default:
1396                         break;
1397         }
1398 }
1399
1400 static void update_sculpt_normal(Sculpt *sd, Object *ob,
1401                                  PBVHNode **nodes, int totnode)
1402 {
1403         const Brush *brush = BKE_paint_brush(&sd->paint);
1404         StrokeCache *cache = ob->sculpt->cache;
1405         
1406         if (cache->mirror_symmetry_pass == 0 &&
1407             cache->radial_symmetry_pass == 0 &&
1408             (cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
1409         {
1410                 calc_sculpt_normal(sd, ob, nodes, totnode, cache->sculpt_normal);
1411                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1412         }
1413         else {
1414                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1415                 flip_v3(cache->sculpt_normal_symm, cache->mirror_symmetry_pass);
1416                 mul_m4_v3(cache->symm_rot_mat, cache->sculpt_normal_symm);
1417         }
1418 }
1419
1420 static void calc_local_y(ViewContext *vc, const float center[3], float y[3])
1421 {
1422         Object *ob = vc->obact;
1423         float loc[3], mval_f[2] = {0.0f, 1.0f};
1424         float zfac;
1425
1426         mul_v3_m4v3(loc, ob->imat, center);
1427         zfac = ED_view3d_calc_zfac(vc->rv3d, loc, NULL);
1428
1429         ED_view3d_win_to_delta(vc->ar, mval_f, y, zfac);
1430         normalize_v3(y);
1431
1432         add_v3_v3(y, ob->loc);
1433         mul_m4_v3(ob->imat, y);
1434 }
1435
1436 static void calc_brush_local_mat(const Brush *brush, Object *ob,
1437                                  float local_mat[4][4])
1438 {
1439         const StrokeCache *cache = ob->sculpt->cache;
1440         float tmat[4][4];
1441         float mat[4][4];
1442         float scale[4][4];
1443         float angle, v[3];
1444         float up[3];
1445
1446         /* Ensure ob->imat is up to date */
1447         invert_m4_m4(ob->imat, ob->obmat);
1448
1449         /* Initialize last column of matrix */
1450         mat[0][3] = 0;
1451         mat[1][3] = 0;
1452         mat[2][3] = 0;
1453         mat[3][3] = 1;
1454
1455         /* Get view's up vector in object-space */
1456         calc_local_y(cache->vc, cache->location, up);
1457
1458         /* Calculate the X axis of the local matrix */
1459         cross_v3_v3v3(v, up, cache->sculpt_normal);
1460         /* Apply rotation (user angle, rake, etc.) to X axis */
1461         angle = brush->mtex.rot - cache->special_rotation;
1462         rotate_v3_v3v3fl(mat[0], v, cache->sculpt_normal, angle);
1463
1464         /* Get other axes */
1465         cross_v3_v3v3(mat[1], cache->sculpt_normal, mat[0]);
1466         copy_v3_v3(mat[2], cache->sculpt_normal);
1467
1468         /* Set location */
1469         copy_v3_v3(mat[3], cache->location);
1470
1471         /* Scale by brush radius */
1472         normalize_m4(mat);
1473         scale_m4_fl(scale, cache->radius);
1474         mul_m4_m4m4(tmat, mat, scale);
1475
1476         /* Return inverse (for converting from modelspace coords to local
1477          * area coords) */
1478         invert_m4_m4(local_mat, tmat);
1479 }
1480
1481 static void update_brush_local_mat(Sculpt *sd, Object *ob)
1482 {
1483         StrokeCache *cache = ob->sculpt->cache;
1484
1485         if (cache->mirror_symmetry_pass == 0 &&
1486             cache->radial_symmetry_pass == 0)
1487         {
1488                 calc_brush_local_mat(BKE_paint_brush(&sd->paint), ob,
1489                                      cache->brush_local_mat);
1490         }
1491 }
1492
1493 /* For the smooth brush, uses the neighboring vertices around vert to calculate
1494  * a smoothed location for vert. Skips corner vertices (used by only one
1495  * polygon.) */
1496 static void neighbor_average(SculptSession *ss, float avg[3], unsigned vert)
1497 {
1498         const MeshElemMap *vert_map = &ss->pmap[vert];
1499         const MVert *mvert = ss->mvert;
1500         float (*deform_co)[3] = ss->deform_cos;
1501
1502         /* Don't modify corner vertices */
1503         if (vert_map->count > 1) {
1504                 int i, total = 0;
1505
1506                 zero_v3(avg);
1507
1508                 for (i = 0; i < vert_map->count; i++) {
1509                         const MPoly *p = &ss->mpoly[vert_map->indices[i]];
1510                         unsigned f_adj_v[2];
1511
1512                         if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1513                                 int j;
1514                                 for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1515                                         if (vert_map->count != 2 || ss->pmap[f_adj_v[j]].count <= 2) {
1516                                                 add_v3_v3(avg, deform_co ? deform_co[f_adj_v[j]] :
1517                                                           mvert[f_adj_v[j]].co);
1518
1519                                                 total++;
1520                                         }
1521                                 }
1522                         }
1523                 }
1524
1525                 if (total > 0) {
1526                         mul_v3_fl(avg, 1.0f / total);
1527                         return;
1528                 }
1529         }
1530
1531         copy_v3_v3(avg, deform_co ? deform_co[vert] : mvert[vert].co);
1532 }
1533
1534 /* Similar to neighbor_average(), but returns an averaged mask value
1535  * instead of coordinate. Also does not restrict based on border or
1536  * corner vertices. */
1537 static float neighbor_average_mask(SculptSession *ss, unsigned vert)
1538 {
1539         const float *vmask = ss->vmask;
1540         float avg = 0;
1541         int i, total = 0;
1542
1543         for (i = 0; i < ss->pmap[vert].count; i++) {
1544                 const MPoly *p = &ss->mpoly[ss->pmap[vert].indices[i]];
1545                 unsigned f_adj_v[2];
1546
1547                 if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1548                         int j;
1549                         for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1550                                 avg += vmask[f_adj_v[j]];
1551                                 total++;
1552                         }
1553                 }
1554         }
1555
1556         if (total > 0)
1557                 return avg / (float)total;
1558         else
1559                 return vmask[vert];
1560 }
1561
1562 /* Same logic as neighbor_average(), but for bmesh rather than mesh */
1563 static void bmesh_neighbor_average(float avg[3], BMVert *v)
1564 {
1565         /* logic for 3 or more is identical */
1566         const int vfcount = BM_vert_face_count_ex(v, 3);
1567
1568         /* Don't modify corner vertices */
1569         if (vfcount > 1) {
1570                 BMIter liter;
1571                 BMLoop *l;
1572                 int i, total = 0;
1573
1574                 zero_v3(avg);
1575
1576                 BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1577                         const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1578
1579                         for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1580                                 const BMVert *v_other = adj_v[i];
1581                                 if (vfcount != 2 || BM_vert_face_count_ex(v_other, 2) <= 2) {
1582                                         add_v3_v3(avg, v_other->co);
1583                                         total++;
1584                                 }
1585                         }
1586                 }
1587
1588                 if (total > 0) {
1589                         mul_v3_fl(avg, 1.0f / total);
1590                         return;
1591                 }
1592         }
1593
1594         copy_v3_v3(avg, v->co);
1595 }
1596
1597 /* Same logic as neighbor_average_mask(), but for bmesh rather than mesh */
1598 static float bmesh_neighbor_average_mask(BMVert *v, const int cd_vert_mask_offset)
1599 {
1600         BMIter liter;
1601         BMLoop *l;
1602         float avg = 0;
1603         int i, total = 0;
1604
1605         BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1606                 /* skip this vertex */
1607                 const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1608
1609                 for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1610                         const BMVert *v_other = adj_v[i];
1611                         const float *vmask = BM_ELEM_CD_GET_VOID_P(v_other, cd_vert_mask_offset);
1612                         avg += (*vmask);
1613                         total++;
1614                 }
1615         }
1616
1617         if (total > 0) {
1618                 return avg / (float)total;
1619         }
1620         else {
1621                 const float *vmask = BM_ELEM_CD_GET_VOID_P(v, cd_vert_mask_offset);
1622                 return (*vmask);
1623         }
1624 }
1625
1626 /* Note: uses after-struct allocated mem to store actual cache... */
1627 typedef struct SculptDoBrushSmoothGridDataChunk {
1628         size_t tmpgrid_size;
1629 } SculptDoBrushSmoothGridDataChunk;
1630
1631 static void do_smooth_brush_mesh_task_cb_ex(
1632         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1633 {
1634         SculptThreadedTaskData *data = userdata;
1635         SculptSession *ss = data->ob->sculpt;
1636         Sculpt *sd = data->sd;
1637         Brush *brush = data->brush;
1638         const bool smooth_mask = data->smooth_mask;
1639         float bstrength = data->strength;
1640
1641         PBVHVertexIter vd;
1642         SculptBrushTest test;
1643
1644         CLAMP(bstrength, 0.0f, 1.0f);
1645
1646         sculpt_brush_test_init(ss, &test);
1647
1648         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1649         {
1650                 if (sculpt_brush_test(&test, vd.co)) {
1651                         const float fade = bstrength * tex_strength(
1652                                                ss, brush, vd.co, test.dist, vd.no, vd.fno,
1653                                                smooth_mask ? 0.0f : (vd.mask ? *vd.mask : 0.0f),
1654                                                thread_id);
1655                         if (smooth_mask) {
1656                                 float val = neighbor_average_mask(ss, vd.vert_indices[vd.i]) - *vd.mask;
1657                                 val *= fade * bstrength;
1658                                 *vd.mask += val;
1659                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1660                         }
1661                         else {
1662                                 float avg[3], val[3];
1663
1664                                 neighbor_average(ss, avg, vd.vert_indices[vd.i]);
1665                                 sub_v3_v3v3(val, avg, vd.co);
1666
1667                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1668
1669                                 sculpt_clip(sd, ss, vd.co, val);
1670                         }
1671
1672                         if (vd.mvert)
1673                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1674                 }
1675         }
1676         BKE_pbvh_vertex_iter_end;
1677 }
1678
1679 static void do_smooth_brush_bmesh_task_cb_ex(
1680         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1681 {
1682         SculptThreadedTaskData *data = userdata;
1683         SculptSession *ss = data->ob->sculpt;
1684         Sculpt *sd = data->sd;
1685         Brush *brush = data->brush;
1686         const bool smooth_mask = data->smooth_mask;
1687         float bstrength = data->strength;
1688
1689         PBVHVertexIter vd;
1690         SculptBrushTest test;
1691
1692         CLAMP(bstrength, 0.0f, 1.0f);
1693
1694         sculpt_brush_test_init(ss, &test);
1695
1696         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1697         {
1698                 if (sculpt_brush_test(&test, vd.co)) {
1699                         const float fade = bstrength * tex_strength(
1700                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, smooth_mask ? 0.0f : *vd.mask,
1701                                                thread_id);
1702                         if (smooth_mask) {
1703                                 float val = bmesh_neighbor_average_mask(vd.bm_vert, vd.cd_vert_mask_offset) - *vd.mask;
1704                                 val *= fade * bstrength;
1705                                 *vd.mask += val;
1706                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1707                         }
1708                         else {
1709                                 float avg[3], val[3];
1710
1711                                 bmesh_neighbor_average(avg, vd.bm_vert);
1712                                 sub_v3_v3v3(val, avg, vd.co);
1713
1714                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1715
1716                                 sculpt_clip(sd, ss, vd.co, val);
1717                         }
1718
1719                         if (vd.mvert)
1720                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1721                 }
1722         }
1723         BKE_pbvh_vertex_iter_end;
1724 }
1725
1726 static void do_smooth_brush_multires_task_cb_ex(
1727         void *userdata, void *userdata_chunk, const int n, const int thread_id)
1728 {
1729         SculptThreadedTaskData *data = userdata;
1730         SculptDoBrushSmoothGridDataChunk *data_chunk = userdata_chunk;
1731         SculptSession *ss = data->ob->sculpt;
1732         Sculpt *sd = data->sd;
1733         Brush *brush = data->brush;
1734         const bool smooth_mask = data->smooth_mask;
1735         float bstrength = data->strength;
1736
1737         SculptBrushTest test;
1738         CCGElem **griddata, *gddata;
1739         CCGKey key;
1740
1741         float (*tmpgrid_co)[3] = NULL;
1742         float tmprow_co[2][3];
1743         float *tmpgrid_mask = NULL;
1744         float tmprow_mask[2];
1745
1746         BLI_bitmap * const *grid_hidden;
1747         int *grid_indices, totgrid, gridsize;
1748         int i, x, y;
1749
1750         sculpt_brush_test_init(ss, &test);
1751
1752         CLAMP(bstrength, 0.0f, 1.0f);
1753
1754         BKE_pbvh_node_get_grids(ss->pbvh, data->nodes[n], &grid_indices, &totgrid, NULL, &gridsize, &griddata);
1755         BKE_pbvh_get_grid_key(ss->pbvh, &key);
1756
1757         grid_hidden = BKE_pbvh_grid_hidden(ss->pbvh);
1758
1759         if (smooth_mask)
1760                 tmpgrid_mask = (void *)(data_chunk + 1);
1761         else
1762                 tmpgrid_co = (void *)(data_chunk + 1);
1763
1764         for (i = 0; i < totgrid; i++) {
1765                 int gi = grid_indices[i];
1766                 const BLI_bitmap *gh = grid_hidden[gi];
1767                 gddata = griddata[gi];
1768
1769                 if (smooth_mask)
1770                         memset(tmpgrid_mask, 0, data_chunk->tmpgrid_size);
1771                 else
1772                         memset(tmpgrid_co, 0, data_chunk->tmpgrid_size);
1773
1774                 for (y = 0; y < gridsize - 1; y++) {
1775                         const int v = y * gridsize;
1776                         if (smooth_mask) {
1777                                 tmprow_mask[0] = (*CCG_elem_offset_mask(&key, gddata, v) +
1778                                                   *CCG_elem_offset_mask(&key, gddata, v + gridsize));
1779                         }
1780                         else {
1781                                 add_v3_v3v3(tmprow_co[0],
1782                                             CCG_elem_offset_co(&key, gddata, v),
1783                                             CCG_elem_offset_co(&key, gddata, v + gridsize));
1784                         }
1785
1786                         for (x = 0; x < gridsize - 1; x++) {
1787                                 const int v1 = x + y * gridsize;
1788                                 const int v2 = v1 + 1;
1789                                 const int v3 = v1 + gridsize;
1790                                 const int v4 = v3 + 1;
1791
1792                                 if (smooth_mask) {
1793                                         float tmp;
1794
1795                                         tmprow_mask[(x + 1) % 2] = (*CCG_elem_offset_mask(&key, gddata, v2) +
1796                                                                     *CCG_elem_offset_mask(&key, gddata, v4));
1797                                         tmp = tmprow_mask[(x + 1) % 2] + tmprow_mask[x % 2];
1798
1799                                         tmpgrid_mask[v1] += tmp;
1800                                         tmpgrid_mask[v2] += tmp;
1801                                         tmpgrid_mask[v3] += tmp;
1802                                         tmpgrid_mask[v4] += tmp;
1803                                 }
1804                                 else {
1805                                         float tmp[3];
1806
1807                                         add_v3_v3v3(tmprow_co[(x + 1) % 2],
1808                                                     CCG_elem_offset_co(&key, gddata, v2),
1809                                                     CCG_elem_offset_co(&key, gddata, v4));
1810                                         add_v3_v3v3(tmp, tmprow_co[(x + 1) % 2], tmprow_co[x % 2]);
1811
1812                                         add_v3_v3(tmpgrid_co[v1], tmp);
1813                                         add_v3_v3(tmpgrid_co[v2], tmp);
1814                                         add_v3_v3(tmpgrid_co[v3], tmp);
1815                                         add_v3_v3(tmpgrid_co[v4], tmp);
1816                                 }
1817                         }
1818                 }
1819
1820                 /* blend with existing coordinates */
1821                 for (y = 0; y < gridsize; y++) {
1822                         for (x = 0; x < gridsize; x++) {
1823                                 float *co;
1824                                 const float *fno;
1825                                 float *mask;
1826                                 const int index = y * gridsize + x;
1827
1828                                 if (gh) {
1829                                         if (BLI_BITMAP_TEST(gh, index))
1830                                                 continue;
1831                                 }
1832
1833                                 co = CCG_elem_offset_co(&key, gddata, index);
1834                                 fno = CCG_elem_offset_no(&key, gddata, index);
1835                                 mask = CCG_elem_offset_mask(&key, gddata, index);
1836
1837                                 if (sculpt_brush_test(&test, co)) {
1838                                         const float strength_mask = (smooth_mask ? 0.0f : *mask);
1839                                         const float fade = bstrength * tex_strength(
1840                                                                ss, brush, co, test.dist, NULL, fno, strength_mask, thread_id);
1841                                         float f = 1.0f / 16.0f;
1842
1843                                         if (x == 0 || x == gridsize - 1)
1844                                                 f *= 2.0f;
1845
1846                                         if (y == 0 || y == gridsize - 1)
1847                                                 f *= 2.0f;
1848
1849                                         if (smooth_mask) {
1850                                                 *mask += ((tmpgrid_mask[index] * f) - *mask) * fade;
1851                                         }
1852                                         else {
1853                                                 float *avg = tmpgrid_co[index];
1854                                                 float val[3];
1855
1856                                                 mul_v3_fl(avg, f);
1857                                                 sub_v3_v3v3(val, avg, co);
1858                                                 madd_v3_v3v3fl(val, co, val, fade);
1859
1860                                                 sculpt_clip(sd, ss, co, val);
1861                                         }
1862                                 }
1863                         }
1864                 }
1865         }
1866 }
1867
1868 static void smooth(
1869         Sculpt *sd, Object *ob, PBVHNode **nodes, const int totnode, float bstrength, const bool smooth_mask)
1870 {
1871         SculptSession *ss = ob->sculpt;
1872         Brush *brush = BKE_paint_brush(&sd->paint);
1873
1874         const int max_iterations = 4;
1875         const float fract = 1.0f / max_iterations;
1876         PBVHType type = BKE_pbvh_type(ss->pbvh);
1877         int iteration, count;
1878         float last;
1879
1880         CLAMP(bstrength, 0.0f, 1.0f);
1881
1882         count = (int)(bstrength * max_iterations);
1883         last  = max_iterations * (bstrength - count * fract);
1884
1885         if (type == PBVH_FACES && !ss->pmap) {
1886                 BLI_assert(!"sculpt smooth: pmap missing");
1887                 return;
1888         }
1889
1890         for (iteration = 0; iteration <= count; ++iteration) {
1891                 const float strength = (iteration != count) ? 1.0f : last;
1892
1893                 SculptThreadedTaskData data = {
1894                     .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
1895                     .smooth_mask = smooth_mask, .strength = strength,
1896                 };
1897
1898                 switch (type) {
1899                         case PBVH_GRIDS:
1900                         {
1901                                 int gridsize;
1902                                 size_t size;
1903                                 SculptDoBrushSmoothGridDataChunk *data_chunk;
1904
1905                                 BKE_pbvh_node_get_grids(ss->pbvh, NULL, NULL, NULL, NULL, &gridsize, NULL);
1906                                 size = (size_t)gridsize;
1907                                 size = sizeof(float) * size * size * (smooth_mask ? 1 : 3);
1908                                 data_chunk = MEM_mallocN(sizeof(*data_chunk) + size, __func__);
1909                                 data_chunk->tmpgrid_size = size;
1910                                 size += sizeof(*data_chunk);
1911
1912                                 BLI_task_parallel_range_ex(
1913                                             0, totnode, &data, data_chunk, size, do_smooth_brush_multires_task_cb_ex,
1914                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1915
1916                                 MEM_freeN(data_chunk);
1917                                 break;
1918                         }
1919                         case PBVH_FACES:
1920                                 BLI_task_parallel_range_ex(
1921                                             0, totnode, &data, NULL, 0, do_smooth_brush_mesh_task_cb_ex,
1922                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1923                                 break;
1924                         case PBVH_BMESH:
1925                                 BLI_task_parallel_range_ex(
1926                                             0, totnode, &data, NULL, 0, do_smooth_brush_bmesh_task_cb_ex,
1927                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1928                                 break;
1929                 }
1930
1931                 if (ss->multires)
1932                         multires_stitch_grids(ob);
1933         }
1934 }
1935
1936 static void do_smooth_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1937 {
1938         SculptSession *ss = ob->sculpt;
1939         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, false);
1940 }
1941
1942 static void do_mask_brush_draw_task_cb_ex(
1943         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1944 {
1945         SculptThreadedTaskData *data = userdata;
1946         SculptSession *ss = data->ob->sculpt;
1947         Brush *brush = data->brush;
1948         const float bstrength = ss->cache->bstrength;
1949
1950         PBVHVertexIter vd;
1951         SculptBrushTest test;
1952
1953         sculpt_brush_test_init(ss, &test);
1954
1955         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1956         {
1957                 if (sculpt_brush_test(&test, vd.co)) {
1958                         const float fade = tex_strength(ss, brush, vd.co, test.dist, vd.no, vd.fno, 0.0f, thread_id);
1959
1960                         (*vd.mask) += fade * bstrength;
1961                         CLAMP(*vd.mask, 0, 1);
1962
1963                         if (vd.mvert)
1964                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1965                 }
1966                 BKE_pbvh_vertex_iter_end;
1967         }
1968 }
1969
1970 static void do_mask_brush_draw(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1971 {
1972         Brush *brush = BKE_paint_brush(&sd->paint);
1973
1974         /* threaded loop over nodes */
1975         SculptThreadedTaskData data = {
1976             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
1977         };
1978
1979         BLI_task_parallel_range_ex(
1980                     0, totnode, &data, NULL, 0, do_mask_brush_draw_task_cb_ex,
1981                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1982 }
1983
1984 static void do_mask_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1985 {
1986         SculptSession *ss = ob->sculpt;
1987         Brush *brush = BKE_paint_brush(&sd->paint);
1988         
1989         switch ((BrushMaskTool)brush->mask_tool) {
1990                 case BRUSH_MASK_DRAW:
1991                         do_mask_brush_draw(sd, ob, nodes, totnode);
1992                         break;
1993                 case BRUSH_MASK_SMOOTH:
1994                         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, true);
1995                         break;
1996         }
1997 }
1998
1999 static void do_draw_brush_task_cb_ex(
2000         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2001 {
2002         SculptThreadedTaskData *data = userdata;
2003         SculptSession *ss = data->ob->sculpt;
2004         Brush *brush = data->brush;
2005         const float *offset = data->offset;
2006
2007         PBVHVertexIter vd;
2008         SculptBrushTest test;
2009         float (*proxy)[3];
2010
2011         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2012
2013         sculpt_brush_test_init(ss, &test);
2014
2015         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2016         {
2017                 if (sculpt_brush_test(&test, vd.co)) {
2018                         /* offset vertex */
2019                         const float fade = tex_strength(
2020                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2021
2022                         mul_v3_v3fl(proxy[vd.i], offset, fade);
2023
2024                         if (vd.mvert)
2025                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2026                 }
2027         }
2028         BKE_pbvh_vertex_iter_end;
2029 }
2030
2031 static void do_draw_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2032 {
2033         SculptSession *ss = ob->sculpt;
2034         Brush *brush = BKE_paint_brush(&sd->paint);
2035         float offset[3];
2036         const float bstrength = ss->cache->bstrength;
2037
2038         /* offset with as much as possible factored in already */
2039         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2040         mul_v3_v3(offset, ss->cache->scale);
2041         mul_v3_fl(offset, bstrength);
2042
2043         /* threaded loop over nodes */
2044         SculptThreadedTaskData data = {
2045             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2046             .offset = offset,
2047         };
2048
2049         BLI_task_parallel_range_ex(
2050                     0, totnode, &data, NULL, 0, do_draw_brush_task_cb_ex,
2051                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2052 }
2053
2054 static void do_crease_brush_task_cb_ex(
2055         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2056 {
2057         SculptThreadedTaskData *data = userdata;
2058         SculptSession *ss = data->ob->sculpt;
2059         Brush *brush = data->brush;
2060         SculptProjectVector *spvc = data->spvc;
2061         const float flippedbstrength = data->flippedbstrength;
2062         const float *offset = data->offset;
2063
2064         PBVHVertexIter vd;
2065         SculptBrushTest test;
2066         float (*proxy)[3];
2067
2068         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2069
2070         sculpt_brush_test_init(ss, &test);
2071
2072         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2073         {
2074                 if (sculpt_brush_test(&test, vd.co)) {
2075                         /* offset vertex */
2076                         const float fade = tex_strength(
2077                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2078                         float val1[3];
2079                         float val2[3];
2080
2081                         /* first we pinch */
2082                         sub_v3_v3v3(val1, test.location, vd.co);
2083                         mul_v3_fl(val1, fade * flippedbstrength);
2084
2085                         sculpt_project_v3(spvc, val1, val1);
2086
2087                         /* then we draw */
2088                         mul_v3_v3fl(val2, offset, fade);
2089
2090                         add_v3_v3v3(proxy[vd.i], val1, val2);
2091
2092                         if (vd.mvert)
2093                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2094                 }
2095         }
2096         BKE_pbvh_vertex_iter_end;
2097 }
2098
2099 static void do_crease_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2100 {
2101         SculptSession *ss = ob->sculpt;
2102         const Scene *scene = ss->cache->vc->scene;
2103         Brush *brush = BKE_paint_brush(&sd->paint);
2104         float offset[3];
2105         float bstrength = ss->cache->bstrength;
2106         float flippedbstrength, crease_correction;
2107         float brush_alpha;
2108
2109         SculptProjectVector spvc;
2110
2111         /* offset with as much as possible factored in already */
2112         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2113         mul_v3_v3(offset, ss->cache->scale);
2114         mul_v3_fl(offset, bstrength);
2115         
2116         /* we divide out the squared alpha and multiply by the squared crease to give us the pinch strength */
2117         crease_correction = brush->crease_pinch_factor * brush->crease_pinch_factor;
2118         brush_alpha = BKE_brush_alpha_get(scene, brush);
2119         if (brush_alpha > 0.0f)
2120                 crease_correction /= brush_alpha * brush_alpha;
2121
2122         /* we always want crease to pinch or blob to relax even when draw is negative */
2123         flippedbstrength = (bstrength < 0) ? -crease_correction * bstrength : crease_correction * bstrength;
2124
2125         if (brush->sculpt_tool == SCULPT_TOOL_BLOB) flippedbstrength *= -1.0f;
2126
2127         /* Use surface normal for 'spvc', so the vertices are pinched towards a line instead of a single point.
2128          * Without this we get a 'flat' surface surrounding the pinch */
2129         sculpt_project_v3_cache_init(&spvc, ss->cache->sculpt_normal_symm);
2130
2131         /* threaded loop over nodes */
2132         SculptThreadedTaskData data = {
2133             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2134             .spvc = &spvc, .offset = offset, .flippedbstrength = flippedbstrength,
2135         };
2136
2137         BLI_task_parallel_range_ex(
2138                     0, totnode, &data, NULL, 0, do_crease_brush_task_cb_ex,
2139                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2140 }
2141
2142 static void do_pinch_brush_task_cb_ex(
2143         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2144 {
2145         SculptThreadedTaskData *data = userdata;
2146         SculptSession *ss = data->ob->sculpt;
2147         Brush *brush = data->brush;
2148
2149         PBVHVertexIter vd;
2150         SculptBrushTest test;
2151         float (*proxy)[3];
2152         const float bstrength = ss->cache->bstrength;
2153
2154         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2155
2156         sculpt_brush_test_init(ss, &test);
2157
2158         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2159         {
2160                 if (sculpt_brush_test(&test, vd.co)) {
2161                         const float fade = bstrength * tex_strength(
2162                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2163                         float val[3];
2164
2165                         sub_v3_v3v3(val, test.location, vd.co);
2166                         mul_v3_v3fl(proxy[vd.i], val, fade);
2167
2168                         if (vd.mvert)
2169                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2170                 }
2171         }
2172         BKE_pbvh_vertex_iter_end;
2173 }
2174
2175 static void do_pinch_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2176 {
2177         Brush *brush = BKE_paint_brush(&sd->paint);
2178
2179         SculptThreadedTaskData data = {
2180             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2181         };
2182
2183         BLI_task_parallel_range_ex(
2184                     0, totnode, &data, NULL, 0, do_pinch_brush_task_cb_ex,
2185                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2186 }
2187
2188 static void do_grab_brush_task_cb_ex(
2189         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2190 {
2191         SculptThreadedTaskData *data = userdata;
2192         SculptSession *ss = data->ob->sculpt;
2193         Brush *brush = data->brush;
2194         const float *grab_delta = data->grab_delta;
2195
2196         PBVHVertexIter vd;
2197         SculptBrushTest test;
2198         SculptOrigVertData orig_data;
2199         float (*proxy)[3];
2200         const float bstrength = ss->cache->bstrength;
2201
2202         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2203
2204         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2205
2206         sculpt_brush_test_init(ss, &test);
2207
2208         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2209         {
2210                 sculpt_orig_vert_data_update(&orig_data, &vd);
2211
2212                 if (sculpt_brush_test(&test, orig_data.co)) {
2213                         const float fade = bstrength * tex_strength(
2214                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2215                                                thread_id);
2216
2217                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2218
2219                         if (vd.mvert)
2220                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2221                 }
2222         }
2223         BKE_pbvh_vertex_iter_end;
2224 }
2225
2226 static void do_grab_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2227 {
2228         SculptSession *ss = ob->sculpt;
2229         Brush *brush = BKE_paint_brush(&sd->paint);
2230         float grab_delta[3];
2231
2232         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2233
2234         if (ss->cache->normal_weight > 0.0f) {
2235                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2236         }
2237
2238         SculptThreadedTaskData data = {
2239             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2240             .grab_delta = grab_delta,
2241         };
2242
2243         BLI_task_parallel_range_ex(
2244                     0, totnode, &data, NULL, 0, do_grab_brush_task_cb_ex,
2245                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2246 }
2247
2248 static void do_nudge_brush_task_cb_ex(
2249         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2250 {
2251         SculptThreadedTaskData *data = userdata;
2252         SculptSession *ss = data->ob->sculpt;
2253         Brush *brush = data->brush;
2254         const float *cono = data->cono;
2255
2256         PBVHVertexIter vd;
2257         SculptBrushTest test;
2258         float (*proxy)[3];
2259         const float bstrength = ss->cache->bstrength;
2260
2261         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2262
2263         sculpt_brush_test_init(ss, &test);
2264
2265         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2266         {
2267                 if (sculpt_brush_test(&test, vd.co)) {
2268                         const float fade = bstrength * tex_strength(
2269                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2270
2271                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2272
2273                         if (vd.mvert)
2274                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2275                 }
2276         }
2277         BKE_pbvh_vertex_iter_end;
2278 }
2279
2280 static void do_nudge_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2281 {
2282         SculptSession *ss = ob->sculpt;
2283         Brush *brush = BKE_paint_brush(&sd->paint);
2284         float grab_delta[3];
2285         float tmp[3], cono[3];
2286
2287         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2288
2289         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2290         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2291
2292         SculptThreadedTaskData data = {
2293             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2294             .cono = cono,
2295         };
2296
2297         BLI_task_parallel_range_ex(
2298                     0, totnode, &data, NULL, 0, do_nudge_brush_task_cb_ex,
2299                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2300 }
2301
2302 static void do_snake_hook_brush_task_cb_ex(
2303         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2304 {
2305         SculptThreadedTaskData *data = userdata;
2306         SculptSession *ss = data->ob->sculpt;
2307         Brush *brush = data->brush;
2308         SculptProjectVector *spvc = data->spvc;
2309         const float *grab_delta = data->grab_delta;
2310
2311         PBVHVertexIter vd;
2312         SculptBrushTest test;
2313         float (*proxy)[3];
2314         const float bstrength = ss->cache->bstrength;
2315         const bool do_rake_rotation = ss->cache->is_rake_rotation_valid;
2316         const bool do_pinch = (brush->crease_pinch_factor != 0.5f);
2317         const float pinch = do_pinch ?
2318                 (2.0f * (0.5f - brush->crease_pinch_factor) * (len_v3(grab_delta) / ss->cache->radius)) : 0.0f;
2319
2320         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2321
2322         sculpt_brush_test_init(ss, &test);
2323
2324         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2325         {
2326                 if (sculpt_brush_test(&test, vd.co)) {
2327                         const float fade = bstrength * tex_strength(
2328                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2329
2330                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2331
2332                         /* negative pinch will inflate, helps maintain volume */
2333                         if (do_pinch) {
2334                                 float delta_pinch_init[3], delta_pinch[3];
2335
2336                                 sub_v3_v3v3(delta_pinch, vd.co, test.location);
2337
2338                                 /* important to calculate based on the grabbed location (intentionally ignore fade here). */
2339                                 add_v3_v3(delta_pinch, grab_delta);
2340
2341                                 sculpt_project_v3(spvc, delta_pinch, delta_pinch);
2342
2343                                 copy_v3_v3(delta_pinch_init, delta_pinch);
2344
2345                                 float pinch_fade = pinch * fade;
2346                                 /* when reducing, scale reduction back by how close to the center we are,
2347                                  * so we don't pinch into nothingness */
2348                                 if (pinch > 0.0f) {
2349                                         /* square to have even less impact for close vertices */
2350                                         pinch_fade *= pow2f(min_ff(1.0f, len_v3(delta_pinch) / ss->cache->radius));
2351                                 }
2352                                 mul_v3_fl(delta_pinch, 1.0f + pinch_fade);
2353                                 sub_v3_v3v3(delta_pinch, delta_pinch_init, delta_pinch);
2354                                 add_v3_v3(proxy[vd.i], delta_pinch);
2355                         }
2356
2357                         if (do_rake_rotation) {
2358                                 float delta_rotate[3];
2359                                 sculpt_rake_rotate(ss, test.location, vd.co, fade, delta_rotate);
2360                                 add_v3_v3(proxy[vd.i], delta_rotate);
2361                         }
2362
2363                         if (vd.mvert)
2364                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2365                 }
2366         }
2367         BKE_pbvh_vertex_iter_end;
2368 }
2369
2370 static void do_snake_hook_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2371 {
2372         SculptSession *ss = ob->sculpt;
2373         Brush *brush = BKE_paint_brush(&sd->paint);
2374         const float bstrength = ss->cache->bstrength;
2375         float grab_delta[3];
2376
2377         SculptProjectVector spvc;
2378
2379         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2380
2381         if (bstrength < 0)
2382                 negate_v3(grab_delta);
2383
2384         if (ss->cache->normal_weight > 0.0f) {
2385                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2386         }
2387
2388         /* optionally pinch while painting */
2389         if (brush->crease_pinch_factor != 0.5f) {
2390                 sculpt_project_v3_cache_init(&spvc, grab_delta);
2391         }
2392
2393         SculptThreadedTaskData data = {
2394             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2395             .spvc = &spvc, .grab_delta = grab_delta,
2396         };
2397
2398         BLI_task_parallel_range_ex(
2399                     0, totnode, &data, NULL, 0, do_snake_hook_brush_task_cb_ex,
2400                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2401 }
2402
2403 static void do_thumb_brush_task_cb_ex(
2404         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2405 {
2406         SculptThreadedTaskData *data = userdata;
2407         SculptSession *ss = data->ob->sculpt;
2408         Brush *brush = data->brush;
2409         const float *cono = data->cono;
2410
2411         PBVHVertexIter vd;
2412         SculptBrushTest test;
2413         SculptOrigVertData orig_data;
2414         float (*proxy)[3];
2415         const float bstrength = ss->cache->bstrength;
2416
2417         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2418
2419         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2420
2421         sculpt_brush_test_init(ss, &test);
2422
2423         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2424         {
2425                 sculpt_orig_vert_data_update(&orig_data, &vd);
2426
2427                 if (sculpt_brush_test(&test, orig_data.co)) {
2428                         const float fade = bstrength * tex_strength(
2429                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2430                                                thread_id);
2431
2432                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2433
2434                         if (vd.mvert)
2435                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2436                 }
2437         }
2438         BKE_pbvh_vertex_iter_end;
2439 }
2440
2441 static void do_thumb_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2442 {
2443         SculptSession *ss = ob->sculpt;
2444         Brush *brush = BKE_paint_brush(&sd->paint);
2445         float grab_delta[3];
2446         float tmp[3], cono[3];
2447
2448         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2449
2450         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2451         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2452
2453         SculptThreadedTaskData data = {
2454             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2455             .cono = cono,
2456         };
2457
2458         BLI_task_parallel_range_ex(
2459                     0, totnode, &data, NULL, 0, do_thumb_brush_task_cb_ex,
2460                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2461 }
2462
2463 static void do_rotate_brush_task_cb_ex(
2464         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2465 {
2466         SculptThreadedTaskData *data = userdata;
2467         SculptSession *ss = data->ob->sculpt;
2468         Brush *brush = data->brush;
2469         const float angle = data->angle;
2470
2471         PBVHVertexIter vd;
2472         SculptBrushTest test;
2473         SculptOrigVertData orig_data;
2474         float (*proxy)[3];
2475         const float bstrength = ss->cache->bstrength;
2476
2477         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2478
2479         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2480
2481         sculpt_brush_test_init(ss, &test);
2482
2483         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2484         {
2485                 sculpt_orig_vert_data_update(&orig_data, &vd);
2486
2487                 if (sculpt_brush_test(&test, orig_data.co)) {
2488                         float vec[3], rot[3][3];
2489                         const float fade = bstrength * tex_strength(
2490                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2491                                                thread_id);
2492
2493                         sub_v3_v3v3(vec, orig_data.co, ss->cache->location);
2494                         axis_angle_normalized_to_mat3(rot, ss->cache->sculpt_normal_symm, angle * fade);
2495                         mul_v3_m3v3(proxy[vd.i], rot, vec);
2496                         add_v3_v3(proxy[vd.i], ss->cache->location);
2497                         sub_v3_v3(proxy[vd.i], orig_data.co);
2498
2499                         if (vd.mvert)
2500                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2501                 }
2502         }
2503         BKE_pbvh_vertex_iter_end;
2504 }
2505
2506 static void do_rotate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2507 {
2508         SculptSession *ss = ob->sculpt;
2509         Brush *brush = BKE_paint_brush(&sd->paint);
2510
2511         static const int flip[8] = { 1, -1, -1, 1, -1, 1, 1, -1 };
2512         const float angle = ss->cache->vertex_rotation * flip[ss->cache->mirror_symmetry_pass];
2513
2514         SculptThreadedTaskData data = {
2515             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2516             .angle = angle,
2517         };
2518
2519         BLI_task_parallel_range_ex(
2520                     0, totnode, &data, NULL, 0, do_rotate_brush_task_cb_ex,
2521                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2522 }
2523
2524 static void do_layer_brush_task_cb_ex(
2525         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2526 {
2527         SculptThreadedTaskData *data = userdata;
2528         SculptSession *ss = data->ob->sculpt;
2529         Sculpt *sd = data->sd;
2530         Brush *brush = data->brush;
2531         const float *offset = data->offset;
2532
2533         PBVHVertexIter vd;
2534         SculptBrushTest test;
2535         SculptOrigVertData orig_data;
2536         float *layer_disp;
2537         const float bstrength = ss->cache->bstrength;
2538         const float lim = (bstrength < 0) ? -data->brush->height : data->brush->height;
2539         /* XXX: layer brush needs conversion to proxy but its more complicated */
2540         /* proxy = BKE_pbvh_node_add_proxy(ss->pbvh, nodes[n])->co; */
2541
2542         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2543
2544         /* Why does this have to be thread-protected? */
2545         BLI_mutex_lock(&data->mutex);
2546         layer_disp = BKE_pbvh_node_layer_disp_get(ss->pbvh, data->nodes[n]);
2547         BLI_mutex_unlock(&data->mutex);
2548
2549         sculpt_brush_test_init(ss, &test);
2550
2551         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2552         {
2553                 sculpt_orig_vert_data_update(&orig_data, &vd);
2554
2555                 if (sculpt_brush_test(&test, orig_data.co)) {
2556                         const float fade = bstrength * tex_strength(
2557                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2558                         float *disp = &layer_disp[vd.i];
2559                         float val[3];
2560
2561                         *disp += fade;
2562
2563                         /* Don't let the displacement go past the limit */
2564                         if ((lim < 0.0f && *disp < lim) || (lim >= 0.0f && *disp > lim))
2565                                 *disp = lim;
2566
2567                         mul_v3_v3fl(val, offset, *disp);
2568
2569                         if (!ss->multires && !ss->bm && ss->layer_co && (brush->flag & BRUSH_PERSISTENT)) {
2570                                 int index = vd.vert_indices[vd.i];
2571
2572                                 /* persistent base */
2573                                 add_v3_v3(val, ss->layer_co[index]);
2574                         }
2575                         else {
2576                                 add_v3_v3(val, orig_data.co);
2577                         }
2578
2579                         sculpt_clip(sd, ss, vd.co, val);
2580
2581                         if (vd.mvert)
2582                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2583                 }
2584         }
2585         BKE_pbvh_vertex_iter_end;
2586 }
2587
2588 static void do_layer_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2589 {
2590         SculptSession *ss = ob->sculpt;
2591         Brush *brush = BKE_paint_brush(&sd->paint);
2592         float offset[3];
2593
2594         mul_v3_v3v3(offset, ss->cache->scale, ss->cache->sculpt_normal_symm);
2595
2596         SculptThreadedTaskData data = {
2597             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2598             .offset = offset,
2599         };
2600         BLI_mutex_init(&data.mutex);
2601
2602         BLI_task_parallel_range_ex(
2603                     0, totnode, &data, NULL, 0, do_layer_brush_task_cb_ex,
2604                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2605
2606         BLI_mutex_end(&data.mutex);
2607 }
2608
2609 static void do_inflate_brush_task_cb_ex(
2610         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2611 {
2612         SculptThreadedTaskData *data = userdata;
2613         SculptSession *ss = data->ob->sculpt;
2614         Brush *brush = data->brush;
2615
2616         PBVHVertexIter vd;
2617         SculptBrushTest test;
2618         float (*proxy)[3];
2619         const float bstrength = ss->cache->bstrength;
2620
2621         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2622
2623         sculpt_brush_test_init(ss, &test);
2624
2625         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2626         {
2627                 if (sculpt_brush_test(&test, vd.co)) {
2628                         const float fade = bstrength * tex_strength(
2629                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2630                         float val[3];
2631
2632                         if (vd.fno)
2633                                 copy_v3_v3(val, vd.fno);
2634                         else
2635                                 normal_short_to_float_v3(val, vd.no);
2636
2637                         mul_v3_fl(val, fade * ss->cache->radius);
2638                         mul_v3_v3v3(proxy[vd.i], val, ss->cache->scale);
2639
2640                         if (vd.mvert)
2641                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2642                 }
2643         }
2644         BKE_pbvh_vertex_iter_end;
2645 }
2646
2647 static void do_inflate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2648 {
2649         Brush *brush = BKE_paint_brush(&sd->paint);
2650
2651         SculptThreadedTaskData data = {
2652             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2653         };
2654
2655         BLI_task_parallel_range_ex(
2656                     0, totnode, &data, NULL, 0, do_inflate_brush_task_cb_ex,
2657                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2658 }
2659
2660 static void calc_sculpt_plane(
2661         Sculpt *sd, Object *ob,
2662         PBVHNode **nodes, int totnode,
2663         float r_area_no[3], float r_area_co[3])
2664 {
2665         SculptSession *ss = ob->sculpt;
2666         Brush *brush = BKE_paint_brush(&sd->paint);
2667
2668         if (ss->cache->mirror_symmetry_pass == 0 &&
2669             ss->cache->radial_symmetry_pass == 0 &&
2670             ss->cache->tile_pass == 0 &&
2671             (ss->cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
2672         {
2673                 switch (brush->sculpt_plane) {
2674                         case SCULPT_DISP_DIR_VIEW:
2675                                 copy_v3_v3(r_area_no, ss->cache->true_view_normal);
2676                                 break;
2677
2678                         case SCULPT_DISP_DIR_X:
2679                                 ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
2680                                 break;
2681
2682                         case SCULPT_DISP_DIR_Y:
2683                                 ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
2684                                 break;
2685
2686                         case SCULPT_DISP_DIR_Z:
2687                                 ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
2688                                 break;
2689
2690                         case SCULPT_DISP_DIR_AREA:
2691                                 calc_area_normal_and_center(sd, ob, nodes, totnode, r_area_no, r_area_co);
2692                                 break;
2693
2694                         default:
2695                                 break;
2696                 }
2697
2698                 /* for flatten center */
2699                 /* flatten center has not been calculated yet if we are not using the area normal */
2700                 if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA)
2701                         calc_area_center(sd, ob, nodes, totnode, r_area_co);
2702
2703                 /* for area normal */
2704                 copy_v3_v3(ss->cache->sculpt_normal, r_area_no);
2705
2706                 /* for flatten center */
2707                 copy_v3_v3(ss->cache->last_center, r_area_co);
2708         }
2709         else {
2710                 /* for area normal */
2711                 copy_v3_v3(r_area_no, ss->cache->sculpt_normal);
2712
2713                 /* for flatten center */
2714                 copy_v3_v3(r_area_co, ss->cache->last_center);
2715
2716                 /* for area normal */
2717                 flip_v3(r_area_no, ss->cache->mirror_symmetry_pass);
2718
2719                 /* for flatten center */
2720                 flip_v3(r_area_co, ss->cache->mirror_symmetry_pass);
2721
2722                 /* for area normal */
2723                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_no);
2724
2725                 /* for flatten center */
2726                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_co);
2727
2728                 /* shift the plane for the current tile */
2729                 add_v3_v3(r_area_co, ss->cache->plane_offset);
2730         }
2731 }
2732
2733 /* Projects a point onto a plane along the plane's normal */
2734 static void point_plane_project(
2735         float intr[3],
2736         const float co[3], const float plane_normal[3], const float plane_center[3])
2737 {
2738         sub_v3_v3v3(intr, co, plane_center);
2739         mul_v3_v3fl(intr, plane_normal, dot_v3v3(plane_normal, intr));
2740         sub_v3_v3v3(intr, co, intr);
2741 }
2742
2743 static int plane_trim(const StrokeCache *cache, const Brush *brush, const float val[3])
2744 {
2745         return (!(brush->flag & BRUSH_PLANE_TRIM) ||
2746                 ((dot_v3v3(val, val) <= cache->radius_squared * cache->plane_trim_squared)));
2747 }
2748
2749 static bool plane_point_side_flip(
2750         const float co[3], const float plane_normal[3], const float plane_center[3],
2751         const bool flip)
2752 {
2753         float delta[3];
2754         float d;
2755
2756         sub_v3_v3v3(delta, co, plane_center);
2757         d = dot_v3v3(plane_normal, delta);
2758
2759         if (flip) d = -d;
2760
2761         return d <= 0.0f;
2762 }
2763
2764 static int plane_point_side(const float co[3], const float plane_normal[3], const float plane_center[3])
2765 {
2766         float delta[3];
2767
2768         sub_v3_v3v3(delta, co, plane_center);
2769         return dot_v3v3(plane_normal, delta) <= 0.0f;
2770 }
2771
2772 static float get_offset(Sculpt *sd, SculptSession *ss)
2773 {
2774         Brush *brush = BKE_paint_brush(&sd->paint);
2775
2776         float rv = brush->plane_offset;
2777
2778         if (brush->flag & BRUSH_OFFSET_PRESSURE) {
2779                 rv *= ss->cache->pressure;
2780         }
2781
2782         return rv;
2783 }
2784
2785 static void do_flatten_brush_task_cb_ex(
2786         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2787 {
2788         SculptThreadedTaskData *data = userdata;
2789         SculptSession *ss = data->ob->sculpt;
2790         Brush *brush = data->brush;
2791         const float *area_no = data->area_no;
2792         const float *area_co = data->area_co;
2793
2794         PBVHVertexIter vd;
2795         SculptBrushTest test;
2796         float (*proxy)[3];
2797         const float bstrength = ss->cache->bstrength;
2798
2799         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2800
2801         sculpt_brush_test_init(ss, &test);
2802
2803         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2804         {
2805                 if (sculpt_brush_test_sq(&test, vd.co)) {
2806                         float intr[3];
2807                         float val[3];
2808
2809                         point_plane_project(intr, vd.co, area_no, area_co);
2810
2811                         sub_v3_v3v3(val, intr, vd.co);
2812
2813                         if (plane_trim(ss->cache, brush, val)) {
2814                                 const float fade = bstrength * tex_strength(
2815                                                        ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
2816                                                        thread_id);
2817
2818                                 mul_v3_v3fl(proxy[vd.i], val, fade);
2819
2820                                 if (vd.mvert)
2821                                         vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2822                         }
2823                 }
2824         }
2825         BKE_pbvh_vertex_iter_end;
2826 }
2827
2828 static void do_flatten_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2829 {
2830         SculptSession *ss = ob->sculpt;
2831         Brush *brush = BKE_paint_brush(&sd->paint);
2832
2833         const float radius = ss->cache->radius;
2834
2835         float area_no[3];
2836         float area_co[3];
2837
2838         float offset = get_offset(sd, ss);
2839         float displace;
2840         float temp[3];
2841
2842         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
2843
2844         displace = radius * offset;
2845
2846         mul_v3_v3v3(temp, area_no, ss->cache->scale);
2847         mul_v3_fl(temp, displace);
2848         add_v3_v3(area_co, temp);
2849
2850         SculptThreadedTaskData data = {
2851             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2852             .area_no = area_no, .area_co = area_co,
2853         };
2854
2855         BLI_task_parallel_range_ex(
2856                     0, totnode, &data, NULL, 0, do_flatten_brush_task_cb_ex,
2857                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2858 }
2859
2860 static void do_clay_brush_task_cb_ex(
2861         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2862 {
2863         SculptThreadedTaskData *data = userdata;
2864         SculptSession *ss = data->ob->sculpt;
2865         Brush *brush = data->brush;
2866         const float *area_no = data->area_no;
2867         const float *area_co = data->area_co;
2868
2869         PBVHVertexIter vd;
2870         SculptBrushTest test;
2871         float (*proxy)[3];
2872         const bool flip = (ss->cache->bstrength < 0);
2873         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
2874
2875         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2876
2877         sculpt_brush_test_init(ss, &test);
2878
2879         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2880         {
2881                 if (sculpt_brush_test_sq(&test, vd.co)) {
2882                         if (plane_point_side_flip(vd.co, area_no, area_co, flip)) {
2883                                 float intr[3];
2884                                 float val[3];
2885
2886                                 point_plane_project(intr, vd.co, area_no, area_co);
2887
2888                                 sub_v3_v3v3(val, intr, vd.co);
2889
2890                                 if (plane_trim(ss->cache, brush, val)) {
2891                                         /* note, the normal from the vertices is ignored,
2892                                          * causes glitch with planes, see: T44390 */
2893                                         const float fade = bstrength * tex_strength(
2894                                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
2895                                                                thread_id);
2896
2897                                         mul_v3_v3fl(proxy[vd.i], val, fade);
2898
2899                                         if (vd.mvert)
2900                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2901                                 }
2902                         }
2903                 }
2904         }
2905         BKE_pbvh_vertex_iter_end;
2906 }
2907
2908 static void do_clay_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2909 {
2910         SculptSession *ss = ob->sculpt;
2911         Brush *brush = BKE_paint_brush(&sd->paint);
2912
2913         const bool flip = (ss->cache->bstrength < 0);
2914         const float radius = flip ? -ss->cache->radius : ss->cache->radius;
2915
2916         float offset = get_offset(sd, ss);
2917         float displace;
2918
2919         float area_no[3];
2920         float area_co[3];
2921         float temp[3];
2922
2923         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
2924
2925         displace = radius * (0.25f + offset);
2926
2927         mul_v3_v3v3(temp, area_no, ss->cache->scale);
2928         mul_v3_fl(temp, displace);
2929         add_v3_v3(area_co, temp);
2930
2931         /* add_v3_v3v3(p, ss->cache->location, area_no); */
2932
2933         SculptThreadedTaskData data = {
2934             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2935             .area_no = area_no, .area_co = area_co,
2936         };
2937
2938         BLI_task_parallel_range_ex(
2939                     0, totnode, &data, NULL, 0, do_clay_brush_task_cb_ex,
2940                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2941 }
2942
2943 static void do_clay_strips_brush_task_cb_ex(
2944         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2945 {
2946         SculptThreadedTaskData *data = userdata;
2947         SculptSession *ss = data->ob->sculpt;
2948         Brush *brush = data->brush;
2949         float (*mat)[4] = data->mat;
2950         const float *area_no_sp = data->area_no_sp;
2951         const float *area_co = data->area_co;
2952
2953         PBVHVertexIter vd;
2954         SculptBrushTest test;
2955         float (*proxy)[3];
2956         const bool flip = (ss->cache->bstrength < 0);
2957         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
2958
2959         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2960
2961         sculpt_brush_test_init(ss, &test);
2962
2963         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2964         {
2965                 if (sculpt_brush_test_cube(&test, vd.co, mat)) {
2966                         if (plane_point_side_flip(vd.co, area_no_sp, area_co, flip)) {
2967                                 float intr[3];
2968                                 float val[3];
2969
2970                                 point_plane_project(intr, vd.co, area_no_sp, area_co);
2971
2972                                 sub_v3_v3v3(val, intr, vd.co);
2973
2974                                 if (plane_trim(ss->cache, brush, val)) {
2975                                         /* note, the normal from the vertices is ignored,
2976                                          * causes glitch with planes, see: T44390 */
2977                                         const float fade = bstrength * tex_strength(
2978                                                                ss, brush, vd.co, ss->cache->radius * test.dist,
2979                                                                vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2980
2981                                         mul_v3_v3fl(proxy[vd.i], val, fade);
2982
2983                                         if (vd.mvert)
2984                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2985                                 }
2986                         }
2987                 }
2988         }
2989         BKE_pbvh_vertex_iter_end;
2990 }
2991
2992 static void do_clay_strips_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2993 {
2994         SculptSession *ss = ob->sculpt;
2995         Brush *brush = BKE_paint_brush(&sd->paint);
2996
2997         const bool flip = (ss->cache->bstrength < 0);
2998         const float radius    = flip ? -ss->cache->radius : ss->cache->radius;
2999         const float offset    = get_offset(sd, ss);
3000         const float displace  = radius * (0.25f + offset);
3001
3002         float area_no_sp[3];  /* the sculpt-plane normal (whatever its set to) */
3003         float area_no[3];     /* geometry normal */
3004         float area_co[3];
3005
3006         float temp[3];
3007         float mat[4][4];
3008         float scale[4][4];
3009         float tmat[4][4];
3010
3011         calc_sculpt_plane(sd, ob, nodes, totnode, area_no_sp, area_co);
3012
3013         if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA || (brush->flag & BRUSH_ORIGINAL_NORMAL))
3014                 calc_area_normal(sd, ob, nodes, totnode, area_no);
3015         else
3016                 copy_v3_v3(area_no, area_no_sp);
3017
3018         /* delay the first daub because grab delta is not setup */
3019         if (ss->cache->first_time)
3020                 return;
3021
3022         mul_v3_v3v3(temp, area_no_sp, ss->cache->scale);
3023         mul_v3_fl(temp, displace);
3024         add_v3_v3(area_co, temp);
3025
3026         /* init mat */
3027         cross_v3_v3v3(mat[0], area_no, ss->cache->grab_delta_symmetry);
3028         mat[0][3] = 0;
3029         cross_v3_v3v3(mat[1], area_no, mat[0]);
3030         mat[1][3] = 0;
3031         copy_v3_v3(mat[2], area_no);
3032         mat[2][3] = 0;
3033         copy_v3_v3(mat[3], ss->cache->location);
3034         mat[3][3] = 1;
3035         normalize_m4(mat);
3036
3037         /* scale mat */
3038         scale_m4_fl(scale, ss->cache->radius);
3039         mul_m4_m4m4(tmat, mat, scale);
3040         invert_m4_m4(mat, tmat);
3041
3042         SculptThreadedTaskData data = {
3043             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3044             .area_no_sp = area_no_sp, .area_co = area_co, .mat = mat,
3045         };
3046
3047         BLI_task_parallel_range_ex(
3048                     0, totnode, &data, NULL, 0, do_clay_strips_brush_task_cb_ex,
3049                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3050 }
3051
3052 static void do_fill_brush_task_cb_ex(
3053         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3054 {
3055         SculptThreadedTaskData *data = userdata;
3056         SculptSession *ss = data->ob->sculpt;
3057         Brush *brush = data->brush;
3058         const float *area_no = data->area_no;
3059         const float *area_co = data->area_co;
3060
3061         PBVHVertexIter vd;
3062         SculptBrushTest test;
3063         float (*proxy)[3];
3064         const float bstrength = ss->cache->bstrength;
3065
3066         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3067
3068         sculpt_brush_test_init(ss, &test);
3069
3070         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3071         {
3072                 if (sculpt_brush_test_sq(&test, vd.co)) {
3073                         if (plane_point_side(vd.co, area_no, area_co)) {
3074                                 float intr[3];
3075                                 float val[3];
3076
3077                                 point_plane_project(intr, vd.co, area_no, area_co);
3078
3079                                 sub_v3_v3v3(val, intr, vd.co);
3080
3081                                 if (plane_trim(ss->cache, brush, val)) {
3082                                         const float fade = bstrength * tex_strength(
3083                                                                ss, brush, vd.co, sqrtf(test.dist),
3084                                                                vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
3085
3086                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3087
3088                                         if (vd.mvert)
3089                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3090                                 }
3091                         }
3092                 }
3093         }
3094         BKE_pbvh_vertex_iter_end;
3095 }
3096
3097 static void do_fill_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3098 {
3099         SculptSession *ss = ob->sculpt;
3100         Brush *brush = BKE_paint_brush(&sd->paint);
3101
3102         const float radius = ss->cache->radius;
3103
3104         float area_no[3];
3105         float area_co[3];
3106         float offset = get_offset(sd, ss);
3107
3108         float displace;
3109
3110         float temp[3];
3111
3112         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
3113
3114         displace = radius * offset;
3115
3116         mul_v3_v3v3(temp, area_no, ss->cache->scale);
3117         mul_v3_fl(temp, displace);
3118         add_v3_v3(area_co, temp);
3119
3120         SculptThreadedTaskData data = {
3121             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3122             .area_no = area_no, .area_co = area_co,
3123         };
3124
3125         BLI_task_parallel_range_ex(
3126                     0, totnode, &data, NULL, 0, do_fill_brush_task_cb_ex,
3127                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3128 }
3129
3130 static void do_scrape_brush_task_cb_ex(
3131         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3132 {
3133         SculptThreadedTaskData *data = userdata;
3134         SculptSession *ss = data->ob->sculpt;
3135         Brush *brush = data->brush;
3136         const float *area_no = data->area_no;
3137         const float *area_co = data->area_co;
3138
3139         PBVHVertexIter vd;
3140         SculptBrushTest test;
3141         float (*proxy)[3];
3142         const float bstrength = ss->cache->bstrength;
3143
3144         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3145
3146         sculpt_brush_test_init(ss, &test);
3147
3148         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3149         {
3150                 if (sculpt_brush_test_sq(&test, vd.co)) {
3151                         if (!plane_point_side(vd.co, area_no, area_co)) {
3152                                 float intr[3];
3153                                 float val[3];
3154
3155                                 point_plane_project(intr, vd.co, area_no, area_co);
3156
3157                                 sub_v3_v3v3(val, intr, vd.co);
3158
3159                                 if (plane_trim(ss->cache, brush, val)) {
3160                                         const float fade = bstrength * tex_strength(
3161                                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
3162                                                                thread_id);
3163
3164                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3165
3166                                         if (vd.mvert)
3167                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3168                                 }
3169                         }
3170                 }
3171         }
3172         BKE_pbvh_vertex_iter_end;
3173 }
3174
3175 static void do_scrape_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3176 {
3177         SculptSession *ss = ob->sculpt;
3178         Brush *brush = BKE_paint_brush(&sd->paint);
3179
3180         const float radius = ss->cache->radius;
3181
3182         float area_no[3];
3183         float area_co[3];
3184         float offset = get_offset(sd, ss);
3185
3186         float displace;
3187
3188         float temp[3];
3189
3190         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
3191
3192         displace = -radius * offset;
3193
3194         mul_v3_v3v3(temp, area_no, ss->cache->scale);
3195         mul_v3_fl(temp, displace);
3196         add_v3_v3(area_co, temp);
3197
3198         SculptThreadedTaskData data = {
3199             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3200             .area_no = area_no, .area_co = area_co,
3201         };
3202
3203         BLI_task_parallel_range_ex(
3204                     0, totnode, &data, NULL, 0, do_scrape_brush_task_cb_ex,
3205                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3206 }
3207
3208 static void do_gravity_task_cb_ex(
3209         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3210 {
3211         SculptThreadedTaskData *data = userdata;
3212         SculptSession *ss = data->ob->sculpt;
3213         Brush *brush = data->brush;
3214         float *offset = data->offset;
3215
3216         PBVHVertexIter vd;
3217         SculptBrushTest test;
3218         float (*proxy)[3];
3219
3220         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3221
3222         sculpt_brush_test_init(ss, &test);
3223
3224         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE) {
3225                 if (sculpt_brush_test_sq(&test, vd.co)) {
3226                         const float fade = tex_strength(
3227                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
3228                                                thread_id);
3229
3230                         mul_v3_v3fl(proxy[vd.i], offset, fade);
3231
3232                         if (vd.mvert)
3233                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3234                 }
3235         }
3236         BKE_pbvh_vertex_iter_end;
3237 }
3238
3239 static void do_gravity(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode, float bstrength)
3240 {
3241         SculptSession *ss = ob->sculpt;
3242         Brush *brush = BKE_paint_brush(&sd->paint);
3243
3244         float offset[3]/*, area_no[3]*/;
3245         float gravity_vector[3];
3246
3247         mul_v3_v3fl(gravity_vector, ss->cache->gravity_direction, -ss->cache->radius_squared);
3248
3249         /* offset with as much as possible factored in already */
3250         mul_v3_v3v3(offset, gravity_vector, ss->cache->scale);
3251         mul_v3_fl(offset, bstrength);
3252
3253         /* threaded loop over nodes */
3254         SculptThreadedTaskData data = {
3255             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3256             .offset = offset,
3257         };
3258
3259         BLI_task_parallel_range_ex(