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_mode_poll(bContext *C)
1196 {
1197         return G.f & G_SCULPTMODE;
1198 }
1199
1200 static int sculpt_poll(bContext *C)
1201 {
1202         return G.f & G_SCULPTMODE && CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
1203                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
1204 }
1205
1206 /*** Sculpt Cursor ***/
1207 static void draw_paint_cursor(bContext *C, int x, int y, void *customdata)
1208 {
1209         Sculpt *sd= CTX_data_tool_settings(C)->sculpt;
1210         
1211         glTranslatef((float)x, (float)y, 0.0f);
1212         
1213         glColor4ub(255, 100, 100, 128);
1214         glEnable( GL_LINE_SMOOTH );
1215         glEnable(GL_BLEND);
1216         glutil_draw_lined_arc(0.0, M_PI*2.0, sd->brush->size, 40);
1217         glDisable(GL_BLEND);
1218         glDisable( GL_LINE_SMOOTH );
1219         
1220         glTranslatef((float)-x, (float)-y, 0.0f);
1221 }
1222
1223 static void toggle_paint_cursor(bContext *C)
1224 {
1225         Sculpt *s = CTX_data_scene(C)->toolsettings->sculpt;
1226
1227         if(s->session->cursor) {
1228                 WM_paint_cursor_end(CTX_wm_manager(C), s->session->cursor);
1229                 s->session->cursor = NULL;
1230         }
1231         else {
1232                 s->session->cursor =
1233                         WM_paint_cursor_activate(CTX_wm_manager(C), sculpt_poll, draw_paint_cursor, NULL);
1234         }
1235 }
1236
1237 static void sculpt_undo_push(bContext *C, Sculpt *sd)
1238 {
1239         switch(sd->brush->sculpt_tool) {
1240         case SCULPT_TOOL_DRAW:
1241                 ED_undo_push(C, "Draw Brush"); break;
1242         case SCULPT_TOOL_SMOOTH:
1243                 ED_undo_push(C, "Smooth Brush"); break;
1244         case SCULPT_TOOL_PINCH:
1245                 ED_undo_push(C, "Pinch Brush"); break;
1246         case SCULPT_TOOL_INFLATE:
1247                 ED_undo_push(C, "Inflate Brush"); break;
1248         case SCULPT_TOOL_GRAB:
1249                 ED_undo_push(C, "Grab Brush"); break;
1250         case SCULPT_TOOL_LAYER:
1251                 ED_undo_push(C, "Layer Brush"); break;
1252         case SCULPT_TOOL_FLATTEN:
1253                 ED_undo_push(C, "Flatten Brush"); break;
1254         default:
1255                 ED_undo_push(C, "Sculpting"); break;
1256         }
1257 }
1258
1259 static int sculpt_brush_curve_preset_exec(bContext *C, wmOperator *op)
1260 {
1261         brush_curve_preset(CTX_data_scene(C)->toolsettings->sculpt->brush, RNA_enum_get(op->ptr, "mode"));
1262         return OPERATOR_FINISHED;
1263 }
1264
1265 static void SCULPT_OT_brush_curve_preset(wmOperatorType *ot)
1266 {
1267         static EnumPropertyItem prop_mode_items[] = {
1268                 {BRUSH_PRESET_SHARP, "SHARP", 0, "Sharp Curve", ""},
1269                 {BRUSH_PRESET_SMOOTH, "SMOOTH", 0, "Smooth Curve", ""},
1270                 {BRUSH_PRESET_MAX, "MAX", 0, "Max Curve", ""},
1271                 {0, NULL, 0, NULL, NULL}};
1272
1273         ot->name= "Preset";
1274         ot->idname= "SCULPT_OT_brush_curve_preset";
1275
1276         ot->exec= sculpt_brush_curve_preset_exec;
1277         ot->poll= sculpt_mode_poll;
1278
1279         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1280
1281         RNA_def_enum(ot->srna, "mode", prop_mode_items, BRUSH_PRESET_SHARP, "Mode", "");
1282 }
1283
1284 /**** Radial control ****/
1285 static int sculpt_radial_control_invoke(bContext *C, wmOperator *op, wmEvent *event)
1286 {
1287         toggle_paint_cursor(C);
1288         brush_radial_control_invoke(op, CTX_data_scene(C)->toolsettings->sculpt->brush, 1);
1289         return WM_radial_control_invoke(C, op, event);
1290 }
1291
1292 static int sculpt_radial_control_modal(bContext *C, wmOperator *op, wmEvent *event)
1293 {
1294         int ret = WM_radial_control_modal(C, op, event);
1295         if(ret != OPERATOR_RUNNING_MODAL)
1296                 toggle_paint_cursor(C);
1297         return ret;
1298 }
1299
1300 static int sculpt_radial_control_exec(bContext *C, wmOperator *op)
1301 {
1302         return brush_radial_control_exec(op, CTX_data_scene(C)->toolsettings->sculpt->brush, 1);
1303 }
1304
1305 static void SCULPT_OT_radial_control(wmOperatorType *ot)
1306 {
1307         WM_OT_radial_control_partial(ot);
1308
1309         ot->name= "Sculpt Radial Control";
1310         ot->idname= "SCULPT_OT_radial_control";
1311
1312         ot->invoke= sculpt_radial_control_invoke;
1313         ot->modal= sculpt_radial_control_modal;
1314         ot->exec= sculpt_radial_control_exec;
1315         ot->poll= sculpt_poll;
1316
1317         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1318 }
1319
1320 /**** Operator for applying a stroke (various attributes including mouse path)
1321       using the current brush. ****/
1322
1323 static float unproject_brush_radius(SculptSession *ss, float offset)
1324 {
1325         float brush_edge[3];
1326
1327         /* In anchored mode, brush size changes with mouse loc, otherwise it's fixed using the brush radius */
1328         unproject(ss->cache->mats, brush_edge, ss->cache->initial_mouse[0] + offset,
1329                   ss->cache->initial_mouse[1], ss->cache->depth);
1330
1331         return VecLenf(ss->cache->true_location, brush_edge);
1332 }
1333
1334 static void sculpt_cache_free(StrokeCache *cache)
1335 {
1336         if(cache->layer_disps)
1337                 MEM_freeN(cache->layer_disps);
1338         if(cache->mesh_store)
1339                 MEM_freeN(cache->mesh_store);
1340         if(cache->orig_norms)
1341                 MEM_freeN(cache->orig_norms);
1342         if(cache->mats)
1343                 MEM_freeN(cache->mats);
1344         MEM_freeN(cache);
1345 }
1346
1347 /* Initialize the stroke cache invariants from operator properties */
1348 static void sculpt_update_cache_invariants(Sculpt *sd, bContext *C, wmOperator *op)
1349 {
1350         StrokeCache *cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
1351         int i;
1352
1353         sd->session->cache = cache;
1354
1355         RNA_float_get_array(op->ptr, "scale", cache->scale);
1356         cache->flag = RNA_int_get(op->ptr, "flag");
1357         RNA_float_get_array(op->ptr, "clip_tolerance", cache->clip_tolerance);
1358         RNA_int_get_array(op->ptr, "initial_mouse", cache->initial_mouse);
1359         cache->depth = RNA_float_get(op->ptr, "depth");
1360
1361         /* Truly temporary data that isn't stored in properties */
1362
1363         view3d_set_viewcontext(C, &cache->vc);
1364
1365         cache->mats = MEM_callocN(sizeof(bglMats), "sculpt bglMats");
1366         view3d_get_transformation(&cache->vc, cache->vc.obact, cache->mats);
1367
1368         sculpt_update_mesh_elements(C);
1369
1370         /* Make copies of the mesh vertex locations and normals for some tools */
1371         if(sd->brush->sculpt_tool == SCULPT_TOOL_LAYER || (sd->brush->flag & BRUSH_ANCHORED)) {
1372                 cache->layer_disps = MEM_callocN(sizeof(float) * sd->session->totvert, "layer brush displacements");
1373                 cache->mesh_store= MEM_mallocN(sizeof(float) * 3 * sd->session->totvert, "sculpt mesh vertices copy");
1374                 for(i = 0; i < sd->session->totvert; ++i)
1375                         VecCopyf(cache->mesh_store[i], sd->session->mvert[i].co);
1376
1377                 if(sd->brush->flag & BRUSH_ANCHORED) {
1378                         cache->orig_norms= MEM_mallocN(sizeof(short) * 3 * sd->session->totvert, "Sculpt orig norm");
1379                         for(i = 0; i < sd->session->totvert; ++i) {
1380                                 cache->orig_norms[i][0] = sd->session->mvert[i].no[0];
1381                                 cache->orig_norms[i][1] = sd->session->mvert[i].no[1];
1382                                 cache->orig_norms[i][2] = sd->session->mvert[i].no[2];
1383                         }
1384                 }
1385         }
1386
1387         unproject(cache->mats, cache->true_location, cache->initial_mouse[0], cache->initial_mouse[1], cache->depth);
1388         cache->radius = unproject_brush_radius(sd->session, brush_size(sd));
1389         cache->rotation = 0;
1390         cache->first_time = 1;
1391 }
1392
1393 /* Initialize the stroke cache variants from operator properties */
1394 static void sculpt_update_cache_variants(Sculpt *sd, PointerRNA *ptr)
1395 {
1396         StrokeCache *cache = sd->session->cache;
1397         float grab_location[3];
1398         int dx, dy;
1399
1400         if(!(sd->brush->flag & BRUSH_ANCHORED))
1401                 RNA_float_get_array(ptr, "location", cache->true_location);
1402         cache->flip = RNA_boolean_get(ptr, "flip");
1403         RNA_int_get_array(ptr, "mouse", cache->mouse);
1404         
1405         /* Truly temporary data that isn't stored in properties */
1406
1407         cache->previous_pixel_radius = cache->pixel_radius;
1408         cache->pixel_radius = brush_size(sd);
1409
1410         if(sd->brush->flag & BRUSH_ANCHORED) {
1411                 dx = cache->mouse[0] - cache->initial_mouse[0];
1412                 dy = cache->mouse[1] - cache->initial_mouse[1];
1413                 cache->pixel_radius = sqrt(dx*dx + dy*dy);
1414                 cache->radius = unproject_brush_radius(sd->session, cache->pixel_radius);
1415                 cache->rotation = atan2(dy, dx);
1416         }
1417         else if(sd->brush->flag & BRUSH_RAKE) {
1418                 int update;
1419
1420                 dx = cache->last_rake[0] - cache->mouse[0];
1421                 dy = cache->last_rake[1] - cache->mouse[1];
1422
1423                 update = dx*dx + dy*dy > 100;
1424
1425                 /* To prevent jitter, only update the angle if the mouse has moved over 10 pixels */
1426                 if(update && !cache->first_time)
1427                         cache->rotation = M_PI_2 + atan2(dy, dx);
1428
1429                 if(update || cache->first_time) {
1430                         cache->last_rake[0] = cache->mouse[0];
1431                         cache->last_rake[1] = cache->mouse[1];
1432                 }
1433         }
1434
1435         /* Find the grab delta */
1436         if(sd->brush->sculpt_tool == SCULPT_TOOL_GRAB) {
1437                 unproject(cache->mats, grab_location, cache->mouse[0], cache->mouse[1], cache->depth);
1438                 if(!cache->first_time)
1439                         VecSubf(cache->grab_delta, grab_location, cache->old_grab_location);
1440                 VecCopyf(cache->old_grab_location, grab_location);
1441         }
1442 }
1443
1444 /* Initialize stroke operator properties */
1445 static void sculpt_brush_stroke_init_properties(bContext *C, wmOperator *op, wmEvent *event, SculptSession *ss)
1446 {
1447         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1448         Object *ob= CTX_data_active_object(C);
1449         ModifierData *md;
1450         ViewContext vc;
1451         float scale[3], clip_tolerance[3] = {0,0,0};
1452         int mouse[2], flag = 0;
1453
1454         /* Set scaling adjustment */
1455         scale[0] = 1.0f / ob->size[0];
1456         scale[1] = 1.0f / ob->size[1];
1457         scale[2] = 1.0f / ob->size[2];
1458         RNA_float_set_array(op->ptr, "scale", scale);
1459
1460         /* Initialize mirror modifier clipping */
1461         for(md= ob->modifiers.first; md; md= md->next) {
1462                 if(md->type==eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
1463                         const MirrorModifierData *mmd = (MirrorModifierData*) md;
1464                         
1465                         /* Mark each axis that needs clipping along with its tolerance */
1466                         if(mmd->flag & MOD_MIR_CLIPPING) {
1467                                 flag |= CLIP_X << mmd->axis;
1468                                 if(mmd->tolerance > clip_tolerance[mmd->axis])
1469                                         clip_tolerance[mmd->axis] = mmd->tolerance;
1470                         }
1471                 }
1472         }
1473         RNA_int_set(op->ptr, "flag", flag);
1474         RNA_float_set_array(op->ptr, "clip_tolerance", clip_tolerance);
1475
1476         /* Initial mouse location */
1477         mouse[0] = event->x;
1478         mouse[1] = event->y;
1479         RNA_int_set_array(op->ptr, "initial_mouse", mouse);
1480
1481         /* Initial screen depth under the mouse */
1482         view3d_set_viewcontext(C, &vc);
1483         RNA_float_set(op->ptr, "depth", read_cached_depth(&vc, event->x, event->y));
1484
1485         sculpt_update_cache_invariants(sd, C, op);
1486 }
1487
1488 static int sculpt_brush_stroke_invoke(bContext *C, wmOperator *op, wmEvent *event)
1489 {
1490         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1491
1492         view3d_operator_needs_opengl(C);
1493         sculpt_brush_stroke_init_properties(C, op, event, sd->session);
1494
1495         sculptmode_update_all_projverts(sd->session);
1496
1497         /* TODO: Shouldn't really have to do this at the start of every
1498            stroke, but sculpt would need some sort of notification when
1499            changes are made to the texture. */
1500         sculpt_update_tex(sd);
1501
1502         /* add modal handler */
1503         WM_event_add_modal_handler(C, &CTX_wm_window(C)->handlers, op);
1504         
1505         return OPERATOR_RUNNING_MODAL;
1506 }
1507
1508 static void sculpt_restore_mesh(Sculpt *sd)
1509 {
1510         StrokeCache *cache = sd->session->cache;
1511         int i;
1512         
1513         /* Restore the mesh before continuing with anchored stroke */
1514         if((sd->brush->flag & BRUSH_ANCHORED) && cache->mesh_store) {
1515                 for(i = 0; i < sd->session->totvert; ++i) {
1516                         VecCopyf(sd->session->mvert[i].co, cache->mesh_store[i]);
1517                         sd->session->mvert[i].no[0] = cache->orig_norms[i][0];
1518                         sd->session->mvert[i].no[1] = cache->orig_norms[i][1];
1519                         sd->session->mvert[i].no[2] = cache->orig_norms[i][2];
1520                 }
1521         }
1522 }
1523
1524 static void sculpt_post_stroke_free(SculptSession *ss)
1525 {
1526         BLI_freelistN(&ss->damaged_rects);
1527         BLI_freelistN(&ss->damaged_verts);
1528 }
1529
1530 static void sculpt_flush_update(bContext *C)
1531 {
1532         Sculpt *s = CTX_data_tool_settings(C)->sculpt;
1533         ARegion *ar = CTX_wm_region(C);
1534         MultiresModifierData *mmd = s->session->multires;
1535
1536         calc_damaged_verts(s->session);
1537
1538         if(mmd) {
1539                 if(mmd->undo_verts && mmd->undo_verts != s->session->mvert)
1540                         MEM_freeN(mmd->undo_verts);
1541                 
1542                 mmd->undo_verts = s->session->mvert;
1543                 mmd->undo_verts_tot = s->session->totvert;
1544                 multires_mark_as_modified(CTX_data_active_object(C));
1545         }
1546
1547         ED_region_tag_redraw(ar);
1548 }
1549
1550 static int sculpt_brush_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
1551 {
1552         PointerRNA itemptr;
1553         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1554         float center[3];
1555         int mouse[2] = {event->x, event->y};
1556
1557         sculpt_update_mesh_elements(C);
1558
1559         unproject(sd->session->cache->mats, center, event->x, event->y,
1560                   read_cached_depth(&sd->session->cache->vc, event->x, event->y));
1561
1562         /* Add to stroke */
1563         RNA_collection_add(op->ptr, "stroke", &itemptr);
1564         RNA_float_set_array(&itemptr, "location", center);
1565         RNA_int_set_array(&itemptr, "mouse", mouse);
1566         RNA_boolean_set(&itemptr, "flip", event->shift);
1567         sculpt_update_cache_variants(sd, &itemptr);
1568
1569         sculpt_restore_mesh(sd);
1570         do_symmetrical_brush_actions(CTX_data_tool_settings(C)->sculpt, sd->session->cache);
1571
1572         sculpt_flush_update(C);
1573         sculpt_post_stroke_free(sd->session);
1574
1575         /* Finished */
1576         if(event->type == LEFTMOUSE && event->val == 0) {
1577                 request_depth_update(sd->session->cache->vc.rv3d);
1578
1579                 sculpt_cache_free(sd->session->cache);
1580
1581                 sculpt_undo_push(C, sd);
1582
1583                 return OPERATOR_FINISHED;
1584         }
1585
1586         return OPERATOR_RUNNING_MODAL;
1587 }
1588
1589 static int sculpt_brush_stroke_exec(bContext *C, wmOperator *op)
1590 {
1591         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
1592
1593         view3d_operator_needs_opengl(C);
1594         sculpt_update_cache_invariants(sd, C, op);
1595         sculptmode_update_all_projverts(sd->session);
1596         sculpt_update_tex(sd);
1597
1598         RNA_BEGIN(op->ptr, itemptr, "stroke") {
1599                 sculpt_update_cache_variants(sd, &itemptr);
1600
1601                 sculpt_restore_mesh(sd);
1602                 do_symmetrical_brush_actions(sd, sd->session->cache);
1603
1604                 sculpt_post_stroke_free(sd->session);
1605         }
1606         RNA_END;
1607
1608         sculpt_flush_update(C);
1609         sculpt_cache_free(sd->session->cache);
1610
1611         sculpt_undo_push(C, sd);
1612
1613         return OPERATOR_FINISHED;
1614 }
1615
1616 static void SCULPT_OT_brush_stroke(wmOperatorType *ot)
1617 {
1618         ot->flag |= OPTYPE_REGISTER;
1619
1620         /* identifiers */
1621         ot->name= "Sculpt Mode";
1622         ot->idname= "SCULPT_OT_brush_stroke";
1623         
1624         /* api callbacks */
1625         ot->invoke= sculpt_brush_stroke_invoke;
1626         ot->modal= sculpt_brush_stroke_modal;
1627         ot->exec= sculpt_brush_stroke_exec;
1628         ot->poll= sculpt_poll;
1629         
1630         /* flags (sculpt does own undo? (ton) */
1631         ot->flag= OPTYPE_REGISTER;
1632
1633         /* properties */
1634         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1635
1636         /* If the object has a scaling factor, brushes also need to be scaled
1637            to work as expected. */
1638         RNA_def_float_vector(ot->srna, "scale", 3, NULL, 0.0f, FLT_MAX, "Scale", "", 0.0f, 1000.0f);
1639
1640         RNA_def_int(ot->srna, "flag", 0, 0, INT_MAX, "flag", "", 0, INT_MAX);
1641
1642         /* For mirror modifiers */
1643         RNA_def_float_vector(ot->srna, "clip_tolerance", 3, NULL, 0.0f, FLT_MAX, "clip_tolerance", "", 0.0f, 1000.0f);
1644
1645         /* The initial 2D location of the mouse */
1646         RNA_def_int_vector(ot->srna, "initial_mouse", 2, NULL, INT_MIN, INT_MAX, "initial_mouse", "", INT_MIN, INT_MAX);
1647
1648         /* The initial screen depth of the mouse */
1649         RNA_def_float(ot->srna, "depth", 0.0f, 0.0f, FLT_MAX, "depth", "", 0.0f, FLT_MAX);
1650 }
1651
1652 /**** Toggle operator for turning sculpt mode on or off ****/
1653
1654 static int sculpt_toggle_mode(bContext *C, wmOperator *op)
1655 {
1656         ToolSettings *ts = CTX_data_tool_settings(C);
1657
1658         if(G.f & G_SCULPTMODE) {
1659                 multires_force_update(CTX_data_active_object(C));
1660
1661                 /* Leave sculptmode */
1662                 G.f &= ~G_SCULPTMODE;
1663
1664                 toggle_paint_cursor(C);
1665
1666                 sculptsession_free(ts->sculpt);
1667         }
1668         else {
1669                 MTex *mtex; // XXX: temporary
1670
1671                 /* Enter sculptmode */
1672
1673                 G.f |= G_SCULPTMODE;
1674                 
1675                 /* Create persistent sculpt mode data */
1676                 if(!ts->sculpt)
1677                         ts->sculpt = MEM_callocN(sizeof(Sculpt), "sculpt mode data");
1678
1679                 /* Create sculpt mode session data */
1680                 if(ts->sculpt->session)
1681                         MEM_freeN(ts->sculpt->session);
1682                 ts->sculpt->session = MEM_callocN(sizeof(SculptSession), "sculpt session");
1683
1684                 toggle_paint_cursor(C);
1685
1686                 /* If there's no brush, create one */
1687                 brush_check_exists(&ts->sculpt->brush);
1688
1689                 /* XXX: testing: set the brush texture to the first available one */
1690                 if(G.main->tex.first) {
1691                         Tex *tex = G.main->tex.first;
1692                         if(tex->type) {
1693                                 mtex = MEM_callocN(sizeof(MTex), "test mtex");
1694                                 ts->sculpt->brush->texact = 0;
1695                                 ts->sculpt->brush->mtex[0] = mtex;
1696                                 mtex->tex = tex;
1697                                 mtex->size[0] = mtex->size[1] = mtex->size[2] = 50;
1698                         }
1699                 }
1700         }
1701
1702         return OPERATOR_FINISHED;
1703 }
1704
1705 static void SCULPT_OT_sculptmode_toggle(wmOperatorType *ot)
1706 {
1707         /* identifiers */
1708         ot->name= "Sculpt Mode";
1709         ot->idname= "SCULPT_OT_sculptmode_toggle";
1710         
1711         /* api callbacks */
1712         ot->exec= sculpt_toggle_mode;
1713         ot->poll= ED_operator_object_active;
1714         
1715         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO;
1716 }
1717
1718 void ED_operatortypes_sculpt()
1719 {
1720         WM_operatortype_append(SCULPT_OT_radial_control);
1721         WM_operatortype_append(SCULPT_OT_brush_stroke);
1722         WM_operatortype_append(SCULPT_OT_sculptmode_toggle);
1723         WM_operatortype_append(SCULPT_OT_brush_curve_preset);
1724 }
1725
1726 void sculpt(Sculpt *sd)
1727 {
1728 #if 0
1729         SculptSession *ss= sd->session;
1730         Object *ob= NULL; /*XXX */
1731         Mesh *me;
1732         MultiresModifierData *mmd = NULL;
1733         /* lastSigMouse is for the rake, to store the last place the mouse movement was significant */
1734         short mouse[2], mvalo[2], lastSigMouse[2],firsttime=1, mousebut;
1735         short modifier_calculations= 0;
1736         BrushAction *a = MEM_callocN(sizeof(BrushAction), "brush action");
1737         short spacing= 32000;
1738         int scissor_box[4];
1739         float offsetRot;
1740         int smooth_stroke = 0, i;
1741         int anchored, rake = 0 /* XXX: rake = ? */;
1742
1743         /* XXX: checking that sculpting is allowed
1744         if(!(G.f & G_SCULPTMODE) || G.obedit || !ob || ob->id.lib || !get_mesh(ob) || (get_mesh(ob)->totface == 0))
1745                 return;
1746         if(!(ob->lay & G.vd->lay))
1747                 error("Active object is not in this layer");
1748         if(ob_get_keyblock(ob)) {
1749                 if(!(ob->shapeflag & OB_SHAPE_LOCK)) {
1750                         error("Cannot sculpt on unlocked shape key");
1751                         return;
1752                 }
1753         }*/
1754         
1755         anchored = sd->brush->flag & BRUSH_ANCHORED;
1756         smooth_stroke = (sd->flags & SCULPT_INPUT_SMOOTH) && (sd->brush->sculpt_tool != SCULPT_TOOL_GRAB) && !anchored;
1757
1758         if(smooth_stroke)
1759                 sculpt_stroke_new(256);
1760
1761         ss->damaged_rects.first = ss->damaged_rects.last = NULL;
1762         ss->damaged_verts.first = ss->damaged_verts.last = NULL;
1763         ss->vertexcosnos = NULL;
1764
1765         mmd = sculpt_multires_active(ob);
1766
1767         /* Check that vertex users are up-to-date */
1768         if(ob != active_ob || !ss->vertex_users || ss->vertex_users_size != cache->totvert) {
1769                 sculpt_vertexusers_free(ss);
1770                 calc_vertex_users(ss);
1771                 if(ss->projverts)
1772                         MEM_freeN(ss->projverts);
1773                 ss->projverts = NULL;
1774                 active_ob= ob;
1775         }
1776                 
1777         glEnableClientState(GL_VERTEX_ARRAY);
1778         glEnableClientState(GL_NORMAL_ARRAY);
1779
1780         /*XXX:
1781         persp(PERSP_VIEW);
1782         getmouseco_areawin(mvalo);*/
1783
1784         /* Init texture
1785            FIXME: Shouldn't be doing this every time! */
1786         if(sd->tex_mode!=SCULPTREPT_3D)
1787                 sculptmode_update_tex(sd);
1788
1789         /*XXX: getmouseco_areawin(mouse); */
1790         mvalo[0]= mouse[0];
1791         mvalo[1]= mouse[1];
1792         lastSigMouse[0]=mouse[0];
1793         lastSigMouse[1]=mouse[1];
1794         mousebut = 0; /* XXX: L_MOUSE; */
1795
1796         /* If modifier_calculations is true, then extra time must be spent
1797            updating the mesh. This takes a *lot* longer, so it's worth
1798            skipping if the modifier stack is empty. */
1799         modifier_calculations= sculpt_modifiers_active(ob);
1800
1801         if(modifier_calculations)
1802                 ss->vertexcosnos= mesh_get_mapped_verts_nors(NULL, ob); /* XXX: scene = ? */
1803         sculptmode_update_all_projverts(ss);
1804
1805         /* Capture original copy */
1806         if(sd->flags & SCULPT_DRAW_FAST)
1807                 glAccum(GL_LOAD, 1);
1808
1809         /* Get original scissor box */
1810         glGetIntegerv(GL_SCISSOR_BOX, scissor_box);
1811         
1812         /* For raking, get the original angle*/
1813         offsetRot=sculpt_tex_angle(sd);
1814
1815         me = get_mesh(ob);
1816
1817         while (/*XXX:get_mbut() & mousebut*/0) {
1818                 /* XXX: getmouseco_areawin(mouse); */
1819                 /* If rake, and the mouse has moved over 10 pixels (euclidean) (prevents jitter) then get the new angle */
1820                 if (rake && (pow(lastSigMouse[0]-mouse[0],2)+pow(lastSigMouse[1]-mouse[1],2))>100){
1821                         /*Nasty looking, but just orig + new angle really*/
1822                         set_tex_angle(sd, offsetRot+180.+to_deg(atan2((float)(mouse[1]-lastSigMouse[1]),(float)(mouse[0]-lastSigMouse[0]))));
1823                         lastSigMouse[0]=mouse[0];
1824                         lastSigMouse[1]=mouse[1];
1825                 }
1826                 
1827                 if(firsttime || mouse[0]!=mvalo[0] || mouse[1]!=mvalo[1] ||
1828                    sd->brush->flag & BRUSH_AIRBRUSH) {
1829                         a->firsttime = firsttime;
1830                         firsttime= 0;
1831
1832                         if(smooth_stroke)
1833                                 sculpt_stroke_add_point(ss->stroke, mouse[0], mouse[1]);
1834
1835                         spacing+= sqrt(pow(mvalo[0]-mouse[0],2)+pow(mvalo[1]-mouse[1],2));
1836
1837                         if(modifier_calculations && !ss->vertexcosnos)
1838                                 ss->vertexcosnos= mesh_get_mapped_verts_nors(NULL, ob); /*XXX scene = ? */
1839
1840                         if(sd->brush->sculpt_tool != SCULPT_TOOL_GRAB) {
1841                                 if(anchored) {
1842                                         /* Restore the mesh before continuing with anchored stroke */
1843                                         /*if(a->mesh_store) {
1844                                                 for(i = 0; i < cache->totvert; ++i) {
1845                                                         VecCopyf(cache->mvert[i].co, &a->mesh_store[i].x);
1846                                                         cache->mvert[i].no[0] = a->orig_norms[i][0];
1847                                                         cache->mvert[i].no[1] = a->orig_norms[i][1];
1848                                                         cache->mvert[i].no[2] = a->orig_norms[i][2];
1849                                                 }
1850                                                 }*/
1851                                         
1852                                         //do_symmetrical_brush_actions(sd, a, mouse, NULL);
1853                                 }
1854                                 else {
1855                                         if(smooth_stroke) {
1856                                                 sculpt_stroke_apply(sd, ss->stroke);
1857                                         }
1858                                         else if(sd->spacing==0 || spacing>sd->spacing) {
1859                                                 //do_symmetrical_brush_actions(sd, a, mouse, NULL);
1860                                                 spacing= 0;
1861                                         }
1862                                 }
1863                         }
1864                         else {
1865                                 //do_symmetrical_brush_actions(sd, a, mouse, mvalo);
1866                                 //unproject(ss, sd->pivot, mouse[0], mouse[1], a->depth);
1867                         }
1868
1869                         if((!ss->multires && modifier_calculations) || ob_get_keyblock(ob)) {
1870                                 /* XXX: DAG_object_flush_update(G.scene, ob, OB_RECALC_DATA); */ }
1871
1872                         if(modifier_calculations || sd->brush->sculpt_tool == SCULPT_TOOL_GRAB || !(sd->flags & SCULPT_DRAW_FAST)) {
1873                                 calc_damaged_verts(ss, a);
1874                                 /*XXX: scrarea_do_windraw(curarea);
1875                                 screen_swapbuffers(); */
1876                         } else { /* Optimized drawing */
1877                                 calc_damaged_verts(ss, a);
1878
1879                                 /* Draw the stored image to the screen */
1880                                 glAccum(GL_RETURN, 1);
1881
1882                                 sculpt_clear_damaged_areas(ss);
1883                                 
1884                                 /* Draw all the polygons that are inside the modified area(s) */
1885                                 glScissor(scissor_box[0], scissor_box[1], scissor_box[2], scissor_box[3]);
1886                                 /* XXX: sculptmode_draw_mesh(1); */
1887                                 glAccum(GL_LOAD, 1);
1888
1889                                 projverts_clear_inside(ss);
1890
1891                                 /* XXX: persp(PERSP_WIN); */
1892                                 glDisable(GL_DEPTH_TEST);
1893                                 
1894                                 /* Draw cursor */
1895                                 if(sd->flags & SCULPT_TOOL_DRAW)
1896                                         fdrawXORcirc((float)mouse[0],(float)mouse[1],sd->brush->size);
1897                                 /* XXX: if(smooth_stroke)
1898                                    sculpt_stroke_draw();
1899                                 
1900                                 myswapbuffers(); */
1901                         }
1902
1903                         BLI_freelistN(&ss->damaged_rects);
1904                         ss->damaged_rects.first = ss->damaged_rects.last = NULL;
1905         
1906                         mvalo[0]= mouse[0];
1907                         mvalo[1]= mouse[1];
1908
1909                         if(ss->vertexcosnos) {
1910                                 MEM_freeN(ss->vertexcosnos);
1911                                 ss->vertexcosnos= NULL;
1912                         }
1913
1914                 }
1915                 else { /*XXX:BIF_wait_for_statechange();*/ }
1916         }
1917
1918         /* Set the rotation of the brush back to what it was before any rake */
1919         set_tex_angle(sd, offsetRot);
1920         
1921         if(smooth_stroke) {
1922                 sculpt_stroke_apply_all(sd, ss->stroke);
1923                 calc_damaged_verts(ss, a);
1924                 BLI_freelistN(&ss->damaged_rects);
1925         }
1926
1927         //if(a->layer_disps) MEM_freeN(a->layer_disps);
1928         //if(a->mesh_store) MEM_freeN(a->mesh_store);
1929         //if(a->orig_norms) MEM_freeN(a->orig_norms);
1930         for(i=0; i<8; ++i)
1931                 BLI_freelistN(&a->grab_active_verts[i]);
1932         MEM_freeN(a);
1933         sculpt_stroke_free(ss->stroke);
1934         ss->stroke = NULL;
1935
1936         if(mmd) {
1937                 if(mmd->undo_verts && mmd->undo_verts != cache->mvert)
1938                         MEM_freeN(mmd->undo_verts);
1939                 
1940                 mmd->undo_verts = cache->mvert;
1941                 mmd->undo_verts_tot = cache->totvert;
1942         }
1943
1944         //sculpt_undo_push(sd);
1945
1946         /* XXX: if(G.vd->depths) G.vd->depths->damaged= 1;
1947            allqueue(REDRAWVIEW3D, 0); */
1948 #endif
1949 }
1950
1951 /* Partial Mesh Visibility */
1952
1953 /* XXX: Partial vis. always was a mess, have to figure something out */
1954 #if 0
1955 /* mode: 0=hide outside selection, 1=hide inside selection */
1956 static void sculptmode_do_pmv(Object *ob, rcti *hb_2d, int mode)
1957 {
1958         Mesh *me= get_mesh(ob);
1959         float hidebox[6][3];
1960         vec3f plane_normals[4];
1961         float plane_ds[4];
1962         unsigned i, j;
1963         unsigned ndx_show, ndx_hide;
1964         MVert *nve;
1965         unsigned face_cnt_show= 0, face_ndx_show= 0;
1966         unsigned edge_cnt_show= 0, edge_ndx_show= 0;
1967         unsigned *old_map= NULL;
1968         const unsigned SHOW= 0, HIDE=1;
1969
1970         /* Convert hide box from 2D to 3D */
1971         unproject(hidebox[0], hb_2d->xmin, hb_2d->ymax, 1);
1972         unproject(hidebox[1], hb_2d->xmax, hb_2d->ymax, 1);
1973         unproject(hidebox[2], hb_2d->xmax, hb_2d->ymin, 1);
1974         unproject(hidebox[3], hb_2d->xmin, hb_2d->ymin, 1);
1975         unproject(hidebox[4], hb_2d->xmin, hb_2d->ymax, 0);
1976         unproject(hidebox[5], hb_2d->xmax, hb_2d->ymin, 0);
1977         
1978         /* Calculate normals for each side of hide box */
1979         CalcNormFloat(hidebox[0], hidebox[1], hidebox[4], &plane_normals[0].x);
1980         CalcNormFloat(hidebox[1], hidebox[2], hidebox[5], &plane_normals[1].x);
1981         CalcNormFloat(hidebox[2], hidebox[3], hidebox[5], &plane_normals[2].x);
1982         CalcNormFloat(hidebox[3], hidebox[0], hidebox[4], &plane_normals[3].x);
1983         
1984         /* Calculate D for each side of hide box */
1985         for(i= 0; i<4; ++i)
1986                 plane_ds[i]= hidebox[i][0]*plane_normals[i].x + hidebox[i][1]*plane_normals[i].y +
1987                         hidebox[i][2]*plane_normals[i].z;
1988         
1989         /* Add partial visibility to mesh */
1990         if(!me->pv) {
1991                 me->pv= MEM_callocN(sizeof(PartialVisibility),"PartialVisibility");
1992         } else {
1993                 old_map= MEM_callocN(sizeof(unsigned)*me->pv->totvert,"PMV oldmap");
1994                 for(i=0; i<me->pv->totvert; ++i) {
1995                         old_map[i]= me->pv->vert_map[i]<me->totvert?0:1;
1996                 }
1997                 mesh_pmv_revert(ob, me);
1998         }
1999         
2000         /* Kill sculpt data */
2001         active_ob= NULL;
2002         
2003         /* Initalize map with which verts are to be hidden */
2004         me->pv->vert_map= MEM_mallocN(sizeof(unsigned)*me->totvert, "PMV vertmap");
2005         me->pv->totvert= me->totvert;
2006         me->totvert= 0;
2007         for(i=0; i<me->pv->totvert; ++i) {
2008                 me->pv->vert_map[i]= mode ? HIDE:SHOW;
2009                 for(j=0; j<4; ++j) {
2010                         if(me->mvert[i].co[0] * plane_normals[j].x +
2011                            me->mvert[i].co[1] * plane_normals[j].y +
2012                            me->mvert[i].co[2] * plane_normals[j].z < plane_ds[j] ) {
2013                                 me->pv->vert_map[i]= mode ? SHOW:HIDE; /* Vert is outside the hide box */
2014                                 break;
2015                         }
2016                 }
2017                 if(old_map && old_map[i]) me->pv->vert_map[i]= 1;
2018                 if(!me->pv->vert_map[i]) ++me->totvert;
2019
2020         }
2021         if(old_map) MEM_freeN(old_map);
2022
2023         /* Find out how many faces to show */
2024         for(i=0; i<me->totface; ++i) {
2025                 if(!me->pv->vert_map[me->mface[i].v1] &&
2026                    !me->pv->vert_map[me->mface[i].v2] &&
2027                    !me->pv->vert_map[me->mface[i].v3]) {
2028                         if(me->mface[i].v4) {
2029                                 if(!me->pv->vert_map[me->mface[i].v4])
2030                                         ++face_cnt_show;
2031                         }
2032                         else ++face_cnt_show;
2033                 }
2034         }
2035         /* Find out how many edges to show */
2036         for(i=0; i<me->totedge; ++i) {
2037                 if(!me->pv->vert_map[me->medge[i].v1] &&
2038                    !me->pv->vert_map[me->medge[i].v2])
2039                         ++edge_cnt_show;
2040         }
2041
2042         /* Create new vert array and reset each vert's map with map[old]=new index */
2043         nve= MEM_mallocN(sizeof(MVert)*me->pv->totvert, "PMV verts");
2044         ndx_show= 0; ndx_hide= me->totvert;
2045         for(i=0; i<me->pv->totvert; ++i) {
2046                 if(me->pv->vert_map[i]) {
2047                         me->pv->vert_map[i]= ndx_hide;
2048                         nve[me->pv->vert_map[i]]= me->mvert[i];
2049                         ++ndx_hide;
2050                 } else {
2051                         me->pv->vert_map[i]= ndx_show;
2052                         nve[me->pv->vert_map[i]]= me->mvert[i];
2053                         ++ndx_show;
2054                 }
2055         }
2056         CustomData_free_layer_active(&me->vdata, CD_MVERT, me->pv->totvert);
2057         me->mvert= CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, nve, me->totvert);
2058
2059         /* Create new face array */
2060         me->pv->old_faces= me->mface;
2061         me->pv->totface= me->totface;
2062         me->mface= MEM_mallocN(sizeof(MFace)*face_cnt_show, "PMV faces");
2063         for(i=0; i<me->totface; ++i) {
2064                 MFace *pr_f= &me->pv->old_faces[i];
2065                 char show= 0;
2066
2067                 if(me->pv->vert_map[pr_f->v1] < me->totvert &&
2068                    me->pv->vert_map[pr_f->v2] < me->totvert &&
2069                    me->pv->vert_map[pr_f->v3] < me->totvert) {
2070                         if(pr_f->v4) {
2071                                 if(me->pv->vert_map[pr_f->v4] < me->totvert)
2072                                         show= 1;
2073                         }
2074                         else show= 1;
2075                 }
2076
2077                 if(show) {
2078                         MFace *cr_f= &me->mface[face_ndx_show];
2079                         *cr_f= *pr_f;
2080                         cr_f->v1= me->pv->vert_map[pr_f->v1];
2081                         cr_f->v2= me->pv->vert_map[pr_f->v2];
2082                         cr_f->v3= me->pv->vert_map[pr_f->v3];
2083                         cr_f->v4= pr_f->v4 ? me->pv->vert_map[pr_f->v4] : 0;
2084                         test_index_face(cr_f,NULL,0,pr_f->v4?4:3);
2085                         ++face_ndx_show;
2086                 }
2087         }
2088         me->totface= face_cnt_show;
2089         CustomData_set_layer(&me->fdata, CD_MFACE, me->mface);
2090
2091         /* Create new edge array */
2092         me->pv->old_edges= me->medge;
2093         me->pv->totedge= me->totedge;
2094         me->medge= MEM_mallocN(sizeof(MEdge)*edge_cnt_show, "PMV edges");
2095         me->pv->edge_map= MEM_mallocN(sizeof(int)*me->pv->totedge,"PMV edgemap");
2096         for(i=0; i<me->totedge; ++i) {
2097                 if(me->pv->vert_map[me->pv->old_edges[i].v1] < me->totvert &&
2098                    me->pv->vert_map[me->pv->old_edges[i].v2] < me->totvert) {
2099                         MEdge *cr_e= &me->medge[edge_ndx_show];
2100                         me->pv->edge_map[i]= edge_ndx_show;
2101                         *cr_e= me->pv->old_edges[i];
2102                         cr_e->v1= me->pv->vert_map[me->pv->old_edges[i].v1];
2103                         cr_e->v2= me->pv->vert_map[me->pv->old_edges[i].v2];
2104                         ++edge_ndx_show;
2105                 }
2106                 else me->pv->edge_map[i]= -1;
2107         }
2108         me->totedge= edge_cnt_show;
2109         CustomData_set_layer(&me->edata, CD_MEDGE, me->medge);
2110
2111         /* XXX: DAG_object_flush_update(G.scene, OBACT, OB_RECALC_DATA); */
2112 }
2113
2114 static rcti sculptmode_pmv_box()
2115 {
2116         /*XXX:  short down[2], mouse[2];
2117         rcti ret;
2118
2119         getmouseco_areawin(down);
2120
2121         while((get_mbut()&L_MOUSE) || (get_mbut()&R_MOUSE)) {
2122                 getmouseco_areawin(mouse);
2123
2124                 scrarea_do_windraw(curarea);
2125
2126                 persp(PERSP_WIN);
2127                 glLineWidth(2);
2128                 setlinestyle(2);
2129                 sdrawXORline(down[0],down[1],mouse[0],down[1]);
2130                 sdrawXORline(mouse[0],down[1],mouse[0],mouse[1]);
2131                 sdrawXORline(mouse[0],mouse[1],down[0],mouse[1]);
2132                 sdrawXORline(down[0],mouse[1],down[0],down[1]);
2133                 setlinestyle(0);
2134                 glLineWidth(1);
2135                 persp(PERSP_VIEW);
2136
2137                 screen_swapbuffers();
2138                 backdrawview3d(0);
2139         }
2140
2141         ret.xmin= down[0]<mouse[0]?down[0]:mouse[0];
2142         ret.ymin= down[1]<mouse[1]?down[1]:mouse[1];
2143         ret.xmax= down[0]>mouse[0]?down[0]:mouse[0];
2144         ret.ymax= down[1]>mouse[1]?down[1]:mouse[1];
2145         return ret;*/
2146 }
2147
2148 void sculptmode_pmv(int mode)
2149 {
2150         Object *ob= NULL; /*XXX: OBACT; */
2151         rcti hb_2d;
2152         
2153         if(ob_get_key(ob)) {
2154                 error("Cannot hide mesh with shape keys enabled");
2155                 return;
2156         }
2157         
2158         hb_2d= sculptmode_pmv_box(); /* Get 2D hide box */
2159         
2160         sculptmode_correct_state();
2161
2162         waitcursor(1);
2163
2164         if(hb_2d.xmax-hb_2d.xmin > 3 && hb_2d.ymax-hb_2d.ymin > 3) {
2165                 init_sculptmatrices();
2166
2167                 sculptmode_do_pmv(ob,&hb_2d,mode);
2168         }
2169         else mesh_pmv_off(ob, get_mesh(ob));
2170
2171         /*XXX: scrarea_do_windraw(curarea); */
2172
2173         waitcursor(0);
2174 }
2175 #endif