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