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