Math Lib: rotate matrix cleanup
[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[3][3];
825                 axis_angle_to_mat3_single(mat, axis, angle);
826                 mul_m3_v3(mat, mirror);
827         }
828
829         /* distsq = len_squared_v3v3(mirror, cache->traced_location); */
830         distsq = len_squared_v3v3(mirror, cache->true_location);
831
832         if (distsq <= 4.0f * (cache->radius_squared))
833                 return (2.0f * (cache->radius) - sqrtf(distsq)) / (2.0f * (cache->radius));
834         else
835                 return 0;
836 }
837
838 static float calc_radial_symmetry_feather(Sculpt *sd, StrokeCache *cache, const char symm, const char axis)
839 {
840         int i;
841         float overlap;
842
843         overlap = 0;
844         for (i = 1; i < sd->radial_symm[axis - 'X']; ++i) {
845                 const float angle = 2 * M_PI * i / sd->radial_symm[axis - 'X'];
846                 overlap += calc_overlap(cache, symm, axis, angle);
847         }
848
849         return overlap;
850 }
851
852 static float calc_symmetry_feather(Sculpt *sd, StrokeCache *cache)
853 {
854         if (sd->paint.symmetry_flags & PAINT_SYMMETRY_FEATHER) {
855                 float overlap;
856                 int symm = cache->symmetry;
857                 int i;
858
859                 overlap = 0;
860                 for (i = 0; i <= symm; i++) {
861                         if (i == 0 || (symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
862
863                                 overlap += calc_overlap(cache, i, 0, 0);
864
865                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'X');
866                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Y');
867                                 overlap += calc_radial_symmetry_feather(sd, cache, i, 'Z');
868                         }
869                 }
870
871                 return 1 / overlap;
872         }
873         else {
874                 return 1;
875         }
876 }
877
878 /** \name Calculate Normal and Center
879  *
880  * Calculate geometry surrounding the brush center.
881  * (optionally using original coordinates).
882  *
883  * Functions are:
884  * - #calc_area_center
885  * - #calc_area_normal
886  * - #calc_area_normal_and_center
887  *
888  * \note These are all _very_ similar, when changing one, check others.
889  * \{ */
890
891 static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
892 {
893         SculptThreadedTaskData *data = userdata;
894         SculptSession *ss = data->ob->sculpt;
895         float (*area_nos)[3] = data->area_nos;
896         float (*area_cos)[3] = data->area_cos;
897
898         PBVHVertexIter vd;
899         SculptBrushTest test;
900         SculptUndoNode *unode;
901
902         float private_co[2][3] = {{0.0f}};
903         float private_no[2][3] = {{0.0f}};
904         int   private_count[2] = {0};
905         bool use_original;
906
907         unode = sculpt_undo_push_node(data->ob, data->nodes[n], SCULPT_UNDO_COORDS);
908         sculpt_brush_test_init(ss, &test);
909
910         use_original = (ss->cache->original && (unode->co || unode->bm_entry));
911
912         /* when the mesh is edited we can't rely on original coords
913          * (original mesh may not even have verts in brush radius) */
914         if (use_original && data->has_bm_orco) {
915                 float (*orco_coords)[3];
916                 int   (*orco_tris)[3];
917                 int     orco_tris_num;
918                 int i;
919
920                 BKE_pbvh_node_get_bm_orco_data(data->nodes[n], &orco_tris, &orco_tris_num, &orco_coords);
921
922                 for (i = 0; i < orco_tris_num; i++) {
923                         const float *co_tri[3] = {
924                             orco_coords[orco_tris[i][0]],
925                             orco_coords[orco_tris[i][1]],
926                             orco_coords[orco_tris[i][2]],
927                         };
928                         float co[3];
929
930                         closest_on_tri_to_point_v3(co, test.location, UNPACK3(co_tri));
931
932                         if (sculpt_brush_test_fast(&test, co)) {
933                                 float no[3];
934                                 int flip_index;
935
936                                 normal_tri_v3(no, UNPACK3(co_tri));
937
938                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
939                                 if (area_cos)
940                                         add_v3_v3(private_co[flip_index], co);
941                                 if (area_nos)
942                                         add_v3_v3(private_no[flip_index], no);
943                                 private_count[flip_index] += 1;
944                         }
945                 }
946         }
947         else {
948                 BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
949                 {
950                         const float *co;
951                         const short *no_s;  /* bm_vert only */
952
953                         if (use_original) {
954                                 if (unode->bm_entry) {
955                                         BM_log_original_vert_data(ss->bm_log, vd.bm_vert, &co, &no_s);
956                                 }
957                                 else {
958                                         co = unode->co[vd.i];
959                                         no_s = unode->no[vd.i];
960                                 }
961                         }
962                         else {
963                                 co = vd.co;
964                         }
965
966                         if (sculpt_brush_test_fast(&test, co)) {
967                                 float no_buf[3];
968                                 const float *no;
969                                 int flip_index;
970
971                                 if (use_original) {
972                                         normal_short_to_float_v3(no_buf, no_s);
973                                         no = no_buf;
974                                 }
975                                 else {
976                                         if (vd.no) {
977                                                 normal_short_to_float_v3(no_buf, vd.no);
978                                                 no = no_buf;
979                                         }
980                                         else {
981                                                 no = vd.fno;
982                                         }
983                                 }
984
985                                 flip_index = (dot_v3v3(ss->cache->view_normal, no) <= 0.0f);
986                                 if (area_cos)
987                                         add_v3_v3(private_co[flip_index], co);
988                                 if (area_nos)
989                                         add_v3_v3(private_no[flip_index], no);
990                                 private_count[flip_index] += 1;
991                         }
992                 }
993                 BKE_pbvh_vertex_iter_end;
994         }
995
996         BLI_mutex_lock(&data->mutex);
997
998         /* for flatten center */
999         if (area_cos) {
1000                 add_v3_v3(area_cos[0], private_co[0]);
1001                 add_v3_v3(area_cos[1], private_co[1]);
1002         }
1003
1004         /* for area normal */
1005         if (area_nos) {
1006                 add_v3_v3(area_nos[0], private_no[0]);
1007                 add_v3_v3(area_nos[1], private_no[1]);
1008         }
1009
1010         /* weights */
1011         data->count[0] += private_count[0];
1012         data->count[1] += private_count[1];
1013
1014         BLI_mutex_unlock(&data->mutex);
1015 }
1016
1017 static void calc_area_center(
1018         Sculpt *sd, Object *ob,
1019         PBVHNode **nodes, int totnode,
1020         float r_area_co[3])
1021 {
1022         const Brush *brush = BKE_paint_brush(&sd->paint);
1023         SculptSession *ss = ob->sculpt;
1024         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1025         int n;
1026
1027         /* 0=towards view, 1=flipped */
1028         float area_cos[2][3] = {{0.0f}};
1029
1030         int count[2] = {0};
1031
1032         SculptThreadedTaskData data = {
1033                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1034                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = NULL, .count = count,
1035         };
1036         BLI_mutex_init(&data.mutex);
1037
1038         BLI_task_parallel_range(
1039                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1040                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1041
1042         BLI_mutex_end(&data.mutex);
1043
1044         /* for flatten center */
1045         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
1046                 if (count[n] != 0) {
1047                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
1048                         break;
1049                 }
1050         }
1051         if (n == 2) {
1052                 zero_v3(r_area_co);
1053         }
1054 }
1055
1056
1057 static void calc_area_normal(
1058         Sculpt *sd, Object *ob,
1059         PBVHNode **nodes, int totnode,
1060         float r_area_no[3])
1061 {
1062         const Brush *brush = BKE_paint_brush(&sd->paint);
1063         SculptSession *ss = ob->sculpt;
1064         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1065         int n;
1066
1067         /* 0=towards view, 1=flipped */
1068         float area_nos[2][3] = {{0.0f}};
1069
1070         int count[2] = {0};
1071
1072         SculptThreadedTaskData data = {
1073                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1074                 .has_bm_orco = has_bm_orco, .area_cos = NULL, .area_nos = area_nos, .count = count,
1075         };
1076         BLI_mutex_init(&data.mutex);
1077
1078         BLI_task_parallel_range(
1079                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1080                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1081
1082         BLI_mutex_end(&data.mutex);
1083
1084         /* for area normal */
1085         for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
1086                 if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
1087                         break;
1088                 }
1089         }
1090 }
1091
1092 /* this calculates flatten center and area normal together,
1093  * amortizing the memory bandwidth and loop overhead to calculate both at the same time */
1094 static void calc_area_normal_and_center(
1095         Sculpt *sd, Object *ob,
1096         PBVHNode **nodes, int totnode,
1097         float r_area_no[3], float r_area_co[3])
1098 {
1099         const Brush *brush = BKE_paint_brush(&sd->paint);
1100         SculptSession *ss = ob->sculpt;
1101         const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
1102         int n;
1103
1104         /* 0=towards view, 1=flipped */
1105         float area_cos[2][3] = {{0.0f}};
1106         float area_nos[2][3] = {{0.0f}};
1107
1108         int count[2] = {0};
1109
1110         SculptThreadedTaskData data = {
1111                 .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
1112                 .has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = area_nos, .count = count,
1113         };
1114         BLI_mutex_init(&data.mutex);
1115
1116         BLI_task_parallel_range(
1117                     0, totnode, &data, calc_area_normal_and_center_task_cb,
1118                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
1119
1120         BLI_mutex_end(&data.mutex);
1121
1122         /* for flatten center */
1123         for (n = 0; n < ARRAY_SIZE(area_cos); n++) {
1124                 if (count[n] != 0) {
1125                         mul_v3_v3fl(r_area_co, area_cos[n], 1.0f / count[n]);
1126                         break;
1127                 }
1128         }
1129         if (n == 2) {
1130                 zero_v3(r_area_co);
1131         }
1132
1133         /* for area normal */
1134         for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
1135                 if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
1136                         break;
1137                 }
1138         }
1139 }
1140
1141 /** \} */
1142
1143
1144 /* Return modified brush strength. Includes the direction of the brush, positive
1145  * values pull vertices, negative values push. Uses tablet pressure and a
1146  * special multiplier found experimentally to scale the strength factor. */
1147 static float brush_strength(
1148         const Sculpt *sd, const StrokeCache *cache,
1149         const float feather, const UnifiedPaintSettings *ups)
1150 {
1151         const Scene *scene = cache->vc->scene;
1152         const Brush *brush = BKE_paint_brush((Paint *)&sd->paint);
1153
1154         /* Primary strength input; square it to make lower values more sensitive */
1155         const float root_alpha = BKE_brush_alpha_get(scene, brush);
1156         float alpha        = root_alpha * root_alpha;
1157         float dir          = (brush->flag & BRUSH_DIR_IN) ? -1 : 1;
1158         float pressure     = BKE_brush_use_alpha_pressure(scene, brush) ? cache->pressure : 1;
1159         float pen_flip     = cache->pen_flip ? -1 : 1;
1160         float invert       = cache->invert ? -1 : 1;
1161         float overlap       = ups->overlap_factor;
1162         /* spacing is integer percentage of radius, divide by 50 to get
1163          * normalized diameter */
1164
1165         float flip         = dir * invert * pen_flip;
1166
1167         switch (brush->sculpt_tool) {
1168                 case SCULPT_TOOL_CLAY:
1169                 case SCULPT_TOOL_CLAY_STRIPS:
1170                 case SCULPT_TOOL_DRAW:
1171                 case SCULPT_TOOL_LAYER:
1172                         return alpha * flip * pressure * overlap * feather;
1173                         
1174                 case SCULPT_TOOL_MASK:
1175                         overlap = (1 + overlap) / 2;
1176                         switch ((BrushMaskTool)brush->mask_tool) {
1177                                 case BRUSH_MASK_DRAW:
1178                                         return alpha * flip * pressure * overlap * feather;
1179                                 case BRUSH_MASK_SMOOTH:
1180                                         return alpha * pressure * feather;
1181                         }
1182
1183                 case SCULPT_TOOL_CREASE:
1184                 case SCULPT_TOOL_BLOB:
1185                         return alpha * flip * pressure * overlap * feather;
1186
1187                 case SCULPT_TOOL_INFLATE:
1188                         if (flip > 0) {
1189                                 return 0.250f * alpha * flip * pressure * overlap * feather;
1190                         }
1191                         else {
1192                                 return 0.125f * alpha * flip * pressure * overlap * feather;
1193                         }
1194
1195                 case SCULPT_TOOL_FILL:
1196                 case SCULPT_TOOL_SCRAPE:
1197                 case SCULPT_TOOL_FLATTEN:
1198                         if (flip > 0) {
1199                                 overlap = (1 + overlap) / 2;
1200                                 return alpha * flip * pressure * overlap * feather;
1201                         }
1202                         else {
1203                                 /* reduce strength for DEEPEN, PEAKS, and CONTRAST */
1204                                 return 0.5f * alpha * flip * pressure * overlap * feather; 
1205                         }
1206
1207                 case SCULPT_TOOL_SMOOTH:
1208                         return alpha * pressure * feather;
1209
1210                 case SCULPT_TOOL_PINCH:
1211                         if (flip > 0) {
1212                                 return alpha * flip * pressure * overlap * feather;
1213                         }
1214                         else {
1215                                 return 0.25f * alpha * flip * pressure * overlap * feather;
1216                         }
1217
1218                 case SCULPT_TOOL_NUDGE:
1219                         overlap = (1 + overlap) / 2;
1220                         return alpha * pressure * overlap * feather;
1221
1222                 case SCULPT_TOOL_THUMB:
1223                         return alpha * pressure * feather;
1224
1225                 case SCULPT_TOOL_SNAKE_HOOK:
1226                         return root_alpha * feather;
1227
1228                 case SCULPT_TOOL_GRAB:
1229                         return root_alpha * feather;
1230
1231                 case SCULPT_TOOL_ROTATE:
1232                         return alpha * pressure * feather;
1233
1234                 default:
1235                         return 0;
1236         }
1237 }
1238
1239 /* Return a multiplier for brush strength on a particular vertex. */
1240 static float tex_strength(SculptSession *ss, Brush *br,
1241                           const float brush_point[3],
1242                           const float len,
1243                           const short vno[3],
1244                           const float fno[3],
1245                           const float mask,
1246                           const int thread_id)
1247 {
1248         StrokeCache *cache = ss->cache;
1249         const Scene *scene = cache->vc->scene;
1250         MTex *mtex = &br->mtex;
1251         float avg = 1;
1252         float rgba[4];
1253         float point[3];
1254
1255         sub_v3_v3v3(point, brush_point, cache->plane_offset);
1256
1257         if (!mtex->tex) {
1258                 avg = 1;
1259         }
1260         else if (mtex->brush_map_mode == MTEX_MAP_MODE_3D) {
1261                 /* Get strength by feeding the vertex 
1262                  * location directly into a texture */
1263                 avg = BKE_brush_sample_tex_3D(scene, br, point, rgba, 0, ss->tex_pool);
1264         }
1265         else if (ss->texcache) {
1266                 float symm_point[3], point_2d[2];
1267                 float x = 0.0f, y = 0.0f; /* Quite warnings */
1268
1269                 /* if the active area is being applied for symmetry, flip it
1270                  * across the symmetry axis and rotate it back to the original
1271                  * position in order to project it. This insures that the 
1272                  * brush texture will be oriented correctly. */
1273
1274                 flip_v3_v3(symm_point, point, cache->mirror_symmetry_pass);
1275
1276                 if (cache->radial_symmetry_pass)
1277                         mul_m4_v3(cache->symm_rot_mat_inv, symm_point);
1278
1279                 ED_view3d_project_float_v2_m4(cache->vc->ar, symm_point, point_2d, cache->projection_mat);
1280
1281                 /* still no symmetry supported for other paint modes.
1282                  * Sculpt does it DIY */
1283                 if (mtex->brush_map_mode == MTEX_MAP_MODE_AREA) {
1284                         /* Similar to fixed mode, but projects from brush angle
1285                          * rather than view direction */
1286
1287                         mul_m4_v3(cache->brush_local_mat, symm_point);
1288
1289                         x = symm_point[0];
1290                         y = symm_point[1];
1291
1292                         x *= br->mtex.size[0];
1293                         y *= br->mtex.size[1];
1294
1295                         x += br->mtex.ofs[0];
1296                         y += br->mtex.ofs[1];
1297
1298                         avg = paint_get_tex_pixel(&br->mtex, x, y, ss->tex_pool, thread_id);
1299
1300                         avg += br->texture_sample_bias;
1301                 }
1302                 else {
1303                         const float point_3d[3] = {point_2d[0], point_2d[1], 0.0f};
1304                         avg = BKE_brush_sample_tex_3D(scene, br, point_3d, rgba, 0, ss->tex_pool);
1305                 }
1306         }
1307
1308         /* Falloff curve */
1309         avg *= BKE_brush_curve_strength(br, len, cache->radius);
1310
1311         avg *= frontface(br, cache->view_normal, vno, fno);
1312
1313         /* Paint mask */
1314         avg *= 1.0f - mask;
1315
1316         return avg;
1317 }
1318
1319 typedef struct {
1320         Sculpt *sd;
1321         SculptSession *ss;
1322         float radius_squared;
1323         bool original;
1324 } SculptSearchSphereData;
1325
1326 /* Test AABB against sphere */
1327 static bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
1328 {
1329         SculptSearchSphereData *data = data_v;
1330         float *center = data->ss->cache->location, nearest[3];
1331         float t[3], bb_min[3], bb_max[3];
1332         int i;
1333
1334         if (data->original)
1335                 BKE_pbvh_node_get_original_BB(node, bb_min, bb_max);
1336         else
1337                 BKE_pbvh_node_get_BB(node, bb_min, bb_max);
1338         
1339         for (i = 0; i < 3; ++i) {
1340                 if (bb_min[i] > center[i])
1341                         nearest[i] = bb_min[i];
1342                 else if (bb_max[i] < center[i])
1343                         nearest[i] = bb_max[i];
1344                 else
1345                         nearest[i] = center[i]; 
1346         }
1347         
1348         sub_v3_v3v3(t, center, nearest);
1349
1350         return len_squared_v3(t) < data->radius_squared;
1351 }
1352
1353 /* Handles clipping against a mirror modifier and SCULPT_LOCK axis flags */
1354 static void sculpt_clip(Sculpt *sd, SculptSession *ss, float co[3], const float val[3])
1355 {
1356         int i;
1357
1358         for (i = 0; i < 3; ++i) {
1359                 if (sd->flags & (SCULPT_LOCK_X << i))
1360                         continue;
1361
1362                 if ((ss->cache->flag & (CLIP_X << i)) && (fabsf(co[i]) <= ss->cache->clip_tolerance[i]))
1363                         co[i] = 0.0f;
1364                 else
1365                         co[i] = val[i];
1366         }
1367 }
1368
1369 /* Calculate primary direction of movement for many brushes */
1370 static void calc_sculpt_normal(
1371         Sculpt *sd, Object *ob,
1372         PBVHNode **nodes, int totnode,
1373         float r_area_no[3])
1374 {
1375         const Brush *brush = BKE_paint_brush(&sd->paint);
1376         const SculptSession *ss = ob->sculpt;
1377
1378         switch (brush->sculpt_plane) {
1379                 case SCULPT_DISP_DIR_VIEW:
1380                         copy_v3_v3(r_area_no, ss->cache->true_view_normal);
1381                         break;
1382
1383                 case SCULPT_DISP_DIR_X:
1384                         ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
1385                         break;
1386
1387                 case SCULPT_DISP_DIR_Y:
1388                         ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
1389                         break;
1390
1391                 case SCULPT_DISP_DIR_Z:
1392                         ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
1393                         break;
1394
1395                 case SCULPT_DISP_DIR_AREA:
1396                         calc_area_normal(sd, ob, nodes, totnode, r_area_no);
1397                         break;
1398
1399                 default:
1400                         break;
1401         }
1402 }
1403
1404 static void update_sculpt_normal(Sculpt *sd, Object *ob,
1405                                  PBVHNode **nodes, int totnode)
1406 {
1407         const Brush *brush = BKE_paint_brush(&sd->paint);
1408         StrokeCache *cache = ob->sculpt->cache;
1409         
1410         if (cache->mirror_symmetry_pass == 0 &&
1411             cache->radial_symmetry_pass == 0 &&
1412             (cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
1413         {
1414                 calc_sculpt_normal(sd, ob, nodes, totnode, cache->sculpt_normal);
1415                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1416         }
1417         else {
1418                 copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
1419                 flip_v3(cache->sculpt_normal_symm, cache->mirror_symmetry_pass);
1420                 mul_m4_v3(cache->symm_rot_mat, cache->sculpt_normal_symm);
1421         }
1422 }
1423
1424 static void calc_local_y(ViewContext *vc, const float center[3], float y[3])
1425 {
1426         Object *ob = vc->obact;
1427         float loc[3], mval_f[2] = {0.0f, 1.0f};
1428         float zfac;
1429
1430         mul_v3_m4v3(loc, ob->imat, center);
1431         zfac = ED_view3d_calc_zfac(vc->rv3d, loc, NULL);
1432
1433         ED_view3d_win_to_delta(vc->ar, mval_f, y, zfac);
1434         normalize_v3(y);
1435
1436         add_v3_v3(y, ob->loc);
1437         mul_m4_v3(ob->imat, y);
1438 }
1439
1440 static void calc_brush_local_mat(const Brush *brush, Object *ob,
1441                                  float local_mat[4][4])
1442 {
1443         const StrokeCache *cache = ob->sculpt->cache;
1444         float tmat[4][4];
1445         float mat[4][4];
1446         float scale[4][4];
1447         float angle, v[3];
1448         float up[3];
1449
1450         /* Ensure ob->imat is up to date */
1451         invert_m4_m4(ob->imat, ob->obmat);
1452
1453         /* Initialize last column of matrix */
1454         mat[0][3] = 0;
1455         mat[1][3] = 0;
1456         mat[2][3] = 0;
1457         mat[3][3] = 1;
1458
1459         /* Get view's up vector in object-space */
1460         calc_local_y(cache->vc, cache->location, up);
1461
1462         /* Calculate the X axis of the local matrix */
1463         cross_v3_v3v3(v, up, cache->sculpt_normal);
1464         /* Apply rotation (user angle, rake, etc.) to X axis */
1465         angle = brush->mtex.rot - cache->special_rotation;
1466         rotate_v3_v3v3fl(mat[0], v, cache->sculpt_normal, angle);
1467
1468         /* Get other axes */
1469         cross_v3_v3v3(mat[1], cache->sculpt_normal, mat[0]);
1470         copy_v3_v3(mat[2], cache->sculpt_normal);
1471
1472         /* Set location */
1473         copy_v3_v3(mat[3], cache->location);
1474
1475         /* Scale by brush radius */
1476         normalize_m4(mat);
1477         scale_m4_fl(scale, cache->radius);
1478         mul_m4_m4m4(tmat, mat, scale);
1479
1480         /* Return inverse (for converting from modelspace coords to local
1481          * area coords) */
1482         invert_m4_m4(local_mat, tmat);
1483 }
1484
1485 static void update_brush_local_mat(Sculpt *sd, Object *ob)
1486 {
1487         StrokeCache *cache = ob->sculpt->cache;
1488
1489         if (cache->mirror_symmetry_pass == 0 &&
1490             cache->radial_symmetry_pass == 0)
1491         {
1492                 calc_brush_local_mat(BKE_paint_brush(&sd->paint), ob,
1493                                      cache->brush_local_mat);
1494         }
1495 }
1496
1497 /* For the smooth brush, uses the neighboring vertices around vert to calculate
1498  * a smoothed location for vert. Skips corner vertices (used by only one
1499  * polygon.) */
1500 static void neighbor_average(SculptSession *ss, float avg[3], unsigned vert)
1501 {
1502         const MeshElemMap *vert_map = &ss->pmap[vert];
1503         const MVert *mvert = ss->mvert;
1504         float (*deform_co)[3] = ss->deform_cos;
1505
1506         /* Don't modify corner vertices */
1507         if (vert_map->count > 1) {
1508                 int i, total = 0;
1509
1510                 zero_v3(avg);
1511
1512                 for (i = 0; i < vert_map->count; i++) {
1513                         const MPoly *p = &ss->mpoly[vert_map->indices[i]];
1514                         unsigned f_adj_v[2];
1515
1516                         if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1517                                 int j;
1518                                 for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1519                                         if (vert_map->count != 2 || ss->pmap[f_adj_v[j]].count <= 2) {
1520                                                 add_v3_v3(avg, deform_co ? deform_co[f_adj_v[j]] :
1521                                                           mvert[f_adj_v[j]].co);
1522
1523                                                 total++;
1524                                         }
1525                                 }
1526                         }
1527                 }
1528
1529                 if (total > 0) {
1530                         mul_v3_fl(avg, 1.0f / total);
1531                         return;
1532                 }
1533         }
1534
1535         copy_v3_v3(avg, deform_co ? deform_co[vert] : mvert[vert].co);
1536 }
1537
1538 /* Similar to neighbor_average(), but returns an averaged mask value
1539  * instead of coordinate. Also does not restrict based on border or
1540  * corner vertices. */
1541 static float neighbor_average_mask(SculptSession *ss, unsigned vert)
1542 {
1543         const float *vmask = ss->vmask;
1544         float avg = 0;
1545         int i, total = 0;
1546
1547         for (i = 0; i < ss->pmap[vert].count; i++) {
1548                 const MPoly *p = &ss->mpoly[ss->pmap[vert].indices[i]];
1549                 unsigned f_adj_v[2];
1550
1551                 if (poly_get_adj_loops_from_vert(p, ss->mloop, vert, f_adj_v) != -1) {
1552                         int j;
1553                         for (j = 0; j < ARRAY_SIZE(f_adj_v); j += 1) {
1554                                 avg += vmask[f_adj_v[j]];
1555                                 total++;
1556                         }
1557                 }
1558         }
1559
1560         if (total > 0)
1561                 return avg / (float)total;
1562         else
1563                 return vmask[vert];
1564 }
1565
1566 /* Same logic as neighbor_average(), but for bmesh rather than mesh */
1567 static void bmesh_neighbor_average(float avg[3], BMVert *v)
1568 {
1569         /* logic for 3 or more is identical */
1570         const int vfcount = BM_vert_face_count_ex(v, 3);
1571
1572         /* Don't modify corner vertices */
1573         if (vfcount > 1) {
1574                 BMIter liter;
1575                 BMLoop *l;
1576                 int i, total = 0;
1577
1578                 zero_v3(avg);
1579
1580                 BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1581                         const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1582
1583                         for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1584                                 const BMVert *v_other = adj_v[i];
1585                                 if (vfcount != 2 || BM_vert_face_count_ex(v_other, 2) <= 2) {
1586                                         add_v3_v3(avg, v_other->co);
1587                                         total++;
1588                                 }
1589                         }
1590                 }
1591
1592                 if (total > 0) {
1593                         mul_v3_fl(avg, 1.0f / total);
1594                         return;
1595                 }
1596         }
1597
1598         copy_v3_v3(avg, v->co);
1599 }
1600
1601 /* Same logic as neighbor_average_mask(), but for bmesh rather than mesh */
1602 static float bmesh_neighbor_average_mask(BMVert *v, const int cd_vert_mask_offset)
1603 {
1604         BMIter liter;
1605         BMLoop *l;
1606         float avg = 0;
1607         int i, total = 0;
1608
1609         BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
1610                 /* skip this vertex */
1611                 const BMVert *adj_v[2] = {l->prev->v, l->next->v};
1612
1613                 for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
1614                         const BMVert *v_other = adj_v[i];
1615                         const float *vmask = BM_ELEM_CD_GET_VOID_P(v_other, cd_vert_mask_offset);
1616                         avg += (*vmask);
1617                         total++;
1618                 }
1619         }
1620
1621         if (total > 0) {
1622                 return avg / (float)total;
1623         }
1624         else {
1625                 const float *vmask = BM_ELEM_CD_GET_VOID_P(v, cd_vert_mask_offset);
1626                 return (*vmask);
1627         }
1628 }
1629
1630 /* Note: uses after-struct allocated mem to store actual cache... */
1631 typedef struct SculptDoBrushSmoothGridDataChunk {
1632         size_t tmpgrid_size;
1633 } SculptDoBrushSmoothGridDataChunk;
1634
1635 static void do_smooth_brush_mesh_task_cb_ex(
1636         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1637 {
1638         SculptThreadedTaskData *data = userdata;
1639         SculptSession *ss = data->ob->sculpt;
1640         Sculpt *sd = data->sd;
1641         Brush *brush = data->brush;
1642         const bool smooth_mask = data->smooth_mask;
1643         float bstrength = data->strength;
1644
1645         PBVHVertexIter vd;
1646         SculptBrushTest test;
1647
1648         CLAMP(bstrength, 0.0f, 1.0f);
1649
1650         sculpt_brush_test_init(ss, &test);
1651
1652         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1653         {
1654                 if (sculpt_brush_test(&test, vd.co)) {
1655                         const float fade = bstrength * tex_strength(
1656                                                ss, brush, vd.co, test.dist, vd.no, vd.fno,
1657                                                smooth_mask ? 0.0f : (vd.mask ? *vd.mask : 0.0f),
1658                                                thread_id);
1659                         if (smooth_mask) {
1660                                 float val = neighbor_average_mask(ss, vd.vert_indices[vd.i]) - *vd.mask;
1661                                 val *= fade * bstrength;
1662                                 *vd.mask += val;
1663                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1664                         }
1665                         else {
1666                                 float avg[3], val[3];
1667
1668                                 neighbor_average(ss, avg, vd.vert_indices[vd.i]);
1669                                 sub_v3_v3v3(val, avg, vd.co);
1670
1671                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1672
1673                                 sculpt_clip(sd, ss, vd.co, val);
1674                         }
1675
1676                         if (vd.mvert)
1677                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1678                 }
1679         }
1680         BKE_pbvh_vertex_iter_end;
1681 }
1682
1683 static void do_smooth_brush_bmesh_task_cb_ex(
1684         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1685 {
1686         SculptThreadedTaskData *data = userdata;
1687         SculptSession *ss = data->ob->sculpt;
1688         Sculpt *sd = data->sd;
1689         Brush *brush = data->brush;
1690         const bool smooth_mask = data->smooth_mask;
1691         float bstrength = data->strength;
1692
1693         PBVHVertexIter vd;
1694         SculptBrushTest test;
1695
1696         CLAMP(bstrength, 0.0f, 1.0f);
1697
1698         sculpt_brush_test_init(ss, &test);
1699
1700         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1701         {
1702                 if (sculpt_brush_test(&test, vd.co)) {
1703                         const float fade = bstrength * tex_strength(
1704                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, smooth_mask ? 0.0f : *vd.mask,
1705                                                thread_id);
1706                         if (smooth_mask) {
1707                                 float val = bmesh_neighbor_average_mask(vd.bm_vert, vd.cd_vert_mask_offset) - *vd.mask;
1708                                 val *= fade * bstrength;
1709                                 *vd.mask += val;
1710                                 CLAMP(*vd.mask, 0.0f, 1.0f);
1711                         }
1712                         else {
1713                                 float avg[3], val[3];
1714
1715                                 bmesh_neighbor_average(avg, vd.bm_vert);
1716                                 sub_v3_v3v3(val, avg, vd.co);
1717
1718                                 madd_v3_v3v3fl(val, vd.co, val, fade);
1719
1720                                 sculpt_clip(sd, ss, vd.co, val);
1721                         }
1722
1723                         if (vd.mvert)
1724                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1725                 }
1726         }
1727         BKE_pbvh_vertex_iter_end;
1728 }
1729
1730 static void do_smooth_brush_multires_task_cb_ex(
1731         void *userdata, void *userdata_chunk, const int n, const int thread_id)
1732 {
1733         SculptThreadedTaskData *data = userdata;
1734         SculptDoBrushSmoothGridDataChunk *data_chunk = userdata_chunk;
1735         SculptSession *ss = data->ob->sculpt;
1736         Sculpt *sd = data->sd;
1737         Brush *brush = data->brush;
1738         const bool smooth_mask = data->smooth_mask;
1739         float bstrength = data->strength;
1740
1741         SculptBrushTest test;
1742         CCGElem **griddata, *gddata;
1743         CCGKey key;
1744
1745         float (*tmpgrid_co)[3] = NULL;
1746         float tmprow_co[2][3];
1747         float *tmpgrid_mask = NULL;
1748         float tmprow_mask[2];
1749
1750         BLI_bitmap * const *grid_hidden;
1751         int *grid_indices, totgrid, gridsize;
1752         int i, x, y;
1753
1754         sculpt_brush_test_init(ss, &test);
1755
1756         CLAMP(bstrength, 0.0f, 1.0f);
1757
1758         BKE_pbvh_node_get_grids(ss->pbvh, data->nodes[n], &grid_indices, &totgrid, NULL, &gridsize, &griddata);
1759         BKE_pbvh_get_grid_key(ss->pbvh, &key);
1760
1761         grid_hidden = BKE_pbvh_grid_hidden(ss->pbvh);
1762
1763         if (smooth_mask)
1764                 tmpgrid_mask = (void *)(data_chunk + 1);
1765         else
1766                 tmpgrid_co = (void *)(data_chunk + 1);
1767
1768         for (i = 0; i < totgrid; i++) {
1769                 int gi = grid_indices[i];
1770                 const BLI_bitmap *gh = grid_hidden[gi];
1771                 gddata = griddata[gi];
1772
1773                 if (smooth_mask)
1774                         memset(tmpgrid_mask, 0, data_chunk->tmpgrid_size);
1775                 else
1776                         memset(tmpgrid_co, 0, data_chunk->tmpgrid_size);
1777
1778                 for (y = 0; y < gridsize - 1; y++) {
1779                         const int v = y * gridsize;
1780                         if (smooth_mask) {
1781                                 tmprow_mask[0] = (*CCG_elem_offset_mask(&key, gddata, v) +
1782                                                   *CCG_elem_offset_mask(&key, gddata, v + gridsize));
1783                         }
1784                         else {
1785                                 add_v3_v3v3(tmprow_co[0],
1786                                             CCG_elem_offset_co(&key, gddata, v),
1787                                             CCG_elem_offset_co(&key, gddata, v + gridsize));
1788                         }
1789
1790                         for (x = 0; x < gridsize - 1; x++) {
1791                                 const int v1 = x + y * gridsize;
1792                                 const int v2 = v1 + 1;
1793                                 const int v3 = v1 + gridsize;
1794                                 const int v4 = v3 + 1;
1795
1796                                 if (smooth_mask) {
1797                                         float tmp;
1798
1799                                         tmprow_mask[(x + 1) % 2] = (*CCG_elem_offset_mask(&key, gddata, v2) +
1800                                                                     *CCG_elem_offset_mask(&key, gddata, v4));
1801                                         tmp = tmprow_mask[(x + 1) % 2] + tmprow_mask[x % 2];
1802
1803                                         tmpgrid_mask[v1] += tmp;
1804                                         tmpgrid_mask[v2] += tmp;
1805                                         tmpgrid_mask[v3] += tmp;
1806                                         tmpgrid_mask[v4] += tmp;
1807                                 }
1808                                 else {
1809                                         float tmp[3];
1810
1811                                         add_v3_v3v3(tmprow_co[(x + 1) % 2],
1812                                                     CCG_elem_offset_co(&key, gddata, v2),
1813                                                     CCG_elem_offset_co(&key, gddata, v4));
1814                                         add_v3_v3v3(tmp, tmprow_co[(x + 1) % 2], tmprow_co[x % 2]);
1815
1816                                         add_v3_v3(tmpgrid_co[v1], tmp);
1817                                         add_v3_v3(tmpgrid_co[v2], tmp);
1818                                         add_v3_v3(tmpgrid_co[v3], tmp);
1819                                         add_v3_v3(tmpgrid_co[v4], tmp);
1820                                 }
1821                         }
1822                 }
1823
1824                 /* blend with existing coordinates */
1825                 for (y = 0; y < gridsize; y++) {
1826                         for (x = 0; x < gridsize; x++) {
1827                                 float *co;
1828                                 const float *fno;
1829                                 float *mask;
1830                                 const int index = y * gridsize + x;
1831
1832                                 if (gh) {
1833                                         if (BLI_BITMAP_TEST(gh, index))
1834                                                 continue;
1835                                 }
1836
1837                                 co = CCG_elem_offset_co(&key, gddata, index);
1838                                 fno = CCG_elem_offset_no(&key, gddata, index);
1839                                 mask = CCG_elem_offset_mask(&key, gddata, index);
1840
1841                                 if (sculpt_brush_test(&test, co)) {
1842                                         const float strength_mask = (smooth_mask ? 0.0f : *mask);
1843                                         const float fade = bstrength * tex_strength(
1844                                                                ss, brush, co, test.dist, NULL, fno, strength_mask, thread_id);
1845                                         float f = 1.0f / 16.0f;
1846
1847                                         if (x == 0 || x == gridsize - 1)
1848                                                 f *= 2.0f;
1849
1850                                         if (y == 0 || y == gridsize - 1)
1851                                                 f *= 2.0f;
1852
1853                                         if (smooth_mask) {
1854                                                 *mask += ((tmpgrid_mask[index] * f) - *mask) * fade;
1855                                         }
1856                                         else {
1857                                                 float *avg = tmpgrid_co[index];
1858                                                 float val[3];
1859
1860                                                 mul_v3_fl(avg, f);
1861                                                 sub_v3_v3v3(val, avg, co);
1862                                                 madd_v3_v3v3fl(val, co, val, fade);
1863
1864                                                 sculpt_clip(sd, ss, co, val);
1865                                         }
1866                                 }
1867                         }
1868                 }
1869         }
1870 }
1871
1872 static void smooth(
1873         Sculpt *sd, Object *ob, PBVHNode **nodes, const int totnode, float bstrength, const bool smooth_mask)
1874 {
1875         SculptSession *ss = ob->sculpt;
1876         Brush *brush = BKE_paint_brush(&sd->paint);
1877
1878         const int max_iterations = 4;
1879         const float fract = 1.0f / max_iterations;
1880         PBVHType type = BKE_pbvh_type(ss->pbvh);
1881         int iteration, count;
1882         float last;
1883
1884         CLAMP(bstrength, 0.0f, 1.0f);
1885
1886         count = (int)(bstrength * max_iterations);
1887         last  = max_iterations * (bstrength - count * fract);
1888
1889         if (type == PBVH_FACES && !ss->pmap) {
1890                 BLI_assert(!"sculpt smooth: pmap missing");
1891                 return;
1892         }
1893
1894         for (iteration = 0; iteration <= count; ++iteration) {
1895                 const float strength = (iteration != count) ? 1.0f : last;
1896
1897                 SculptThreadedTaskData data = {
1898                     .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
1899                     .smooth_mask = smooth_mask, .strength = strength,
1900                 };
1901
1902                 switch (type) {
1903                         case PBVH_GRIDS:
1904                         {
1905                                 int gridsize;
1906                                 size_t size;
1907                                 SculptDoBrushSmoothGridDataChunk *data_chunk;
1908
1909                                 BKE_pbvh_node_get_grids(ss->pbvh, NULL, NULL, NULL, NULL, &gridsize, NULL);
1910                                 size = (size_t)gridsize;
1911                                 size = sizeof(float) * size * size * (smooth_mask ? 1 : 3);
1912                                 data_chunk = MEM_mallocN(sizeof(*data_chunk) + size, __func__);
1913                                 data_chunk->tmpgrid_size = size;
1914                                 size += sizeof(*data_chunk);
1915
1916                                 BLI_task_parallel_range_ex(
1917                                             0, totnode, &data, data_chunk, size, do_smooth_brush_multires_task_cb_ex,
1918                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1919
1920                                 MEM_freeN(data_chunk);
1921                                 break;
1922                         }
1923                         case PBVH_FACES:
1924                                 BLI_task_parallel_range_ex(
1925                                             0, totnode, &data, NULL, 0, do_smooth_brush_mesh_task_cb_ex,
1926                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1927                                 break;
1928                         case PBVH_BMESH:
1929                                 BLI_task_parallel_range_ex(
1930                                             0, totnode, &data, NULL, 0, do_smooth_brush_bmesh_task_cb_ex,
1931                                             ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1932                                 break;
1933                 }
1934
1935                 if (ss->multires)
1936                         multires_stitch_grids(ob);
1937         }
1938 }
1939
1940 static void do_smooth_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1941 {
1942         SculptSession *ss = ob->sculpt;
1943         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, false);
1944 }
1945
1946 static void do_mask_brush_draw_task_cb_ex(
1947         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
1948 {
1949         SculptThreadedTaskData *data = userdata;
1950         SculptSession *ss = data->ob->sculpt;
1951         Brush *brush = data->brush;
1952         const float bstrength = ss->cache->bstrength;
1953
1954         PBVHVertexIter vd;
1955         SculptBrushTest test;
1956
1957         sculpt_brush_test_init(ss, &test);
1958
1959         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
1960         {
1961                 if (sculpt_brush_test(&test, vd.co)) {
1962                         const float fade = tex_strength(ss, brush, vd.co, test.dist, vd.no, vd.fno, 0.0f, thread_id);
1963
1964                         (*vd.mask) += fade * bstrength;
1965                         CLAMP(*vd.mask, 0, 1);
1966
1967                         if (vd.mvert)
1968                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
1969                 }
1970                 BKE_pbvh_vertex_iter_end;
1971         }
1972 }
1973
1974 static void do_mask_brush_draw(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1975 {
1976         Brush *brush = BKE_paint_brush(&sd->paint);
1977
1978         /* threaded loop over nodes */
1979         SculptThreadedTaskData data = {
1980             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
1981         };
1982
1983         BLI_task_parallel_range_ex(
1984                     0, totnode, &data, NULL, 0, do_mask_brush_draw_task_cb_ex,
1985                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
1986 }
1987
1988 static void do_mask_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
1989 {
1990         SculptSession *ss = ob->sculpt;
1991         Brush *brush = BKE_paint_brush(&sd->paint);
1992         
1993         switch ((BrushMaskTool)brush->mask_tool) {
1994                 case BRUSH_MASK_DRAW:
1995                         do_mask_brush_draw(sd, ob, nodes, totnode);
1996                         break;
1997                 case BRUSH_MASK_SMOOTH:
1998                         smooth(sd, ob, nodes, totnode, ss->cache->bstrength, true);
1999                         break;
2000         }
2001 }
2002
2003 static void do_draw_brush_task_cb_ex(
2004         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2005 {
2006         SculptThreadedTaskData *data = userdata;
2007         SculptSession *ss = data->ob->sculpt;
2008         Brush *brush = data->brush;
2009         const float *offset = data->offset;
2010
2011         PBVHVertexIter vd;
2012         SculptBrushTest test;
2013         float (*proxy)[3];
2014
2015         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2016
2017         sculpt_brush_test_init(ss, &test);
2018
2019         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2020         {
2021                 if (sculpt_brush_test(&test, vd.co)) {
2022                         /* offset vertex */
2023                         const float fade = tex_strength(
2024                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2025
2026                         mul_v3_v3fl(proxy[vd.i], offset, fade);
2027
2028                         if (vd.mvert)
2029                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2030                 }
2031         }
2032         BKE_pbvh_vertex_iter_end;
2033 }
2034
2035 static void do_draw_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2036 {
2037         SculptSession *ss = ob->sculpt;
2038         Brush *brush = BKE_paint_brush(&sd->paint);
2039         float offset[3];
2040         const float bstrength = ss->cache->bstrength;
2041
2042         /* offset with as much as possible factored in already */
2043         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2044         mul_v3_v3(offset, ss->cache->scale);
2045         mul_v3_fl(offset, bstrength);
2046
2047         /* threaded loop over nodes */
2048         SculptThreadedTaskData data = {
2049             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2050             .offset = offset,
2051         };
2052
2053         BLI_task_parallel_range_ex(
2054                     0, totnode, &data, NULL, 0, do_draw_brush_task_cb_ex,
2055                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2056 }
2057
2058 static void do_crease_brush_task_cb_ex(
2059         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2060 {
2061         SculptThreadedTaskData *data = userdata;
2062         SculptSession *ss = data->ob->sculpt;
2063         Brush *brush = data->brush;
2064         SculptProjectVector *spvc = data->spvc;
2065         const float flippedbstrength = data->flippedbstrength;
2066         const float *offset = data->offset;
2067
2068         PBVHVertexIter vd;
2069         SculptBrushTest test;
2070         float (*proxy)[3];
2071
2072         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2073
2074         sculpt_brush_test_init(ss, &test);
2075
2076         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2077         {
2078                 if (sculpt_brush_test(&test, vd.co)) {
2079                         /* offset vertex */
2080                         const float fade = tex_strength(
2081                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2082                         float val1[3];
2083                         float val2[3];
2084
2085                         /* first we pinch */
2086                         sub_v3_v3v3(val1, test.location, vd.co);
2087                         mul_v3_fl(val1, fade * flippedbstrength);
2088
2089                         sculpt_project_v3(spvc, val1, val1);
2090
2091                         /* then we draw */
2092                         mul_v3_v3fl(val2, offset, fade);
2093
2094                         add_v3_v3v3(proxy[vd.i], val1, val2);
2095
2096                         if (vd.mvert)
2097                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2098                 }
2099         }
2100         BKE_pbvh_vertex_iter_end;
2101 }
2102
2103 static void do_crease_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2104 {
2105         SculptSession *ss = ob->sculpt;
2106         const Scene *scene = ss->cache->vc->scene;
2107         Brush *brush = BKE_paint_brush(&sd->paint);
2108         float offset[3];
2109         float bstrength = ss->cache->bstrength;
2110         float flippedbstrength, crease_correction;
2111         float brush_alpha;
2112
2113         SculptProjectVector spvc;
2114
2115         /* offset with as much as possible factored in already */
2116         mul_v3_v3fl(offset, ss->cache->sculpt_normal_symm, ss->cache->radius);
2117         mul_v3_v3(offset, ss->cache->scale);
2118         mul_v3_fl(offset, bstrength);
2119         
2120         /* we divide out the squared alpha and multiply by the squared crease to give us the pinch strength */
2121         crease_correction = brush->crease_pinch_factor * brush->crease_pinch_factor;
2122         brush_alpha = BKE_brush_alpha_get(scene, brush);
2123         if (brush_alpha > 0.0f)
2124                 crease_correction /= brush_alpha * brush_alpha;
2125
2126         /* we always want crease to pinch or blob to relax even when draw is negative */
2127         flippedbstrength = (bstrength < 0) ? -crease_correction * bstrength : crease_correction * bstrength;
2128
2129         if (brush->sculpt_tool == SCULPT_TOOL_BLOB) flippedbstrength *= -1.0f;
2130
2131         /* Use surface normal for 'spvc', so the vertices are pinched towards a line instead of a single point.
2132          * Without this we get a 'flat' surface surrounding the pinch */
2133         sculpt_project_v3_cache_init(&spvc, ss->cache->sculpt_normal_symm);
2134
2135         /* threaded loop over nodes */
2136         SculptThreadedTaskData data = {
2137             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2138             .spvc = &spvc, .offset = offset, .flippedbstrength = flippedbstrength,
2139         };
2140
2141         BLI_task_parallel_range_ex(
2142                     0, totnode, &data, NULL, 0, do_crease_brush_task_cb_ex,
2143                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2144 }
2145
2146 static void do_pinch_brush_task_cb_ex(
2147         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2148 {
2149         SculptThreadedTaskData *data = userdata;
2150         SculptSession *ss = data->ob->sculpt;
2151         Brush *brush = data->brush;
2152
2153         PBVHVertexIter vd;
2154         SculptBrushTest test;
2155         float (*proxy)[3];
2156         const float bstrength = ss->cache->bstrength;
2157
2158         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2159
2160         sculpt_brush_test_init(ss, &test);
2161
2162         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2163         {
2164                 if (sculpt_brush_test(&test, vd.co)) {
2165                         const float fade = bstrength * tex_strength(
2166                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2167                         float val[3];
2168
2169                         sub_v3_v3v3(val, test.location, vd.co);
2170                         mul_v3_v3fl(proxy[vd.i], val, fade);
2171
2172                         if (vd.mvert)
2173                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2174                 }
2175         }
2176         BKE_pbvh_vertex_iter_end;
2177 }
2178
2179 static void do_pinch_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2180 {
2181         Brush *brush = BKE_paint_brush(&sd->paint);
2182
2183         SculptThreadedTaskData data = {
2184             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2185         };
2186
2187         BLI_task_parallel_range_ex(
2188                     0, totnode, &data, NULL, 0, do_pinch_brush_task_cb_ex,
2189                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2190 }
2191
2192 static void do_grab_brush_task_cb_ex(
2193         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2194 {
2195         SculptThreadedTaskData *data = userdata;
2196         SculptSession *ss = data->ob->sculpt;
2197         Brush *brush = data->brush;
2198         const float *grab_delta = data->grab_delta;
2199
2200         PBVHVertexIter vd;
2201         SculptBrushTest test;
2202         SculptOrigVertData orig_data;
2203         float (*proxy)[3];
2204         const float bstrength = ss->cache->bstrength;
2205
2206         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2207
2208         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2209
2210         sculpt_brush_test_init(ss, &test);
2211
2212         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2213         {
2214                 sculpt_orig_vert_data_update(&orig_data, &vd);
2215
2216                 if (sculpt_brush_test(&test, orig_data.co)) {
2217                         const float fade = bstrength * tex_strength(
2218                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2219                                                thread_id);
2220
2221                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2222
2223                         if (vd.mvert)
2224                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2225                 }
2226         }
2227         BKE_pbvh_vertex_iter_end;
2228 }
2229
2230 static void do_grab_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2231 {
2232         SculptSession *ss = ob->sculpt;
2233         Brush *brush = BKE_paint_brush(&sd->paint);
2234         float grab_delta[3];
2235
2236         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2237
2238         if (ss->cache->normal_weight > 0.0f) {
2239                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2240         }
2241
2242         SculptThreadedTaskData data = {
2243             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2244             .grab_delta = grab_delta,
2245         };
2246
2247         BLI_task_parallel_range_ex(
2248                     0, totnode, &data, NULL, 0, do_grab_brush_task_cb_ex,
2249                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2250 }
2251
2252 static void do_nudge_brush_task_cb_ex(
2253         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2254 {
2255         SculptThreadedTaskData *data = userdata;
2256         SculptSession *ss = data->ob->sculpt;
2257         Brush *brush = data->brush;
2258         const float *cono = data->cono;
2259
2260         PBVHVertexIter vd;
2261         SculptBrushTest test;
2262         float (*proxy)[3];
2263         const float bstrength = ss->cache->bstrength;
2264
2265         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2266
2267         sculpt_brush_test_init(ss, &test);
2268
2269         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2270         {
2271                 if (sculpt_brush_test(&test, vd.co)) {
2272                         const float fade = bstrength * tex_strength(
2273                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2274
2275                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2276
2277                         if (vd.mvert)
2278                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2279                 }
2280         }
2281         BKE_pbvh_vertex_iter_end;
2282 }
2283
2284 static void do_nudge_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2285 {
2286         SculptSession *ss = ob->sculpt;
2287         Brush *brush = BKE_paint_brush(&sd->paint);
2288         float grab_delta[3];
2289         float tmp[3], cono[3];
2290
2291         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2292
2293         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2294         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2295
2296         SculptThreadedTaskData data = {
2297             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2298             .cono = cono,
2299         };
2300
2301         BLI_task_parallel_range_ex(
2302                     0, totnode, &data, NULL, 0, do_nudge_brush_task_cb_ex,
2303                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2304 }
2305
2306 static void do_snake_hook_brush_task_cb_ex(
2307         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2308 {
2309         SculptThreadedTaskData *data = userdata;
2310         SculptSession *ss = data->ob->sculpt;
2311         Brush *brush = data->brush;
2312         SculptProjectVector *spvc = data->spvc;
2313         const float *grab_delta = data->grab_delta;
2314
2315         PBVHVertexIter vd;
2316         SculptBrushTest test;
2317         float (*proxy)[3];
2318         const float bstrength = ss->cache->bstrength;
2319         const bool do_rake_rotation = ss->cache->is_rake_rotation_valid;
2320         const bool do_pinch = (brush->crease_pinch_factor != 0.5f);
2321         const float pinch = do_pinch ?
2322                 (2.0f * (0.5f - brush->crease_pinch_factor) * (len_v3(grab_delta) / ss->cache->radius)) : 0.0f;
2323
2324         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2325
2326         sculpt_brush_test_init(ss, &test);
2327
2328         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2329         {
2330                 if (sculpt_brush_test(&test, vd.co)) {
2331                         const float fade = bstrength * tex_strength(
2332                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2333
2334                         mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
2335
2336                         /* negative pinch will inflate, helps maintain volume */
2337                         if (do_pinch) {
2338                                 float delta_pinch_init[3], delta_pinch[3];
2339
2340                                 sub_v3_v3v3(delta_pinch, vd.co, test.location);
2341
2342                                 /* important to calculate based on the grabbed location (intentionally ignore fade here). */
2343                                 add_v3_v3(delta_pinch, grab_delta);
2344
2345                                 sculpt_project_v3(spvc, delta_pinch, delta_pinch);
2346
2347                                 copy_v3_v3(delta_pinch_init, delta_pinch);
2348
2349                                 float pinch_fade = pinch * fade;
2350                                 /* when reducing, scale reduction back by how close to the center we are,
2351                                  * so we don't pinch into nothingness */
2352                                 if (pinch > 0.0f) {
2353                                         /* square to have even less impact for close vertices */
2354                                         pinch_fade *= pow2f(min_ff(1.0f, len_v3(delta_pinch) / ss->cache->radius));
2355                                 }
2356                                 mul_v3_fl(delta_pinch, 1.0f + pinch_fade);
2357                                 sub_v3_v3v3(delta_pinch, delta_pinch_init, delta_pinch);
2358                                 add_v3_v3(proxy[vd.i], delta_pinch);
2359                         }
2360
2361                         if (do_rake_rotation) {
2362                                 float delta_rotate[3];
2363                                 sculpt_rake_rotate(ss, test.location, vd.co, fade, delta_rotate);
2364                                 add_v3_v3(proxy[vd.i], delta_rotate);
2365                         }
2366
2367                         if (vd.mvert)
2368                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2369                 }
2370         }
2371         BKE_pbvh_vertex_iter_end;
2372 }
2373
2374 static void do_snake_hook_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2375 {
2376         SculptSession *ss = ob->sculpt;
2377         Brush *brush = BKE_paint_brush(&sd->paint);
2378         const float bstrength = ss->cache->bstrength;
2379         float grab_delta[3];
2380
2381         SculptProjectVector spvc;
2382
2383         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2384
2385         if (bstrength < 0)
2386                 negate_v3(grab_delta);
2387
2388         if (ss->cache->normal_weight > 0.0f) {
2389                 sculpt_project_v3_normal_align(ss, ss->cache->normal_weight, grab_delta);
2390         }
2391
2392         /* optionally pinch while painting */
2393         if (brush->crease_pinch_factor != 0.5f) {
2394                 sculpt_project_v3_cache_init(&spvc, grab_delta);
2395         }
2396
2397         SculptThreadedTaskData data = {
2398             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2399             .spvc = &spvc, .grab_delta = grab_delta,
2400         };
2401
2402         BLI_task_parallel_range_ex(
2403                     0, totnode, &data, NULL, 0, do_snake_hook_brush_task_cb_ex,
2404                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2405 }
2406
2407 static void do_thumb_brush_task_cb_ex(
2408         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2409 {
2410         SculptThreadedTaskData *data = userdata;
2411         SculptSession *ss = data->ob->sculpt;
2412         Brush *brush = data->brush;
2413         const float *cono = data->cono;
2414
2415         PBVHVertexIter vd;
2416         SculptBrushTest test;
2417         SculptOrigVertData orig_data;
2418         float (*proxy)[3];
2419         const float bstrength = ss->cache->bstrength;
2420
2421         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2422
2423         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2424
2425         sculpt_brush_test_init(ss, &test);
2426
2427         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2428         {
2429                 sculpt_orig_vert_data_update(&orig_data, &vd);
2430
2431                 if (sculpt_brush_test(&test, orig_data.co)) {
2432                         const float fade = bstrength * tex_strength(
2433                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2434                                                thread_id);
2435
2436                         mul_v3_v3fl(proxy[vd.i], cono, fade);
2437
2438                         if (vd.mvert)
2439                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2440                 }
2441         }
2442         BKE_pbvh_vertex_iter_end;
2443 }
2444
2445 static void do_thumb_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2446 {
2447         SculptSession *ss = ob->sculpt;
2448         Brush *brush = BKE_paint_brush(&sd->paint);
2449         float grab_delta[3];
2450         float tmp[3], cono[3];
2451
2452         copy_v3_v3(grab_delta, ss->cache->grab_delta_symmetry);
2453
2454         cross_v3_v3v3(tmp, ss->cache->sculpt_normal_symm, grab_delta);
2455         cross_v3_v3v3(cono, tmp, ss->cache->sculpt_normal_symm);
2456
2457         SculptThreadedTaskData data = {
2458             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2459             .cono = cono,
2460         };
2461
2462         BLI_task_parallel_range_ex(
2463                     0, totnode, &data, NULL, 0, do_thumb_brush_task_cb_ex,
2464                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2465 }
2466
2467 static void do_rotate_brush_task_cb_ex(
2468         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2469 {
2470         SculptThreadedTaskData *data = userdata;
2471         SculptSession *ss = data->ob->sculpt;
2472         Brush *brush = data->brush;
2473         const float angle = data->angle;
2474
2475         PBVHVertexIter vd;
2476         SculptBrushTest test;
2477         SculptOrigVertData orig_data;
2478         float (*proxy)[3];
2479         const float bstrength = ss->cache->bstrength;
2480
2481         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2482
2483         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2484
2485         sculpt_brush_test_init(ss, &test);
2486
2487         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2488         {
2489                 sculpt_orig_vert_data_update(&orig_data, &vd);
2490
2491                 if (sculpt_brush_test(&test, orig_data.co)) {
2492                         float vec[3], rot[3][3];
2493                         const float fade = bstrength * tex_strength(
2494                                                ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
2495                                                thread_id);
2496
2497                         sub_v3_v3v3(vec, orig_data.co, ss->cache->location);
2498                         axis_angle_normalized_to_mat3(rot, ss->cache->sculpt_normal_symm, angle * fade);
2499                         mul_v3_m3v3(proxy[vd.i], rot, vec);
2500                         add_v3_v3(proxy[vd.i], ss->cache->location);
2501                         sub_v3_v3(proxy[vd.i], orig_data.co);
2502
2503                         if (vd.mvert)
2504                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2505                 }
2506         }
2507         BKE_pbvh_vertex_iter_end;
2508 }
2509
2510 static void do_rotate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2511 {
2512         SculptSession *ss = ob->sculpt;
2513         Brush *brush = BKE_paint_brush(&sd->paint);
2514
2515         static const int flip[8] = { 1, -1, -1, 1, -1, 1, 1, -1 };
2516         const float angle = ss->cache->vertex_rotation * flip[ss->cache->mirror_symmetry_pass];
2517
2518         SculptThreadedTaskData data = {
2519             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2520             .angle = angle,
2521         };
2522
2523         BLI_task_parallel_range_ex(
2524                     0, totnode, &data, NULL, 0, do_rotate_brush_task_cb_ex,
2525                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2526 }
2527
2528 static void do_layer_brush_task_cb_ex(
2529         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2530 {
2531         SculptThreadedTaskData *data = userdata;
2532         SculptSession *ss = data->ob->sculpt;
2533         Sculpt *sd = data->sd;
2534         Brush *brush = data->brush;
2535         const float *offset = data->offset;
2536
2537         PBVHVertexIter vd;
2538         SculptBrushTest test;
2539         SculptOrigVertData orig_data;
2540         float *layer_disp;
2541         const float bstrength = ss->cache->bstrength;
2542         const float lim = (bstrength < 0) ? -data->brush->height : data->brush->height;
2543         /* XXX: layer brush needs conversion to proxy but its more complicated */
2544         /* proxy = BKE_pbvh_node_add_proxy(ss->pbvh, nodes[n])->co; */
2545
2546         sculpt_orig_vert_data_init(&orig_data, data->ob, data->nodes[n]);
2547
2548         /* Why does this have to be thread-protected? */
2549         BLI_mutex_lock(&data->mutex);
2550         layer_disp = BKE_pbvh_node_layer_disp_get(ss->pbvh, data->nodes[n]);
2551         BLI_mutex_unlock(&data->mutex);
2552
2553         sculpt_brush_test_init(ss, &test);
2554
2555         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2556         {
2557                 sculpt_orig_vert_data_update(&orig_data, &vd);
2558
2559                 if (sculpt_brush_test(&test, orig_data.co)) {
2560                         const float fade = bstrength * tex_strength(
2561                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2562                         float *disp = &layer_disp[vd.i];
2563                         float val[3];
2564
2565                         *disp += fade;
2566
2567                         /* Don't let the displacement go past the limit */
2568                         if ((lim < 0.0f && *disp < lim) || (lim >= 0.0f && *disp > lim))
2569                                 *disp = lim;
2570
2571                         mul_v3_v3fl(val, offset, *disp);
2572
2573                         if (!ss->multires && !ss->bm && ss->layer_co && (brush->flag & BRUSH_PERSISTENT)) {
2574                                 int index = vd.vert_indices[vd.i];
2575
2576                                 /* persistent base */
2577                                 add_v3_v3(val, ss->layer_co[index]);
2578                         }
2579                         else {
2580                                 add_v3_v3(val, orig_data.co);
2581                         }
2582
2583                         sculpt_clip(sd, ss, vd.co, val);
2584
2585                         if (vd.mvert)
2586                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2587                 }
2588         }
2589         BKE_pbvh_vertex_iter_end;
2590 }
2591
2592 static void do_layer_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2593 {
2594         SculptSession *ss = ob->sculpt;
2595         Brush *brush = BKE_paint_brush(&sd->paint);
2596         float offset[3];
2597
2598         mul_v3_v3v3(offset, ss->cache->scale, ss->cache->sculpt_normal_symm);
2599
2600         SculptThreadedTaskData data = {
2601             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2602             .offset = offset,
2603         };
2604         BLI_mutex_init(&data.mutex);
2605
2606         BLI_task_parallel_range_ex(
2607                     0, totnode, &data, NULL, 0, do_layer_brush_task_cb_ex,
2608                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2609
2610         BLI_mutex_end(&data.mutex);
2611 }
2612
2613 static void do_inflate_brush_task_cb_ex(
2614         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2615 {
2616         SculptThreadedTaskData *data = userdata;
2617         SculptSession *ss = data->ob->sculpt;
2618         Brush *brush = data->brush;
2619
2620         PBVHVertexIter vd;
2621         SculptBrushTest test;
2622         float (*proxy)[3];
2623         const float bstrength = ss->cache->bstrength;
2624
2625         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2626
2627         sculpt_brush_test_init(ss, &test);
2628
2629         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2630         {
2631                 if (sculpt_brush_test(&test, vd.co)) {
2632                         const float fade = bstrength * tex_strength(
2633                                                ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2634                         float val[3];
2635
2636                         if (vd.fno)
2637                                 copy_v3_v3(val, vd.fno);
2638                         else
2639                                 normal_short_to_float_v3(val, vd.no);
2640
2641                         mul_v3_fl(val, fade * ss->cache->radius);
2642                         mul_v3_v3v3(proxy[vd.i], val, ss->cache->scale);
2643
2644                         if (vd.mvert)
2645                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2646                 }
2647         }
2648         BKE_pbvh_vertex_iter_end;
2649 }
2650
2651 static void do_inflate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2652 {
2653         Brush *brush = BKE_paint_brush(&sd->paint);
2654
2655         SculptThreadedTaskData data = {
2656             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2657         };
2658
2659         BLI_task_parallel_range_ex(
2660                     0, totnode, &data, NULL, 0, do_inflate_brush_task_cb_ex,
2661                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2662 }
2663
2664 static void calc_sculpt_plane(
2665         Sculpt *sd, Object *ob,
2666         PBVHNode **nodes, int totnode,
2667         float r_area_no[3], float r_area_co[3])
2668 {
2669         SculptSession *ss = ob->sculpt;
2670         Brush *brush = BKE_paint_brush(&sd->paint);
2671
2672         if (ss->cache->mirror_symmetry_pass == 0 &&
2673             ss->cache->radial_symmetry_pass == 0 &&
2674             ss->cache->tile_pass == 0 &&
2675             (ss->cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
2676         {
2677                 switch (brush->sculpt_plane) {
2678                         case SCULPT_DISP_DIR_VIEW:
2679                                 copy_v3_v3(r_area_no, ss->cache->true_view_normal);
2680                                 break;
2681
2682                         case SCULPT_DISP_DIR_X:
2683                                 ARRAY_SET_ITEMS(r_area_no, 1, 0, 0);
2684                                 break;
2685
2686                         case SCULPT_DISP_DIR_Y:
2687                                 ARRAY_SET_ITEMS(r_area_no, 0, 1, 0);
2688                                 break;
2689
2690                         case SCULPT_DISP_DIR_Z:
2691                                 ARRAY_SET_ITEMS(r_area_no, 0, 0, 1);
2692                                 break;
2693
2694                         case SCULPT_DISP_DIR_AREA:
2695                                 calc_area_normal_and_center(sd, ob, nodes, totnode, r_area_no, r_area_co);
2696                                 break;
2697
2698                         default:
2699                                 break;
2700                 }
2701
2702                 /* for flatten center */
2703                 /* flatten center has not been calculated yet if we are not using the area normal */
2704                 if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA)
2705                         calc_area_center(sd, ob, nodes, totnode, r_area_co);
2706
2707                 /* for area normal */
2708                 copy_v3_v3(ss->cache->sculpt_normal, r_area_no);
2709
2710                 /* for flatten center */
2711                 copy_v3_v3(ss->cache->last_center, r_area_co);
2712         }
2713         else {
2714                 /* for area normal */
2715                 copy_v3_v3(r_area_no, ss->cache->sculpt_normal);
2716
2717                 /* for flatten center */
2718                 copy_v3_v3(r_area_co, ss->cache->last_center);
2719
2720                 /* for area normal */
2721                 flip_v3(r_area_no, ss->cache->mirror_symmetry_pass);
2722
2723                 /* for flatten center */
2724                 flip_v3(r_area_co, ss->cache->mirror_symmetry_pass);
2725
2726                 /* for area normal */
2727                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_no);
2728
2729                 /* for flatten center */
2730                 mul_m4_v3(ss->cache->symm_rot_mat, r_area_co);
2731
2732                 /* shift the plane for the current tile */
2733                 add_v3_v3(r_area_co, ss->cache->plane_offset);
2734         }
2735 }
2736
2737 /* Projects a point onto a plane along the plane's normal */
2738 static void point_plane_project(
2739         float intr[3],
2740         const float co[3], const float plane_normal[3], const float plane_center[3])
2741 {
2742         sub_v3_v3v3(intr, co, plane_center);
2743         mul_v3_v3fl(intr, plane_normal, dot_v3v3(plane_normal, intr));
2744         sub_v3_v3v3(intr, co, intr);
2745 }
2746
2747 static int plane_trim(const StrokeCache *cache, const Brush *brush, const float val[3])
2748 {
2749         return (!(brush->flag & BRUSH_PLANE_TRIM) ||
2750                 ((dot_v3v3(val, val) <= cache->radius_squared * cache->plane_trim_squared)));
2751 }
2752
2753 static bool plane_point_side_flip(
2754         const float co[3], const float plane_normal[3], const float plane_center[3],
2755         const bool flip)
2756 {
2757         float delta[3];
2758         float d;
2759
2760         sub_v3_v3v3(delta, co, plane_center);
2761         d = dot_v3v3(plane_normal, delta);
2762
2763         if (flip) d = -d;
2764
2765         return d <= 0.0f;
2766 }
2767
2768 static int plane_point_side(const float co[3], const float plane_normal[3], const float plane_center[3])
2769 {
2770         float delta[3];
2771
2772         sub_v3_v3v3(delta, co, plane_center);
2773         return dot_v3v3(plane_normal, delta) <= 0.0f;
2774 }
2775
2776 static float get_offset(Sculpt *sd, SculptSession *ss)
2777 {
2778         Brush *brush = BKE_paint_brush(&sd->paint);
2779
2780         float rv = brush->plane_offset;
2781
2782         if (brush->flag & BRUSH_OFFSET_PRESSURE) {
2783                 rv *= ss->cache->pressure;
2784         }
2785
2786         return rv;
2787 }
2788
2789 static void do_flatten_brush_task_cb_ex(
2790         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2791 {
2792         SculptThreadedTaskData *data = userdata;
2793         SculptSession *ss = data->ob->sculpt;
2794         Brush *brush = data->brush;
2795         const float *area_no = data->area_no;
2796         const float *area_co = data->area_co;
2797
2798         PBVHVertexIter vd;
2799         SculptBrushTest test;
2800         float (*proxy)[3];
2801         const float bstrength = ss->cache->bstrength;
2802
2803         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2804
2805         sculpt_brush_test_init(ss, &test);
2806
2807         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2808         {
2809                 if (sculpt_brush_test_sq(&test, vd.co)) {
2810                         float intr[3];
2811                         float val[3];
2812
2813                         point_plane_project(intr, vd.co, area_no, area_co);
2814
2815                         sub_v3_v3v3(val, intr, vd.co);
2816
2817                         if (plane_trim(ss->cache, brush, val)) {
2818                                 const float fade = bstrength * tex_strength(
2819                                                        ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
2820                                                        thread_id);
2821
2822                                 mul_v3_v3fl(proxy[vd.i], val, fade);
2823
2824                                 if (vd.mvert)
2825                                         vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2826                         }
2827                 }
2828         }
2829         BKE_pbvh_vertex_iter_end;
2830 }
2831
2832 static void do_flatten_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2833 {
2834         SculptSession *ss = ob->sculpt;
2835         Brush *brush = BKE_paint_brush(&sd->paint);
2836
2837         const float radius = ss->cache->radius;
2838
2839         float area_no[3];
2840         float area_co[3];
2841
2842         float offset = get_offset(sd, ss);
2843         float displace;
2844         float temp[3];
2845
2846         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
2847
2848         displace = radius * offset;
2849
2850         mul_v3_v3v3(temp, area_no, ss->cache->scale);
2851         mul_v3_fl(temp, displace);
2852         add_v3_v3(area_co, temp);
2853
2854         SculptThreadedTaskData data = {
2855             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2856             .area_no = area_no, .area_co = area_co,
2857         };
2858
2859         BLI_task_parallel_range_ex(
2860                     0, totnode, &data, NULL, 0, do_flatten_brush_task_cb_ex,
2861                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2862 }
2863
2864 static void do_clay_brush_task_cb_ex(
2865         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2866 {
2867         SculptThreadedTaskData *data = userdata;
2868         SculptSession *ss = data->ob->sculpt;
2869         Brush *brush = data->brush;
2870         const float *area_no = data->area_no;
2871         const float *area_co = data->area_co;
2872
2873         PBVHVertexIter vd;
2874         SculptBrushTest test;
2875         float (*proxy)[3];
2876         const bool flip = (ss->cache->bstrength < 0);
2877         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
2878
2879         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2880
2881         sculpt_brush_test_init(ss, &test);
2882
2883         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2884         {
2885                 if (sculpt_brush_test_sq(&test, vd.co)) {
2886                         if (plane_point_side_flip(vd.co, area_no, area_co, flip)) {
2887                                 float intr[3];
2888                                 float val[3];
2889
2890                                 point_plane_project(intr, vd.co, area_no, area_co);
2891
2892                                 sub_v3_v3v3(val, intr, vd.co);
2893
2894                                 if (plane_trim(ss->cache, brush, val)) {
2895                                         /* note, the normal from the vertices is ignored,
2896                                          * causes glitch with planes, see: T44390 */
2897                                         const float fade = bstrength * tex_strength(
2898                                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
2899                                                                thread_id);
2900
2901                                         mul_v3_v3fl(proxy[vd.i], val, fade);
2902
2903                                         if (vd.mvert)
2904                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2905                                 }
2906                         }
2907                 }
2908         }
2909         BKE_pbvh_vertex_iter_end;
2910 }
2911
2912 static void do_clay_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2913 {
2914         SculptSession *ss = ob->sculpt;
2915         Brush *brush = BKE_paint_brush(&sd->paint);
2916
2917         const bool flip = (ss->cache->bstrength < 0);
2918         const float radius = flip ? -ss->cache->radius : ss->cache->radius;
2919
2920         float offset = get_offset(sd, ss);
2921         float displace;
2922
2923         float area_no[3];
2924         float area_co[3];
2925         float temp[3];
2926
2927         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
2928
2929         displace = radius * (0.25f + offset);
2930
2931         mul_v3_v3v3(temp, area_no, ss->cache->scale);
2932         mul_v3_fl(temp, displace);
2933         add_v3_v3(area_co, temp);
2934
2935         /* add_v3_v3v3(p, ss->cache->location, area_no); */
2936
2937         SculptThreadedTaskData data = {
2938             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
2939             .area_no = area_no, .area_co = area_co,
2940         };
2941
2942         BLI_task_parallel_range_ex(
2943                     0, totnode, &data, NULL, 0, do_clay_brush_task_cb_ex,
2944                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
2945 }
2946
2947 static void do_clay_strips_brush_task_cb_ex(
2948         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
2949 {
2950         SculptThreadedTaskData *data = userdata;
2951         SculptSession *ss = data->ob->sculpt;
2952         Brush *brush = data->brush;
2953         float (*mat)[4] = data->mat;
2954         const float *area_no_sp = data->area_no_sp;
2955         const float *area_co = data->area_co;
2956
2957         PBVHVertexIter vd;
2958         SculptBrushTest test;
2959         float (*proxy)[3];
2960         const bool flip = (ss->cache->bstrength < 0);
2961         const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
2962
2963         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
2964
2965         sculpt_brush_test_init(ss, &test);
2966
2967         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
2968         {
2969                 if (sculpt_brush_test_cube(&test, vd.co, mat)) {
2970                         if (plane_point_side_flip(vd.co, area_no_sp, area_co, flip)) {
2971                                 float intr[3];
2972                                 float val[3];
2973
2974                                 point_plane_project(intr, vd.co, area_no_sp, area_co);
2975
2976                                 sub_v3_v3v3(val, intr, vd.co);
2977
2978                                 if (plane_trim(ss->cache, brush, val)) {
2979                                         /* note, the normal from the vertices is ignored,
2980                                          * causes glitch with planes, see: T44390 */
2981                                         const float fade = bstrength * tex_strength(
2982                                                                ss, brush, vd.co, ss->cache->radius * test.dist,
2983                                                                vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
2984
2985                                         mul_v3_v3fl(proxy[vd.i], val, fade);
2986
2987                                         if (vd.mvert)
2988                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
2989                                 }
2990                         }
2991                 }
2992         }
2993         BKE_pbvh_vertex_iter_end;
2994 }
2995
2996 static void do_clay_strips_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
2997 {
2998         SculptSession *ss = ob->sculpt;
2999         Brush *brush = BKE_paint_brush(&sd->paint);
3000
3001         const bool flip = (ss->cache->bstrength < 0);
3002         const float radius    = flip ? -ss->cache->radius : ss->cache->radius;
3003         const float offset    = get_offset(sd, ss);
3004         const float displace  = radius * (0.25f + offset);
3005
3006         float area_no_sp[3];  /* the sculpt-plane normal (whatever its set to) */
3007         float area_no[3];     /* geometry normal */
3008         float area_co[3];
3009
3010         float temp[3];
3011         float mat[4][4];
3012         float scale[4][4];
3013         float tmat[4][4];
3014
3015         calc_sculpt_plane(sd, ob, nodes, totnode, area_no_sp, area_co);
3016
3017         if (brush->sculpt_plane != SCULPT_DISP_DIR_AREA || (brush->flag & BRUSH_ORIGINAL_NORMAL))
3018                 calc_area_normal(sd, ob, nodes, totnode, area_no);
3019         else
3020                 copy_v3_v3(area_no, area_no_sp);
3021
3022         /* delay the first daub because grab delta is not setup */
3023         if (ss->cache->first_time)
3024                 return;
3025
3026         mul_v3_v3v3(temp, area_no_sp, ss->cache->scale);
3027         mul_v3_fl(temp, displace);
3028         add_v3_v3(area_co, temp);
3029
3030         /* init mat */
3031         cross_v3_v3v3(mat[0], area_no, ss->cache->grab_delta_symmetry);
3032         mat[0][3] = 0;
3033         cross_v3_v3v3(mat[1], area_no, mat[0]);
3034         mat[1][3] = 0;
3035         copy_v3_v3(mat[2], area_no);
3036         mat[2][3] = 0;
3037         copy_v3_v3(mat[3], ss->cache->location);
3038         mat[3][3] = 1;
3039         normalize_m4(mat);
3040
3041         /* scale mat */
3042         scale_m4_fl(scale, ss->cache->radius);
3043         mul_m4_m4m4(tmat, mat, scale);
3044         invert_m4_m4(mat, tmat);
3045
3046         SculptThreadedTaskData data = {
3047             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3048             .area_no_sp = area_no_sp, .area_co = area_co, .mat = mat,
3049         };
3050
3051         BLI_task_parallel_range_ex(
3052                     0, totnode, &data, NULL, 0, do_clay_strips_brush_task_cb_ex,
3053                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3054 }
3055
3056 static void do_fill_brush_task_cb_ex(
3057         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3058 {
3059         SculptThreadedTaskData *data = userdata;
3060         SculptSession *ss = data->ob->sculpt;
3061         Brush *brush = data->brush;
3062         const float *area_no = data->area_no;
3063         const float *area_co = data->area_co;
3064
3065         PBVHVertexIter vd;
3066         SculptBrushTest test;
3067         float (*proxy)[3];
3068         const float bstrength = ss->cache->bstrength;
3069
3070         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3071
3072         sculpt_brush_test_init(ss, &test);
3073
3074         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3075         {
3076                 if (sculpt_brush_test_sq(&test, vd.co)) {
3077                         if (plane_point_side(vd.co, area_no, area_co)) {
3078                                 float intr[3];
3079                                 float val[3];
3080
3081                                 point_plane_project(intr, vd.co, area_no, area_co);
3082
3083                                 sub_v3_v3v3(val, intr, vd.co);
3084
3085                                 if (plane_trim(ss->cache, brush, val)) {
3086                                         const float fade = bstrength * tex_strength(
3087                                                                ss, brush, vd.co, sqrtf(test.dist),
3088                                                                vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
3089
3090                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3091
3092                                         if (vd.mvert)
3093                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3094                                 }
3095                         }
3096                 }
3097         }
3098         BKE_pbvh_vertex_iter_end;
3099 }
3100
3101 static void do_fill_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3102 {
3103         SculptSession *ss = ob->sculpt;
3104         Brush *brush = BKE_paint_brush(&sd->paint);
3105
3106         const float radius = ss->cache->radius;
3107
3108         float area_no[3];
3109         float area_co[3];
3110         float offset = get_offset(sd, ss);
3111
3112         float displace;
3113
3114         float temp[3];
3115
3116         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
3117
3118         displace = radius * offset;
3119
3120         mul_v3_v3v3(temp, area_no, ss->cache->scale);
3121         mul_v3_fl(temp, displace);
3122         add_v3_v3(area_co, temp);
3123
3124         SculptThreadedTaskData data = {
3125             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3126             .area_no = area_no, .area_co = area_co,
3127         };
3128
3129         BLI_task_parallel_range_ex(
3130                     0, totnode, &data, NULL, 0, do_fill_brush_task_cb_ex,
3131                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3132 }
3133
3134 static void do_scrape_brush_task_cb_ex(
3135         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3136 {
3137         SculptThreadedTaskData *data = userdata;
3138         SculptSession *ss = data->ob->sculpt;
3139         Brush *brush = data->brush;
3140         const float *area_no = data->area_no;
3141         const float *area_co = data->area_co;
3142
3143         PBVHVertexIter vd;
3144         SculptBrushTest test;
3145         float (*proxy)[3];
3146         const float bstrength = ss->cache->bstrength;
3147
3148         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3149
3150         sculpt_brush_test_init(ss, &test);
3151
3152         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
3153         {
3154                 if (sculpt_brush_test_sq(&test, vd.co)) {
3155                         if (!plane_point_side(vd.co, area_no, area_co)) {
3156                                 float intr[3];
3157                                 float val[3];
3158
3159                                 point_plane_project(intr, vd.co, area_no, area_co);
3160
3161                                 sub_v3_v3v3(val, intr, vd.co);
3162
3163                                 if (plane_trim(ss->cache, brush, val)) {
3164                                         const float fade = bstrength * tex_strength(
3165                                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
3166                                                                thread_id);
3167
3168                                         mul_v3_v3fl(proxy[vd.i], val, fade);
3169
3170                                         if (vd.mvert)
3171                                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3172                                 }
3173                         }
3174                 }
3175         }
3176         BKE_pbvh_vertex_iter_end;
3177 }
3178
3179 static void do_scrape_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
3180 {
3181         SculptSession *ss = ob->sculpt;
3182         Brush *brush = BKE_paint_brush(&sd->paint);
3183
3184         const float radius = ss->cache->radius;
3185
3186         float area_no[3];
3187         float area_co[3];
3188         float offset = get_offset(sd, ss);
3189
3190         float displace;
3191
3192         float temp[3];
3193
3194         calc_sculpt_plane(sd, ob, nodes, totnode, area_no, area_co);
3195
3196         displace = -radius * offset;
3197
3198         mul_v3_v3v3(temp, area_no, ss->cache->scale);
3199         mul_v3_fl(temp, displace);
3200         add_v3_v3(area_co, temp);
3201
3202         SculptThreadedTaskData data = {
3203             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
3204             .area_no = area_no, .area_co = area_co,
3205         };
3206
3207         BLI_task_parallel_range_ex(
3208                     0, totnode, &data, NULL, 0, do_scrape_brush_task_cb_ex,
3209                     ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
3210 }
3211
3212 static void do_gravity_task_cb_ex(
3213         void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
3214 {
3215         SculptThreadedTaskData *data = userdata;
3216         SculptSession *ss = data->ob->sculpt;
3217         Brush *brush = data->brush;
3218         float *offset = data->offset;
3219
3220         PBVHVertexIter vd;
3221         SculptBrushTest test;
3222         float (*proxy)[3];
3223
3224         proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
3225
3226         sculpt_brush_test_init(ss, &test);
3227
3228         BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE) {
3229                 if (sculpt_brush_test_sq(&test, vd.co)) {
3230                         const float fade = tex_strength(
3231                                                ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
3232                                                thread_id);
3233
3234                         mul_v3_v3fl(proxy[vd.i], offset, fade);
3235
3236                         if (vd.mvert)
3237                                 vd.mvert->flag |= ME_VERT_PBVH_UPDATE;
3238                 }
3239         }
3240         BKE_pbvh_vertex_iter_end;
3241 }
3242
3243 static void do_gravity(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode, float bstrength)
3244 {
3245         SculptSession *ss = ob->sculpt;
3246         Brush *brush = BKE_paint_brush(&sd->paint);
3247
3248         float offset[3]/*, area_no[3]*/;
3249         float gravity_vector[3];
3250
3251         mul_v3_v3fl(gravity_vector, ss->cache->gravity_direction, -ss->cache->radius_squared);
3252
3253         /* offset with as much as possible factored in already */
3254         mul_v3_v3v3(offset, gravity_vector, ss->cache->scale);
3255         mul_v3_fl(offset, bstrength);
3256
3257         /* threaded loop over nodes */
3258         SculptThreadedTaskData data = {
3259             .sd = sd, .ob = ob, .brush = brush, .nodes = nodes,