f03141c35131be619a2841fd220ab704b4560ce8
[blender.git] / source / blender / editors / gpencil / annotate_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/2018, Blender Foundation
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/annotate_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_math_geom.h"
43
44 #include "BLT_translation.h"
45
46 #include "PIL_time.h"
47
48 #include "BKE_colortools.h"
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_gpencil.h"
52 #include "BKE_layer.h"
53 #include "BKE_main.h"
54 #include "BKE_report.h"
55 #include "BKE_screen.h"
56 #include "BKE_tracking.h"
57
58 #include "DNA_object_types.h"
59 #include "DNA_scene_types.h"
60 #include "DNA_gpencil_types.h"
61 #include "DNA_windowmanager_types.h"
62
63 #include "UI_view2d.h"
64
65 #include "ED_gpencil.h"
66 #include "ED_screen.h"
67 #include "ED_view3d.h"
68 #include "ED_clip.h"
69
70 #include "BIF_glutil.h"
71
72 #include "GPU_immediate.h"
73 #include "GPU_immediate_util.h"
74 #include "GPU_state.h"
75
76 #include "RNA_access.h"
77 #include "RNA_define.h"
78
79 #include "WM_api.h"
80 #include "WM_types.h"
81
82 #include "DEG_depsgraph.h"
83
84 #include "gpencil_intern.h"
85
86 /* ******************************************* */
87 /* 'Globals' and Defines */
88
89 /* values for tGPsdata->status */
90 typedef enum eGPencil_PaintStatus {
91         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
92         GP_STATUS_PAINTING,     /* a stroke is in progress */
93         GP_STATUS_ERROR,        /* something wasn't correctly set up */
94         GP_STATUS_DONE          /* painting done */
95 } eGPencil_PaintStatus;
96
97 /* Return flags for adding points to stroke buffer */
98 typedef enum eGP_StrokeAdd_Result {
99         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
100         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
101         GP_STROKEADD_NORMAL,                /* point was successfully added */
102         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
103 } eGP_StrokeAdd_Result;
104
105 /* Runtime flags */
106 typedef enum eGPencil_PaintFlags {
107         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
108         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
109         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
110         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
111 } eGPencil_PaintFlags;
112
113
114 /* Temporary 'Stroke' Operation data
115  *   "p" = op->customdata
116  */
117 typedef struct tGPsdata {
118         Main *bmain;
119         Scene *scene;       /* current scene from context */
120         struct Depsgraph *depsgraph;
121
122         wmWindow *win;      /* window where painting originated */
123         ScrArea *sa;        /* area where painting originated */
124         ARegion *ar;        /* region where painting originated */
125         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
126         rctf *subrect;      /* for using the camera rect within the 3d view */
127         rctf subrect_data;
128
129         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
130
131         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
132         bGPdata *gpd;       /* gp-datablock layer comes from */
133         bGPDlayer *gpl;     /* layer we're working on */
134         bGPDframe *gpf;     /* frame we're working on */
135
136         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
137
138         eGPencil_PaintStatus status;     /* current status of painting */
139         eGPencil_PaintModes  paintmode;  /* mode for painting */
140         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
141
142         short radius;       /* radius of influence for eraser */
143
144         float mval[2];        /* current mouse-position */
145         float mvalo[2];       /* previous recorded mouse-position */
146
147         float pressure;     /* current stylus pressure */
148         float opressure;    /* previous stylus pressure */
149
150         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
151          * float (and its 7 digits precision) is definitively not enough here!
152          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
153          */
154         double inittime;    /* Used when converting to path */
155         double curtime;     /* Used when converting to path */
156         double ocurtime;    /* Used when converting to path */
157
158         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
159                              * to region space */
160         float mat[4][4];
161
162         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
163
164         void *erasercursor; /* radial cursor data for drawing eraser */
165
166         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
167
168         short keymodifier;   /* key used for invoking the operator */
169 } tGPsdata;
170
171 /* ------ */
172
173 /* Macros for accessing sensitivity thresholds... */
174 /* minimum number of pixels mouse should move before new point created */
175 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
176 /* minimum length of new segment before new point can be added */
177 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
178
179 static bool gp_stroke_added_check(tGPsdata *p)
180 {
181         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
182 }
183
184 static void gp_stroke_added_enable(tGPsdata *p)
185 {
186         BLI_assert(p->gpf->strokes.last != NULL);
187         p->flags |= GP_PAINTFLAG_STROKEADDED;
188 }
189
190 /* ------ */
191 /* Forward defines for some functions... */
192
193 static void gp_session_validatebuffer(tGPsdata *p);
194
195 /* ******************************************* */
196 /* Context Wrangling... */
197
198 /* check if context is suitable for drawing */
199 static bool gpencil_draw_poll(bContext *C)
200 {
201         if (ED_operator_regionactive(C)) {
202                 /* check if current context can support GPencil data */
203                 if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
204                         /* check if Grease Pencil isn't already running */
205                         if (ED_gpencil_session_active() == 0)
206                                 return 1;
207                         else
208                                 CTX_wm_operator_poll_msg_set(C, "Annotation operator is already active");
209                 }
210                 else {
211                         CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
212                 }
213         }
214         else {
215                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
216         }
217
218         return 0;
219 }
220
221 /* check if projecting strokes into 3d-geometry in the 3D-View */
222 static bool gpencil_project_check(tGPsdata *p)
223 {
224         bGPdata *gpd = p->gpd;
225         return ((gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
226 }
227
228 /* ******************************************* */
229 /* Calculations/Conversions */
230
231 /* Utilities --------------------------------- */
232
233 /* get the reference point for stroke-point conversions */
234 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
235 {
236         const float *fp = p->scene->cursor.location;
237
238         /* use 3D-cursor */
239         copy_v3_v3(vec, fp);
240 }
241
242 /* Stroke Editing ---------------------------- */
243
244 /* check if the current mouse position is suitable for adding a new point */
245 static bool gp_stroke_filtermval(tGPsdata *p, const float mval[2], float pmval[2])
246 {
247         int dx = (int)fabsf(mval[0] - pmval[0]);
248         int dy = (int)fabsf(mval[1] - pmval[1]);
249
250         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
251         if (p->gpd->runtime.sbuffer_size == 0)
252                 return true;
253
254         /* check if mouse moved at least certain distance on both axes (best case)
255          * - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
256          */
257         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
258                 return true;
259
260         /* check if the distance since the last point is significant enough
261          * - prevents points being added too densely
262          * - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
263          */
264         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
265                 return true;
266
267         /* mouse 'didn't move' */
268         else
269                 return false;
270 }
271
272 /* convert screen-coordinates to buffer-coordinates */
273 static void gp_stroke_convertcoords(tGPsdata *p, const float mval[2], float out[3], float *depth)
274 {
275         bGPdata *gpd = p->gpd;
276
277         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
278         if (gpd->runtime.sbuffer_sflag & GP_STROKE_3DSPACE) {
279                 int mval_i[2];
280                 round_v2i_v2fl(mval_i, mval);
281                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval_i, out, 0, depth))) {
282                         /* projecting onto 3D-Geometry
283                          * - nothing more needs to be done here, since view_autodist_simple() has already done it
284                          */
285                 }
286                 else {
287                         float mval_prj[2];
288                         float rvec[3], dvec[3];
289                         float zfac;
290
291                         /* Current method just converts each point in screen-coordinates to
292                          * 3D-coordinates using the 3D-cursor as reference. In general, this
293                          * works OK, but it could of course be improved.
294                          *
295                          * TODO:
296                          * - investigate using nearest point(s) on a previous stroke as
297                          *   reference point instead or as offset, for easier stroke matching
298                          */
299
300                         gp_get_3d_reference(p, rvec);
301                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
302
303                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
304                                 float mval_f[2];
305                                 sub_v2_v2v2(mval_f, mval_prj, mval);
306                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
307                                 sub_v3_v3v3(out, rvec, dvec);
308                         }
309                         else {
310                                 zero_v3(out);
311                         }
312                 }
313         }
314
315         /* 2d - on 'canvas' (assume that p->v2d is set) */
316         else if ((gpd->runtime.sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
317                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
318                 mul_v3_m4v3(out, p->imat, out);
319         }
320
321         /* 2d - relative to screen (viewport area) */
322         else {
323                 if (p->subrect == NULL) { /* normal 3D view */
324                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
325                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
326                 }
327                 else { /* camera view, use subrect */
328                         out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
329                         out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
330                 }
331         }
332 }
333
334 /* add current stroke-point to buffer (returns whether point was successfully added) */
335 static short gp_stroke_addpoint(
336         tGPsdata *p, const float mval[2], float pressure, double curtime)
337 {
338         bGPdata *gpd = p->gpd;
339         tGPspoint *pt;
340         ToolSettings *ts = p->scene->toolsettings;
341
342         /* check painting mode */
343         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
344                 /* straight lines only - i.e. only store start and end point in buffer */
345                 if (gpd->runtime.sbuffer_size == 0) {
346                         /* first point in buffer (start point) */
347                         pt = (tGPspoint *)(gpd->runtime.sbuffer);
348
349                         /* store settings */
350                         copy_v2_v2(&pt->x, mval);
351                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
352                         pt->strength = 1.0f;
353                         pt->time = (float)(curtime - p->inittime);
354
355                         /* increment buffer size */
356                         gpd->runtime.sbuffer_size++;
357                 }
358                 else {
359                         /* just reset the endpoint to the latest value
360                          * - assume that pointers for this are always valid...
361                          */
362                         pt = ((tGPspoint *)(gpd->runtime.sbuffer) + 1);
363
364                         /* store settings */
365                         copy_v2_v2(&pt->x, mval);
366                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
367                         pt->strength = 1.0f;
368                         pt->time = (float)(curtime - p->inittime);
369
370                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
371                         gpd->runtime.sbuffer_size = 2;
372                 }
373
374                 /* can keep carrying on this way :) */
375                 return GP_STROKEADD_NORMAL;
376         }
377         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
378                 /* check if still room in buffer */
379                 if (gpd->runtime.sbuffer_size >= GP_STROKE_BUFFER_MAX)
380                         return GP_STROKEADD_OVERFLOW;
381
382                 /* get pointer to destination point */
383                 pt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
384
385                 /* store settings */
386                 copy_v2_v2(&pt->x, mval);
387                 pt->pressure = pressure;
388                 pt->strength = 1.0f;  /* unused for annotations, but initialise for easier conversions to GP Object */
389
390                 /* point time */
391                 pt->time = (float)(curtime - p->inittime);
392
393                 /* increment counters */
394                 gpd->runtime.sbuffer_size++;
395
396                 /* check if another operation can still occur */
397                 if (gpd->runtime.sbuffer_size == GP_STROKE_BUFFER_MAX)
398                         return GP_STROKEADD_FULL;
399                 else
400                         return GP_STROKEADD_NORMAL;
401         }
402         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
403                 /* get pointer to destination point */
404                 pt = (tGPspoint *)(gpd->runtime.sbuffer);
405
406                 /* store settings */
407                 copy_v2_v2(&pt->x, mval);
408                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
409                 pt->strength = 1.0f;
410                 pt->time = (float)(curtime - p->inittime);
411
412                 /* if there's stroke for this poly line session add (or replace last) point
413                  * to stroke. This allows to draw lines more interactively (see new segment
414                  * during mouse slide, e.g.)
415                  */
416                 if (gp_stroke_added_check(p)) {
417                         bGPDstroke *gps = p->gpf->strokes.last;
418                         bGPDspoint *pts;
419
420                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
421                         if (gpd->runtime.sbuffer_size == 0) {
422                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
423                                 gps->totpoints++;
424                         }
425
426                         pts = &gps->points[gps->totpoints - 1];
427
428                         /* special case for poly lines: normally,
429                          * depth is needed only when creating new stroke from buffer,
430                          * but poly lines are converting to stroke instantly,
431                          * so initialize depth buffer before converting coordinates
432                          */
433                         if (gpencil_project_check(p)) {
434                                 View3D *v3d = p->sa->spacedata.first;
435
436                                 view3d_region_operator_needs_opengl(p->win, p->ar);
437                                 ED_view3d_autodist_init(
438                                         p->depsgraph, p->ar, v3d, (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
439                         }
440
441                         /* convert screen-coordinates to appropriate coordinates (and store them) */
442                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
443
444                         /* copy pressure and time */
445                         pts->pressure = pt->pressure;
446                         pts->strength = pt->strength;
447                         pts->time = pt->time;
448
449                         /* force fill recalc */
450                         gps->flag |= GP_STROKE_RECALC_CACHES;
451                 }
452
453                 /* increment counters */
454                 if (gpd->runtime.sbuffer_size == 0)
455                         gpd->runtime.sbuffer_size++;
456
457                 return GP_STROKEADD_NORMAL;
458         }
459
460         /* return invalid state for now... */
461         return GP_STROKEADD_INVALID;
462 }
463
464 /* simplify a stroke (in buffer) before storing it
465  * - applies a reverse Chaikin filter
466  * - code adapted from etch-a-ton branch
467  */
468 static void gp_stroke_simplify(tGPsdata *p)
469 {
470         bGPdata *gpd = p->gpd;
471         tGPspoint *old_points = (tGPspoint *)gpd->runtime.sbuffer;
472         short num_points = gpd->runtime.sbuffer_size;
473         short flag = gpd->runtime.sbuffer_sflag;
474         short i, j;
475
476         /* only simplify if simplification is enabled, and we're not doing a straight line */
477         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
478                 return;
479
480         /* don't simplify if less than 4 points in buffer */
481         if ((num_points <= 4) || (old_points == NULL))
482                 return;
483
484         /* clear buffer (but don't free mem yet) so that we can write to it
485          * - firstly set sbuffer to NULL, so a new one is allocated
486          * - secondly, reset flag after, as it gets cleared auto
487          */
488         gpd->runtime.sbuffer = NULL;
489         gp_session_validatebuffer(p);
490         gpd->runtime.sbuffer_sflag = flag;
491
492 /* macro used in loop to get position of new point
493  * - used due to the mixture of datatypes in use here
494  */
495 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
496         { \
497                 co[0] += (float)(old_points[offs].x * sfac); \
498                 co[1] += (float)(old_points[offs].y * sfac); \
499                 pressure += old_points[offs].pressure * sfac; \
500                 time += old_points[offs].time * sfac; \
501         } (void)0
502
503         /* XXX Here too, do not lose start and end points! */
504         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
505         for (i = 0, j = 0; i < num_points; i++) {
506                 if (i - j == 3) {
507                         float co[2], pressure, time;
508                         float mco[2];
509
510                         /* initialize values */
511                         co[0] = 0.0f;
512                         co[1] = 0.0f;
513                         pressure = 0.0f;
514                         time = 0.0f;
515
516                         /* using macro, calculate new point */
517                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
518                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
519                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
520                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
521
522                         /* set values for adding */
523                         mco[0] = co[0];
524                         mco[1] = co[1];
525
526                         /* ignore return values on this... assume to be ok for now */
527                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
528
529                         j += 2;
530                 }
531         }
532         gp_stroke_addpoint(
533                 p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
534                 p->inittime + (double)old_points[num_points - 1].time);
535
536         /* free old buffer */
537         MEM_freeN(old_points);
538 }
539
540 /* make a new stroke from the buffer data */
541 static void gp_stroke_newfrombuffer(tGPsdata *p)
542 {
543         bGPdata *gpd = p->gpd;
544         bGPDlayer *gpl = p->gpl;
545         bGPDstroke *gps;
546         bGPDspoint *pt;
547         tGPspoint *ptc;
548         ToolSettings *ts = p->scene->toolsettings;
549
550         int i, totelem;
551         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
552         int depth_margin = (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
553
554         /* get total number of points to allocate space for
555          * - drawing straight-lines only requires the endpoints
556          */
557         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
558                 totelem = (gpd->runtime.sbuffer_size >= 2) ? 2 : gpd->runtime.sbuffer_size;
559         else
560                 totelem = gpd->runtime.sbuffer_size;
561
562         /* exit with error if no valid points from this stroke */
563         if (totelem == 0) {
564                 if (G.debug & G_DEBUG)
565                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->runtime.sbuffer_size);
566                 return;
567         }
568
569         /* special case for poly line -- for already added stroke during session
570          * coordinates are getting added to stroke immediately to allow more
571          * interactive behavior
572          */
573         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
574                 if (gp_stroke_added_check(p)) {
575                         return;
576                 }
577         }
578
579         /* allocate memory for a new stroke */
580         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
581
582         /* copy appropriate settings for stroke */
583         gps->totpoints = totelem;
584         gps->thickness = gpl->thickness;
585         gps->flag = gpd->runtime.sbuffer_sflag;
586         gps->inittime = p->inittime;
587
588         /* enable recalculation flag by default (only used if hq fill) */
589         gps->flag |= GP_STROKE_RECALC_CACHES;
590
591         /* allocate enough memory for a continuous array for storage points */
592         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
593         gps->tot_triangles = 0;
594
595         /* set pointer to first non-initialized point */
596         pt = gps->points + (gps->totpoints - totelem);
597
598         /* copy points from the buffer to the stroke */
599         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
600                 /* straight lines only -> only endpoints */
601                 {
602                         /* first point */
603                         ptc = gpd->runtime.sbuffer;
604
605                         /* convert screen-coordinates to appropriate coordinates (and store them) */
606                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
607
608                         /* copy pressure and time */
609                         pt->pressure = ptc->pressure;
610                         pt->strength = ptc->strength;
611                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
612                         pt->time = ptc->time;
613
614                         pt++;
615                 }
616
617                 if (totelem == 2) {
618                         /* last point if applicable */
619                         ptc = ((tGPspoint *)gpd->runtime.sbuffer) + (gpd->runtime.sbuffer_size - 1);
620
621                         /* convert screen-coordinates to appropriate coordinates (and store them) */
622                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
623
624                         /* copy pressure and time */
625                         pt->pressure = ptc->pressure;
626                         pt->strength = ptc->strength;
627                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
628                         pt->time = ptc->time;
629                 }
630         }
631         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
632                 /* first point */
633                 ptc = gpd->runtime.sbuffer;
634
635                 /* convert screen-coordinates to appropriate coordinates (and store them) */
636                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
637
638                 /* copy pressure and time */
639                 pt->pressure = ptc->pressure;
640                 pt->strength = ptc->strength;
641                 pt->time = ptc->time;
642         }
643         else {
644                 float *depth_arr = NULL;
645
646                 /* get an array of depths, far depths are blended */
647                 if (gpencil_project_check(p)) {
648                         int mval_i[2], mval_prev[2] = { 0 };
649                         int interp_depth = 0;
650                         int found_depth = 0;
651
652                         depth_arr = MEM_mallocN(sizeof(float) * gpd->runtime.sbuffer_size, "depth_points");
653
654                         for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size; i++, ptc++, pt++) {
655                                 round_v2i_v2fl(mval_i, &ptc->x);
656
657                                 if ((ED_view3d_autodist_depth(p->ar, mval_i, depth_margin, depth_arr + i) == 0) &&
658                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval_i, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
659                                 {
660                                         interp_depth = true;
661                                 }
662                                 else {
663                                         found_depth = true;
664                                 }
665
666                                 copy_v2_v2_int(mval_prev, mval_i);
667                         }
668
669                         if (found_depth == false) {
670                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
671                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--)
672                                         depth_arr[i] = 0.9999f;
673                         }
674                         else {
675                                 if (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
676                                         /* remove all info between the valid endpoints */
677                                         int first_valid = 0;
678                                         int last_valid = 0;
679
680                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
681                                                 if (depth_arr[i] != FLT_MAX)
682                                                         break;
683                                         }
684                                         first_valid = i;
685
686                                         for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--) {
687                                                 if (depth_arr[i] != FLT_MAX)
688                                                         break;
689                                         }
690                                         last_valid = i;
691
692                                         /* invalidate non-endpoints, so only blend between first and last */
693                                         for (i = first_valid + 1; i < last_valid; i++)
694                                                 depth_arr[i] = FLT_MAX;
695
696                                         interp_depth = true;
697                                 }
698
699                                 if (interp_depth) {
700                                         interp_sparse_array(depth_arr, gpd->runtime.sbuffer_size, FLT_MAX);
701                                 }
702                         }
703                 }
704
705
706                 pt = gps->points;
707
708                 /* convert all points (normal behavior) */
709                 for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size && ptc; i++, ptc++, pt++) {
710                         /* convert screen-coordinates to appropriate coordinates (and store them) */
711                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
712
713                         /* copy pressure and time */
714                         pt->pressure = ptc->pressure;
715                         pt->strength = ptc->strength;
716                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
717                         pt->time = ptc->time;
718                 }
719
720                 if (depth_arr)
721                         MEM_freeN(depth_arr);
722         }
723
724         /* add stroke to frame */
725         BLI_addtail(&p->gpf->strokes, gps);
726         gp_stroke_added_enable(p);
727 }
728
729 /* --- 'Eraser' for 'Paint' Tool ------ */
730
731 /* helper to free a stroke
732  * NOTE: gps->dvert and gps->triangles should be NULL, but check anyway for good measure
733  */
734 static void gp_free_stroke(bGPDframe *gpf, bGPDstroke *gps)
735 {
736         if (gps->points) {
737                 MEM_freeN(gps->points);
738         }
739
740         if (gps->dvert) {
741                 BKE_gpencil_free_stroke_weights(gps);
742                 MEM_freeN(gps->dvert);
743         }
744
745         if (gps->triangles) {
746                 MEM_freeN(gps->triangles);
747         }
748
749         BLI_freelinkN(&gpf->strokes, gps);
750 }
751
752
753 /* which which point is infront (result should only be used for comparison) */
754 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
755 {
756         if (rv3d->is_persp) {
757                 return ED_view3d_calc_zfac(rv3d, co, NULL);
758         }
759         else {
760                 return -dot_v3v3(rv3d->viewinv[2], co);
761         }
762 }
763
764 /* only erase stroke points that are visible (3d view) */
765 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
766 {
767         if ((p->sa->spacetype == SPACE_VIEW3D) &&
768             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
769         {
770                 RegionView3D *rv3d = p->ar->regiondata;
771                 const int mval_i[2] = {x, y};
772                 float mval_3d[3];
773
774                 if (ED_view3d_autodist_simple(p->ar, mval_i, mval_3d, 0, NULL)) {
775                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
776                         const float depth_pt   = view3d_point_depth(rv3d, &pt->x);
777
778                         if (depth_pt > depth_mval) {
779                                 return true;
780                         }
781                 }
782         }
783         return false;
784 }
785
786 /* eraser tool - evaluation per stroke */
787 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
788 static void gp_stroke_eraser_dostroke(
789         tGPsdata *p,
790         bGPDframe *gpf, bGPDstroke *gps,
791         const float mval[2], const float mvalo[2],
792         const int radius, const rcti *rect)
793 {
794         bGPDspoint *pt1, *pt2;
795         int pc1[2] = {0};
796         int pc2[2] = {0};
797         int i;
798         int mval_i[2];
799         round_v2i_v2fl(mval_i, mval);
800
801         if (gps->totpoints == 0) {
802                 /* just free stroke */
803                 gp_free_stroke(gpf, gps);
804         }
805         else if (gps->totpoints == 1) {
806                 /* only process if it hasn't been masked out... */
807                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
808                         gp_point_to_xy(&p->gsc, gps, gps->points, &pc1[0], &pc1[1]);
809
810                         /* do boundbox check first */
811                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
812                                 /* only check if point is inside */
813                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
814                                         /* free stroke */
815                                         gp_free_stroke(gpf, gps);
816                                 }
817                         }
818                 }
819         }
820         else {
821                 /* Perform culling? */
822                 bool do_cull = false;
823
824                 /* Clear Tags
825                  *
826                  * Note: It's better this way, as we are sure that
827                  * we don't miss anything, though things will be
828                  * slightly slower as a result
829                  */
830                 for (i = 0; i < gps->totpoints; i++) {
831                         bGPDspoint *pt = &gps->points[i];
832                         pt->flag &= ~GP_SPOINT_TAG;
833                 }
834
835                 /* First Pass: Loop over the points in the stroke
836                  *   1) Thin out parts of the stroke under the brush
837                  *   2) Tag "too thin" parts for removal (in second pass)
838                  */
839                 for (i = 0; (i + 1) < gps->totpoints; i++) {
840                         /* get points to work with */
841                         pt1 = gps->points + i;
842                         pt2 = gps->points + i + 1;
843
844                         /* only process if it hasn't been masked out... */
845                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
846                                 continue;
847
848                         gp_point_to_xy(&p->gsc, gps, pt1, &pc1[0], &pc1[1]);
849                         gp_point_to_xy(&p->gsc, gps, pt2, &pc2[0], &pc2[1]);
850
851                         /* Check that point segment of the boundbox of the eraser stroke */
852                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
853                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
854                         {
855                                 /* Check if point segment of stroke had anything to do with
856                                  * eraser region  (either within stroke painted, or on its lines)
857                                  *  - this assumes that linewidth is irrelevant
858                                  */
859                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
860                                         if ((gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
861                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
862                                         {
863                                                 /* Edge is affected - Check individual points now */
864                                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
865                                                         pt1->flag |= GP_SPOINT_TAG;
866                                                 }
867                                                 if (len_v2v2_int(mval_i, pc2) <= radius) {
868                                                         pt2->flag |= GP_SPOINT_TAG;
869                                                 }
870                                                 do_cull = true;
871                                         }
872                                 }
873                         }
874                 }
875
876                 /* Second Pass: Remove any points that are tagged */
877                 if (do_cull) {
878                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false);
879                 }
880         }
881 }
882
883 /* erase strokes which fall under the eraser strokes */
884 static void gp_stroke_doeraser(tGPsdata *p)
885 {
886         bGPDframe *gpf = p->gpf;
887         bGPDstroke *gps, *gpn;
888         rcti rect;
889
890         /* rect is rectangle of eraser */
891         rect.xmin = p->mval[0] - p->radius;
892         rect.ymin = p->mval[1] - p->radius;
893         rect.xmax = p->mval[0] + p->radius;
894         rect.ymax = p->mval[1] + p->radius;
895
896         if (p->sa->spacetype == SPACE_VIEW3D) {
897                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
898                         View3D *v3d = p->sa->spacedata.first;
899                         view3d_region_operator_needs_opengl(p->win, p->ar);
900                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
901                 }
902         }
903
904         /* loop over strokes of active layer only (session init already took care of ensuring validity),
905          * checking segments for intersections to remove
906          */
907         for (gps = gpf->strokes.first; gps; gps = gpn) {
908                 gpn = gps->next;
909                 /* Not all strokes in the datablock may be valid in the current editor/context
910                  * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
911                  */
912                 if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
913                         gp_stroke_eraser_dostroke(p, gpf, gps, p->mval, p->mvalo, p->radius, &rect);
914                 }
915         }
916 }
917
918 /* ******************************************* */
919 /* Sketching Operator */
920
921 /* clear the session buffers (call this before AND after a paint operation) */
922 static void gp_session_validatebuffer(tGPsdata *p)
923 {
924         bGPdata *gpd = p->gpd;
925
926         /* clear memory of buffer (or allocate it if starting a new session) */
927         if (gpd->runtime.sbuffer) {
928                 /* printf("\t\tGP - reset sbuffer\n"); */
929                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
930         }
931         else {
932                 /* printf("\t\tGP - allocate sbuffer\n"); */
933                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
934         }
935
936         /* reset indices */
937         gpd->runtime.sbuffer_size = 0;
938
939         /* reset flags */
940         gpd->runtime.sbuffer_sflag = 0;
941
942         /* reset inittime */
943         p->inittime = 0.0;
944 }
945
946 /* (re)init new painting data */
947 static bool gp_session_initdata(bContext *C, tGPsdata *p)
948 {
949         Main *bmain = CTX_data_main(C);
950         bGPdata **gpd_ptr = NULL;
951         ScrArea *curarea = CTX_wm_area(C);
952         ARegion *ar = CTX_wm_region(C);
953         ToolSettings *ts = CTX_data_tool_settings(C);
954
955         /* make sure the active view (at the starting time) is a 3d-view */
956         if (curarea == NULL) {
957                 p->status = GP_STATUS_ERROR;
958                 if (G.debug & G_DEBUG)
959                         printf("Error: No active view for painting\n");
960                 return 0;
961         }
962
963         /* pass on current scene and window */
964         p->bmain = CTX_data_main(C);
965         p->scene = CTX_data_scene(C);
966         p->depsgraph = CTX_data_depsgraph(C);
967         p->win = CTX_wm_window(C);
968
969         unit_m4(p->imat);
970         unit_m4(p->mat);
971
972         switch (curarea->spacetype) {
973                 /* supported views first */
974                 case SPACE_VIEW3D:
975                 {
976                         /* View3D *v3d = curarea->spacedata.first; */
977                         /* RegionView3D *rv3d = ar->regiondata; */
978
979                         /* set current area
980                          * - must verify that region data is 3D-view (and not something else)
981                          */
982                         /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
983                         p->sa = curarea;
984                         p->ar = ar;
985                         p->align_flag = &ts->annotate_v3d_align;
986
987                         if (ar->regiondata == NULL) {
988                                 p->status = GP_STATUS_ERROR;
989                                 if (G.debug & G_DEBUG)
990                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
991                                 return 0;
992                         }
993                         break;
994                 }
995                 case SPACE_NODE:
996                 {
997                         /* SpaceNode *snode = curarea->spacedata.first; */
998
999                         /* set current area */
1000                         p->sa = curarea;
1001                         p->ar = ar;
1002                         p->v2d = &ar->v2d;
1003                         p->align_flag = &ts->gpencil_v2d_align;
1004                         break;
1005                 }
1006                 case SPACE_SEQ:
1007                 {
1008                         SpaceSeq *sseq = curarea->spacedata.first;
1009
1010                         /* set current area */
1011                         p->sa = curarea;
1012                         p->ar = ar;
1013                         p->v2d = &ar->v2d;
1014                         p->align_flag = &ts->gpencil_seq_align;
1015
1016                         /* check that gpencil data is allowed to be drawn */
1017                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1018                                 p->status = GP_STATUS_ERROR;
1019                                 if (G.debug & G_DEBUG)
1020                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1021                                 return 0;
1022                         }
1023                         break;
1024                 }
1025                 case SPACE_IMAGE:
1026                 {
1027                         /* SpaceImage *sima = curarea->spacedata.first; */
1028
1029                         /* set the current area */
1030                         p->sa = curarea;
1031                         p->ar = ar;
1032                         p->v2d = &ar->v2d;
1033                         p->align_flag = &ts->gpencil_ima_align;
1034                         break;
1035                 }
1036                 case SPACE_CLIP:
1037                 {
1038                         SpaceClip *sc = curarea->spacedata.first;
1039                         MovieClip *clip = ED_space_clip_get_clip(sc);
1040
1041                         if (clip == NULL) {
1042                                 p->status = GP_STATUS_ERROR;
1043                                 return false;
1044                         }
1045
1046                         /* set the current area */
1047                         p->sa = curarea;
1048                         p->ar = ar;
1049                         p->v2d = &ar->v2d;
1050                         p->align_flag = &ts->gpencil_v2d_align;
1051
1052                         invert_m4_m4(p->imat, sc->unistabmat);
1053
1054                         /* custom color for new layer */
1055                         p->custom_color[0] = 1.0f;
1056                         p->custom_color[1] = 0.0f;
1057                         p->custom_color[2] = 0.5f;
1058                         p->custom_color[3] = 0.9f;
1059
1060                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1061                                 int framenr = ED_space_clip_get_clip_frame_number(sc);
1062                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
1063                                 MovieTrackingMarker *marker = track ? BKE_tracking_marker_get(track, framenr) : NULL;
1064
1065                                 if (marker) {
1066                                         p->imat[3][0] -= marker->pos[0];
1067                                         p->imat[3][1] -= marker->pos[1];
1068                                 }
1069                                 else {
1070                                         p->status = GP_STATUS_ERROR;
1071                                         return false;
1072                                 }
1073                         }
1074
1075                         invert_m4_m4(p->mat, p->imat);
1076                         copy_m4_m4(p->gsc.mat, p->mat);
1077                         break;
1078                 }
1079                 /* unsupported views */
1080                 default:
1081                 {
1082                         p->status = GP_STATUS_ERROR;
1083                         if (G.debug & G_DEBUG)
1084                                 printf("Error: Annotations are not supported in this editor\n");
1085                         return 0;
1086                 }
1087         }
1088
1089         /* get gp-data */
1090         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1091         if ((gpd_ptr == NULL) || !ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1092                 p->status = GP_STATUS_ERROR;
1093                 if (G.debug & G_DEBUG)
1094                         printf("Error: Current context doesn't allow for any Annotation data\n");
1095                 return 0;
1096         }
1097         else {
1098                 /* if no existing GPencil block exists, add one */
1099                 if (*gpd_ptr == NULL) {
1100                         bGPdata *gpd = BKE_gpencil_data_addnew(bmain, "Annotations");
1101                         *gpd_ptr = gpd;
1102
1103                         /* mark datablock as being used for annotations */
1104                         gpd->flag |= GP_DATA_ANNOTATIONS;
1105
1106                         /* annotations always in front of all objects */
1107                         gpd->xray_mode = GP_XRAY_FRONT;
1108                 }
1109                 p->gpd = *gpd_ptr;
1110         }
1111
1112         if (ED_gpencil_session_active() == 0) {
1113                 /* initialize undo stack,
1114                  * also, existing undo stack would make buffer drawn
1115                  */
1116                 gpencil_undo_init(p->gpd);
1117         }
1118
1119         /* clear out buffer (stored in gp-data), in case something contaminated it */
1120         gp_session_validatebuffer(p);
1121
1122         return 1;
1123 }
1124
1125 /* init new painting session */
1126 static tGPsdata *gp_session_initpaint(bContext *C)
1127 {
1128         tGPsdata *p = NULL;
1129
1130         /* create new context data */
1131         p = MEM_callocN(sizeof(tGPsdata), "Annotation Drawing Data");
1132
1133         /* Try to initialise context data
1134          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
1135          */
1136         if (gp_session_initdata(C, p) == 0) {
1137                 /* Invalid state - Exit
1138                  * NOTE: It should be safe to just free the data, since failing context checks should
1139                  * only happen when no data has been allocated.
1140                  */
1141                 MEM_freeN(p);
1142                 return NULL;
1143         }
1144
1145         /* Radius for eraser circle is defined in userprefs */
1146         /* NOTE: we do this here, so that if we exit immediately,
1147          *       erase size won't get lost
1148          */
1149         p->radius = U.gp_eraser;
1150
1151         /* return context data for running paint operator */
1152         return p;
1153 }
1154
1155 /* cleanup after a painting session */
1156 static void gp_session_cleanup(tGPsdata *p)
1157 {
1158         bGPdata *gpd = (p) ? p->gpd : NULL;
1159
1160         /* error checking */
1161         if (gpd == NULL)
1162                 return;
1163
1164         /* free stroke buffer */
1165         if (gpd->runtime.sbuffer) {
1166                 /* printf("\t\tGP - free sbuffer\n"); */
1167                 MEM_freeN(gpd->runtime.sbuffer);
1168                 gpd->runtime.sbuffer = NULL;
1169         }
1170
1171         /* clear flags */
1172         gpd->runtime.sbuffer_size = 0;
1173         gpd->runtime.sbuffer_sflag = 0;
1174         p->inittime = 0.0;
1175 }
1176
1177 static void gp_session_free(tGPsdata *p)
1178 {
1179         MEM_freeN(p);
1180 }
1181
1182
1183 /* init new stroke */
1184 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
1185 {
1186         Scene *scene = p->scene;
1187         ToolSettings *ts = scene->toolsettings;
1188
1189         /* get active layer (or add a new one if non-existent) */
1190         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1191         if (p->gpl == NULL) {
1192                 /* tag for annotations */
1193                 p->gpd->flag |= GP_DATA_ANNOTATIONS;
1194                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("Note"), true);
1195
1196                 if (p->custom_color[3])
1197                         copy_v3_v3(p->gpl->color, p->custom_color);
1198         }
1199         if (p->gpl->flag & GP_LAYER_LOCKED) {
1200                 p->status = GP_STATUS_ERROR;
1201                 if (G.debug & G_DEBUG)
1202                         printf("Error: Cannot paint on locked layer\n");
1203                 return;
1204         }
1205
1206         /* get active frame (add a new one if not matching frame) */
1207         if (paintmode == GP_PAINTMODE_ERASER) {
1208                 /* Eraser mode:
1209                  * 1) Only allow erasing on the active layer (unlike for 3d-art Grease Pencil),
1210                  *    since we won't be exposing layer locking in the UI
1211                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1212                  *    (to avoid problems with other tools which expect it to exist)
1213                  */
1214                 bool has_layer_to_erase = false;
1215
1216                 if (gpencil_layer_is_editable(p->gpl)) {
1217                         /* Ensure that there's stuff to erase here (not including selection mask below)... */
1218                         if (p->gpl->actframe && p->gpl->actframe->strokes.first) {
1219                                 has_layer_to_erase = true;
1220                         }
1221                 }
1222
1223                 /* Ensure active frame is set correctly... */
1224                 p->gpf = p->gpl->actframe;
1225
1226                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
1227                  * (though this is only available in editmode)
1228                  */
1229                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
1230                         if (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
1231                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
1232                         }
1233                 }
1234
1235                 if (has_layer_to_erase == false) {
1236                         p->status = GP_STATUS_ERROR;
1237                         //if (G.debug & G_DEBUG)
1238                                 printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
1239                         return;
1240                 }
1241         }
1242         else {
1243                 /* Drawing Modes - Add a new frame if needed on the active layer */
1244                 short add_frame_mode = GP_GETFRAME_ADD_NEW;
1245
1246                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
1247                         add_frame_mode = GP_GETFRAME_ADD_COPY;
1248                 else
1249                         add_frame_mode = GP_GETFRAME_ADD_NEW;
1250
1251                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, CFRA, add_frame_mode);
1252
1253                 if (p->gpf == NULL) {
1254                         p->status = GP_STATUS_ERROR;
1255                         if (G.debug & G_DEBUG)
1256                                 printf("Error: No frame created (gpencil_paint_init)\n");
1257                         return;
1258                 }
1259                 else {
1260                         p->gpf->flag |= GP_FRAME_PAINT;
1261                 }
1262         }
1263
1264         /* set 'eraser' for this stroke if using eraser */
1265         p->paintmode = paintmode;
1266         if (p->paintmode == GP_PAINTMODE_ERASER) {
1267                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
1268
1269                 /* check if we should respect depth while erasing */
1270                 if (p->sa->spacetype == SPACE_VIEW3D) {
1271                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1272                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1273                         }
1274                 }
1275         }
1276         else {
1277                 /* disable eraser flags - so that we can switch modes during a session */
1278                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
1279
1280                 if (p->sa->spacetype == SPACE_VIEW3D) {
1281                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1282                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
1283                         }
1284                 }
1285         }
1286
1287         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1288         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1289
1290
1291         /* when drawing in the camera view, in 2D space, set the subrect */
1292         p->subrect = NULL;
1293         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
1294                 if (p->sa->spacetype == SPACE_VIEW3D) {
1295                         View3D *v3d = p->sa->spacedata.first;
1296                         RegionView3D *rv3d = p->ar->regiondata;
1297
1298                         /* for camera view set the subrect */
1299                         if (rv3d->persp == RV3D_CAMOB) {
1300                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1301                                 p->subrect = &p->subrect_data;
1302                         }
1303                 }
1304         }
1305
1306         /* init stroke point space-conversion settings... */
1307         p->gsc.gpd = p->gpd;
1308         p->gsc.gpl = p->gpl;
1309
1310         p->gsc.sa = p->sa;
1311         p->gsc.ar = p->ar;
1312         p->gsc.v2d = p->v2d;
1313
1314         p->gsc.subrect_data = p->subrect_data;
1315         p->gsc.subrect = p->subrect;
1316
1317         copy_m4_m4(p->gsc.mat, p->mat);
1318
1319
1320         /* check if points will need to be made in view-aligned space */
1321         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
1322                 switch (p->sa->spacetype) {
1323                         case SPACE_VIEW3D:
1324                         {
1325                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
1326                                 break;
1327                         }
1328                         case SPACE_NODE:
1329                         {
1330                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1331                                 break;
1332                         }
1333                         case SPACE_SEQ:
1334                         {
1335                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1336                                 break;
1337                         }
1338                         case SPACE_IMAGE:
1339                         {
1340                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1341
1342                                 /* only set these flags if the image editor doesn't have an image active,
1343                                  * otherwise user will be confused by strokes not appearing after they're drawn
1344                                  *
1345                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1346                                  */
1347                                 if (ELEM(NULL, sima, sima->image)) {
1348                                         /* make strokes be drawn in screen space */
1349                                         p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1350                                         *(p->align_flag) &= ~GP_PROJECT_VIEWSPACE;
1351                                 }
1352                                 else {
1353                                         p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1354                                 }
1355                                 break;
1356                         }
1357                         case SPACE_CLIP:
1358                         {
1359                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_2DSPACE;
1360                                 break;
1361                         }
1362                 }
1363         }
1364 }
1365
1366 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1367 static void gp_paint_strokeend(tGPsdata *p)
1368 {
1369         ToolSettings *ts = p->scene->toolsettings;
1370         /* for surface sketching, need to set the right OpenGL context stuff so that
1371          * the conversions will project the values correctly...
1372          */
1373         if (gpencil_project_check(p)) {
1374                 View3D *v3d = p->sa->spacedata.first;
1375
1376                 /* need to restore the original projection settings before packing up */
1377                 view3d_region_operator_needs_opengl(p->win, p->ar);
1378                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->annotate_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
1379         }
1380
1381         /* check if doing eraser or not */
1382         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1383                 /* simplify stroke before transferring? */
1384                 gp_stroke_simplify(p);
1385
1386                 /* transfer stroke to frame */
1387                 gp_stroke_newfrombuffer(p);
1388         }
1389
1390         /* clean up buffer now */
1391         gp_session_validatebuffer(p);
1392 }
1393
1394 /* finish off stroke painting operation */
1395 static void gp_paint_cleanup(tGPsdata *p)
1396 {
1397         /* p->gpd==NULL happens when stroke failed to initialize,
1398          * for example when GP is hidden in current space (sergey)
1399          */
1400         if (p->gpd) {
1401                 /* finish off a stroke */
1402                 gp_paint_strokeend(p);
1403         }
1404
1405         /* "unlock" frame */
1406         if (p->gpf)
1407                 p->gpf->flag &= ~GP_FRAME_PAINT;
1408 }
1409
1410 /* ------------------------------- */
1411
1412 /* Helper callback for drawing the cursor itself */
1413 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1414 {
1415         tGPsdata *p = (tGPsdata *)p_ptr;
1416
1417         if (p->paintmode == GP_PAINTMODE_ERASER) {
1418                 GPUVertFormat *format = immVertexFormat();
1419                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
1420                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1421
1422                 GPU_line_smooth(true);
1423                 GPU_blend(true);
1424                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
1425
1426                 immUniformColor4ub(255, 100, 100, 20);
1427                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
1428
1429                 immUnbindProgram();
1430
1431                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
1432
1433                 float viewport_size[4];
1434                 GPU_viewport_size_get_f(viewport_size);
1435                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
1436
1437                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
1438                 immUniform1i("colors_len", 0);  /* "simple" mode */
1439                 immUniform1f("dash_width", 12.0f);
1440                 immUniform1f("dash_factor", 0.5f);
1441
1442                 imm_draw_circle_wire_2d(
1443                         shdr_pos, x, y, p->radius,
1444                         /* XXX Dashed shader gives bad results with sets of small segments currently,
1445                          *     temp hack around the issue. :( */
1446                         max_ii(8, p->radius / 2));  /* was fixed 40 */
1447
1448                 immUnbindProgram();
1449
1450                 GPU_blend(false);
1451                 GPU_line_smooth(false);
1452         }
1453 }
1454
1455 /* Turn brush cursor in 3D view on/off */
1456 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1457 {
1458         if (p->erasercursor && !enable) {
1459                 /* clear cursor */
1460                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1461                 p->erasercursor = NULL;
1462         }
1463         else if (enable && !p->erasercursor) {
1464                 /* enable cursor */
1465                 p->erasercursor = WM_paint_cursor_activate(
1466                         CTX_wm_manager(C),
1467                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
1468                         NULL, /* XXX */
1469                         gpencil_draw_eraser, p);
1470         }
1471 }
1472
1473 /* Check if tablet eraser is being used (when processing events) */
1474 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
1475 {
1476         if (event->tablet_data) {
1477                 const wmTabletData *wmtab = event->tablet_data;
1478                 return (wmtab->Active == EVT_TABLET_ERASER);
1479         }
1480
1481         return false;
1482 }
1483
1484 /* ------------------------------- */
1485
1486 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1487 {
1488         tGPsdata *p = op->customdata;
1489
1490         /* restore cursor to indicate end of drawing */
1491         WM_cursor_modal_restore(CTX_wm_window(C));
1492
1493         /* don't assume that operator data exists at all */
1494         if (p) {
1495                 /* check size of buffer before cleanup, to determine if anything happened here */
1496                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1497                         /* turn off radial brush cursor */
1498                         gpencil_draw_toggle_eraser_cursor(C, p, false);
1499                 }
1500
1501                 /* always store the new eraser size to be used again next time
1502                  * NOTE: Do this even when not in eraser mode, as eraser may
1503                  *       have been toggled at some point.
1504                  */
1505                 U.gp_eraser = p->radius;
1506
1507                 /* clear undo stack */
1508                 gpencil_undo_finish();
1509
1510                 /* cleanup */
1511                 gp_paint_cleanup(p);
1512                 gp_session_cleanup(p);
1513                 gp_session_free(p);
1514                 p = NULL;
1515         }
1516
1517         op->customdata = NULL;
1518 }
1519
1520 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
1521 {
1522         /* this is just a wrapper around exit() */
1523         gpencil_draw_exit(C, op);
1524 }
1525
1526 /* ------------------------------- */
1527
1528
1529 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
1530 {
1531         tGPsdata *p;
1532         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
1533
1534         /* check context */
1535         p = op->customdata = gp_session_initpaint(C);
1536         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1537                 /* something wasn't set correctly in context */
1538                 gpencil_draw_exit(C, op);
1539                 return 0;
1540         }
1541
1542         /* init painting data */
1543         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
1544         if (p->status == GP_STATUS_ERROR) {
1545                 gpencil_draw_exit(C, op);
1546                 return 0;
1547         }
1548
1549         if (event != NULL) {
1550                 p->keymodifier = event->keymodifier;
1551         }
1552         else {
1553                 p->keymodifier = -1;
1554         }
1555
1556         /* everything is now setup ok */
1557         return 1;
1558 }
1559
1560
1561 /* ------------------------------- */
1562
1563 /* ensure that the correct cursor icon is set */
1564 static void gpencil_draw_cursor_set(tGPsdata *p)
1565 {
1566         if (p->paintmode == GP_PAINTMODE_ERASER)
1567                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
1568         else
1569                 WM_cursor_modal_set(p->win, BC_PAINTBRUSHCURSOR);
1570 }
1571
1572 /* update UI indicators of status, including cursor and header prints */
1573 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
1574 {
1575         /* header prints */
1576         switch (p->status) {
1577                 case GP_STATUS_PAINTING:
1578                         switch (p->paintmode) {
1579                                 case GP_PAINTMODE_DRAW_POLY:
1580                                         /* Provide usage tips, since this is modal, and unintuitive without hints */
1581                                         ED_workspace_status_text(C, IFACE_("Annotation Create Poly: LMB click to place next stroke vertex | "
1582                                                                           "ESC/Enter to end  (or click outside this area)"));
1583                                         break;
1584                                 default:
1585                                         /* Do nothing - the others are self explanatory, exit quickly once the mouse is released
1586                                          * Showing any text would just be annoying as it would flicker.
1587                                          */
1588                                         break;
1589                         }
1590                         break;
1591
1592                 case GP_STATUS_IDLING:
1593                         /* print status info */
1594                         switch (p->paintmode) {
1595                                 case GP_PAINTMODE_ERASER:
1596                                         ED_workspace_status_text(C, IFACE_("Annotation Eraser: Hold and drag LMB or RMB to erase | "
1597                                                                           "ESC/Enter to end  (or click outside this area)"));
1598                                         break;
1599                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1600                                         ED_workspace_status_text(C, IFACE_("Annotation Line Draw: Hold and drag LMB to draw | "
1601                                                                           "ESC/Enter to end  (or click outside this area)"));
1602                                         break;
1603                                 case GP_PAINTMODE_DRAW:
1604                                         ED_workspace_status_text(C, IFACE_("Annotation Freehand Draw: Hold and drag LMB to draw | "
1605                                                                           "E/ESC/Enter to end  (or click outside this area)"));
1606                                         break;
1607                                 case GP_PAINTMODE_DRAW_POLY:
1608                                         ED_workspace_status_text(C, IFACE_("Annotation Create Poly: LMB click to place next stroke vertex | "
1609                                                                           "ESC/Enter to end  (or click outside this area)"));
1610                                         break;
1611
1612                                 default: /* unhandled future cases */
1613                                         ED_workspace_status_text(C, IFACE_("Annotation Session: ESC/Enter to end   (or click outside this area)"));
1614                                         break;
1615                         }
1616                         break;
1617
1618                 case GP_STATUS_ERROR:
1619                 case GP_STATUS_DONE:
1620                         /* clear status string */
1621                         ED_workspace_status_text(C, NULL);
1622                         break;
1623         }
1624 }
1625
1626 /* ------------------------------- */
1627
1628 /* create a new stroke point at the point indicated by the painting context */
1629 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
1630 {
1631         /* handle drawing/erasing -> test for erasing first */
1632         if (p->paintmode == GP_PAINTMODE_ERASER) {
1633                 /* do 'live' erasing now */
1634                 gp_stroke_doeraser(p);
1635
1636                 /* store used values */
1637                 p->mvalo[0] = p->mval[0];
1638                 p->mvalo[1] = p->mval[1];
1639                 p->opressure = p->pressure;
1640         }
1641         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1642         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1643                 /* try to add point */
1644                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1645
1646                 /* handle errors while adding point */
1647                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1648                         /* finish off old stroke */
1649                         gp_paint_strokeend(p);
1650                         /* And start a new one!!! Else, projection errors! */
1651                         gp_paint_initstroke(p, p->paintmode, depsgraph);
1652
1653                         /* start a new stroke, starting from previous point */
1654                         /* XXX Must manually reset inittime... */
1655                         /* XXX We only need to reuse previous point if overflow! */
1656                         if (ok == GP_STROKEADD_OVERFLOW) {
1657                                 p->inittime = p->ocurtime;
1658                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
1659                         }
1660                         else {
1661                                 p->inittime = p->curtime;
1662                         }
1663                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
1664                 }
1665                 else if (ok == GP_STROKEADD_INVALID) {
1666                         /* the painting operation cannot continue... */
1667                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1668                         p->status = GP_STATUS_ERROR;
1669
1670                         if (G.debug & G_DEBUG)
1671                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
1672                         return;
1673                 }
1674
1675                 /* store used values */
1676                 p->mvalo[0] = p->mval[0];
1677                 p->mvalo[1] = p->mval[1];
1678                 p->opressure = p->pressure;
1679                 p->ocurtime = p->curtime;
1680         }
1681 }
1682
1683 /* handle draw event */
1684 static void gpencil_draw_apply_event(wmOperator *op, const wmEvent *event, Depsgraph *depsgraph)
1685 {
1686         tGPsdata *p = op->customdata;
1687         PointerRNA itemptr;
1688         float mousef[2];
1689         int tablet = 0;
1690
1691         /* convert from window-space to area-space mouse coordinates
1692          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1693          */
1694         p->mval[0] = event->mval[0] + 1;
1695         p->mval[1] = event->mval[1] + 1;
1696
1697         /* verify key status for straight lines */
1698         if ((event->ctrl > 0) || (event->alt > 0)) {
1699                 if (p->straight[0] == 0) {
1700                         int dx = abs(p->mval[0] - p->mvalo[0]);
1701                         int dy = abs(p->mval[1] - p->mvalo[1]);
1702                         if ((dx > 0) || (dy > 0)) {
1703                                 /* check mouse direction to replace the other coordinate with previous values */
1704                                 if (dx >= dy) {
1705                                         /* horizontal */
1706                                         p->straight[0] = 1;
1707                                         p->straight[1] = p->mval[1]; /* save y */
1708                                 }
1709                                 else {
1710                                         /* vertical */
1711                                         p->straight[0] = 2;
1712                                         p->straight[1] = p->mval[0]; /* save x */
1713                                 }
1714                         }
1715                 }
1716         }
1717         else {
1718                 p->straight[0] = 0;
1719         }
1720
1721         p->curtime = PIL_check_seconds_timer();
1722
1723         /* handle pressure sensitivity (which is supplied by tablets) */
1724         if (event->tablet_data) {
1725                 const wmTabletData *wmtab = event->tablet_data;
1726
1727                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1728                 p->pressure = wmtab->Pressure;
1729
1730                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
1731                  * The pen has to float over the tablet surface, resulting in
1732                  * zero pressure (T47101). Ignore pressure values if floating
1733                  * (i.e. "effectively zero" pressure), and only when the "active"
1734                  * end is the stylus (i.e. the default when not eraser)
1735                  */
1736                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1737                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
1738                                 p->pressure = 1.0f;
1739                         }
1740                 }
1741         }
1742         else {
1743                 /* No tablet data -> No pressure info is available */
1744                 p->pressure = 1.0f;
1745         }
1746
1747         /* special exception for start of strokes (i.e. maybe for just a dot) */
1748         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1749                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1750
1751                 p->mvalo[0] = p->mval[0];
1752                 p->mvalo[1] = p->mval[1];
1753                 p->opressure = p->pressure;
1754                 p->inittime = p->ocurtime = p->curtime;
1755                 p->straight[0] = 0;
1756                 p->straight[1] = 0;
1757
1758                 /* special exception here for too high pressure values on first touch in
1759                  * windows for some tablets, then we just skip first touch...
1760                  */
1761                 if (tablet && (p->pressure >= 0.99f))
1762                         return;
1763         }
1764
1765         /* check if alt key is pressed and limit to straight lines */
1766         if ((p->paintmode != GP_PAINTMODE_ERASER) && (p->straight[0] != 0)) {
1767                 if (p->straight[0] == 1) {
1768                         /* horizontal */
1769                         p->mval[1] = p->straight[1]; /* replace y */
1770                 }
1771                 else {
1772                         /* vertical */
1773                         p->mval[0] = p->straight[1]; /* replace x */
1774                 }
1775         }
1776
1777         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1778         RNA_collection_add(op->ptr, "stroke", &itemptr);
1779
1780         mousef[0] = p->mval[0];
1781         mousef[1] = p->mval[1];
1782         RNA_float_set_array(&itemptr, "mouse", mousef);
1783         RNA_float_set(&itemptr, "pressure", p->pressure);
1784         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
1785
1786         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
1787
1788         /* apply the current latest drawing point */
1789         gpencil_draw_apply(op, p, depsgraph);
1790
1791         /* force refresh */
1792         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1793 }
1794
1795 /* ------------------------------- */
1796
1797 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1798 static int gpencil_draw_exec(bContext *C, wmOperator *op)
1799 {
1800         tGPsdata *p = NULL;
1801         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1802
1803         /* printf("GPencil - Starting Re-Drawing\n"); */
1804
1805         /* try to initialize context data needed while drawing */
1806         if (!gpencil_draw_init(C, op, NULL)) {
1807                 if (op->customdata) MEM_freeN(op->customdata);
1808                 /* printf("\tGP - no valid data\n"); */
1809                 return OPERATOR_CANCELLED;
1810         }
1811         else
1812                 p = op->customdata;
1813
1814         /* printf("\tGP - Start redrawing stroke\n"); */
1815
1816         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1817          * setting the relevant values in context at each step, then applying
1818          */
1819         RNA_BEGIN (op->ptr, itemptr, "stroke")
1820         {
1821                 float mousef[2];
1822
1823                 /* printf("\t\tGP - stroke elem\n"); */
1824
1825                 /* get relevant data for this point from stroke */
1826                 RNA_float_get_array(&itemptr, "mouse", mousef);
1827                 p->mval[0] = (int)mousef[0];
1828                 p->mval[1] = (int)mousef[1];
1829                 p->pressure = RNA_float_get(&itemptr, "pressure");
1830                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
1831
1832                 if (RNA_boolean_get(&itemptr, "is_start")) {
1833                         /* if first-run flag isn't set already (i.e. not true first stroke),
1834                          * then we must terminate the previous one first before continuing
1835                          */
1836                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1837                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
1838                                 gp_paint_strokeend(p);
1839                                 gp_paint_initstroke(p, p->paintmode, depsgraph);
1840                         }
1841                 }
1842
1843                 /* if first run, set previous data too */
1844                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1845                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1846
1847                         p->mvalo[0] = p->mval[0];
1848                         p->mvalo[1] = p->mval[1];
1849                         p->opressure = p->pressure;
1850                         p->ocurtime = p->curtime;
1851                 }
1852
1853                 /* apply this data as necessary now (as per usual) */
1854                 gpencil_draw_apply(op, p, depsgraph);
1855         }
1856         RNA_END;
1857
1858         /* printf("\tGP - done\n"); */
1859
1860         /* cleanup */
1861         gpencil_draw_exit(C, op);
1862
1863         /* refreshes */
1864         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1865
1866         /* done */
1867         return OPERATOR_FINISHED;
1868 }
1869
1870 /* ------------------------------- */
1871
1872 /* start of interactive drawing part of operator */
1873 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1874 {
1875         Object *ob = CTX_data_active_object(C);
1876         ScrArea *sa = CTX_wm_area(C);
1877         Scene *scene = CTX_data_scene(C);
1878         tGPsdata *p = NULL;
1879
1880         /* if try to do annotations with a gp object selected, first
1881          * unselect the object to avoid conflicts.
1882          * The solution is not perfect but we can keep running the annotations while
1883          * found a better solution.
1884          */
1885         if (sa && sa->spacetype == SPACE_VIEW3D) {
1886                 if ((ob != NULL) && (ob->type == OB_GPENCIL)) {
1887                         ob->mode = OB_MODE_OBJECT;
1888                         bGPdata *gpd = (bGPdata *)ob->data;
1889                         ED_gpencil_setup_modes(C, gpd, 0);
1890                         DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);
1891
1892                         ViewLayer *view_layer = CTX_data_view_layer(C);
1893                         BKE_view_layer_base_deselect_all(view_layer);
1894                         view_layer->basact = NULL;
1895                         DEG_id_tag_update(&scene->id, ID_RECALC_SELECT);
1896                         WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
1897                 }
1898         }
1899
1900         if (G.debug & G_DEBUG)
1901                 printf("GPencil - Starting Drawing\n");
1902
1903         /* try to initialize context data needed while drawing */
1904         if (!gpencil_draw_init(C, op, event)) {
1905                 if (op->customdata)
1906                         MEM_freeN(op->customdata);
1907                 if (G.debug & G_DEBUG)
1908                         printf("\tGP - no valid data\n");
1909                 return OPERATOR_CANCELLED;
1910         }
1911         else
1912                 p = op->customdata;
1913
1914         /* TODO: set any additional settings that we can take from the events?
1915          * TODO? if tablet is erasing, force eraser to be on? */
1916
1917         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
1918
1919         /* if eraser is on, draw radial aid */
1920         if (p->paintmode == GP_PAINTMODE_ERASER) {
1921                 gpencil_draw_toggle_eraser_cursor(C, p, true);
1922         }
1923         /* set cursor
1924          * NOTE: This may change later (i.e. intentionally via brush toggle,
1925          *       or unintentionally if the user scrolls outside the area)...
1926          */
1927         gpencil_draw_cursor_set(p);
1928
1929         /* only start drawing immediately if we're allowed to do so... */
1930         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
1931                 /* hotkey invoked - start drawing */
1932                 /* printf("\tGP - set first spot\n"); */
1933                 p->status = GP_STATUS_PAINTING;
1934
1935                 /* handle the initial drawing - i.e. for just doing a simple dot */
1936                 gpencil_draw_apply_event(op, event, CTX_data_depsgraph(C));
1937                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
1938         }
1939         else {
1940                 /* toolbar invoked - don't start drawing yet... */
1941                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
1942                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
1943         }
1944
1945         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1946         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1947         WM_event_add_modal_handler(C, op);
1948         return OPERATOR_RUNNING_MODAL;
1949 }
1950
1951 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1952 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
1953 {
1954         bScreen *sc = CTX_wm_screen(C);
1955         return (BLI_findindex(&sc->areabase, sa_test) != -1);
1956 }
1957
1958 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
1959 {
1960         tGPsdata *p = op->customdata;
1961
1962         /* we must check that we're still within the area that we're set up to work from
1963          * otherwise we could crash (see bug #20586)
1964          */
1965         if (CTX_wm_area(C) != p->sa) {
1966                 printf("\t\t\tGP - wrong area execution abort!\n");
1967                 p->status = GP_STATUS_ERROR;
1968         }
1969
1970         /* printf("\t\tGP - start stroke\n"); */
1971
1972         /* we may need to set up paint env again if we're resuming */
1973         /* XXX: watch it with the paintmode! in future,
1974          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
1975
1976         if (gp_session_initdata(C, p))
1977                 gp_paint_initstroke(p, p->paintmode, CTX_data_depsgraph(C));
1978
1979         if (p->status != GP_STATUS_ERROR) {
1980                 p->status = GP_STATUS_PAINTING;
1981                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
1982         }
1983
1984         return op->customdata;
1985 }
1986
1987 static void gpencil_stroke_end(wmOperator *op)
1988 {
1989         tGPsdata *p = op->customdata;
1990
1991         gp_paint_cleanup(p);
1992
1993         gpencil_undo_push(p->gpd);
1994
1995         gp_session_cleanup(p);
1996
1997         p->status = GP_STATUS_IDLING;
1998         op->flag |= OP_IS_MODAL_CURSOR_REGION;
1999
2000         p->gpd = NULL;
2001         p->gpl = NULL;
2002         p->gpf = NULL;
2003 }
2004
2005 /* events handling during interactive drawing part of operator */
2006 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2007 {
2008         tGPsdata *p = op->customdata;
2009         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2010
2011         /* if (event->type == NDOF_MOTION)
2012          *    return OPERATOR_PASS_THROUGH;
2013          * -------------------------------
2014          * [mce] Not quite what I was looking
2015          * for, but a good start! GP continues to
2016          * draw on the screen while the 3D mouse
2017          * moves the viewpoint. Problem is that
2018          * the stroke is converted to 3D only after
2019          * it is finished. This approach should work
2020          * better in tools that immediately apply
2021          * in 3D space.
2022          */
2023
2024         if (p->status == GP_STATUS_IDLING) {
2025                 ARegion *ar = CTX_wm_region(C);
2026                 p->ar = ar;
2027         }
2028
2029         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2030         if (ISKEYBOARD(event->type)) {
2031                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2032                         /* allow some keys:
2033                          *   - for frame changing [#33412]
2034                          *   - for undo (during sketching sessions)
2035                          */
2036                 }
2037                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2038                         /* allow numpad keys so that camera/view manipulations can still take place
2039                          * - PAD0 in particular is really important for Grease Pencil drawing,
2040                          *   as animators may be working "to camera", so having this working
2041                          *   is essential for ensuring that they can quickly return to that view
2042                          */
2043                 }
2044                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2045                         /* Add Blank Frame
2046                          * - Since this operator is non-modal, we can just call it here, and keep going...
2047                          * - This operator is especially useful when animating
2048                          */
2049                         WM_operator_name_call(C, "GPENCIL_OT_blank_frame_add", WM_OP_EXEC_DEFAULT, NULL);
2050                         estate = OPERATOR_RUNNING_MODAL;
2051                 }
2052                 else {
2053                         estate = OPERATOR_RUNNING_MODAL;
2054                 }
2055         }
2056
2057         //printf("\tGP - handle modal event...\n");
2058
2059         /* exit painting mode (and/or end current stroke)
2060          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
2061          */
2062         if (ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, EKEY)) {
2063                 /* exit() ends the current stroke before cleaning up */
2064                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
2065                 p->status = GP_STATUS_DONE;
2066                 estate = OPERATOR_FINISHED;
2067         }
2068
2069         /* toggle painting mode upon mouse-button movement
2070          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
2071          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
2072          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
2073          * also making sure we have a valid event value, to not exit too early
2074          */
2075         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE) && (ELEM(event->val, KM_PRESS, KM_RELEASE))) {
2076                 /* if painting, end stroke */
2077                 if (p->status == GP_STATUS_PAINTING) {
2078                         int sketch = 0;
2079
2080                         /* basically, this should be mouse-button up = end stroke
2081                          * BUT, polyline drawing is an exception -- all knots should be added during one session
2082                          */
2083                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
2084
2085                         if (sketch) {
2086                                 /* end stroke only, and then wait to resume painting soon */
2087                                 /* printf("\t\tGP - end stroke only\n"); */
2088                                 gpencil_stroke_end(op);
2089
2090                                 /* If eraser mode is on, turn it off after the stroke finishes
2091                                  * NOTE: This just makes it nicer to work with drawing sessions
2092                                  */
2093                                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2094                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2095
2096                                         /* if the original mode was *still* eraser,
2097                                          * we'll let it say for now, since this gives
2098                                          * users an opportunity to have visual feedback
2099                                          * when adjusting eraser size
2100                                          */
2101                                         if (p->paintmode != GP_PAINTMODE_ERASER) {
2102                                                 /* turn off cursor...
2103                                                  * NOTE: this should be enough for now
2104                                                  *       Just hiding this makes it seem like
2105                                                  *       you can paint again...
2106                                                  */
2107                                                 gpencil_draw_toggle_eraser_cursor(C, p, false);
2108                                         }
2109                                 }
2110
2111                                 /* we've just entered idling state, so this event was processed (but no others yet) */
2112                                 estate = OPERATOR_RUNNING_MODAL;
2113
2114                                 /* stroke could be smoothed, send notifier to refresh screen */
2115                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2116                         }
2117                         else {
2118                                 /* printf("\t\tGP - end of stroke + op\n"); */
2119                                 p->status = GP_STATUS_DONE;
2120                                 estate = OPERATOR_FINISHED;
2121                         }
2122                 }
2123                 else if (event->val == KM_PRESS) {
2124                         bool in_bounds = false;
2125
2126                         /* Check if we're outside the bounds of the active region
2127                          * NOTE: An exception here is that if launched from the toolbar,
2128                          *       whatever region we're now in should become the new region
2129                          */
2130                         if ((p->ar) && (p->ar->regiontype == RGN_TYPE_TOOLS)) {
2131                                 /* Change to whatever region is now under the mouse */
2132                                 ARegion *current_region = BKE_area_find_region_xy(p->sa, RGN_TYPE_ANY, event->x, event->y);
2133
2134                                 if (G.debug & G_DEBUG) {
2135                                         printf("found alternative region %p (old was %p) - at %d %d (sa: %d %d -> %d %d)\n",
2136                                                 current_region, p->ar, event->x, event->y,
2137                                                 p->sa->totrct.xmin, p->sa->totrct.ymin, p->sa->totrct.xmax, p->sa->totrct.ymax);
2138                                 }
2139
2140                                 if (current_region) {
2141                                         /* Assume that since we found the cursor in here, it is in bounds
2142                                          * and that this should be the region that we begin drawing in
2143                                          */
2144                                         p->ar = current_region;
2145                                         in_bounds = true;
2146                                 }
2147                                 else {
2148                                         /* Out of bounds, or invalid in some other way */
2149                                         p->status = GP_STATUS_ERROR;
2150                                         estate = OPERATOR_CANCELLED;
2151
2152                                         if (G.debug & G_DEBUG)
2153                                                 printf("%s: Region under cursor is out of bounds, so cannot be drawn on\n", __func__);
2154                                 }
2155                         }
2156                         else if (p->ar) {
2157                                 rcti region_rect;
2158
2159                                 /* Perform bounds check using  */
2160                                 ED_region_visible_rect(p->ar, &region_rect);
2161                                 in_bounds = BLI_rcti_isect_pt_v(&region_rect, event->mval);
2162                         }
2163                         else {
2164                                 /* No region */
2165                                 p->status = GP_STATUS_ERROR;
2166                                 estate = OPERATOR_CANCELLED;
2167
2168                                 if (G.debug & G_DEBUG)
2169                                         printf("%s: No active region found in GP Paint session data\n", __func__);
2170                         }
2171
2172                         if (in_bounds) {
2173                                 /* Switch paintmode (temporarily if need be) based on which button was used
2174                                  * NOTE: This is to make it more convenient to erase strokes when using drawing sessions
2175                                  */
2176                                 if ((event->type == RIGHTMOUSE) || gpencil_is_tablet_eraser_active(event)) {
2177                                         /* turn on eraser */
2178                                         p->paintmode = GP_PAINTMODE_ERASER;
2179                                 }
2180                                 else if (event->type == LEFTMOUSE) {
2181                                         /* restore drawmode to default */
2182                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2183                                 }
2184
2185                                 gpencil_draw_toggle_eraser_cursor(C, p, p->paintmode == GP_PAINTMODE_ERASER);
2186
2187                                 /* not painting, so start stroke (this should be mouse-button down) */
2188                                 p = gpencil_stroke_begin(C, op);
2189
2190                                 if (p->status == GP_STATUS_ERROR) {
2191                                         estate = OPERATOR_CANCELLED;
2192                                 }
2193                         }
2194                         else if (p->status != GP_STATUS_ERROR) {
2195                                 /* User clicked outside bounds of window while idling, so exit paintmode
2196                                  * NOTE: Don't enter this case if an error occurred while finding the
2197                                  *       region (as above)
2198                                  */
2199                                 p->status = GP_STATUS_DONE;
2200                                 estate = OPERATOR_FINISHED;
2201                         }
2202                 }
2203                 else if (event->val == KM_RELEASE) {
2204                         p->status = GP_STATUS_IDLING;
2205                         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2206                 }
2207         }
2208
2209         /* handle mode-specific events */
2210         if (p->status == GP_STATUS_PAINTING) {
2211                 /* handle painting mouse-movements? */
2212                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
2213                         /* handle drawing event */
2214                         /* printf("\t\tGP - add point\n"); */
2215                         gpencil_draw_apply_event(op, event, CTX_data_depsgraph(C));
2216
2217                         /* finish painting operation if anything went wrong just now */
2218                         if (p->status == GP_STATUS_ERROR) {
2219                                 printf("\t\t\t\tGP - add error done!\n");
2220                                 estate = OPERATOR_CANCELLED;
2221                         }
2222                         else {
2223                                 /* event handled, so just tag as running modal */
2224                                 /* printf("\t\t\t\tGP - add point handled!\n"); */
2225                                 estate = OPERATOR_RUNNING_MODAL;
2226                         }
2227                 }
2228                 /* eraser size */
2229                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
2230                          ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
2231                 {
2232                         /* just resize the brush (local version)
2233                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
2234                          */
2235                         /* printf("\t\tGP - resize eraser\n"); */
2236                         switch (event->type) {
2237                                 case WHEELDOWNMOUSE: /* larger */
2238                                 case PADPLUSKEY:
2239                                         p->radius += 5;
2240                                         break;
2241
2242                                 case WHEELUPMOUSE: /* smaller */
2243                                 case PADMINUS:
2244                                         p->radius -= 5;
2245
2246                                         if (p->radius <= 0)
2247                                                 p->radius = 1;
2248                                         break;
2249                         }
2250
2251                         /* force refresh */
2252                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2253
2254                         /* event handled, so just tag as running modal */
2255                         estate = OPERATOR_RUNNING_MODAL;
2256                 }
2257                 /* there shouldn't be any other events, but just in case there are, let's swallow them
2258                  * (i.e. to prevent problems with undo)
2259                  */
2260                 else {
2261                         /* swallow event to save ourselves trouble */
2262                         estate = OPERATOR_RUNNING_MODAL;
2263                 }
2264         }
2265
2266         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2267         if (0 == gpencil_area_exists(C, p->sa))
2268                 estate = OPERATOR_CANCELLED;
2269         else {
2270                 /* update status indicators - cursor, header, etc. */
2271                 gpencil_draw_status_indicators(C, p);
2272                 gpencil_draw_cursor_set(p); /* cursor may have changed outside our control - T44084 */
2273         }
2274
2275         /* process last operations before exiting */
2276         switch (estate) {
2277                 case OPERATOR_FINISHED:
2278                         /* one last flush before we're done */
2279                         gpencil_draw_exit(C, op);
2280                         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2281                         break;
2282
2283                 case OPERATOR_CANCELLED:
2284                         gpencil_draw_exit(C, op);
2285                         break;
2286
2287                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
2288                         /* event doesn't need to be handled */
2289 #if 0
2290                         printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
2291                                event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
2292 #endif
2293                         break;
2294         }
2295
2296         /* return status code */
2297         return estate;
2298 }
2299
2300 /* ------------------------------- */
2301
2302 static const EnumPropertyItem prop_gpencil_drawmodes[] = {
2303         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
2304         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
2305         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
2306         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Annotation strokes"},
2307         {0, NULL, 0, NULL, NULL}
2308 };
2309
2310 void GPENCIL_OT_annotate(wmOperatorType *ot)
2311 {
2312         PropertyRNA *prop;
2313
2314         /* identifiers */
2315         ot->name = "Annotation Draw";
2316         ot->idname = "GPENCIL_OT_annotate";
2317         ot->description = "Make annotations on the active data";
2318
2319         /* api callbacks */
2320         ot->exec = gpencil_draw_exec;
2321         ot->invoke = gpencil_draw_invoke;
2322         ot->modal = gpencil_draw_modal;
2323         ot->cancel = gpencil_draw_cancel;
2324         ot->poll = gpencil_draw_poll;
2325
2326         /* flags */
2327         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2328
2329         /* settings for drawing */
2330         ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
2331
2332         prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2333         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2334
2335         /* NOTE: wait for input is enabled by default, so that all UI code can work properly without needing users to know about this */
2336         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
2337         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
2338 }