2.5/Sculpt:
[blender-staging.git] / source / blender / editors / sculpt_paint / sculpt.c
1 /*
2  * $Id: sculptmode.c 18309 2009-01-04 07:47:11Z nicholasbishop $
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software  Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2006 by Nicholas Bishop
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  *
29  * Implements the Sculpt Mode tools
30  *
31  */
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_arithb.h"
36 #include "BLI_blenlib.h"
37 #include "BLI_dynstr.h"
38
39 #include "DNA_armature_types.h"
40 #include "DNA_brush_types.h"
41 #include "DNA_image_types.h"
42 #include "DNA_key_types.h"
43 #include "DNA_mesh_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_modifier_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_texture_types.h"
50 #include "DNA_view3d_types.h"
51 #include "DNA_userdef_types.h"
52 #include "DNA_color_types.h"
53
54 #include "BKE_brush.h"
55 #include "BKE_context.h"
56 #include "BKE_customdata.h"
57 #include "BKE_DerivedMesh.h"
58 #include "BKE_depsgraph.h"
59 #include "BKE_global.h"
60 #include "BKE_image.h"
61 #include "BKE_key.h"
62 #include "BKE_library.h"
63 #include "BKE_main.h"
64 #include "BKE_mesh.h"
65 #include "BKE_modifier.h"
66 #include "BKE_multires.h"
67 #include "BKE_sculpt.h"
68 #include "BKE_texture.h"
69 #include "BKE_utildefines.h"
70 #include "BKE_colortools.h"
71
72 #include "BIF_gl.h"
73 #include "BIF_glutil.h"
74
75 #include "WM_api.h"
76 #include "WM_types.h"
77 #include "ED_screen.h"
78 #include "ED_sculpt.h"
79 #include "ED_space_api.h"
80 #include "ED_util.h"
81 #include "ED_view3d.h"
82 #include "sculpt_intern.h"
83
84 #include "RNA_access.h"
85 #include "RNA_define.h"
86
87 #include "IMB_imbuf_types.h"
88
89 #include "RE_render_ext.h"
90 #include "RE_shader_ext.h" /*for multitex_ext*/
91
92 #include "GPU_draw.h"
93
94 #include <math.h>
95 #include <stdlib.h>
96 #include <string.h>
97
98 /* Number of vertices to average in order to determine the flatten distance */
99 #define FLATTEN_SAMPLE_SIZE 10
100
101 /* ===== STRUCTS =====
102  *
103  */
104
105 /* ActiveData stores an Index into the mvert array of Mesh, plus Fade, which
106    stores how far the vertex is from the brush center, scaled to the range [0,1]. */
107 typedef struct ActiveData {
108         struct ActiveData *next, *prev;
109         unsigned int Index;
110         float Fade;
111         float dist;
112 } ActiveData;
113
114 typedef enum StrokeFlags {
115         CLIP_X = 1,
116         CLIP_Y = 2,
117         CLIP_Z = 4
118 } StrokeFlags;
119
120 /* Cache stroke properties. Used because
121    RNA property lookup isn't particularly fast.
122
123    For descriptions of these settings, check the operator properties.
124 */
125 typedef struct StrokeCache {
126         /* Invariants */
127         float radius;
128         float scale[3];
129         int flag;
130         float clip_tolerance[3];
131         int initial_mouse[2];
132         float depth;
133
134         /* Variants */
135         float true_location[3];
136         float location[3];
137         float flip;
138         float pressure;
139         int mouse[2];
140
141         /* The rest is temporary storage that isn't saved as a property */
142
143         int first_time; /* Beginning of stroke may do some things special */
144
145         ViewContext vc;
146         bglMats *mats;
147
148         float *layer_disps; /* Displacements for each vertex */
149         float (*mesh_store)[3]; /* Copy of the mesh vertices' locations */
150         short (*orig_norms)[3]; /* Copy of the mesh vertices' normals */
151         float rotation; /* Texture rotation (radians) for anchored and rake modes */
152         int pixel_radius, previous_pixel_radius;
153         ListBase grab_active_verts[8]; /* The same list of verts is used throught grab stroke */
154         float grab_delta[3], grab_delta_symmetry[3];
155         float old_grab_location[3];
156         int symmetry; /* Symmetry index between 0 and 7 */
157         float view_normal[3], view_normal_symmetry[3];
158         int last_dot[2]; /* Last location of stroke application */
159         int last_rake[2]; /* Last location of updating rake rotation */
160 } StrokeCache;
161
162 typedef struct RectNode {
163         struct RectNode *next, *prev;
164         rcti r;
165 } RectNode;
166
167 /* Used to store to 2D screen coordinates of each vertex in the mesh. */
168 typedef struct ProjVert {
169         short co[2];
170         
171         /* Used to mark whether a vertex is inside a rough bounding box
172            containing the brush. */
173         char inside;
174 } ProjVert;
175
176 /* ===== OPENGL =====
177  *
178  * Simple functions to get data from the GL
179  */
180
181 /* Uses window coordinates (x,y) and depth component z to find a point in
182    modelspace */
183 static void unproject(bglMats *mats, float out[3], const short x, const short y, const float z)
184 {
185         double ux, uy, uz;
186
187         gluUnProject(x,y,z, mats->modelview, mats->projection,
188                      (GLint *)mats->viewport, &ux, &uy, &uz );
189         out[0] = ux;
190         out[1] = uy;
191         out[2] = uz;
192 }
193
194 /* Convert a point in model coordinates to 2D screen coordinates. */
195 static void projectf(bglMats *mats, const float v[3], float p[2])
196 {
197         double ux, uy, uz;
198
199         gluProject(v[0],v[1],v[2], mats->modelview, mats->projection,
200                    (GLint *)mats->viewport, &ux, &uy, &uz);
201         p[0]= ux;
202         p[1]= uy;
203 }
204
205 static void project(bglMats *mats, const float v[3], short p[2])
206 {
207         float f[2];
208         projectf(mats, v, f);
209
210         p[0]= f[0];
211         p[1]= f[1];
212 }
213
214 /* ===== Sculpting =====
215  *
216  */
217
218 /* Return modified brush size. Uses current tablet pressure (if available) to
219    shrink the brush. Skipped for grab brush because only the first mouse down
220    size is used, which is small if the user has just touched the pen to the
221    tablet */
222 static char brush_size(Sculpt *sd)
223 {
224         float size= sd->brush->size;
225         
226         if((sd->brush->sculpt_tool != SCULPT_TOOL_GRAB) && (sd->brush->flag & BRUSH_SIZE_PRESSURE))
227                 size *= sd->session->cache->pressure;
228
229         return size;
230 }
231
232 /* Return modified brush strength. Includes the direction of the brush, positive
233    values pull vertices, negative values push. Uses tablet pressure and a
234    special multiplier found experimentally to scale the strength factor. */
235 static float brush_strength(Sculpt *sd, StrokeCache *cache)
236 {
237         /* Primary strength input; square it to make lower values more sensitive */
238         float alpha = sd->brush->alpha * sd->brush->alpha;
239
240         float dir= sd->brush->flag & BRUSH_DIR_IN ? -1 : 1;
241         float pressure= 1;
242         float flip= cache->flip ? -1:1;
243         float anchored = sd->brush->flag & BRUSH_ANCHORED ? 25 : 1;
244
245         if(sd->brush->flag & BRUSH_ALPHA_PRESSURE)
246                 pressure *= cache->pressure;
247         
248         switch(sd->brush->sculpt_tool){
249         case SCULPT_TOOL_DRAW:
250         case SCULPT_TOOL_INFLATE:
251         case SCULPT_TOOL_CLAY:
252         case SCULPT_TOOL_FLATTEN:
253                 return alpha * dir * pressure * flip; /*XXX: not sure why? was multiplied by G.vd->grid */;
254         case SCULPT_TOOL_SMOOTH:
255                 return alpha * 4 * pressure;
256         case SCULPT_TOOL_PINCH:
257                 return alpha / 2 * dir * pressure * flip;
258         case SCULPT_TOOL_GRAB:
259                 return 1;
260         case SCULPT_TOOL_LAYER:
261                 return sd->brush->alpha / 50.0f * dir * pressure * flip * anchored; /*XXX: not sure why? multiplied by G.vd->grid */;
262         default:
263                 return 0;
264         }
265 }
266
267 /* For clipping against a mirror modifier */
268 static void sculpt_clip(StrokeCache *cache, float *co, const float val[3])
269 {
270         int i;
271         for(i=0; i<3; ++i) {
272                 if((cache->flag & (CLIP_X << i)) && (fabs(co[i]) <= cache->clip_tolerance[i]))
273                         co[i]= 0.0f;
274                 else
275                         co[i]= val[i];
276         }               
277 }
278
279 static void sculpt_axislock(Sculpt *sd, float *co)
280 {
281         if(sd->flags == (SCULPT_LOCK_X|SCULPT_LOCK_Y|SCULPT_LOCK_Z))
282                 return;
283
284         if(sd->session->cache->vc.v3d->twmode == V3D_MANIP_LOCAL) {
285                 float mat[3][3], imat[3][3];
286                 Mat3CpyMat4(mat, sd->session->cache->vc.obact->obmat);
287                 Mat3Inv(imat, mat);
288                 Mat3MulVecfl(mat, co);
289                 if (sd->flags & SCULPT_LOCK_X) co[0] = 0.0;
290                 if (sd->flags & SCULPT_LOCK_Y) co[1] = 0.0;
291                 if (sd->flags & SCULPT_LOCK_Z) co[2] = 0.0;             
292                 Mat3MulVecfl(imat, co);
293         } else {
294                 if (sd->flags & SCULPT_LOCK_X) co[0] = 0.0;
295                 if (sd->flags & SCULPT_LOCK_Y) co[1] = 0.0;
296                 if (sd->flags & SCULPT_LOCK_Z) co[2] = 0.0;             
297         }
298 }
299
300 static void add_norm_if(float view_vec[3], float out[3], float out_flip[3], const short no[3])
301 {
302         float fno[3] = {no[0], no[1], no[2]};
303
304         Normalize(fno);
305
306         if((Inpf(view_vec, fno)) > 0) {
307                 VecAddf(out, out, fno);
308         } else {
309                 VecAddf(out_flip, out_flip, fno); /* out_flip is used when out is {0,0,0} */
310         }
311 }
312
313 /* Currently only for the draw brush; finds average normal for all active
314    vertices */
315 static void calc_area_normal(Sculpt *sd, float out[3], const ListBase* active_verts)
316 {
317         StrokeCache *cache = sd->session->cache;
318         ActiveData *node = active_verts->first;
319         const int view = 0; /* XXX: should probably be a flag, not number: sd->brush_type==SCULPT_TOOL_DRAW ? sculptmode_brush()->view : 0; */
320         float out_flip[3];
321         float *out_dir = cache->view_normal_symmetry;
322         
323         out[0]=out[1]=out[2] = out_flip[0]=out_flip[1]=out_flip[2] = 0;
324
325         if(sd->brush->flag & BRUSH_ANCHORED) {
326                 for(; node; node = node->next)
327                         add_norm_if(out_dir, out, out_flip, cache->orig_norms[node->Index]);
328         }
329         else {
330                 for(; node; node = node->next)
331                         add_norm_if(out_dir, out, out_flip, sd->session->mvert[node->Index].no);
332         }
333
334         if (out[0]==0.0 && out[1]==0.0 && out[2]==0.0) {
335                 VECCOPY(out, out_flip);
336         }
337         
338         Normalize(out);
339
340         if(out_dir) {
341                 out[0] = out_dir[0] * view + out[0] * (10-view);
342                 out[1] = out_dir[1] * view + out[1] * (10-view);
343                 out[2] = out_dir[2] * view + out[2] * (10-view);
344         }
345         
346         Normalize(out);
347 }
348
349 static void do_draw_brush(Sculpt *sd, SculptSession *ss, const ListBase* active_verts)
350 {
351         float area_normal[3];
352         ActiveData *node= active_verts->first;
353
354         calc_area_normal(sd, area_normal, active_verts);
355         
356         sculpt_axislock(sd, area_normal);
357         
358         while(node){
359                 float *co= ss->mvert[node->Index].co;
360
361                 const float val[3]= {co[0]+area_normal[0]*ss->cache->radius*node->Fade*ss->cache->scale[0],
362                                      co[1]+area_normal[1]*ss->cache->radius*node->Fade*ss->cache->scale[1],
363                                      co[2]+area_normal[2]*ss->cache->radius*node->Fade*ss->cache->scale[2]};
364                                      
365                 sculpt_clip(ss->cache, co, val);
366                 
367                 node= node->next;
368         }
369 }
370
371 /* For the smooth brush, uses the neighboring vertices around vert to calculate
372    a smoothed location for vert. Skips corner vertices (used by only one
373    polygon.) */
374 static void neighbor_average(SculptSession *ss, float avg[3], const int vert)
375 {
376         int i, skip= -1, total=0;
377         IndexNode *node= ss->fmap[vert].first;
378         char ncount= BLI_countlist(&ss->fmap[vert]);
379         MFace *f;
380
381         avg[0] = avg[1] = avg[2] = 0;
382                 
383         /* Don't modify corner vertices */
384         if(ncount==1) {
385                 VecCopyf(avg, ss->mvert[vert].co);
386                 return;
387         }
388
389         while(node){
390                 f= &ss->mface[node->index];
391                 
392                 if(f->v4) {
393                         skip= (f->v1==vert?2:
394                                f->v2==vert?3:
395                                f->v3==vert?0:
396                                f->v4==vert?1:-1);
397                 }
398
399                 for(i=0; i<(f->v4?4:3); ++i) {
400                         if(i != skip && (ncount!=2 || BLI_countlist(&ss->fmap[(&f->v1)[i]]) <= 2)) {
401                                 VecAddf(avg, avg, ss->mvert[(&f->v1)[i]].co);
402                                 ++total;
403                         }
404                 }
405
406                 node= node->next;
407         }
408
409         if(total>0)
410                 VecMulf(avg, 1.0f / total);
411         else
412                 VecCopyf(avg, ss->mvert[vert].co);
413 }
414
415 static void do_smooth_brush(SculptSession *ss, const ListBase* active_verts)
416 {
417         ActiveData *node= active_verts->first;
418         int i;
419         
420         for(i = 0; i < 2; ++i) {
421                 while(node){
422                         float *co= ss->mvert[node->Index].co;
423                         float avg[3], val[3];
424                         
425                         neighbor_average(ss, avg, node->Index);
426                         val[0] = co[0]+(avg[0]-co[0])*node->Fade;
427                         val[1] = co[1]+(avg[1]-co[1])*node->Fade;
428                         val[2] = co[2]+(avg[2]-co[2])*node->Fade;
429                         
430                         sculpt_clip(ss->cache, co, val);
431                         node= node->next;
432                 }
433         }
434 }
435
436 static void do_pinch_brush(SculptSession *ss, const ListBase* active_verts)
437 {
438         ActiveData *node= active_verts->first;
439
440         while(node) {
441                 float *co= ss->mvert[node->Index].co;
442                 const float val[3]= {co[0]+(ss->cache->location[0]-co[0])*node->Fade,
443                                      co[1]+(ss->cache->location[1]-co[1])*node->Fade,
444                                      co[2]+(ss->cache->location[2]-co[2])*node->Fade};
445                 sculpt_clip(ss->cache, co, val);
446                 node= node->next;
447         }
448 }
449
450 static void do_grab_brush(Sculpt *sd, SculptSession *ss)
451 {
452         ActiveData *node= ss->cache->grab_active_verts[ss->cache->symmetry].first;
453         float add[3];
454         float grab_delta[3];
455         
456         VecCopyf(grab_delta, ss->cache->grab_delta_symmetry);
457         sculpt_axislock(sd, grab_delta);
458         
459         while(node) {
460                 float *co= ss->mvert[node->Index].co;
461                 
462                 VecCopyf(add, grab_delta);
463                 VecMulf(add, node->Fade);
464                 VecAddf(add, add, co);
465                 sculpt_clip(ss->cache, co, add);
466
467                 node= node->next;
468         }
469         
470 }
471
472 static void do_layer_brush(Sculpt *sd, SculptSession *ss, const ListBase *active_verts)
473 {
474         float area_normal[3];
475         ActiveData *node= active_verts->first;
476         float lim= brush_strength(sd, ss->cache);
477
478         if(sd->brush->flag & BRUSH_DIR_IN)
479                 lim = -lim;
480
481         calc_area_normal(sd, area_normal, active_verts);
482
483         while(node){
484                 float *disp= &ss->cache->layer_disps[node->Index];
485                 
486                 if((lim > 0 && *disp < lim) ||
487                    (lim < 0 && *disp > lim)) {
488                         float *co= ss->mvert[node->Index].co;
489                         float val[3];
490                         
491                         *disp+= node->Fade;
492
493                         if(lim < 0 && *disp < lim)
494                                 *disp = lim;
495                         else if(lim > 0 && *disp > lim)
496                                         *disp = lim;
497
498                         val[0] = ss->cache->mesh_store[node->Index][0]+area_normal[0] * *disp*ss->cache->scale[0];
499                         val[1] = ss->cache->mesh_store[node->Index][1]+area_normal[1] * *disp*ss->cache->scale[1];
500                         val[2] = ss->cache->mesh_store[node->Index][2]+area_normal[2] * *disp*ss->cache->scale[2];
501                         //VecMulf(val, ss->cache->radius);
502                         sculpt_clip(ss->cache, co, val);
503                 }
504
505                 node= node->next;
506         }
507 }
508
509 static void do_inflate_brush(SculptSession *ss, const ListBase *active_verts)
510 {
511         ActiveData *node= active_verts->first;
512         float add[3];
513         
514         while(node) {
515                 float *co= ss->mvert[node->Index].co;
516                 short *no= ss->mvert[node->Index].no;
517
518                 add[0]= no[0]/ 32767.0f;
519                 add[1]= no[1]/ 32767.0f;
520                 add[2]= no[2]/ 32767.0f;
521                 VecMulf(add, node->Fade * ss->cache->radius);
522                 add[0]*= ss->cache->scale[0];
523                 add[1]*= ss->cache->scale[1];
524                 add[2]*= ss->cache->scale[2];
525                 VecAddf(add, add, co);
526                 
527                 sculpt_clip(ss->cache, co, add);
528
529                 node= node->next;
530         }
531 }
532
533 static void calc_flatten_center(SculptSession *ss, ActiveData *node, float co[3])
534 {
535         ActiveData *outer[FLATTEN_SAMPLE_SIZE];
536         int i;
537         
538         for(i = 0; i < FLATTEN_SAMPLE_SIZE; ++i)
539                 outer[i] = node;
540                 
541         for(; node; node = node->next) {
542                 for(i = 0; i < FLATTEN_SAMPLE_SIZE; ++i) {
543                         if(node->dist > outer[i]->dist) {
544                                 outer[i] = node;
545                                 break;
546                         }
547                 }
548         }
549         
550         co[0] = co[1] = co[2] = 0.0f;
551         for(i = 0; i < FLATTEN_SAMPLE_SIZE; ++i)
552                 VecAddf(co, co, ss->mvert[outer[i]->Index].co);
553         VecMulf(co, 1.0f / FLATTEN_SAMPLE_SIZE);
554 }
555
556 static void do_flatten_clay_brush(Sculpt *sd, SculptSession *ss, const ListBase *active_verts, int clay)
557 {
558         ActiveData *node= active_verts->first;
559         /* area_normal and cntr define the plane towards which vertices are squashed */
560         float area_normal[3];
561         float cntr[3];
562
563         calc_area_normal(sd, area_normal, active_verts);
564         calc_flatten_center(ss, node, cntr);
565
566         while(node){
567                 float *co= ss->mvert[node->Index].co;
568                 float p1[3], sub1[3], sub2[3], intr[3], val[3];
569                 
570                 /* Find the intersection between squash-plane and vertex (along the area normal) */
571                 VecSubf(p1, co, area_normal);
572                 VecSubf(sub1, cntr, p1);
573                 VecSubf(sub2, co, p1);
574                 VecSubf(intr, co, p1);
575                 VecMulf(intr, Inpf(area_normal, sub1) / Inpf(area_normal, sub2));
576                 VecAddf(intr, intr, p1);
577                 
578                 VecSubf(val, intr, co);
579                 VecMulf(val, fabs(node->Fade));
580                 VecAddf(val, val, co);
581                 
582                 if(clay) {
583                         /* Clay brush displaces after flattening */
584                         float tmp[3];
585                         VecCopyf(tmp, area_normal);
586                         VecMulf(tmp, ss->cache->radius * node->Fade * 0.1);
587                         VecAddf(val, val, tmp);
588                 }
589
590                 sculpt_clip(ss->cache, co, val);
591                 
592                 node= node->next;
593         }
594 }
595  
596 /* Uses symm to selectively flip any axis of a coordinate. */
597 static void flip_coord(float out[3], float in[3], const char symm)
598 {
599         if(symm & SCULPT_SYMM_X)
600                 out[0]= -in[0];
601         else
602                 out[0]= in[0];
603         if(symm & SCULPT_SYMM_Y)
604                 out[1]= -in[1];
605         else
606                 out[1]= in[1];
607         if(symm & SCULPT_SYMM_Z)
608                 out[2]= -in[2];
609         else
610                 out[2]= in[2];
611 }
612
613 /* Get a pixel from the texcache at (px, py) */
614 static unsigned char get_texcache_pixel(const SculptSession *ss, int px, int py)
615 {
616         unsigned *p;
617         p = ss->texcache + py * ss->texcache_side + px;
618         return ((unsigned char*)(p))[0];
619 }
620
621 static float get_texcache_pixel_bilinear(const SculptSession *ss, float u, float v)
622 {
623         int x, y, x2, y2;
624         const int tc_max = ss->texcache_side - 1;
625         float urat, vrat, uopp;
626
627         if(u < 0) u = 0;
628         else if(u >= ss->texcache_side) u = tc_max;
629         if(v < 0) v = 0;
630         else if(v >= ss->texcache_side) v = tc_max;
631
632         x = floor(u);
633         y = floor(v);
634         x2 = x + 1;
635         y2 = y + 1;
636
637         if(x2 > ss->texcache_side) x2 = tc_max;
638         if(y2 > ss->texcache_side) y2 = tc_max;
639         
640         urat = u - x;
641         vrat = v - y;
642         uopp = 1 - urat;
643                 
644         return ((get_texcache_pixel(ss, x, y) * uopp +
645                  get_texcache_pixel(ss, x2, y) * urat) * (1 - vrat) + 
646                 (get_texcache_pixel(ss, x, y2) * uopp +
647                  get_texcache_pixel(ss, x2, y2) * urat) * vrat) / 255.0;
648 }
649
650 /* Return a multiplier for brush strength on a particular vertex. */
651 static float tex_strength(Sculpt *sd, float *point, const float len)
652 {
653         SculptSession *ss= sd->session;
654         Brush *br = sd->brush;
655         float avg= 1;
656
657         if(br->texact==-1 || !br->mtex[br->texact])
658                 avg= 1;
659         else if(br->tex_mode==BRUSH_TEX_3D) {
660                 /* Get strength by feeding the vertex location directly
661                    into a texture */
662                 float jnk;
663                 const float factor= 0.01;
664                 MTex mtex;
665                 memset(&mtex,0,sizeof(MTex));
666                 mtex.tex= br->mtex[br->texact]->tex;
667                 mtex.projx= 1;
668                 mtex.projy= 2;
669                 mtex.projz= 3;
670                 VecCopyf(mtex.size, br->mtex[br->texact]->size);
671                 VecMulf(mtex.size, factor);
672                 if(!sd->texsep)
673                         mtex.size[1]= mtex.size[2]= mtex.size[0];
674                 
675                 externtex(&mtex,point,&avg,&jnk,&jnk,&jnk,&jnk);
676         }
677         else if(ss->texcache) {
678                 const float bsize= ss->cache->pixel_radius * 2;
679                 const float rot= sd->brush->rot + ss->cache->rotation;
680                 int px, py;
681                 float flip[3], point_2d[2];
682
683                 /* If the active area is being applied for symmetry, flip it
684                    across the symmetry axis in order to project it. This insures
685                    that the brush texture will be oriented correctly. */
686                 VecCopyf(flip, point);
687                 flip_coord(flip, flip, ss->cache->symmetry);
688                 projectf(ss->cache->mats, flip, point_2d);
689
690                 /* For Tile and Drag modes, get the 2D screen coordinates of the
691                    and scale them up or down to the texture size. */
692                 if(br->tex_mode==BRUSH_TEX_TILE) {
693                         const int sx= (const int)br->mtex[br->texact]->size[0];
694                         const int sy= (const int)sd->texsep ? br->mtex[br->texact]->size[1] : sx;
695                         
696                         float fx= point_2d[0];
697                         float fy= point_2d[1];
698                         
699                         float angle= atan2(fy, fx) - rot;
700                         float flen= sqrtf(fx*fx + fy*fy);
701                         
702                         if(rot<0.001 && rot>-0.001) {
703                                 px= point_2d[0];
704                                 py= point_2d[1];
705                         } else {
706                                 px= flen * cos(angle) + 2000;
707                                 py= flen * sin(angle) + 2000;
708                         }
709                         if(sx != 1)
710                                 px %= sx-1;
711                         if(sy != 1)
712                                 py %= sy-1;
713                         avg= get_texcache_pixel_bilinear(ss, ss->texcache_side*px/sx, ss->texcache_side*py/sy);
714                 } else {
715                         float fx= (point_2d[0] - ss->cache->mouse[0]) / bsize;
716                         float fy= (point_2d[1] - ss->cache->mouse[1]) / bsize;
717
718                         float angle= atan2(fy, fx) - rot;
719                         float flen= sqrtf(fx*fx + fy*fy);
720                         
721                         fx = flen * cos(angle) + 0.5;
722                         fy = flen * sin(angle) + 0.5;
723
724                         avg= get_texcache_pixel_bilinear(ss, fx * ss->texcache_side, fy * ss->texcache_side);
725                 }
726         }
727
728         avg*= brush_curve_strength(sd->brush, len, ss->cache->radius); /* Falloff curve */
729
730         return avg;
731 }
732
733 /* Mark area around the brush as damaged. projverts are marked if they are
734    inside the area and the damaged rectangle in 2D screen coordinates is 
735    added to damaged_rects. */
736 static void sculpt_add_damaged_rect(SculptSession *ss)
737 {
738         short p[2];
739         RectNode *rn= MEM_mallocN(sizeof(RectNode),"RectNode");
740         const float radius = MAX2(ss->cache->pixel_radius, ss->cache->previous_pixel_radius);
741         unsigned i;
742
743         /* Find center */
744         project(ss->cache->mats, ss->cache->location, p);
745         rn->r.xmin= p[0] - radius;
746         rn->r.ymin= p[1] - radius;
747         rn->r.xmax= p[0] + radius;
748         rn->r.ymax= p[1] + radius;
749
750         BLI_addtail(&ss->damaged_rects, rn);
751
752         /* Update insides */
753         for(i=0; i<ss->totvert; ++i) {
754                 if(!ss->projverts[i].inside) {
755                         if(ss->projverts[i].co[0] > rn->r.xmin && ss->projverts[i].co[1] > rn->r.ymin &&
756                            ss->projverts[i].co[0] < rn->r.xmax && ss->projverts[i].co[1] < rn->r.ymax) {
757                                 ss->projverts[i].inside= 1;
758                         }
759                 }
760                 // XXX: remember to fix this!
761                 // temporary pass
762                 ss->projverts[i].inside = 1;
763         }
764 }
765
766 /* Clears the depth buffer in each modified area. */
767 #if 0
768 static void sculpt_clear_damaged_areas(SculptSession *ss)
769 {
770         RectNode *rn= NULL;
771
772         for(rn = ss->damaged_rects.first; rn; rn = rn->next) {
773                 rcti clp = rn->r;
774                 rcti *win = NULL; /*XXX: &curarea->winrct; */
775                 
776                 clp.xmin += win->xmin;
777                 clp.xmax += win->xmin;
778                 clp.ymin += win->ymin;
779                 clp.ymax += win->ymin;
780                 
781                 if(clp.xmin < win->xmax && clp.xmax > win->xmin &&
782                    clp.ymin < win->ymax && clp.ymax > win->ymin) {
783                         if(clp.xmin < win->xmin) clp.xmin = win->xmin;
784                         if(clp.ymin < win->ymin) clp.ymin = win->ymin;
785                         if(clp.xmax > win->xmax) clp.xmax = win->xmax;
786                         if(clp.ymax > win->ymax) clp.ymax = win->ymax;
787
788                         glScissor(clp.xmin + 1, clp.ymin + 1,
789                                   clp.xmax - clp.xmin - 2,
790                                   clp.ymax - clp.ymin - 2);
791                 }
792                 
793                 glClear(GL_DEPTH_BUFFER_BIT);
794         }
795 }
796 #endif
797 static void do_brush_action(Sculpt *sd, StrokeCache *cache)
798 {
799         SculptSession *ss = sd->session;
800         float av_dist;
801         ListBase active_verts={0,0};
802         ListBase *grab_active_verts = &ss->cache->grab_active_verts[ss->cache->symmetry];
803         ActiveData *adata= 0;
804         float *vert;
805         Mesh *me= NULL; /*XXX: get_mesh(OBACT); */
806         const float bstrength= brush_strength(sd, cache);
807         KeyBlock *keyblock= NULL; /*XXX: ob_get_keyblock(OBACT); */
808         Brush *b = sd->brush;
809         int i;
810
811         sculpt_add_damaged_rect(ss);
812
813         /* Build a list of all vertices that are potentially within the brush's
814            area of influence. Only do this once for the grab brush. */
815         if((b->sculpt_tool != SCULPT_TOOL_GRAB) || cache->first_time) {
816                 for(i=0; i<ss->totvert; ++i) {
817                         /* Projverts.inside provides a rough bounding box */
818                         if(ss->multires || ss->projverts[i].inside) {
819                                 //vert= ss->vertexcosnos ? &ss->vertexcosnos[i*6] : a->verts[i].co;
820                                 vert= ss->mvert[i].co;
821                                 av_dist= VecLenf(ss->cache->location, vert);
822                                 if(av_dist < cache->radius) {
823                                         adata= (ActiveData*)MEM_mallocN(sizeof(ActiveData), "ActiveData");
824
825                                         adata->Index = i;
826                                         /* Fade is used to store the final strength at which the brush
827                                            should modify a particular vertex. */
828                                         adata->Fade= tex_strength(sd, vert, av_dist) * bstrength;
829                                         adata->dist = av_dist;
830
831                                         if(b->sculpt_tool == SCULPT_TOOL_GRAB && cache->first_time)
832                                                 BLI_addtail(grab_active_verts, adata);
833                                         else
834                                                 BLI_addtail(&active_verts, adata);
835                                 }
836                         }
837                 }
838         }
839
840         /* Only act if some verts are inside the brush area */
841         if(active_verts.first || (b->sculpt_tool == SCULPT_TOOL_GRAB && grab_active_verts->first)) {
842                 /* Apply one type of brush action */
843                 switch(b->sculpt_tool){
844                 case SCULPT_TOOL_DRAW:
845                         do_draw_brush(sd, ss, &active_verts);
846                         break;
847                 case SCULPT_TOOL_SMOOTH:
848                         do_smooth_brush(ss, &active_verts);
849                         break;
850                 case SCULPT_TOOL_PINCH:
851                         do_pinch_brush(ss, &active_verts);
852                         break;
853                 case SCULPT_TOOL_INFLATE:
854                         do_inflate_brush(ss, &active_verts);
855                         break;
856                 case SCULPT_TOOL_GRAB:
857                         do_grab_brush(sd, ss);
858                         break;
859                 case SCULPT_TOOL_LAYER:
860                         do_layer_brush(sd, ss, &active_verts);
861                         break;
862                 case SCULPT_TOOL_FLATTEN:
863                         do_flatten_clay_brush(sd, ss, &active_verts, 0);
864                         break;
865                 case SCULPT_TOOL_CLAY:
866                         do_flatten_clay_brush(sd, ss, &active_verts, 1);
867                 }
868         
869                 /* Copy the modified vertices from mesh to the active key */
870                 if(keyblock && !ss->multires) {
871                         float *co= keyblock->data;
872                         if(co) {
873                                 if(b->sculpt_tool == SCULPT_TOOL_GRAB)
874                                         adata = grab_active_verts->first;
875                                 else
876                                         adata = active_verts.first;
877
878                                 for(; adata; adata= adata->next)
879                                         if(adata->Index < keyblock->totelem)
880                                                 VecCopyf(&co[adata->Index*3], me->mvert[adata->Index].co);
881                         }
882                 }
883
884                 if(ss->vertexcosnos && !ss->multires)
885                         BLI_freelistN(&active_verts);
886                 else {
887                         if(b->sculpt_tool != SCULPT_TOOL_GRAB)
888                                 addlisttolist(&ss->damaged_verts, &active_verts);
889                 }
890         }
891 }
892
893 /* Flip all the editdata across the axis/axes specified by symm. Used to
894    calculate multiple modifications to the mesh when symmetry is enabled. */
895 static void calc_brushdata_symm(StrokeCache *cache, const char symm)
896 {
897         flip_coord(cache->location, cache->true_location, symm);
898         flip_coord(cache->view_normal_symmetry, cache->view_normal, symm);
899         flip_coord(cache->grab_delta_symmetry, cache->grab_delta, symm);
900         cache->symmetry= symm;
901 }
902
903 static void do_symmetrical_brush_actions(Sculpt *sd, StrokeCache *cache)
904 {
905         const char symm = sd->flags & 7;
906         int i;
907
908         /* Brush spacing: only apply dot if next dot is far enough away */
909         if((sd->brush->flag & BRUSH_SPACE) && !(sd->brush->flag & BRUSH_ANCHORED) && !cache->first_time) {
910                 int dx = cache->last_dot[0] - cache->mouse[0];
911                 int dy = cache->last_dot[1] - cache->mouse[1];
912                 if(sqrt(dx*dx+dy*dy) < sd->brush->spacing)
913                         return;
914         }
915         memcpy(cache->last_dot, cache->mouse, sizeof(int) * 2);
916
917         VecCopyf(cache->location, cache->true_location);
918         VecCopyf(cache->grab_delta_symmetry, cache->grab_delta);
919         cache->symmetry = 0;
920         do_brush_action(sd, cache);
921
922         for(i = 1; i <= symm; ++i) {
923                 if(symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5))) {
924                         calc_brushdata_symm(cache, i);
925                         do_brush_action(sd, cache);
926                 }
927         }
928
929         cache->first_time = 0;
930 }
931
932 static void add_face_normal(vec3f *norm, MVert *mvert, const MFace* face, float *fn)
933 {
934         vec3f c= {mvert[face->v1].co[0],mvert[face->v1].co[1],mvert[face->v1].co[2]};
935         vec3f b= {mvert[face->v2].co[0],mvert[face->v2].co[1],mvert[face->v2].co[2]};
936         vec3f a= {mvert[face->v3].co[0],mvert[face->v3].co[1],mvert[face->v3].co[2]};
937         vec3f s1, s2;
938         float final[3];
939
940         VecSubf(&s1.x,&a.x,&b.x);
941         VecSubf(&s2.x,&c.x,&b.x);
942
943         final[0] = s1.y * s2.z - s1.z * s2.y;
944         final[1] = s1.z * s2.x - s1.x * s2.z;
945         final[2] = s1.x * s2.y - s1.y * s2.x;
946
947         if(fn)
948                 VecCopyf(fn, final);
949
950         norm->x+= final[0];
951         norm->y+= final[1];
952         norm->z+= final[2];
953 }
954
955 static void update_damaged_vert(SculptSession *ss, ListBase *lb)
956 {
957         ActiveData *vert;
958        
959         for(vert= lb->first; vert; vert= vert->next) {
960                 vec3f norm= {0,0,0};            
961                 IndexNode *face= ss->fmap[vert->Index].first;
962
963                 while(face){
964                         float *fn = NULL;
965                         if(ss->face_normals)
966                                 fn = &ss->face_normals[face->index*3];
967                         add_face_normal(&norm, ss->mvert, &ss->mface[face->index], fn);
968                         face= face->next;
969                 }
970                 Normalize(&norm.x);
971                 
972                 ss->mvert[vert->Index].no[0]=norm.x*32767;
973                 ss->mvert[vert->Index].no[1]=norm.y*32767;
974                 ss->mvert[vert->Index].no[2]=norm.z*32767;
975         }
976 }
977
978 static void calc_damaged_verts(SculptSession *ss)
979 {
980         int i;
981         
982         for(i=0; i<8; ++i)
983                 update_damaged_vert(ss, &ss->cache->grab_active_verts[i]);
984         update_damaged_vert(ss, &ss->damaged_verts);
985         BLI_freelistN(&ss->damaged_verts);
986         ss->damaged_verts.first = ss->damaged_verts.last = NULL;
987 }
988
989 #if 0
990 static void projverts_clear_inside(SculptSession *ss)
991 {
992         int i;
993         for(i = 0; i < ss->totvert; ++i)
994                 ss->projverts[i].inside = 0;
995 }
996 #endif
997
998 static void sculpt_update_tex(Sculpt *sd)
999 {
1000         SculptSession *ss= sd->session;
1001
1002         if(ss->texcache) {
1003                 MEM_freeN(ss->texcache);
1004                 ss->texcache= NULL;
1005         }
1006
1007         /* Need to allocate a bigger buffer for bigger brush size */
1008         ss->texcache_side = sd->brush->size * 2;
1009         if(!ss->texcache || ss->texcache_side > ss->texcache_actual) {
1010                 ss->texcache = brush_gen_texture_cache(sd->brush, sd->brush->size);
1011                 ss->texcache_actual = ss->texcache_side;
1012         }
1013 }
1014
1015 void sculptmode_selectbrush_menu(void)
1016 {
1017         /* XXX: I guess menus belong elsewhere too?
1018
1019         Sculpt *sd= sculpt_data();
1020         int val;
1021         
1022         pupmenu_set_active(sd->brush_type);
1023         
1024         val= pupmenu("Select Brush%t|Draw|Smooth|Pinch|Inflate|Grab|Layer|Flatten");
1025
1026         if(val>0) {
1027                 sd->brush_type= val;
1028
1029                 allqueue(REDRAWVIEW3D, 1);
1030                 allqueue(REDRAWBUTSEDIT, 1);
1031         }*/
1032 }
1033
1034 static void sculptmode_update_all_projverts(SculptSession *ss)
1035 {
1036         unsigned i;
1037
1038         if(!ss->projverts)
1039                 ss->projverts = MEM_mallocN(sizeof(ProjVert)*ss->totvert,"ProjVerts");
1040
1041         for(i=0; i<ss->totvert; ++i) {
1042                 project(ss->cache->mats, ss->vertexcosnos ? &ss->vertexcosnos[i * 6] : ss->mvert[i].co,
1043                         ss->projverts[i].co);
1044                 ss->projverts[i].inside= 0;
1045         }
1046 }
1047
1048 /* Checks whether full update mode (slower) needs to be used to work with modifiers */
1049 char sculpt_modifiers_active(Object *ob)
1050 {
1051         ModifierData *md;
1052         
1053         for(md= modifiers_getVirtualModifierList(ob); md; md= md->next) {
1054                 if(md->mode & eModifierMode_Realtime && md->type != eModifierType_Multires)
1055                         return 1;
1056         }
1057         
1058         return 0;
1059 }
1060
1061 /* Sculpt mode handles multires differently from regular meshes, but only if
1062    it's the last modifier on the stack and it is not on the first level */
1063 static struct MultiresModifierData *sculpt_multires_active(Object *ob)
1064 {
1065         ModifierData *md;
1066         
1067         for(md= modifiers_getVirtualModifierList(ob); md; md= md->next) {
1068                 if(md->type == eModifierType_Multires && !md->next) {
1069                         MultiresModifierData *mmd = (MultiresModifierData*)md;
1070                         if(mmd->lvl != 1)
1071                                 return mmd;
1072                 }
1073         }
1074
1075         return NULL;
1076 }
1077
1078 static void sculpt_update_mesh_elements(bContext *C)
1079 {
1080         SculptSession *ss = CTX_data_tool_settings(C)->sculpt->session;
1081         Object *ob = CTX_data_active_object(C);
1082         int oldtotvert = ss->totvert;
1083
1084         if((ss->multires = sculpt_multires_active(ob))) {
1085                 DerivedMesh *dm = mesh_get_derived_final(CTX_data_scene(C), ob, CD_MASK_BAREMESH);
1086                 ss->totvert = dm->getNumVerts(dm);
1087                 ss->totface = dm->getNumFaces(dm);
1088                 ss->mvert = dm->getVertDataArray(dm, CD_MVERT);
1089                 ss->mface = dm->getFaceDataArray(dm, CD_MFACE);
1090                 ss->face_normals = dm->getFaceDataArray(dm, CD_NORMAL);
1091         }
1092         else {
1093                 Mesh *me = get_mesh(ob);
1094                 ss->totvert = me->totvert;
1095                 ss->totface = me->totface;
1096                 ss->mvert = me->mvert;
1097                 ss->mface = me->mface;
1098                 ss->face_normals = NULL;
1099         }
1100
1101         if(ss->totvert != oldtotvert) {
1102                 if(ss->projverts) MEM_freeN(ss->projverts);
1103                 ss->projverts = NULL;
1104
1105                 if(ss->fmap) MEM_freeN(ss->fmap);
1106                 if(ss->fmap_mem) MEM_freeN(ss->fmap_mem);
1107                 create_vert_face_map(&ss->fmap, &ss->fmap_mem, ss->mface, ss->totvert, ss->totface);
1108                 ss->fmap_size = ss->totvert;
1109         }
1110 }
1111
1112 /* XXX: lots of drawing code (partial redraw), has to go elsewhere */
1113 #if 0
1114 void sculptmode_draw_wires(SculptSession *ss, int only_damaged)
1115 {
1116         Mesh *me = get_mesh(OBACT);
1117         int i;
1118
1119         bglPolygonOffset(1.0);
1120         glDepthMask(0);
1121         BIF_ThemeColor((OBACT==OBACT)?TH_ACTIVE:TH_SELECT);
1122
1123         for(i=0; i<me->totedge; i++) {
1124                 MEdge *med= &me->medge[i];
1125
1126                 if((!only_damaged || (ss->projverts[med->v1].inside || ss->projverts[med->v2].inside)) &&
1127                    (med->flag & ME_EDGEDRAW)) {
1128                         glDrawElements(GL_LINES, 2, GL_UNSIGNED_INT, &med->v1);
1129                 }
1130         }
1131
1132         glDepthMask(1);
1133         bglPolygonOffset(0.0);
1134 }
1135
1136 void sculptmode_draw_mesh(int only_damaged) 
1137 {
1138         int i, j, dt, drawCurrentMat = 1, matnr= -1;
1139         SculptSession *ss = sculpt_session();
1140
1141         sculpt_update_mesh_elements(ss, OBACT);
1142
1143         persp(PERSP_VIEW);
1144         mymultmatrix(OBACT->obmat);
1145         glEnable(GL_DEPTH_TEST);
1146         glEnable(GL_LIGHTING);
1147         /* XXX: GPU_set_object_materials(G.scene, OBACT, 0, NULL); */
1148         glEnable(GL_CULL_FACE);
1149
1150         glShadeModel(GL_SMOOTH);
1151
1152         glVertexPointer(3, GL_FLOAT, sizeof(MVert), &cache->mvert[0].co);
1153         glNormalPointer(GL_SHORT, sizeof(MVert), &cache->mvert[0].no);
1154
1155         dt= MIN2(G.vd->drawtype, OBACT->dt);
1156         if(dt==OB_WIRE)
1157                 glColorMask(0,0,0,0);
1158
1159         for(i=0; i<ss->totface; ++i) {
1160                 MFace *f= &ss->mface[i];
1161                 char inside= 0;
1162                 int new_matnr= f->mat_nr + 1;
1163                 
1164                 if(new_matnr != matnr)
1165                         drawCurrentMat= GPU_enable_material(matnr = new_matnr, NULL);
1166                 
1167                 /* If only_damaged!=0, only draw faces that are partially
1168                    inside the area(s) modified by the brush */
1169                 if(only_damaged) {
1170                         for(j=0; j<(f->v4?4:3); ++j) {
1171                                 if(ss->projverts[*((&f->v1)+j)].inside) {
1172                                         inside= 1;
1173                                         break;
1174                                 }
1175                         }
1176                 }
1177                 else
1178                         inside= 1;
1179                         
1180                 if(inside && drawCurrentMat)
1181                         glDrawElements(f->v4?GL_QUADS:GL_TRIANGLES, f->v4?4:3, GL_UNSIGNED_INT, &f->v1);
1182         }
1183
1184         glDisable(GL_CULL_FACE);
1185         glDisable(GL_LIGHTING);
1186         glColorMask(1,1,1,1);
1187
1188         if(dt==OB_WIRE || (OBACT->dtx & OB_DRAWWIRE))
1189                 sculptmode_draw_wires(ss, only_damaged);
1190
1191         glDisable(GL_DEPTH_TEST);
1192 }
1193 #endif
1194
1195 static int sculpt_poll(bContext *C)
1196 {
1197         return G.f & G_SCULPTMODE && CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
1198                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
1199 }
1200
1201 /*** Sculpt Cursor ***/
1202 static void draw_paint_cursor(bContext *C, int x, int y, void *customdata)
1203 {
1204         Sculpt *sd= CTX_data_tool_settings(C)->sculpt;
1205         
1206         glTranslatef((float)x, (float)y, 0.0f);
1207         
1208         glColor4ub(255, 100, 100, 128);
1209         glEnable( GL_LINE_SMOOTH );
1210         glEnable(GL_BLEND);
1211         glutil_draw_lined_arc(0.0, M_PI*2.0, sd->brush->size, 40);
1212         glDisable(GL_BLEND);
1213         glDisable( GL_LINE_SMOOTH );
1214         
1215         glTranslatef((float)-x, (float)-y, 0.0f);
1216 }
1217
1218 static void toggle_paint_cursor(bContext *C)
1219 {
1220         Sculpt *s = CTX_data_scene(C)->toolsettings->sculpt;
1221
1222         if(s->session->cursor) {
1223                 WM_paint_cursor_end(CTX_wm_manager(C), s->session->cursor);
1224                 s->session->cursor = NULL;
1225         }
1226         else {
1227                 s->session->cursor =
1228                         WM_paint_cursor_activate(CTX_wm_manager(C), sculpt_poll, draw_paint_cursor, NULL);
1229         }
1230 }
1231
1232 static void sculpt_undo_push(bContext *C, Sculpt *sd)
1233 {
1234         switch(sd->brush->sculpt_tool) {
1235         case SCULPT_TOOL_DRAW:
1236                 ED_undo_push(C, "Draw Brush"); break;
1237         case SCULPT_TOOL_SMOOTH:
1238                 ED_undo_push(C, "Smooth Brush"); break;
1239         case SCULPT_TOOL_PINCH:
1240                 ED_undo_push(C, "Pinch Brush"); break;
1241         case SCULPT_TOOL_INFLATE:
1242                 ED_undo_push(C, "Inflate Brush"); break;
1243         case SCULPT_TOOL_GRAB:
1244                 ED_undo_push(C, "Grab Brush"); break;
1245         case SCULPT_TOOL_LAYER:
1246                 ED_undo_push(C, "Layer Brush"); break;
1247         case SCULPT_TOOL_FLATTEN:
1248                 ED_undo_push(C, "Flatten Brush"); break;
1249         default:
1250                 ED_undo_push(C, "Sculpting"); break;
1251         }
1252 }
1253
1254 static int sculpt_brush_curve_preset_exec(bContext *C, wmOperator *op)
1255 {
1256         brush_curve_preset(CTX_data_scene(C)->toolsettings->sculpt->brush, RNA_enum_get(op->ptr, "mode"));
1257         return OPERATOR_FINISHED;
1258 }
1259
1260 static void SCULPT_OT_brush_curve_preset(wmOperatorType *ot)
1261 {
1262         static EnumPropertyItem prop_mode_items[] = {
1263                 {BRUSH_PRESET_SHARP, "SHARP", 0, "Sharp Curve", ""},
1264                 {BRUSH_PRESET_SMOOTH, "SMOOTH", 0, "Smooth Curve", ""},
1265                 {BRUSH_PRESET_MAX, "MAX", 0, "Max Curve", ""},
1266                 {0, NULL, 0, NULL, NULL}};
1267
1268         ot->name= "Preset";
1269         ot->idname= "SCULPT_OT_brush_curve_preset";
1270
1271         ot->exec= sculpt_brush_curve_preset_exec;
1272         ot->poll= sculpt_poll;
1273
1274         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1275
1276         RNA_def_enum(ot->srna, "mode", prop_mode_items, BRUSH_PRESET_SHARP, "Mode", "");
1277 }
1278
1279 /**** Radial control ****/
1280 static int sculpt_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
1281 {
1282         toggle_paint_cursor(C);
1283         brush_radial_control_invoke(op, CTX_data_scene(C)->toolsettings->sculpt->brush, 1);
1284         return WM_radial_control_invoke(C, op, event);
1285 }
1286
1287 static int sculpt_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
1288 {
1289         int ret = WM_radial_control_modal(C, op, event);
1290         if(ret != OPERATOR_RUNNING_MODAL)
1291                 toggle_paint_cursor(C);
1292         return ret;
1293 }
1294
1295 static int sculpt_radial_control_exec(bContext *C, wmOperator *op)
1296 {
1297         return brush_radial_control_exec(op, CTX_data_scene(C)->toolsettings->sculpt->brush, 1);
1298 }
1299
1300 static void SCULPT_OT_radial_control(wmOperatorType *ot)
1301 {
1302         WM_OT_radial_control_partial(ot);
1303
1304         ot->name= "Sculpt Radial Control";
1305         ot->idname= "SCULPT_OT_radial_control";
1306
1307         ot->invoke= sculpt_radial_control_invoke;
1308         ot->modal= sculpt_radial_control_modal;
1309         ot->exec= sculpt_radial_control_exec;
1310         ot->poll= sculpt_poll;
1311
1312         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1313 }
1314
1315 /**** Operator for applying a stroke (various attributes including mouse path)
1316       using the current brush. ****/
1317
1318 static float unproject_brush_radius(SculptSession *ss, float offset)
1319 {
1320         float brush_edge[3];
1321
1322         /* In anchored mode, brush size changes with mouse loc, otherwise it's fixed using the brush radius */
1323         unproject(ss->cache->mats, brush_edge, ss->cache->initial_mouse[0] + offset,
1324                   ss->cache->initial_mouse[1], ss->cache->depth);
1325
1326         return VecLenf(ss->cache->true_location, brush_edge);
1327 }
1328
1329 static void sculpt_cache_free(StrokeCache *cache)
1330 {
1331         if(cache->layer_disps)
1332                 MEM_freeN(cache->layer_disps);
1333         if(cache->mesh_store)
1334                 MEM_freeN(cache->mesh_store);
1335         if(cache->orig_norms)
1336                 MEM_freeN(cache->orig_norms);
1337         if(cache->mats)
1338                 MEM_freeN(cache->mats);
1339         MEM_freeN(cache);
1340 }
1341
1342 /* Initialize the stroke cache invariants from operator properties */
1343 static void sculpt_update_cache_invariants(Sculpt *sd, bContext *C, wmOperator *op)
1344 {
1345         StrokeCache *cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
1346         int i;
1347
1348         sd->session->cache = cache;
1349
1350         RNA_float_get_array(op->ptr, "scale", cache->scale);
1351         cache->flag = RNA_int_get(op->ptr, "flag");
1352         RNA_float_get_array(op->ptr, "clip_tolerance", cache->clip_tolerance);
1353         RNA_int_get_array(op->ptr, "initial_mouse", cache->initial_mouse);
1354         cache->depth = RNA_float_get(op->ptr, "depth");
1355
1356         /* Truly temporary data that isn't stored in properties */
1357
1358         view3d_set_viewcontext(C, &cache->vc);
1359
1360         cache->mats = MEM_callocN(sizeof(bglMats), "sculpt bglMats");
1361         view3d_get_transformation(&cache->vc, cache->vc.obact, cache->mats);
1362
1363         sculpt_update_mesh_elements(C);
1364
1365         /* Make copies of the mesh vertex locations and normals for some tools */
1366         if(sd->brush->sculpt_tool == SCULPT_TOOL_LAYER || (sd->brush->flag & BRUSH_ANCHORED)) {
1367                 cache->layer_disps = MEM_callocN(sizeof(float) * sd->session->totvert, "layer brush displacements");
1368                 cache->mesh_store= MEM_mallocN(sizeof(float) * 3 * sd->session->totvert, "sculpt mesh vertices copy");
1369                 for(i = 0; i < sd->session->totvert; ++i)
1370                         VecCopyf(cache->mesh_store[i], sd->session->mvert[i].co);
1371
1372                 if(sd->brush->flag & BRUSH_ANCHORED) {
1373                         cache->orig_norms= MEM_mallocN(sizeof(short) * 3 * sd->session->totvert, "Sculpt orig norm");
1374                         for(i = 0; i < sd->session->totvert; ++i) {
1375                                 cache->orig_norms[i][0] = sd->session->mvert[i].no[0];
1376                                 cache->orig_norms[i][1] = sd->session->mvert[i].no[1];
1377                                 cache->orig_norms[i][2] = sd->session->mvert[i].no[2];
1378                         }
1379                 }
1380         }
1381
1382         unproject(cache->mats, cache->true_location, cache->initial_mouse[0], cache->initial_mouse[1], cache->depth);
1383         cache->radius = unproject_brush_radius(sd->session, brush_size(sd));
1384         cache->rotation = 0;
1385         cache->first_time = 1;
1386 }
1387
1388 /* Initialize the stroke cache variants from operator properties */
1389 static void sculpt_update_cache_variants(Sculpt *sd, PointerRNA *ptr)
1390 {
1391         StrokeCache *cache = sd->session->cache;
1392         float grab_location[3];
1393         int dx, dy;
1394
1395         if(!(sd->brush->flag & BRUSH_ANCHORED))
1396                 RNA_float_get_array(ptr, "location", cache->true_location);
1397         cache->flip = RNA_boolean_get(ptr, "flip");
1398         RNA_int_get_array(ptr, "mouse", cache->mouse);
1399         
1400         /* Truly temporary data that isn't stored in properties */
1401
1402         cache->previous_pixel_radius = cache->pixel_radius;
1403         cache->pixel_radius = brush_size(sd);
1404
1405         if(sd->brush->flag & BRUSH_ANCHORED) {
1406                 dx = cache->mouse[0] - cache->initial_mouse[0];
1407                 dy = cache->mouse[1] - cache->initial_mouse[1];
1408                 cache->pixel_radius = sqrt(dx*dx + dy*dy);
1409                 cache->radius = unproject_brush_radius(sd->session, cache->pixel_radius);
1410                 cache->rotation = atan2(dy, dx);
1411         }
1412         else if(sd->brush->flag & BRUSH_RAKE) {
1413                 int update;
1414
1415                 dx = cache->last_rake[0] - cache->mouse[0];
1416                 dy = cache->last_rake[1] - cache->mouse[1];
1417
1418                 update = dx*dx + dy*dy > 100;
1419
1420                 /* To prevent jitter, only update the angle if the mouse has moved over 10 pixels */
1421                 if(update && !cache->first_time)
1422                         cache->rotation = M_PI_2 + atan2(dy, dx);
1423
1424                 if(update || cache->first_time) {
1425                         cache->last_rake[0] = cache->mouse[0];
1426                         cache->last_rake[1] = cache->mouse[1];
1427                 }
1428         }
1429
1430         /* Find the grab delta */
1431         if(sd->brush->sculpt_tool == SCULPT_TOOL_GRAB) {
1432                 unproject(cache->mats, grab_location, cache->mouse[0], cache->mouse[1], cache->depth);
1433                 if(!cache->first_time)
1434                         VecSubf(cache->grab_delta, grab_location, cache->old_grab_location);
1435                 VecCopyf(cache->old_grab_location, grab_location);
1436         }
1437 }
1438
1439 /* Initialize stroke operator properties */
1440 static void sculpt_brush_stroke_init_properties(bContext *C, wmOperator *op, wmEvent *event, SculptSession *ss)
1441 {
1442         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1443         Object *ob= CTX_data_active_object(C);
1444         ModifierData *md;
1445         ViewContext vc;
1446         float scale[3], clip_tolerance[3] = {0,0,0};
1447         int mouse[2], flag = 0;
1448
1449         /* Set scaling adjustment */
1450         scale[0] = 1.0f / ob->size[0];
1451         scale[1] = 1.0f / ob->size[1];
1452         scale[2] = 1.0f / ob->size[2];
1453         RNA_float_set_array(op->ptr, "scale", scale);
1454
1455         /* Initialize mirror modifier clipping */
1456         for(md= ob->modifiers.first; md; md= md->next) {
1457                 if(md->type==eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
1458                         const MirrorModifierData *mmd = (MirrorModifierData*) md;
1459                         
1460                         /* Mark each axis that needs clipping along with its tolerance */
1461                         if(mmd->flag & MOD_MIR_CLIPPING) {
1462                                 flag |= CLIP_X << mmd->axis;
1463                                 if(mmd->tolerance > clip_tolerance[mmd->axis])
1464                                         clip_tolerance[mmd->axis] = mmd->tolerance;
1465                         }
1466                 }
1467         }
1468         RNA_int_set(op->ptr, "flag", flag);
1469         RNA_float_set_array(op->ptr, "clip_tolerance", clip_tolerance);
1470
1471         /* Initial mouse location */
1472         mouse[0] = event->x;
1473         mouse[1] = event->y;
1474         RNA_int_set_array(op->ptr, "initial_mouse", mouse);
1475
1476         /* Initial screen depth under the mouse */
1477         view3d_set_viewcontext(C, &vc);
1478         RNA_float_set(op->ptr, "depth", read_cached_depth(&vc, event->x, event->y));
1479
1480         sculpt_update_cache_invariants(sd, C, op);
1481 }
1482
1483 static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, wmEvent *event)
1484 {
1485         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1486
1487         view3d_operator_needs_opengl(C);
1488         sculpt_brush_stroke_init_properties(C, op, event, sd->session);
1489
1490         sculptmode_update_all_projverts(sd->session);
1491
1492         /* TODO: Shouldn't really have to do this at the start of every
1493            stroke, but sculpt would need some sort of notification when
1494            changes are made to the texture. */
1495         sculpt_update_tex(sd);
1496
1497         /* add modal handler */
1498         WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1499         
1500         return OPERATOR_RUNNING_MODAL;
1501 }
1502
1503 static void sculpt_restore_mesh(Sculpt *sd)
1504 {
1505         StrokeCache *cache = sd->session->cache;
1506         int i;
1507         
1508         /* Restore the mesh before continuing with anchored stroke */
1509         if((sd->brush->flag & BRUSH_ANCHORED) && cache->mesh_store) {
1510                 for(i = 0; i < sd->session->totvert; ++i) {
1511                         VecCopyf(sd->session->mvert[i].co, cache->mesh_store[i]);
1512                         sd->session->mvert[i].no[0] = cache->orig_norms[i][0];
1513                         sd->session->mvert[i].no[1] = cache->orig_norms[i][1];
1514                         sd->session->mvert[i].no[2] = cache->orig_norms[i][2];
1515                 }
1516         }
1517 }
1518
1519 static void sculpt_post_stroke_free(SculptSession *ss)
1520 {
1521         BLI_freelistN(&ss->damaged_rects);
1522         BLI_freelistN(&ss->damaged_verts);
1523 }
1524
1525 static void sculpt_flush_update(bContext *C)
1526 {
1527         Sculpt *s = CTX_data_tool_settings(C)->sculpt;
1528         ARegion *ar = CTX_wm_region(C);
1529         MultiresModifierData *mmd = s->session->multires;
1530
1531         calc_damaged_verts(s->session);
1532
1533         if(mmd) {
1534                 if(mmd->undo_verts && mmd->undo_verts != s->session->mvert)
1535                         MEM_freeN(mmd->undo_verts);
1536                 
1537                 mmd->undo_verts = s->session->mvert;
1538                 mmd->undo_verts_tot = s->session->totvert;
1539                 multires_mark_as_modified(CTX_data_active_object(C));
1540         }
1541
1542         ED_region_tag_redraw(ar);
1543 }
1544
1545 static int sculpt_brush_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
1546 {
1547         PointerRNA itemptr;
1548         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1549         float center[3];
1550         int mouse[2] = {event->x, event->y};
1551
1552         sculpt_update_mesh_elements(C);
1553
1554         unproject(sd->session->cache->mats, center, event->x, event->y,
1555                   read_cached_depth(&sd->session->cache->vc, event->x, event->y));
1556
1557         /* Add to stroke */
1558         RNA_collection_add(op->ptr, "stroke", &itemptr);
1559         RNA_float_set_array(&itemptr, "location", center);
1560         RNA_int_set_array(&itemptr, "mouse", mouse);
1561         RNA_boolean_set(&itemptr, "flip", event->shift);
1562         sculpt_update_cache_variants(sd, &itemptr);
1563
1564         sculpt_restore_mesh(sd);
1565         do_symmetrical_brush_actions(CTX_data_tool_settings(C)->sculpt, sd->session->cache);
1566
1567         sculpt_flush_update(C);
1568         sculpt_post_stroke_free(sd->session);
1569
1570         /* Finished */
1571         if(event->type == LEFTMOUSE && event->val == 0) {
1572                 request_depth_update(sd->session->cache->vc.rv3d);
1573
1574                 sculpt_cache_free(sd->session->cache);
1575
1576                 sculpt_undo_push(C, sd);
1577
1578                 return OPERATOR_FINISHED;
1579         }
1580
1581         return OPERATOR_RUNNING_MODAL;
1582 }
1583
1584 static int sculpt_brush_stroke_exec(bContext *C, wmOperator *op)
1585 {
1586         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1587
1588         view3d_operator_needs_opengl(C);
1589         sculpt_update_cache_invariants(sd, C, op);
1590         sculptmode_update_all_projverts(sd->session);
1591         sculpt_update_tex(sd);
1592
1593         RNA_BEGIN(op->ptr, itemptr, "stroke") {
1594                 sculpt_update_cache_variants(sd, &itemptr);
1595
1596                 sculpt_restore_mesh(sd);
1597                 do_symmetrical_brush_actions(sd, sd->session->cache);
1598
1599                 sculpt_post_stroke_free(sd->session);
1600         }
1601         RNA_END;
1602
1603         sculpt_flush_update(C);
1604         sculpt_cache_free(sd->session->cache);
1605
1606         sculpt_undo_push(C, sd);
1607
1608         return OPERATOR_FINISHED;
1609 }
1610
1611 static void SCULPT_OT_brush_stroke(wmOperatorType *ot)
1612 {
1613         ot->flag |= OPTYPE_REGISTER;
1614
1615         /* identifiers */
1616         ot->name= "Sculpt Mode";
1617         ot->idname= "SCULPT_OT_brush_stroke";
1618         
1619         /* api callbacks */
1620         ot->invoke= sculpt_brush_stroke_invoke;
1621         ot->modal= sculpt_brush_stroke_modal;
1622         ot->exec= sculpt_brush_stroke_exec;
1623         ot->poll= sculpt_poll;
1624         
1625         /* flags (sculpt does own undo? (ton) */
1626         ot->flag= OPTYPE_REGISTER;
1627
1628         /* properties */
1629         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1630
1631         /* If the object has a scaling factor, brushes also need to be scaled
1632            to work as expected. */
1633         RNA_def_float_vector(ot->srna, "scale", 3, NULL, 0.0f, FLT_MAX, "Scale", "", 0.0f, 1000.0f);
1634
1635         RNA_def_int(ot->srna, "flag", 0, 0, INT_MAX, "flag", "", 0, INT_MAX);
1636
1637         /* For mirror modifiers */
1638         RNA_def_float_vector(ot->srna, "clip_tolerance", 3, NULL, 0.0f, FLT_MAX, "clip_tolerance", "", 0.0f, 1000.0f);
1639
1640         /* The initial 2D location of the mouse */
1641         RNA_def_int_vector(ot->srna, "initial_mouse", 2, NULL, INT_MIN, INT_MAX, "initial_mouse", "", INT_MIN, INT_MAX);
1642
1643         /* The initial screen depth of the mouse */
1644         RNA_def_float(ot->srna, "depth", 0.0f, 0.0f, FLT_MAX, "depth", "", 0.0f, FLT_MAX);
1645 }
1646
1647 /**** Toggle operator for turning sculpt mode on or off ****/
1648
1649 static int sculpt_toggle_mode(bContext *C, wmOperator *op)
1650 {
1651         ToolSettings *ts = CTX_data_tool_settings(C);
1652
1653         if(G.f & G_SCULPTMODE) {
1654                 multires_force_update(CTX_data_active_object(C));
1655
1656                 /* Leave sculptmode */
1657                 G.f &= ~G_SCULPTMODE;
1658
1659                 toggle_paint_cursor(C);
1660
1661                 sculptsession_free(ts->sculpt);
1662         }
1663         else {
1664                 MTex *mtex; // XXX: temporary
1665
1666                 /* Enter sculptmode */
1667
1668                 G.f |= G_SCULPTMODE;
1669                 
1670                 /* Create persistent sculpt mode data */
1671                 if(!ts->sculpt)
1672                         ts->sculpt = MEM_callocN(sizeof(Sculpt), "sculpt mode data");
1673
1674                 /* Create sculpt mode session data */
1675                 if(ts->sculpt->session)
1676                         MEM_freeN(ts->sculpt->session);
1677                 ts->sculpt->session = MEM_callocN(sizeof(SculptSession), "sculpt session");
1678
1679                 toggle_paint_cursor(C);
1680
1681                 /* If there's no brush, create one */
1682                 brush_check_exists(&ts->sculpt->brush);
1683
1684                 /* XXX: testing: set the brush texture to the first available one */
1685                 if(G.main->tex.first) {
1686                         Tex *tex = G.main->tex.first;
1687                         if(tex->type) {
1688                                 mtex = MEM_callocN(sizeof(MTex), "test mtex");
1689                                 ts->sculpt->brush->texact = 0;
1690                                 ts->sculpt->brush->mtex[0] = mtex;
1691                                 mtex->tex = tex;
1692                                 mtex->size[0] = mtex->size[1] = mtex->size[2] = 50;
1693                         }
1694                 }
1695         }
1696
1697         return OPERATOR_FINISHED;
1698 }
1699
1700 static void SCULPT_OT_sculptmode_toggle(wmOperatorType *ot)
1701 {
1702         /* identifiers */
1703         ot->name= "Sculpt Mode";
1704         ot->idname= "SCULPT_OT_sculptmode_toggle";
1705         
1706         /* api callbacks */
1707         ot->exec= sculpt_toggle_mode;
1708         ot->poll= ED_operator_object_active;
1709         
1710         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1711 }
1712
1713 void ED_operatortypes_sculpt()
1714 {
1715         WM_operatortype_append(SCULPT_OT_radial_control);
1716         WM_operatortype_append(SCULPT_OT_brush_stroke);
1717         WM_operatortype_append(SCULPT_OT_sculptmode_toggle);
1718         WM_operatortype_append(SCULPT_OT_brush_curve_preset);
1719 }
1720
1721 void sculpt(Sculpt *sd)
1722 {
1723 #if 0
1724         SculptSession *ss= sd->session;
1725         Object *ob= NULL; /*XXX */
1726         Mesh *me;
1727         MultiresModifierData *mmd = NULL;
1728         /* lastSigMouse is for the rake, to store the last place the mouse movement was significant */
1729         short mouse[2], mvalo[2], lastSigMouse[2],firsttime=1, mousebut;
1730         short modifier_calculations= 0;
1731         BrushAction *a = MEM_callocN(sizeof(BrushAction), "brush action");
1732         short spacing= 32000;
1733         int scissor_box[4];
1734         float offsetRot;
1735         int smooth_stroke = 0, i;
1736         int anchored, rake = 0 /* XXX: rake = ? */;
1737
1738         /* XXX: checking that sculpting is allowed
1739         if(!(G.f & G_SCULPTMODE) || G.obedit || !ob || ob->id.lib || !get_mesh(ob) || (get_mesh(ob)->totface == 0))
1740                 return;
1741         if(!(ob->lay & G.vd->lay))
1742                 error("Active object is not in this layer");
1743         if(ob_get_keyblock(ob)) {
1744                 if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
1745                         error("Cannot sculpt on unlocked shape key");
1746                         return;
1747                 }
1748         }*/
1749         
1750         anchored = sd->brush->flag & BRUSH_ANCHORED;
1751         smooth_stroke = (sd->flags & SCULPT_INPUT_SMOOTH) && (sd->brush->sculpt_tool != SCULPT_TOOL_GRAB) && !anchored;
1752
1753         if(smooth_stroke)
1754                 sculpt_stroke_new(256);
1755
1756         ss->damaged_rects.first = ss->damaged_rects.last = NULL;
1757         ss->damaged_verts.first = ss->damaged_verts.last = NULL;
1758         ss->vertexcosnos = NULL;
1759
1760         mmd = sculpt_multires_active(ob);
1761
1762         /* Check that vertex users are up-to-date */
1763         if(ob != active_ob || !ss->vertex_users || ss->vertex_users_size != cache->totvert) {
1764                 sculpt_vertexusers_free(ss);
1765                 calc_vertex_users(ss);
1766                 if(ss->projverts)
1767                         MEM_freeN(ss->projverts);
1768                 ss->projverts = NULL;
1769                 active_ob= ob;
1770         }
1771                 
1772         glEnableClientState(GL_VERTEX_ARRAY);
1773         glEnableClientState(GL_NORMAL_ARRAY);
1774
1775         /*XXX:
1776         persp(PERSP_VIEW);
1777         getmouseco_areawin(mvalo);*/
1778
1779         /* Init texture
1780            FIXME: Shouldn't be doing this every time! */
1781         if(sd->tex_mode!=SCULPTREPT_3D)
1782                 sculptmode_update_tex(sd);
1783
1784         /*XXX: getmouseco_areawin(mouse); */
1785         mvalo[0]= mouse[0];
1786         mvalo[1]= mouse[1];
1787         lastSigMouse[0]=mouse[0];
1788         lastSigMouse[1]=mouse[1];
1789         mousebut = 0; /* XXX: L_MOUSE; */
1790
1791         /* If modifier_calculations is true, then extra time must be spent
1792            updating the mesh. This takes a *lot* longer, so it's worth
1793            skipping if the modifier stack is empty. */
1794         modifier_calculations= sculpt_modifiers_active(ob);
1795
1796         if(modifier_calculations)
1797                 ss->vertexcosnos= mesh_get_mapped_verts_nors(NULL, ob); /* XXX: scene = ? */
1798         sculptmode_update_all_projverts(ss);
1799
1800         /* Capture original copy */
1801         if(sd->flags & SCULPT_DRAW_FAST)
1802                 glAccum(GL_LOAD, 1);
1803
1804         /* Get original scissor box */
1805         glGetIntegerv(GL_SCISSOR_BOX, scissor_box);
1806         
1807         /* For raking, get the original angle*/
1808         offsetRot=sculpt_tex_angle(sd);
1809
1810         me = get_mesh(ob);
1811
1812         while (/*XXX:get_mbut() & mousebut*/0) {
1813                 /* XXX: getmouseco_areawin(mouse); */
1814                 /* If rake, and the mouse has moved over 10 pixels (euclidean) (prevents jitter) then get the new angle */
1815                 if (rake && (pow(lastSigMouse[0]-mouse[0],2)+pow(lastSigMouse[1]-mouse[1],2))>100){
1816                         /*Nasty looking, but just orig + new angle really*/
1817                         set_tex_angle(sd, offsetRot+180.+to_deg(atan2((float)(mouse[1]-lastSigMouse[1]),(float)(mouse[0]-lastSigMouse[0]))));
1818                         lastSigMouse[0]=mouse[0];
1819                         lastSigMouse[1]=mouse[1];
1820                 }
1821                 
1822                 if(firsttime || mouse[0]!=mvalo[0] || mouse[1]!=mvalo[1] ||
1823                    sd->brush->flag & BRUSH_AIRBRUSH) {
1824                         a->firsttime = firsttime;
1825                         firsttime= 0;
1826
1827                         if(smooth_stroke)
1828                                 sculpt_stroke_add_point(ss->stroke, mouse[0], mouse[1]);
1829
1830                         spacing+= sqrt(pow(mvalo[0]-mouse[0],2)+pow(mvalo[1]-mouse[1],2));
1831
1832                         if(modifier_calculations && !ss->vertexcosnos)
1833                                 ss->vertexcosnos= mesh_get_mapped_verts_nors(NULL, ob); /*XXX scene = ? */
1834
1835                         if(sd->brush->sculpt_tool != SCULPT_TOOL_GRAB) {
1836                                 if(anchored) {
1837                                         /* Restore the mesh before continuing with anchored stroke */
1838                                         /*if(a->mesh_store) {
1839                                                 for(i = 0; i < cache->totvert; ++i) {
1840                                                         VecCopyf(cache->mvert[i].co, &a->mesh_store[i].x);
1841                                                         cache->mvert[i].no[0] = a->orig_norms[i][0];
1842                                                         cache->mvert[i].no[1] = a->orig_norms[i][1];
1843                                                         cache->mvert[i].no[2] = a->orig_norms[i][2];
1844                                                 }
1845                                                 }*/
1846                                         
1847                                         //do_symmetrical_brush_actions(sd, a, mouse, NULL);
1848                                 }
1849                                 else {
1850                                         if(smooth_stroke) {
1851                                                 sculpt_stroke_apply(sd, ss->stroke);
1852                                         }
1853                                         else if(sd->spacing==0 || spacing>sd->spacing) {
1854                                                 //do_symmetrical_brush_actions(sd, a, mouse, NULL);
1855                                                 spacing= 0;
1856                                         }
1857                                 }
1858                         }
1859                         else {
1860                                 //do_symmetrical_brush_actions(sd, a, mouse, mvalo);
1861                                 //unproject(ss, sd->pivot, mouse[0], mouse[1], a->depth);
1862                         }
1863
1864                         if((!ss->multires && modifier_calculations) || ob_get_keyblock(ob)) {
1865                                 /* XXX: DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA); */ }
1866
1867                         if(modifier_calculations || sd->brush->sculpt_tool == SCULPT_TOOL_GRAB || !(sd->flags & SCULPT_DRAW_FAST)) {
1868                                 calc_damaged_verts(ss, a);
1869                                 /*XXX: scrarea_do_windraw(curarea);
1870                                 screen_swapbuffers(); */
1871                         } else { /* Optimized drawing */
1872                                 calc_damaged_verts(ss, a);
1873
1874                                 /* Draw the stored image to the screen */
1875                                 glAccum(GL_RETURN, 1);
1876
1877                                 sculpt_clear_damaged_areas(ss);
1878                                 
1879                                 /* Draw all the polygons that are inside the modified area(s) */
1880                                 glScissor(scissor_box[0], scissor_box[1], scissor_box[2], scissor_box[3]);
1881                                 /* XXX: sculptmode_draw_mesh(1); */
1882                                 glAccum(GL_LOAD, 1);
1883
1884                                 projverts_clear_inside(ss);
1885
1886                                 /* XXX: persp(PERSP_WIN); */
1887                                 glDisable(GL_DEPTH_TEST);
1888                                 
1889                                 /* Draw cursor */
1890                                 if(sd->flags & SCULPT_TOOL_DRAW)
1891                                         fdrawXORcirc((float)mouse[0],(float)mouse[1],sd->brush->size);
1892                                 /* XXX: if(smooth_stroke)
1893                                    sculpt_stroke_draw();
1894                                 
1895                                 myswapbuffers(); */
1896                         }
1897
1898                         BLI_freelistN(&ss->damaged_rects);
1899                         ss->damaged_rects.first = ss->damaged_rects.last = NULL;
1900         
1901                         mvalo[0]= mouse[0];
1902                         mvalo[1]= mouse[1];
1903
1904                         if(ss->vertexcosnos) {
1905                                 MEM_freeN(ss->vertexcosnos);
1906                                 ss->vertexcosnos= NULL;
1907                         }
1908
1909                 }
1910                 else { /*XXX:BIF_wait_for_statechange();*/ }
1911         }
1912
1913         /* Set the rotation of the brush back to what it was before any rake */
1914         set_tex_angle(sd, offsetRot);
1915         
1916         if(smooth_stroke) {
1917                 sculpt_stroke_apply_all(sd, ss->stroke);
1918                 calc_damaged_verts(ss, a);
1919                 BLI_freelistN(&ss->damaged_rects);
1920         }
1921
1922         //if(a->layer_disps) MEM_freeN(a->layer_disps);
1923         //if(a->mesh_store) MEM_freeN(a->mesh_store);
1924         //if(a->orig_norms) MEM_freeN(a->orig_norms);
1925         for(i=0; i<8; ++i)
1926                 BLI_freelistN(&a->grab_active_verts[i]);
1927         MEM_freeN(a);
1928         sculpt_stroke_free(ss->stroke);
1929         ss->stroke = NULL;
1930
1931         if(mmd) {
1932                 if(mmd->undo_verts && mmd->undo_verts != cache->mvert)
1933                         MEM_freeN(mmd->undo_verts);
1934                 
1935                 mmd->undo_verts = cache->mvert;
1936                 mmd->undo_verts_tot = cache->totvert;
1937         }
1938
1939         //sculpt_undo_push(sd);
1940
1941         /* XXX: if(G.vd->depths) G.vd->depths->damaged= 1;
1942            allqueue(REDRAWVIEW3D, 0); */
1943 #endif
1944 }
1945
1946 /* Partial Mesh Visibility */
1947
1948 /* XXX: Partial vis. always was a mess, have to figure something out */
1949 #if 0
1950 /* mode: 0=hide outside selection, 1=hide inside selection */
1951 static void sculptmode_do_pmv(Object *ob, rcti *hb_2d, int mode)
1952 {
1953         Mesh *me= get_mesh(ob);
1954         float hidebox[6][3];
1955         vec3f plane_normals[4];
1956         float plane_ds[4];
1957         unsigned i, j;
1958         unsigned ndx_show, ndx_hide;
1959         MVert *nve;
1960         unsigned face_cnt_show= 0, face_ndx_show= 0;
1961         unsigned edge_cnt_show= 0, edge_ndx_show= 0;
1962         unsigned *old_map= NULL;
1963         const unsigned SHOW= 0, HIDE=1;
1964
1965         /* Convert hide box from 2D to 3D */
1966         unproject(hidebox[0], hb_2d->xmin, hb_2d->ymax, 1);
1967         unproject(hidebox[1], hb_2d->xmax, hb_2d->ymax, 1);
1968         unproject(hidebox[2], hb_2d->xmax, hb_2d->ymin, 1);
1969         unproject(hidebox[3], hb_2d->xmin, hb_2d->ymin, 1);
1970         unproject(hidebox[4], hb_2d->xmin, hb_2d->ymax, 0);
1971         unproject(hidebox[5], hb_2d->xmax, hb_2d->ymin, 0);
1972         
1973         /* Calculate normals for each side of hide box */
1974         CalcNormFloat(hidebox[0], hidebox[1], hidebox[4], &plane_normals[0].x);
1975         CalcNormFloat(hidebox[1], hidebox[2], hidebox[5], &plane_normals[1].x);
1976         CalcNormFloat(hidebox[2], hidebox[3], hidebox[5], &plane_normals[2].x);
1977         CalcNormFloat(hidebox[3], hidebox[0], hidebox[4], &plane_normals[3].x);
1978         
1979         /* Calculate D for each side of hide box */
1980         for(i= 0; i<4; ++i)
1981                 plane_ds[i]= hidebox[i][0]*plane_normals[i].x + hidebox[i][1]*plane_normals[i].y +
1982                         hidebox[i][2]*plane_normals[i].z;
1983         
1984         /* Add partial visibility to mesh */
1985         if(!me->pv) {
1986                 me->pv= MEM_callocN(sizeof(PartialVisibility),"PartialVisibility");
1987         } else {
1988                 old_map= MEM_callocN(sizeof(unsigned)*me->pv->totvert,"PMV oldmap");
1989                 for(i=0; i<me->pv->totvert; ++i) {
1990                         old_map[i]= me->pv->vert_map[i]<me->totvert?0:1;
1991                 }
1992                 mesh_pmv_revert(ob, me);
1993         }
1994         
1995         /* Kill sculpt data */
1996         active_ob= NULL;
1997         
1998         /* Initalize map with which verts are to be hidden */
1999         me->pv->vert_map= MEM_mallocN(sizeof(unsigned)*me->totvert, "PMV vertmap");
2000         me->pv->totvert= me->totvert;
2001         me->totvert= 0;
2002         for(i=0; i<me->pv->totvert; ++i) {
2003                 me->pv->vert_map[i]= mode ? HIDE:SHOW;
2004                 for(j=0; j<4; ++j) {
2005                         if(me->mvert[i].co[0] * plane_normals[j].x +
2006                            me->mvert[i].co[1] * plane_normals[j].y +
2007                            me->mvert[i].co[2] * plane_normals[j].z < plane_ds[j] ) {
2008                                 me->pv->vert_map[i]= mode ? SHOW:HIDE; /* Vert is outside the hide box */
2009                                 break;
2010                         }
2011                 }
2012                 if(old_map && old_map[i]) me->pv->vert_map[i]= 1;
2013                 if(!me->pv->vert_map[i]) ++me->totvert;
2014
2015         }
2016         if(old_map) MEM_freeN(old_map);
2017
2018         /* Find out how many faces to show */
2019         for(i=0; i<me->totface; ++i) {
2020                 if(!me->pv->vert_map[me->mface[i].v1] &&
2021                    !me->pv->vert_map[me->mface[i].v2] &&
2022                    !me->pv->vert_map[me->mface[i].v3]) {
2023                         if(me->mface[i].v4) {
2024                                 if(!me->pv->vert_map[me->mface[i].v4])
2025                                         ++face_cnt_show;
2026                         }
2027                         else ++face_cnt_show;
2028                 }
2029         }
2030         /* Find out how many edges to show */
2031         for(i=0; i<me->totedge; ++i) {
2032                 if(!me->pv->vert_map[me->medge[i].v1] &&
2033                    !me->pv->vert_map[me->medge[i].v2])
2034                         ++edge_cnt_show;
2035         }
2036
2037         /* Create new vert array and reset each vert's map with map[old]=new index */
2038         nve= MEM_mallocN(sizeof(MVert)*me->pv->totvert, "PMV verts");
2039         ndx_show= 0; ndx_hide= me->totvert;
2040         for(i=0; i<me->pv->totvert; ++i) {
2041                 if(me->pv->vert_map[i]) {
2042                         me->pv->vert_map[i]= ndx_hide;
2043                         nve[me->pv->vert_map[i]]= me->mvert[i];
2044                         ++ndx_hide;
2045                 } else {
2046                         me->pv->vert_map[i]= ndx_show;
2047                         nve[me->pv->vert_map[i]]= me->mvert[i];
2048                         ++ndx_show;
2049                 }
2050         }
2051         CustomData_free_layer_active(&me->vdata, CD_MVERT, me->pv->totvert);
2052         me->mvert= CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, nve, me->totvert);
2053
2054         /* Create new face array */
2055         me->pv->old_faces= me->mface;
2056         me->pv->totface= me->totface;
2057         me->mface= MEM_mallocN(sizeof(MFace)*face_cnt_show, "PMV faces");
2058         for(i=0; i<me->totface; ++i) {
2059                 MFace *pr_f= &me->pv->old_faces[i];
2060                 char show= 0;
2061
2062                 if(me->pv->vert_map[pr_f->v1] < me->totvert &&
2063                    me->pv->vert_map[pr_f->v2] < me->totvert &&
2064                    me->pv->vert_map[pr_f->v3] < me->totvert) {
2065                         if(pr_f->v4) {
2066                                 if(me->pv->vert_map[pr_f->v4] < me->totvert)
2067                                         show= 1;
2068                         }
2069                         else show= 1;
2070                 }
2071
2072                 if(show) {
2073                         MFace *cr_f= &me->mface[face_ndx_show];
2074                         *cr_f= *pr_f;
2075                         cr_f->v1= me->pv->vert_map[pr_f->v1];
2076                         cr_f->v2= me->pv->vert_map[pr_f->v2];
2077                         cr_f->v3= me->pv->vert_map[pr_f->v3];
2078                         cr_f->v4= pr_f->v4 ? me->pv->vert_map[pr_f->v4] : 0;
2079                         test_index_face(cr_f,NULL,0,pr_f->v4?4:3);
2080                         ++face_ndx_show;
2081                 }
2082         }
2083         me->totface= face_cnt_show;
2084         CustomData_set_layer(&me->fdata, CD_MFACE, me->mface);
2085
2086         /* Create new edge array */
2087         me->pv->old_edges= me->medge;
2088         me->pv->totedge= me->totedge;
2089         me->medge= MEM_mallocN(sizeof(MEdge)*edge_cnt_show, "PMV edges");
2090         me->pv->edge_map= MEM_mallocN(sizeof(int)*me->pv->totedge,"PMV edgemap");
2091         for(i=0; i<me->totedge; ++i) {
2092                 if(me->pv->vert_map[me->pv->old_edges[i].v1] < me->totvert &&
2093                    me->pv->vert_map[me->pv->old_edges[i].v2] < me->totvert) {
2094                         MEdge *cr_e= &me->medge[edge_ndx_show];
2095                         me->pv->edge_map[i]= edge_ndx_show;
2096                         *cr_e= me->pv->old_edges[i];
2097                         cr_e->v1= me->pv->vert_map[me->pv->old_edges[i].v1];
2098                         cr_e->v2= me->pv->vert_map[me->pv->old_edges[i].v2];
2099                         ++edge_ndx_show;
2100                 }
2101                 else me->pv->edge_map[i]= -1;
2102         }
2103         me->totedge= edge_cnt_show;
2104         CustomData_set_layer(&me->edata, CD_MEDGE, me->medge);
2105
2106         /* XXX: DAG_object_flush_update(G.scene, OBACT, OB_RECALC_DATA); */
2107 }
2108
2109 static rcti sculptmode_pmv_box()
2110 {
2111         /*XXX:  short down[2], mouse[2];
2112         rcti ret;
2113
2114         getmouseco_areawin(down);
2115
2116         while((get_mbut()&L_MOUSE) || (get_mbut()&R_MOUSE)) {
2117                 getmouseco_areawin(mouse);
2118
2119                 scrarea_do_windraw(curarea);
2120
2121                 persp(PERSP_WIN);
2122                 glLineWidth(2);
2123                 setlinestyle(2);
2124                 sdrawXORline(down[0],down[1],mouse[0],down[1]);
2125                 sdrawXORline(mouse[0],down[1],mouse[0],mouse[1]);
2126                 sdrawXORline(mouse[0],mouse[1],down[0],mouse[1]);
2127                 sdrawXORline(down[0],mouse[1],down[0],down[1]);
2128                 setlinestyle(0);
2129                 glLineWidth(1);
2130                 persp(PERSP_VIEW);
2131
2132                 screen_swapbuffers();
2133                 backdrawview3d(0);
2134         }
2135
2136         ret.xmin= down[0]<mouse[0]?down[0]:mouse[0];
2137         ret.ymin= down[1]<mouse[1]?down[1]:mouse[1];
2138         ret.xmax= down[0]>mouse[0]?down[0]:mouse[0];
2139         ret.ymax= down[1]>mouse[1]?down[1]:mouse[1];
2140         return ret;*/
2141 }
2142
2143 void sculptmode_pmv(int mode)
2144 {
2145         Object *ob= NULL; /*XXX: OBACT; */
2146         rcti hb_2d;
2147         
2148         if(ob_get_key(ob)) {
2149                 error("Cannot hide mesh with shape keys enabled");
2150                 return;
2151         }
2152         
2153         hb_2d= sculptmode_pmv_box(); /* Get 2D hide box */
2154         
2155         sculptmode_correct_state();
2156
2157         waitcursor(1);
2158
2159         if(hb_2d.xmax-hb_2d.xmin > 3 && hb_2d.ymax-hb_2d.ymin > 3) {
2160                 init_sculptmatrices();
2161
2162                 sculptmode_do_pmv(ob,&hb_2d,mode);
2163         }
2164         else mesh_pmv_off(ob, get_mesh(ob));
2165
2166         /*XXX: scrarea_do_windraw(curarea); */
2167
2168         waitcursor(0);
2169 }
2170 #endif