GPencil: New Dots gradient
[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->gradient_f = brush->gpencil_settings->gradient_f;
948         copy_v2_v2(gps->gradient_s, brush->gpencil_settings->gradient_s);
949         gps->flag = gpd->runtime.sbuffer_sflag;
950         gps->inittime = p->inittime;
951
952         /* enable recalculation flag by default (only used if hq fill) */
953         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
954
955         /* allocate enough memory for a continuous array for storage points */
956         const int subdivide = brush->gpencil_settings->draw_subdivide;
957
958         gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
959
960         /* initialize triangle memory to dummy data */
961         gps->triangles = MEM_callocN(sizeof(bGPDtriangle), "GP Stroke triangulation");
962         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
963         gps->tot_triangles = 0;
964         /* drawing batch cache is dirty now */
965         gp_update_cache(p->gpd);
966         /* set pointer to first non-initialized point */
967         pt = gps->points + (gps->totpoints - totelem);
968         if (gps->dvert != NULL) {
969                 dvert = gps->dvert + (gps->totpoints - totelem);
970         }
971
972         /* copy points from the buffer to the stroke */
973         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
974                 /* straight lines only -> only endpoints */
975                 {
976                         /* first point */
977                         ptc = gpd->runtime.sbuffer;
978
979                         /* convert screen-coordinates to appropriate coordinates (and store them) */
980                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
981                         /* copy pressure and time */
982                         pt->pressure = ptc->pressure;
983                         pt->strength = ptc->strength;
984                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
985                         pt->time = ptc->time;
986                         pt++;
987
988                         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
989                                 BKE_gpencil_dvert_ensure(gps);
990                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
991                                 if (dw) {
992                                         dw->weight = ts->vgroup_weight;
993                                 }
994                                 dvert++;
995                         }
996                         else {
997                                 if (dvert != NULL) {
998                                         dvert->totweight = 0;
999                                         dvert->dw = NULL;
1000                                         dvert++;
1001                                 }
1002                         }
1003                 }
1004
1005                 if (totelem == 2) {
1006                         /* last point if applicable */
1007                         ptc = ((tGPspoint *)gpd->runtime.sbuffer) + (gpd->runtime.sbuffer_size - 1);
1008
1009                         /* convert screen-coordinates to appropriate coordinates (and store them) */
1010                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
1011                         /* copy pressure and time */
1012                         pt->pressure = ptc->pressure;
1013                         pt->strength = ptc->strength;
1014                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1015                         pt->time = ptc->time;
1016
1017                         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1018                                 BKE_gpencil_dvert_ensure(gps);
1019                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
1020                                 if (dw) {
1021                                         dw->weight = ts->vgroup_weight;
1022                                 }
1023                         }
1024                         else {
1025                                 if (dvert != NULL) {
1026                                         dvert->totweight = 0;
1027                                         dvert->dw = NULL;
1028                                 }
1029                         }
1030                 }
1031
1032                 /* reproject to plane (only in 3d space) */
1033                 gp_reproject_toplane(p, gps);
1034                 pt = gps->points;
1035                 for (i = 0; i < gps->totpoints; i++, pt++) {
1036                         /* if parented change position relative to parent object */
1037                         gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
1038                 }
1039
1040                 /* if camera view, reproject flat to view to avoid perspective effect */
1041                 if (is_camera) {
1042                         ED_gpencil_project_stroke_to_view(p->C, p->gpl, gps);
1043                 }
1044         }
1045         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
1046                 /* first point */
1047                 ptc = gpd->runtime.sbuffer;
1048
1049                 /* convert screen-coordinates to appropriate coordinates (and store them) */
1050                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
1051                 /* reproject to plane (only in 3d space) */
1052                 gp_reproject_toplane(p, gps);
1053                 /* if parented change position relative to parent object */
1054                 gp_apply_parent_point(depsgraph, obact, gpd, gpl, pt);
1055                 /* if camera view, reproject flat to view to avoid perspective effect */
1056                 if (is_camera) {
1057                         ED_gpencil_project_stroke_to_view(p->C, p->gpl, gps);
1058                 }
1059                 /* copy pressure and time */
1060                 pt->pressure = ptc->pressure;
1061                 pt->strength = ptc->strength;
1062                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1063                 pt->time = ptc->time;
1064
1065                 if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1066                         BKE_gpencil_dvert_ensure(gps);
1067                         MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
1068                         if (dw) {
1069                                 dw->weight = ts->vgroup_weight;
1070                         }
1071                 }
1072                 else {
1073                         if (dvert != NULL) {
1074                                 dvert->totweight = 0;
1075                                 dvert->dw = NULL;
1076                         }
1077                 }
1078
1079         }
1080         else {
1081                 float *depth_arr = NULL;
1082
1083                 /* get an array of depths, far depths are blended */
1084                 if (gpencil_project_check(p)) {
1085                         int mval_i[2], mval_prev[2] = { 0 };
1086                         int interp_depth = 0;
1087                         int found_depth = 0;
1088
1089                         depth_arr = MEM_mallocN(sizeof(float) * gpd->runtime.sbuffer_size, "depth_points");
1090
1091                         for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size; i++, ptc++, pt++) {
1092
1093                                 round_v2i_v2fl(mval_i, &ptc->x);
1094
1095                                 if ((ED_view3d_autodist_depth(p->ar, mval_i, depth_margin, depth_arr + i) == 0) &&
1096                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval_i, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
1097                                 {
1098                                         interp_depth = true;
1099                                 }
1100                                 else {
1101                                         found_depth = true;
1102                                 }
1103
1104                                 copy_v2_v2_int(mval_prev, mval_i);
1105                         }
1106
1107                         if (found_depth == false) {
1108                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
1109                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--)
1110                                         depth_arr[i] = 0.9999f;
1111                         }
1112                         else {
1113                                 if ((ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) ||
1114                                     (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST))
1115                                 {
1116                                         int first_valid = 0;
1117                                         int last_valid = 0;
1118
1119                                         /* find first valid contact point */
1120                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
1121                                                 if (depth_arr[i] != FLT_MAX)
1122                                                         break;
1123                                         }
1124                                         first_valid = i;
1125
1126                                         /* find last valid contact point */
1127                                         if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST) {
1128                                                 last_valid = first_valid;
1129                                         }
1130                                         else {
1131                                                 for (i = gpd->runtime.sbuffer_size - 1; i >= 0; i--) {
1132                                                         if (depth_arr[i] != FLT_MAX)
1133                                                                 break;
1134                                                 }
1135                                                 last_valid = i;
1136                                         }
1137                                         /* invalidate any other point, to interpolate between
1138                                          * first and last contact in an imaginary line between them */
1139                                         for (i = 0; i < gpd->runtime.sbuffer_size; i++) {
1140                                                 if ((i != first_valid) && (i != last_valid)) {
1141                                                         depth_arr[i] = FLT_MAX;
1142                                                 }
1143                                         }
1144                                         interp_depth = true;
1145                                 }
1146
1147                                 if (interp_depth) {
1148                                         interp_sparse_array(depth_arr, gpd->runtime.sbuffer_size, FLT_MAX);
1149                                 }
1150                         }
1151                 }
1152
1153                 pt = gps->points;
1154                 dvert = gps->dvert;
1155
1156                 /* convert all points (normal behavior) */
1157                 for (i = 0, ptc = gpd->runtime.sbuffer; i < gpd->runtime.sbuffer_size && ptc; i++, ptc++, pt++) {
1158                         /* convert screen-coordinates to appropriate coordinates (and store them) */
1159                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
1160
1161                         /* copy pressure and time */
1162                         pt->pressure = ptc->pressure;
1163                         pt->strength = ptc->strength;
1164                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1165                         pt->time = ptc->time;
1166                         pt->uv_fac = ptc->uv_fac;
1167                         pt->uv_rot = ptc->uv_rot;
1168
1169                         if (dvert != NULL) {
1170                                 dvert->totweight = 0;
1171                                 dvert->dw = NULL;
1172                                 dvert++;
1173                         }
1174                 }
1175
1176                 /* subdivide and smooth the stroke */
1177                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) && (subdivide > 0)) {
1178                         gp_subdivide_stroke(gps, subdivide);
1179                 }
1180                 /* apply randomness to stroke */
1181                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
1182                     (brush->gpencil_settings->draw_random_sub > 0.0f))
1183                 {
1184                         gp_randomize_stroke(gps, brush, p->rng);
1185                 }
1186
1187                 /* smooth stroke after subdiv - only if there's something to do
1188                  * for each iteration, the factor is reduced to get a better smoothing without changing too much
1189                  * the original stroke
1190                  */
1191                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1192                     (brush->gpencil_settings->draw_smoothfac > 0.0f))
1193                 {
1194                         float reduce = 0.0f;
1195                         for (int r = 0; r < brush->gpencil_settings->draw_smoothlvl; r++) {
1196                                 for (i = 0; i < gps->totpoints - 1; i++) {
1197                                         BKE_gpencil_smooth_stroke(gps, i, brush->gpencil_settings->draw_smoothfac - reduce);
1198                                         BKE_gpencil_smooth_stroke_strength(gps, i, brush->gpencil_settings->draw_smoothfac);
1199                                 }
1200                                 reduce += 0.25f;  // reduce the factor
1201                         }
1202                 }
1203                 /* smooth thickness */
1204                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1205                     (brush->gpencil_settings->thick_smoothfac > 0.0f))
1206                 {
1207                         for (int r = 0; r < brush->gpencil_settings->thick_smoothlvl * 2; r++) {
1208                                 for (i = 0; i < gps->totpoints - 1; i++) {
1209                                         BKE_gpencil_smooth_stroke_thickness(gps, i, brush->gpencil_settings->thick_smoothfac);
1210                                 }
1211                         }
1212                 }
1213
1214                 /* reproject to plane (only in 3d space) */
1215                 gp_reproject_toplane(p, gps);
1216                 /* change position relative to parent object */
1217                 gp_apply_parent(depsgraph, obact, gpd, gpl, gps);
1218                 /* if camera view, reproject flat to view to avoid perspective effect */
1219                 if (is_camera) {
1220                         ED_gpencil_project_stroke_to_view(p->C, p->gpl, gps);
1221                 }
1222
1223                 if (depth_arr)
1224                         MEM_freeN(depth_arr);
1225         }
1226
1227         /* Save material index */
1228         gps->mat_nr = BKE_gpencil_object_material_get_index_from_brush(p->ob, p->brush);
1229
1230         /* calculate UVs along the stroke */
1231         ED_gpencil_calc_stroke_uv(obact, gps);
1232
1233         /* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head
1234          * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
1235          * when drawing the background
1236          */
1237         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
1238                 BLI_addhead(&p->gpf->strokes, gps);
1239         }
1240         else {
1241                 BLI_addtail(&p->gpf->strokes, gps);
1242         }
1243         /* add weights */
1244         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1245                 BKE_gpencil_dvert_ensure(gps);
1246                 for (i = 0; i < gps->totpoints; i++) {
1247                         MDeformVert *ve = &gps->dvert[i];
1248                         MDeformWeight *dw = defvert_verify_index(ve, def_nr);
1249                         if (dw) {
1250                                 dw->weight = ts->vgroup_weight;
1251                         }
1252                 }
1253         }
1254
1255         /* post process stroke */
1256         if ((p->brush->gpencil_settings->flag & GP_BRUSH_GROUP_SETTINGS) &&
1257             p->brush->gpencil_settings->flag & GP_BRUSH_TRIM_STROKE)
1258         {
1259                 BKE_gpencil_trim_stroke(gps);
1260         }
1261
1262         gp_stroke_added_enable(p);
1263 }
1264
1265 /* --- 'Eraser' for 'Paint' Tool ------ */
1266
1267 /* which which point is infront (result should only be used for comparison) */
1268 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1269 {
1270         if (rv3d->is_persp) {
1271                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1272         }
1273         else {
1274                 return -dot_v3v3(rv3d->viewinv[2], co);
1275         }
1276 }
1277
1278 /* only erase stroke points that are visible */
1279 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1280 {
1281         Object *obact = (Object *)p->ownerPtr.data;
1282         Brush *brush = p->brush;
1283         Brush *eraser = p->eraser;
1284         BrushGpencilSettings *gp_settings = NULL;
1285
1286         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1287                 gp_settings = brush->gpencil_settings;
1288         }
1289         else if ((eraser != NULL) & (eraser->gpencil_tool == GPAINT_TOOL_ERASE)) {
1290                 gp_settings = eraser->gpencil_settings;
1291         }
1292
1293         if ((gp_settings != NULL) && (p->sa->spacetype == SPACE_VIEW3D) &&
1294             (gp_settings->flag & GP_BRUSH_OCCLUDE_ERASER))
1295         {
1296                 RegionView3D *rv3d = p->ar->regiondata;
1297                 bGPDlayer *gpl = p->gpl;
1298
1299                 const int mval_i[2] = {x, y};
1300                 float mval_3d[3];
1301                 float fpt[3];
1302
1303                 float diff_mat[4][4];
1304                 /* calculate difference matrix if parent object */
1305                 ED_gpencil_parent_location(p->depsgraph, obact, p->gpd, gpl, diff_mat);
1306
1307                 if (ED_view3d_autodist_simple(p->ar, mval_i, mval_3d, 0, NULL)) {
1308                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1309
1310                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1311                         const float depth_pt = view3d_point_depth(rv3d, fpt);
1312
1313                         if (depth_pt > depth_mval) {
1314                                 return true;
1315                         }
1316                 }
1317         }
1318         return false;
1319 }
1320
1321 /* apply a falloff effect to brush strength, based on distance */
1322 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const float mval[2], const int radius, const int co[2])
1323 {
1324         Brush *brush = p->brush;
1325         /* Linear Falloff... */
1326         int mval_i[2];
1327         round_v2i_v2fl(mval_i, mval);
1328         float distance = (float)len_v2v2_int(mval_i, co);
1329         float fac;
1330
1331         CLAMP(distance, 0.0f, (float)radius);
1332         fac = 1.0f - (distance / (float)radius);
1333
1334         /* apply strength factor */
1335         fac *= brush->gpencil_settings->draw_strength;
1336
1337         /* Control this further using pen pressure */
1338         if (brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE) {
1339                 fac *= p->pressure;
1340         }
1341         /* Return influence factor computed here */
1342         return fac;
1343 }
1344
1345 /* helper to free a stroke */
1346 static void gp_free_stroke(bGPdata *gpd, bGPDframe *gpf, bGPDstroke *gps)
1347 {
1348         if (gps->points) {
1349                 MEM_freeN(gps->points);
1350         }
1351
1352         if (gps->dvert) {
1353                 BKE_gpencil_free_stroke_weights(gps);
1354                 MEM_freeN(gps->dvert);
1355         }
1356
1357         if (gps->triangles)
1358                 MEM_freeN(gps->triangles);
1359         BLI_freelinkN(&gpf->strokes, gps);
1360         gp_update_cache(gpd);
1361 }
1362
1363 /**
1364  * Analyze points to be removed when soft eraser is used
1365  * to avoid that segments gets the end points rounded.
1366  * The round caps breaks the artistic effect.
1367  */
1368 static void gp_stroke_soft_refine(bGPDstroke *gps)
1369 {
1370         bGPDspoint *pt = NULL;
1371         bGPDspoint *pt2 = NULL;
1372         int i;
1373
1374         /* check if enough points*/
1375         if (gps->totpoints < 3) {
1376                 return;
1377         }
1378
1379         /* loop all points to untag any point that next is not tagged */
1380         pt = gps->points;
1381         for (i = 1; i < gps->totpoints - 1; i++, pt++) {
1382                 if (pt->flag & GP_SPOINT_TAG) {
1383                         pt2 = &gps->points[i + 1];
1384                         if ((pt2->flag & GP_SPOINT_TAG) == 0) {
1385                                 pt->flag &= ~GP_SPOINT_TAG;
1386                         }
1387                 }
1388         }
1389
1390         /* loop reverse all points to untag any point that previous is not tagged */
1391         pt = &gps->points[gps->totpoints - 1];
1392         for (i = gps->totpoints - 1; i > 0; i--, pt--) {
1393                 if (pt->flag & GP_SPOINT_TAG) {
1394                         pt2 = &gps->points[i - 1];
1395                         if ((pt2->flag & GP_SPOINT_TAG) == 0) {
1396                                 pt->flag &= ~GP_SPOINT_TAG;
1397                         }
1398                 }
1399         }
1400 }
1401
1402 /* eraser tool - evaluation per stroke */
1403 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1404 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1405         bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1406         const float mval[2], const float mvalo[2],
1407         const int radius, const rcti *rect)
1408 {
1409         Depsgraph *depsgraph = p->depsgraph;
1410         Object *obact = (Object *)p->ownerPtr.data;
1411         Brush *eraser = p->eraser;
1412         bGPDspoint *pt0, *pt1, *pt2;
1413         int pc0[2] = {0};
1414         int pc1[2] = {0};
1415         int pc2[2] = {0};
1416         int i;
1417         float diff_mat[4][4];
1418         int mval_i[2];
1419         round_v2i_v2fl(mval_i, mval);
1420
1421         /* calculate difference matrix */
1422         ED_gpencil_parent_location(depsgraph, obact, p->gpd, gpl, diff_mat);
1423
1424         if (gps->totpoints == 0) {
1425                 /* just free stroke */
1426                 gp_free_stroke(p->gpd, gpf, gps);
1427         }
1428         else if (gps->totpoints == 1) {
1429                 /* only process if it hasn't been masked out... */
1430                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1431                         bGPDspoint pt_temp;
1432                         gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1433                         gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1434                         /* do boundbox check first */
1435                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1436                                 /* only check if point is inside */
1437                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1438                                         /* free stroke */
1439                                         gp_free_stroke(p->gpd, gpf, gps);
1440                                 }
1441                         }
1442                 }
1443         }
1444         else if ((p->flags & GP_PAINTFLAG_STROKE_ERASER) || (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_STROKE)) {
1445                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1446
1447                         /* only process if it hasn't been masked out... */
1448                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1449                                 continue;
1450
1451                         /* get points to work with */
1452                         pt1 = gps->points + i;
1453                         bGPDspoint npt;
1454                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1455                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1456
1457                         /* do boundbox check first */
1458                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1459                                 /* only check if point is inside */
1460                                 if (len_v2v2_int(mval_i, pc1) <= radius) {
1461                                         /* free stroke */
1462                                         gp_free_stroke(p->gpd, gpf, gps);
1463                                         return;
1464                                 }
1465                         }
1466                 }
1467         }
1468         else {
1469                 /* Pressure threshold at which stroke should be culled */
1470                 const float cull_thresh = 0.005f;
1471
1472                 /* Amount to decrease the pressure of each point with each stroke */
1473                 const float strength = 0.1f;
1474
1475                 /* Perform culling? */
1476                 bool do_cull = false;
1477
1478                 /* Clear Tags
1479                  *
1480                  * Note: It's better this way, as we are sure that
1481                  * we don't miss anything, though things will be
1482                  * slightly slower as a result
1483                  */
1484                 for (i = 0; i < gps->totpoints; i++) {
1485                         bGPDspoint *pt = &gps->points[i];
1486                         pt->flag &= ~GP_SPOINT_TAG;
1487                 }
1488
1489                 /* First Pass: Loop over the points in the stroke
1490                  *   1) Thin out parts of the stroke under the brush
1491                  *   2) Tag "too thin" parts for removal (in second pass)
1492                  */
1493                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1494                         /* get points to work with */
1495                         pt0 = i > 0 ? gps->points + i - 1 : NULL;
1496                         pt1 = gps->points + i;
1497                         pt2 = gps->points + i + 1;
1498
1499                         /* only process if it hasn't been masked out... */
1500                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1501                                 continue;
1502
1503                         bGPDspoint npt;
1504                         if (pt0) {
1505                                 gp_point_to_parent_space(pt0, diff_mat, &npt);
1506                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc0[0], &pc0[1]);
1507                         }
1508                         else {
1509                                 /* avoid null values */
1510                                 copy_v2_v2_int(pc0, pc1);
1511                         }
1512
1513                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1514                         gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1515
1516                         gp_point_to_parent_space(pt2, diff_mat, &npt);
1517                         gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1518
1519                         /* Check that point segment of the boundbox of the eraser stroke */
1520                         if (((!ELEM(V2D_IS_CLIPPED, pc0[0], pc0[1])) && BLI_rcti_isect_pt(rect, pc0[0], pc0[1])) ||
1521                             ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1522                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1523                         {
1524                                 /* Check if point segment of stroke had anything to do with
1525                                  * eraser region  (either within stroke painted, or on its lines)
1526                                  * - this assumes that linewidth is irrelevant
1527                                  */
1528                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc0[0], pc0[1], pc2[0], pc2[1])) {
1529                                         if ((gp_stroke_eraser_is_occluded(p, pt0, pc0[0], pc0[1]) == false) ||
1530                                             (gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1531                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1532                                         {
1533                                                 /* Point is affected: */
1534                                                 /* Adjust thickness
1535                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1536                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1537                                                  */
1538
1539                                                 /* Adjust strength if the eraser is soft */
1540                                                 if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1541                                                         float f_strength = eraser->gpencil_settings->era_strength_f / 100.0f;
1542                                                         float f_thickness = eraser->gpencil_settings->era_thickness_f / 100.0f;
1543                                                         float influence = 0.0f;
1544
1545                                                         if (pt0) {
1546                                                                 influence = gp_stroke_eraser_calc_influence(p, mval, radius, pc0);
1547                                                                 pt0->strength -= influence * strength * f_strength * 0.5f;
1548                                                                 CLAMP_MIN(pt0->strength, 0.0f);
1549                                                                 pt0->pressure -= influence * strength * f_thickness * 0.5f;
1550                                                         }
1551
1552                                                         influence = gp_stroke_eraser_calc_influence(p, mval, radius, pc1);
1553                                                         pt1->strength -= influence * strength * f_strength;
1554                                                         CLAMP_MIN(pt1->strength, 0.0f);
1555                                                         pt1->pressure -= influence * strength * f_thickness;
1556
1557                                                         influence = gp_stroke_eraser_calc_influence(p, mval, radius, pc2);
1558                                                         pt2->strength -= influence * strength * f_strength * 0.5f;
1559                                                         CLAMP_MIN(pt2->strength, 0.0f);
1560                                                         pt2->pressure -= influence * strength * f_thickness * 0.5f;
1561
1562                                                         /* if invisible, delete point */
1563                                                         if ((pt0) &&
1564                                                             ((pt0->strength <= GPENCIL_ALPHA_OPACITY_THRESH) ||
1565                                                              (pt0->pressure < cull_thresh)))
1566                                                         {
1567                                                                 pt0->flag |= GP_SPOINT_TAG;
1568                                                                 do_cull = true;
1569                                                         }
1570                                                         if ((pt1->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt1->pressure < cull_thresh)) {
1571                                                                 pt1->flag |= GP_SPOINT_TAG;
1572                                                                 do_cull = true;
1573                                                         }
1574                                                         if ((pt2->strength <= GPENCIL_ALPHA_OPACITY_THRESH) || (pt2->pressure < cull_thresh)) {
1575                                                                 pt2->flag |= GP_SPOINT_TAG;
1576                                                                 do_cull = true;
1577                                                         }
1578                                                 }
1579                                                 else {
1580                                                         pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1581                                                         pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength * 0.5f;
1582                                                 }
1583
1584                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1585                                                 if ((pt1->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1586                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1587                                                 {
1588                                                         pt1->flag |= GP_SPOINT_TAG;
1589                                                         do_cull = true;
1590                                                 }
1591                                                 if ((pt2->pressure < cull_thresh) || (p->flags & GP_PAINTFLAG_HARD_ERASER) ||
1592                                                     (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_HARD))
1593                                                 {
1594                                                         pt2->flag |= GP_SPOINT_TAG;
1595                                                         do_cull = true;
1596                                                 }
1597                                         }
1598                                 }
1599                         }
1600                 }
1601
1602                 /* Second Pass: Remove any points that are tagged */
1603                 if (do_cull) {
1604                         /* if soft eraser, must analyze points to be sure the stroke ends
1605                          * don't get rounded */
1606                         if (eraser->gpencil_settings->eraser_mode == GP_BRUSH_ERASER_SOFT) {
1607                                 gp_stroke_soft_refine(gps);
1608                         }
1609
1610                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG, false, 0);
1611                 }
1612                 gp_update_cache(p->gpd);
1613         }
1614 }
1615
1616 /* erase strokes which fall under the eraser strokes */
1617 static void gp_stroke_doeraser(tGPsdata *p)
1618 {
1619         bGPDlayer *gpl;
1620         bGPDstroke *gps, *gpn;
1621         rcti rect;
1622         Brush *brush = p->brush;
1623         Brush *eraser = p->eraser;
1624         bool use_pressure = false;
1625         float press = 1.0f;
1626         BrushGpencilSettings *gp_settings = NULL;
1627
1628         /* detect if use pressure in eraser */
1629         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1630                 use_pressure = (bool)(brush->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1631                 gp_settings = brush->gpencil_settings;
1632         }
1633         else if ((eraser != NULL) & (eraser->gpencil_tool == GPAINT_TOOL_ERASE)) {
1634                 use_pressure = (bool)(eraser->gpencil_settings->flag & GP_BRUSH_USE_PRESSURE);
1635                 gp_settings = eraser->gpencil_settings;
1636         }
1637         if (use_pressure) {
1638                 press = p->pressure;
1639                 CLAMP(press, 0.01f, 1.0f);
1640         }
1641         /* rect is rectangle of eraser */
1642         const int calc_radius = (int)p->radius * press;
1643         rect.xmin = p->mval[0] - calc_radius;
1644         rect.ymin = p->mval[1] - calc_radius;
1645         rect.xmax = p->mval[0] + calc_radius;
1646         rect.ymax = p->mval[1] + calc_radius;
1647
1648         if (p->sa->spacetype == SPACE_VIEW3D) {
1649                 if ((gp_settings != NULL) && (gp_settings->flag & GP_BRUSH_OCCLUDE_ERASER)) {
1650                         View3D *v3d = p->sa->spacedata.first;
1651                         view3d_region_operator_needs_opengl(p->win, p->ar);
1652                         ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, 0);
1653                 }
1654         }
1655
1656         /* loop over all layers too, since while it's easy to restrict editing to
1657          * only a subset of layers, it is harder to perform the same erase operation
1658          * on multiple layers...
1659          */
1660         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1661                 bGPDframe *gpf = gpl->actframe;
1662
1663                 /* only affect layer if it's editable (and visible) */
1664                 if (gpencil_layer_is_editable(gpl) == false) {
1665                         continue;
1666                 }
1667                 else if (gpf == NULL) {
1668                         continue;
1669                 }
1670
1671                 /* loop over strokes, checking segments for intersections */
1672                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1673                         gpn = gps->next;
1674                         /* check if the color is editable */
1675                         if (ED_gpencil_stroke_color_use(p->ob, gpl, gps) == false) {
1676                                 continue;
1677                         }
1678                         /* Not all strokes in the datablock may be valid in the current editor/context
1679                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1680                          */
1681                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1682                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, calc_radius, &rect);
1683                         }
1684                 }
1685         }
1686 }
1687
1688 /* ******************************************* */
1689 /* Sketching Operator */
1690
1691 /* clear the session buffers (call this before AND after a paint operation) */
1692 static void gp_session_validatebuffer(tGPsdata *p)
1693 {
1694         bGPdata *gpd = p->gpd;
1695         Brush *brush = p->brush;
1696
1697         /* clear memory of buffer (or allocate it if starting a new session) */
1698         if (gpd->runtime.sbuffer) {
1699                 /* printf("\t\tGP - reset sbuffer\n"); */
1700                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1701         }
1702         else {
1703                 /* printf("\t\tGP - allocate sbuffer\n"); */
1704                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1705         }
1706
1707         /* reset indices */
1708         gpd->runtime.sbuffer_size = 0;
1709
1710         /* reset flags */
1711         gpd->runtime.sbuffer_sflag = 0;
1712
1713         /* reset region */
1714         gpd->runtime.ar = NULL;
1715
1716         /* reset inittime */
1717         p->inittime = 0.0;
1718
1719         /* reset lazy */
1720         if (brush) {
1721                 brush->gpencil_settings->flag &= ~GP_BRUSH_STABILIZE_MOUSE_TEMP;
1722         }
1723 }
1724
1725 /* helper to get default eraser and create one if no eraser brush */
1726 static Brush *gp_get_default_eraser(Main *bmain, ToolSettings *ts)
1727 {
1728         Brush *brush_dft = NULL;
1729         Paint *paint = &ts->gp_paint->paint;
1730         Brush *brush_old = paint->brush;
1731         for (Brush *brush = bmain->brushes.first; brush; brush = brush->id.next) {
1732                 if ((brush->ob_mode == OB_MODE_PAINT_GPENCIL) &&
1733                     (brush->gpencil_tool == GPAINT_TOOL_ERASE))
1734                 {
1735                         /* save first eraser to use later if no default */
1736                         if (brush_dft == NULL) {
1737                                 brush_dft = brush;
1738                         }
1739                         /* found default */
1740                         if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1741                                 return brush;
1742                         }
1743                 }
1744         }
1745         /* if no default, but exist eraser brush, return this and set as default */
1746         if (brush_dft) {
1747                 brush_dft->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1748                 return brush_dft;
1749         }
1750         /* create a new soft eraser brush */
1751         else {
1752                 brush_dft = BKE_brush_add_gpencil(bmain, ts, "Soft Eraser");
1753                 brush_dft->size = 30.0f;
1754                 brush_dft->gpencil_settings->flag |= (GP_BRUSH_ENABLE_CURSOR | GP_BRUSH_DEFAULT_ERASER);
1755                 brush_dft->gpencil_settings->icon_id = GP_BRUSH_ICON_ERASE_SOFT;
1756                 brush_dft->gpencil_tool = GPAINT_TOOL_ERASE;
1757                 brush_dft->gpencil_settings->eraser_mode = GP_BRUSH_ERASER_SOFT;
1758
1759                 /* reset current brush */
1760                 BKE_paint_brush_set(paint, brush_old);
1761
1762                 return brush_dft;
1763         }
1764 }
1765
1766 /* helper to set default eraser and disable others */
1767 static void gp_set_default_eraser(Main *bmain, Brush *brush_dft)
1768 {
1769         if (brush_dft == NULL) {
1770                 return;
1771         }
1772
1773         for (Brush *brush = bmain->brushes.first; brush; brush = brush->id.next) {
1774                 if ((brush->gpencil_settings) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
1775                         if (brush == brush_dft) {
1776                                 brush->gpencil_settings->flag |= GP_BRUSH_DEFAULT_ERASER;
1777                         }
1778                         else if (brush->gpencil_settings->flag & GP_BRUSH_DEFAULT_ERASER) {
1779                                 brush->gpencil_settings->flag &= ~GP_BRUSH_DEFAULT_ERASER;
1780                         }
1781                 }
1782         }
1783 }
1784
1785 /* initialize a drawing brush */
1786 static void gp_init_drawing_brush(bContext *C, tGPsdata *p)
1787 {
1788         Scene *scene = CTX_data_scene(C);
1789         ToolSettings *ts = CTX_data_tool_settings(C);
1790
1791         Paint *paint = &ts->gp_paint->paint;
1792         bool changed = false;
1793         /* if not exist, create a new one */
1794         if (paint->brush == NULL) {
1795                 /* create new brushes */
1796                 BKE_brush_gpencil_presets(C);
1797                 changed = true;
1798         }
1799         /* be sure curves are initializated */
1800         curvemapping_initialize(paint->brush->gpencil_settings->curve_sensitivity);
1801         curvemapping_initialize(paint->brush->gpencil_settings->curve_strength);
1802         curvemapping_initialize(paint->brush->gpencil_settings->curve_jitter);
1803
1804         /* assign to temp tGPsdata */
1805         p->brush = paint->brush;
1806         if (paint->brush->gpencil_tool != GPAINT_TOOL_ERASE) {
1807                 p->eraser = gp_get_default_eraser(p->bmain, ts);
1808         }
1809         else {
1810                 p->eraser = paint->brush;
1811         }
1812         /* set new eraser as default */
1813         gp_set_default_eraser(p->bmain, p->eraser);
1814
1815         /* use radius of eraser */
1816         p->radius = (short)p->eraser->size;
1817
1818         /* GPXX: Need this update to synchronize brush with draw manager.
1819          * Maybe this update can be removed when the new tool system
1820          * will be in place, but while, we need this to keep drawing working.
1821          */
1822         if (changed) {
1823                 DEG_id_tag_update(&scene->id, ID_RECALC_COPY_ON_WRITE);
1824         }
1825 }
1826
1827
1828 /* initialize a paint brush and a default color if not exist */
1829 static void gp_init_colors(tGPsdata *p)
1830 {
1831         bGPdata *gpd = p->gpd;
1832         Brush *brush = p->brush;
1833
1834         MaterialGPencilStyle *gp_style = NULL;
1835
1836         /* use brush material */
1837         p->material = BKE_gpencil_object_material_ensure_from_active_input_brush(p->bmain, p->ob, brush);
1838
1839         /* assign color information to temp tGPsdata */
1840         gp_style = p->material->gp_style;
1841         if (gp_style) {
1842
1843                 /* set colors */
1844                 if (gp_style->flag & GP_STYLE_STROKE_SHOW) {
1845                         copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
1846                 }
1847                 else {
1848                         /* if no stroke, use fill */
1849                         copy_v4_v4(gpd->runtime.scolor, gp_style->fill_rgba);
1850                 }
1851                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
1852                 /* add some alpha to make easy the filling without hide strokes */
1853                 if (gpd->runtime.sfill[3] > 0.8f) {
1854                         gpd->runtime.sfill[3] = 0.8f;
1855                 }
1856
1857                 gpd->runtime.mode = (short)gp_style->mode;
1858                 gpd->runtime.bstroke_style = gp_style->stroke_style;
1859                 gpd->runtime.bfill_style = gp_style->fill_style;
1860         }
1861 }
1862
1863 /* (re)init new painting data */
1864 static bool gp_session_initdata(bContext *C, wmOperator *op, tGPsdata *p)
1865 {
1866         Main *bmain = CTX_data_main(C);
1867         bGPdata **gpd_ptr = NULL;
1868         ScrArea *curarea = CTX_wm_area(C);
1869         ARegion *ar = CTX_wm_region(C);
1870         ToolSettings *ts = CTX_data_tool_settings(C);
1871         Object *obact = CTX_data_active_object(C);
1872
1873         /* make sure the active view (at the starting time) is a 3d-view */
1874         if (curarea == NULL) {
1875                 p->status = GP_STATUS_ERROR;
1876                 if (G.debug & G_DEBUG)
1877                         printf("Error: No active view for painting\n");
1878                 return 0;
1879         }
1880
1881         /* pass on current scene and window */
1882         p->C = C;
1883         p->bmain = CTX_data_main(C);
1884         p->scene = CTX_data_scene(C);
1885         p->depsgraph = CTX_data_depsgraph(C);
1886         p->win = CTX_wm_window(C);
1887         p->disable_fill = RNA_boolean_get(op->ptr, "disable_fill");
1888
1889         unit_m4(p->imat);
1890         unit_m4(p->mat);
1891
1892         switch (curarea->spacetype) {
1893                 /* supported views first */
1894                 case SPACE_VIEW3D:
1895                 {
1896                         /* View3D *v3d = curarea->spacedata.first; */
1897                         /* RegionView3D *rv3d = ar->regiondata; */
1898
1899                         /* set current area
1900                          * - must verify that region data is 3D-view (and not something else)
1901                          */
1902                          /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1903                         p->sa = curarea;
1904                         p->ar = ar;
1905                         p->align_flag = &ts->gpencil_v3d_align;
1906
1907                         if (ar->regiondata == NULL) {
1908                                 p->status = GP_STATUS_ERROR;
1909                                 if (G.debug & G_DEBUG)
1910                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1911                                 return 0;
1912                         }
1913
1914                         if ((!obact) || (obact->type != OB_GPENCIL)) {
1915                                 View3D *v3d = p->sa->spacedata.first;
1916                                 /* if active object doesn't exist or isn't a GP Object, create one */
1917                                 const float *cur = p->scene->cursor.location;
1918
1919                                 ushort local_view_bits = 0;
1920                                 if (v3d->localvd) {
1921                                         local_view_bits = v3d->local_view_uuid;
1922                                 }
1923                                 /* create new default object */
1924                                 obact = ED_gpencil_add_object(C, p->scene, cur, local_view_bits);
1925                         }
1926                         /* assign object after all checks to be sure we have one active */
1927                         p->ob = obact;
1928
1929                         break;
1930                 }
1931
1932                 /* unsupported views */
1933                 default:
1934                 {
1935                         p->status = GP_STATUS_ERROR;
1936                         if (G.debug & G_DEBUG)
1937                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1938                         return 0;
1939                 }
1940         }
1941
1942         /* get gp-data */
1943         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1944         if ((gpd_ptr == NULL) || ED_gpencil_data_owner_is_annotation(&p->ownerPtr)) {
1945                 p->status = GP_STATUS_ERROR;
1946                 if (G.debug & G_DEBUG)
1947                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1948                 return 0;
1949         }
1950         else {
1951                 /* if no existing GPencil block exists, add one */
1952                 if (*gpd_ptr == NULL)
1953                         *gpd_ptr = BKE_gpencil_data_addnew(bmain, "GPencil");
1954                 p->gpd = *gpd_ptr;
1955         }
1956
1957         /* clear out buffer (stored in gp-data), in case something contaminated it */
1958         gp_session_validatebuffer(p);
1959
1960         /* set brush and create a new one if null */
1961         gp_init_drawing_brush(C, p);
1962
1963         /* setup active color */
1964         if (curarea->spacetype == SPACE_VIEW3D) {
1965                 /* region where paint was originated */
1966                 p->gpd->runtime.ar = CTX_wm_region(C);
1967
1968                 /* NOTE: This is only done for 3D view, as Materials aren't used for
1969                  *       annotations in 2D editors
1970                  */
1971                 int totcol = p->ob->totcol;
1972
1973                 gp_init_colors(p);
1974
1975                 /* check whether the material was newly added */
1976                 if (totcol != p->ob->totcol) {
1977                         WM_event_add_notifier(C, NC_SPACE | ND_SPACE_PROPERTIES, NULL);
1978                 }
1979         }
1980
1981         /* lock axis (in some modes, disable) */
1982         if (((*p->align_flag & GP_PROJECT_DEPTH_VIEW) == 0) &&
1983             ((*p->align_flag & GP_PROJECT_DEPTH_STROKE) == 0))
1984         {
1985                 p->lock_axis = ts->gp_sculpt.lock_axis;
1986         }
1987         else {
1988                 p->lock_axis = 0;
1989         }
1990
1991         return 1;
1992 }
1993
1994 /* init new painting session */
1995 static tGPsdata *gp_session_initpaint(bContext *C, wmOperator *op)
1996 {
1997         tGPsdata *p = NULL;
1998
1999         /* Create new context data */
2000         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
2001
2002         /* Try to initialize context data
2003          * WARNING: This may not always succeed (e.g. using GP in an annotation-only context)
2004          */
2005         if (gp_session_initdata(C, op, p) == 0) {
2006                 /* Invalid state - Exit
2007                  * NOTE: It should be safe to just free the data, since failing context checks should
2008                  * only happen when no data has been allocated.
2009                  */
2010                 MEM_freeN(p);
2011                 return NULL;
2012         }
2013
2014         /* Random generator, only init once. */
2015         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
2016         rng_seed ^= POINTER_AS_UINT(p);
2017         p->rng = BLI_rng_new(rng_seed);
2018
2019         /* return context data for running paint operator */
2020         return p;
2021 }
2022
2023 /* cleanup after a painting session */
2024 static void gp_session_cleanup(tGPsdata *p)
2025 {
2026         bGPdata *gpd = (p) ? p->gpd : NULL;
2027
2028         /* error checking */
2029         if (gpd == NULL)
2030                 return;
2031
2032         /* free stroke buffer */
2033         if (gpd->runtime.sbuffer) {
2034                 /* printf("\t\tGP - free sbuffer\n"); */
2035                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
2036                 gpd->runtime.sbuffer = NULL;
2037         }
2038
2039         /* clear flags */
2040         gpd->runtime.sbuffer_size = 0;
2041         gpd->runtime.sbuffer_sflag = 0;
2042         p->inittime = 0.0;
2043 }
2044
2045 static void gp_session_free(tGPsdata *p)
2046 {
2047         if (p->rng != NULL) {
2048                 BLI_rng_free(p->rng);
2049         }
2050
2051         MEM_freeN(p);
2052 }
2053
2054 /* init new stroke */
2055 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode, Depsgraph *depsgraph)
2056 {
2057         Scene *scene = p->scene;
2058         ToolSettings *ts = scene->toolsettings;
2059         int cfra_eval = (int)DEG_get_ctime(p->depsgraph);
2060
2061         /* get active layer (or add a new one if non-existent) */
2062         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
2063         if (p->gpl == NULL) {
2064                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, DATA_("GP_Layer"), true);
2065
2066                 if (p->custom_color[3]) {
2067                         copy_v3_v3(p->gpl->color, p->custom_color);
2068                 }
2069         }
2070         if ((paintmode != GP_PAINTMODE_ERASER) &&
2071             (p->gpl->flag & GP_LAYER_LOCKED))
2072         {
2073                 p->status = GP_STATUS_ERROR;
2074                 if (G.debug & G_DEBUG)
2075                         printf("Error: Cannot paint on locked layer\n");
2076                 return;
2077         }
2078
2079         /* get active frame (add a new one if not matching frame) */
2080         if (paintmode == GP_PAINTMODE_ERASER) {
2081                 /* Eraser mode:
2082                  * 1) Add new frames to all frames that we might touch,
2083                  * 2) Ensure that p->gpf refers to the frame used for the active layer
2084                  *    (to avoid problems with other tools which expect it to exist)
2085                  */
2086                 bool has_layer_to_erase = false;
2087
2088                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
2089                         /* Skip if layer not editable */
2090                         if (gpencil_layer_is_editable(gpl) == false)
2091                                 continue;
2092
2093                         /* Add a new frame if needed (and based off the active frame,
2094                          * as we need some existing strokes to erase)
2095                          *
2096                          * Note: We don't add a new frame if there's nothing there now, so
2097                          *       -> If there are no frames at all, don't add one
2098                          *       -> If there are no strokes in that frame, don't add a new empty frame
2099                          */
2100                         if (gpl->actframe && gpl->actframe->strokes.first) {
2101                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_COPY);
2102                                 has_layer_to_erase = true;
2103                         }
2104
2105                         /* XXX: we omit GP_FRAME_PAINT here for now,
2106                          * as it is only really useful for doing
2107                          * paintbuffer drawing
2108                          */
2109                 }
2110
2111                 /* Ensure this gets set... */
2112                 p->gpf = p->gpl->actframe;
2113
2114                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
2115                  * (though this is only available in editmode)
2116                  */
2117                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
2118                         if (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
2119                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
2120                         }
2121                 }
2122
2123                 if (has_layer_to_erase == false) {
2124                         p->status = GP_STATUS_ERROR;
2125                         return;
2126                 }
2127         }
2128         else {
2129                 /* Drawing Modes - Add a new frame if needed on the active layer */
2130                 short add_frame_mode;
2131
2132                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
2133                         add_frame_mode = GP_GETFRAME_ADD_COPY;
2134                 else
2135                         add_frame_mode = GP_GETFRAME_ADD_NEW;
2136
2137                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, cfra_eval, add_frame_mode);
2138
2139                 if (p->gpf == NULL) {
2140                         p->status = GP_STATUS_ERROR;
2141                         if (G.debug & G_DEBUG)
2142                                 printf("Error: No frame created (gpencil_paint_init)\n");
2143                         return;
2144                 }
2145                 else {
2146                         p->gpf->flag |= GP_FRAME_PAINT;
2147                 }
2148         }
2149
2150         /* set 'eraser' for this stroke if using eraser */
2151         p->paintmode = paintmode;
2152         if (p->paintmode == GP_PAINTMODE_ERASER) {
2153                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_ERASER;
2154         }
2155         else {
2156                 /* disable eraser flags - so that we can switch modes during a session */
2157                 p->gpd->runtime.sbuffer_sflag &= ~GP_STROKE_ERASER;
2158         }
2159
2160         /* set special fill stroke mode */
2161         if (p->disable_fill == true) {
2162                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_NOFILL;
2163                 /* replace stroke color with fill color */
2164                 copy_v4_v4(p->gpd->runtime.scolor, p->gpd->runtime.sfill);
2165         }
2166
2167         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
2168         p->flags |= GP_PAINTFLAG_FIRSTRUN;
2169
2170         /* when drawing in the camera view, in 2D space, set the subrect */
2171         p->subrect = NULL;
2172         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
2173                 if (p->sa->spacetype == SPACE_VIEW3D) {
2174                         View3D *v3d = p->sa->spacedata.first;
2175                         RegionView3D *rv3d = p->ar->regiondata;
2176
2177                         /* for camera view set the subrect */
2178                         if (rv3d->persp == RV3D_CAMOB) {
2179                                 /* no shift */
2180                                 ED_view3d_calc_camera_border(p->scene, depsgraph, p->ar, v3d, rv3d, &p->subrect_data, true);
2181                                 p->subrect = &p->subrect_data;
2182                         }
2183                 }
2184         }
2185
2186         /* init stroke point space-conversion settings... */
2187         p->gsc.gpd = p->gpd;
2188         p->gsc.gpl = p->gpl;
2189
2190         p->gsc.sa = p->sa;
2191         p->gsc.ar = p->ar;
2192         p->gsc.v2d = p->v2d;
2193
2194         p->gsc.subrect_data = p->subrect_data;
2195         p->gsc.subrect = p->subrect;
2196
2197         copy_m4_m4(p->gsc.mat, p->mat);
2198
2199
2200         /* check if points will need to be made in view-aligned space */
2201         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
2202                 switch (p->sa->spacetype) {
2203                         case SPACE_VIEW3D:
2204                         {
2205                                 p->gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
2206                                 break;
2207                         }
2208                 }
2209         }
2210 }
2211
2212 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
2213 static void gp_paint_strokeend(tGPsdata *p)
2214 {
2215         ToolSettings *ts = p->scene->toolsettings;
2216         /* for surface sketching, need to set the right OpenGL context stuff so that
2217          * the conversions will project the values correctly...
2218          */
2219         if (gpencil_project_check(p)) {
2220                 View3D *v3d = p->sa->spacedata.first;
2221
2222                 /* need to restore the original projection settings before packing up */
2223                 view3d_region_operator_needs_opengl(p->win, p->ar);
2224                 ED_view3d_autodist_init(p->depsgraph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
2225         }
2226
2227         /* check if doing eraser or not */
2228         if ((p->gpd->runtime.sbuffer_sflag & GP_STROKE_ERASER) == 0) {
2229                 /* transfer stroke to frame */
2230                 gp_stroke_newfrombuffer(p);
2231         }
2232
2233         /* clean up buffer now */
2234         gp_session_validatebuffer(p);
2235 }
2236
2237 /* finish off stroke painting operation */
2238 static void gp_paint_cleanup(tGPsdata *p)
2239 {
2240         /* p->gpd==NULL happens when stroke failed to initialize,
2241          * for example when GP is hidden in current space (sergey)
2242          */
2243         if (p->gpd) {
2244                 /* finish off a stroke */
2245                 gp_paint_strokeend(p);
2246         }
2247
2248         /* "unlock" frame */
2249         if (p->gpf)
2250                 p->gpf->flag &= ~GP_FRAME_PAINT;
2251 }
2252
2253 /* ------------------------------- */
2254
2255 /* Helper callback for drawing the cursor itself */
2256 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
2257 {
2258         tGPsdata *p = (tGPsdata *)p_ptr;
2259
2260         if (p->paintmode == GP_PAINTMODE_ERASER) {
2261                 GPUVertFormat *format = immVertexFormat();
2262                 const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
2263                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
2264
2265                 GPU_line_smooth(true);
2266                 GPU_blend(true);
2267                 GPU_blend_set_func_separate(GPU_SRC_ALPHA, GPU_ONE_MINUS_SRC_ALPHA, GPU_ONE, GPU_ONE_MINUS_SRC_ALPHA);
2268
2269                 immUniformColor4ub(255, 100, 100, 20);
2270                 imm_draw_circle_fill_2d(shdr_pos, x, y, p->radius, 40);
2271
2272                 immUnbindProgram();
2273
2274                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
2275
2276                 float viewport_size[4];
2277                 GPU_viewport_size_get_f(viewport_size);
2278                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
2279
2280                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
2281                 immUniform1i("colors_len", 0);  /* "simple" mode */
2282                 immUniform1f("dash_width", 12.0f);
2283                 immUniform1f("dash_factor", 0.5f);
2284
2285                 imm_draw_circle_wire_2d(
2286                         shdr_pos, x, y, p->radius,
2287                         /* XXX Dashed shader gives bad results with sets of small segments currently,
2288                          *     temp hack around the issue. :( */
2289                         max_ii(8, p->radius / 2));  /* was fixed 40 */
2290
2291                 immUnbindProgram();
2292
2293                 GPU_blend(false);
2294                 GPU_line_smooth(false);
2295         }
2296 }
2297
2298 /* Turn brush cursor in 3D view on/off */
2299 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
2300 {
2301         if (p->erasercursor && !enable) {
2302                 /* clear cursor */
2303                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
2304                 p->erasercursor = NULL;
2305         }
2306         else if (enable && !p->erasercursor) {
2307                 ED_gpencil_toggle_brush_cursor(p->C, false, NULL);
2308                 /* enable cursor */
2309                 p->erasercursor = WM_paint_cursor_activate(
2310                         CTX_wm_manager(C),
2311                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
2312                         NULL, /* XXX */
2313                         gpencil_draw_eraser, p);
2314         }
2315 }
2316
2317 /* Check if tablet eraser is being used (when processing events) */
2318 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
2319 {
2320         if (event->tablet_data) {
2321                 const wmTabletData *wmtab = event->tablet_data;
2322                 return (wmtab->Active == EVT_TABLET_ERASER);
2323         }
2324
2325         return false;
2326 }
2327
2328 /* ------------------------------- */
2329
2330 static void gpencil_draw_exit(bContext *C, wmOperator *op)
2331 {
2332         tGPsdata *p = op->customdata;
2333
2334         /* don't assume that operator data exists at all */
2335         if (p) {
2336                 /* check size of buffer before cleanup, to determine if anything happened here */
2337                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2338                         /* turn off radial brush cursor */
2339                         gpencil_draw_toggle_eraser_cursor(C, p, false);
2340                 }
2341
2342                 /* always store the new eraser size to be used again next time
2343                  * NOTE: Do this even when not in eraser mode, as eraser may
2344                  *       have been toggled at some point.
2345                  */
2346                 if (p->eraser) {
2347                         p->eraser->size = p->radius;
2348                 }
2349
2350                 /* restore cursor to indicate end of drawing */
2351                 if (p->sa->spacetype != SPACE_VIEW3D) {
2352                         WM_cursor_modal_restore(CTX_wm_window(C));
2353                 }
2354                 else {
2355                         /* or restore paint if 3D view */
2356                         if ((p) && (p->paintmode == GP_PAINTMODE_ERASER)) {
2357                                 WM_cursor_modal_set(p->win, CURSOR_STD);
2358                         }
2359
2360                         /* drawing batch cache is dirty now */
2361                         bGPdata *gpd = CTX_data_gpencil_data(C);
2362                         if (gpd) {
2363                                 gpd->flag &= ~GP_DATA_STROKE_POLYGON;
2364                                 gp_update_cache(gpd);
2365                         }
2366                 }
2367
2368                 /* clear undo stack */
2369                 gpencil_undo_finish();
2370
2371                 /* cleanup */
2372                 WM_cursor_modal_set(p->win, CURSOR_STD);
2373
2374                 gp_paint_cleanup(p);
2375                 gp_session_cleanup(p);
2376                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
2377
2378                 /* finally, free the temp data */
2379                 gp_session_free(p);
2380                 p = NULL;
2381         }
2382
2383         op->customdata = NULL;
2384 }
2385
2386 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
2387 {
2388         /* this is just a wrapper around exit() */
2389         gpencil_draw_exit(C, op);
2390 }
2391
2392 /* ------------------------------- */
2393
2394
2395 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
2396 {
2397         tGPsdata *p;
2398         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
2399         ToolSettings *ts = CTX_data_tool_settings(C);
2400         Brush *brush = BKE_paint_brush(&ts->gp_paint->paint);
2401
2402         /* if mode is draw and the brush is eraser, cancel */
2403         if (paintmode != GP_PAINTMODE_ERASER) {
2404                 if ((brush) && (brush->gpencil_tool == GPAINT_TOOL_ERASE)) {
2405                         return 0;
2406                 }
2407         }
2408
2409         /* check context */
2410         p = op->customdata = gp_session_initpaint(C, op);
2411         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
2412                 /* something wasn't set correctly in context */
2413                 gpencil_draw_exit(C, op);
2414                 return 0;
2415         }
2416
2417         /* init painting data */
2418         gp_paint_initstroke(p, paintmode, CTX_data_depsgraph(C));
2419         if (p->status == GP_STATUS_ERROR) {
2420                 gpencil_draw_exit(C, op);
2421                 return 0;
2422         }
2423
2424         if (event != NULL) {
2425                 p->keymodifier = event->keymodifier;
2426         }
2427         else {
2428                 p->keymodifier = -1;
2429         }
2430
2431         p->reports = op->reports;
2432
2433         /* everything is now setup ok */
2434         return 1;
2435 }
2436
2437
2438 /* ------------------------------- */
2439
2440 /* ensure that the correct cursor icon is set */
2441 static void gpencil_draw_cursor_set(tGPsdata *p)
2442 {
2443         Brush *brush = p->brush;
2444         if ((p->paintmode == GP_PAINTMODE_ERASER) ||
2445             (brush->gpencil_tool == GPAINT_TOOL_ERASE))
2446         {
2447                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2448         }
2449         else {
2450                 WM_cursor_modal_set(p->win,     CURSOR_NONE);
2451         }
2452 }
2453
2454 /* update UI indicators of status, including cursor and header prints */
2455 static void gpencil_draw_status_indicators(bContext *C, tGPsdata *p)
2456 {
2457         /* header prints */
2458         switch (p->status) {
2459                 case GP_STATUS_IDLING:
2460                 {
2461                         /* print status info */
2462                         switch (p->paintmode) {
2463                                 case GP_PAINTMODE_ERASER:
2464                                 {
2465                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2466                                                 "ESC/Enter to end  (or click outside this area)"));
2467                                         break;
2468                                 }
2469                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2470                                 {
2471                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2472                                                 "ESC/Enter to end  (or click outside this area)"));
2473                                         break;
2474                                 }
2475                                 case GP_PAINTMODE_SET_CP:
2476                                 {
2477                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Guides: LMB click and release to place reference point | "
2478                                                 "Esc/RMB to cancel"));
2479                                         break;
2480                                 }
2481                                 case GP_PAINTMODE_DRAW:
2482                                 {
2483                                         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2484                                         if (guide->use_guide) {
2485                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
2486                                                         "M key to flip guide | O key to move reference point"));
2487                                         }
2488                                         else {
2489                                                 ED_workspace_status_text(C, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw"));
2490                                         }
2491                                         break;
2492                                 }
2493                                 case GP_PAINTMODE_DRAW_POLY:
2494                                 {
2495                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2496                                                 "Release Shift/ESC/Enter to end  (or click outside this area)"));
2497                                         break;
2498                                 }
2499                                 default: /* unhandled future cases */
2500                                 {
2501                                         ED_workspace_status_text(C, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2502                                         break;
2503                                 }
2504                         }
2505                         break;
2506                 }
2507                 case GP_STATUS_ERROR:
2508                 case GP_STATUS_DONE:
2509                 {
2510                         /* clear status string */
2511                         ED_workspace_status_text(C, NULL);
2512                         break;
2513                 }
2514                 case GP_STATUS_PAINTING:
2515                         break;
2516         }
2517 }
2518
2519 /* ------------------------------- */
2520
2521 /* create a new stroke point at the point indicated by the painting context */
2522 static void gpencil_draw_apply(bContext *C, wmOperator *op, tGPsdata *p, Depsgraph *depsgraph)
2523 {
2524         bGPdata *gpd = p->gpd;
2525         tGPspoint *pt = NULL;
2526
2527         /* handle drawing/erasing -> test for erasing first */
2528         if (p->paintmode == GP_PAINTMODE_ERASER) {
2529                 /* do 'live' erasing now */
2530                 gp_stroke_doeraser(p);
2531
2532                 /* store used values */
2533                 copy_v2_v2(p->mvalo, p->mval);
2534                 p->opressure = p->pressure;
2535         }
2536         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2537         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2538
2539                 /* if lazy mouse, interpolate the last and current mouse positions */
2540                 if (GPENCIL_LAZY_MODE(p->brush, p->shift)) {
2541                         float now_mouse[2];
2542                         float last_mouse[2];
2543                         copy_v2_v2(now_mouse, p->mval);
2544                         copy_v2_v2(last_mouse, p->mvalo);
2545                         interp_v2_v2v2(now_mouse, now_mouse, last_mouse, p->brush->smooth_stroke_factor);
2546                         copy_v2_v2(p->mval, now_mouse);
2547                 }
2548
2549                 /* try to add point */
2550                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2551
2552                 /* handle errors while adding point */
2553                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2554                         /* finish off old stroke */
2555                         gp_paint_strokeend(p);
2556                         /* And start a new one!!! Else, projection errors! */
2557                         gp_paint_initstroke(p, p->paintmode, depsgraph);
2558
2559                         /* start a new stroke, starting from previous point */
2560                         /* XXX Must manually reset inittime... */
2561                         /* XXX We only need to reuse previous point if overflow! */
2562                         if (ok == GP_STROKEADD_OVERFLOW) {
2563                                 p->inittime = p->ocurtime;
2564                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2565                         }
2566                         else {
2567                                 p->inittime = p->curtime;
2568                         }
2569                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2570                 }
2571                 else if (ok == GP_STROKEADD_INVALID) {
2572                         /* the painting operation cannot continue... */
2573                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2574                         p->status = GP_STATUS_ERROR;
2575
2576                         if (G.debug & G_DEBUG)
2577                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2578                         return;
2579                 }
2580
2581                 /* store used values */
2582                 copy_v2_v2(p->mvalo, p->mval);
2583                 p->opressure = p->pressure;
2584                 p->ocurtime = p->curtime;
2585
2586                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2587                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2588                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2589                 }
2590         }
2591         else if ((p->brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) &&
2592                  (gpd->runtime.sbuffer_size > 0))
2593         {
2594                 pt = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
2595                 if (p->paintmode != GP_PAINTMODE_ERASER) {
2596                         ED_gpencil_toggle_brush_cursor(C, true, &pt->x);
2597                 }
2598         }
2599 }
2600
2601 /* Helper to rotate point around origin */
2602 static void gp_rotate_v2_v2v2fl(float v[2], const float p[2], const float origin[2], const float angle)
2603 {
2604         float pt[2];
2605         float r[2];
2606         sub_v2_v2v2(pt, p, origin);
2607         rotate_v2_v2fl(r, pt, angle);
2608         add_v2_v2v2(v, r, origin);
2609 }
2610
2611 /* Helper to snap value to grid */
2612 static float gp_snap_to_grid_fl(float v, const float offset, const float spacing)
2613 {
2614         if (spacing > 0.0f) {
2615                 return roundf(v / spacing) * spacing + fmodf(offset, spacing);
2616         }
2617         else {
2618                 return v;
2619         }
2620 }
2621
2622 static void UNUSED_FUNCTION(gp_snap_to_grid_v2)(float v[2], const float offset[2], const float spacing)
2623 {
2624         v[0] = gp_snap_to_grid_fl(v[0], offset[0], spacing);
2625         v[1] = gp_snap_to_grid_fl(v[1], offset[1], spacing);
2626 }
2627
2628 /* get reference point - screen coords to buffer coords */
2629 static void gp_origin_set(wmOperator *op, const int mval[2])
2630 {
2631         tGPsdata *p = op->customdata;
2632         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2633         float origin[2];
2634         float point[3];
2635         copy_v2fl_v2i(origin, mval);
2636         gp_stroke_convertcoords(p, origin, point, NULL);
2637         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2638                 copy_v3_v3(guide->location, point);
2639         }
2640         else if (guide->reference_point == GP_GUIDE_REF_CURSOR) {
2641                 copy_v3_v3(p->scene->cursor.location, point);
2642         }
2643 }
2644
2645 /* get reference point - buffer coords to screen coords */
2646 static void gp_origin_get(tGPsdata *p, float origin[2])
2647 {
2648         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2649         float location[3];
2650         if (guide->reference_point == GP_GUIDE_REF_CUSTOM) {
2651                 copy_v3_v3(location, guide->location);
2652         }
2653         else if (guide->reference_point == GP_GUIDE_REF_OBJECT &&
2654                  guide->reference_object != NULL)
2655         {
2656                 copy_v3_v3(location, guide->reference_object->loc);
2657         }
2658         else {
2659                 copy_v3_v3(location, p->scene->cursor.location);
2660         }
2661         GP_SpaceConversion *gsc = &p->gsc;
2662         gp_point_3d_to_xy(gsc, p->gpd->runtime.sbuffer_sflag, location, origin);
2663 }
2664
2665 /* handle draw event */
2666 static void gpencil_draw_apply_event(bContext *C, wmOperator *op, const wmEvent *event, Depsgraph *depsgraph, float x, float y)
2667 {
2668         tGPsdata *p = op->customdata;
2669         GP_Sculpt_Guide *guide = &p->scene->toolsettings->gp_sculpt.guide;
2670         PointerRNA itemptr;
2671         float mousef[2];
2672         int tablet = 0;
2673
2674         /* convert from window-space to area-space mouse coordinates
2675          * add any x,y override position for fake events
2676          */
2677         p->mval[0] = (float)event->mval[0] - x;
2678         p->mval[1] = (float)event->mval[1] - y;
2679         p->shift = event->shift;
2680
2681         /* verify direction for straight lines */
2682         if ((guide->use_guide) || ((event->alt > 0) && (RNA_boolean_get(op->ptr, "disable_straight") == false))) {
2683                 if (p->straight == 0) {
2684                         int dx = (int)fabsf(p->mval[0] - p->mvali[0]);
2685                         int dy = (int)fabsf(p->mval[1] - p->mvali[1]);
2686                         if ((dx > 0) || (dy > 0)) {
2687                                 /* store mouse direction */
2688                                 if (dx > dy) {
2689                                         p->straight = STROKE_HORIZONTAL;
2690                                 }
2691                                 else if (dx < dy) {
2692                                         p->straight = STROKE_VERTICAL;
2693                                 }
2694                         }
2695                 }
2696         }
2697
2698         p->curtime = PIL_check_seconds_timer();
2699
2700         /* handle pressure sensitivity (which is supplied by tablets) */
2701         if (event->tablet_data) {
2702                 const wmTabletData *wmtab = event->tablet_data;
2703
2704                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2705                 p->pressure = wmtab->Pressure;
2706
2707                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2708                  * The pen has to float over the tablet surface, resulting in
2709                  * zero pressure (T47101). Ignore pressure values if floating
2710                  * (i.e. "effectively zero" pressure), and only when the "active"
2711                  * end is the stylus (i.e. the default when not eraser)
2712                  */
2713                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2714                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2715                                 p->pressure = 1.0f;
2716                         }
2717                 }
2718         }
2719         else {
2720                 /* No tablet data -> No pressure info is available */
2721                 p->pressure = 1.0f;
2722         }
2723
2724         /* special eraser modes */
2725         if (p->paintmode == GP_PAINTMODE_ERASER) {
2726                 if (event->shift > 0) {
2727                         p->flags |= GP_PAINTFLAG_HARD_ERASER;
2728                 }
2729                 else {
2730                         p->flags &= ~GP_PAINTFLAG_HARD_ERASER;
2731                 }
2732                 if (event->alt > 0) {
2733                         p->flags |= GP_PAINTFLAG_STROKE_ERASER;
2734                 }
2735                 else {
2736                         p->flags &= ~GP_PAINTFLAG_STROKE_ERASER;
2737                 }
2738         }
2739
2740         /* special exception for start of strokes (i.e. maybe for just a dot) */
2741         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2742                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2743
2744                 /* set values */
2745                 copy_v2_v2(p->mvalo, p->mval);
2746                 p->opressure = p->pressure;
2747                 p->inittime = p->ocurtime = p->curtime;
2748                 p->straight = 0;
2749
2750                 /* save initial mouse */
2751                 copy_v2_v2(p->mvali, p->mval);
2752
2753                 /* calculate once and store snapping distance and origin */
2754                 RegionView3D * rv3d = p->ar->regiondata;
2755                 float scale = 1.0f;
2756                 if (rv3d->is_persp) {
2757                         float vec[3];
2758                         gp_get_3d_reference(p, vec);
2759                         mul_m4_v3(rv3d->persmat, vec);
2760                         scale = vec[2] * rv3d->pixsize;
2761                 }
2762                 else {
2763                         scale = rv3d->pixsize;
2764                 }
2765                 p->guide_spacing = guide->spacing / scale;
2766                 p->half_spacing = p->guide_spacing * 0.5f;
2767                 gp_origin_get(p, p->origin);
2768
2769                 /* special exception here for too high pressure values on first touch in
2770                  * windows for some tablets, then we just skip first touch...
2771                  */
2772                 if (tablet && (p->pressure >= 0.99f)) {
2773                         return;
2774                 }
2775
2776                 /* special exception for grid snapping
2777                  * it requires direction which needs at least two points
2778                  */
2779                 if (!ELEM(p->paintmode, GP_PAINTMODE_ERASER, GP_PAINTMODE_SET_CP) &&
2780                     guide->use_guide &&
2781                     guide->use_snapping &&
2782                     (guide->type == GP_GUIDE_GRID))
2783                 {
2784                         p->flags |= GP_PAINTFLAG_REQ_VECTOR;
2785                 }
2786         }
2787
2788         /* wait for vector then add initial point */
2789         if (p->flags & GP_PAINTFLAG_REQ_VECTOR) {
2790                 if (p->straight == 0) {
2791                         return;
2792                 }
2793
2794                 p->flags &= ~GP_PAINTFLAG_REQ_VECTOR;
2795
2796                 /* create fake events */
2797                 float tmp[2];
2798                 float pt[2];
2799                 copy_v2_v2(tmp, p->mval);
2800                 sub_v2_v2v2(pt, p->mval, p->mvali);
2801                 gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2802                 if (len_v2v2(p->mval, p->mvalo)) {
2803                         sub_v2_v2v2(pt, p->mval, p->mvalo);
2804                         gpencil_draw_apply_event(C, op, event, CTX_data_depsgraph(C), pt[0], pt[1]);
2805                 }
2806                 copy_v2_v2(p->mval, tmp);
2807         }
2808
2809         /* check if stroke is straight or guided */
2810         if ((p->paintmode != GP_PAINTMODE_ERASER) &&
2811             ((p->straight) || (guide->use_guide)))
2812         {
2813                 /* guided stroke */
2814                 if (guide->use_guide) {
2815                         switch (guide->type) {
2816                                 default:
2817                                 case GP_GUIDE_CIRCULAR:
2818                                 {
2819                                         float distance;
2820                                         distance = len_v2v2(p->mvali, p->origin);
2821
2822                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2823                                                 distance = gp_snap_to_grid_fl(distance, 0.0f, p->guide_spacing);
2824                                         }
2825
2826                                         dist_ensure_v2_v2fl(p->mval, p->origin, distance);
2827                                         break;
2828                                 }
2829                                 case GP_GUIDE_RADIAL:
2830                                 {
2831                                         if (guide->use_snapping && (guide->angle_snap > 0.0f)) {
2832                                                 float point[2];
2833                                                 float xy[2];
2834                                                 float angle;
2835                                                 float half_angle = guide->angle_snap * 0.5f;
2836                                                 sub_v2_v2v2(xy, p->mvali, p->origin);
2837                                                 angle = atan2f(xy[1], xy[0]);
2838                                                 angle += (M_PI * 2.0f);
2839                                                 angle = fmodf(angle + half_angle, guide->angle_snap);
2840                                                 angle -= half_angle;
2841                                                 gp_rotate_v2_v2v2fl(point, p->mvali, p->origin, -angle);
2842                                                 closest_to_line_v2(p->mval, p->mval, point, p->origin);
2843                                         }
2844                                         else {
2845                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, p->origin);
2846                                         }
2847                                         break;
2848                                 }
2849                                 case GP_GUIDE_PARALLEL:
2850                                 {
2851                                         float point[2];
2852                                         float unit[2];
2853                                         copy_v2_v2(unit, p->mvali);
2854                                         unit[0] += 1.0f; /* start from horizontal */
2855                                         gp_rotate_v2_v2v2fl(point, unit, p->mvali, guide->angle);
2856                                         closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2857
2858                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2859                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, -guide->angle);
2860                                                 p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2861                                                 gp_rotate_v2_v2v2fl(p->mval, p->mval, p->origin, guide->angle);
2862                                         }
2863                                         break;
2864                                 }
2865                                 case GP_GUIDE_GRID:
2866                                 {
2867                                         if (guide->use_snapping && (guide->spacing > 0.0f)) {
2868                                                 float point[2];
2869                                                 float unit[2];
2870                                                 float angle;
2871                                                 copy_v2_v2(unit, p->mvali);
2872                                                 unit[0] += 1.0f; /* start from horizontal */
2873                                                 angle = (p->straight == STROKE_VERTICAL) ? M_PI_2 : 0.0f;
2874                                                 gp_rotate_v2_v2v2fl(point, unit, p->mvali, angle);
2875                                                 closest_to_line_v2(p->mval, p->mval, p->mvali, point);
2876
2877                                                 if (p->straight == STROKE_HORIZONTAL) {
2878                                                         p->mval[1] = gp_snap_to_grid_fl(p->mval[1] - p->half_spacing, p->origin[1], p->guide_spacing);
2879                                                 }
2880                                                 else {
2881                                                         p->mval[0] = gp_snap_to_grid_fl(p->mval[0] - p->half_spacing, p->origin[0], p->guide_spacing);
2882                                                 }
2883                                         }
2884                                         else if (p->straight == STROKE_HORIZONTAL) {
2885                                                 p->mval[1] = p->mvali[1]; /* replace y */
2886                                         }
2887                                         else {
2888                                                 p->mval[0] = p->mvali[0]; /* replace x */
2889                                         }
2890                                         break;
2891                                 }
2892                         }
2893                 }
2894                 else if (p->straight == STROKE_HORIZONTAL) {
2895                         p->mval[1] = p->mvali[1]; /* replace y */
2896                 }
2897                 else {
2898                         p->mval[0] = p->mvali[0]; /* replace x */
2899                 }
2900         }
2901
2902         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2903         RNA_collection_add(op->ptr, "stroke", &itemptr);
2904
2905         mousef[0] = p->mval[0];
2906         mousef[1] = p->mval[1];
2907         RNA_float_set_array(&itemptr, "mouse", mousef);
2908         RNA_float_set(&itemptr, "pressure", p->pressure);
2909         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2910
2911         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2912
2913         /* apply the current latest drawing point */
2914         gpencil_draw_apply(C, op, p, depsgraph);
2915
2916         /* force refresh */
2917         /* just active area for now, since doing whole screen is too slow */
2918         ED_region_tag_redraw(p->ar);
2919 }
2920
2921 /* ------------------------------- */
2922
2923 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2924 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2925 {
2926         tGPsdata *p = NULL;
2927         Depsgraph *depsgraph = CTX_data_depsgraph(C);
2928
2929         /* printf("GPencil - Starting Re-Drawing\n"); */
2930
2931         /* try to initialize context data needed while drawing */
2932         if (!gpencil_draw_init(C, op, NULL)) {
2933                 MEM_SAFE_FREE(op->customdata);
2934                 /* printf("\tGP - no valid data\n"); */
2935                 return OPERATOR_CANCELLED;
2936         }
2937         else
2938                 p = op->customdata;
2939
2940         /* printf("\tGP - Start redrawing stroke\n"); */
2941
2942         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
2943          * setting the relevant values in context at each step, then applying
2944          */
2945         RNA_BEGIN(op->ptr, itemptr, "stroke")
2946         {
2947                 float mousef[2];
2948
2949                 /* printf("\t\tGP - stroke elem\n"); */
2950
2951                 /* get relevant data for this point from stroke */
2952                 RNA_float_get_array(&itemptr, "mouse", mousef);
2953                 p->mval[0] = mousef[0];
2954                 p->mval[1] = mousef[1];
2955                 p->pressure = RNA_float_get(&itemptr, "pressure");
2956                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
2957
2958                 if (RNA_boolean_get(&itemptr, "is_start")) {
2959                         /* if first-run flag isn't set already (i.e. not true first stroke),
2960                          * then we must terminate the previous one first before continuing
2961                          */
2962                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
2963                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
2964                                 gp_paint_strokeend(p);
2965                                 gp_paint_initstroke(p, p->paintmode, depsgraph);
2966                         }
2967                 }
2968
2969                 /* if first run, set previous data too */
2970                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {