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