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