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