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