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