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