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