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