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