Sculpt/Paint: Ignore INBETWEEN_MOUSEMOVE events on certain brush tools
[blender.git] / source / blender / editors / sculpt_paint / paint_stroke.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software  Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2009 by Nicholas Bishop
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup edsculpt
22  */
23
24 #include "MEM_guardedalloc.h"
25
26 #include "BLI_math.h"
27 #include "BLI_utildefines.h"
28 #include "BLI_rand.h"
29 #include "BLI_listbase.h"
30
31 #include "PIL_time.h"
32
33 #include "DNA_object_types.h"
34 #include "DNA_scene_types.h"
35 #include "DNA_brush_types.h"
36 #include "DNA_curve_types.h"
37
38 #include "RNA_access.h"
39
40 #include "BKE_context.h"
41 #include "BKE_paint.h"
42 #include "BKE_brush.h"
43 #include "BKE_curve.h"
44 #include "BKE_colortools.h"
45 #include "BKE_image.h"
46 #include "BKE_mesh.h"
47
48 #include "WM_api.h"
49 #include "WM_types.h"
50
51 #include "GPU_immediate.h"
52 #include "GPU_state.h"
53
54 #include "ED_screen.h"
55 #include "ED_view3d.h"
56
57 #include "IMB_imbuf_types.h"
58
59 #include "paint_intern.h"
60
61 #include <float.h>
62 #include <math.h>
63
64 //#define DEBUG_TIME
65
66 #ifdef DEBUG_TIME
67 #  include "PIL_time_utildefines.h"
68 #endif
69
70 typedef struct PaintSample {
71   float mouse[2];
72   float pressure;
73 } PaintSample;
74
75 typedef struct PaintStroke {
76   void *mode_data;
77   void *stroke_cursor;
78   wmTimer *timer;
79   struct RNG *rng;
80
81   /* Cached values */
82   ViewContext vc;
83   Brush *brush;
84   UnifiedPaintSettings *ups;
85
86   /* used for lines and curves */
87   ListBase line;
88
89   /* Paint stroke can use up to PAINT_MAX_INPUT_SAMPLES prior inputs
90    * to smooth the stroke */
91   PaintSample samples[PAINT_MAX_INPUT_SAMPLES];
92   int num_samples;
93   int cur_sample;
94
95   float last_mouse_position[2];
96   /* space distance covered so far */
97   float stroke_distance;
98
99   /* Set whether any stroke step has yet occurred
100    * e.g. in sculpt mode, stroke doesn't start until cursor
101    * passes over the mesh */
102   bool stroke_started;
103   /* Set when enough motion was found for rake rotation */
104   bool rake_started;
105   /* event that started stroke, for modal() return */
106   int event_type;
107   /* check if stroke variables have been initialized */
108   bool stroke_init;
109   /* check if various brush mapping variables have been initialized */
110   bool brush_init;
111   float initial_mouse[2];
112   /* cached_pressure stores initial pressure for size pressure influence mainly */
113   float cached_size_pressure;
114   /* last pressure will store last pressure value for use in interpolation for space strokes */
115   float last_pressure;
116   int stroke_mode;
117
118   float zoom_2d;
119   int pen_flip;
120
121   /* line constraint */
122   bool constrain_line;
123   float constrained_pos[2];
124
125   StrokeGetLocation get_location;
126   StrokeTestStart test_start;
127   StrokeUpdateStep update_step;
128   StrokeRedraw redraw;
129   StrokeDone done;
130 } PaintStroke;
131
132 /*** Cursors ***/
133 static void paint_draw_smooth_cursor(bContext *C, int x, int y, void *customdata)
134 {
135   Paint *paint = BKE_paint_get_active_from_context(C);
136   Brush *brush = BKE_paint_brush(paint);
137   PaintStroke *stroke = customdata;
138
139   if (stroke && brush) {
140     GPU_line_smooth(true);
141     GPU_blend(true);
142
143     ARegion *ar = stroke->vc.ar;
144
145     uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
146     immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
147     immUniformColor4ubv(paint->paint_cursor_col);
148
149     immBegin(GPU_PRIM_LINES, 2);
150     immVertex2f(pos, x, y);
151     immVertex2f(pos,
152                 stroke->last_mouse_position[0] + ar->winrct.xmin,
153                 stroke->last_mouse_position[1] + ar->winrct.ymin);
154
155     immEnd();
156
157     immUnbindProgram();
158
159     GPU_blend(false);
160     GPU_line_smooth(false);
161   }
162 }
163
164 static void paint_draw_line_cursor(bContext *C, int x, int y, void *customdata)
165 {
166   Paint *paint = BKE_paint_get_active_from_context(C);
167   PaintStroke *stroke = customdata;
168
169   GPU_line_smooth(true);
170
171   uint shdr_pos = GPU_vertformat_attr_add(
172       immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
173
174   immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
175
176   float viewport_size[4];
177   GPU_viewport_size_get_f(viewport_size);
178   immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
179
180   immUniform1i("colors_len", 2); /* "advanced" mode */
181   const float alpha = (float)paint->paint_cursor_col[3] / 255.0f;
182   immUniformArray4fv(
183       "colors", (float *)(float[][4]){{0.0f, 0.0f, 0.0f, alpha}, {1.0f, 1.0f, 1.0f, alpha}}, 2);
184   immUniform1f("dash_width", 6.0f);
185   immUniform1f("dash_factor", 0.5f);
186
187   immBegin(GPU_PRIM_LINES, 2);
188
189   ARegion *ar = stroke->vc.ar;
190
191   if (stroke->constrain_line) {
192     immVertex2f(shdr_pos,
193                 stroke->last_mouse_position[0] + ar->winrct.xmin,
194                 stroke->last_mouse_position[1] + ar->winrct.ymin);
195
196     immVertex2f(shdr_pos,
197                 stroke->constrained_pos[0] + ar->winrct.xmin,
198                 stroke->constrained_pos[1] + ar->winrct.ymin);
199   }
200   else {
201     immVertex2f(shdr_pos,
202                 stroke->last_mouse_position[0] + ar->winrct.xmin,
203                 stroke->last_mouse_position[1] + ar->winrct.ymin);
204
205     immVertex2f(shdr_pos, x, y);
206   }
207
208   immEnd();
209
210   immUnbindProgram();
211
212   GPU_line_smooth(false);
213 }
214
215 static bool paint_tool_require_location(Brush *brush, ePaintMode mode)
216 {
217   switch (mode) {
218     case PAINT_MODE_SCULPT:
219       if (ELEM(brush->sculpt_tool,
220                SCULPT_TOOL_GRAB,
221                SCULPT_TOOL_ROTATE,
222                SCULPT_TOOL_SNAKE_HOOK,
223                SCULPT_TOOL_THUMB)) {
224         return false;
225       }
226       else {
227         return true;
228       }
229     default:
230       break;
231   }
232
233   return true;
234 }
235
236 static bool paint_tool_require_inbetween_mouse_events(Brush *brush, ePaintMode mode)
237 {
238   switch (mode) {
239     case PAINT_MODE_SCULPT:
240       if (ELEM(brush->sculpt_tool, SCULPT_TOOL_GRAB, SCULPT_TOOL_ROTATE, SCULPT_TOOL_THUMB)) {
241         return false;
242       }
243       else {
244         return true;
245       }
246     default:
247       break;
248   }
249
250   return true;
251 }
252
253 /* Initialize the stroke cache variants from operator properties */
254 static bool paint_brush_update(bContext *C,
255                                Brush *brush,
256                                ePaintMode mode,
257                                struct PaintStroke *stroke,
258                                const float mouse_init[2],
259                                float mouse[2],
260                                float pressure,
261                                float r_location[3],
262                                bool *r_location_is_set)
263 {
264   Scene *scene = CTX_data_scene(C);
265   UnifiedPaintSettings *ups = stroke->ups;
266   bool location_sampled = false;
267   bool location_success = false;
268   /* Use to perform all operations except applying the stroke,
269    * needed for operations that require cursor motion (rake). */
270   bool is_dry_run = false;
271   bool do_random = false;
272   bool do_random_mask = false;
273   *r_location_is_set = false;
274   /* XXX: Use pressure value from first brush step for brushes which don't
275    *      support strokes (grab, thumb). They depends on initial state and
276    *      brush coord/pressure/etc.
277    *      It's more an events design issue, which doesn't split coordinate/pressure/angle
278    *      changing events. We should avoid this after events system re-design */
279   if (!stroke->brush_init) {
280     copy_v2_v2(stroke->initial_mouse, mouse);
281     copy_v2_v2(ups->last_rake, mouse);
282     copy_v2_v2(ups->tex_mouse, mouse);
283     copy_v2_v2(ups->mask_tex_mouse, mouse);
284     stroke->cached_size_pressure = pressure;
285
286     ups->do_linear_conversion = false;
287     ups->colorspace = NULL;
288
289     /* check here if color sampling the main brush should do color conversion. This is done here
290      * to avoid locking up to get the image buffer during sampling */
291     if (brush->mtex.tex && brush->mtex.tex->type == TEX_IMAGE && brush->mtex.tex->ima) {
292       ImBuf *tex_ibuf = BKE_image_pool_acquire_ibuf(
293           brush->mtex.tex->ima, &brush->mtex.tex->iuser, NULL);
294       if (tex_ibuf && tex_ibuf->rect_float == NULL) {
295         ups->do_linear_conversion = true;
296         ups->colorspace = tex_ibuf->rect_colorspace;
297       }
298       BKE_image_pool_release_ibuf(brush->mtex.tex->ima, tex_ibuf, NULL);
299     }
300
301     stroke->brush_init = true;
302   }
303
304   if (paint_supports_dynamic_size(brush, mode)) {
305     copy_v2_v2(ups->tex_mouse, mouse);
306     copy_v2_v2(ups->mask_tex_mouse, mouse);
307     stroke->cached_size_pressure = pressure;
308   }
309
310   /* Truly temporary data that isn't stored in properties */
311
312   ups->stroke_active = true;
313   ups->size_pressure_value = stroke->cached_size_pressure;
314
315   ups->pixel_radius = BKE_brush_size_get(scene, brush);
316
317   if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, mode)) {
318     ups->pixel_radius *= stroke->cached_size_pressure;
319   }
320
321   if (paint_supports_dynamic_tex_coords(brush, mode)) {
322
323     if (ELEM(brush->mtex.brush_map_mode,
324              MTEX_MAP_MODE_VIEW,
325              MTEX_MAP_MODE_AREA,
326              MTEX_MAP_MODE_RANDOM)) {
327       do_random = true;
328     }
329
330     if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM) {
331       BKE_brush_randomize_texture_coords(ups, false);
332     }
333     else {
334       copy_v2_v2(ups->tex_mouse, mouse);
335     }
336
337     /* take care of mask texture, if any */
338     if (brush->mask_mtex.tex) {
339
340       if (ELEM(brush->mask_mtex.brush_map_mode,
341                MTEX_MAP_MODE_VIEW,
342                MTEX_MAP_MODE_AREA,
343                MTEX_MAP_MODE_RANDOM)) {
344         do_random_mask = true;
345       }
346
347       if (brush->mask_mtex.brush_map_mode == MTEX_MAP_MODE_RANDOM) {
348         BKE_brush_randomize_texture_coords(ups, true);
349       }
350       else {
351         copy_v2_v2(ups->mask_tex_mouse, mouse);
352       }
353     }
354   }
355
356   if (brush->flag & BRUSH_ANCHORED) {
357     bool hit = false;
358     float halfway[2];
359
360     const float dx = mouse[0] - stroke->initial_mouse[0];
361     const float dy = mouse[1] - stroke->initial_mouse[1];
362
363     ups->anchored_size = ups->pixel_radius = sqrtf(dx * dx + dy * dy);
364
365     ups->brush_rotation = ups->brush_rotation_sec = atan2f(dx, dy) + (float)M_PI;
366
367     if (brush->flag & BRUSH_EDGE_TO_EDGE) {
368       halfway[0] = dx * 0.5f + stroke->initial_mouse[0];
369       halfway[1] = dy * 0.5f + stroke->initial_mouse[1];
370
371       if (stroke->get_location) {
372         if (stroke->get_location(C, r_location, halfway)) {
373           hit = true;
374           location_sampled = true;
375           location_success = true;
376           *r_location_is_set = true;
377         }
378         else if (!paint_tool_require_location(brush, mode)) {
379           hit = true;
380         }
381       }
382       else {
383         hit = true;
384       }
385     }
386     if (hit) {
387       copy_v2_v2(ups->anchored_initial_mouse, halfway);
388       copy_v2_v2(ups->tex_mouse, halfway);
389       copy_v2_v2(ups->mask_tex_mouse, halfway);
390       copy_v2_v2(mouse, halfway);
391       ups->anchored_size /= 2.0f;
392       ups->pixel_radius /= 2.0f;
393       stroke->stroke_distance = ups->pixel_radius;
394     }
395     else {
396       copy_v2_v2(ups->anchored_initial_mouse, stroke->initial_mouse);
397       copy_v2_v2(mouse, stroke->initial_mouse);
398       stroke->stroke_distance = ups->pixel_radius;
399     }
400     ups->pixel_radius /= stroke->zoom_2d;
401     ups->draw_anchored = true;
402   }
403   else {
404     /* here we are using the initial mouse coordinate because we do not want the rake
405      * result to depend on jittering */
406     if (!stroke->brush_init) {
407       copy_v2_v2(ups->last_rake, mouse_init);
408     }
409     /* curve strokes do their own rake calculation */
410     else if (!(brush->flag & BRUSH_CURVE)) {
411       if (!paint_calculate_rake_rotation(ups, brush, mouse_init)) {
412         /* Not enough motion to define an angle. */
413         if (!stroke->rake_started) {
414           is_dry_run = true;
415         }
416       }
417       else {
418         stroke->rake_started = true;
419       }
420     }
421   }
422
423   if ((do_random || do_random_mask) && stroke->rng == NULL) {
424     /* Lazy initialization. */
425     uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
426     rng_seed ^= (uint)POINTER_AS_INT(brush);
427     stroke->rng = BLI_rng_new(rng_seed);
428   }
429
430   if (do_random) {
431     if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) {
432       ups->brush_rotation += -brush->mtex.random_angle / 2.0f +
433                              brush->mtex.random_angle * BLI_rng_get_float(stroke->rng);
434     }
435   }
436
437   if (do_random_mask) {
438     if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RANDOM) {
439       ups->brush_rotation_sec += -brush->mask_mtex.random_angle / 2.0f +
440                                  brush->mask_mtex.random_angle * BLI_rng_get_float(stroke->rng);
441     }
442   }
443
444   if (!location_sampled) {
445     if (stroke->get_location) {
446       if (stroke->get_location(C, r_location, mouse)) {
447         location_success = true;
448         *r_location_is_set = true;
449       }
450       else if (!paint_tool_require_location(brush, mode)) {
451         location_success = true;
452       }
453     }
454     else {
455       zero_v3(r_location);
456       location_success = true;
457       /* don't set 'r_location_is_set', since we don't want to use the value. */
458     }
459   }
460
461   return location_success && (is_dry_run == false);
462 }
463
464 static bool paint_stroke_use_jitter(ePaintMode mode, Brush *brush, bool invert)
465 {
466   bool use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ? (brush->jitter_absolute != 0) :
467                                                             (brush->jitter != 0);
468
469   /* jitter-ed brush gives weird and unpredictable result for this
470    * kinds of stroke, so manually disable jitter usage (sergey) */
471   use_jitter &= (brush->flag & (BRUSH_DRAG_DOT | BRUSH_ANCHORED)) == 0;
472   use_jitter &= (!ELEM(mode, PAINT_MODE_TEXTURE_2D, PAINT_MODE_TEXTURE_3D) ||
473                  !(invert && brush->imagepaint_tool == PAINT_TOOL_CLONE));
474
475   return use_jitter;
476 }
477
478 /* Put the location of the next stroke dot into the stroke RNA and apply it to the mesh */
479 static void paint_brush_stroke_add_step(bContext *C,
480                                         wmOperator *op,
481                                         const float mouse_in[2],
482                                         float pressure)
483 {
484   Scene *scene = CTX_data_scene(C);
485   Paint *paint = BKE_paint_get_active_from_context(C);
486   ePaintMode mode = BKE_paintmode_get_active_from_context(C);
487   Brush *brush = BKE_paint_brush(paint);
488   PaintStroke *stroke = op->customdata;
489   UnifiedPaintSettings *ups = stroke->ups;
490   float mouse_out[2];
491   PointerRNA itemptr;
492   float location[3];
493
494 /* the following code is adapted from texture paint. It may not be needed but leaving here
495  * just in case for reference (code in texpaint removed as part of refactoring).
496  * It's strange that only texpaint had these guards. */
497 #if 0
498   /* special exception here for too high pressure values on first touch in
499    * windows for some tablets, then we just skip first touch ..  */
500   if (tablet && (pressure >= 0.99f) &&
501       ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) ||
502        BKE_brush_use_alpha_pressure(scene, pop->s.brush) ||
503        BKE_brush_use_size_pressure(scene, pop->s.brush))) {
504     return;
505   }
506
507   /* This can be removed once fixed properly in
508    * BKE_brush_painter_paint(
509    *     BrushPainter *painter, BrushFunc func,
510    *     float *pos, double time, float pressure, void *user);
511    * at zero pressure we should do nothing 1/2^12 is 0.0002
512    * which is the sensitivity of the most sensitive pen tablet available */
513   if (tablet && (pressure < 0.0002f) &&
514       ((pop->s.brush->flag & BRUSH_SPACING_PRESSURE) ||
515        BKE_brush_use_alpha_pressure(scene, pop->s.brush) ||
516        BKE_brush_use_size_pressure(scene, pop->s.brush))) {
517     return;
518   }
519 #endif
520
521   /* copy last position -before- jittering, or space fill code
522    * will create too many dabs */
523   copy_v2_v2(stroke->last_mouse_position, mouse_in);
524   stroke->last_pressure = pressure;
525
526   if (paint_stroke_use_jitter(mode, brush, stroke->stroke_mode == BRUSH_STROKE_INVERT)) {
527     float delta[2];
528     float factor = stroke->zoom_2d;
529
530     if (brush->flag & BRUSH_JITTER_PRESSURE) {
531       factor *= pressure;
532     }
533
534     BKE_brush_jitter_pos(scene, brush, mouse_in, mouse_out);
535
536     /* XXX: meh, this is round about because
537      * BKE_brush_jitter_pos isn't written in the best way to
538      * be reused here */
539     if (factor != 1.0f) {
540       sub_v2_v2v2(delta, mouse_out, mouse_in);
541       mul_v2_fl(delta, factor);
542       add_v2_v2v2(mouse_out, mouse_in, delta);
543     }
544   }
545   else {
546     copy_v2_v2(mouse_out, mouse_in);
547   }
548
549   bool is_location_is_set;
550   ups->last_hit = paint_brush_update(
551       C, brush, mode, stroke, mouse_in, mouse_out, pressure, location, &is_location_is_set);
552   if (is_location_is_set) {
553     copy_v3_v3(ups->last_location, location);
554   }
555   if (!ups->last_hit) {
556     return;
557   }
558
559   /* Add to stroke */
560   RNA_collection_add(op->ptr, "stroke", &itemptr);
561   RNA_float_set(&itemptr, "size", ups->pixel_radius);
562   RNA_float_set_array(&itemptr, "location", location);
563   RNA_float_set_array(&itemptr, "mouse", mouse_out);
564   RNA_boolean_set(&itemptr, "pen_flip", stroke->pen_flip);
565   RNA_float_set(&itemptr, "pressure", pressure);
566
567   stroke->update_step(C, stroke, &itemptr);
568
569   /* don't record this for now, it takes up a lot of memory when doing long
570    * strokes with small brush size, and operators have register disabled */
571   RNA_collection_clear(op->ptr, "stroke");
572 }
573
574 /* Returns zero if no sculpt changes should be made, non-zero otherwise */
575 static bool paint_smooth_stroke(PaintStroke *stroke,
576                                 const PaintSample *sample,
577                                 ePaintMode mode,
578                                 float r_mouse[2],
579                                 float *r_pressure)
580 {
581   if (paint_supports_smooth_stroke(stroke->brush, mode)) {
582     float radius = stroke->brush->smooth_stroke_radius * stroke->zoom_2d;
583     float u = stroke->brush->smooth_stroke_factor;
584
585     /* If the mouse is moving within the radius of the last move,
586      * don't update the mouse position. This allows sharp turns. */
587     if (len_squared_v2v2(stroke->last_mouse_position, sample->mouse) < SQUARE(radius)) {
588       return false;
589     }
590
591     interp_v2_v2v2(r_mouse, sample->mouse, stroke->last_mouse_position, u);
592     *r_pressure = interpf(sample->pressure, stroke->last_pressure, u);
593   }
594   else {
595     r_mouse[0] = sample->mouse[0];
596     r_mouse[1] = sample->mouse[1];
597     *r_pressure = sample->pressure;
598   }
599
600   return true;
601 }
602
603 static float paint_space_stroke_spacing(const Scene *scene,
604                                         PaintStroke *stroke,
605                                         float size_pressure,
606                                         float spacing_pressure)
607 {
608   /* brushes can have a minimum size of 1.0 but with pressure it can be smaller then a pixel
609    * causing very high step sizes, hanging blender [#32381] */
610   const float size_clamp = max_ff(1.0f, BKE_brush_size_get(scene, stroke->brush) * size_pressure);
611   float spacing = stroke->brush->spacing;
612
613   /* apply spacing pressure */
614   if (stroke->brush->flag & BRUSH_SPACING_PRESSURE) {
615     spacing = spacing * (1.5f - spacing_pressure);
616   }
617
618   /* stroke system is used for 2d paint too, so we need to account for
619    * the fact that brush can be scaled there. */
620   spacing *= stroke->zoom_2d;
621
622   return max_ff(1.0, size_clamp * spacing / 50.0f);
623 }
624
625 static float paint_stroke_overlapped_curve(Brush *br, float x, float spacing)
626 {
627   int i;
628   const int n = 100 / spacing;
629   const float h = spacing / 50.0f;
630   const float x0 = x - 1;
631
632   float sum;
633
634   sum = 0;
635   for (i = 0; i < n; i++) {
636     float xx;
637
638     xx = fabsf(x0 + i * h);
639
640     if (xx < 1.0f) {
641       sum += BKE_brush_curve_strength(br, xx, 1);
642     }
643   }
644
645   return sum;
646 }
647
648 static float paint_stroke_integrate_overlap(Brush *br, float factor)
649 {
650   int i;
651   int m;
652   float g;
653   float max;
654
655   float spacing = br->spacing * factor;
656
657   if (!(br->flag & BRUSH_SPACE_ATTEN && (br->spacing < 100))) {
658     return 1.0;
659   }
660
661   m = 10;
662   g = 1.0f / m;
663   max = 0;
664   for (i = 0; i < m; i++) {
665     float overlap = fabs(paint_stroke_overlapped_curve(br, i * g, spacing));
666
667     if (overlap > max) {
668       max = overlap;
669     }
670   }
671
672   if (max == 0.0f) {
673     return 1.0f;
674   }
675   else {
676     return 1.0f / max;
677   }
678 }
679
680 static float paint_space_stroke_spacing_variable(
681     const Scene *scene, PaintStroke *stroke, float pressure, float dpressure, float length)
682 {
683   if (BKE_brush_use_size_pressure(scene, stroke->brush)) {
684     /* use pressure to modify size. set spacing so that at 100%, the circles
685      * are aligned nicely with no overlap. for this the spacing needs to be
686      * the average of the previous and next size. */
687     float s = paint_space_stroke_spacing(scene, stroke, 1.0f, pressure);
688     float q = s * dpressure / (2.0f * length);
689     float pressure_fac = (1.0f + q) / (1.0f - q);
690
691     float last_size_pressure = stroke->last_pressure;
692     float new_size_pressure = stroke->last_pressure * pressure_fac;
693
694     /* average spacing */
695     float last_spacing = paint_space_stroke_spacing(scene, stroke, last_size_pressure, pressure);
696     float new_spacing = paint_space_stroke_spacing(scene, stroke, new_size_pressure, pressure);
697
698     return 0.5f * (last_spacing + new_spacing);
699   }
700   else {
701     /* no size pressure */
702     return paint_space_stroke_spacing(scene, stroke, 1.0f, pressure);
703   }
704 }
705
706 /* For brushes with stroke spacing enabled, moves mouse in steps
707  * towards the final mouse location. */
708 static int paint_space_stroke(bContext *C,
709                               wmOperator *op,
710                               const float final_mouse[2],
711                               float final_pressure)
712 {
713   const Scene *scene = CTX_data_scene(C);
714   PaintStroke *stroke = op->customdata;
715   UnifiedPaintSettings *ups = stroke->ups;
716   int cnt = 0;
717
718   float pressure, dpressure;
719   float mouse[2], dmouse[2];
720   float length;
721   float no_pressure_spacing = paint_space_stroke_spacing(scene, stroke, 1.0f, 1.0f);
722
723   sub_v2_v2v2(dmouse, final_mouse, stroke->last_mouse_position);
724
725   pressure = stroke->last_pressure;
726   dpressure = final_pressure - stroke->last_pressure;
727
728   length = normalize_v2(dmouse);
729
730   while (length > 0.0f) {
731     float spacing = paint_space_stroke_spacing_variable(
732         scene, stroke, pressure, dpressure, length);
733
734     if (length >= spacing) {
735       mouse[0] = stroke->last_mouse_position[0] + dmouse[0] * spacing;
736       mouse[1] = stroke->last_mouse_position[1] + dmouse[1] * spacing;
737       pressure = stroke->last_pressure + (spacing / length) * dpressure;
738
739       ups->overlap_factor = paint_stroke_integrate_overlap(stroke->brush,
740                                                            spacing / no_pressure_spacing);
741
742       stroke->stroke_distance += spacing / stroke->zoom_2d;
743       paint_brush_stroke_add_step(C, op, mouse, pressure);
744
745       length -= spacing;
746       pressure = stroke->last_pressure;
747       dpressure = final_pressure - stroke->last_pressure;
748
749       cnt++;
750     }
751     else {
752       break;
753     }
754   }
755
756   return cnt;
757 }
758
759 /**** Public API ****/
760
761 PaintStroke *paint_stroke_new(bContext *C,
762                               wmOperator *op,
763                               StrokeGetLocation get_location,
764                               StrokeTestStart test_start,
765                               StrokeUpdateStep update_step,
766                               StrokeRedraw redraw,
767                               StrokeDone done,
768                               int event_type)
769 {
770   PaintStroke *stroke = MEM_callocN(sizeof(PaintStroke), "PaintStroke");
771   ToolSettings *toolsettings = CTX_data_tool_settings(C);
772   UnifiedPaintSettings *ups = &toolsettings->unified_paint_settings;
773   Paint *p = BKE_paint_get_active_from_context(C);
774   Brush *br = stroke->brush = BKE_paint_brush(p);
775   float zoomx, zoomy;
776
777   ED_view3d_viewcontext_init(C, &stroke->vc);
778
779   stroke->get_location = get_location;
780   stroke->test_start = test_start;
781   stroke->update_step = update_step;
782   stroke->redraw = redraw;
783   stroke->done = done;
784   stroke->event_type = event_type; /* for modal, return event */
785   stroke->ups = ups;
786   stroke->stroke_mode = RNA_enum_get(op->ptr, "mode");
787
788   get_imapaint_zoom(C, &zoomx, &zoomy);
789   stroke->zoom_2d = max_ff(zoomx, zoomy);
790
791   if (stroke->stroke_mode == BRUSH_STROKE_INVERT) {
792     if (br->flag & (BRUSH_CURVE)) {
793       RNA_enum_set(op->ptr, "mode", BRUSH_STROKE_NORMAL);
794     }
795   }
796   /* initialize here */
797   ups->overlap_factor = 1.0;
798   ups->stroke_active = true;
799
800   zero_v3(ups->average_stroke_accum);
801   ups->average_stroke_counter = 0;
802
803   /* initialize here to avoid initialization conflict with threaded strokes */
804   BKE_curvemapping_initialize(br->curve);
805   if (p->flags & PAINT_USE_CAVITY_MASK) {
806     BKE_curvemapping_initialize(p->cavity_curve);
807   }
808
809   BKE_paint_set_overlay_override(br->overlay_flags);
810
811   return stroke;
812 }
813
814 void paint_stroke_data_free(struct wmOperator *op)
815 {
816   BKE_paint_set_overlay_override(0);
817   MEM_SAFE_FREE(op->customdata);
818 }
819
820 static void stroke_done(struct bContext *C, struct wmOperator *op)
821 {
822   struct PaintStroke *stroke = op->customdata;
823   UnifiedPaintSettings *ups = stroke->ups;
824
825   ups->draw_anchored = false;
826   ups->stroke_active = false;
827
828   /* reset rotation here to avoid doing so in cursor display */
829   if (!(stroke->brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
830     ups->brush_rotation = 0.0f;
831   }
832
833   if (!(stroke->brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
834     ups->brush_rotation_sec = 0.0f;
835   }
836
837   if (stroke->stroke_started) {
838     if (stroke->redraw) {
839       stroke->redraw(C, stroke, true);
840     }
841
842     if (stroke->done) {
843       stroke->done(C, stroke);
844     }
845   }
846
847   if (stroke->timer) {
848     WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), stroke->timer);
849   }
850
851   if (stroke->rng) {
852     BLI_rng_free(stroke->rng);
853   }
854
855   if (stroke->stroke_cursor) {
856     WM_paint_cursor_end(CTX_wm_manager(C), stroke->stroke_cursor);
857   }
858
859   BLI_freelistN(&stroke->line);
860
861   paint_stroke_data_free(op);
862 }
863
864 /* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
865 bool paint_space_stroke_enabled(Brush *br, ePaintMode mode)
866 {
867   return (br->flag & BRUSH_SPACE) && paint_supports_dynamic_size(br, mode);
868 }
869
870 static bool sculpt_is_grab_tool(Brush *br)
871 {
872   return ELEM(br->sculpt_tool,
873               SCULPT_TOOL_GRAB,
874               SCULPT_TOOL_THUMB,
875               SCULPT_TOOL_ROTATE,
876               SCULPT_TOOL_SNAKE_HOOK);
877 }
878
879 /* return true if the brush size can change during paint (normally used for pressure) */
880 bool paint_supports_dynamic_size(Brush *br, ePaintMode mode)
881 {
882   if (br->flag & BRUSH_ANCHORED) {
883     return false;
884   }
885
886   switch (mode) {
887     case PAINT_MODE_SCULPT:
888       if (sculpt_is_grab_tool(br)) {
889         return false;
890       }
891       break;
892
893     case PAINT_MODE_TEXTURE_2D: /* fall through */
894     case PAINT_MODE_TEXTURE_3D:
895       if ((br->imagepaint_tool == PAINT_TOOL_FILL) && (br->flag & BRUSH_USE_GRADIENT)) {
896         return false;
897       }
898       break;
899
900     default:
901       break;
902   }
903   return true;
904 }
905
906 bool paint_supports_smooth_stroke(Brush *br, ePaintMode mode)
907 {
908   if (!(br->flag & BRUSH_SMOOTH_STROKE) ||
909       (br->flag & (BRUSH_ANCHORED | BRUSH_DRAG_DOT | BRUSH_LINE))) {
910     return false;
911   }
912
913   switch (mode) {
914     case PAINT_MODE_SCULPT:
915       if (sculpt_is_grab_tool(br)) {
916         return false;
917       }
918       break;
919     default:
920       break;
921   }
922   return true;
923 }
924
925 bool paint_supports_texture(ePaintMode mode)
926 {
927   /* omit: PAINT_WEIGHT, PAINT_SCULPT_UV, PAINT_INVALID */
928   return ELEM(
929       mode, PAINT_MODE_SCULPT, PAINT_MODE_VERTEX, PAINT_MODE_TEXTURE_3D, PAINT_MODE_TEXTURE_2D);
930 }
931
932 /* return true if the brush size can change during paint (normally used for pressure) */
933 bool paint_supports_dynamic_tex_coords(Brush *br, ePaintMode mode)
934 {
935   if (br->flag & BRUSH_ANCHORED) {
936     return false;
937   }
938
939   switch (mode) {
940     case PAINT_MODE_SCULPT:
941       if (sculpt_is_grab_tool(br)) {
942         return false;
943       }
944       break;
945     default:
946       break;
947   }
948   return true;
949 }
950
951 #define PAINT_STROKE_MODAL_CANCEL 1
952
953 /* called in paint_ops.c, on each regeneration of keymaps  */
954 struct wmKeyMap *paint_stroke_modal_keymap(struct wmKeyConfig *keyconf)
955 {
956   static struct EnumPropertyItem modal_items[] = {
957       {PAINT_STROKE_MODAL_CANCEL, "CANCEL", 0, "Cancel", "Cancel and undo a stroke in progress"},
958
959       {0}};
960
961   static const char *name = "Paint Stroke Modal";
962
963   struct wmKeyMap *keymap = WM_modalkeymap_get(keyconf, name);
964
965   /* this function is called for each spacetype, only needs to add map once */
966   if (!keymap) {
967     keymap = WM_modalkeymap_add(keyconf, name, modal_items);
968   }
969
970   return keymap;
971 }
972
973 static void paint_stroke_add_sample(
974     const Paint *paint, PaintStroke *stroke, float x, float y, float pressure)
975 {
976   PaintSample *sample = &stroke->samples[stroke->cur_sample];
977   int max_samples = CLAMPIS(paint->num_input_samples, 1, PAINT_MAX_INPUT_SAMPLES);
978
979   sample->mouse[0] = x;
980   sample->mouse[1] = y;
981   sample->pressure = pressure;
982
983   stroke->cur_sample++;
984   if (stroke->cur_sample >= max_samples) {
985     stroke->cur_sample = 0;
986   }
987   if (stroke->num_samples < max_samples) {
988     stroke->num_samples++;
989   }
990 }
991
992 static void paint_stroke_sample_average(const PaintStroke *stroke, PaintSample *average)
993 {
994   int i;
995
996   memset(average, 0, sizeof(*average));
997
998   BLI_assert(stroke->num_samples > 0);
999
1000   for (i = 0; i < stroke->num_samples; i++) {
1001     add_v2_v2(average->mouse, stroke->samples[i].mouse);
1002     average->pressure += stroke->samples[i].pressure;
1003   }
1004
1005   mul_v2_fl(average->mouse, 1.0f / stroke->num_samples);
1006   average->pressure /= stroke->num_samples;
1007
1008   // printf("avg=(%f, %f), num=%d\n", average->mouse[0], average->mouse[1], stroke->num_samples);
1009 }
1010
1011 /**
1012  * Slightly different version of spacing for line/curve strokes,
1013  * makes sure the dabs stay on the line path.
1014  */
1015 static void paint_line_strokes_spacing(bContext *C,
1016                                        wmOperator *op,
1017                                        PaintStroke *stroke,
1018                                        float spacing,
1019                                        float *length_residue,
1020                                        const float old_pos[2],
1021                                        const float new_pos[2])
1022 {
1023   UnifiedPaintSettings *ups = stroke->ups;
1024
1025   float mouse[2], dmouse[2];
1026   float length;
1027
1028   sub_v2_v2v2(dmouse, new_pos, old_pos);
1029   copy_v2_v2(stroke->last_mouse_position, old_pos);
1030
1031   length = normalize_v2(dmouse);
1032
1033   BLI_assert(length >= 0.0f);
1034
1035   if (length == 0.0f) {
1036     return;
1037   }
1038
1039   while (length > 0.0f) {
1040     float spacing_final = spacing - *length_residue;
1041     length += *length_residue;
1042     *length_residue = 0.0;
1043
1044     if (length >= spacing) {
1045       mouse[0] = stroke->last_mouse_position[0] + dmouse[0] * spacing_final;
1046       mouse[1] = stroke->last_mouse_position[1] + dmouse[1] * spacing_final;
1047
1048       ups->overlap_factor = paint_stroke_integrate_overlap(stroke->brush, 1.0);
1049
1050       stroke->stroke_distance += spacing / stroke->zoom_2d;
1051       paint_brush_stroke_add_step(C, op, mouse, 1.0);
1052
1053       length -= spacing;
1054       spacing_final = spacing;
1055     }
1056     else {
1057       break;
1058     }
1059   }
1060
1061   *length_residue = length;
1062 }
1063
1064 static void paint_stroke_line_end(bContext *C, wmOperator *op, PaintStroke *stroke, float mouse[2])
1065 {
1066   Brush *br = stroke->brush;
1067   if (stroke->stroke_started && (br->flag & BRUSH_LINE)) {
1068     stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
1069
1070     paint_brush_stroke_add_step(C, op, stroke->last_mouse_position, 1.0);
1071     paint_space_stroke(C, op, mouse, 1.0);
1072   }
1073 }
1074
1075 static bool paint_stroke_curve_end(bContext *C, wmOperator *op, PaintStroke *stroke)
1076 {
1077   Brush *br = stroke->brush;
1078
1079   if (br->flag & BRUSH_CURVE) {
1080     UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
1081     const Scene *scene = CTX_data_scene(C);
1082     const float spacing = paint_space_stroke_spacing(scene, stroke, 1.0f, 1.0f);
1083     PaintCurve *pc = br->paint_curve;
1084     PaintCurvePoint *pcp;
1085     float length_residue = 0.0f;
1086     int i;
1087
1088     if (!pc) {
1089       return true;
1090     }
1091
1092 #ifdef DEBUG_TIME
1093     TIMEIT_START_AVERAGED(whole_stroke);
1094 #endif
1095
1096     pcp = pc->points;
1097     stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
1098
1099     for (i = 0; i < pc->tot_points - 1; i++, pcp++) {
1100       int j;
1101       float data[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
1102       float tangents[(PAINT_CURVE_NUM_SEGMENTS + 1) * 2];
1103       PaintCurvePoint *pcp_next = pcp + 1;
1104       bool do_rake = false;
1105
1106       for (j = 0; j < 2; j++) {
1107         BKE_curve_forward_diff_bezier(pcp->bez.vec[1][j],
1108                                       pcp->bez.vec[2][j],
1109                                       pcp_next->bez.vec[0][j],
1110                                       pcp_next->bez.vec[1][j],
1111                                       data + j,
1112                                       PAINT_CURVE_NUM_SEGMENTS,
1113                                       sizeof(float[2]));
1114       }
1115
1116       if ((br->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) ||
1117           (br->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
1118         do_rake = true;
1119         for (j = 0; j < 2; j++) {
1120           BKE_curve_forward_diff_tangent_bezier(pcp->bez.vec[1][j],
1121                                                 pcp->bez.vec[2][j],
1122                                                 pcp_next->bez.vec[0][j],
1123                                                 pcp_next->bez.vec[1][j],
1124                                                 tangents + j,
1125                                                 PAINT_CURVE_NUM_SEGMENTS,
1126                                                 sizeof(float[2]));
1127         }
1128       }
1129
1130       for (j = 0; j < PAINT_CURVE_NUM_SEGMENTS; j++) {
1131         if (do_rake) {
1132           float rotation = atan2f(tangents[2 * j], tangents[2 * j + 1]);
1133           paint_update_brush_rake_rotation(ups, br, rotation);
1134         }
1135
1136         if (!stroke->stroke_started) {
1137           stroke->last_pressure = 1.0;
1138           copy_v2_v2(stroke->last_mouse_position, data + 2 * j);
1139           stroke->stroke_started = stroke->test_start(C, op, stroke->last_mouse_position);
1140
1141           if (stroke->stroke_started) {
1142             paint_brush_stroke_add_step(C, op, data + 2 * j, 1.0);
1143             paint_line_strokes_spacing(
1144                 C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1));
1145           }
1146         }
1147         else {
1148           paint_line_strokes_spacing(
1149               C, op, stroke, spacing, &length_residue, data + 2 * j, data + 2 * (j + 1));
1150         }
1151       }
1152     }
1153
1154     stroke_done(C, op);
1155
1156 #ifdef DEBUG_TIME
1157     TIMEIT_END_AVERAGED(whole_stroke);
1158 #endif
1159
1160     return true;
1161   }
1162
1163   return false;
1164 }
1165
1166 static void paint_stroke_line_constrain(PaintStroke *stroke, float mouse[2])
1167 {
1168   if (stroke->constrain_line) {
1169     float line[2];
1170     float angle, len, res;
1171
1172     sub_v2_v2v2(line, mouse, stroke->last_mouse_position);
1173     angle = atan2f(line[1], line[0]);
1174     len = len_v2(line);
1175
1176     /* divide angle by PI/4 */
1177     angle = 4.0f * angle / (float)M_PI;
1178
1179     /* now take residue */
1180     res = angle - floorf(angle);
1181
1182     /* residue decides how close we are at a certain angle */
1183     if (res <= 0.5f) {
1184       angle = floorf(angle) * (float)M_PI_4;
1185     }
1186     else {
1187       angle = (floorf(angle) + 1.0f) * (float)M_PI_4;
1188     }
1189
1190     mouse[0] = stroke->constrained_pos[0] = len * cosf(angle) + stroke->last_mouse_position[0];
1191     mouse[1] = stroke->constrained_pos[1] = len * sinf(angle) + stroke->last_mouse_position[1];
1192   }
1193 }
1194
1195 int paint_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
1196 {
1197   Paint *p = BKE_paint_get_active_from_context(C);
1198   ePaintMode mode = BKE_paintmode_get_active_from_context(C);
1199   PaintStroke *stroke = op->customdata;
1200   Brush *br = stroke->brush;
1201   PaintSample sample_average;
1202   float mouse[2];
1203   bool first_dab = false;
1204   bool first_modal = false;
1205   bool redraw = false;
1206   float pressure;
1207
1208   if (event->type == INBETWEEN_MOUSEMOVE && !paint_tool_require_inbetween_mouse_events(br, mode)) {
1209     return OPERATOR_RUNNING_MODAL;
1210   }
1211
1212   /* see if tablet affects event. Line, anchored and drag dot strokes do not support pressure */
1213   pressure = ((br->flag & (BRUSH_LINE | BRUSH_ANCHORED | BRUSH_DRAG_DOT)) ?
1214                   1.0f :
1215                   WM_event_tablet_data(event, &stroke->pen_flip, NULL));
1216
1217   paint_stroke_add_sample(p, stroke, event->mval[0], event->mval[1], pressure);
1218   paint_stroke_sample_average(stroke, &sample_average);
1219
1220 #ifdef WITH_INPUT_NDOF
1221   /* let NDOF motion pass through to the 3D view so we can paint and rotate simultaneously!
1222    * this isn't perfect... even when an extra MOUSEMOVE is spoofed, the stroke discards it
1223    * since the 2D deltas are zero -- code in this file needs to be updated to use the
1224    * post-NDOF_MOTION MOUSEMOVE */
1225   if (event->type == NDOF_MOTION) {
1226     return OPERATOR_PASS_THROUGH;
1227   }
1228 #endif
1229
1230   /* one time initialization */
1231   if (!stroke->stroke_init) {
1232     if (paint_stroke_curve_end(C, op, stroke)) {
1233       return OPERATOR_FINISHED;
1234     }
1235
1236     if (paint_supports_smooth_stroke(br, mode)) {
1237       stroke->stroke_cursor = WM_paint_cursor_activate(CTX_wm_manager(C),
1238                                                        SPACE_TYPE_ANY,
1239                                                        RGN_TYPE_ANY,
1240                                                        paint_poll,
1241                                                        paint_draw_smooth_cursor,
1242                                                        stroke);
1243     }
1244
1245     stroke->stroke_init = true;
1246     first_modal = true;
1247   }
1248
1249   /* one time stroke initialization */
1250   if (!stroke->stroke_started) {
1251     stroke->last_pressure = sample_average.pressure;
1252     copy_v2_v2(stroke->last_mouse_position, sample_average.mouse);
1253     stroke->stroke_started = stroke->test_start(C, op, sample_average.mouse);
1254     BLI_assert((stroke->stroke_started & ~1) == 0); /* 0/1 */
1255
1256     if (stroke->stroke_started) {
1257       if (br->flag & BRUSH_AIRBRUSH) {
1258         stroke->timer = WM_event_add_timer(
1259             CTX_wm_manager(C), CTX_wm_window(C), TIMER, stroke->brush->rate);
1260       }
1261
1262       if (br->flag & BRUSH_LINE) {
1263         stroke->stroke_cursor = WM_paint_cursor_activate(CTX_wm_manager(C),
1264                                                          SPACE_TYPE_ANY,
1265                                                          RGN_TYPE_ANY,
1266                                                          paint_poll,
1267                                                          paint_draw_line_cursor,
1268                                                          stroke);
1269       }
1270
1271       first_dab = true;
1272     }
1273   }
1274
1275   /* Cancel */
1276   if (event->type == EVT_MODAL_MAP && event->val == PAINT_STROKE_MODAL_CANCEL) {
1277     if (op->type->cancel) {
1278       op->type->cancel(C, op);
1279     }
1280     else {
1281       paint_stroke_cancel(C, op);
1282     }
1283     return OPERATOR_CANCELLED;
1284   }
1285
1286   if (event->type == stroke->event_type && !first_modal) {
1287     if (event->val == KM_RELEASE) {
1288       copy_v2_fl2(mouse, event->mval[0], event->mval[1]);
1289       paint_stroke_line_constrain(stroke, mouse);
1290       paint_stroke_line_end(C, op, stroke, mouse);
1291       stroke_done(C, op);
1292       return OPERATOR_FINISHED;
1293     }
1294   }
1295   else if (ELEM(event->type, RETKEY, SPACEKEY)) {
1296     paint_stroke_line_end(C, op, stroke, sample_average.mouse);
1297     stroke_done(C, op);
1298     return OPERATOR_FINISHED;
1299   }
1300   else if (br->flag & BRUSH_LINE) {
1301     if (event->alt) {
1302       stroke->constrain_line = true;
1303     }
1304     else {
1305       stroke->constrain_line = false;
1306     }
1307
1308     copy_v2_fl2(mouse, event->mval[0], event->mval[1]);
1309     paint_stroke_line_constrain(stroke, mouse);
1310
1311     if (stroke->stroke_started &&
1312         (first_modal || (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)))) {
1313       if ((br->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) ||
1314           (br->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
1315         copy_v2_v2(stroke->ups->last_rake, stroke->last_mouse_position);
1316       }
1317       paint_calculate_rake_rotation(stroke->ups, br, mouse);
1318     }
1319   }
1320   else if (first_modal ||
1321            /* regular dabs */
1322            (!(br->flag & (BRUSH_AIRBRUSH)) &&
1323             (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE))) ||
1324            /* airbrush */
1325            ((br->flag & BRUSH_AIRBRUSH) && event->type == TIMER &&
1326             event->customdata == stroke->timer)) {
1327     if (paint_smooth_stroke(stroke, &sample_average, mode, mouse, &pressure)) {
1328       if (stroke->stroke_started) {
1329         if (paint_space_stroke_enabled(br, mode)) {
1330           if (paint_space_stroke(C, op, mouse, pressure)) {
1331             redraw = true;
1332           }
1333         }
1334         else {
1335           float dmouse[2];
1336           sub_v2_v2v2(dmouse, mouse, stroke->last_mouse_position);
1337           stroke->stroke_distance += len_v2(dmouse);
1338           paint_brush_stroke_add_step(C, op, mouse, pressure);
1339           redraw = true;
1340         }
1341       }
1342     }
1343   }
1344
1345   /* we want the stroke to have the first daub at the start location
1346    * instead of waiting till we have moved the space distance */
1347   if (first_dab && paint_space_stroke_enabled(br, mode) && !(br->flag & BRUSH_SMOOTH_STROKE)) {
1348     stroke->ups->overlap_factor = paint_stroke_integrate_overlap(br, 1.0);
1349     paint_brush_stroke_add_step(C, op, sample_average.mouse, sample_average.pressure);
1350     redraw = true;
1351   }
1352
1353   /* do updates for redraw. if event is in between mouse-move there are more
1354    * coming, so postpone potentially slow redraw updates until all are done */
1355   if (event->type != INBETWEEN_MOUSEMOVE) {
1356     wmWindow *window = CTX_wm_window(C);
1357     ARegion *ar = CTX_wm_region(C);
1358
1359     /* At the very least, invalidate the cursor */
1360     if (ar && (p->flags & PAINT_SHOW_BRUSH)) {
1361       WM_paint_cursor_tag_redraw(window, ar);
1362     }
1363
1364     if (redraw && stroke->redraw) {
1365       stroke->redraw(C, stroke, false);
1366     }
1367   }
1368
1369   return OPERATOR_RUNNING_MODAL;
1370 }
1371
1372 int paint_stroke_exec(bContext *C, wmOperator *op)
1373 {
1374   PaintStroke *stroke = op->customdata;
1375
1376   /* only when executed for the first time */
1377   if (stroke->stroke_started == 0) {
1378     PropertyRNA *strokeprop;
1379     PointerRNA firstpoint;
1380     float mouse[2];
1381
1382     strokeprop = RNA_struct_find_property(op->ptr, "stroke");
1383
1384     if (RNA_property_collection_lookup_int(op->ptr, strokeprop, 0, &firstpoint)) {
1385       RNA_float_get_array(&firstpoint, "mouse", mouse);
1386       stroke->stroke_started = stroke->test_start(C, op, mouse);
1387     }
1388   }
1389
1390   if (stroke->stroke_started) {
1391     RNA_BEGIN (op->ptr, itemptr, "stroke") {
1392       stroke->update_step(C, stroke, &itemptr);
1393     }
1394     RNA_END;
1395   }
1396
1397   bool ok = (stroke->stroke_started != 0);
1398
1399   stroke_done(C, op);
1400
1401   return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
1402 }
1403
1404 void paint_stroke_cancel(bContext *C, wmOperator *op)
1405 {
1406   stroke_done(C, op);
1407 }
1408
1409 ViewContext *paint_stroke_view_context(PaintStroke *stroke)
1410 {
1411   return &stroke->vc;
1412 }
1413
1414 void *paint_stroke_mode_data(struct PaintStroke *stroke)
1415 {
1416   return stroke->mode_data;
1417 }
1418
1419 bool paint_stroke_flipped(struct PaintStroke *stroke)
1420 {
1421   return stroke->pen_flip;
1422 }
1423
1424 bool paint_stroke_inverted(struct PaintStroke *stroke)
1425 {
1426   return stroke->stroke_mode == BRUSH_STROKE_INVERT;
1427 }
1428
1429 float paint_stroke_distance_get(struct PaintStroke *stroke)
1430 {
1431   return stroke->stroke_distance;
1432 }
1433
1434 void paint_stroke_set_mode_data(PaintStroke *stroke, void *mode_data)
1435 {
1436   stroke->mode_data = mode_data;
1437 }
1438
1439 bool paint_poll(bContext *C)
1440 {
1441   Paint *p = BKE_paint_get_active_from_context(C);
1442   Object *ob = CTX_data_active_object(C);
1443   ScrArea *sa = CTX_wm_area(C);
1444   ARegion *ar = CTX_wm_region(C);
1445
1446   if (p && ob && BKE_paint_brush(p) && (sa && ELEM(sa->spacetype, SPACE_VIEW3D, SPACE_IMAGE)) &&
1447       (ar && ar->regiontype == RGN_TYPE_WINDOW)) {
1448     /* Check the current tool is a brush. */
1449     bToolRef *tref = sa->runtime.tool;
1450     if (tref && tref->runtime && tref->runtime->data_block[0]) {
1451       return true;
1452     }
1453   }
1454   return false;
1455 }