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