- correct some spelling errors.
[blender.git] / source / blender / editors / sculpt_paint / paint_stroke.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software  Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2009 by Nicholas Bishop
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Jason Wilkins, Tom Musgrove.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  */
28
29 #include "MEM_guardedalloc.h"
30
31 #include "DNA_object_types.h"
32 #include "DNA_scene_types.h"
33
34 #include "RNA_access.h"
35
36 #include "BKE_context.h"
37 #include "BKE_paint.h"
38 #include "BKE_brush.h"
39
40 #include "WM_api.h"
41 #include "WM_types.h"
42
43 #include "BLI_math.h"
44
45
46 #include "BIF_gl.h"
47 #include "BIF_glutil.h"
48
49 #include "ED_screen.h"
50 #include "ED_view3d.h"
51
52 #include "paint_intern.h"
53 #include "sculpt_intern.h" // XXX, for expedience in getting this working, refactor later (or this just shows that this needs unification)
54
55 #include "BKE_image.h"
56
57 #include <float.h>
58 #include <math.h>
59
60 typedef struct PaintStroke {
61         void *mode_data;
62         void *smooth_stroke_cursor;
63         wmTimer *timer;
64
65         /* Cached values */
66         ViewContext vc;
67         bglMats mats;
68         Brush *brush;
69
70         float last_mouse_position[2];
71
72         /* Set whether any stroke step has yet occurred
73            e.g. in sculpt mode, stroke doesn't start until cursor
74            passes over the mesh */
75         int stroke_started;
76
77         StrokeGetLocation get_location;
78         StrokeTestStart test_start;
79         StrokeUpdateStep update_step;
80         StrokeDone done;
81 } PaintStroke;
82
83 /*** Cursor ***/
84 static void paint_draw_smooth_stroke(bContext *C, int x, int y, void *customdata) 
85 {
86         Brush *brush = paint_brush(paint_get_active(CTX_data_scene(C)));
87         PaintStroke *stroke = customdata;
88
89         glColor4ubv(paint_get_active(CTX_data_scene(C))->paint_cursor_col);
90         glEnable(GL_LINE_SMOOTH);
91         glEnable(GL_BLEND);
92
93         if(stroke && brush && (brush->flag & BRUSH_SMOOTH_STROKE)) {
94                 ARegion *ar = CTX_wm_region(C);
95                 sdrawline(x, y, (int)stroke->last_mouse_position[0] - ar->winrct.xmin,
96                           (int)stroke->last_mouse_position[1] - ar->winrct.ymin);
97         }
98
99         glDisable(GL_BLEND);
100         glDisable(GL_LINE_SMOOTH);
101 }
102
103 #if 0
104
105 // grid texture for testing
106
107 #define GRID_WIDTH   8
108 #define GRID_LENGTH  8
109
110 #define W (0xFFFFFFFF)
111 #define G (0x00888888)
112 #define E (0xE1E1E1E1)
113 #define C (0xC3C3C3C3)
114 #define O (0xB4B4B4B4)
115 #define Q (0xA9A9A9A9)
116
117 static unsigned grid_texture0[256] =
118 {
119    W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
120    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
121    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
122    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
123    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
124    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
125    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
126    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
127    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
128    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
129    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
130    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
131    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
132    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
133    W,G,G,G,G,G,G,G,G,G,G,G,G,G,G,W,
134    W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,W,
135 };
136
137 static unsigned grid_texture1[64] =
138 {
139    C,C,C,C,C,C,C,C,
140    C,G,G,G,G,G,G,C,
141    C,G,G,G,G,G,G,C,
142    C,G,G,G,G,G,G,C,
143    C,G,G,G,G,G,G,C,
144    C,G,G,G,G,G,G,C,
145    C,G,G,G,G,G,G,C,
146    C,C,C,C,C,C,C,C,
147 };
148
149 static unsigned grid_texture2[16] =
150 {
151    O,O,O,O,
152    O,G,G,O,
153    O,G,G,O,
154    O,O,O,O,
155 };
156
157 static unsigned grid_texture3[4] =
158 {
159    Q,Q,
160    Q,Q,
161 };
162
163 static unsigned grid_texture4[1] =
164 {
165    Q,
166 };
167
168 #undef W
169 #undef G
170 #undef E
171 #undef C
172 #undef O
173 #undef Q
174
175 static void load_grid()
176 {
177         static GLuint overlay_texture;
178
179         if (!overlay_texture) {
180                 //GLfloat largest_supported_anisotropy;
181
182                 glGenTextures(1, &overlay_texture);
183                 glBindTexture(GL_TEXTURE_2D, overlay_texture);
184                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture0);
185                 glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB,  8,  8, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture1);
186                 glTexImage2D(GL_TEXTURE_2D, 2, GL_RGB,  4,  4, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture2);
187                 glTexImage2D(GL_TEXTURE_2D, 3, GL_RGB,  2,  2, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture3);
188                 glTexImage2D(GL_TEXTURE_2D, 4, GL_RGB,  1,  1, 0, GL_RGBA, GL_UNSIGNED_BYTE, grid_texture4);
189                 glEnable(GL_TEXTURE_2D);
190                 glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
191                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
192                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
193
194                 //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
195                 //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
196
197                 //glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
198                 //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, largest_supported_anisotropy);
199         }
200 }
201
202 #endif
203
204 extern float get_tex_pixel(Brush* br, float u, float v);
205
206 typedef struct Snapshot {
207         float size[3];
208         float ofs[3];
209         float rot;
210         int brush_size;
211         int winx;
212         int winy;
213         int brush_map_mode;
214         int curve_changed_timestamp;
215 } Snapshot;
216
217 static int same_snap(Snapshot* snap, Brush* brush, ViewContext* vc)
218 {
219         MTex* mtex = &brush->mtex;
220
221         return 
222                 (mtex->tex &&
223                     mtex->ofs[0] == snap->ofs[0] &&
224                     mtex->ofs[1] == snap->ofs[1] &&
225                     mtex->ofs[2] == snap->ofs[2] &&
226                     mtex->size[0] == snap->size[0] &&
227                     mtex->size[1] == snap->size[1] &&
228                     mtex->size[2] == snap->size[2] &&
229                     mtex->rot == snap->rot) &&
230                 ((mtex->brush_map_mode == MTEX_MAP_MODE_FIXED && sculpt_get_brush_size(brush) <= snap->brush_size) || (sculpt_get_brush_size(brush) == snap->brush_size)) && // make brush smaller shouldn't cause a resample
231                 mtex->brush_map_mode == snap->brush_map_mode &&
232                 vc->ar->winx == snap->winx &&
233                 vc->ar->winy == snap->winy;
234 }
235
236 static void make_snap(Snapshot* snap, Brush* brush, ViewContext* vc)
237 {
238         if (brush->mtex.tex) {
239                 snap->brush_map_mode = brush->mtex.brush_map_mode;
240                 copy_v3_v3(snap->ofs, brush->mtex.ofs);
241                 copy_v3_v3(snap->size, brush->mtex.size);
242                 snap->rot = brush->mtex.rot;
243         }
244         else {
245                 snap->brush_map_mode = -1;
246                 snap->ofs[0]= snap->ofs[1]= snap->ofs[2]= -1;
247                 snap->size[0]= snap->size[1]= snap->size[2]= -1;
248                 snap->rot = -1;
249         }
250
251         snap->brush_size = sculpt_get_brush_size(brush);
252         snap->winx = vc->ar->winx;
253         snap->winy = vc->ar->winy;
254 }
255
256 int load_tex(Sculpt *sd, Brush* br, ViewContext* vc)
257 {
258         static GLuint overlay_texture = 0;
259         static int init = 0;
260         static int tex_changed_timestamp = -1;
261         static int curve_changed_timestamp = -1;
262         static Snapshot snap;
263         static int old_size = -1;
264
265         GLubyte* buffer = 0;
266
267         int size;
268         int j;
269         int refresh;
270
271         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED && !br->mtex.tex) return 0;
272
273         refresh = 
274                 !overlay_texture ||
275                 (br->mtex.tex && 
276                     (!br->mtex.tex->preview ||
277                       br->mtex.tex->preview->changed_timestamp[0] != tex_changed_timestamp)) ||
278                 !br->curve ||
279                 br->curve->changed_timestamp != curve_changed_timestamp ||
280                 !same_snap(&snap, br, vc);
281
282         if (refresh) {
283                 if (br->mtex.tex && br->mtex.tex->preview)
284                         tex_changed_timestamp = br->mtex.tex->preview->changed_timestamp[0];
285
286                 if (br->curve)
287                         curve_changed_timestamp = br->curve->changed_timestamp;
288
289                 make_snap(&snap, br, vc);
290
291                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
292                         int s = sculpt_get_brush_size(br);
293                         int r = 1;
294
295                         for (s >>= 1; s > 0; s >>= 1)
296                                 r++;
297
298                         size = (1<<r);
299
300                         if (size < 256)
301                                 size = 256;
302
303                         if (size < old_size)
304                                 size = old_size;
305                 }
306                 else
307                         size = 512;
308
309                 if (old_size != size) {
310                         if (overlay_texture) {
311                                 glDeleteTextures(1, &overlay_texture);
312                                 overlay_texture = 0;
313                         }
314
315                         init = 0;
316
317                         old_size = size;
318                 }
319
320                 buffer = MEM_mallocN(sizeof(GLubyte)*size*size, "load_tex");
321
322                 #pragma omp parallel for schedule(static) if (sd->flags & SCULPT_USE_OPENMP)
323                 for (j= 0; j < size; j++) {
324                         int i;
325                         float y;
326                         float len;
327
328                         for (i= 0; i < size; i++) {
329
330                                 // largely duplicated from tex_strength
331
332                                 const float rotation = -br->mtex.rot;
333                                 float diameter = sculpt_get_brush_size(br);
334                                 int index = j*size + i;
335                                 float x;
336                                 float avg;
337
338                                 x = (float)i/size;
339                                 y = (float)j/size;
340
341                                 x -= 0.5f;
342                                 y -= 0.5f;
343
344                                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) {
345                                         x *= vc->ar->winx / diameter;
346                                         y *= vc->ar->winy / diameter;
347                                 }
348                                 else {
349                                         x *= 2;
350                                         y *= 2;
351                                 }
352
353                                 len = sqrtf(x*x + y*y);
354
355                                 if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) || len <= 1) {
356                                         /* it is probably worth optimizing for those cases where 
357                                            the texture is not rotated by skipping the calls to
358                                            atan2, sqrtf, sin, and cos. */
359                                         if (br->mtex.tex && (rotation > 0.001 || rotation < -0.001)) {
360                                                 const float angle    = atan2(y, x) + rotation;
361
362                                                 x = len * cos(angle);
363                                                 y = len * sin(angle);
364                                         }
365
366                                         x *= br->mtex.size[0];
367                                         y *= br->mtex.size[1];
368
369                                         x += br->mtex.ofs[0];
370                                         y += br->mtex.ofs[1];
371
372                                         avg = br->mtex.tex ? get_tex_pixel(br, x, y) : 1;
373
374                                         avg += br->texture_sample_bias;
375
376                                         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED)
377                                                 avg *= brush_curve_strength(br, len, 1); /* Falloff curve */
378
379                                         buffer[index] = (GLubyte)(255*avg);
380                                 }
381                                 else {
382                                         buffer[index] = 0;
383                                 }
384                         }
385                 }
386
387                 if (!overlay_texture)
388                         glGenTextures(1, &overlay_texture);
389         }
390         else {
391                 size= old_size;
392         }
393
394         glBindTexture(GL_TEXTURE_2D, overlay_texture);
395
396         if (refresh) {
397                 if (!init) {
398                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
399                         init = 1;
400                 }
401                 else {
402                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
403                 }
404
405                 if (buffer)
406                         MEM_freeN(buffer);
407         }
408
409         glEnable(GL_TEXTURE_2D);
410
411         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
412         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
413         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
414
415         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
416                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
417                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
418         }
419
420         return 1;
421 }
422
423 /* Convert a point in model coordinates to 2D screen coordinates. */
424 // XXX duplicated from sculpt.c, deal with this later.
425 static void projectf(bglMats *mats, const float v[3], float p[2])
426 {
427         double ux, uy, uz;
428
429         gluProject(v[0],v[1],v[2], mats->modelview, mats->projection,
430                    (GLint *)mats->viewport, &ux, &uy, &uz);
431         p[0]= ux;
432         p[1]= uy;
433 }
434
435 static int project_brush_radius(RegionView3D* rv3d, float radius, float location[3], bglMats* mats)
436 {
437         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
438
439         viewvector(rv3d, location, view);
440
441         // create a vector that is not orthogonal to view
442
443         if (fabsf(view[0]) < 0.1) {
444                 nonortho[0] = view[0] + 1;
445                 nonortho[1] = view[1];
446                 nonortho[2] = view[2];
447         }
448         else if (fabsf(view[1]) < 0.1) {
449                 nonortho[0] = view[0];
450                 nonortho[1] = view[1] + 1;
451                 nonortho[2] = view[2];
452         }
453         else {
454                 nonortho[0] = view[0];
455                 nonortho[1] = view[1];
456                 nonortho[2] = view[2] + 1;
457         }
458
459         // get a vector in the plane of the view
460         cross_v3_v3v3(ortho, nonortho, view);
461         normalize_v3(ortho);
462
463         // make a point on the surface of the brush tagent to the view
464         mul_v3_fl(ortho, radius);
465         add_v3_v3v3(offset, location, ortho);
466
467         // project the center of the brush, and the tagent point to the view onto the screen
468         projectf(mats, location, p1);
469         projectf(mats, offset, p2);
470
471         // the distance between these points is the size of the projected brush in pixels
472         return len_v2v2(p1, p2);
473 }
474
475 int sculpt_get_brush_geometry(bContext* C, int x, int y, int* pixel_radius, float location[3], float modelview[16], float projection[16], int viewport[4])
476 {
477         struct PaintStroke *stroke;
478         float window[2];
479         int hit;
480
481         stroke = paint_stroke_new(C, NULL, NULL, NULL, NULL);
482
483         window[0] = x + stroke->vc.ar->winrct.xmin;
484         window[1] = y + stroke->vc.ar->winrct.ymin;
485
486         memcpy(modelview, stroke->vc.rv3d->viewmat, sizeof(float[16]));
487         memcpy(projection, stroke->vc.rv3d->winmat, sizeof(float[16]));
488         memcpy(viewport, stroke->mats.viewport, sizeof(int[4]));
489
490         if (stroke->vc.obact->sculpt && stroke->vc.obact->sculpt->pbvh && sculpt_stroke_get_location(C, stroke, location, window)) {
491                 *pixel_radius = project_brush_radius(stroke->vc.rv3d, sculpt_get_brush_unprojected_radius(stroke->brush), location, &stroke->mats);
492
493                 if (*pixel_radius == 0)
494                         *pixel_radius = sculpt_get_brush_size(stroke->brush);
495
496                 mul_m4_v3(stroke->vc.obact->sculpt->ob->obmat, location);
497
498                 hit = 1;
499         }
500         else {
501                 Sculpt* sd    = CTX_data_tool_settings(C)->sculpt;
502                 Brush*  brush = paint_brush(&sd->paint);
503
504                 *pixel_radius = sculpt_get_brush_size(brush);
505                 hit = 0;
506         }
507
508         paint_stroke_free(stroke);
509
510         return hit;
511 }
512
513 // XXX duplicated from sculpt.c
514 float unproject_brush_radius(Object *ob, ViewContext *vc, float center[3], float offset)
515 {
516         float delta[3], scale, loc[3];
517
518         mul_v3_m4v3(loc, ob->obmat, center);
519
520         initgrabz(vc->rv3d, loc[0], loc[1], loc[2]);
521         window_to_3d_delta(vc->ar, delta, offset, 0);
522
523         scale= fabsf(mat4_to_scale(ob->obmat));
524         scale= (scale == 0.0f)? 1.0f: scale;
525
526         return len_v3(delta)/scale;
527 }
528
529 // XXX paint cursor now does a lot of the same work that is needed during a sculpt stroke
530 // problem: all this stuff was not intended to be used at this point, so things feel a
531 // bit hacked.  I've put lots of stuff in Brush that probably better goes in Paint
532 // Functions should be refactored so that they can be used between sculpt.c and
533 // paint_stroke.c clearly and optimally and the lines of communication between the
534 // two modules should be more clearly defined.
535 static void paint_draw_cursor(bContext *C, int x, int y, void *unused)
536 {
537         ViewContext vc;
538
539         (void)unused;
540
541         view3d_set_viewcontext(C, &vc);
542
543         if (vc.obact->sculpt) {
544                 Paint *paint = paint_get_active(CTX_data_scene(C));
545                 Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
546                 Brush *brush = paint_brush(paint);
547
548                 int pixel_radius, viewport[4];
549                 float location[3], modelview[16], projection[16];
550
551                 int hit;
552
553                 int flip;
554                 int sign;
555
556                 float* col;
557                 float  alpha;
558
559                 float visual_strength = sculpt_get_brush_alpha(brush)*sculpt_get_brush_alpha(brush);
560
561                 const float min_alpha = 0.20f;
562                 const float max_alpha = 0.80f;
563
564                 {
565                         const float u = 0.5f;
566                         const float v = 1 - u;
567                         const float r = 20;
568
569                         const float dx = sd->last_x - x;
570                         const float dy = sd->last_y - y;
571
572                         if (dx*dx + dy*dy >= r*r) {
573                                 sd->last_angle = atan2(dx, dy);
574
575                                 sd->last_x = u*sd->last_x + v*x;
576                                 sd->last_y = u*sd->last_y + v*y;
577                         }
578                 }
579
580                 if(!sculpt_get_lock_brush_size(brush) && !(paint->flags & PAINT_SHOW_BRUSH)) 
581                         return;
582
583                 hit = sculpt_get_brush_geometry(C, x, y, &pixel_radius, location, modelview, projection, viewport);
584
585                 if (sculpt_get_lock_brush_size(brush))
586                         sculpt_set_brush_size(brush, pixel_radius);
587
588                 // XXX: no way currently to know state of pen flip or invert key modifier without starting a stroke
589                 flip = 1;
590
591                 sign = flip * ((brush->flag & BRUSH_DIR_IN)? -1 : 1);
592
593                 if (sign < 0 && ELEM4(brush->sculpt_tool, SCULPT_TOOL_DRAW, SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY, SCULPT_TOOL_PINCH))
594                         col = brush->sub_col;
595                 else
596                         col = brush->add_col;
597
598                 alpha = (paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE) ? min_alpha + (visual_strength*(max_alpha-min_alpha)) : 0.50f;
599
600                 if (ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_FIXED, MTEX_MAP_MODE_TILED) && brush->flag & BRUSH_TEXTURE_OVERLAY) {
601                         glPushAttrib(
602                                 GL_COLOR_BUFFER_BIT|
603                                 GL_CURRENT_BIT|
604                                 GL_DEPTH_BUFFER_BIT|
605                                 GL_ENABLE_BIT|
606                                 GL_LINE_BIT|
607                                 GL_POLYGON_BIT|
608                                 GL_STENCIL_BUFFER_BIT|
609                                 GL_TRANSFORM_BIT|
610                                 GL_VIEWPORT_BIT|
611                                 GL_TEXTURE_BIT);
612
613                         if (load_tex(sd, brush, &vc)) {
614                                 glEnable(GL_BLEND);
615
616                                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
617                                 glDepthMask(GL_FALSE);
618                                 glDepthFunc(GL_ALWAYS);
619
620                                 glMatrixMode(GL_TEXTURE);
621                                 glPushMatrix();
622                                 glLoadIdentity();
623
624                                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
625                                         glTranslatef(0.5f, 0.5f, 0);
626
627                                         if (brush->flag & BRUSH_RAKE) {
628                                                 glRotatef(sd->last_angle*(float)(180.0/M_PI), 0, 0, 1);
629                                         }
630                                         else {
631                                                 glRotatef(sd->special_rotation*(float)(180.0/M_PI), 0, 0, 1);
632                                         }
633
634                                         glTranslatef(-0.5f, -0.5f, 0);
635
636                                         if (sd->draw_pressure && (brush->flag & BRUSH_SIZE_PRESSURE)) {
637                                                 glTranslatef(0.5f, 0.5f, 0);
638                                                 glScalef(1.0f/sd->pressure_value, 1.0f/sd->pressure_value, 1);
639                                                 glTranslatef(-0.5f, -0.5f, 0);
640                                         }
641                                 }
642
643                                 glColor4f(
644                                         U.sculpt_paint_overlay_col[0],
645                                         U.sculpt_paint_overlay_col[1],
646                                         U.sculpt_paint_overlay_col[2],
647                                         brush->texture_overlay_alpha / 100.0f);
648
649                                 glBegin(GL_QUADS);
650                                 if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
651                                         if (sd->draw_anchored) {
652                                                 glTexCoord2f(0, 0);
653                                                 glVertex2f(sd->anchored_initial_mouse[0]-sd->anchored_size - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1]-sd->anchored_size - vc.ar->winrct.ymin);
654
655                                                 glTexCoord2f(1, 0);
656                                                 glVertex2f(sd->anchored_initial_mouse[0]+sd->anchored_size - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1]-sd->anchored_size - vc.ar->winrct.ymin);
657
658                                                 glTexCoord2f(1, 1);
659                                                 glVertex2f(sd->anchored_initial_mouse[0]+sd->anchored_size - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1]+sd->anchored_size - vc.ar->winrct.ymin);
660
661                                                 glTexCoord2f(0, 1);
662                                                 glVertex2f(sd->anchored_initial_mouse[0]-sd->anchored_size - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1]+sd->anchored_size - vc.ar->winrct.ymin);
663                                         }
664                                         else {
665                                                 glTexCoord2f(0, 0);
666                                                 glVertex2f((float)x-sculpt_get_brush_size(brush), (float)y-sculpt_get_brush_size(brush));
667
668                                                 glTexCoord2f(1, 0);
669                                                 glVertex2f((float)x+sculpt_get_brush_size(brush), (float)y-sculpt_get_brush_size(brush));
670
671                                                 glTexCoord2f(1, 1);
672                                                 glVertex2f((float)x+sculpt_get_brush_size(brush), (float)y+sculpt_get_brush_size(brush));
673
674                                                 glTexCoord2f(0, 1);
675                                                 glVertex2f((float)x-sculpt_get_brush_size(brush), (float)y+sculpt_get_brush_size(brush));
676                                         }
677                                 }
678                                 else {
679                                         glTexCoord2f(0, 0);
680                                         glVertex2f(0, 0);
681
682                                         glTexCoord2f(1, 0);
683                                         glVertex2f(viewport[2], 0);
684
685                                         glTexCoord2f(1, 1);
686                                         glVertex2f(viewport[2], viewport[3]);
687
688                                         glTexCoord2f(0, 1);
689                                         glVertex2f(0, viewport[3]);
690                                 }
691                                 glEnd();
692
693                                 glPopMatrix();
694                         }
695
696                         glPopAttrib();
697                 }
698
699                 if (hit) {
700                         float unprojected_radius;
701
702                         // XXX duplicated from brush_strength & paint_stroke_add_step, refactor later
703                         //wmEvent* event = CTX_wm_window(C)->eventstate;
704
705                         if (sd->draw_pressure && (brush->flag & BRUSH_ALPHA_PRESSURE))
706                                 visual_strength *= sd->pressure_value;
707
708                         // don't show effect of strength past the soft limit
709                         if (visual_strength > 1) visual_strength = 1;
710
711                         if (sd->draw_anchored) {
712                                 unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, sd->anchored_size);
713                         }
714                         else {
715                                 if (brush->flag & BRUSH_ANCHORED)
716                                         unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, 8);
717                                 else
718                                         unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, sculpt_get_brush_size(brush));
719                         }
720
721                         if (sd->draw_pressure && (brush->flag & BRUSH_SIZE_PRESSURE))
722                                 unprojected_radius *= sd->pressure_value;
723
724                         if (!sculpt_get_lock_brush_size(brush))
725                                 sculpt_set_brush_unprojected_radius(brush, unprojected_radius);
726
727                         if(!(paint->flags & PAINT_SHOW_BRUSH))
728                                 return;
729
730                 }
731
732                 glPushAttrib(
733                         GL_COLOR_BUFFER_BIT|
734                         GL_CURRENT_BIT|
735                         GL_DEPTH_BUFFER_BIT|
736                         GL_ENABLE_BIT|
737                         GL_LINE_BIT|
738                         GL_POLYGON_BIT|
739                         GL_STENCIL_BUFFER_BIT|
740                         GL_TRANSFORM_BIT|
741                         GL_VIEWPORT_BIT|
742                         GL_TEXTURE_BIT);
743
744                 glColor4f(col[0], col[1], col[2], alpha);
745
746                 glEnable(GL_BLEND);
747
748                 glEnable(GL_LINE_SMOOTH);
749
750                 if (sd->draw_anchored) {
751                         glTranslatef(sd->anchored_initial_mouse[0] - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1] - vc.ar->winrct.ymin, 0.0f);
752                         glutil_draw_lined_arc(0.0, M_PI*2.0, sd->anchored_size, 40);
753                         glTranslatef(-sd->anchored_initial_mouse[0] + vc.ar->winrct.xmin, -sd->anchored_initial_mouse[1] + vc.ar->winrct.xmin, 0.0f);
754                 }
755                 else {
756                         glTranslatef((float)x, (float)y, 0.0f);
757                         glutil_draw_lined_arc(0.0, M_PI*2.0, sculpt_get_brush_size(brush), 40);
758                         glTranslatef(-(float)x, -(float)y, 0.0f);
759                 }
760
761                 glPopAttrib();
762         }
763         else {
764                 Paint *paint = paint_get_active(CTX_data_scene(C));
765                 Brush *brush = paint_brush(paint);
766
767                 if(!(paint->flags & PAINT_SHOW_BRUSH))
768                         return;
769
770                 glColor4ubv(paint_get_active(CTX_data_scene(C))->paint_cursor_col);
771                 glEnable(GL_LINE_SMOOTH);
772                 glEnable(GL_BLEND);
773
774                 glTranslatef((float)x, (float)y, 0.0f);
775                 glutil_draw_lined_arc(0.0, M_PI*2.0, brush->size, 40); // XXX: for now use the brushes size instead of potentially using the unified size because the feature has been enabled for sculpt
776                 glTranslatef((float)-x, (float)-y, 0.0f);
777
778                 glDisable(GL_BLEND);
779                 glDisable(GL_LINE_SMOOTH);
780         }
781 }
782
783 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
784 static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
785 {
786         Paint *paint = paint_get_active(CTX_data_scene(C)); // XXX
787         Brush *brush = paint_brush(paint); // XXX
788
789         float mouse[2];
790
791         PointerRNA itemptr;
792
793         float location[3];
794
795         float pressure;
796         int   pen_flip;
797
798         ViewContext vc; // XXX
799
800         PaintStroke *stroke = op->customdata;
801
802         view3d_set_viewcontext(C, &vc); // XXX
803
804         /* Tablet */
805         if(event->custom == EVT_DATA_TABLET) {
806                 wmTabletData *wmtab= event->customdata;
807
808                 pressure = (wmtab->Active != EVT_TABLET_NONE) ? wmtab->Pressure : 1;
809                 pen_flip = (wmtab->Active == EVT_TABLET_ERASER);
810         }
811         else {
812                 pressure = 1;
813                 pen_flip = 0;
814         }
815
816         // XXX: temporary check for sculpt mode until things are more unified
817         if (vc.obact->sculpt) {
818                 float delta[3];
819
820                 brush_jitter_pos(brush, mouse_in, mouse);
821
822                 // XXX: meh, this is round about because brush_jitter_pos isn't written in the best way to be reused here
823                 if (brush->flag & BRUSH_JITTER_PRESSURE) {
824                         sub_v3_v3v3(delta, mouse, mouse_in);
825                         mul_v3_fl(delta, pressure);
826                         add_v3_v3v3(mouse, mouse_in, delta);
827                 }
828         }
829         else
830                 copy_v3_v3(mouse, mouse_in);
831
832         /* XXX: can remove the if statement once all modes have this */
833         if(stroke->get_location)
834                 stroke->get_location(C, stroke, location, mouse);
835         else
836                 zero_v3(location);
837
838         /* Add to stroke */
839         RNA_collection_add(op->ptr, "stroke", &itemptr);
840
841         RNA_float_set_array(&itemptr, "location",     location);
842         RNA_float_set_array(&itemptr, "mouse",        mouse);
843         RNA_boolean_set    (&itemptr, "pen_flip",     pen_flip);
844         RNA_float_set      (&itemptr, "pressure", pressure);
845
846         stroke->last_mouse_position[0] = mouse[0];
847         stroke->last_mouse_position[1] = mouse[1];
848
849         stroke->update_step(C, stroke, &itemptr);
850 }
851
852 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
853 static int paint_smooth_stroke(PaintStroke *stroke, float output[2], wmEvent *event)
854 {
855         output[0] = event->x; 
856         output[1] = event->y;
857
858         if ((stroke->brush->flag & BRUSH_SMOOTH_STROKE) &&  
859             !ELEM4(stroke->brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK) &&
860             !(stroke->brush->flag & BRUSH_ANCHORED) &&
861             !(stroke->brush->flag & BRUSH_RESTORE_MESH))
862         {
863                 float u = stroke->brush->smooth_stroke_factor, v = 1.0 - u;
864                 float dx = stroke->last_mouse_position[0] - event->x, dy = stroke->last_mouse_position[1] - event->y;
865
866                 /* If the mouse is moving within the radius of the last move,
867                    don't update the mouse position. This allows sharp turns. */
868                 if(dx*dx + dy*dy < stroke->brush->smooth_stroke_radius * stroke->brush->smooth_stroke_radius)
869                         return 0;
870
871                 output[0] = event->x * v + stroke->last_mouse_position[0] * u;
872                 output[1] = event->y * v + stroke->last_mouse_position[1] * u;
873         }
874
875         return 1;
876 }
877
878 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
879 static int paint_space_stroke_enabled(Brush *br)
880 {
881         return (br->flag & BRUSH_SPACE) &&
882                !(br->flag & BRUSH_ANCHORED) &&
883                !ELEM4(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK);
884 }
885
886 /* For brushes with stroke spacing enabled, moves mouse in steps
887    towards the final mouse location. */
888 static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const float final_mouse[2])
889 {
890         PaintStroke *stroke = op->customdata;
891         int cnt = 0;
892
893         if(paint_space_stroke_enabled(stroke->brush)) {
894                 float mouse[2];
895                 float vec[2];
896                 float length, scale;
897
898                 copy_v2_v2(mouse, stroke->last_mouse_position);
899                 sub_v2_v2v2(vec, final_mouse, mouse);
900
901                 length = len_v2(vec);
902
903                 if(length > FLT_EPSILON) {
904                         int steps;
905                         int i;
906                         float pressure = 1;
907
908                         // XXX duplicate code
909                         if(event->custom == EVT_DATA_TABLET) {
910                                 wmTabletData *wmtab= event->customdata;
911                                 if(wmtab->Active != EVT_TABLET_NONE)
912                                         pressure = stroke->brush->flag & BRUSH_SIZE_PRESSURE ? wmtab->Pressure : 1;
913                         }
914
915                         scale = (sculpt_get_brush_size(stroke->brush)*pressure*stroke->brush->spacing/50.0f) / length;
916                         mul_v2_fl(vec, scale);
917
918                         steps = (int)(1.0f / scale);
919
920                         for(i = 0; i < steps; ++i, ++cnt) {
921                                 add_v2_v2(mouse, vec);
922                                 paint_brush_stroke_add_step(C, op, event, mouse);
923                         }
924                 }
925         }
926
927         return cnt;
928 }
929
930 /**** Public API ****/
931
932 PaintStroke *paint_stroke_new(bContext *C,
933                                   StrokeGetLocation get_location,
934                                   StrokeTestStart test_start,
935                                   StrokeUpdateStep update_step,
936                                   StrokeDone done)
937 {
938         PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
939
940         stroke->brush = paint_brush(paint_get_active(CTX_data_scene(C)));
941         view3d_set_viewcontext(C, &stroke->vc);
942         view3d_get_transformation(stroke->vc.ar, stroke->vc.rv3d, stroke->vc.obact, &stroke->mats);
943
944         stroke->get_location = get_location;
945         stroke->test_start = test_start;
946         stroke->update_step = update_step;
947         stroke->done = done;
948
949         return stroke;
950 }
951
952 void paint_stroke_free(PaintStroke *stroke)
953 {
954         MEM_freeN(stroke);
955 }
956
957 int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
958 {
959         PaintStroke *stroke = op->customdata;
960         float mouse[2];
961         int first= 0;
962
963         if(!stroke->stroke_started) {
964                 stroke->last_mouse_position[0] = event->x;
965                 stroke->last_mouse_position[1] = event->y;
966                 stroke->stroke_started = stroke->test_start(C, op, event);
967
968                 if(stroke->stroke_started) {
969                         stroke->smooth_stroke_cursor =
970                                 WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_stroke, stroke);
971
972                         if(stroke->brush->flag & BRUSH_AIRBRUSH)
973                                 stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
974                 }
975
976                 first= 1;
977                 //ED_region_tag_redraw(ar);
978         }
979
980         /* TODO: fix hardcoded events here */
981         if(event->type == LEFTMOUSE && event->val == KM_RELEASE) {
982                 /* exit stroke, free data */
983                 if(stroke->smooth_stroke_cursor)
984                         WM_paint_cursor_end(CTX_wm_manager(C), stroke->smooth_stroke_cursor);
985
986                 if(stroke->timer)
987                         WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);
988
989                 stroke->done(C, stroke);
990                 MEM_freeN(stroke);
991                 return OPERATOR_FINISHED;
992         }
993         else if(first || ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (event->type == TIMER && (event->customdata == stroke->timer))) {
994                 if(stroke->stroke_started) {
995                         if(paint_smooth_stroke(stroke, mouse, event)) {
996                                 if(paint_space_stroke_enabled(stroke->brush)) {
997                                         if(!paint_space_stroke(C, op, event, mouse)) {
998                                                 //ED_region_tag_redraw(ar);
999                                         }
1000                                 }
1001                                 else {
1002                                         paint_brush_stroke_add_step(C, op, event, mouse);
1003                                 }
1004                         }
1005                         else
1006                                 ;//ED_region_tag_redraw(ar);
1007                 }
1008         }
1009
1010         /* we want the stroke to have the first daub at the start location instead of waiting till we have moved the space distance */
1011         if(first &&
1012            stroke->stroke_started &&
1013            paint_space_stroke_enabled(stroke->brush) &&
1014            !(stroke->brush->flag & BRUSH_ANCHORED) &&
1015            !(stroke->brush->flag & BRUSH_SMOOTH_STROKE))
1016         {
1017                 paint_brush_stroke_add_step(C, op, event, mouse);
1018         }
1019         
1020         return OPERATOR_RUNNING_MODAL;
1021 }
1022
1023 int paint_stroke_exec(bContext *C, wmOperator *op)
1024 {
1025         PaintStroke *stroke = op->customdata;
1026
1027         RNA_BEGIN(op->ptr, itemptr, "stroke") {
1028                 stroke->update_step(C, stroke, &itemptr);
1029         }
1030         RNA_END;
1031
1032         MEM_freeN(stroke);
1033         op->customdata = NULL;
1034
1035         return OPERATOR_FINISHED;
1036 }
1037
1038 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
1039 {
1040         return &stroke->vc;
1041 }
1042
1043 void *paint_stroke_mode_data(struct PaintStroke *stroke)
1044 {
1045         return stroke->mode_data;
1046 }
1047
1048 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
1049 {
1050         stroke->mode_data = mode_data;
1051 }
1052
1053 int paint_poll(bContext *C)
1054 {
1055         Paint *p = paint_get_active(CTX_data_scene(C));
1056         Object *ob = CTX_data_active_object(C);
1057
1058         return p && ob && paint_brush(p) &&
1059                 CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
1060                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
1061 }
1062
1063 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
1064 {
1065         Paint *p = paint_get_active(CTX_data_scene(C));
1066
1067         if(p && !p->paint_cursor)
1068                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
1069 }
1070