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