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