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