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