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