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