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