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