== Sculpt/Paint Fixes ==
[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 && brush_size(brush) <= snap->brush_size) || (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 = 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 = 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 radius = 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 / radius;
346                                         y *= vc->ar->winy / radius;
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, brush_unprojected_radius(stroke->brush), location, &stroke->mats);
492
493                 if (*pixel_radius == 0)
494                         *pixel_radius = 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 = 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 = brush_alpha(brush)*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(!brush_use_locked_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 (brush_use_locked_size(brush))
586                         brush_set_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_use_size_pressure(brush)) {
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                                                 const int radius= brush_size(brush);
666
667                                                 glTexCoord2f(0, 0);
668                                                 glVertex2f((float)x-radius, (float)y-radius);
669
670                                                 glTexCoord2f(1, 0);
671                                                 glVertex2f((float)x+radius, (float)y-radius);
672
673                                                 glTexCoord2f(1, 1);
674                                                 glVertex2f((float)x+radius, (float)y+radius);
675
676                                                 glTexCoord2f(0, 1);
677                                                 glVertex2f((float)x-radius, (float)y+radius);
678                                         }
679                                 }
680                                 else {
681                                         glTexCoord2f(0, 0);
682                                         glVertex2f(0, 0);
683
684                                         glTexCoord2f(1, 0);
685                                         glVertex2f(viewport[2], 0);
686
687                                         glTexCoord2f(1, 1);
688                                         glVertex2f(viewport[2], viewport[3]);
689
690                                         glTexCoord2f(0, 1);
691                                         glVertex2f(0, viewport[3]);
692                                 }
693                                 glEnd();
694
695                                 glPopMatrix();
696                         }
697
698                         glPopAttrib();
699                 }
700
701                 if (hit) {
702                         float unprojected_radius;
703
704                         // XXX duplicated from brush_strength & paint_stroke_add_step, refactor later
705                         //wmEvent* event = CTX_wm_window(C)->eventstate;
706
707                         if (sd->draw_pressure && brush_use_alpha_pressure(brush))
708                                 visual_strength *= sd->pressure_value;
709
710                         // don't show effect of strength past the soft limit
711                         if (visual_strength > 1) visual_strength = 1;
712
713                         if (sd->draw_anchored) {
714                                 unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, sd->anchored_size);
715                         }
716                         else {
717                                 if (brush->flag & BRUSH_ANCHORED)
718                                         unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, 8);
719                                 else
720                                         unprojected_radius = unproject_brush_radius(CTX_data_active_object(C), &vc, location, brush_size(brush));
721                         }
722
723                         if (sd->draw_pressure && brush_use_size_pressure(brush))
724                                 unprojected_radius *= sd->pressure_value;
725
726                         if (!brush_use_locked_size(brush))
727                                 brush_set_unprojected_radius(brush, unprojected_radius);
728
729                         if(!(paint->flags & PAINT_SHOW_BRUSH))
730                                 return;
731
732                 }
733
734                 glPushAttrib(
735                         GL_COLOR_BUFFER_BIT|
736                         GL_CURRENT_BIT|
737                         GL_DEPTH_BUFFER_BIT|
738                         GL_ENABLE_BIT|
739                         GL_LINE_BIT|
740                         GL_POLYGON_BIT|
741                         GL_STENCIL_BUFFER_BIT|
742                         GL_TRANSFORM_BIT|
743                         GL_VIEWPORT_BIT|
744                         GL_TEXTURE_BIT);
745
746                 glColor4f(col[0], col[1], col[2], alpha);
747
748                 glEnable(GL_BLEND);
749
750                 glEnable(GL_LINE_SMOOTH);
751
752                 if (sd->draw_anchored) {
753                         glTranslatef(sd->anchored_initial_mouse[0] - vc.ar->winrct.xmin, sd->anchored_initial_mouse[1] - vc.ar->winrct.ymin, 0.0f);
754                         glutil_draw_lined_arc(0.0, M_PI*2.0, sd->anchored_size, 40);
755                         glTranslatef(-sd->anchored_initial_mouse[0] + vc.ar->winrct.xmin, -sd->anchored_initial_mouse[1] + vc.ar->winrct.xmin, 0.0f);
756                 }
757                 else {
758                         glTranslatef((float)x, (float)y, 0.0f);
759                         glutil_draw_lined_arc(0.0, M_PI*2.0, brush_size(brush), 40);
760                         glTranslatef(-(float)x, -(float)y, 0.0f);
761                 }
762
763                 glPopAttrib();
764         }
765         else {
766                 Paint *paint = paint_get_active(CTX_data_scene(C));
767                 Brush *brush = paint_brush(paint);
768
769                 if(!(paint->flags & PAINT_SHOW_BRUSH))
770                         return;
771
772                 glColor4f(brush->add_col[0], brush->add_col[1], brush->add_col[2], 0.5f);
773                 glEnable(GL_LINE_SMOOTH);
774                 glEnable(GL_BLEND);
775
776                 glTranslatef((float)x, (float)y, 0.0f);
777                 glutil_draw_lined_arc(0.0, M_PI*2.0, brush_size(brush), 40); // XXX: for now use the brushes size instead of potentially using the unified size because the feature has been enabled for sculpt
778                 glTranslatef((float)-x, (float)-y, 0.0f);
779
780                 glDisable(GL_BLEND);
781                 glDisable(GL_LINE_SMOOTH);
782         }
783 }
784
785 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
786 static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
787 {
788         Paint *paint = paint_get_active(CTX_data_scene(C)); // XXX
789         Brush *brush = paint_brush(paint); // XXX
790
791         float mouse[2];
792
793         PointerRNA itemptr;
794
795         float location[3];
796
797         float pressure;
798         int   pen_flip;
799
800         ViewContext vc; // XXX
801
802         PaintStroke *stroke = op->customdata;
803
804         view3d_set_viewcontext(C, &vc); // XXX
805
806         /* Tablet */
807         if(event->custom == EVT_DATA_TABLET) {
808                 wmTabletData *wmtab= event->customdata;
809
810                 pressure = (wmtab->Active != EVT_TABLET_NONE) ? wmtab->Pressure : 1;
811                 pen_flip = (wmtab->Active == EVT_TABLET_ERASER);
812         }
813         else {
814                 pressure = 1;
815                 pen_flip = 0;
816         }
817
818         // XXX: temporary check for sculpt mode until things are more unified
819         if (vc.obact->sculpt) {
820                 float delta[3];
821
822                 brush_jitter_pos(brush, mouse_in, mouse);
823
824                 // XXX: meh, this is round about because brush_jitter_pos isn't written in the best way to be reused here
825                 if (brush->flag & BRUSH_JITTER_PRESSURE) {
826                         sub_v3_v3v3(delta, mouse, mouse_in);
827                         mul_v3_fl(delta, pressure);
828                         add_v3_v3v3(mouse, mouse_in, delta);
829                 }
830         }
831         else
832                 copy_v3_v3(mouse, mouse_in);
833
834         /* XXX: can remove the if statement once all modes have this */
835         if(stroke->get_location)
836                 stroke->get_location(C, stroke, location, mouse);
837         else
838                 zero_v3(location);
839
840         /* Add to stroke */
841         RNA_collection_add(op->ptr, "stroke", &itemptr);
842
843         RNA_float_set_array(&itemptr, "location",     location);
844         RNA_float_set_array(&itemptr, "mouse",        mouse);
845         RNA_boolean_set    (&itemptr, "pen_flip",     pen_flip);
846         RNA_float_set      (&itemptr, "pressure", pressure);
847
848         stroke->last_mouse_position[0] = mouse[0];
849         stroke->last_mouse_position[1] = mouse[1];
850
851         stroke->update_step(C, stroke, &itemptr);
852 }
853
854 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
855 static int paint_smooth_stroke(PaintStroke *stroke, float output[2], wmEvent *event)
856 {
857         output[0] = event->x; 
858         output[1] = event->y;
859
860         if ((stroke->brush->flag & BRUSH_SMOOTH_STROKE) &&  
861             !ELEM4(stroke->brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK) &&
862             !(stroke->brush->flag & BRUSH_ANCHORED) &&
863             !(stroke->brush->flag & BRUSH_RESTORE_MESH))
864         {
865                 float u = stroke->brush->smooth_stroke_factor, v = 1.0 - u;
866                 float dx = stroke->last_mouse_position[0] - event->x, dy = stroke->last_mouse_position[1] - event->y;
867
868                 /* If the mouse is moving within the radius of the last move,
869                    don't update the mouse position. This allows sharp turns. */
870                 if(dx*dx + dy*dy < stroke->brush->smooth_stroke_radius * stroke->brush->smooth_stroke_radius)
871                         return 0;
872
873                 output[0] = event->x * v + stroke->last_mouse_position[0] * u;
874                 output[1] = event->y * v + stroke->last_mouse_position[1] * u;
875         }
876
877         return 1;
878 }
879
880 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
881 static int paint_space_stroke_enabled(Brush *br)
882 {
883         return (br->flag & BRUSH_SPACE) &&
884                !(br->flag & BRUSH_ANCHORED) &&
885                !ELEM4(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK);
886 }
887
888 /* For brushes with stroke spacing enabled, moves mouse in steps
889    towards the final mouse location. */
890 static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const float final_mouse[2])
891 {
892         PaintStroke *stroke = op->customdata;
893         int cnt = 0;
894
895         if(paint_space_stroke_enabled(stroke->brush)) {
896                 float mouse[2];
897                 float vec[2];
898                 float length, scale;
899
900                 copy_v2_v2(mouse, stroke->last_mouse_position);
901                 sub_v2_v2v2(vec, final_mouse, mouse);
902
903                 length = len_v2(vec);
904
905                 if(length > FLT_EPSILON) {
906                         int steps;
907                         int i;
908                         float pressure = 1;
909
910                         // XXX duplicate code
911                         if(event->custom == EVT_DATA_TABLET) {
912                                 wmTabletData *wmtab= event->customdata;
913                                 if(wmtab->Active != EVT_TABLET_NONE)
914                                         pressure = brush_use_size_pressure(stroke->brush) ? wmtab->Pressure : 1;
915                         }
916
917                         scale = (brush_size(stroke->brush)*pressure*stroke->brush->spacing/50.0f) / length;
918                         mul_v2_fl(vec, scale);
919
920                         steps = (int)(1.0f / scale);
921
922                         for(i = 0; i < steps; ++i, ++cnt) {
923                                 add_v2_v2(mouse, vec);
924                                 paint_brush_stroke_add_step(C, op, event, mouse);
925                         }
926                 }
927         }
928
929         return cnt;
930 }
931
932 /**** Public API ****/
933
934 PaintStroke *paint_stroke_new(bContext *C,
935                                   StrokeGetLocation get_location,
936                                   StrokeTestStart test_start,
937                                   StrokeUpdateStep update_step,
938                                   StrokeDone done)
939 {
940         PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
941
942         stroke->brush = paint_brush(paint_get_active(CTX_data_scene(C)));
943         view3d_set_viewcontext(C, &stroke->vc);
944         view3d_get_transformation(stroke->vc.ar, stroke->vc.rv3d, stroke->vc.obact, &stroke->mats);
945
946         stroke->get_location = get_location;
947         stroke->test_start = test_start;
948         stroke->update_step = update_step;
949         stroke->done = done;
950
951         return stroke;
952 }
953
954 void paint_stroke_free(PaintStroke *stroke)
955 {
956         MEM_freeN(stroke);
957 }
958
959 int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
960 {
961         PaintStroke *stroke = op->customdata;
962         float mouse[2];
963         int first= 0;
964
965         if(!stroke->stroke_started) {
966                 stroke->last_mouse_position[0] = event->x;
967                 stroke->last_mouse_position[1] = event->y;
968                 stroke->stroke_started = stroke->test_start(C, op, event);
969
970                 if(stroke->stroke_started) {
971                         stroke->smooth_stroke_cursor =
972                                 WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_stroke, stroke);
973
974                         if(stroke->brush->flag & BRUSH_AIRBRUSH)
975                                 stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
976                 }
977
978                 first= 1;
979                 //ED_region_tag_redraw(ar);
980         }
981
982         /* TODO: fix hardcoded events here */
983         if(event->type == LEFTMOUSE && event->val == KM_RELEASE) {
984                 /* exit stroke, free data */
985                 if(stroke->smooth_stroke_cursor)
986                         WM_paint_cursor_end(CTX_wm_manager(C), stroke->smooth_stroke_cursor);
987
988                 if(stroke->timer)
989                         WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);
990
991                 stroke->done(C, stroke);
992                 MEM_freeN(stroke);
993                 return OPERATOR_FINISHED;
994         }
995         else if(first || ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (event->type == TIMER && (event->customdata == stroke->timer))) {
996                 if(stroke->stroke_started) {
997                         if(paint_smooth_stroke(stroke, mouse, event)) {
998                                 if(paint_space_stroke_enabled(stroke->brush)) {
999                                         if(!paint_space_stroke(C, op, event, mouse)) {
1000                                                 //ED_region_tag_redraw(ar);
1001                                         }
1002                                 }
1003                                 else {
1004                                         paint_brush_stroke_add_step(C, op, event, mouse);
1005                                 }
1006                         }
1007                         else
1008                                 ;//ED_region_tag_redraw(ar);
1009                 }
1010         }
1011
1012         /* we want the stroke to have the first daub at the start location instead of waiting till we have moved the space distance */
1013         if(first &&
1014            stroke->stroke_started &&
1015            paint_space_stroke_enabled(stroke->brush) &&
1016            !(stroke->brush->flag & BRUSH_ANCHORED) &&
1017            !(stroke->brush->flag & BRUSH_SMOOTH_STROKE))
1018         {
1019                 paint_brush_stroke_add_step(C, op, event, mouse);
1020         }
1021         
1022         return OPERATOR_RUNNING_MODAL;
1023 }
1024
1025 int paint_stroke_exec(bContext *C, wmOperator *op)
1026 {
1027         PaintStroke *stroke = op->customdata;
1028
1029         RNA_BEGIN(op->ptr, itemptr, "stroke") {
1030                 stroke->update_step(C, stroke, &itemptr);
1031         }
1032         RNA_END;
1033
1034         MEM_freeN(stroke);
1035         op->customdata = NULL;
1036
1037         return OPERATOR_FINISHED;
1038 }
1039
1040 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
1041 {
1042         return &stroke->vc;
1043 }
1044
1045 void *paint_stroke_mode_data(struct PaintStroke *stroke)
1046 {
1047         return stroke->mode_data;
1048 }
1049
1050 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
1051 {
1052         stroke->mode_data = mode_data;
1053 }
1054
1055 int paint_poll(bContext *C)
1056 {
1057         Paint *p = paint_get_active(CTX_data_scene(C));
1058         Object *ob = CTX_data_active_object(C);
1059
1060         return p && ob && paint_brush(p) &&
1061                 CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
1062                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
1063 }
1064
1065 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
1066 {
1067         Paint *p = paint_get_active(CTX_data_scene(C));
1068
1069         if(p && !p->paint_cursor)
1070                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
1071 }
1072