Fix some RNA/scene issuess with unified paint settings.
[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  ( (mtex->tex) &&
127                   equals_v3v3(mtex->ofs, snap->ofs) &&
128                   equals_v3v3(mtex->size, snap->size) &&
129                   mtex->rot == snap->rot
130                   ) &&
131
132                 /* make brush smaller shouldn't cause a resample */
133                 ( (mtex->brush_map_mode == MTEX_MAP_MODE_FIXED && (brush_size(brush) <= snap->brush_size)) ||
134                   (brush_size(brush) == snap->brush_size)) &&
135
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)RAD2DEGF((brush->flag & BRUSH_RAKE) ?
451                                                    sd->last_angle : sd->special_rotation),
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(vc->scene, 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(vc->scene, 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(vc->scene, brush))
533                 unprojected_radius *= sd->pressure_value;
534
535         if(!brush_use_locked_size(vc->scene, 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         Scene *scene = CTX_data_scene(C);
542         Paint *paint = paint_get_active(scene);
543         Brush *brush = paint_brush(paint);
544         ViewContext vc;
545         float final_radius;
546         float translation[2];
547         float outline_alpha, *outline_col;
548         
549         /* set various defaults */
550         translation[0] = x;
551         translation[1] = y;
552         outline_alpha = 0.5;
553         outline_col = brush->add_col;
554         final_radius = brush_size(brush);
555
556         /* check that brush drawing is enabled */
557         if(!(paint->flags & PAINT_SHOW_BRUSH))
558                 return;
559
560         /* can't use stroke vc here because this will be called during
561            mouse over too, not just during a stroke */     
562         view3d_set_viewcontext(C, &vc);
563
564         /* TODO: as sculpt and other paint modes are unified, this
565            special mode of drawing will go away */
566         if(vc.obact->sculpt) {
567                 Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
568                 float location[3];
569                 int pixel_radius, hit;
570                 const float root_alpha = brush_alpha(brush);
571                 float visual_strength = root_alpha*root_alpha;
572                 const float min_alpha = 0.20f;
573                 const float max_alpha = 0.80f;
574
575                 /* this is probably here so that rake takes into
576                    account the brush movements before the stroke
577                    starts, but this doesn't really belong in draw code
578                    (TODO) */
579                 {
580                         const float u = 0.5f;
581                         const float v = 1 - u;
582                         const float r = 20;
583
584                         const float dx = sd->last_x - x;
585                         const float dy = sd->last_y - y;
586
587                         if(dx*dx + dy*dy >= r*r) {
588                                 sd->last_angle = atan2(dx, dy);
589
590                                 sd->last_x = u*sd->last_x + v*x;
591                                 sd->last_y = u*sd->last_y + v*y;
592                         }
593                 }
594
595                 /* test if brush is over the mesh */
596                 hit = sculpt_get_brush_geometry(C, x, y, &pixel_radius, location);
597
598                 /* draw overlay */
599                 paint_draw_alpha_overlay(sd, brush, &vc, x, y);
600
601                 if(brush_use_locked_size(scene, brush))
602                         brush_set_size(brush, pixel_radius);
603
604                 /* check if brush is subtracting, use different color then */
605                 /* TODO: no way currently to know state of pen flip or
606                    invert key modifier without starting a stroke */
607                 if((!(brush->flag & BRUSH_INVERTED) ^
608                     !(brush->flag & BRUSH_DIR_IN)) &&
609                    ELEM5(brush->sculpt_tool, SCULPT_TOOL_DRAW,
610                          SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
611                          SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
612                         outline_col = brush->sub_col;
613
614                 /* only do if brush is over the mesh */
615                 if(hit)
616                         paint_cursor_on_hit(sd, brush, &vc, location, &visual_strength);
617
618                 /* don't show effect of strength past the soft limit */
619                 if(visual_strength > 1)
620                         visual_strength = 1;
621
622                 outline_alpha = ((paint->flags & PAINT_SHOW_BRUSH_ON_SURFACE) ?
623                                      min_alpha + (visual_strength*(max_alpha-min_alpha)) : 0.50f);
624
625                 if(sd->draw_anchored) {
626                         final_radius = sd->anchored_size;
627                         translation[0] = sd->anchored_initial_mouse[0] - vc.ar->winrct.xmin;
628                         translation[1] = sd->anchored_initial_mouse[1] - vc.ar->winrct.ymin;
629                 }
630         }
631
632         /* make lines pretty */
633         glEnable(GL_BLEND);
634         glEnable(GL_LINE_SMOOTH);
635
636         /* set brush color */
637         glColor4f(outline_col[0], outline_col[1], outline_col[2], outline_alpha);
638
639         /* draw brush outline */
640         glTranslatef(translation[0], translation[1], 0);
641         glutil_draw_lined_arc(0.0, M_PI*2.0, final_radius, 40);
642         glTranslatef(-translation[0], -translation[1], 0);
643
644         /* restore GL state */
645         glDisable(GL_BLEND);
646         glDisable(GL_LINE_SMOOTH);
647 }
648
649 /* if this is a tablet event, return tablet pressure and set *pen_flip
650    to 1 if the eraser tool is being used, 0 otherwise */
651 static float event_tablet_data(wmEvent *event, int *pen_flip)
652 {
653         int erasor = 0;
654         float pressure = 1;
655
656         if(event->custom == EVT_DATA_TABLET) {
657                 wmTabletData *wmtab= event->customdata;
658
659                 erasor = (wmtab->Active == EVT_TABLET_ERASER);
660                 pressure = (wmtab->Active != EVT_TABLET_NONE) ? wmtab->Pressure : 1;
661         }
662
663         if(pen_flip)
664                 (*pen_flip) = erasor;
665
666         return pressure;
667 }
668
669 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
670 static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, wmEvent *event, float mouse_in[2])
671 {
672         Paint *paint = paint_get_active(CTX_data_scene(C));
673         Brush *brush = paint_brush(paint);
674         PaintStroke *stroke = op->customdata;
675         float mouse[3];
676         PointerRNA itemptr;
677         float location[3];
678         float pressure;
679         int pen_flip;
680
681         /* see if tablet affects event */
682         pressure = event_tablet_data(event, &pen_flip);
683
684         /* TODO: as sculpt and other paint modes are unified, this
685            separation will go away */
686         if(stroke->vc.obact->sculpt) {
687                 float delta[2];
688
689                 brush_jitter_pos(brush, mouse_in, mouse);
690
691                 /* XXX: meh, this is round about because
692                    brush_jitter_pos isn't written in the best way to
693                    be reused here */
694                 if(brush->flag & BRUSH_JITTER_PRESSURE) {
695                         sub_v2_v2v2(delta, mouse, mouse_in);
696                         mul_v2_fl(delta, pressure);
697                         add_v2_v2v2(mouse, mouse_in, delta);
698                 }
699         }
700         else {
701                 copy_v2_v2(mouse, mouse_in);
702         }
703
704         /* TODO: can remove the if statement once all modes have this */
705         if(stroke->get_location)
706                 stroke->get_location(C, stroke, location, mouse);
707         else
708                 zero_v3(location);
709
710         /* Add to stroke */
711         RNA_collection_add(op->ptr, "stroke", &itemptr);
712
713         RNA_float_set_array(&itemptr, "location", location);
714         RNA_float_set_array(&itemptr, "mouse", mouse);
715         RNA_boolean_set(&itemptr, "pen_flip", pen_flip);
716         RNA_float_set(&itemptr, "pressure", pressure);
717
718         stroke->last_mouse_position[0] = mouse[0];
719         stroke->last_mouse_position[1] = mouse[1];
720
721         stroke->update_step(C, stroke, &itemptr);
722 }
723
724 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
725 static int paint_smooth_stroke(PaintStroke *stroke, float output[2], wmEvent *event)
726 {
727         output[0] = event->x; 
728         output[1] = event->y;
729
730         if ((stroke->brush->flag & BRUSH_SMOOTH_STROKE) &&  
731             !ELEM4(stroke->brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK) &&
732             !(stroke->brush->flag & BRUSH_ANCHORED) &&
733             !(stroke->brush->flag & BRUSH_RESTORE_MESH))
734         {
735                 float u = stroke->brush->smooth_stroke_factor, v = 1.0f - u;
736                 float dx = stroke->last_mouse_position[0] - event->x, dy = stroke->last_mouse_position[1] - event->y;
737
738                 /* If the mouse is moving within the radius of the last move,
739                    don't update the mouse position. This allows sharp turns. */
740                 if(dx*dx + dy*dy < stroke->brush->smooth_stroke_radius * stroke->brush->smooth_stroke_radius)
741                         return 0;
742
743                 output[0] = event->x * v + stroke->last_mouse_position[0] * u;
744                 output[1] = event->y * v + stroke->last_mouse_position[1] * u;
745         }
746
747         return 1;
748 }
749
750 /* For brushes with stroke spacing enabled, moves mouse in steps
751    towards the final mouse location. */
752 static int paint_space_stroke(bContext *C, wmOperator *op, wmEvent *event, const float final_mouse[2])
753 {
754         PaintStroke *stroke = op->customdata;
755         int cnt = 0;
756
757         if(paint_space_stroke_enabled(stroke->brush)) {
758                 float mouse[2];
759                 float vec[2];
760                 float length, scale;
761
762                 copy_v2_v2(mouse, stroke->last_mouse_position);
763                 sub_v2_v2v2(vec, final_mouse, mouse);
764
765                 length = len_v2(vec);
766
767                 if(length > FLT_EPSILON) {
768                         const Scene *scene = CTX_data_scene(C);
769                         int steps;
770                         int i;
771                         float pressure= 1.0f;
772
773                         /* XXX mysterious :) what has 'use size' do with this here... if you don't check for it, pressure fails */
774                         if(brush_use_size_pressure(scene, stroke->brush))
775                                 pressure = event_tablet_data(event, NULL);
776                         
777                         if(pressure > FLT_EPSILON) {
778                                 scale = (brush_size(stroke->brush)*pressure*stroke->brush->spacing/50.0f) / length;
779                                 if(scale > FLT_EPSILON) {
780                                         mul_v2_fl(vec, scale);
781
782                                         steps = (int)(1.0f / scale);
783
784                                         for(i = 0; i < steps; ++i, ++cnt) {
785                                                 add_v2_v2(mouse, vec);
786                                                 paint_brush_stroke_add_step(C, op, event, mouse);
787                                         }
788                                 }
789                         }
790                 }
791         }
792
793         return cnt;
794 }
795
796 /**** Public API ****/
797
798 PaintStroke *paint_stroke_new(bContext *C,
799                                   StrokeGetLocation get_location,
800                                   StrokeTestStart test_start,
801                                   StrokeUpdateStep update_step,
802                                   StrokeDone done, int event_type)
803 {
804         PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
805
806         stroke->brush = paint_brush(paint_get_active(CTX_data_scene(C)));
807         view3d_set_viewcontext(C, &stroke->vc);
808         view3d_get_transformation(stroke->vc.ar, stroke->vc.rv3d, stroke->vc.obact, &stroke->mats);
809
810         stroke->get_location = get_location;
811         stroke->test_start = test_start;
812         stroke->update_step = update_step;
813         stroke->done = done;
814         stroke->event_type= event_type; /* for modal, return event */
815         
816         return stroke;
817 }
818
819 void paint_stroke_free(PaintStroke *stroke)
820 {
821         MEM_freeN(stroke);
822 }
823
824 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
825 int paint_space_stroke_enabled(Brush *br)
826 {
827         return (br->flag & BRUSH_SPACE) &&
828                !(br->flag & BRUSH_ANCHORED) &&
829                !ELEM4(br->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_THUMB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_SNAKE_HOOK);
830 }
831
832 int paint_stroke_modal(bContext *C, wmOperator *op, wmEvent *event)
833 {
834         PaintStroke *stroke = op->customdata;
835         float mouse[2];
836         int first= 0;
837
838         // let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
839         // this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
840         // since the 2D deltas are zero -- code in this file needs to be updated to use the
841         // post-NDOF_MOTION MOUSEMOVE
842         if (event->type == NDOF_MOTION)
843                 return OPERATOR_PASS_THROUGH;
844
845         if(!stroke->stroke_started) {
846                 stroke->last_mouse_position[0] = event->x;
847                 stroke->last_mouse_position[1] = event->y;
848                 stroke->stroke_started = stroke->test_start(C, op, event);
849
850                 if(stroke->stroke_started) {
851                         stroke->smooth_stroke_cursor =
852                                 WM_paint_cursor_activate(CTX_wm_manager(C), paint_poll, paint_draw_smooth_stroke, stroke);
853
854                         if(stroke->brush->flag & BRUSH_AIRBRUSH)
855                                 stroke->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
856                 }
857
858                 first= 1;
859                 //ED_region_tag_redraw(ar);
860         }
861
862         if(event->type == stroke->event_type && event->val == KM_RELEASE) {
863                 /* exit stroke, free data */
864                 if(stroke->smooth_stroke_cursor)
865                         WM_paint_cursor_end(CTX_wm_manager(C), stroke->smooth_stroke_cursor);
866
867                 if(stroke->timer)
868                         WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);
869
870                 stroke->done(C, stroke);
871                 MEM_freeN(stroke);
872                 return OPERATOR_FINISHED;
873         }
874         else if( (first) ||
875                  (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) ||
876                  (event->type == TIMER && (event->customdata == stroke->timer)) )
877         {
878                 if(stroke->stroke_started) {
879                         if(paint_smooth_stroke(stroke, mouse, event)) {
880                                 if(paint_space_stroke_enabled(stroke->brush)) {
881                                         if(!paint_space_stroke(C, op, event, mouse)) {
882                                                 //ED_region_tag_redraw(ar);
883                                         }
884                                 }
885                                 else {
886                                         paint_brush_stroke_add_step(C, op, event, mouse);
887                                 }
888                         }
889                         else {
890                                 ;//ED_region_tag_redraw(ar);
891                         }
892                 }
893         }
894
895         /* we want the stroke to have the first daub at the start location
896          * instead of waiting till we have moved the space distance */
897         if(first &&
898            stroke->stroke_started &&
899            paint_space_stroke_enabled(stroke->brush) &&
900            !(stroke->brush->flag & BRUSH_ANCHORED) &&
901            !(stroke->brush->flag & BRUSH_SMOOTH_STROKE))
902         {
903                 paint_brush_stroke_add_step(C, op, event, mouse);
904         }
905         
906         return OPERATOR_RUNNING_MODAL;
907 }
908
909 int paint_stroke_exec(bContext *C, wmOperator *op)
910 {
911         PaintStroke *stroke = op->customdata;
912
913         /* only when executed for the first time */
914         if(stroke->stroke_started == 0) {
915                 /* XXX stroke->last_mouse_position is unset, this may cause problems */
916                 stroke->test_start(C, op, NULL);
917                 stroke->stroke_started= 1;
918         }
919
920         RNA_BEGIN(op->ptr, itemptr, "stroke") {
921                 stroke->update_step(C, stroke, &itemptr);
922         }
923         RNA_END;
924
925         stroke->done(C, stroke);
926
927         MEM_freeN(stroke);
928         op->customdata = NULL;
929
930         return OPERATOR_FINISHED;
931 }
932
933 int paint_stroke_cancel(bContext *C, wmOperator *op)
934 {
935         PaintStroke *stroke = op->customdata;
936
937         if(stroke->done)
938                 stroke->done(C, stroke);
939
940         MEM_freeN(stroke);
941         op->customdata = NULL;
942
943         return OPERATOR_CANCELLED;
944 }
945
946 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
947 {
948         return &stroke->vc;
949 }
950
951 void *paint_stroke_mode_data(struct PaintStroke *stroke)
952 {
953         return stroke->mode_data;
954 }
955
956 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
957 {
958         stroke->mode_data = mode_data;
959 }
960
961 int paint_poll(bContext *C)
962 {
963         Paint *p = paint_get_active(CTX_data_scene(C));
964         Object *ob = CTX_data_active_object(C);
965
966         return p && ob && paint_brush(p) &&
967                 CTX_wm_area(C)->spacetype == SPACE_VIEW3D &&
968                 CTX_wm_region(C)->regiontype == RGN_TYPE_WINDOW;
969 }
970
971 void paint_cursor_start(bContext *C, int (*poll)(bContext *C))
972 {
973         Paint *p = paint_get_active(CTX_data_scene(C));
974
975         if(p && !p->paint_cursor)
976                 p->paint_cursor = WM_paint_cursor_activate(CTX_wm_manager(C), poll, paint_draw_cursor, NULL);
977 }
978