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