Fix T56199: Crash on Annotation in (VSE) Image Preview
[blender.git] / source / blender / editors / gpencil / gpencil_paint.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) 2008, Blender Foundation, Joshua Leung
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung, Antonio Vazquez
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/gpencil_paint.c
27  *  \ingroup edgpencil
28  */
29
30
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_rand.h"
43 #include "BLI_math_geom.h"
44
45 #include "BLT_translation.h"
46
47 #include "PIL_time.h"
48
49 #include "DNA_meshdata_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52 #include "DNA_gpencil_types.h"
53 #include "DNA_material_types.h"
54 #include "DNA_brush_types.h"
55 #include "DNA_windowmanager_types.h"
56
57 #include "BKE_colortools.h"
58 #include "BKE_main.h"
59 #include "BKE_brush.h"
60 #include "BKE_paint.h"
61 #include "BKE_context.h"
62 #include "BKE_global.h"
63 #include "BKE_gpencil.h"
64 #include "BKE_report.h"
65 #include "BKE_layer.h"
66 #include "BKE_material.h"
67 #include "BKE_screen.h"
68 #include "BKE_tracking.h"
69
70 #include "UI_view2d.h"
71
72 #include "ED_gpencil.h"
73 #include "ED_screen.h"
74 #include "ED_object.h"
75 #include "ED_view3d.h"
76 #include "ED_clip.h"
77
78 #include "BIF_glutil.h"
79
80 #include "GPU_immediate.h"
81 #include "GPU_immediate_util.h"
82 #include "GPU_state.h"
83
84 #include "RNA_access.h"
85 #include "RNA_define.h"
86
87 #include "WM_api.h"
88 #include "WM_types.h"
89
90 #include "DEG_depsgraph.h"
91 #include "DEG_depsgraph_query.h"
92
93 #include "gpencil_intern.h"
94
95 /* ******************************************* */
96 /* 'Globals' and Defines */
97
98 /* values for tGPsdata->status */
99 typedef enum eGPencil_PaintStatus {
100         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
101         GP_STATUS_PAINTING,     /* a stroke is in progress */
102         GP_STATUS_ERROR,        /* something wasn't correctly set up */
103         GP_STATUS_DONE          /* painting done */
104 } eGPencil_PaintStatus;
105
106 /* Return flags for adding points to stroke buffer */
107 typedef enum eGP_StrokeAdd_Result {
108         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
109         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
110         GP_STROKEADD_NORMAL,                /* point was successfully added */
111         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
112 } eGP_StrokeAdd_Result;
113
114 /* Runtime flags */
115 typedef enum eGPencil_PaintFlags {
116         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
117         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
118         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
119         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
120         GP_PAINTFLAG_HARD_ERASER    = (1 << 4),
121         GP_PAINTFLAG_STROKE_ERASER  = (1 << 5),
122 } eGPencil_PaintFlags;
123
124
125 /* Temporary 'Stroke' Operation data
126  *   "p" = op->customdata
127  */
128 typedef struct tGPsdata {
129         bContext *C;
130
131         Main *bmain;        /* main database pointer */
132         Scene *scene;       /* current scene from context */
133         struct Depsgraph *depsgraph;
134
135         Object *ob;         /* current object */
136         wmWindow *win;      /* window where painting originated */
137         ScrArea *sa;        /* area where painting originated */
138         ARegion *ar;        /* region where painting originated */
139         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
140         rctf *subrect;      /* for using the camera rect within the 3d view */
141         rctf subrect_data;
142
143         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
144
145         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
146         bGPdata *gpd;       /* gp-datablock layer comes from */
147         bGPDlayer *gpl;     /* layer we're working on */
148         bGPDframe *gpf;     /* frame we're working on */
149
150         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
151
152         eGPencil_PaintStatus status;     /* current status of painting */
153         eGPencil_PaintModes  paintmode;  /* mode for painting */
154         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
155
156         short radius;       /* radius of influence for eraser */
157
158         int mval[2];        /* current mouse-position */
159         int mvalo[2];       /* previous recorded mouse-position */
160
161         float pressure;     /* current stylus pressure */
162         float opressure;    /* previous stylus pressure */
163
164         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
165          * float (and its 7 digits precision) is definitively not enough here!
166          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
167          */
168         double inittime;    /* Used when converting to path */
169         double curtime;     /* Used when converting to path */
170         double ocurtime;    /* Used when converting to path */
171
172         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
173                              * to region space */
174         float mat[4][4];
175
176         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
177
178         void *erasercursor; /* radial cursor data for drawing eraser */
179
180         /* mat settings are only used for 3D view */
181         Material *material;   /* current material */
182
183         Brush *brush;    /* current drawing brush */
184         Brush *eraser;   /* default eraser brush */
185         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
186         int lock_axis;       /* lock drawing to one axis */
187         bool disable_fill;   /* the stroke is no fill mode */
188
189         RNG *rng;
190
191         short keymodifier;   /* key used for invoking the operator */
192         short shift;         /* shift modifier flag */
193
194         float totpixlen;     /* size in pixels for uv calculation */
195
196         ReportList *reports;
197 } tGPsdata;
198
199 /* ------ */
200
201 /* Macros for accessing sensitivity thresholds... */
202 /* minimum number of pixels mouse should move before new point created */
203 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
204 /* minimum length of new segment before new point can be added */
205 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
206
207 static void gp_update_cache(bGPdata *gpd)
208 {
209         if (gpd) {
210                 DEG_id_tag_update(&gpd->id, OB_RECALC_OB | OB_RECALC_DATA);
211                 gpd->flag |= GP_DATA_CACHE_IS_DIRTY;
212         }
213 }
214
215 static bool gp_stroke_added_check(tGPsdata *p)
216 {
217         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
218 }
219
220 static void gp_stroke_added_enable(tGPsdata *p)
221 {
222         BLI_assert(p->gpf->strokes.last != NULL);
223         p->flags |= GP_PAINTFLAG_STROKEADDED;
224
225         /* drawing batch cache is dirty now */
226         gp_update_cache(p->gpd);
227 }
228
229 /* ------ */
230 /* Forward defines for some functions... */
231
232 static void gp_session_validatebuffer(tGPsdata *p);
233
234 /* ******************************************* */
235 /* Context Wrangling... */
236
237 /* check if context is suitable for drawing */
238 static bool gpencil_draw_poll(bContext *C)
239 {
240         if (ED_operator_regionactive(C)) {
241                 ScrArea *sa = CTX_wm_area(C);
242                 if (!ELEM(sa->spacetype, SPACE_VIEW3D)) {
243                         /* check if current context can support GPencil data */
244                         if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
245                                 /* check if Grease Pencil isn't already running */
246                                 if (ED_gpencil_session_active() == 0)
247                                         return 1;
248                                 else
249                                         CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
250                         }
251                         else {
252                                 CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
253                         }
254                         return 0;
255                 }
256                 /* 3D Viewport */
257                 else {
258                         if (ED_gpencil_session_active() == 0) {
259                                 return 1;
260                         }
261                         else {
262                                 return 0;
263                         }
264                 }
265         }
266         else {
267                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
268                 return 0;
269         }
270 }
271
272 /* check if projecting strokes into 3d-geometry in the 3D-View */
273 static bool gpencil_project_check(tGPsdata *p)
274 {
275         bGPdata *gpd = p->gpd;
276         return ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
277 }
278
279 /* ******************************************* */
280 /* Calculations/Conversions */
281
282 /* Utilities --------------------------------- */
283
284 /* get the reference point for stroke-point conversions */
285 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
286 {
287         View3D *v3d = p->sa->spacedata.first;
288         Object *ob = NULL;
289         if (p->ownerPtr.type == &RNA_Object) {
290                 ob = (Object *)p->ownerPtr.data;
291         }
292         ED_gp_get_drawing_reference(v3d, p->scene, ob, p->gpl, *p->align_flag, vec);
293 }
294
295 /* Stroke Editing ---------------------------- */
296 /* check if the current mouse position is suitable for adding a new point */
297 static bool gp_stroke_filtermval(tGPsdata *p, const int mval[2], int pmval[2])
298 {
299         Brush *brush = p->brush;
300         int dx = abs(mval[0] - pmval[0]);
301         int dy = abs(mval[1] - pmval[1]);
302         brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
303
304         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
305         if (p->gpd->runtime.sbuffer_size == 0) {
306                 return true;
307         }
308         /* if lazy mouse, check minimum distance */
309         else if (GPENCIL_LAZY_MODE(brush, p->shift)) {
310                 brush->gpencil_settings->flag |= GP_BRUSH_STABILIZE_MOUSE_TEMP;
311                 if ((dx * dx + dy * dy) > (brush->smooth_stroke_radius * brush->smooth_stroke_radius)) {
312                         return true;
313                 }
314                 else {
315                         /* If the mouse is moving within the radius of the last move,
316                         * don't update the mouse position. This allows sharp turns. */
317                         copy_v2_v2_int(p->mval, p->mvalo);
318                         return false;
319                 }
320         }
321         /* check if mouse moved at least certain distance on both axes (best case)
322          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
323          */
324         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
325                 return true;
326
327         /* check if the distance since the last point is significant enough
328          *      - prevents points being added too densely
329          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
330          */
331         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
332                 return true;
333
334         /* mouse 'didn't move' */
335         else
336                 return false;
337 }
338
339 /* reproject stroke to plane locked to axis in 3d cursor location */
340 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
341 {
342         bGPdata *gpd = p->gpd;
343         Object *obact = (Object *)p->ownerPtr.data;
344
345         float origin[3];
346         RegionView3D *rv3d = p->ar->regiondata;
347
348         /* verify the stroke mode is CURSOR 3d space mode */
349         if ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
350                 return;
351         }
352         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
353                 return;
354         }
355         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
356                 return;
357         }
358
359         /* get drawing origin */
360         gp_get_3d_reference(p, origin);
361         ED_gp_project_stroke_to_plane(obact, rv3d, gps, origin, p->lock_axis - 1);
362 }
363
364 /* convert screen-coordinates to buffer-coordinates */
365 /* XXX this method needs a total overhaul! */
366 static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3], float *depth)
367 {
368         bGPdata *gpd = p->gpd;
369
370         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
371         if (gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) {
372                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
373                         /* projecting onto 3D-Geometry
374                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
375                          */
376                 }
377                 else {
378                         float mval_prj[2];
379                         float rvec[3], dvec[3];
380                         float mval_f[2];
381                         copy_v2fl_v2i(mval_f, mval);
382                         float zfac;
383
384                         /* Current method just converts each point in screen-coordinates to
385                          * 3D-coordinates using the 3D-cursor as reference. In general, this
386                          * works OK, but it could of course be improved.
387                          *
388                          * TODO:
389                          *      - investigate using nearest point(s) on a previous stroke as
390                          *        reference point instead or as offset, for easier stroke matching
391                          */
392
393                         gp_get_3d_reference(p, rvec);
394                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
395
396                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
397                                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
398                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
399                                 sub_v3_v3v3(out, rvec, dvec);
400                         }
401                         else {
402                                 zero_v3(out);
403                         }
404                 }
405         }
406 }
407
408 /* apply jitter to stroke */
409 static void gp_brush_jitter(bGPdata *gpd, Brush *brush, tGPspoint *pt, const int mval[2], int r_mval[2], RNG *rng)
410 {
411         float pressure = pt->pressure;
412         float tmp_pressure = pt->pressure;
413         if (brush->gpencil_settings->draw_jitter > 0.0f) {
414                 float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_jitter, 0, pressure);
415                 tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
416         }
417         const float exfactor = (brush->gpencil_settings->draw_jitter + 2.0f) * (brush->gpencil_settings->draw_jitter + 2.0f); /* exponential value */
418         const float fac = BLI_rng_get_float(rng) * exfactor * tmp_pressure;
419         /* Jitter is applied perpendicular to the mouse movement vector (2D space) */
420         float mvec[2], svec[2];
421         /* mouse movement in ints -> floats */
422         if (gpd->runtime.sbuffer_size > 1) {
423                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
424                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
425                 normalize_v2(mvec);
426         }
427         else {
428                 mvec[0] = 0.0f;
429                 mvec[1] = 0.0f;
430         }
431         /* rotate mvec by 90 degrees... */
432         svec[0] = -mvec[1];
433         svec[1] = mvec[0];
434         /* scale the displacement by the random, and apply */
435         if (BLI_rng_get_float(rng) > 0.5f) {
436                 mul_v2_fl(svec, -fac);
437         }
438         else {
439                 mul_v2_fl(svec, fac);
440         }
441
442         r_mval[0] = mval[0] + svec[0];
443         r_mval[1] = mval[1] + svec[1];
444
445 }
446
447 /* apply pressure change depending of the angle of the stroke to simulate a pen with shape */
448 static void gp_brush_angle(bGPdata *gpd, Brush *brush, tGPspoint *pt, const int mval[2])
449 {
450         float mvec[2];
451         float sen = brush->gpencil_settings->draw_angle_factor; /* sensitivity */;
452         float fac;
453         float mpressure;
454
455         float angle = brush->gpencil_settings->draw_angle; /* default angle of brush in radians */;
456         float v0[2] = { cos(angle), sin(angle) }; /* angle vector of the brush with full thickness */
457
458         /* Apply to first point (only if there are 2 points because before no data to do it ) */
459         if (gpd->runtime.sbuffer_size == 1) {
460                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
461                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
462                 normalize_v2(mvec);
463
464                 /* uses > 1.0f to get a smooth transition in first point */
465                 fac = 1.4f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
466                 (pt - 1)->pressure = (pt - 1)->pressure - (sen * fac);
467
468                 CLAMP((pt - 1)->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
469         }
470
471         /* apply from second point */
472         if (gpd->runtime.sbuffer_size >= 1) {
473                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
474                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
475                 normalize_v2(mvec);
476
477                 fac = 1.0f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
478                 /* interpolate with previous point for smoother transitions */
479                 mpressure = interpf(pt->pressure - (sen * fac), (pt - 1)->pressure, 0.3f);
480                 pt->pressure = mpressure;
481
482                 CLAMP(pt->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
483         }
484
485 }
486
487 /* Apply smooth to buffer while drawing
488 * to smooth point C, use 2 before (A, B) and current point (D):
489 *
490 *   A----B-----C------D
491 *
492 * \param p          Temp data
493 * \param inf    Influence factor
494 * \param idx    Index of the last point (need minimum 3 points in the array)
495 */
496 static void gp_smooth_buffer(tGPsdata *p, float inf, int idx)
497 {
498         bGPdata *gpd = p->gpd;
499         short num_points = gpd->runtime.sbuffer_size;
500
501         /* Do nothing if not enough points to smooth out */
502         if ((num_points < 3) || (idx < 3) || (inf == 0.0f)) {
503                 return;
504         }
505
506         tGPspoint *points = (tGPspoint *)gpd->runtime.sbuffer;
507         float steps = 4.0f;
508         if (idx < 4) {
509                 steps--;
510         }
511
512         tGPspoint *pta = idx >= 4 ? &points[idx - 4] : NULL;
513         tGPspoint *ptb = idx >= 3 ? &points[idx - 3] : NULL;
514         tGPspoint *ptc = idx >= 2 ? &points[idx - 2] : NULL;
515         tGPspoint *ptd = &points[idx - 1];
516
517         float sco[2] = { 0.0f };
518         float a[2], b[2], c[2], d[2];
519         const float average_fac = 1.0f / steps;
520
521         /* Compute smoothed coordinate by taking the ones nearby */
522         if (pta) {
523                 copy_v2fl_v2i(a, &pta->x);
524                 madd_v2_v2fl(sco, a, average_fac);
525         }
526         if (ptb) {
527                 copy_v2fl_v2i(b, &ptb->x);
528                 madd_v2_v2fl(sco, b, average_fac);
529         }
530         if (ptc) {
531                 copy_v2fl_v2i(c, &ptc->x);
532                 madd_v2_v2fl(sco, c, average_fac);
533         }
534         if (ptd) {
535                 copy_v2fl_v2i(d, &ptd->x);
536                 madd_v2_v2fl(sco, d, average_fac);
537         }
538
539         /* Based on influence factor, blend between original and optimal smoothed coordinate */
540         interp_v2_v2v2(c, c, sco, inf);
541         round_v2i_v2fl(&ptc->x, c);
542 }
543
544 /* add current stroke-point to buffer (returns whether point was successfully added) */
545 static short gp_stroke_addpoint(
546         tGPsdata *p, const int mval[2], float pressure, double curtime)
547 {
548         bGPdata *gpd = p->gpd;
549         Brush *brush = p->brush;
550         tGPspoint *pt;
551         ToolSettings *ts = p->scene->toolsettings;
552         Object *obact = (Object *)p->ownerPtr.data;
553         Depsgraph *depsgraph = p->depsgraph;                                      \
554         RegionView3D *rv3d = p->ar->regiondata;
555         View3D *v3d = p->sa->spacedata.first;
556         MaterialGPencilStyle *gp_style = p->material->gp_style;
557
558         /* check painting mode */
559         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
560                 /* straight lines only - i.e. only store start and end point in buffer */
561                 if (gpd->runtime.sbuffer_size == 0) {
562                         /* first point in buffer (start point) */
563                         pt = (tGPspoint *)(gpd->runtime.sbuffer);
564
565                         /* store settings */
566                         copy_v2_v2_int(&pt->x, mval);
567                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
568                         pt->strength = 1.0f;
569                         pt->time = (float)(curtime - p->inittime);
570
571                         /* increment buffer size */
572                         gpd->runtime.sbuffer_size++;
573                 }
574                 else {
575                         /* just reset the endpoint to the latest value
576                          *      - assume that pointers for this are always valid...
577                          */
578                         pt = ((tGPspoint *)(gpd->runtime.sbuffer) + 1);
579
580                         /* store settings */
581                         copy_v2_v2_int(&pt->x, mval);
582                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
583                         pt->strength = 1.0f;
584                         pt->time = (float)(curtime - p->inittime);
585
586                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
587                         gpd->runtime.sbuffer_size = 2;
588                 }
589
590                 /* tag depsgraph to update object */
591                 DEG_id_tag_update(&gpd->id, OB_RECALC_DATA);
592
593                 /* can keep carrying on this way :) */
594                 return GP_STROKEADD_NORMAL;
595         }
596         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
597                 /* check if still room in buffer */
598                 if (gpd->runtime.sbuffer_size >= GP_STROKE_BUFFER_MAX)
599                         return GP_STROKEADD_OVERFLOW;
600
601                 /* get pointer to destination point */
602                 pt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
603
604                 /* store settings */
605                 /* pressure */
606                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE) {
607                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_sensitivity, 0, pressure);
608                         pt->pressure = curvef * brush->gpencil_settings->draw_sensitivity;
609                 }
610                 else {
611                         pt->pressure = 1.0f;
612                 }
613
614                 /* Apply jitter to position */
615                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) && (brush->gpencil_settings->draw_jitter > 0.0f)) {
616                         int r_mval[2];
617                         gp_brush_jitter(gpd, brush, pt, mval, r_mval, p->rng);
618                         copy_v2_v2_int(&pt->x, r_mval);
619                 }
620                 else {
621                         copy_v2_v2_int(&pt->x, mval);
622                 }
623                 /* apply randomness to pressure */
624                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
625                     (brush->gpencil_settings->draw_random_press > 0.0f))
626                 {
627                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_sensitivity, 0, pressure);
628                         float tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
629                         if (BLI_rng_get_float(p->rng) > 0.5f) {
630                                 pt->pressure -= tmp_pressure * brush->gpencil_settings->draw_random_press * BLI_rng_get_float(p->rng);
631                         }
632                         else {
633                                 pt->pressure += tmp_pressure * brush->gpencil_settings->draw_random_press * BLI_rng_get_float(p->rng);
634                         }
635                         CLAMP(pt->pressure, GPENCIL_STRENGTH_MIN, 1.0f);
636                 }
637
638                 /* apply randomness to uv texture rotation */
639                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) && (brush->gpencil_settings->uv_random > 0.0f)) {
640                         if (BLI_rng_get_float(p->rng) > 0.5f) {
641                                 pt->uv_rot = (BLI_rng_get_float(p->rng) * M_PI * -1) * brush->gpencil_settings->uv_random;
642                         }
643                         else {
644                                 pt->uv_rot = (BLI_rng_get_float(p->rng) * M_PI) * brush->gpencil_settings->uv_random;
645                         }
646                         CLAMP(pt->uv_rot, -M_PI_2, M_PI_2);
647                 }
648                 else {
649                         pt->uv_rot = 0.0f;
650                 }
651
652                 /* apply angle of stroke to brush size */
653                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
654                     (brush->gpencil_settings->draw_angle_factor > 0.0f))
655                 {
656                         gp_brush_angle(gpd, brush, pt, mval);
657                 }
658
659                 /* color strength */
660                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
661                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_strength, 0, pressure);
662                         float tmp_pressure = curvef * brush->gpencil_settings->draw_sensitivity;
663
664                         pt->strength = tmp_pressure * brush->gpencil_settings->draw_strength;
665                 }
666                 else {
667                         pt->strength = brush->gpencil_settings->draw_strength;
668                 }
669                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
670
671                 /* apply randomness to color strength */
672                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
673                     (brush->gpencil_settings->draw_random_strength > 0.0f))
674                 {
675                         if (BLI_rng_get_float(p->rng) > 0.5f) {
676                                 pt->strength -= pt->strength * brush->gpencil_settings->draw_random_strength * BLI_rng_get_float(p->rng);
677                         }
678                         else {
679                                 pt->strength += pt->strength * brush->gpencil_settings->draw_random_strength * BLI_rng_get_float(p->rng);
680                         }
681                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
682                 }
683
684                 /* point time */
685                 pt->time = (float)(curtime - p->inittime);
686
687                 /* point uv (only 3d view) */
688                 if ((p->sa->spacetype == SPACE_VIEW3D) && (gpd->runtime.sbuffer_size > 1)) {
689                         float pixsize = gp_style->texture_pixsize / 1000000.0f;
690                         tGPspoint *ptb = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 2;
691                         bGPDspoint spt, spt2;
692
693                         /* get origin to reproject point */
694                         float origin[3];
695                         gp_get_3d_reference(p, origin);
696                         /* reproject current */
697                         ED_gpencil_tpoint_to_point(p->ar, origin, pt, &spt);
698                         ED_gp_project_point_to_plane(obact, rv3d, origin, ts->gp_sculpt.lock_axis - 1, &spt);
699
700                         /* reproject previous */
701                         ED_gpencil_tpoint_to_point(p->ar, origin, ptb, &spt2);
702                         ED_gp_project_point_to_plane(obact, rv3d, origin, ts->gp_sculpt.lock_axis - 1, &spt2);
703
704                         p->totpixlen += len_v3v3(&spt.x, &spt2.x) / pixsize;
705                         pt->uv_fac = p->totpixlen;
706                         if ((gp_style) && (gp_style->sima)) {
707                                 pt->uv_fac /= gp_style->sima->gen_x;
708                         }
709                 }
710                 else {
711                         p->totpixlen = 0.0f;
712                         pt->uv_fac = 0.0f;
713                 }
714
715                 /* increment counters */
716                 gpd->runtime.sbuffer_size++;
717
718                 /* smooth while drawing previous points with a reduction factor for previous */
719                 if (brush->gpencil_settings->active_smooth > 0.0f) {
720                         for (int s = 0; s < 3; s++) {
721                                 gp_smooth_buffer(p, brush->gpencil_settings->active_smooth * ((3.0f - s) / 3.0f), gpd->runtime.sbuffer_size - s);
722                         }
723                 }
724
725                 /* tag depsgraph to update object */
726                 DEG_id_tag_update(&gpd->id, OB_RECALC_DATA);
727
728                 /* check if another operation can still occur */
729                 if (gpd->runtime.sbuffer_size == GP_STROKE_BUFFER_MAX)
730                         return GP_STROKEADD_FULL;
731                 else
732                         return GP_STROKEADD_NORMAL;
733         }
734         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
735
736                 bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
737                 /* get pointer to destination point */
738                 pt = (tGPspoint *)(gpd->runtime.sbuffer);
739
740                 /* store settings */
741                 copy_v2_v2_int(&pt->x, mval);
742                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
743                 pt->strength = 1.0f;
744                 pt->time = (float)(curtime - p->inittime);
745
746                 /* if there's stroke for this poly line session add (or replace last) point
747                  * to stroke. This allows to draw lines more interactively (see new segment
748                  * during mouse slide, e.g.)
749                  */
750                 if (gp_stroke_added_check(p)) {
751                         bGPDstroke *gps = p->gpf->strokes.last;
752                         bGPDspoint *pts;
753                         MDeformVert *dvert;
754
755                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
756                         if (gpd->runtime.sbuffer_size == 0) {
757                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
758                                 gps->dvert = MEM_reallocN(gps->dvert, sizeof(MDeformVert) * (gps->totpoints + 1));
759                                 gps->totpoints++;
760                         }
761
762                         pts = &gps->points[gps->totpoints - 1];
763                         dvert = &gps->dvert[gps->totpoints - 1];
764
765                         /* special case for poly lines: normally,
766                          * depth is needed only when creating new stroke from buffer,
767                          * but poly lines are converting to stroke instantly,
768                          * so initialize depth buffer before converting coordinates
769                          */
770                         if (gpencil_project_check(p)) {
771                                 view3d_region_operator_needs_opengl(p->win, p->ar);
772                                 ED_view3d_autodist_init(
773                                         p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
774                         }
775
776                         /* convert screen-coordinates to appropriate coordinates (and store them) */
777                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
778                         /* reproject to plane (only in 3d space) */
779                         gp_reproject_toplane(p, gps);
780                         /* if parented change position relative to parent object */
781                         gp_apply_parent_point(depsgraph, obact, gpd, gpl, pts);
782                         /* copy pressure and time */
783                         pts->pressure = pt->pressure;
784                         pts->strength = pt->strength;
785                         pts->time = pt->time;
786                         pts->uv_fac = pt->uv_fac;
787                         pts->uv_rot = pt->uv_rot;
788
789                         dvert->totweight = 0;
790                         dvert->dw = NULL;
791
792                         /* force fill recalc */
793                         gps->flag |= GP_STROKE_RECALC_CACHES;
794                         /* drawing batch cache is dirty now */
795                         gp_update_cache(p->gpd);
796                 }
797
798                 /* increment counters */
799                 if (gpd->runtime.sbuffer_size == 0)
800                         gpd->runtime.sbuffer_size++;
801
802                 /* tag depsgraph to update object */
803                 DEG_id_tag_update(&gpd->id, OB_RECALC_DATA);
804
805                 return GP_STROKEADD_NORMAL;
806         }
807
808         /* return invalid state for now... */
809         return GP_STROKEADD_INVALID;
810 }
811
812 /* simplify a stroke (in buffer) before storing it
813  *      - applies a reverse Chaikin filter
814  *      - code adapted from etch-a-ton branch
815  */
816 static void gp_stroke_simplify(tGPsdata *p)
817 {
818         bGPdata *gpd = p->gpd;
819         tGPspoint *old_points = (tGPspoint *)gpd->runtime.sbuffer;
820         short num_points = gpd->runtime.sbuffer_size;
821         short flag = gpd->runtime.sbuffer_sflag;
822         short i, j;
823
824         /* only simplify if simplification is enabled, and we're not doing a straight line */
825         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
826                 return;
827
828         /* don't simplify if less than 4 points in buffer */
829         if ((num_points <= 4) || (old_points == NULL))
830                 return;
831
832         /* clear buffer (but don't free mem yet) so that we can write to it
833          *      - firstly set sbuffer to NULL, so a new one is allocated
834          *      - secondly, reset flag after, as it gets cleared auto
835          */
836         gpd->runtime.sbuffer = NULL;
837         gp_session_validatebuffer(p);
838         gpd->runtime.sbuffer_sflag = flag;
839
840 /* macro used in loop to get position of new point
841  *      - used due to the mixture of datatypes in use here
842  */
843 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
844         { \
845                 co[0] += (float)(old_points[offs].x * sfac); \
846                 co[1] += (float)(old_points[offs].y * sfac); \
847                 pressure += old_points[offs].pressure * sfac; \
848                 time += old_points[offs].time * sfac; \
849         } (void)0
850
851         /* XXX Here too, do not lose start and end points! */
852         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
853         for (i = 0, j = 0; i < num_points; i++) {
854                 if (i - j == 3) {
855                         float co[2], pressure, time;
856                         int mco[2];
857
858                         /* initialize values */
859                         co[0] = 0.0f;
860                         co[1] = 0.0f;
861                         pressure = 0.0f;
862                         time = 0.0f;
863
864                         /* using macro, calculate new point */
865                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
866                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
867                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
868                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
869
870                         /* set values for adding */
871                         mco[0] = (int)co[0];
872                         mco[1] = (int)co[1];
873
874                         /* ignore return values on this... assume to be ok for now */
875                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
876
877                         j += 2;
878                 }
879         }
880         gp_stroke_addpoint(p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
881                            p->inittime + (double)old_points[num_points - 1].time);
882
883         /* free old buffer */
884         MEM_freeN(old_points);
885 }
886
887 /* make a new stroke from the buffer data */
888 static void gp_stroke_newfrombuffer(tGPsdata *p)
889 {
890         bGPdata *gpd = p->gpd;
891         bGPDlayer *gpl = p->gpl;
892         bGPDstroke *gps;
893         bGPDspoint *pt;
894         tGPspoint *ptc;
895         MDeformVert *dvert;
896         Brush *brush = p->brush;
897         ToolSettings *ts = p->scene->toolsettings;
898         Depsgraph *depsgraph = p->depsgraph;
899         Object *obact = (Object *)p->ownerPtr.data;
900
901         int i, totelem;
902         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
903         int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
904
905         /* get total number of points to allocate space for
906          *      - drawing straight-lines only requires the endpoints
907          */
908         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
909                 totelem = (gpd->runtime.sbuffer_size >= 2) ? 2 : gpd->runtime.sbuffer_size;
910         else
911                 totelem = gpd->runtime.sbuffer_size;
912
913         /* exit with error if no valid points from this stroke */
914         if (totelem == 0) {
915                 if (G.debug & G_DEBUG)
916                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->runtime.sbuffer_size);
917                 return;
918         }
919
920         /* special case for poly line -- for already added stroke during session
921          * coordinates are getting added to stroke immediately to allow more
922          * interactive behavior
923          */
924         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
925                 /* be sure to hide any lazy cursor */
926                 ED_gpencil_toggle_brush_cursor(p->C, true, NULL);
927
928                 if (gp_stroke_added_check(p)) {
929                         return;
930                 }
931         }
932
933         /* allocate memory for a new stroke */
934         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
935
936         /* copy appropriate settings for stroke */
937         gps->totpoints = totelem;
938         gps->thickness = brush->size;
939         gps->flag = gpd->runtime.sbuffer_sflag;
940         gps->inittime = p->inittime;
941
942         /* enable recalculation flag by default (only used if hq fill) */
943         gps->flag |= GP_STROKE_RECALC_CACHES;
944
945         /* allocate enough memory for a continuous array for storage points */
946         const int subdivide = brush->gpencil_settings->draw_subdivide;
947
948         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
949         gps->dvert = MEM_callocN(sizeof(MDeformVert) * gps->totpoints, "gp_stroke_weights");
950
951         /* initialize triangle memory to dummy data */
952         gps->triangles = MEM_callocN(sizeof(bGPDtriangle), "GP Stroke triangulation");
953         gps->flag |= GP_STROKE_RECALC_CACHES;
954         gps->tot_triangles = 0;
955         /* drawing batch cache is dirty now */
956         gp_update_cache(p->gpd);
957         /* set pointer to first non-initialized point */
958         pt = gps->points + (gps->totpoints - totelem);
959         dvert = gps->dvert + (gps->totpoints - totelem);
960
961         /* copy points from the buffer to the stroke */
962         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
963                 /* straight lines only -> only endpoints */
964                 {
965                         /* first point */
966                         ptc = gpd->runtime.sbuffer;
967
968                         /* convert screen-coordinates to appropriate coordinates (and store them) */
969                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
970                         /* copy pressure and time */
971                         pt->pressure = ptc->pressure;
972                         pt->strength = ptc->strength;
973                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
974                         pt->time = ptc->time;
975
976                         dvert->totweight = 0;
977                         dvert->dw = NULL;
978
979                         pt++;
980                         dvert++;
981                 }
982
983                 if (totelem == 2) {
984                         /* last point if applicable */
985                         ptc = ((tGPspoint *)gpd->runtime.sbuffer) + (gpd->runtime.sbuffer_size - 1);
986
987                         /* convert screen-coordinates to appropriate coordinates (and store them) */
988                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
989                         /* copy pressure and time */
990                         pt->pressure = ptc->pressure;
991                         pt->strength = ptc->strength;
992                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
993                         pt->time = ptc->time;
994
995                         dvert->totweight = 0;
996                         dvert->dw = NULL;
997                 }
998
999                 /* reproject to plane (only in 3d space) */
1000                 gp_reproject_toplane(p, gps);
1001                 pt = gps->points;
1002                 for (i = 0; i < gps->totpoints; i++, pt++) {
1003                         /* if parented change position relative to parent object */
1004                         gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
1005                 }
1006         }
1007         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
1008                 /* first point */
1009                 ptc = gpd->runtime.sbuffer;
1010
1011                 /* convert screen-coordinates to appropriate coordinates (and store them) */
1012                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
1013                 /* reproject to plane (only in 3d space) */
1014                 gp_reproject_toplane(p, gps);
1015                 /* if parented change position relative to parent object */
1016                 gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
1017                 /* copy pressure and time */
1018                 pt->pressure = ptc->pressure;
1019                 pt->strength = ptc->strength;
1020                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1021                 pt->time = ptc->time;
1022
1023                 dvert->totweight = 0;
1024                 dvert->dw = NULL;
1025
1026         }
1027         else {
1028                 float *depth_arr = NULL;
1029
1030                 /* get an array of depths, far depths are blended */
1031                 if (gpencil_project_check(p)) {
1032                         int mval[2], mval_prev[2] = { 0 };
1033                         int interp_depth = 0;
1034                         int found_depth = 0;
1035
1036                         depth_arr = MEM_mallocN(sizeof(float) * gpd->runtime.sbuffer_size, "depth_points");
1037
1038                         for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size; i++, ptc++, pt++) {
1039                                 copy_v2_v2_int(mval, &ptc->x);
1040
1041                                 if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
1042                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
1043                                 {
1044                                         interp_depth = true;
1045                                 }
1046                                 else {
1047                                         found_depth = true;
1048                                 }
1049
1050                                 copy_v2_v2_int(mval_prev, mval);
1051                         }
1052
1053                         if (found_depth == false) {
1054                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
1055                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--)
1056                                         depth_arr[i] = 0.9999f;
1057                         }
1058                         else {
1059                                 if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
1060                                         /* remove all info between the valid endpoints */
1061                                         int first_valid = 0;
1062                                         int last_valid = 0;
1063
1064                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
1065                                                 if (depth_arr[i] != FLT_MAX)
1066                                                         break;
1067                                         }
1068                                         first_valid = i;
1069
1070                                         for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--) {
1071                                                 if (depth_arr[i] != FLT_MAX)
1072                                                         break;
1073                                         }
1074                                         last_valid = i;
1075
1076                                         /* invalidate non-endpoints, so only blend between first and last */
1077                                         for (i = first_valid + 1; i < last_valid; i++)
1078                                                 depth_arr[i] = FLT_MAX;
1079
1080                                         interp_depth = true;
1081                                 }
1082
1083                                 if (interp_depth) {
1084                                         interp_sparse_array(depth_arr, gpd->runtime.sbuffer_size, FLT_MAX);
1085                                 }
1086                         }
1087                 }
1088
1089                 pt = gps->points;
1090
1091                 /* convert all points (normal behavior) */
1092                 for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size && ptc; i++, ptc++, pt++) {
1093                         /* convert screen-coordinates to appropriate coordinates (and store them) */
1094                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
1095
1096                         /* copy pressure and time */
1097                         pt->pressure = ptc->pressure;
1098                         pt->strength = ptc->strength;
1099                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1100                         pt->time = ptc->time;
1101                         pt->uv_fac = ptc->uv_fac;
1102                         pt->uv_rot = ptc->uv_rot;
1103                 }
1104
1105                 /* subdivide and smooth the stroke */
1106                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) && (subdivide > 0)) {
1107                         gp_subdivide_stroke(gps, subdivide);
1108                 }
1109                 /* apply randomness to stroke */
1110                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
1111                     (brush->gpencil_settings->draw_random_sub > 0.0f))
1112                 {
1113                         gp_randomize_stroke(gps, brush, p->rng);
1114                 }
1115
1116                 /* smooth stroke after subdiv - only if there's something to do
1117                  * for each iteration, the factor is reduced to get a better smoothing without changing too much
1118                  * the original stroke
1119                  */
1120                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1121                     (brush->gpencil_settings->draw_smoothfac > 0.0f))
1122                 {
1123                         float reduce = 0.0f;
1124                         for (int r = 0; r < brush->gpencil_settings->draw_smoothlvl; r++) {
1125                                 for (i = 0; i < gps->totpoints; i++) {
1126                                         BKE_gpencil_smooth_stroke(gps, i, brush->gpencil_settings->draw_smoothfac - reduce);
1127                                         BKE_gpencil_smooth_stroke_strength(gps, i, brush->gpencil_settings->draw_smoothfac);
1128                                 }
1129                                 reduce += 0.25f;  // reduce the factor
1130                         }
1131                 }
1132                 /* smooth thickness */
1133                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1134                     (brush->gpencil_settings->thick_smoothfac > 0.0f))
1135                 {
1136                         for (int r = 0; r < brush->gpencil_settings->thick_smoothlvl * 2; r++) {
1137                                 for (i = 0; i < gps->totpoints; i++) {
1138                                         BKE_gpencil_smooth_stroke_thickness(gps, i, brush->gpencil_settings->thick_smoothfac);
1139                                 }
1140                         }
1141                 }
1142
1143                 /* reproject to plane (only in 3d space) */
1144                 gp_reproject_toplane(p, gps);
1145                 /* change position relative to parent object */
1146                 gp_apply_parent(depsgraph, obact, gpd, gpl, gps);
1147
1148                 if (depth_arr)
1149                         MEM_freeN(depth_arr);
1150         }
1151
1152         /* Save material index */
1153         gps->mat_nr = BKE_object_material_slot_find_index(p->ob, p->material) - 1;
1154
1155         /* calculate UVs along the stroke */
1156         ED_gpencil_calc_stroke_uv(obact, gps);
1157
1158         /* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head
1159          * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
1160          * when drawing the background
1161          */
1162         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
1163                 BLI_addhead(&p->gpf->strokes, gps);
1164         }
1165         else {
1166                 BLI_addtail(&p->gpf->strokes, gps);
1167         }
1168         gp_stroke_added_enable(p);
1169 }
1170
1171 /* --- 'Eraser' for 'Paint' Tool ------ */
1172
1173 /* which which point is infront (result should only be used for comparison) */
1174 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1175 {
1176         if (rv3d->is_persp) {
1177                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1178         }
1179         else {
1180                 return -dot_v3v3(rv3d->viewinv[2], co);
1181         }
1182 }
1183
1184 /* only erase stroke points that are visible */
1185 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1186 {
1187         Object *obact = (Object *)p->ownerPtr.data;
1188
1189         if ((p->sa->spacetype == SPACE_VIEW3D) &&
1190             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
1191         {
1192                 RegionView3D *rv3d = p->ar->regiondata;
1193                 bGPDlayer *gpl = p->gpl;
1194
1195                 const int mval[2] = {x, y};
1196                 float mval_3d[3];
1197                 float fpt[3];
1198
1199                 float diff_mat[4][4];
1200                 /* calculate difference matrix if parent object */
1201                 ED_gpencil_parent_location(p->depsgraph, obact, p->gpd, gpl, diff_mat);
1202
1203                 if (ED_view3d_autodist_simple(p->ar, mval, mval_3d, 0, NULL)) {
1204                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1205
1206                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1207                         const float depth_pt   = view3d_point_depth(rv3d, fpt);
1208
1209                         if (depth_pt > depth_mval) {
1210                                 return true;
1211                         }
1212                 }
1213         }
1214         return false;
1215 }
1216
1217 /* apply a falloff effect to brush strength, based on distance */
1218 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const int mval[2], const int radius, const int co[2])
1219 {
1220         /* Linear Falloff... */
1221         float distance = (float)len_v2v2_int(mval, co);
1222         float fac;
1223
1224         CLAMP(distance, 0.0f, (float)radius);
1225         fac = 1.0f - (distance / (float)radius);
1226
1227         /* Control this further using pen pressure */
1228         fac *= p->pressure;
1229
1230         /* Return influence factor computed here */
1231         return fac;
1232 }
1233
1234 /* helper to free a stroke */
1235 static void gp_free_stroke(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps)
1236 {
1237         if (gps->points) {
1238                 MEM_freeN(gps->points);
1239         }
1240
1241         if (gps->dvert) {
1242                 BKE_gpencil_free_stroke_weights(gps);
1243                 MEM_freeN(gps->dvert);
1244         }
1245
1246         if (gps->triangles)
1247                 MEM_freeN(gps->triangles);
1248         BLI_freelinkN(&gpf->strokes, gps);
1249         gp_update_cache(gpd);
1250 }
1251
1252 /* eraser tool - evaluation per stroke */
1253 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1254 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1255                                       bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1256                                       const int mval[2], const int mvalo[2],
1257                                       const int radius, const rcti *rect)
1258 {
1259         Depsgraph *depsgraph = p->depsgraph;
1260         Object *obact = (Object *)p->ownerPtr.data;
1261         Brush *eraser = p->eraser;
1262         bGPDspoint *pt1, *pt2;
1263         int pc1[2] = {0};
1264         int pc2[2] = {0};
1265         int i;
1266         float diff_mat[4][4];
1267
1268         /* calculate difference matrix */
1269         ED_gpencil_parent_location(depsgraph, obact, p->gpd, gpl, diff_mat);
1270
1271         if (gps->totpoints == 0) {
1272                 /* just free stroke */
1273                 gp_free_stroke(p->gpd, gpf, gps);
1274         }
1275         else if (gps->totpoints == 1) {
1276                 /* only process if it hasn't been masked out... */
1277                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1278                         bGPDspoint pt_temp;
1279                         gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1280                         gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1281                         /* do boundbox check first */
1282                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1283                                 /* only check if point is inside */
1284                                 if (len_v2v2_int(mval, pc1) <= radius) {
1285                                         /* free stroke */
1286                                         gp_free_stroke(p->gpd, gpf, gps);
1287                                 }
1288                         }
1289                 }
1290         }
1291         else if ((p->flags & GP_PAINTFLAG_STROKE_ERASER) || (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_STROKE)) {
1292                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1293
1294                         /* only process if it hasn't been masked out... */
1295                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1296                                 continue;
1297
1298                         /* get points to work with */
1299                         pt1 = gps->points + i;
1300                         bGPDspoint npt;
1301                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1302                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1303
1304                         /* do boundbox check first */
1305                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1306                                 /* only check if point is inside */
1307                                 if (len_v2v2_int(mval, pc1) <= radius) {
1308                                         /* free stroke */
1309                                         gp_free_stroke(p->gpd, gpf, gps);
1310                                         return;
1311                                 }
1312                         }
1313                 }
1314         }
1315         else {
1316                 /* Pressure threshold at which stroke should be culled: Calculated as pressure value
1317                  * below which we would have invisible strokes
1318                  */
1319                 const float cull_thresh = (gps->thickness) ?  1.0f / ((float)gps->thickness)  : 1.0f;
1320
1321                 /* Amount to decrease the pressure of each point with each stroke */
1322                 // TODO: Fetch from toolsettings, or compute based on thickness instead?
1323                 const float strength = 0.1f;
1324
1325                 /* Perform culling? */
1326                 bool do_cull = false;
1327
1328
1329                 /* Clear Tags
1330                  *
1331                  * Note: It's better this way, as we are sure that
1332                  * we don't miss anything, though things will be
1333                  * slightly slower as a result
1334                  */
1335                 for (i = 0; i < gps->totpoints; i++) {
1336                         bGPDspoint *pt = &gps->points[i];
1337                         pt->flag &= ~GP_SPOINT_TAG;
1338                 }
1339
1340                 /* First Pass: Loop over the points in the stroke
1341                  *   1) Thin out parts of the stroke under the brush
1342                  *   2) Tag "too thin" parts for removal (in second pass)
1343                  */
1344                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1345                         /* get points to work with */
1346                         pt1 = gps->points + i;
1347                         pt2 = gps->points + i + 1;
1348
1349                         /* only process if it hasn't been masked out... */
1350                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1351                                 continue;
1352
1353                         bGPDspoint npt;
1354                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1355                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1356
1357                         gp_point_to_parent_space(pt2, diff_mat, &npt);
1358                         gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1359
1360                         /* Check that point segment of the boundbox of the eraser stroke */
1361                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1362                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1363                         {
1364                                 /* Check if point segment of stroke had anything to do with
1365                                  * eraser region  (either within stroke painted, or on its lines)
1366                                  *  - this assumes that linewidth is irrelevant
1367                                  */
1368                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
1369                                         if ((gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1370                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1371                                         {
1372                                                 /* Point is affected: */
1373                                                 /* 1) Adjust thickness
1374                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1375                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1376                                                  */
1377                                                 pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1378                                                 pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength / 2.0f;
1379
1380                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1381                                                 if ((pt1->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1382                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1383                                                 {
1384                                                         pt1->flag |= GP_SPOINT_TAG;
1385                                                         do_cull = true;
1386                                                 }
1387                                                 if ((pt2->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1388                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1389                                                 {
1390                                                         pt2->flag |= GP_SPOINT_TAG;
1391                                                         do_cull = true;
1392                                                 }
1393                                         }
1394                                 }
1395                         }
1396                 }
1397
1398                 /* Second Pass: Remove any points that are tagged */
1399                 if (do_cull) {
1400                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false);
1401                 }
1402                 gp_update_cache(p->gpd);
1403         }
1404 }
1405
1406 /* erase strokes which fall under the eraser strokes */
1407 static void gp_stroke_doeraser(tGPsdata *p)
1408 {
1409         bGPDlayer *gpl;
1410         bGPDstroke *gps, *gpn;
1411         rcti rect;
1412
1413         /* rect is rectangle of eraser */
1414         rect.xmin = p->mval[0] - p->radius;
1415         rect.ymin = p->mval[1] - p->radius;
1416         rect.xmax = p->mval[0] + p->radius;
1417         rect.ymax = p->mval[1] + p->radius;
1418
1419         if (p->sa->spacetype == SPACE_VIEW3D) {
1420                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
1421                         View3D *v3d = p->sa->spacedata.first;
1422                         view3d_region_operator_needs_opengl(p->win, p->ar);
1423                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
1424                 }
1425         }
1426
1427         /* loop over all layers too, since while it's easy to restrict editing to
1428          * only a subset of layers, it is harder to perform the same erase operation
1429          * on multiple layers...
1430          */
1431         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1432                 bGPDframe *gpf = gpl->actframe;
1433
1434                 /* only affect layer if it's editable (and visible) */
1435                 if (gpencil_layer_is_editable(gpl) == false) {
1436                         continue;
1437                 }
1438                 else if (gpf == NULL) {
1439                         continue;
1440                 }
1441
1442                 /* loop over strokes, checking segments for intersections */
1443                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1444                         gpn = gps->next;
1445                         /* check if the color is editable */
1446                         if (ED_gpencil_stroke_color_use(p->ob, gpl, gps) == false) {
1447                                 continue;
1448                         }
1449                         /* Not all strokes in the datablock may be valid in the current editor/context
1450                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1451                          */
1452                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1453                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, p->radius, &rect);
1454                         }
1455                 }
1456         }
1457 }
1458
1459 /* ******************************************* */
1460 /* Sketching Operator */
1461
1462 /* clear the session buffers (call this before AND after a paint operation) */
1463 static void gp_session_validatebuffer(tGPsdata *p)
1464 {
1465         bGPdata *gpd = p->gpd;
1466         Brush *brush = p->brush;
1467
1468         /* clear memory of buffer (or allocate it if starting a new session) */
1469         if (gpd->runtime.sbuffer) {
1470                 /* printf("\t\tGP - reset sbuffer\n"); */
1471                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1472         }
1473         else {
1474                 /* printf("\t\tGP - allocate sbuffer\n"); */
1475                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1476         }
1477
1478         /* reset indices */
1479         gpd->runtime.sbuffer_size = 0;
1480
1481         /* reset flags */
1482         gpd->runtime.sbuffer_sflag = 0;
1483
1484         /* reset inittime */
1485         p->inittime = 0.0;
1486
1487         /* reset lazy */
1488         if (brush) {
1489                 brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
1490         }
1491 }
1492
1493 /* helper to get default eraser and create one if no eraser brush */
1494 static Brush *gp_get_default_eraser(Main *bmain, ToolSettings *ts)
1495 {
1496         Brush *brush_dft = NULL;
1497         Paint *paint = BKE_brush_get_gpencil_paint(ts);
1498         Brush *brush_old = paint->brush;
1499         for (Brush *brush = bmain->brush.first; brush; brush = brush->id.next) {
1500                 if ((brush->ob_mode == OB_MODE_GPENCIL_PAINT) &&
1501                     (brush->gpencil_settings->brush_type == GP_BRUSH_TYPE_ERASE))
1502                 {
1503                         /* save first eraser to use later if no default */
1504                         if (brush_dft == NULL) {
1505                                 brush_dft = brush;
1506                         }
1507                         /* found default */
1508                         if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1509                                 return brush;
1510                         }
1511                 }
1512         }
1513         /* if no default, but exist eraser brush, return this and set as default */
1514         if (brush_dft) {
1515                 brush_dft->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1516                 return brush_dft;
1517         }
1518         /* create a new soft eraser brush */
1519         else {
1520                 brush_dft = BKE_brush_add_gpencil(bmain, ts, "Soft Eraser");
1521                 brush_dft->size = 30.0f;
1522                 brush_dft->gpencil_settings->flag |= (GP_BRUSH_ENABLE_CURSOR | GP_BRUSH_DEFAULT_ERASER);
1523                 brush_dft->gpencil_settings->icon_id = GP_BRUSH_ICON_ERASE_SOFT;
1524                 brush_dft->gpencil_settings->brush_type = GP_BRUSH_TYPE_ERASE;
1525                 brush_dft->gpencil_settings->eraser_mode = GP_BRUSH_ERASER_SOFT;
1526
1527                 /* reset current brush */
1528                 BKE_paint_brush_set(paint, brush_old);
1529
1530                 return brush_dft;
1531         }
1532 }
1533
1534 /* initialize a drawing brush */
1535 static void gp_init_drawing_brush(bContext *C, tGPsdata *p)
1536 {
1537         Brush *brush;
1538         Scene *scene = CTX_data_scene(C);
1539         ToolSettings *ts = CTX_data_tool_settings(C);
1540
1541         Paint *paint = BKE_brush_get_gpencil_paint(ts);
1542
1543         /* if not exist, create a new one */
1544         if (paint->brush == NULL) {
1545                 /* create new brushes */
1546                 BKE_brush_gpencil_presets(C);
1547                 brush = BKE_brush_getactive_gpencil(ts);
1548         }
1549         else {
1550                 /* Use the current */
1551                 brush = BKE_brush_getactive_gpencil(ts);
1552         }
1553         /* be sure curves are initializated */
1554         curvemapping_initialize(brush->gpencil_settings->curve_sensitivity);
1555         curvemapping_initialize(brush->gpencil_settings->curve_strength);
1556         curvemapping_initialize(brush->gpencil_settings->curve_jitter);
1557
1558         /* asign to temp tGPsdata */
1559         p->brush = brush;
1560         if (brush->gpencil_settings->brush_type != GP_BRUSH_TYPE_ERASE) {
1561                 p->eraser = gp_get_default_eraser(p->bmain, ts);
1562         }
1563         else {
1564                 p->eraser = brush;
1565         }
1566         /* use radius of eraser */
1567         p->radius = (short)p->eraser->size;
1568
1569         /* GPXX: Need this update to synchronize brush with draw manager.
1570         * Maybe this update can be removed when the new tool system
1571         * will be in place, but while, we need this to keep drawing working.
1572         *
1573         */
1574         DEG_id_tag_update(&scene->id, DEG_TAG_COPY_ON_WRITE);
1575 }
1576
1577
1578 /* initialize a paint brush and a default color if not exist */
1579 static void gp_init_colors(tGPsdata *p)
1580 {
1581         bGPdata *gpd = p->gpd;
1582         Brush *brush = p->brush;
1583
1584         Material *ma = NULL;
1585         MaterialGPencilStyle *gp_style = NULL;
1586
1587         /* use brush material */
1588         ma = BKE_gpencil_get_material_from_brush(brush);
1589
1590         /* if no brush defaults, get material and color info
1591          * NOTE: Ensures that everything we need will exist...
1592          */
1593         if ((ma == NULL) || (ma->gp_style == NULL)) {
1594                 BKE_gpencil_material_ensure(p->bmain, p->ob);
1595
1596                 /* assign always the first material to the brush */
1597                 p->material = give_current_material(p->ob, 1);
1598                 brush->gpencil_settings->material = p->material;
1599         }
1600         else {
1601                 p->material = ma;
1602         }
1603
1604         /* check if the material is already on object material slots and add it if missing */
1605         if (BKE_object_material_slot_find_index(p->ob, p->material) == 0) {
1606                 BKE_object_material_slot_add(p->bmain, p->ob);
1607                 assign_material(p->bmain, p->ob, ma, p->ob->totcol, BKE_MAT_ASSIGN_EXISTING);
1608         }
1609
1610         /* assign color information to temp tGPsdata */
1611         gp_style = p->material->gp_style;
1612         if (gp_style) {
1613
1614                 /* set colors */
1615                 copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
1616                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
1617                 /* add some alpha to make easy the filling without hide strokes */
1618                 if (gpd->runtime.sfill[3] > 0.8f) {
1619                         gpd->runtime.sfill[3] = 0.8f;
1620                 }
1621
1622                 gpd->runtime.mode = (short)gp_style->mode;
1623                 gpd->runtime.bstroke_style = gp_style->stroke_style;
1624                 gpd->runtime.bfill_style = gp_style->fill_style;
1625         }
1626 }
1627
1628 /* (re)init new painting data */
1629 static bool gp_session_initdata(bContext *C, wmOperator *op, tGPsdata *p)
1630 {
1631         Main *bmain = CTX_data_main(C);
1632         bGPdata **gpd_ptr = NULL;
1633         ScrArea *curarea = CTX_wm_area(C);
1634         ARegion *ar = CTX_wm_region(C);
1635         ToolSettings *ts = CTX_data_tool_settings(C);
1636         Object *obact = CTX_data_active_object(C);
1637         View3D *v3d = curarea->spacedata.first;
1638
1639         /* make sure the active view (at the starting time) is a 3d-view */
1640         if (curarea == NULL) {
1641                 p->status = GP_STATUS_ERROR;
1642                 if (G.debug & G_DEBUG)
1643                         printf("Error: No active view for painting\n");
1644                 return 0;
1645         }
1646
1647         /* pass on current scene and window */
1648         p->C = C;
1649         p->bmain = CTX_data_main(C);
1650         p->scene = CTX_data_scene(C);
1651         p->depsgraph = CTX_data_depsgraph(C);
1652         p->win = CTX_wm_window(C);
1653         p->disable_fill = RNA_boolean_get(op->ptr, "disable_fill");
1654
1655         unit_m4(p->imat);
1656         unit_m4(p->mat);
1657
1658         switch (curarea->spacetype) {
1659                 /* supported views first */
1660                 case SPACE_VIEW3D:
1661                 {
1662                         /* View3D *v3d = curarea->spacedata.first; */
1663                         /* RegionView3D *rv3d = ar->regiondata; */
1664
1665                         /* set current area
1666                          *      - must verify that region data is 3D-view (and not something else)
1667                          */
1668                          /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1669                         p->sa = curarea;
1670                         p->ar = ar;
1671                         p->align_flag = &ts->gpencil_v3d_align;
1672
1673                         if (ar->regiondata == NULL) {
1674                                 p->status = GP_STATUS_ERROR;
1675                                 if (G.debug & G_DEBUG)
1676                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1677                                 return 0;
1678                         }
1679
1680                         /* if active object doesn't exist or isn't a GP Object, create one */
1681                         float *cur = ED_view3d_cursor3d_get(p->scene, v3d)->location;
1682                         if ((!obact) || (obact->type != OB_GPENCIL)) {
1683                                 /* create new default object */
1684                                 obact = ED_add_gpencil_object(C, p->scene, cur);
1685                         }
1686                         /* assign object after all checks to be sure we have one active */
1687                         p->ob = obact;
1688
1689                         break;
1690                 }
1691
1692                 /* unsupported views */
1693                 default:
1694                 {
1695                         p->status = GP_STATUS_ERROR;
1696                         if (G.debug & G_DEBUG)
1697                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1698                         return 0;
1699                 }
1700         }
1701
1702         /* get gp-data */
1703         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1704         if ((gpd_ptr == NULL) || ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1705                 p->status = GP_STATUS_ERROR;
1706                 if (G.debug & G_DEBUG)
1707                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1708                 return 0;
1709         }
1710         else {
1711                 /* if no existing GPencil block exists, add one */
1712                 if (*gpd_ptr == NULL)
1713                         *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil");
1714                 p->gpd = *gpd_ptr;
1715         }
1716
1717         if (ED_gpencil_session_active() == 0) {
1718                 /* initialize undo stack,
1719                  * also, existing undo stack would make buffer drawn
1720                  */
1721                 gpencil_undo_init(p->gpd);
1722         }
1723
1724         /* clear out buffer (stored in gp-data), in case something contaminated it */
1725         gp_session_validatebuffer(p);
1726
1727         /* set brush and create a new one if null */
1728         gp_init_drawing_brush(C, p);
1729
1730         /* setup active color */
1731         if (curarea->spacetype == SPACE_VIEW3D) {
1732                 /* NOTE: This is only done for 3D view, as Materials aren't used for
1733                  *       annotations in 2D editors
1734                  */
1735                 gp_init_colors(p);
1736         }
1737
1738         /* lock axis */
1739         p->lock_axis = ts->gp_sculpt.lock_axis;
1740
1741         return 1;
1742 }
1743
1744 /* init new painting session */
1745 static tGPsdata *gp_session_initpaint(bContext *C, wmOperator *op)
1746 {
1747         tGPsdata *p = NULL;
1748
1749         /* Create new context data */
1750         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1751
1752         /* Try to initialise context data
1753          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
1754          */
1755         if (gp_session_initdata(C, op, p) == 0) {
1756                 /* Invalid state - Exit
1757                  * NOTE: It should be safe to just free the data, since failing context checks should
1758                  * only happen when no data has been allocated.
1759                  */
1760                 MEM_freeN(p);
1761                 return NULL;
1762         }
1763
1764         /* Random generator, only init once. */
1765         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
1766         rng_seed ^= GET_UINT_FROM_POINTER(p);
1767         p->rng = BLI_rng_new(rng_seed);
1768
1769         /* return context data for running paint operator */
1770         return p;
1771 }
1772
1773 /* cleanup after a painting session */
1774 static void gp_session_cleanup(tGPsdata *p)
1775 {
1776         bGPdata *gpd = (p) ? p->gpd : NULL;
1777
1778         /* error checking */
1779         if (gpd == NULL)
1780                 return;
1781
1782         /* free stroke buffer */
1783         if (gpd->runtime.sbuffer) {
1784                 /* printf("\t\tGP - free sbuffer\n"); */
1785                 MEM_freeN(gpd->runtime.sbuffer);
1786                 gpd->runtime.sbuffer = NULL;
1787         }
1788
1789         /* clear flags */
1790         gpd->runtime.sbuffer_size = 0;
1791         gpd->runtime.sbuffer_sflag = 0;
1792         p->inittime = 0.0;
1793 }
1794
1795 static void gp_session_free(tGPsdata *p)
1796 {
1797         if (p->rng != NULL) {
1798                 BLI_rng_free(p->rng);
1799         }
1800         MEM_freeN(p);
1801 }
1802
1803
1804 /* init new stroke */
1805 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
1806 {
1807         Scene *scene = p->scene;
1808         ToolSettings *ts = scene->toolsettings;
1809         int cfra_eval = (int)DEG_get_ctime(p->depsgraph);
1810
1811         /* get active layer (or add a new one if non-existent) */
1812         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1813         if (p->gpl == NULL) {
1814                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("GP_Layer"), true);
1815
1816                 if (p->custom_color[3])
1817                         copy_v3_v3(p->gpl->color, p->custom_color);
1818         }
1819         if (p->gpl->flag & GP_LAYER_LOCKED) {
1820                 p->status = GP_STATUS_ERROR;
1821                 if (G.debug & G_DEBUG)
1822                         printf("Error: Cannot paint on locked layer\n");
1823                 return;
1824         }
1825
1826         /* get active frame (add a new one if not matching frame) */
1827         if (paintmode == GP_PAINTMODE_ERASER) {
1828                 /* Eraser mode:
1829                  * 1) Add new frames to all frames that we might touch,
1830                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1831                  *    (to avoid problems with other tools which expect it to exist)
1832                  */
1833                 bool has_layer_to_erase = false;
1834
1835                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1836                         /* Skip if layer not editable */
1837                         if (gpencil_layer_is_editable(gpl) == false)
1838                                 continue;
1839
1840                         /* Add a new frame if needed (and based off the active frame,
1841                          * as we need some existing strokes to erase)
1842                          *
1843                          * Note: We don't add a new frame if there's nothing there now, so
1844                          *       -> If there are no frames at all, don't add one
1845                          *       -> If there are no strokes in that frame, don't add a new empty frame
1846                          */
1847                         if (gpl->actframe && gpl->actframe->strokes.first) {
1848                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_COPY);
1849                                 has_layer_to_erase = true;
1850                         }
1851
1852                         /* XXX: we omit GP_FRAME_PAINT here for now,
1853                          * as it is only really useful for doing
1854                          * paintbuffer drawing
1855                          */
1856                 }
1857
1858                 /* Ensure this gets set... */
1859                 p->gpf = p->gpl->actframe;
1860
1861                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
1862                  * (though this is only available in editmode)
1863                  */
1864                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
1865                         if (ts->gp_sculpt.flag & GP_BRUSHEDIT_FLAG_SELECT_MASK) {
1866                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
1867                         }
1868                 }
1869
1870                 if (has_layer_to_erase == false) {
1871                         p->status = GP_STATUS_ERROR;
1872                         //if (G.debug & G_DEBUG)
1873                                 printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
1874                         return;
1875                 }
1876         }
1877         else {
1878                 /* Drawing Modes - Add a new frame if needed on the active layer */
1879                 short add_frame_mode;
1880
1881                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
1882                         add_frame_mode = GP_GETFRAME_ADD_COPY;
1883                 else
1884                         add_frame_mode = GP_GETFRAME_ADD_NEW;
1885
1886                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, cfra_eval, add_frame_mode);
1887                 /* set as dirty draw manager cache */
1888                 gp_update_cache(p->gpd);
1889
1890                 if (p->gpf == NULL) {
1891                         p->status = GP_STATUS_ERROR;
1892                         if (G.debug & G_DEBUG)
1893                                 printf("Error: No frame created (gpencil_paint_init)\n");
1894                         return;
1895                 }
1896                 else {
1897                         p->gpf->flag |= GP_FRAME_PAINT;
1898                 }
1899         }
1900
1901         /* set 'eraser' for this stroke if using eraser */
1902         p->paintmode = paintmode;
1903         if (p->paintmode == GP_PAINTMODE_ERASER) {
1904                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
1905
1906                 /* check if we should respect depth while erasing */
1907                 if (p->sa->spacetype == SPACE_VIEW3D) {
1908                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1909                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1910                         }
1911                 }
1912         }
1913         else {
1914                 /* disable eraser flags - so that we can switch modes during a session */
1915                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
1916
1917                 if (p->sa->spacetype == SPACE_VIEW3D) {
1918                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1919                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
1920                         }
1921                 }
1922         }
1923
1924         /* set special fill stroke mode */
1925         if (p->disable_fill == true) {
1926                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_NOFILL;
1927                 /* replace stroke color with fill color */
1928                 copy_v4_v4(p->gpd->runtime.scolor, p->gpd->runtime.sfill);
1929         }
1930
1931         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1932         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1933
1934         /* when drawing in the camera view, in 2D space, set the subrect */
1935         p->subrect = NULL;
1936         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
1937                 if (p->sa->spacetype == SPACE_VIEW3D) {
1938                         View3D *v3d = p->sa->spacedata.first;
1939                         RegionView3D *rv3d = p->ar->regiondata;
1940
1941                         /* for camera view set the subrect */
1942                         if (rv3d->persp == RV3D_CAMOB) {
1943                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1944                                 p->subrect = &p->subrect_data;
1945                         }
1946                 }
1947         }
1948
1949         /* init stroke point space-conversion settings... */
1950         p->gsc.gpd = p->gpd;
1951         p->gsc.gpl = p->gpl;
1952
1953         p->gsc.sa = p->sa;
1954         p->gsc.ar = p->ar;
1955         p->gsc.v2d = p->v2d;
1956
1957         p->gsc.subrect_data = p->subrect_data;
1958         p->gsc.subrect = p->subrect;
1959
1960         copy_m4_m4(p->gsc.mat, p->mat);
1961
1962
1963         /* check if points will need to be made in view-aligned space */
1964         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
1965                 switch (p->sa->spacetype) {
1966                         case SPACE_VIEW3D:
1967                         {
1968                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
1969                                 break;
1970                         }
1971                 }
1972         }
1973 }
1974
1975 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1976 static void gp_paint_strokeend(tGPsdata *p)
1977 {
1978         ToolSettings *ts = p->scene->toolsettings;
1979         /* for surface sketching, need to set the right OpenGL context stuff so that
1980          * the conversions will project the values correctly...
1981          */
1982         if (gpencil_project_check(p)) {
1983                 View3D *v3d = p->sa->spacedata.first;
1984
1985                 /* need to restore the original projection settings before packing up */
1986                 view3d_region_operator_needs_opengl(p->win, p->ar);
1987                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
1988         }
1989
1990         /* check if doing eraser or not */
1991         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1992                 /* simplify stroke before transferring? */
1993                 gp_stroke_simplify(p);
1994
1995                 /* transfer stroke to frame */
1996                 gp_stroke_newfrombuffer(p);
1997         }
1998
1999         /* clean up buffer now */
2000         gp_session_validatebuffer(p);
2001 }
2002
2003 /* finish off stroke painting operation */
2004 static void gp_paint_cleanup(tGPsdata *p)
2005 {
2006         /* p->gpd==NULL happens when stroke failed to initialize,
2007          * for example when GP is hidden in current space (sergey)
2008          */
2009         if (p->gpd) {
2010                 /* finish off a stroke */
2011                 gp_paint_strokeend(p);
2012         }
2013
2014         /* "unlock" frame */
2015         if (p->gpf)
2016                 p->gpf->flag &= ~GP_FRAME_PAINT;
2017 }
2018
2019 /* ------------------------------- */
2020
2021 /* Helper callback for drawing the cursor itself */
2022 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
2023 {
2024         tGPsdata *p = (tGPsdata *)p_ptr;
2025
2026         if (p->paintmode == GP_PAINTMODE_ERASER) {
2027                 GPUVertFormat *format = immVertexFormat();
2028                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2029                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2030
2031                 GPU_line_smooth(true);
2032                 GPU_blend(true);
2033                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2034
2035                 immUniformColor4ub(255, 100, 100, 20);
2036                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
2037
2038                 immUnbindProgram();
2039
2040                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
2041
2042                 float viewport_size[4];
2043                 GPU_viewport_size_get_f(viewport_size);
2044                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
2045
2046                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
2047                 immUniform1i("colors_len", 0);  /* "simple" mode */
2048                 immUniform1f("dash_width", 12.0f);
2049                 immUniform1f("dash_factor", 0.5f);
2050
2051                 imm_draw_circle_wire_2d(shdr_pos, x, y, p->radius,
2052                                      /* XXX Dashed shader gives bad results with sets of small segments currently,
2053                                       *     temp hack around the issue. :( */
2054                                      max_ii(8, p->radius / 2));  /* was fixed 40 */
2055
2056                 immUnbindProgram();
2057
2058                 GPU_blend(false);
2059                 GPU_line_smooth(false);
2060         }
2061 }
2062
2063 /* Turn brush cursor in 3D view on/off */
2064 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
2065 {
2066         if (p->erasercursor && !enable) {
2067                 /* clear cursor */
2068                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
2069                 p->erasercursor = NULL;
2070         }
2071         else if (enable && !p->erasercursor) {
2072                 ED_gpencil_toggle_brush_cursor(p->C, false, NULL);
2073                 /* enable cursor */
2074                 p->erasercursor = WM_paint_cursor_activate(
2075                         CTX_wm_manager(C),
2076                         NULL, /* XXX */
2077                         gpencil_draw_eraser, p);
2078         }
2079 }
2080
2081 /* Check if tablet eraser is being used (when processing events) */
2082 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
2083 {
2084         if (event->tablet_data) {
2085                 const wmTabletData *wmtab = event->tablet_data;
2086                 return (wmtab->Active == EVT_TABLET_ERASER);
2087         }
2088
2089         return false;
2090 }
2091
2092 /* ------------------------------- */
2093
2094 static void gpencil_draw_exit(bContext *C, wmOperator *op)
2095 {
2096         tGPsdata *p = op->customdata;
2097
2098         /* don't assume that operator data exists at all */
2099         if (p) {
2100                 /* check size of buffer before cleanup, to determine if anything happened here */
2101                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2102                         /* turn off radial brush cursor */
2103                         gpencil_draw_toggle_eraser_cursor(C, p, false);
2104                 }
2105
2106                 /* always store the new eraser size to be used again next time
2107                  * NOTE: Do this even when not in eraser mode, as eraser may
2108                  *       have been toggled at some point.
2109                  */
2110                 if (p->eraser) {
2111                         p->eraser->size = p->radius;
2112                 }
2113
2114                 /* restore cursor to indicate end of drawing */
2115                 if (p->sa->spacetype != SPACE_VIEW3D) {
2116                         WM_cursor_modal_restore(CTX_wm_window(C));
2117                 }
2118                 else {
2119                         /* or restore paint if 3D view */
2120                         if ((p) && (p->paintmode == GP_PAINTMODE_ERASER)) {
2121                                 WM_cursor_modal_set(p->win, CURSOR_STD);
2122                         }
2123
2124                         /* drawing batch cache is dirty now */
2125                         bGPdata *gpd = CTX_data_gpencil_data(C);
2126                         if (gpd) {
2127                                 gp_update_cache(gpd);
2128                         }
2129                 }
2130
2131                 /* clear undo stack */
2132                 gpencil_undo_finish();
2133
2134                 /* cleanup */
2135                 gp_paint_cleanup(p);
2136                 gp_session_cleanup(p);
2137                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2138
2139                 /* finally, free the temp data */
2140                 gp_session_free(p);
2141                 p = NULL;
2142         }
2143
2144         op->customdata = NULL;
2145 }
2146
2147 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
2148 {
2149         /* this is just a wrapper around exit() */
2150         gpencil_draw_exit(C, op);
2151 }
2152
2153 /* ------------------------------- */
2154
2155
2156 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
2157 {
2158         tGPsdata *p;
2159         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
2160         ToolSettings *ts = CTX_data_tool_settings(C);
2161         Brush *brush = BKE_brush_getactive_gpencil(ts);
2162
2163         /* if mode is draw and the brush is eraser, cancel */
2164         if (paintmode != GP_PAINTMODE_ERASER) {
2165                 if ((brush) && (brush->gpencil_settings->brush_type == GP_BRUSH_TYPE_ERASE)) {
2166                         return 0;
2167                 }
2168         }
2169
2170         /* check context */
2171         p = op->customdata = gp_session_initpaint(C, op);
2172         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
2173                 /* something wasn't set correctly in context */
2174                 gpencil_draw_exit(C, op);
2175                 return 0;
2176         }
2177
2178         /* init painting data */
2179         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
2180         if (p->status == GP_STATUS_ERROR) {
2181                 gpencil_draw_exit(C, op);
2182                 return 0;
2183         }
2184
2185         if (event != NULL) {
2186                 p->keymodifier = event->keymodifier;
2187         }
2188         else {
2189                 p->keymodifier = -1;
2190         }
2191
2192         p->reports = op->reports;
2193
2194         /* everything is now setup ok */
2195         return 1;
2196 }
2197
2198
2199 /* ------------------------------- */
2200
2201 /* ensure that the correct cursor icon is set */
2202 static void gpencil_draw_cursor_set(tGPsdata *p)
2203 {
2204         Brush *brush = p->brush;
2205         if ((p->paintmode == GP_PAINTMODE_ERASER) ||
2206             (brush->gpencil_settings->brush_type == GP_BRUSH_TYPE_ERASE))
2207         {
2208                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2209         }
2210         else {
2211                 WM_cursor_modal_set(p->win, CURSOR_STD);
2212         }
2213 }
2214
2215 /* update UI indicators of status, including cursor and header prints */
2216 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
2217 {
2218         /* header prints */
2219         switch (p->status) {
2220
2221 #if 0 /* FIXME, this never runs! */
2222                 switch (p->paintmode) {
2223                         case GP_PAINTMODE_DRAW_POLY:
2224                                 /* Provide usage tips, since this is modal, and unintuitive without hints */
2225                                 ED_workspace_status_text(
2226                                         C, IFACE_(
2227                                                 "Annotation Create Poly: LMB click to place next stroke vertex | "
2228                                                 "ESC/Enter to end  (or click outside this area)"
2229                                         ));
2230                                 break;
2231                         default:
2232                                 /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
2233                                  * Showing any text would just be annoying as it would flicker.
2234                                  */
2235                                 break;
2236                 }
2237 #endif
2238
2239                 case GP_STATUS_IDLING:
2240                         /* print status info */
2241                         switch (p->paintmode) {
2242                                 case GP_PAINTMODE_ERASER:
2243                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2244                                                                           "ESC/Enter to end  (or click outside this area)"));
2245                                         break;
2246                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2247                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2248                                                                           "ESC/Enter to end  (or click outside this area)"));
2249                                         break;
2250                                 case GP_PAINTMODE_DRAW:
2251                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw"));
2252                                         break;
2253                                 case GP_PAINTMODE_DRAW_POLY:
2254                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2255                                                                           "Release Shift/ESC/Enter to end  (or click outside this area)"));
2256                                         break;
2257
2258                                 default: /* unhandled future cases */
2259                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2260                                         break;
2261                         }
2262                         break;
2263
2264                 case GP_STATUS_ERROR:
2265                 case GP_STATUS_DONE:
2266                         /* clear status string */
2267                         ED_workspace_status_text(C, NULL);
2268                         break;
2269                 case GP_STATUS_PAINTING:
2270                         break;
2271         }
2272 }
2273
2274 /* ------------------------------- */
2275
2276 /* create a new stroke point at the point indicated by the painting context */
2277 static void gpencil_draw_apply(bContext *C, wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
2278 {
2279         bGPdata *gpd = p->gpd;
2280         tGPspoint *pt = NULL;
2281
2282         /* handle drawing/erasing -> test for erasing first */
2283         if (p->paintmode == GP_PAINTMODE_ERASER) {
2284                 /* do 'live' erasing now */
2285                 gp_stroke_doeraser(p);
2286
2287                 /* store used values */
2288                 p->mvalo[0] = p->mval[0];
2289                 p->mvalo[1] = p->mval[1];
2290                 p->opressure = p->pressure;
2291         }
2292         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2293         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2294
2295                 /* if lazy mouse, interpolate the last and current mouse positions */
2296                 if (GPENCIL_LAZY_MODE(p->brush, p->shift)) {
2297                         float now_mouse[2];
2298                         float last_mouse[2];
2299                         copy_v2fl_v2i(now_mouse, p->mval);
2300                         copy_v2fl_v2i(last_mouse, p->mvalo);
2301                         interp_v2_v2v2(now_mouse, now_mouse, last_mouse, p->brush->smooth_stroke_factor);
2302                         round_v2i_v2fl(p->mval, now_mouse);
2303                 }
2304
2305                 /* try to add point */
2306                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2307
2308                 /* handle errors while adding point */
2309                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2310                         /* finish off old stroke */
2311                         gp_paint_strokeend(p);
2312                         /* And start a new one!!! Else, projection errors! */
2313                         gp_paint_initstroke(p, p->paintmode, depsgraph);
2314
2315                         /* start a new stroke, starting from previous point */
2316                         /* XXX Must manually reset inittime... */
2317                         /* XXX We only need to reuse previous point if overflow! */
2318                         if (ok == GP_STROKEADD_OVERFLOW) {
2319                                 p->inittime = p->ocurtime;
2320                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2321                         }
2322                         else {
2323                                 p->inittime = p->curtime;
2324                         }
2325                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2326                 }
2327                 else if (ok == GP_STROKEADD_INVALID) {
2328                         /* the painting operation cannot continue... */
2329                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2330                         p->status = GP_STATUS_ERROR;
2331
2332                         if (G.debug & G_DEBUG)
2333                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2334                         return;
2335                 }
2336
2337                 /* store used values */
2338                 p->mvalo[0] = p->mval[0];
2339                 p->mvalo[1] = p->mval[1];
2340                 p->opressure = p->pressure;
2341                 p->ocurtime = p->curtime;
2342
2343                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2344                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2345                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2346                 }
2347         }
2348         else if ((p->brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) &&
2349                  (gpd->runtime.sbuffer_size > 0))
2350         {
2351                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2352                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2353                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2354                 }
2355         }
2356 }
2357
2358 /* handle draw event */
2359 static void gpencil_draw_apply_event(bContext *C, wmOperator *op, const wmEvent *event, Depsgraph *depsgraph, int x, int y)
2360 {
2361         tGPsdata *p = op->customdata;
2362         PointerRNA itemptr;
2363         float mousef[2];
2364         int tablet = 0;
2365
2366         /* convert from window-space to area-space mouse coordinates
2367          * add any x,y override position for fake events
2368          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
2369          */
2370         p->mval[0] = event->mval[0] + 1 - x;
2371         p->mval[1] = event->mval[1] + 1 - y;
2372         p->shift = event->shift;
2373
2374         /* verify key status for straight lines */
2375         if ((event->alt > 0) && (RNA_boolean_get(op->ptr, "disable_straight") == false)) {
2376                 if (p->straight[0] == 0) {
2377                         int dx = abs(p->mval[0] - p->mvalo[0]);
2378                         int dy = abs(p->mval[1] - p->mvalo[1]);
2379                         if ((dx > 0) || (dy > 0)) {
2380                                 /* check mouse direction to replace the other coordinate with previous values */
2381                                 if (dx >= dy) {
2382                                         /* horizontal */
2383                                         p->straight[0] = 1;
2384                                         p->straight[1] = (short)p->mval[1]; /* save y */
2385                                 }
2386                                 else {
2387                                         /* vertical */
2388                                         p->straight[0] = 2;
2389                                         p->straight[1] = (short)p->mval[0]; /* save x */
2390                                 }
2391                         }
2392                 }
2393         }
2394         else {
2395                 p->straight[0] = 0;
2396         }
2397
2398         p->curtime = PIL_check_seconds_timer();
2399
2400         /* handle pressure sensitivity (which is supplied by tablets) */
2401         if (event->tablet_data) {
2402                 const wmTabletData *wmtab = event->tablet_data;
2403
2404                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2405                 p->pressure = wmtab->Pressure;
2406
2407                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2408                  *  The pen has to float over the tablet surface, resulting in
2409                  *  zero pressure (T47101). Ignore pressure values if floating
2410                  *  (i.e. "effectively zero" pressure), and only when the "active"
2411                  *  end is the stylus (i.e. the default when not eraser)
2412                  */
2413                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2414                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2415                                 p->pressure = 1.0f;
2416                         }
2417                 }
2418         }
2419         else {
2420                 /* No tablet data -> No pressure info is available */
2421                 p->pressure = 1.0f;
2422         }
2423
2424         /* special eraser modes */
2425         if (p->paintmode == GP_PAINTMODE_ERASER) {
2426                 if (event->shift > 0) {
2427                         p->flags |= GP_PAINTFLAG_HARD_ERASER;
2428                 }
2429                 else {
2430                         p->flags &= ~GP_PAINTFLAG_HARD_ERASER;
2431                 }
2432                 if (event->alt > 0) {
2433                         p->flags |= GP_PAINTFLAG_STROKE_ERASER;
2434                 }
2435                 else {
2436                         p->flags &= ~GP_PAINTFLAG_STROKE_ERASER;
2437                 }
2438         }
2439
2440         /* special exception for start of strokes (i.e. maybe for just a dot) */
2441         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2442                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2443
2444                 p->mvalo[0] = p->mval[0];
2445                 p->mvalo[1] = p->mval[1];
2446                 p->opressure = p->pressure;
2447                 p->inittime = p->ocurtime = p->curtime;
2448                 p->straight[0] = 0;
2449                 p->straight[1] = 0;
2450
2451                 /* special exception here for too high pressure values on first touch in
2452                  *  windows for some tablets, then we just skip first touch...
2453                  */
2454                 if (tablet && (p->pressure >= 0.99f))
2455                         return;
2456         }
2457
2458         /* check if alt key is pressed and limit to straight lines */
2459         if (p->straight[0] != 0) {
2460                 if (p->straight[0] == 1) {
2461                         /* horizontal */
2462                         p->mval[1] = p->straight[1]; /* replace y */
2463                 }
2464                 else {
2465                         /* vertical */
2466                         p->mval[0] = p->straight[1]; /* replace x */
2467                 }
2468         }
2469
2470         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2471         RNA_collection_add(op->ptr, "stroke", &itemptr);
2472
2473         mousef[0] = p->mval[0];
2474         mousef[1] = p->mval[1];
2475         RNA_float_set_array(&itemptr, "mouse", mousef);
2476         RNA_float_set(&itemptr, "pressure", p->pressure);
2477         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2478
2479         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2480
2481         /* apply the current latest drawing point */
2482         gpencil_draw_apply(C, op, p, depsgraph);
2483
2484         /* force refresh */
2485         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2486 }
2487
2488 /* ------------------------------- */
2489
2490 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2491 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2492 {
2493         tGPsdata *p = NULL;
2494         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2495
2496         /* printf("GPencil - Starting Re-Drawing\n"); */
2497
2498         /* try to initialize context data needed while drawing */
2499         if (!gpencil_draw_init(C, op, NULL)) {
2500                 MEM_SAFE_FREE(op->customdata);
2501                 /* printf("\tGP - no valid data\n"); */
2502                 return OPERATOR_CANCELLED;
2503         }
2504         else
2505                 p = op->customdata;
2506
2507         /* printf("\tGP - Start redrawing stroke\n"); */
2508
2509         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
2510          * setting the relevant values in context at each step, then applying
2511          */
2512         RNA_BEGIN (op->ptr, itemptr, "stroke")
2513         {
2514                 float mousef[2];
2515
2516                 /* printf("\t\tGP - stroke elem\n"); */
2517
2518                 /* get relevant data for this point from stroke */
2519                 RNA_float_get_array(&itemptr, "mouse", mousef);
2520                 p->mval[0] = (int)mousef[0];
2521                 p->mval[1] = (int)mousef[1];
2522                 p->pressure = RNA_float_get(&itemptr, "pressure");
2523                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
2524
2525                 if (RNA_boolean_get(&itemptr, "is_start")) {
2526                         /* if first-run flag isn't set already (i.e. not true first stroke),
2527                          * then we must terminate the previous one first before continuing
2528                          */
2529                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
2530                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
2531                                 gp_paint_strokeend(p);
2532                                 gp_paint_initstroke(p, p->paintmode, depsgraph);
2533                         }
2534                 }
2535
2536                 /* if first run, set previous data too */
2537                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2538                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2539
2540                         p->mvalo[0] = p->mval[0];
2541                         p->mvalo[1] = p->mval[1];
2542                         p->opressure = p->pressure;
2543                         p->ocurtime = p->curtime;
2544                 }
2545
2546                 /* apply this data as necessary now (as per usual) */
2547                 gpencil_draw_apply(C, op, p, depsgraph);
2548         }
2549         RNA_END;
2550
2551         /* printf("\tGP - done\n"); */
2552
2553         /* cleanup */
2554         gpencil_draw_exit(C, op);
2555
2556         /* refreshes */
2557         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2558
2559         /* done */
2560         return OPERATOR_FINISHED;
2561 }
2562
2563 /* ------------------------------- */
2564
2565 /* start of interactive drawing part of operator */
2566 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2567 {
2568         tGPsdata *p = NULL;
2569
2570         if (G.debug & G_DEBUG)
2571                 printf("GPencil - Starting Drawing\n");
2572
2573         /* support for tablets eraser pen */
2574         if (gpencil_is_tablet_eraser_active(event)) {
2575                 RNA_enum_set(op->ptr, "mode", GP_PAINTMODE_ERASER);
2576         }
2577
2578         /* try to initialize context data needed while drawing */
2579         if (!gpencil_draw_init(C, op, event)) {
2580                 if (op->customdata)
2581                         MEM_freeN(op->customdata);
2582                 if (G.debug & G_DEBUG)
2583                         printf("\tGP - no valid data\n");
2584                 return OPERATOR_CANCELLED;
2585         }
2586         else
2587                 p = op->customdata;
2588
2589         /* TODO: set any additional settings that we can take from the events?
2590          * TODO? if tablet is erasing, force eraser to be on? */
2591
2592         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
2593
2594         /* if eraser is on, draw radial aid */
2595         if (p->paintmode == GP_PAINTMODE_ERASER) {
2596                 gpencil_draw_toggle_eraser_cursor(C, p, true);
2597         }
2598         else {
2599                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2600         }
2601         /* set cursor
2602          * NOTE: This may change later (i.e. intentionally via brush toggle,
2603          *       or unintentionally if the user scrolls outside the area)...
2604          */
2605         gpencil_draw_cursor_set(p);
2606
2607         /* only start drawing immediately if we're allowed to do so... */
2608         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
2609                 /* hotkey invoked - start drawing */
2610                 /* printf("\tGP - set first spot\n"); */
2611                 p->status = GP_STATUS_PAINTING;
2612
2613                 /* handle the initial drawing - i.e. for just doing a simple dot */
2614                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), 0, 0);
2615                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2616         }
2617         else {
2618                 /* toolbar invoked - don't start drawing yet... */
2619                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
2620                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2621         }
2622
2623         /* enable paint mode */
2624         if (p->sa->spacetype == SPACE_VIEW3D) {
2625                 Object *ob = CTX_data_active_object(C);
2626                 if (ob && (ob->type == OB_GPENCIL) && ((p->gpd->flag & GP_DATA_STROKE_PAINTMODE) == 0)) {
2627                         /* Just set paintmode flag... */
2628                         p->gpd->flag |= GP_DATA_STROKE_PAINTMODE;
2629                         /* disable other GP modes */
2630                         p->gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
2631                         p->gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
2632                         p->gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
2633                         /* set workspace mode */
2634                         ob->restore_mode = ob->mode;
2635                         ob->mode = OB_MODE_GPENCIL_PAINT;
2636                         /* redraw mode on screen */
2637                         WM_event_add_notifier(C, NC_SCENE | ND_MODE, NULL);
2638                 }
2639         }
2640
2641         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2642
2643         /* add a modal handler for this operator, so that we can then draw continuous strokes */
2644         WM_event_add_modal_handler(C, op);
2645
2646         return OPERATOR_RUNNING_MODAL;
2647 }
2648
2649 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2650 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
2651 {
2652         bScreen *sc = CTX_wm_screen(C);
2653         return (BLI_findindex(&sc->areabase, sa_test) != -1);
2654 }
2655
2656 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
2657 {
2658         tGPsdata *p = op->customdata;
2659
2660         /* we must check that we're still within the area that we're set up to work from
2661          * otherwise we could crash (see bug #20586)
2662          */
2663         if (CTX_wm_area(C) != p->sa) {
2664                 printf("\t\t\tGP - wrong area execution abort!\n");
2665                 p->status = GP_STATUS_ERROR;
2666         }
2667
2668         /* printf("\t\tGP - start stroke\n"); */
2669
2670         /* we may need to set up paint env again if we're resuming */
2671         /* XXX: watch it with the paintmode! in future,
2672          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
2673
2674         if (gp_session_initdata(C, op, p))
2675                 gp_paint_initstroke(p, p->paintmode, CTX_data_depsgraph(C));
2676
2677         if (p->status != GP_STATUS_ERROR) {
2678                 p->status = GP_STATUS_PAINTING;
2679                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
2680         }
2681
2682         return op->customdata;
2683 }
2684
2685 static void gpencil_stroke_end(wmOperator *op)
2686 {
2687         tGPsdata *p = op->customdata;
2688
2689         gp_paint_cleanup(p);
2690
2691         gpencil_undo_push(p->gpd);
2692
2693         gp_session_cleanup(p);
2694
2695         p->status = GP_STATUS_IDLING;
2696         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2697
2698         p->gpd = NULL;
2699         p->gpl = NULL;
2700         p->gpf = NULL;
2701 }
2702
2703 /* Move last stroke in the listbase to the head to be drawn below all previous strokes in the layer */
2704 static void gpencil_move_last_stroke_to_back(bContext *C)
2705 {
2706         /* move last stroke (the polygon) to head of the listbase stroke to draw on back of all previous strokes */
2707         bGPdata *gpd = ED_gpencil_data_get_active(C);
2708         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
2709
2710         /* sanity checks */
2711         if (ELEM(NULL, gpd, gpl, gpl->actframe)) {
2712                 return;
2713         }
2714
2715         bGPDframe *gpf = gpl->actframe;
2716         bGPDstroke *gps = gpf->strokes.last;
2717         if (ELEM(NULL, gps)) {
2718                 return;
2719         }
2720
2721         BLI_remlink(&gpf->strokes, gps);
2722         BLI_insertlinkbefore(&gpf->strokes, gpf->strokes.first, gps);
2723 }
2724
2725 /* add events for missing mouse movements when the artist draw very fast */
2726 static void gpencil_add_missing_events(bContext *C, wmOperator *op, const wmEvent *event, tGPsdata *p)
2727 {
2728         Brush *brush = p->brush;
2729         if (brush->gpencil_settings->input_samples == 0) {
2730                 return;
2731         }
2732         RegionView3D *rv3d = p->ar->regiondata;
2733         float defaultpixsize = rv3d->pixsize * 1000.0f;
2734         int samples = (GP_MAX_INPUT_SAMPLES - brush->gpencil_settings->input_samples + 1);
2735         float thickness = (float)brush->size;
2736
2737         float pt[2], a[2], b[2];
2738         float vec[3];
2739         float scale = 1.0f;
2740
2741         /* get pixel scale */
2742         gp_get_3d_reference(p, vec);
2743         mul_m4_v3(rv3d->persmat, vec);
2744         if (rv3d->is_persp) {
2745                 scale = vec[2] * defaultpixsize;
2746         }
2747         else {
2748                 scale = defaultpixsize;
2749         }
2750
2751         /* The thickness of the brush is reduced of thickness to get overlap dots */
2752         float dot_factor = 0.50f;
2753         if (samples < 2) {
2754                 dot_factor = 0.05f;
2755         }
2756         else if (samples < 4) {
2757                 dot_factor = 0.10f;
2758         }
2759         else if (samples < 7) {
2760                 dot_factor = 0.3f;
2761         }
2762         else if (samples < 10) {
2763                 dot_factor = 0.4f;
2764         }
2765         float factor = ((thickness * dot_factor) / scale) * samples;
2766
2767         copy_v2fl_v2i(a, p->mvalo);
2768         b[0] = event->mval[0] + 1;
2769         b[1] = event->mval[1] + 1;
2770
2771         /* get distance in pixels */
2772         float dist = len_v2v2(a, b);
2773
2774         /* for very small distances, add a half way point */
2775         if (dist <= 2.0f) {
2776                 interp_v2_v2v2(pt, a, b, 0.5f);
2777                 sub_v2_v2v2(pt, b, pt);
2778                 /* create fake event */
2779                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C),
2780                                          (int)pt[0], (int)pt[1]);
2781         }
2782         else if (dist >= factor) {
2783                 int slices = 2 + (int)((dist - 1.0) / factor);
2784                 float n = 1.0f / slices;
2785                 for (int i = 1; i < slices; i++) {
2786                         interp_v2_v2v2(pt, a, b, n * i);
2787                         sub_v2_v2v2(pt, b, pt);
2788                         /* create fake event */
2789                         gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C),
2790                                                  (int)pt[0], (int)pt[1]);
2791                 }
2792         }
2793 }
2794
2795 /* events handling during interactive drawing part of operator */
2796 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2797 {
2798         tGPsdata *p = op->customdata;
2799         ToolSettings *ts = CTX_data_tool_settings(C);
2800         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2801
2802         /* if (event->type == NDOF_MOTION)
2803          *    return OPERATOR_PASS_THROUGH;
2804          * -------------------------------
2805          * [mce] Not quite what I was looking
2806          * for, but a good start! GP continues to
2807          * draw on the screen while the 3D mouse
2808          * moves the viewpoint. Problem is that
2809          * the stroke is converted to 3D only after
2810          * it is finished. This approach should work
2811          * better in tools that immediately apply
2812          * in 3D space.
2813          */
2814
2815         if (p->status == GP_STATUS_IDLING) {
2816                 ARegion *ar = CTX_wm_region(C);
2817                 p->ar = ar;
2818         }
2819
2820         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2821         if (ISKEYBOARD(event->type)) {
2822                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2823                         /* allow some keys:
2824                          *   - for frame changing [#33412]
2825                          *   - for undo (during sketching sessions)
2826                          */
2827                 }
2828                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2829                         /* allow numpad keys so that camera/view manipulations can still take place
2830                          * - PAD0 in particular is really important for Grease Pencil drawing,
2831                          *   as animators may be working "to camera", so having this working
2832                          *   is essential for ensuring that they can quickly return to that view
2833                          */
2834                 }
2835                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2836                         /* Add Blank Frame
2837                          * - Since this operator is non-modal, we can just call it here, and keep going...
2838                  * - This operator is especially useful when animating
2839                          */
2840                         WM_operator_name_call(C, "GPENCIL_OT_blank_frame_add", WM_OP_EXEC_DEFAULT, NULL);
2841                         estate = OPERATOR_RUNNING_MODAL;
2842                 }
2843                 else {
2844                         estate = OPERATOR_RUNNING_MODAL;
2845                 }
2846         }
2847
2848         //printf("\tGP - handle modal event...\n");
2849
2850         /* exit painting mode (and/or end current stroke)
2851          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
2852          */
2853         /* if polyline and release shift must cancel */
2854         if ((ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, EKEY)) ||
2855             ((p->paintmode == GP_PAINTMODE_DRAW_POLY) && (event->shift == 0)))
2856         {
2857                 /* exit() ends the current stroke before cleaning up */
2858                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
2859                 /* if drawing polygon and enable on back, must move stroke */
2860                 if (ts) {
2861                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2862                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2863                                         gpencil_move_last_stroke_to_back(C);
2864                                 }
2865                         }
2866                 }
2867                 p->status = GP_STATUS_DONE;
2868                 estate = OPERATOR_FINISHED;
2869         }
2870
2871         /* toggle painting mode upon mouse-button movement
2872          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
2873          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
2874          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
2875          * also making sure we have a valid event value, to not exit too early
2876          */
2877         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE) && (ELEM(event->val, KM_PRESS, KM_RELEASE))) {
2878                 /* if painting, end stroke */
2879                 if (p->status == GP_STATUS_PAINTING) {
2880                         int sketch = 0;
2881
2882                         /* basically, this should be mouse-button up = end stroke
2883                          * BUT, polyline drawing is an exception -- all knots should be added during one session
2884                          */
2885                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
2886
2887                         if (sketch) {
2888                                 /* end stroke only, and then wait to resume painting soon */
2889                                 /* printf("\t\tGP - end stroke only\n"); */
2890                                 gpencil_stroke_end(op);
2891
2892                                 /* If eraser mode is on, turn it off after the stroke finishes
2893                                  * NOTE: This just makes it nicer to work with drawing sessions
2894                                  */
2895                                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2896                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2897
2898                                         /* if the original mode was *still* eraser,
2899                                          * we'll let it say for now, since this gives
2900                                          * users an opportunity to have visual feedback
2901                                          * when adjusting eraser size
2902                                          */
2903                                         if (p->paintmode != GP_PAINTMODE_ERASER) {
2904                                                 /* turn off cursor...
2905                                                  * NOTE: this should be enough for now
2906                                                  *       Just hiding this makes it seem like
2907                                                  *       you can paint again...
2908                                                  */
2909                                                 gpencil_draw_toggle_eraser_cursor(C, p, false);
2910                                         }
2911                                 }
2912
2913                                 /* we've just entered idling state, so this event was processed (but no others yet) */
2914                                 estate = OPERATOR_RUNNING_MODAL;
2915
2916                                 /* stroke could be smoothed, send notifier to refresh screen */
2917                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2918                         }
2919                         else {
2920                                 /* printf("\t\tGP - end of stroke + op\n"); */
2921                                 /* if drawing polygon and enable on back, must move stroke */
2922                                 if (ts) {
2923                                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2924                                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2925                                                         gpencil_move_last_stroke_to_back(C);
2926                                                 }
2927                                         }
2928                                 }
2929                                 /* drawing batch cache is dirty now */
2930                                 gp_update_cache(p->gpd);
2931
2932                                 p->status = GP_STATUS_DONE;
2933                                 estate = OPERATOR_FINISHED;
2934                         }
2935                 }
2936                 else if (event->val == KM_PRESS) {
2937                         bool in_bounds = false;
2938
2939                         /* Check if we're outside the bounds of the active region
2940                          * NOTE: An exception here is that if launched from the toolbar,
2941                          *       whatever region we're now in should become the new region
2942                          */
2943                         if ((p->ar) && (p->ar->regiontype == RGN_TYPE_TOOLS)) {
2944                                 /* Change to whatever region is now under the mouse */
2945                                 ARegion *current_region = BKE_area_find_region_xy(p->sa, RGN_TYPE_ANY, event->x, event->y);
2946
2947                                 if (G.debug & G_DEBUG) {
2948                                         printf("found alternative region %p (old was %p) - at %d %d (sa: %d %d -> %d %d)\n",
2949                                                 current_region, p->ar, event->x, event->y,
2950                                                 p->sa->totrct.xmin, p->sa->totrct.ymin, p->sa->totrct.xmax, p->sa->totrct.ymax);
2951                                 }
2952
2953                                 if (current_region) {
2954                                         /* Assume that since we found the cursor in here, it is in bounds
2955                                          * and that this should be the region that we begin drawing in
2956                                          */
2957                                         p->ar = current_region;
2958                                         in_bounds = true;
2959                                 }
2960                                 else {
2961                                         /* Out of bounds, or invalid in some other way */
2962                                         p->status = GP_STATUS_ERROR;
2963                                         estate = OPERATOR_CANCELLED;
2964
2965                                         if (G.debug & G_DEBUG)
2966                                                 printf("%s: Region under cursor is out of bounds, so cannot be drawn on\n", __func__);
2967                                 }
2968                         }
2969                         else if (p->ar) {
2970                                 rcti region_rect;
2971
2972                                 /* Perform bounds check using  */
2973                                 ED_region_visible_rect(p->ar, &region_rect);
2974                                 in_bounds = BLI_rcti_isect_pt_v(&region_rect, event->mval);
2975                         }
2976                         else {
2977                                 /* No region */
2978                                 p->status = GP_STATUS_ERROR;
2979                                 estate = OPERATOR_CANCELLED;
2980
2981                                 if (G.debug & G_DEBUG)
2982                                         printf("%s: No active region found in GP Paint session data\n", __func__);
2983                         }
2984
2985                         if (in_bounds) {
2986                                 /* Switch paintmode (temporarily if need be) based on which button was used
2987                                  * NOTE: This is to make it more convenient to erase strokes when using drawing sessions
2988                                  */
2989                                 if ((event->type == RIGHTMOUSE) || gpencil_is_tablet_eraser_active(event)) {
2990                                         /* turn on eraser */
2991                                         p->paintmode = GP_PAINTMODE_ERASER;
2992                                 }
2993                                 else if (event->type == LEFTMOUSE) {
2994                                         /* restore drawmode to default */
2995                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2996                                 }
2997
2998                                 gpencil_draw_toggle_eraser_cursor(C, p, p->paintmode == GP_PAINTMODE_ERASER);
2999
3000                                 /* not painting, so start stroke (this should be mouse-button down) */
3001                                 p = gpencil_stroke_begin(C, op);
3002
3003                                 if (p->status == GP_STATUS_ERROR) {
3004                                         estate = OPERATOR_CANCELLED;
3005                                 }
3006                         }