I made multitude of fixes based on the comments provided online:
[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 /** \file blender/editors/sculpt_paint/paint_stroke.c
30  *  \ingroup edsculpt
31  */
32
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_math.h"
37 #include "BLI_utildefines.h"
38
39 #include "DNA_object_types.h"
40 #include "DNA_scene_types.h"
41 #include "DNA_brush_types.h"
42
43 #include "RNA_access.h"
44
45 #include "BKE_context.h"
46 #include "BKE_paint.h"
47 #include "BKE_brush.h"
48
49 #include "WM_api.h"
50 #include "WM_types.h"
51
52 #include "BIF_gl.h"
53 #include "BIF_glutil.h"
54
55 #include "ED_screen.h"
56 #include "ED_view3d.h"
57
58 #include "paint_intern.h"
59 /* still needed for sculpt_stroke_get_location, should be
60    removed eventually (TODO) */
61 #include "sculpt_intern.h"
62
63 #include <float.h>
64 #include <math.h>
65
66 typedef struct PaintStroke {
67         void *mode_data;
68         void *smooth_stroke_cursor;
69         wmTimer *timer;
70
71         /* Cached values */
72         ViewContext vc;
73         bglMats mats;
74         Brush *brush;
75
76         float last_mouse_position[2];
77
78         /* Set whether any stroke step has yet occurred
79            e.g. in sculpt mode, stroke doesn't start until cursor
80            passes over the mesh */
81         int stroke_started;
82         /* event that started stroke, for modal() return */
83         int event_type;
84         
85         StrokeGetLocation get_location;
86         StrokeTestStart test_start;
87         StrokeUpdateStep update_step;
88         StrokeDone done;
89 } PaintStroke;
90
91 /*** Cursor ***/
92 static void paint_draw_smooth_stroke(bContext *C, int x, int y, void *customdata) 
93 {
94         Brush *brush = paint_brush(paint_get_active(CTX_data_scene(C)));
95         PaintStroke *stroke = customdata;
96
97         glColor4ubv(paint_get_active(CTX_data_scene(C))->paint_cursor_col);
98         glEnable(GL_LINE_SMOOTH);
99         glEnable(GL_BLEND);
100
101         if(stroke && brush && (brush->flag & BRUSH_SMOOTH_STROKE)) {
102                 ARegion *ar = CTX_wm_region(C);
103                 sdrawline(x, y, (int)stroke->last_mouse_position[0] - ar->winrct.xmin,
104                           (int)stroke->last_mouse_position[1] - ar->winrct.ymin);
105         }
106
107         glDisable(GL_BLEND);
108         glDisable(GL_LINE_SMOOTH);
109 }
110
111 typedef struct Snapshot {
112         float size[3];
113         float ofs[3];
114         float rot;
115         int brush_size;
116         int winx;
117         int winy;
118         int brush_map_mode;
119         int curve_changed_timestamp;
120 } Snapshot;
121
122 static int same_snap(Snapshot* snap, Brush* brush, ViewContext* vc)
123 {
124         MTex* mtex = &brush->mtex;
125
126         return 
127                 (mtex->tex &&
128                     mtex->ofs[0] == snap->ofs[0] &&
129                     mtex->ofs[1] == snap->ofs[1] &&
130                     mtex->ofs[2] == snap->ofs[2] &&
131                     mtex->size[0] == snap->size[0] &&
132                     mtex->size[1] == snap->size[1] &&
133                     mtex->size[2] == snap->size[2] &&
134                     mtex->rot == snap->rot) &&
135                 ((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
136                 mtex->brush_map_mode == snap->brush_map_mode &&
137                 vc->ar->winx == snap->winx &&
138                 vc->ar->winy == snap->winy;
139 }
140
141 static void make_snap(Snapshot* snap, Brush* brush, ViewContext* vc)
142 {
143         if (brush->mtex.tex) {
144                 snap->brush_map_mode = brush->mtex.brush_map_mode;
145                 copy_v3_v3(snap->ofs, brush->mtex.ofs);
146                 copy_v3_v3(snap->size, brush->mtex.size);
147                 snap->rot = brush->mtex.rot;
148         }
149         else {
150                 snap->brush_map_mode = -1;
151                 snap->ofs[0]= snap->ofs[1]= snap->ofs[2]= -1;
152                 snap->size[0]= snap->size[1]= snap->size[2]= -1;
153                 snap->rot = -1;
154         }
155
156         snap->brush_size = brush_size(brush);
157         snap->winx = vc->ar->winx;
158         snap->winy = vc->ar->winy;
159 }
160
161 static int load_tex(Sculpt *sd, Brush* br, ViewContext* vc)
162 {
163         static GLuint overlay_texture = 0;
164         static int init = 0;
165         static int tex_changed_timestamp = -1;
166         static int curve_changed_timestamp = -1;
167         static Snapshot snap;
168         static int old_size = -1;
169
170         GLubyte* buffer = NULL;
171
172         int size;
173         int j;
174         int refresh;
175
176 #ifndef _OPENMP
177         (void)sd; /* quied unused warning */
178 #endif
179         
180         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED && !br->mtex.tex) return 0;
181         
182         refresh = 
183                 !overlay_texture ||
184                 (br->mtex.tex && 
185                     (!br->mtex.tex->preview ||
186                       br->mtex.tex->preview->changed_timestamp[0] != tex_changed_timestamp)) ||
187                 !br->curve ||
188                 br->curve->changed_timestamp != curve_changed_timestamp ||
189                 !same_snap(&snap, br, vc);
190
191         if (refresh) {
192                 if (br->mtex.tex && br->mtex.tex->preview)
193                         tex_changed_timestamp = br->mtex.tex->preview->changed_timestamp[0];
194
195                 if (br->curve)
196                         curve_changed_timestamp = br->curve->changed_timestamp;
197
198                 make_snap(&snap, br, vc);
199
200                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
201                         int s = brush_size(br);
202                         int r = 1;
203
204                         for (s >>= 1; s > 0; s >>= 1)
205                                 r++;
206
207                         size = (1<<r);
208
209                         if (size < 256)
210                                 size = 256;
211
212                         if (size < old_size)
213                                 size = old_size;
214                 }
215                 else
216                         size = 512;
217
218                 if (old_size != size) {
219                         if (overlay_texture) {
220                                 glDeleteTextures(1, &overlay_texture);
221                                 overlay_texture = 0;
222                         }
223
224                         init = 0;
225
226                         old_size = size;
227                 }
228
229                 buffer = MEM_mallocN(sizeof(GLubyte)*size*size, "load_tex");
230
231                 #pragma omp parallel for schedule(static) if (sd->flags & SCULPT_USE_OPENMP)
232                 for (j= 0; j < size; j++) {
233                         int i;
234                         float y;
235                         float len;
236
237                         for (i= 0; i < size; i++) {
238
239                                 // largely duplicated from tex_strength
240
241                                 const float rotation = -br->mtex.rot;
242                                 float radius = brush_size(br);
243                                 int index = j*size + i;
244                                 float x;
245                                 float avg;
246
247                                 x = (float)i/size;
248                                 y = (float)j/size;
249
250                                 x -= 0.5f;
251                                 y -= 0.5f;
252
253                                 if (br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) {
254                                         x *= vc->ar->winx / radius;
255                                         y *= vc->ar->winy / radius;
256                                 }
257                                 else {
258                                         x *= 2;
259                                         y *= 2;
260                                 }
261
262                                 len = sqrtf(x*x + y*y);
263
264                                 if ((br->mtex.brush_map_mode == MTEX_MAP_MODE_TILED) || len <= 1) {
265                                         /* it is probably worth optimizing for those cases where 
266                                            the texture is not rotated by skipping the calls to
267                                            atan2, sqrtf, sin, and cos. */
268                                         if (br->mtex.tex && (rotation > 0.001f || rotation < -0.001f)) {
269                                                 const float angle    = atan2f(y, x) + rotation;
270
271                                                 x = len * cosf(angle);
272                                                 y = len * sinf(angle);
273                                         }
274
275                                         x *= br->mtex.size[0];
276                                         y *= br->mtex.size[1];
277
278                                         x += br->mtex.ofs[0];
279                                         y += br->mtex.ofs[1];
280
281                                         avg = br->mtex.tex ? paint_get_tex_pixel(br, x, y) : 1;
282
283                                         avg += br->texture_sample_bias;
284
285                                         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED)
286                                                 avg *= brush_curve_strength(br, len, 1); /* Falloff curve */
287
288                                         buffer[index] = 255 - (GLubyte)(255*avg);
289                                 }
290                                 else {
291                                         buffer[index] = 0;
292                                 }
293                         }
294                 }
295
296                 if (!overlay_texture)
297                         glGenTextures(1, &overlay_texture);
298         }
299         else {
300                 size= old_size;
301         }
302
303         glBindTexture(GL_TEXTURE_2D, overlay_texture);
304
305         if (refresh) {
306                 if (!init) {
307                         glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, size, size, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
308                         init = 1;
309                 }
310                 else {
311                         glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size, size, GL_ALPHA, GL_UNSIGNED_BYTE, buffer);
312                 }
313
314                 if (buffer)
315                         MEM_freeN(buffer);
316         }
317
318         glEnable(GL_TEXTURE_2D);
319
320         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
321         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
322         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
323
324         if (br->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
325                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
326                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
327         }
328
329         return 1;
330 }
331
332 static int project_brush_radius(RegionView3D* rv3d, float radius, float location[3], bglMats* mats)
333 {
334         float view[3], nonortho[3], ortho[3], offset[3], p1[2], p2[2];
335
336         ED_view3d_global_to_vector(rv3d, location, view);
337
338         // create a vector that is not orthogonal to view
339
340         if (fabsf(view[0]) < 0.1f) {
341                 nonortho[0] = view[0] + 1.0f;
342                 nonortho[1] = view[1];
343                 nonortho[2] = view[2];
344         }
345         else if (fabsf(view[1]) < 0.1f) {
346                 nonortho[0] = view[0];
347                 nonortho[1] = view[1] + 1.0f;
348                 nonortho[2] = view[2];
349         }
350         else {
351                 nonortho[0] = view[0];
352                 nonortho[1] = view[1];
353                 nonortho[2] = view[2] + 1.0f;
354         }
355
356         // get a vector in the plane of the view
357         cross_v3_v3v3(ortho, nonortho, view);
358         normalize_v3(ortho);
359
360         // make a point on the surface of the brush tagent to the view
361         mul_v3_fl(ortho, radius);
362         add_v3_v3v3(offset, location, ortho);
363
364         // project the center of the brush, and the tagent point to the view onto the screen
365         projectf(mats, location, p1);
366         projectf(mats, offset, p2);
367
368         // the distance between these points is the size of the projected brush in pixels
369         return len_v2v2(p1, p2);
370 }
371
372 static int sculpt_get_brush_geometry(bContext* C, int x, int y, int* pixel_radius,
373                               float location[3])
374 {
375         struct PaintStroke *stroke;
376         float window[2];
377         int hit;
378
379         stroke = paint_stroke_new(C, NULL, NULL, NULL, NULL, 0);
380
381         window[0] = x + stroke->vc.ar->winrct.xmin;
382         window[1] = y + stroke->vc.ar->winrct.ymin;
383
384         if(stroke->vc.obact->sculpt && stroke->vc.obact->sculpt->pbvh &&
385            sculpt_stroke_get_location(C, stroke, location, window)) {
386                 *pixel_radius = project_brush_radius(stroke->vc.rv3d,
387                                                      brush_unprojected_radius(stroke->brush),
388                                                      location, &stroke->mats);
389
390                 if (*pixel_radius == 0)
391                         *pixel_radius = brush_size(stroke->brush);
392
393                 mul_m4_v3(stroke->vc.obact->obmat, location);
394
395                 hit = 1;
396         }
397         else {
398                 Sculpt* sd    = CTX_data_tool_settings(C)->sculpt;
399                 Brush*  brush = paint_brush(&sd->paint);
400
401                 *pixel_radius = brush_size(brush);
402                 hit = 0;
403         }
404
405         paint_stroke_free(stroke);
406
407         return hit;
408 }
409
410 /* Draw an overlay that shows what effect the brush's texture will
411    have on brush strength */
412 /* TODO: sculpt only for now */
413 static void paint_draw_alpha_overlay(Sculpt *sd, Brush *brush,
414                                      ViewContext *vc, int x, int y)
415 {
416         rctf quad;
417
418         /* check for overlay mode */
419         if(!(brush->flag & BRUSH_TEXTURE_OVERLAY) ||
420            !(ELEM(brush->mtex.brush_map_mode, MTEX_MAP_MODE_FIXED, MTEX_MAP_MODE_TILED)))
421                 return;
422
423         /* save lots of GL state
424            TODO: check on whether all of these are needed? */
425         glPushAttrib(GL_COLOR_BUFFER_BIT|
426                      GL_CURRENT_BIT|
427                      GL_DEPTH_BUFFER_BIT|
428                      GL_ENABLE_BIT|
429                      GL_LINE_BIT|
430                      GL_POLYGON_BIT|
431                      GL_STENCIL_BUFFER_BIT|
432                      GL_TRANSFORM_BIT|
433                      GL_VIEWPORT_BIT|
434                      GL_TEXTURE_BIT);
435
436         if(load_tex(sd, brush, vc)) {
437                 glEnable(GL_BLEND);
438
439                 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
440                 glDepthMask(GL_FALSE);
441                 glDepthFunc(GL_ALWAYS);
442
443                 glMatrixMode(GL_TEXTURE);
444                 glPushMatrix();
445                 glLoadIdentity();
446
447                 if(brush->mtex.brush_map_mode == MTEX_MAP_MODE_FIXED) {
448                         /* brush rotation */
449                         glTranslatef(0.5, 0.5, 0);
450                         glRotatef((double)((brush->flag & BRUSH_RAKE) ?
451                                    sd->last_angle : sd->special_rotation) * (180.0/M_PI),
452                                   0.0, 0.0, 1.0);
453                         glTranslatef(-0.5f, -0.5f, 0);
454
455                         /* scale based on tablet pressure */
456                         if(sd->draw_pressure && brush_use_size_pressure(brush)) {
457                                 glTranslatef(0.5f, 0.5f, 0);
458                                 glScalef(1.0f/sd->pressure_value, 1.0f/sd->pressure_value, 1);
459                                 glTranslatef(-0.5f, -0.5f, 0);
460                         }
461
462                         if(sd->draw_anchored) {
463                                 const float *aim = sd->anchored_initial_mouse;
464                                 const rcti *win = &vc->ar->winrct;
465                                 quad.xmin = aim[0]-sd->anchored_size - win->xmin;
466                                 quad.ymin = aim[1]-sd->anchored_size - win->ymin;
467                                 quad.xmax = aim[0]+sd->anchored_size - win->xmin;
468                                 quad.ymax = aim[1]+sd->anchored_size - win->ymin;
469                         }
470                         else {
471                                 const int radius= brush_size(brush);
472                                 quad.xmin = x - radius;
473                                 quad.ymin = y - radius;
474                                 quad.xmax = x + radius;
475                                 quad.ymax = y + radius;
476                         }
477                 }
478                 else {
479                         quad.xmin = 0;
480                         quad.ymin = 0;
481                         quad.xmax = vc->ar->winrct.xmax - vc->ar->winrct.xmin;
482                         quad.ymax = vc->ar->winrct.ymax - vc->ar->winrct.ymin;
483                 }
484
485                 /* set quad color */
486                 glColor4f(U.sculpt_paint_overlay_col[0],
487                           U.sculpt_paint_overlay_col[1],
488                           U.sculpt_paint_overlay_col[2],
489                           brush->texture_overlay_alpha / 100.0f);
490
491                 /* draw textured quad */
492                 glBegin(GL_QUADS);
493                 glTexCoord2f(0, 0);
494                 glVertex2f(quad.xmin, quad.ymin);
495                 glTexCoord2f(1, 0);
496                 glVertex2f(quad.xmax, quad.ymin);
497                 glTexCoord2f(1, 1);
498                 glVertex2f(quad.xmax, quad.ymax);
499                 glTexCoord2f(0, 1);
500                 glVertex2f(quad.xmin, quad.ymax);
501                 glEnd();
502
503                 glPopMatrix();
504         }
505
506         glPopAttrib();
507 }
508
509 /* Special actions taken when paint cursor goes over mesh */
510 /* TODO: sculpt only for now */
511 static void paint_cursor_on_hit(Sculpt *sd, Brush *brush, ViewContext *vc,
512                                 float location[3], float *visual_strength)
513 {
514         float unprojected_radius, projected_radius;
515
516         /* TODO: check whether this should really only be done when
517            brush is over mesh? */
518         if(sd->draw_pressure && brush_use_alpha_pressure(brush))
519                 (*visual_strength) *= sd->pressure_value;
520
521         if(sd->draw_anchored)
522                 projected_radius = sd->anchored_size;
523         else {
524                 if(brush->flag & BRUSH_ANCHORED)
525                         projected_radius = 8;
526                 else
527                         projected_radius = brush_size(brush);
528         }
529         unprojected_radius = paint_calc_object_space_radius(vc, location,
530                                                             projected_radius);
531
532         if(sd->draw_pressure && brush_use_size_pressure(brush))
533                 unprojected_radius *= sd->pressure_value;
534
535         if(!brush_use_locked_size(brush))
536                 brush_set_unprojected_radius(brush, unprojected_radius);
537 }
538
539 static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
540 {
541         Paint *paint = paint_get_active(CTX_data_scene(C));
542         Brush *brush = paint_brush(paint);
543         ViewContext vc;
544         float final_radius;
545         float translation[2];
546         float outline_alpha, *outline_col;
547         
548         /* set various defaults */
549         translation[0] = x;
550         translation[1] = y;
551         outline_alpha = 0.5;
552         outline_col = brush->add_col;
553         final_radius = brush_size(brush);
554
555         /* check that brush drawing is enabled */
556         if(!(paint->flags & PAINT_SHOW_BRUSH))
557                 return;
558
559         /* can't use stroke vc here because this will be called during
560            mouse over too, not just during a stroke */     
561         view3d_set_viewcontext(C, &vc);
562
563         /* TODO: as sculpt and other paint modes are unified, this
564            special mode of drawing will go away */
565         if(vc.obact->sculpt) {
566                 Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
567                 float location[3];
568                 int pixel_radius, hit;
569                 const float root_alpha = brush_alpha(brush);
570                 float visual_strength = root_alpha*root_alpha;
571                 const float min_alpha = 0.20f;
572                 const float max_alpha = 0.80f;
573
574                 /* this is probably here so that rake takes into
575                    account the brush movements before the stroke
576                    starts, but this doesn't really belong in draw code
577                    (TODO) */
578                 {
579                         const float u = 0.5f;
580                         const float v = 1 - u;
581                         const float r = 20;
582
583                         const float dx = sd->last_x - x;
584                         const float dy = sd->last_y - y;
585
586                         if(dx*dx + dy*dy >= r*r) {
587                                 sd->last_angle = atan2(dx, dy);
588
589                                 sd->last_x = u*sd->last_x + v*x;
590                                 sd->last_y = u*sd->last_y + v*y;
591                         }
592                 }
593
594                 /* test if brush is over the mesh */
595                 hit = sculpt_get_brush_geometry(C, x, y, &pixel_radius, location);
596
597                 /* draw overlay */
598                 paint_draw_alpha_overlay(sd, brush, &vc, x, y);
599
600                 if(brush_use_locked_size(brush))
601                         brush_set_size(brush, pixel_radius);
602
603                 /* check if brush is subtracting, use different color then */
604                 /* TODO: no way currently to know state of pen flip or
605                    invert key modifier without starting a stroke */
606                 if((!(brush->flag & BRUSH_INVERTED) ^
607                     !(brush->flag & BRUSH_DIR_IN)) &&
608                    ELEM5(brush->sculpt_tool, SCULPT_TOOL_DRAW,
609                          SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
610                          SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
611                         outline_col = brush->sub_col;
612
613                 /* only do if brush is over the mesh */
614                 if(hit)
615                         paint_cursor_on_hit(sd, brush, &vc, location, &visual_strength);
616
617                 /* don't show effect of strength past the soft limit */
618                 if(visual_strength > 1)
619                         visual_strength = 1;
620
621                 outline_alpha = ((paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE) ?
622                                  min_alpha + (visual_strength*(max_alpha-min_alpha)) : 0.50f);
623
624                 if(sd->draw_anchored) {
625                         final_radius = sd->anchored_size;
626                         translation[0] = sd->anchored_initial_mouse[0] - vc.ar->winrct.xmin;
627                         translation[1] = sd->anchored_initial_mouse[1] - vc.ar->winrct.ymin;
628                 }
629         }
630
631         /* make lines pretty */
632         glEnable(GL_BLEND);
633         glEnable(GL_LINE_SMOOTH);
634
635         /* set brush color */
636         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
637
638         /* draw brush outline */
639         glTranslatef(translation[0], translation[1], 0);
640         glutil_draw_lined_arc(0.0, M_PI*2.0, final_radius, 40);
641         glTranslatef(-translation[0], -translation[1], 0);
642
643         /* restore GL state */
644         glDisable(GL_BLEND);
645         glDisable(GL_LINE_SMOOTH);
646 }
647
648 /* if this is a tablet event, return tablet pressure and set *pen_flip
649    to 1 if the eraser tool is being used, 0 otherwise */
650 static float event_tablet_data(wmEvent *event, int *pen_flip)
651 {
652         int erasor = 0;
653         float pressure = 1;
654
655         if(event->custom == EVT_DATA_TABLET) {
656                 wmTabletData *wmtab= event->customdata;
657
658                 erasor = (wmtab->Active == EVT_TABLET_ERASER);
659                 pressure = (wmtab->Active != EVT_TABLET_NONE) ? wmtab->Pressure : 1;
660         }
661
662         if(pen_flip)
663                 (*pen_flip) = erasor;
664
665         return pressure;
666 }
667
668 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
669 static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
670 {
671         Paint *paint = paint_get_active(CTX_data_scene(C));
672         Brush *brush = paint_brush(paint);
673         PaintStroke *stroke = op->customdata;
674         float mouse[3];
675         PointerRNA itemptr;
676         float location[3];
677         float pressure;
678         int pen_flip;
679
680         /* see if tablet affects event */
681         pressure = event_tablet_data(event, &pen_flip);
682
683         /* TODO: as sculpt and other paint modes are unified, this
684            separation will go away */
685         if(stroke->vc.obact->sculpt) {
686                 float delta[3];
687
688                 brush_jitter_pos(brush, mouse_in, mouse);
689
690                 /* XXX: meh, this is round about because
691                    brush_jitter_pos isn't written in the best way to
692                    be reused here */
693                 if(brush->flag & BRUSH_JITTER_PRESSURE) {
694                         sub_v3_v3v3(delta, mouse, mouse_in);
695                         mul_v3_fl(delta, pressure);
696                         add_v3_v3v3(mouse, mouse_in, delta);
697                 }
698         }
699         else
700                 copy_v3_v3(mouse, mouse_in);
701
702         /* TODO: can remove the if statement once all modes have this */
703         if(stroke->get_location)
704                 stroke->get_location(C, stroke, location, mouse);
705         else
706                 zero_v3(location);
707
708         /* Add to stroke */
709         RNA_collection_add(op->ptr, "stroke", &itemptr);
710
711         RNA_float_set_array(&itemptr, "location", location);
712         RNA_float_set_array(&itemptr, "mouse", mouse);
713         RNA_boolean_set(&itemptr, "pen_flip", pen_flip);
714         RNA_float_set(&itemptr, "pressure", pressure);
715
716         stroke->last_mouse_position[0] = mouse[0];
717         stroke->last_mouse_position[1] = mouse[1];
718
719         stroke->update_step(C, stroke, &itemptr);
720 }
721
722 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
723 static int paint_smooth_stroke(PaintStroke *stroke, float output[2], wmEvent *event)
724 {
725         output[0] = event->x; 
726         output[1] = event->y;
727
728         if ((stroke->brush->flag & BRUSH_SMOOTH_STROKE) &&  
729             !ELEM4(stroke->brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK) &&
730             !(stroke->brush->flag & BRUSH_ANCHORED) &&
731             !(stroke->brush->flag & BRUSH_RESTORE_MESH))
732         {
733                 float u = stroke->brush->smooth_stroke_factor, v = 1.0f - u;
734                 float dx = stroke->last_mouse_position[0] - event->x, dy = stroke->last_mouse_position[1] - event->y;
735
736                 /* If the mouse is moving within the radius of the last move,
737                    don't update the mouse position. This allows sharp turns. */
738                 if(dx*dx + dy*dy < stroke->brush->smooth_stroke_radius * stroke->brush->smooth_stroke_radius)
739                         return 0;
740
741                 output[0] = event->x * v + stroke->last_mouse_position[0] * u;
742                 output[1] = event->y * v + stroke->last_mouse_position[1] * u;
743         }
744
745         return 1;
746 }
747
748 /* For brushes with stroke spacing enabled, moves mouse in steps
749    towards the final mouse location. */
750 static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const float final_mouse[2])
751 {
752         PaintStroke *stroke = op->customdata;
753         int cnt = 0;
754
755         if(paint_space_stroke_enabled(stroke->brush)) {
756                 float mouse[2];
757                 float vec[2];
758                 float length, scale;
759
760                 copy_v2_v2(mouse, stroke->last_mouse_position);
761                 sub_v2_v2v2(vec, final_mouse, mouse);
762
763                 length = len_v2(vec);
764
765                 if(length > FLT_EPSILON) {
766                         int steps;
767                         int i;
768                         float pressure= 1.0f;
769
770                         /* XXX mysterious :) what has 'use size' do with this here... if you don't check for it, pressure fails */
771                         if(brush_use_size_pressure(stroke->brush))
772                                 pressure = event_tablet_data(event, NULL);
773                         
774                         if(pressure > FLT_EPSILON) {
775                                 scale = (brush_size(stroke->brush)*pressure*stroke->brush->spacing/50.0f) / length;
776                                 if(scale > FLT_EPSILON) {
777                                         mul_v2_fl(vec, scale);
778
779                                         steps = (int)(1.0f / scale);
780
781                                         for(i = 0; i < steps; ++i, ++cnt) {
782                                                 add_v2_v2(mouse, vec);
783                                                 paint_brush_stroke_add_step(C, op, event, mouse);
784                                         }
785                                 }
786                         }
787                 }
788         }
789
790         return cnt;
791 }
792
793 /**** Public API ****/
794
795 PaintStroke *paint_stroke_new(bContext *C,
796                                   StrokeGetLocation get_location,
797                                   StrokeTestStart test_start,
798                                   StrokeUpdateStep update_step,
799                                   StrokeDone done, int event_type)
800 {
801         PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
802
803         stroke->brush = paint_brush(paint_get_active(CTX_data_scene(C)));
804         view3d_set_viewcontext(C, &stroke->vc);
805         view3d_get_transformation(stroke->vc.ar, stroke->vc.rv3d, stroke->vc.obact, &stroke->mats);
806
807         stroke->get_location = get_location;
808         stroke->test_start = test_start;
809         stroke->update_step = update_step;
810         stroke->done = done;
811         stroke->event_type= event_type; /* for modal, return event */
812         
813         return stroke;
814 }
815
816 void paint_stroke_free(PaintStroke *stroke)
817 {
818         MEM_freeN(stroke);
819 }
820
821 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
822 int paint_space_stroke_enabled(Brush *br)
823 {
824         return (br->flag & BRUSH_SPACE) &&
825                !(br->flag & BRUSH_ANCHORED) &&
826                !ELEM4(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK);
827 }
828
829 int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
830 {
831         PaintStroke *stroke = op->customdata;
832         float mouse[2];
833         int first= 0;
834
835         // let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
836         // this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
837         // since the 2D deltas are zero -- code in this file needs to be updated to use the
838         // post-NDOF_MOTION MOUSEMOVE
839         if (event->type == NDOF_MOTION)
840                 return OPERATOR_PASS_THROUGH;
841
842         if(!stroke->stroke_started) {
843                 stroke->last_mouse_position[0] = event->x;
844                 stroke->last_mouse_position[1] = event->y;
845                 stroke->stroke_started = stroke->test_start(C, op, event);
846
847                 if(stroke->stroke_started) {
848                         stroke->smooth_stroke_cursor =
849                                 WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_stroke, stroke);
850
851                         if(stroke->brush->flag & BRUSH_AIRBRUSH)
852                                 stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
853                 }
854
855                 first= 1;
856                 //ED_region_tag_redraw(ar);
857         }
858
859         if(event->type == stroke->event_type && event->val == KM_RELEASE) {
860                 /* exit stroke, free data */
861                 if(stroke->smooth_stroke_cursor)
862                         WM_paint_cursor_end(CTX_wm_manager(C), stroke->smooth_stroke_cursor);
863
864                 if(stroke->timer)
865                         WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);
866
867                 stroke->done(C, stroke);
868                 MEM_freeN(stroke);
869                 return OPERATOR_FINISHED;
870         }
871         else if(first || ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (event->type == TIMER && (event->customdata == stroke->timer))) {
872                 if(stroke->stroke_started) {
873                         if(paint_smooth_stroke(stroke, mouse, event)) {
874                                 if(paint_space_stroke_enabled(stroke->brush)) {
875                                         if(!paint_space_stroke(C, op, event, mouse)) {
876                                                 //ED_region_tag_redraw(ar);
877                                         }
878                                 }
879                                 else {
880                                         paint_brush_stroke_add_step(C, op, event, mouse);
881                                 }
882                         }
883                         else {
884                                 ;//ED_region_tag_redraw(ar);
885                         }
886                 }
887         }
888
889         /* we want the stroke to have the first daub at the start location instead of waiting till we have moved the space distance */
890         if(first &&
891            stroke->stroke_started &&
892            paint_space_stroke_enabled(stroke->brush) &&
893            !(stroke->brush->flag & BRUSH_ANCHORED) &&
894            !(stroke->brush->flag & BRUSH_SMOOTH_STROKE))
895         {
896                 paint_brush_stroke_add_step(C, op, event, mouse);
897         }
898         
899         return OPERATOR_RUNNING_MODAL;
900 }
901
902 int paint_stroke_exec(bContext *C, wmOperator *op)
903 {
904         PaintStroke *stroke = op->customdata;
905
906         /* only when executed for the first time */
907         if(stroke->stroke_started == 0) {
908                 /* XXX stroke->last_mouse_position is unset, this may cause problems */
909                 stroke->test_start(C, op, NULL);
910                 stroke->stroke_started= 1;
911         }
912
913         RNA_BEGIN(op->ptr, itemptr, "stroke") {
914                 stroke->update_step(C, stroke, &itemptr);
915         }
916         RNA_END;
917
918         stroke->done(C, stroke);
919
920         MEM_freeN(stroke);
921         op->customdata = NULL;
922
923         return OPERATOR_FINISHED;
924 }
925
926 int paint_stroke_cancel(bContext *C, wmOperator *op)
927 {
928         PaintStroke *stroke = op->customdata;
929
930         if(stroke->done)
931                 stroke->done(C, stroke);
932
933         MEM_freeN(stroke);
934         op->customdata = NULL;
935
936         return OPERATOR_CANCELLED;
937 }
938
939 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
940 {
941         return &stroke->vc;
942 }
943
944 void *paint_stroke_mode_data(struct PaintStroke *stroke)
945 {
946         return stroke->mode_data;
947 }
948
949 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
950 {
951         stroke->mode_data = mode_data;
952 }
953
954 int paint_poll(bContext *C)
955 {
956         Paint *p = paint_get_active(CTX_data_scene(C));
957         Object *ob = CTX_data_active_object(C);
958
959         return p && ob && paint_brush(p) &&
960                 CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
961                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
962 }
963
964 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
965 {
966         Paint *p = paint_get_active(CTX_data_scene(C));
967
968         if(p && !p->paint_cursor)
969                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
970 }
971