Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung, Antonio Vazquez
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/gpencil_paint.c
27  *  \ingroup edgpencil
28  */
29
30
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_rand.h"
43 #include "BLI_math_geom.h"
44
45 #include "BLT_translation.h"
46
47 #include "PIL_time.h"
48
49 #include "BKE_main.h"
50 #include "BKE_paint.h"
51 #include "BKE_gpencil.h"
52 #include "BKE_context.h"
53 #include "BKE_global.h"
54 #include "BKE_report.h"
55 #include "BKE_screen.h"
56 #include "BKE_tracking.h"
57 #include "BKE_colortools.h"
58
59 #include "DNA_object_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_gpencil_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_windowmanager_types.h"
64
65 #include "UI_view2d.h"
66
67 #include "ED_gpencil.h"
68 #include "ED_screen.h"
69 #include "ED_view3d.h"
70 #include "ED_clip.h"
71
72 #include "BIF_glutil.h"
73
74 #include "GPU_immediate.h"
75 #include "GPU_immediate_util.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 "gpencil_intern.h"
84
85 /* ******************************************* */
86 /* 'Globals' and Defines */
87
88 /* values for tGPsdata->status */
89 typedef enum eGPencil_PaintStatus {
90         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
91         GP_STATUS_PAINTING,     /* a stroke is in progress */
92         GP_STATUS_ERROR,        /* something wasn't correctly set up */
93         GP_STATUS_DONE          /* painting done */
94 } eGPencil_PaintStatus;
95
96 /* Return flags for adding points to stroke buffer */
97 typedef enum eGP_StrokeAdd_Result {
98         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
99         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
100         GP_STROKEADD_NORMAL,                /* point was successfully added */
101         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
102 } eGP_StrokeAdd_Result;
103
104 /* Runtime flags */
105 typedef enum eGPencil_PaintFlags {
106         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
107         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
108         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
109         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
110 } eGPencil_PaintFlags;
111
112
113 /* Temporary 'Stroke' Operation data
114  *   "p" = op->customdata
115  */
116 typedef struct tGPsdata {
117         Scene *scene;       /* current scene from context */
118         struct Depsgraph *graph;
119         
120         wmWindow *win;      /* window where painting originated */
121         ScrArea *sa;        /* area where painting originated */
122         ARegion *ar;        /* region where painting originated */
123         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
124         rctf *subrect;      /* for using the camera rect within the 3d view */
125         rctf subrect_data;
126         
127         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
128         
129         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
130         bGPdata *gpd;       /* gp-datablock layer comes from */
131         bGPDlayer *gpl;     /* layer we're working on */
132         bGPDframe *gpf;     /* frame we're working on */
133         
134         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
135         
136         eGPencil_PaintStatus status;     /* current status of painting */
137         eGPencil_PaintModes  paintmode;  /* mode for painting */
138         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
139         
140         short radius;       /* radius of influence for eraser */
141         
142         int mval[2];        /* current mouse-position */
143         int mvalo[2];       /* previous recorded mouse-position */
144         
145         float pressure;     /* current stylus pressure */
146         float opressure;    /* previous stylus pressure */
147         
148         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
149          * float (and its 7 digits precision) is definitively not enough here!
150          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
151          */
152         double inittime;    /* Used when converting to path */
153         double curtime;     /* Used when converting to path */
154         double ocurtime;    /* Used when converting to path */
155         
156         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
157                              * to region space */
158         float mat[4][4];
159         
160         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
161         
162         void *erasercursor; /* radial cursor data for drawing eraser */
163
164         bGPDpalettecolor *palettecolor; /* current palette color */
165         bGPDbrush *brush; /* current drawing brush */
166         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
167         int lock_axis;       /* lock drawing to one axis */
168
169         short keymodifier;   /* key used for invoking the operator */
170 } tGPsdata;
171
172 /* ------ */
173
174 /* Macros for accessing sensitivity thresholds... */
175 /* minimum number of pixels mouse should move before new point created */
176 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
177 /* minimum length of new segment before new point can be added */
178 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
179
180 static bool gp_stroke_added_check(tGPsdata *p)
181 {
182         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
183 }
184
185 static void gp_stroke_added_enable(tGPsdata *p)
186 {
187         BLI_assert(p->gpf->strokes.last != NULL);
188         p->flags |= GP_PAINTFLAG_STROKEADDED;
189 }
190
191 /* ------ */
192 /* Forward defines for some functions... */
193
194 static void gp_session_validatebuffer(tGPsdata *p);
195
196 /* ******************************************* */
197 /* Context Wrangling... */
198
199 /* check if context is suitable for drawing */
200 static int gpencil_draw_poll(bContext *C)
201 {
202         if (ED_operator_regionactive(C)) {
203                 /* check if current context can support GPencil data */
204                 if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
205                         /* check if Grease Pencil isn't already running */
206                         if (ED_gpencil_session_active() == 0)
207                                 return 1;
208                         else
209                                 CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
210                 }
211                 else {
212                         CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
213                 }
214         }
215         else {
216                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
217         }
218         
219         return 0;
220 }
221
222 /* check if projecting strokes into 3d-geometry in the 3D-View */
223 static bool gpencil_project_check(tGPsdata *p)
224 {
225         bGPdata *gpd = p->gpd;
226         return ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
227 }
228
229 /* ******************************************* */
230 /* Calculations/Conversions */
231
232 /* Utilities --------------------------------- */
233
234 /* get the reference point for stroke-point conversions */
235 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
236 {
237         View3D *v3d = p->sa->spacedata.first;
238         const float *fp = ED_view3d_cursor3d_get(p->scene, v3d);
239         
240         /* the reference point used depends on the owner... */
241 #if 0 /* XXX: disabled for now, since we can't draw relative to the owner yet */
242         if (p->ownerPtr.type == &RNA_Object) {
243                 Object *ob = (Object *)p->ownerPtr.data;
244                 
245                 /* active Object
246                  *  - use relative distance of 3D-cursor from object center
247                  */
248                 sub_v3_v3v3(vec, fp, ob->loc);
249         }
250         else
251 #endif
252         {
253                 /* use 3D-cursor */
254                 copy_v3_v3(vec, fp);
255         }
256 }
257
258 /* Stroke Editing ---------------------------- */
259
260 /* check if the current mouse position is suitable for adding a new point */
261 static bool gp_stroke_filtermval(tGPsdata *p, const int mval[2], int pmval[2])
262 {
263         int dx = abs(mval[0] - pmval[0]);
264         int dy = abs(mval[1] - pmval[1]);
265         
266         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
267         if (p->gpd->sbuffer_size == 0)
268                 return true;
269         
270         /* check if mouse moved at least certain distance on both axes (best case)
271          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
272          */
273         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
274                 return true;
275         
276         /* check if the distance since the last point is significant enough
277          *      - prevents points being added too densely
278          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
279          */
280         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
281                 return true;
282         
283         /* mouse 'didn't move' */
284         else
285                 return false;
286 }
287
288 /* reproject the points of the stroke to a plane locked to axis to avoid stroke offset */
289 static void gp_project_points_to_plane(RegionView3D *rv3d, bGPDstroke *gps, const float origin[3], const int axis)
290 {
291         float plane_normal[3];
292         float vn[3];
293
294         float ray[3];
295         float rpoint[3];
296
297         /* normal vector for a plane locked to axis */
298         zero_v3(plane_normal);
299         plane_normal[axis] = 1.0f;
300
301         /* Reproject the points in the plane */
302         for (int i = 0; i < gps->totpoints; i++) {
303                 bGPDspoint *pt = &gps->points[i];
304
305                 /* get a vector from the point with the current view direction of the viewport */
306                 ED_view3d_global_to_vector(rv3d, &pt->x, vn);
307
308                 /* calculate line extrem point to create a ray that cross the plane */
309                 mul_v3_fl(vn, -50.0f);
310                 add_v3_v3v3(ray, &pt->x, vn);
311
312                 /* if the line never intersect, the point is not changed */
313                 if (isect_line_plane_v3(rpoint, &pt->x, ray, origin, plane_normal)) {
314                         copy_v3_v3(&pt->x, rpoint);
315                 }
316         }
317 }
318
319 /* reproject stroke to plane locked to axis in 3d cursor location */
320 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
321 {
322         bGPdata *gpd = p->gpd;
323         float origin[3];
324         float cursor[3];
325         RegionView3D *rv3d = p->ar->regiondata;
326
327         /* verify the stroke mode is CURSOR 3d space mode */
328         if ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
329                 return;
330         }
331         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
332                 return;
333         }
334         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
335                 return;
336         }
337
338         /* get 3d cursor and set origin for locked axis only. Uses axis-1 because the enum for XYZ start with 1 */
339         gp_get_3d_reference(p, cursor);
340         zero_v3(origin);
341         origin[p->lock_axis - 1] = cursor[p->lock_axis - 1];
342
343         gp_project_points_to_plane(rv3d, gps, origin, p->lock_axis - 1);
344 }
345
346 /* convert screen-coordinates to buffer-coordinates */
347 /* XXX this method needs a total overhaul! */
348 static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3], float *depth)
349 {
350         bGPdata *gpd = p->gpd;
351         
352         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
353         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
354                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
355                         /* projecting onto 3D-Geometry
356                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
357                          */
358                 }
359                 else {
360                         float mval_prj[2];
361                         float rvec[3], dvec[3];
362                         float mval_f[2] = {UNPACK2(mval)};
363                         float zfac;
364                 
365                         /* Current method just converts each point in screen-coordinates to
366                          * 3D-coordinates using the 3D-cursor as reference. In general, this
367                          * works OK, but it could of course be improved.
368                          *
369                          * TODO:
370                          *      - investigate using nearest point(s) on a previous stroke as
371                          *        reference point instead or as offset, for easier stroke matching
372                          */
373                         
374                         gp_get_3d_reference(p, rvec);
375                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
376                         
377                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
378                                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
379                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
380                                 sub_v3_v3v3(out, rvec, dvec);
381                         }
382                         else {
383                                 zero_v3(out);
384                         }
385                 }
386         }
387         
388         /* 2d - on 'canvas' (assume that p->v2d is set) */
389         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
390                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
391                 mul_v3_m4v3(out, p->imat, out);
392         }
393         
394         /* 2d - relative to screen (viewport area) */
395         else {
396                 if (p->subrect == NULL) { /* normal 3D view */
397                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
398                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
399                 }
400                 else { /* camera view, use subrect */
401                         out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
402                         out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
403                 }
404         }
405 }
406
407 /* apply jitter to stroke */
408 static void gp_brush_jitter(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2], int r_mval[2])
409 {
410         float pressure = pt->pressure;
411         float tmp_pressure = pt->pressure;
412         if (brush->draw_jitter > 0.0f) {
413                 float curvef = curvemapping_evaluateF(brush->cur_jitter, 0, pressure);
414                 tmp_pressure = curvef * brush->draw_sensitivity;
415         }
416         const float exfactor = (brush->draw_jitter + 2.0f) * (brush->draw_jitter + 2.0f); /* exponential value */
417         const float fac = BLI_frand() * exfactor * tmp_pressure;
418         /* Jitter is applied perpendicular to the mouse movement vector (2D space) */
419         float mvec[2], svec[2];
420         /* mouse movement in ints -> floats */
421         if (gpd->sbuffer_size > 1) {
422                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
423                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
424                 normalize_v2(mvec);
425         }
426         else {
427                 mvec[0] = 0.0f;
428                 mvec[1] = 0.0f;
429         }
430         /* rotate mvec by 90 degrees... */
431         svec[0] = -mvec[1];
432         svec[1] = mvec[0];
433         /* scale the displacement by the random, and apply */
434         if (BLI_frand() > 0.5f) {
435                 mul_v2_fl(svec, -fac);
436         }
437         else {
438                 mul_v2_fl(svec, fac);
439         }
440
441         r_mval[0] = mval[0] + svec[0];
442         r_mval[1] = mval[1] + svec[1];
443
444 }
445
446 /* apply pressure change depending of the angle of the stroke to simulate a pen with shape */
447 static void gp_brush_angle(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2])
448 {
449         float mvec[2];
450         float sen = brush->draw_angle_factor; /* sensitivity */;
451         float fac;
452         float mpressure;
453
454         float angle = brush->draw_angle; /* default angle of brush in radians */;
455         float v0[2] = { cos(angle), sin(angle) }; /* angle vector of the brush with full thickness */
456
457         /* Apply to first point (only if there are 2 points because before no data to do it ) */
458         if (gpd->sbuffer_size == 1) {
459                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
460                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
461                 normalize_v2(mvec);
462
463                 /* uses > 1.0f to get a smooth transition in first point */
464                 fac = 1.4f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
465                 (pt - 1)->pressure = (pt - 1)->pressure - (sen * fac);
466
467                 CLAMP((pt - 1)->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
468         }
469
470         /* apply from second point */
471         if (gpd->sbuffer_size >= 1) {
472                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
473                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
474                 normalize_v2(mvec);
475
476                 fac = 1.0f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
477                 /* interpolate with previous point for smoother transitions */
478                 mpressure = interpf(pt->pressure - (sen * fac), (pt - 1)->pressure, 0.3f);
479                 pt->pressure = mpressure; 
480
481                 CLAMP(pt->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
482         }
483
484 }
485
486 /* add current stroke-point to buffer (returns whether point was successfully added) */
487 static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure, double curtime)
488 {
489         bGPdata *gpd = p->gpd;
490         bGPDbrush *brush = p->brush;
491         tGPspoint *pt;
492         ToolSettings *ts = p->scene->toolsettings;
493
494         /* check painting mode */
495         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
496                 /* straight lines only - i.e. only store start and end point in buffer */
497                 if (gpd->sbuffer_size == 0) {
498                         /* first point in buffer (start point) */
499                         pt = (tGPspoint *)(gpd->sbuffer);
500                         
501                         /* store settings */
502                         copy_v2_v2_int(&pt->x, mval);
503                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
504                         pt->strength = 1.0f;
505                         pt->time = (float)(curtime - p->inittime);
506                         
507                         /* increment buffer size */
508                         gpd->sbuffer_size++;
509                 }
510                 else {
511                         /* just reset the endpoint to the latest value
512                          *      - assume that pointers for this are always valid...
513                          */
514                         pt = ((tGPspoint *)(gpd->sbuffer) + 1);
515                         
516                         /* store settings */
517                         copy_v2_v2_int(&pt->x, mval);
518                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
519                         pt->strength = 1.0f;
520                         pt->time = (float)(curtime - p->inittime);
521                         
522                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
523                         gpd->sbuffer_size = 2;
524                 }
525                 
526                 /* can keep carrying on this way :) */
527                 return GP_STROKEADD_NORMAL;
528         }
529         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
530                 /* check if still room in buffer */
531                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
532                         return GP_STROKEADD_OVERFLOW;
533                 
534                 /* get pointer to destination point */
535                 pt = ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
536                 
537                 /* store settings */
538                 /* pressure */
539                 if (brush->flag & GP_BRUSH_USE_PRESSURE) {
540                         float curvef = curvemapping_evaluateF(brush->cur_sensitivity, 0, pressure);
541                         pt->pressure = curvef * brush->draw_sensitivity;
542                 }
543                 else {
544                         pt->pressure = 1.0f;
545                 }
546                 /* Apply jitter to position */
547                 if (brush->draw_jitter > 0.0f) {
548                         int r_mval[2];
549                         gp_brush_jitter(gpd, brush, pt, mval, r_mval);
550                         copy_v2_v2_int(&pt->x, r_mval);
551                 }
552                 else {
553                         copy_v2_v2_int(&pt->x, mval);
554                 }
555                 /* apply randomness to pressure */
556                 if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_PRESSURE)) {
557                         float curvef = curvemapping_evaluateF(brush->cur_sensitivity, 0, pressure);
558                         float tmp_pressure = curvef * brush->draw_sensitivity;
559                         if (BLI_frand() > 0.5f) {
560                                 pt->pressure -= tmp_pressure * brush->draw_random_press * BLI_frand();
561                         }
562                         else {
563                                 pt->pressure += tmp_pressure * brush->draw_random_press * BLI_frand();
564                         }
565                         CLAMP(pt->pressure, GPENCIL_STRENGTH_MIN, 1.0f);
566                 }
567
568                 /* apply angle of stroke to brush size */
569                 if (brush->draw_angle_factor > 0.0f) {
570                         gp_brush_angle(gpd, brush, pt, mval);
571                 }
572
573                 /* color strength */
574                 if (brush->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
575                         float curvef = curvemapping_evaluateF(brush->cur_strength, 0, pressure);
576                         float tmp_pressure = curvef * brush->draw_sensitivity;
577
578                         pt->strength = tmp_pressure * brush->draw_strength;
579                 }
580                 else {
581                         pt->strength = brush->draw_strength;
582                 }
583                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
584
585                 /* apply randomness to color strength */
586                 if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_STRENGTH)) {
587                         if (BLI_frand() > 0.5f) {
588                                 pt->strength -= pt->strength * brush->draw_random_press * BLI_frand();
589                         }
590                         else {
591                                 pt->strength += pt->strength * brush->draw_random_press * BLI_frand();
592                         }
593                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
594                 }
595
596                 /* point time */
597                 pt->time = (float)(curtime - p->inittime);
598                 
599                 /* increment counters */
600                 gpd->sbuffer_size++;
601                 
602                 /* check if another operation can still occur */
603                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
604                         return GP_STROKEADD_FULL;
605                 else
606                         return GP_STROKEADD_NORMAL;
607         }
608         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
609                 
610                 bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
611                 /* get pointer to destination point */
612                 pt = (tGPspoint *)(gpd->sbuffer);
613                 
614                 /* store settings */
615                 copy_v2_v2_int(&pt->x, mval);
616                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
617                 pt->strength = 1.0f;
618                 pt->time = (float)(curtime - p->inittime);
619                 
620                 /* if there's stroke for this poly line session add (or replace last) point
621                  * to stroke. This allows to draw lines more interactively (see new segment
622                  * during mouse slide, e.g.)
623                  */
624                 if (gp_stroke_added_check(p)) {
625                         bGPDstroke *gps = p->gpf->strokes.last;
626                         bGPDspoint *pts;
627                         
628                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
629                         if (gpd->sbuffer_size == 0) {
630                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
631                                 gps->totpoints++;
632                         }
633                         
634                         pts = &gps->points[gps->totpoints - 1];
635                         
636                         /* special case for poly lines: normally,
637                          * depth is needed only when creating new stroke from buffer,
638                          * but poly lines are converting to stroke instantly,
639                          * so initialize depth buffer before converting coordinates
640                          */
641                         if (gpencil_project_check(p)) {
642                                 View3D *v3d = p->sa->spacedata.first;
643                                 
644                                 view3d_region_operator_needs_opengl(p->win, p->ar);
645                                 ED_view3d_autodist_init(
646                                         p->graph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
647                         }
648                         
649                         /* convert screen-coordinates to appropriate coordinates (and store them) */
650                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
651                         /* if axis locked, reproject to plane locked (only in 3d space) */
652                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
653                                 gp_reproject_toplane(p, gps);
654                         }
655                         /* if parented change position relative to parent object */
656                         if (gpl->parent != NULL) {
657                                 gp_apply_parent_point(gpl, pts);
658                         }
659                         /* copy pressure and time */
660                         pts->pressure = pt->pressure;
661                         pts->strength = pt->strength;
662                         pts->time = pt->time;
663                         /* force fill recalc */
664                         gps->flag |= GP_STROKE_RECALC_CACHES;
665                 }
666                 
667                 /* increment counters */
668                 if (gpd->sbuffer_size == 0)
669                         gpd->sbuffer_size++;
670                 
671                 return GP_STROKEADD_NORMAL;
672         }
673
674         /* return invalid state for now... */
675         return GP_STROKEADD_INVALID;
676 }
677
678 /* simplify a stroke (in buffer) before storing it
679  *      - applies a reverse Chaikin filter
680  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
681  */
682 static void gp_stroke_simplify(tGPsdata *p)
683 {
684         bGPdata *gpd = p->gpd;
685         tGPspoint *old_points = (tGPspoint *)gpd->sbuffer;
686         short num_points = gpd->sbuffer_size;
687         short flag = gpd->sbuffer_sflag;
688         short i, j;
689         
690         /* only simplify if simplification is enabled, and we're not doing a straight line */
691         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
692                 return;
693         
694         /* don't simplify if less than 4 points in buffer */
695         if ((num_points <= 4) || (old_points == NULL))
696                 return;
697         
698         /* clear buffer (but don't free mem yet) so that we can write to it
699          *      - firstly set sbuffer to NULL, so a new one is allocated
700          *      - secondly, reset flag after, as it gets cleared auto
701          */
702         gpd->sbuffer = NULL;
703         gp_session_validatebuffer(p);
704         gpd->sbuffer_sflag = flag;
705         
706 /* macro used in loop to get position of new point
707  *      - used due to the mixture of datatypes in use here
708  */
709 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
710         { \
711                 co[0] += (float)(old_points[offs].x * sfac); \
712                 co[1] += (float)(old_points[offs].y * sfac); \
713                 pressure += old_points[offs].pressure * sfac; \
714                 time += old_points[offs].time * sfac; \
715         } (void)0
716         
717         /* XXX Here too, do not lose start and end points! */
718         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
719         for (i = 0, j = 0; i < num_points; i++) {
720                 if (i - j == 3) {
721                         float co[2], pressure, time;
722                         int mco[2];
723                         
724                         /* initialize values */
725                         co[0] = 0.0f;
726                         co[1] = 0.0f;
727                         pressure = 0.0f;
728                         time = 0.0f;
729                         
730                         /* using macro, calculate new point */
731                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
732                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
733                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
734                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
735                         
736                         /* set values for adding */
737                         mco[0] = (int)co[0];
738                         mco[1] = (int)co[1];
739                         
740                         /* ignore return values on this... assume to be ok for now */
741                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
742                         
743                         j += 2;
744                 }
745         }
746         gp_stroke_addpoint(p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
747                            p->inittime + (double)old_points[num_points - 1].time);
748         
749         /* free old buffer */
750         MEM_freeN(old_points);
751 }
752
753 /* make a new stroke from the buffer data */
754 static void gp_stroke_newfrombuffer(tGPsdata *p)
755 {
756         bGPdata *gpd = p->gpd;
757         bGPDlayer *gpl = p->gpl;
758         bGPDstroke *gps;
759         bGPDspoint *pt;
760         tGPspoint *ptc;
761         bGPDbrush *brush = p->brush;
762         ToolSettings *ts = p->scene->toolsettings;
763         
764         int i, totelem;
765         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
766         int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
767         
768         /* get total number of points to allocate space for
769          *      - drawing straight-lines only requires the endpoints
770          */
771         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
772                 totelem = (gpd->sbuffer_size >= 2) ? 2 : gpd->sbuffer_size;
773         else
774                 totelem = gpd->sbuffer_size;
775         
776         /* exit with error if no valid points from this stroke */
777         if (totelem == 0) {
778                 if (G.debug & G_DEBUG)
779                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->sbuffer_size);
780                 return;
781         }
782         
783         /* special case for poly line -- for already added stroke during session
784          * coordinates are getting added to stroke immediately to allow more
785          * interactive behavior
786          */
787         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
788                 if (gp_stroke_added_check(p)) {
789                         return;
790                 }
791         }
792         
793         /* allocate memory for a new stroke */
794         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
795         
796         /* copy appropriate settings for stroke */
797         gps->totpoints = totelem;
798         gps->thickness = brush->thickness;
799         gps->flag = gpd->sbuffer_sflag;
800         gps->inittime = p->inittime;
801         
802         /* enable recalculation flag by default (only used if hq fill) */
803         gps->flag |= GP_STROKE_RECALC_CACHES;
804
805         /* allocate enough memory for a continuous array for storage points */
806         int sublevel = brush->sublevel;
807         int new_totpoints = gps->totpoints;
808         
809         for (i = 0; i < sublevel; i++) {
810                 new_totpoints += new_totpoints - 1;
811         }
812         gps->points = MEM_callocN(sizeof(bGPDspoint) * new_totpoints, "gp_stroke_points");
813         /* initialize triangle memory to dummy data */
814         gps->triangles = MEM_callocN(sizeof(bGPDtriangle), "GP Stroke triangulation");
815         gps->flag |= GP_STROKE_RECALC_CACHES;
816         gps->tot_triangles = 0;
817         /* set pointer to first non-initialized point */
818         pt = gps->points + (gps->totpoints - totelem);
819         
820         /* copy points from the buffer to the stroke */
821         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
822                 /* straight lines only -> only endpoints */
823                 {
824                         /* first point */
825                         ptc = gpd->sbuffer;
826                         
827                         /* convert screen-coordinates to appropriate coordinates (and store them) */
828                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
829                         /* if axis locked, reproject to plane locked (only in 3d space) */
830                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
831                                 gp_reproject_toplane(p, gps);
832                         }
833                         /* if parented change position relative to parent object */
834                         if (gpl->parent != NULL) {
835                                 gp_apply_parent_point(gpl, pt);
836                         }
837                         /* copy pressure and time */
838                         pt->pressure = ptc->pressure;
839                         pt->strength = ptc->strength;
840                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
841                         pt->time = ptc->time;
842                         
843                         pt++;
844                 }
845                 
846                 if (totelem == 2) {
847                         /* last point if applicable */
848                         ptc = ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
849                         
850                         /* convert screen-coordinates to appropriate coordinates (and store them) */
851                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
852                         /* if axis locked, reproject to plane locked (only in 3d space) */
853                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
854                                 gp_reproject_toplane(p, gps);
855                         }
856                         /* if parented change position relative to parent object */
857                         if (gpl->parent != NULL) {
858                                 gp_apply_parent_point(gpl, pt);
859                         }
860
861                         /* copy pressure and time */
862                         pt->pressure = ptc->pressure;
863                         pt->strength = ptc->strength;
864                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
865                         pt->time = ptc->time;
866                 }
867         }
868         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
869                 /* first point */
870                 ptc = gpd->sbuffer;
871                 
872                 /* convert screen-coordinates to appropriate coordinates (and store them) */
873                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
874                 /* if axis locked, reproject to plane locked (only in 3d space) */
875                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
876                         gp_reproject_toplane(p, gps);
877                 }
878                 /* if parented change position relative to parent object */
879                 if (gpl->parent != NULL) {
880                         gp_apply_parent_point(gpl, pt);
881                 }
882                 /* copy pressure and time */
883                 pt->pressure = ptc->pressure;
884                 pt->strength = ptc->strength;
885                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
886                 pt->time = ptc->time;
887         }
888         else {
889                 float *depth_arr = NULL;
890
891                 /* get an array of depths, far depths are blended */
892                 if (gpencil_project_check(p)) {
893                         int mval[2], mval_prev[2] = { 0 };
894                         int interp_depth = 0;
895                         int found_depth = 0;
896
897                         depth_arr = MEM_mallocN(sizeof(float) * gpd->sbuffer_size, "depth_points");
898
899                         for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size; i++, ptc++, pt++) {
900                                 copy_v2_v2_int(mval, &ptc->x);
901
902                                 if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
903                                     (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
904                                 {
905                                         interp_depth = true;
906                                 }
907                                 else {
908                                         found_depth = true;
909                                 }
910
911                                 copy_v2_v2_int(mval_prev, mval);
912                         }
913
914                         if (found_depth == false) {
915                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
916                                 for (i = gpd->sbuffer_size - 1; i >= 0; i--)
917                                         depth_arr[i] = 0.9999f;
918                         }
919                         else {
920                                 if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
921                                         /* remove all info between the valid endpoints */
922                                         int first_valid = 0;
923                                         int last_valid = 0;
924
925                                         for (i = 0; i < gpd->sbuffer_size; i++) {
926                                                 if (depth_arr[i] != FLT_MAX)
927                                                         break;
928                                         }
929                                         first_valid = i;
930
931                                         for (i = gpd->sbuffer_size - 1; i >= 0; i--) {
932                                                 if (depth_arr[i] != FLT_MAX)
933                                                         break;
934                                         }
935                                         last_valid = i;
936
937                                         /* invalidate non-endpoints, so only blend between first and last */
938                                         for (i = first_valid + 1; i < last_valid; i++)
939                                                 depth_arr[i] = FLT_MAX;
940
941                                         interp_depth = true;
942                                 }
943
944                                 if (interp_depth) {
945                                         interp_sparse_array(depth_arr, gpd->sbuffer_size, FLT_MAX);
946                                 }
947                         }
948                 }
949
950
951                 pt = gps->points;
952
953                 /* convert all points (normal behavior) */
954                 for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++, pt++) {
955                         /* convert screen-coordinates to appropriate coordinates (and store them) */
956                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
957
958                         /* copy pressure and time */
959                         pt->pressure = ptc->pressure;
960                         pt->strength = ptc->strength;
961                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
962                         pt->time = ptc->time;
963                 }
964
965                 /* subdivide the stroke */
966                 if (sublevel > 0) {
967                         int totpoints = gps->totpoints;
968                         for (i = 0; i < sublevel; i++) {
969                                 /* we're adding one new point between each pair of verts on each step */
970                                 totpoints += totpoints - 1;
971
972                                 gp_subdivide_stroke(gps, totpoints);
973                         }
974                 }
975                 /* apply randomness to stroke */
976                 if (brush->draw_random_sub > 0.0f) {
977                         gp_randomize_stroke(gps, brush);
978                 }
979
980                 /* smooth stroke after subdiv - only if there's something to do
981                  * for each iteration, the factor is reduced to get a better smoothing without changing too much
982                  * the original stroke
983                  */
984                 if (brush->draw_smoothfac > 0.0f) {
985                         float reduce = 0.0f;
986                         for (int r = 0; r < brush->draw_smoothlvl; ++r) {
987                                 for (i = 0; i < gps->totpoints; i++) {
988                                         /* NOTE: No pressure smoothing, or else we get annoying thickness changes while drawing... */
989                                         gp_smooth_stroke(gps, i, brush->draw_smoothfac - reduce, false);
990                                 }
991                                 reduce += 0.25f;  // reduce the factor
992                         }
993                 }
994
995                 /* if axis locked, reproject to plane locked (only in 3d space) */
996                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
997                         gp_reproject_toplane(p, gps);
998                 }
999                 /* if parented change position relative to parent object */
1000                 if (gpl->parent != NULL) {
1001                         gp_apply_parent(gpl, gps);
1002                 }
1003
1004                 if (depth_arr)
1005                         MEM_freeN(depth_arr);
1006         }
1007         /* Save palette color */
1008         bGPDpalette *palette = BKE_gpencil_palette_getactive(p->gpd);
1009         bGPDpalettecolor *palcolor = BKE_gpencil_palettecolor_getactive(palette);
1010         gps->palcolor = palcolor;
1011         BLI_strncpy(gps->colorname, palcolor->info, sizeof(gps->colorname));
1012
1013         /* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head 
1014          * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
1015          * when drawing the background
1016          */
1017         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
1018                 BLI_addhead(&p->gpf->strokes, gps);
1019         }
1020         else {
1021                 BLI_addtail(&p->gpf->strokes, gps);
1022         }
1023         gp_stroke_added_enable(p);
1024 }
1025
1026 /* --- 'Eraser' for 'Paint' Tool ------ */
1027
1028 /* which which point is infront (result should only be used for comparison) */
1029 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1030 {
1031         if (rv3d->is_persp) {
1032                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1033         }
1034         else {
1035                 return -dot_v3v3(rv3d->viewinv[2], co);
1036         }
1037 }
1038
1039 /* only erase stroke points that are visible */
1040 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1041 {
1042         if ((p->sa->spacetype == SPACE_VIEW3D) &&
1043             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
1044         {
1045                 RegionView3D *rv3d = p->ar->regiondata;
1046                 bGPDlayer *gpl = p->gpl;
1047
1048                 const int mval[2] = {x, y};
1049                 float mval_3d[3];
1050                 float fpt[3];
1051
1052                 float diff_mat[4][4];
1053                 /* calculate difference matrix if parent object */
1054                 ED_gpencil_parent_location(gpl, diff_mat);
1055
1056                 if (ED_view3d_autodist_simple(p->ar, mval, mval_3d, 0, NULL)) {
1057                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1058
1059                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1060                         const float depth_pt   = view3d_point_depth(rv3d, fpt);
1061                         
1062                         if (depth_pt > depth_mval) {
1063                                 return true;
1064                         }
1065                 }
1066         }
1067         return false;
1068 }
1069
1070 /* apply a falloff effect to brush strength, based on distance */
1071 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const int mval[2], const int radius, const int co[2])
1072 {
1073         /* Linear Falloff... */
1074         float distance = (float)len_v2v2_int(mval, co);
1075         float fac;
1076         
1077         CLAMP(distance, 0.0f, (float)radius);
1078         fac = 1.0f - (distance / (float)radius);
1079         
1080         /* Control this further using pen pressure */
1081         fac *= p->pressure;
1082         
1083         /* Return influence factor computed here */
1084         return fac;
1085 }
1086
1087 /* eraser tool - evaluation per stroke */
1088 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1089 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1090                                       bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1091                                       const int mval[2], const int mvalo[2],
1092                                       const int radius, const rcti *rect)
1093 {
1094         bGPDspoint *pt1, *pt2;
1095         int pc1[2] = {0};
1096         int pc2[2] = {0};
1097         int i;
1098         float diff_mat[4][4];
1099
1100         /* calculate difference matrix if parent object */
1101         if (gpl->parent != NULL) {
1102                 ED_gpencil_parent_location(gpl, diff_mat);
1103         }
1104
1105         if (gps->totpoints == 0) {
1106                 /* just free stroke */
1107                 if (gps->points)
1108                         MEM_freeN(gps->points);
1109                 if (gps->triangles)
1110                         MEM_freeN(gps->triangles);
1111                 BLI_freelinkN(&gpf->strokes, gps);
1112         }
1113         else if (gps->totpoints == 1) {
1114                 /* only process if it hasn't been masked out... */
1115                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1116                         if (gpl->parent == NULL) {
1117                                 gp_point_to_xy(&p->gsc, gps, gps->points, &pc1[0], &pc1[1]);
1118                         }
1119                         else {
1120                                 bGPDspoint pt_temp;
1121                                 gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1122                                 gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1123                         }
1124                         /* do boundbox check first */
1125                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1126                                 /* only check if point is inside */
1127                                 if (len_v2v2_int(mval, pc1) <= radius) {
1128                                         /* free stroke */
1129                                         // XXX: pressure sensitive eraser should apply here too?
1130                                         MEM_freeN(gps->points);
1131                                         if (gps->triangles)
1132                                                 MEM_freeN(gps->triangles);
1133                                         BLI_freelinkN(&gpf->strokes, gps);
1134                                 }
1135                         }
1136                 }
1137         }
1138         else {
1139                 /* Pressure threshold at which stroke should be culled: Calculated as pressure value
1140                  * below which we would have invisible strokes
1141                  */
1142                 const float cull_thresh = (gps->thickness) ?  1.0f / ((float)gps->thickness)  : 1.0f;
1143                 
1144                 /* Amount to decrease the pressure of each point with each stroke */
1145                 // TODO: Fetch from toolsettings, or compute based on thickness instead?
1146                 const float strength = 0.1f;
1147                 
1148                 /* Perform culling? */
1149                 bool do_cull = false;
1150                 
1151                 
1152                 /* Clear Tags
1153                  *
1154                  * Note: It's better this way, as we are sure that
1155                  * we don't miss anything, though things will be
1156                  * slightly slower as a result
1157                  */
1158                 for (i = 0; i < gps->totpoints; i++) {
1159                         bGPDspoint *pt = &gps->points[i];
1160                         pt->flag &= ~GP_SPOINT_TAG;
1161                 }
1162                 
1163                 /* First Pass: Loop over the points in the stroke
1164                  *   1) Thin out parts of the stroke under the brush
1165                  *   2) Tag "too thin" parts for removal (in second pass)
1166                  */
1167                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1168                         /* get points to work with */
1169                         pt1 = gps->points + i;
1170                         pt2 = gps->points + i + 1;
1171
1172                         /* only process if it hasn't been masked out... */
1173                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1174                                 continue;
1175                         
1176                         if (gpl->parent == NULL) {
1177                                 gp_point_to_xy(&p->gsc, gps, pt1, &pc1[0], &pc1[1]);
1178                                 gp_point_to_xy(&p->gsc, gps, pt2, &pc2[0], &pc2[1]);
1179                         }
1180                         else {
1181                                 bGPDspoint npt;
1182                                 gp_point_to_parent_space(pt1, diff_mat, &npt);
1183                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1184
1185                                 gp_point_to_parent_space(pt2, diff_mat, &npt);
1186                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1187                         }
1188
1189                         /* Check that point segment of the boundbox of the eraser stroke */
1190                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1191                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1192                         {
1193                                 /* Check if point segment of stroke had anything to do with
1194                                  * eraser region  (either within stroke painted, or on its lines)
1195                                  *  - this assumes that linewidth is irrelevant
1196                                  */
1197                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
1198                                         if ((gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1199                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1200                                         {
1201                                                 /* Point is affected: */
1202                                                 /* 1) Adjust thickness
1203                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1204                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1205                                                  */
1206                                                 pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1207                                                 pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength / 2.0f;
1208                                                 
1209                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1210                                                 if (pt1->pressure < cull_thresh) {
1211                                                         pt1->flag |= GP_SPOINT_TAG;
1212                                                         do_cull = true;
1213                                                 }
1214                                                 if (pt2->pressure < cull_thresh) {
1215                                                         pt2->flag |= GP_SPOINT_TAG;
1216                                                         do_cull = true;
1217                                                 }
1218                                         }
1219                                 }
1220                         }
1221                 }
1222                 
1223                 /* Second Pass: Remove any points that are tagged */
1224                 if (do_cull) {
1225                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG);
1226                 }
1227         }
1228 }
1229
1230 /* erase strokes which fall under the eraser strokes */
1231 static void gp_stroke_doeraser(tGPsdata *p)
1232 {
1233         bGPDlayer *gpl;
1234         bGPDstroke *gps, *gpn;
1235         rcti rect;
1236         
1237         /* rect is rectangle of eraser */
1238         rect.xmin = p->mval[0] - p->radius;
1239         rect.ymin = p->mval[1] - p->radius;
1240         rect.xmax = p->mval[0] + p->radius;
1241         rect.ymax = p->mval[1] + p->radius;
1242         
1243         if (p->sa->spacetype == SPACE_VIEW3D) {
1244                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
1245                         View3D *v3d = p->sa->spacedata.first;
1246                         view3d_region_operator_needs_opengl(p->win, p->ar);
1247                         ED_view3d_autodist_init(p->graph, p->ar, v3d, 0);
1248                 }
1249         }
1250         
1251         /* loop over all layers too, since while it's easy to restrict editing to
1252          * only a subset of layers, it is harder to perform the same erase operation
1253          * on multiple layers...
1254          */
1255         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1256                 bGPDframe *gpf = gpl->actframe;
1257                 
1258                 /* only affect layer if it's editable (and visible) */
1259                 if (gpencil_layer_is_editable(gpl) == false) {
1260                         continue;
1261                 }
1262                 else if (gpf == NULL) {
1263                         continue;
1264                 }
1265                 
1266                 /* loop over strokes, checking segments for intersections */
1267                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1268                         gpn = gps->next;
1269                         /* check if the color is editable */
1270                         if (ED_gpencil_stroke_color_use(gpl, gps) == false) {
1271                                 continue;
1272                         }
1273                         /* Not all strokes in the datablock may be valid in the current editor/context
1274                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1275                          */
1276                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1277                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, p->radius, &rect);
1278                         }
1279                 }
1280         }
1281 }
1282
1283 /* ******************************************* */
1284 /* Sketching Operator */
1285
1286 /* clear the session buffers (call this before AND after a paint operation) */
1287 static void gp_session_validatebuffer(tGPsdata *p)
1288 {
1289         bGPdata *gpd = p->gpd;
1290         
1291         /* clear memory of buffer (or allocate it if starting a new session) */
1292         if (gpd->sbuffer) {
1293                 /* printf("\t\tGP - reset sbuffer\n"); */
1294                 memset(gpd->sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1295         }
1296         else {
1297                 /* printf("\t\tGP - allocate sbuffer\n"); */
1298                 gpd->sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1299         }
1300         
1301         /* reset indices */
1302         gpd->sbuffer_size = 0;
1303         
1304         /* reset flags */
1305         gpd->sbuffer_sflag = 0;
1306         
1307         /* reset inittime */
1308         p->inittime = 0.0;
1309 }
1310
1311 /* create a new palette color */
1312 static bGPDpalettecolor *gp_create_new_color(bGPDpalette *palette)
1313 {
1314         bGPDpalettecolor *palcolor;
1315
1316         palcolor = BKE_gpencil_palettecolor_addnew(palette, DATA_("Color"), true);
1317         
1318         return palcolor;
1319 }
1320
1321 /* initialize a drawing brush */
1322 static void gp_init_drawing_brush(ToolSettings *ts, tGPsdata *p)
1323 {
1324         bGPDbrush *brush;
1325
1326         /* if not exist, create a new one */
1327         if (BLI_listbase_is_empty(&ts->gp_brushes)) {
1328                 /* create new brushes */
1329                 BKE_gpencil_brush_init_presets(ts);
1330                 brush = BKE_gpencil_brush_getactive(ts);
1331         }
1332         else {
1333                 /* Use the current */
1334                 brush = BKE_gpencil_brush_getactive(ts);
1335         }
1336         /* be sure curves are initializated */
1337         curvemapping_initialize(brush->cur_sensitivity);
1338         curvemapping_initialize(brush->cur_strength);
1339         curvemapping_initialize(brush->cur_jitter);
1340
1341         /* asign to temp tGPsdata */
1342         p->brush = brush;
1343 }
1344
1345
1346 /* initialize a paint palette brush and a default color if not exist */
1347 static void gp_init_palette(tGPsdata *p)
1348 {
1349         bGPdata *gpd;
1350         bGPDpalette *palette;
1351         bGPDpalettecolor *palcolor;
1352
1353         gpd = p->gpd;
1354
1355         /* if not exist, create a new palette */
1356         if (BLI_listbase_is_empty(&gpd->palettes)) {
1357                 /* create new palette */
1358                 palette = BKE_gpencil_palette_addnew(gpd, DATA_("GP_Palette"), true);
1359                 /* now create a default color */
1360                 palcolor = gp_create_new_color(palette);
1361         }
1362         else {
1363                 /* Use the current palette and color */
1364                 palette = BKE_gpencil_palette_getactive(gpd);
1365                 /* the palette needs one color */
1366                 if (BLI_listbase_is_empty(&palette->colors)) {
1367                         palcolor = gp_create_new_color(palette);
1368                 }
1369                 else {
1370                         palcolor = BKE_gpencil_palettecolor_getactive(palette);
1371                 }
1372                 /* in some situations can be null, so use first */
1373                 if (palcolor == NULL) {
1374                         BKE_gpencil_palettecolor_setactive(palette, palette->colors.first);
1375                         palcolor = palette->colors.first;
1376                 }
1377         }
1378
1379         /* asign to temp tGPsdata */
1380         p->palettecolor = palcolor;
1381 }
1382
1383 /* (re)init new painting data */
1384 static bool gp_session_initdata(bContext *C, tGPsdata *p)
1385 {
1386         bGPdata **gpd_ptr = NULL;
1387         ScrArea *curarea = CTX_wm_area(C);
1388         ARegion *ar = CTX_wm_region(C);
1389         ToolSettings *ts = CTX_data_tool_settings(C);
1390         
1391         /* make sure the active view (at the starting time) is a 3d-view */
1392         if (curarea == NULL) {
1393                 p->status = GP_STATUS_ERROR;
1394                 if (G.debug & G_DEBUG)
1395                         printf("Error: No active view for painting\n");
1396                 return 0;
1397         }
1398         
1399         /* pass on current scene and window */
1400         p->scene = CTX_data_scene(C);
1401         p->graph = CTX_data_depsgraph(C);
1402         p->win = CTX_wm_window(C);
1403         
1404         unit_m4(p->imat);
1405         unit_m4(p->mat);
1406         
1407         switch (curarea->spacetype) {
1408                 /* supported views first */
1409                 case SPACE_VIEW3D:
1410                 {
1411                         /* View3D *v3d = curarea->spacedata.first; */
1412                         /* RegionView3D *rv3d = ar->regiondata; */
1413                         
1414                         /* set current area
1415                          *      - must verify that region data is 3D-view (and not something else)
1416                          */
1417                         /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1418                         p->sa = curarea;
1419                         p->ar = ar;
1420                         p->align_flag = &ts->gpencil_v3d_align;
1421                         
1422                         if (ar->regiondata == NULL) {
1423                                 p->status = GP_STATUS_ERROR;
1424                                 if (G.debug & G_DEBUG)
1425                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1426                                 return 0;
1427                         }
1428                         break;
1429                 }
1430                 case SPACE_NODE:
1431                 {
1432                         /* SpaceNode *snode = curarea->spacedata.first; */
1433                         
1434                         /* set current area */
1435                         p->sa = curarea;
1436                         p->ar = ar;
1437                         p->v2d = &ar->v2d;
1438                         p->align_flag = &ts->gpencil_v2d_align;
1439                         break;
1440                 }
1441                 case SPACE_SEQ:
1442                 {
1443                         SpaceSeq *sseq = curarea->spacedata.first;
1444                         
1445                         /* set current area */
1446                         p->sa = curarea;
1447                         p->ar = ar;
1448                         p->v2d = &ar->v2d;
1449                         p->align_flag = &ts->gpencil_seq_align;
1450                         
1451                         /* check that gpencil data is allowed to be drawn */
1452                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1453                                 p->status = GP_STATUS_ERROR;
1454                                 if (G.debug & G_DEBUG)
1455                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1456                                 return 0;
1457                         }
1458                         break;
1459                 }
1460                 case SPACE_IMAGE:
1461                 {
1462                         /* SpaceImage *sima = curarea->spacedata.first; */
1463                         
1464                         /* set the current area */
1465                         p->sa = curarea;
1466                         p->ar = ar;
1467                         p->v2d = &ar->v2d;
1468                         p->align_flag = &ts->gpencil_ima_align;
1469                         break;
1470                 }
1471                 case SPACE_CLIP:
1472                 {
1473                         SpaceClip *sc = curarea->spacedata.first;
1474                         MovieClip *clip = ED_space_clip_get_clip(sc);
1475                         
1476                         if (clip == NULL) {
1477                                 p->status = GP_STATUS_ERROR;
1478                                 return false;
1479                         }
1480
1481                         /* set the current area */
1482                         p->sa = curarea;
1483                         p->ar = ar;
1484                         p->v2d = &ar->v2d;
1485                         p->align_flag = &ts->gpencil_v2d_align;
1486                         
1487                         invert_m4_m4(p->imat, sc->unistabmat);
1488                         
1489                         /* custom color for new layer */
1490                         p->custom_color[0] = 1.0f;
1491                         p->custom_color[1] = 0.0f;
1492                         p->custom_color[2] = 0.5f;
1493                         p->custom_color[3] = 0.9f;
1494                         
1495                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1496                                 int framenr = ED_space_clip_get_clip_frame_number(sc);
1497                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
1498                                 MovieTrackingMarker *marker = track ? BKE_tracking_marker_get(track, framenr) : NULL;
1499
1500                                 if (marker) {
1501                                         p->imat[3][0] -= marker->pos[0];
1502                                         p->imat[3][1] -= marker->pos[1];
1503                                 }
1504                                 else {
1505                                         p->status = GP_STATUS_ERROR;
1506                                         return false;
1507                                 }
1508                         }
1509                         
1510                         invert_m4_m4(p->mat, p->imat);
1511                         copy_m4_m4(p->gsc.mat, p->mat);
1512                         break;
1513                 }
1514                 /* unsupported views */
1515                 default:
1516                 {
1517                         p->status = GP_STATUS_ERROR;
1518                         if (G.debug & G_DEBUG)
1519                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1520                         return 0;
1521                 }
1522         }
1523         
1524         /* get gp-data */
1525         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1526         if (gpd_ptr == NULL) {
1527                 p->status = GP_STATUS_ERROR;
1528                 if (G.debug & G_DEBUG)
1529                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1530                 return 0;
1531         }
1532         else {
1533                 /* if no existing GPencil block exists, add one */
1534                 if (*gpd_ptr == NULL)
1535                         *gpd_ptr = BKE_gpencil_data_addnew("GPencil");
1536                 p->gpd = *gpd_ptr;
1537         }
1538         
1539         if (ED_gpencil_session_active() == 0) {
1540                 /* initialize undo stack,
1541                  * also, existing undo stack would make buffer drawn
1542                  */
1543                 gpencil_undo_init(p->gpd);
1544         }
1545         
1546         /* clear out buffer (stored in gp-data), in case something contaminated it */
1547         gp_session_validatebuffer(p);
1548         /* set brush and create a new one if null */
1549         gp_init_drawing_brush(ts, p);
1550         /* set palette info and create a new one if null */
1551         gp_init_palette(p);
1552         /* set palette colors */
1553         bGPDpalettecolor *palcolor = p->palettecolor;
1554         bGPdata *pdata = p->gpd;
1555         copy_v4_v4(pdata->scolor, palcolor->color);
1556         copy_v4_v4(pdata->sfill, palcolor->fill);
1557         pdata->sflag = palcolor->flag;
1558         /* lock axis */
1559         p->lock_axis = ts->gp_sculpt.lock_axis;
1560
1561         return 1;
1562 }
1563
1564 /* init new painting session */
1565 static tGPsdata *gp_session_initpaint(bContext *C)
1566 {
1567         tGPsdata *p = NULL;
1568         
1569         /* create new context data */
1570         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1571         
1572         gp_session_initdata(C, p);
1573         
1574         /* radius for eraser circle is defined in userprefs now */
1575         /* NOTE: we do this here, so that if we exit immediately,
1576          *       erase size won't get lost
1577          */
1578         p->radius = U.gp_eraser;
1579
1580         /* return context data for running paint operator */
1581         return p;
1582 }
1583
1584 /* cleanup after a painting session */
1585 static void gp_session_cleanup(tGPsdata *p)
1586 {
1587         bGPdata *gpd = (p) ? p->gpd : NULL;
1588         
1589         /* error checking */
1590         if (gpd == NULL)
1591                 return;
1592         
1593         /* free stroke buffer */
1594         if (gpd->sbuffer) {
1595                 /* printf("\t\tGP - free sbuffer\n"); */
1596                 MEM_freeN(gpd->sbuffer);
1597                 gpd->sbuffer = NULL;
1598         }
1599         
1600         /* clear flags */
1601         gpd->sbuffer_size = 0;
1602         gpd->sbuffer_sflag = 0;
1603         p->inittime = 0.0;
1604 }
1605
1606 /* init new stroke */
1607 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode)
1608 {
1609         Scene *scene = p->scene;
1610         ToolSettings *ts = scene->toolsettings;
1611         
1612         /* get active layer (or add a new one if non-existent) */
1613         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1614         if (p->gpl == NULL) {
1615                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, "GP_Layer", true);
1616                 
1617                 if (p->custom_color[3])
1618                         copy_v3_v3(p->gpl->color, p->custom_color);
1619         }
1620         if (p->gpl->flag & GP_LAYER_LOCKED) {
1621                 p->status = GP_STATUS_ERROR;
1622                 if (G.debug & G_DEBUG)
1623                         printf("Error: Cannot paint on locked layer\n");
1624                 return;
1625         }
1626         
1627         /* get active frame (add a new one if not matching frame) */
1628         if (paintmode == GP_PAINTMODE_ERASER) {
1629                 /* Eraser mode:
1630                  * 1) Add new frames to all frames that we might touch,
1631                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1632                  *    (to avoid problems with other tools which expect it to exist)
1633                  */
1634                 bool has_layer_to_erase = false;
1635                 
1636                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1637                         /* Skip if layer not editable */
1638                         if (gpencil_layer_is_editable(gpl) == false)
1639                                 continue;
1640                         
1641                         /* Add a new frame if needed (and based off the active frame,
1642                          * as we need some existing strokes to erase)
1643                          *
1644                          * Note: We don't add a new frame if there's nothing there now, so
1645                          *       -> If there are no frames at all, don't add one
1646                          *       -> If there are no strokes in that frame, don't add a new empty frame
1647                          */
1648                         if (gpl->actframe && gpl->actframe->strokes.first) {
1649                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, CFRA, GP_GETFRAME_ADD_COPY);
1650                                 has_layer_to_erase = true;
1651                         }
1652                         
1653                         /* XXX: we omit GP_FRAME_PAINT here for now,
1654                          * as it is only really useful for doing
1655                          * paintbuffer drawing
1656                          */
1657                 }
1658                 
1659                 /* Ensure this gets set... */
1660                 p->gpf = p->gpl->actframe;
1661                 
1662                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
1663                  * (though this is only available in editmode)
1664                  */
1665                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
1666                         if (ts->gp_sculpt.flag & GP_BRUSHEDIT_FLAG_SELECT_MASK) {
1667                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
1668                         }
1669                 }
1670                 
1671                 if (has_layer_to_erase == false) {
1672                         p->status = GP_STATUS_ERROR;
1673                         //if (G.debug & G_DEBUG)
1674                                 printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
1675                         return;
1676                 }
1677         }
1678         else {
1679                 /* Drawing Modes - Add a new frame if needed on the active layer */
1680                 short add_frame_mode;
1681                 
1682                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
1683                         add_frame_mode = GP_GETFRAME_ADD_COPY;
1684                 else
1685                         add_frame_mode = GP_GETFRAME_ADD_NEW;
1686                         
1687                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, CFRA, add_frame_mode);
1688                 
1689                 if (p->gpf == NULL) {
1690                         p->status = GP_STATUS_ERROR;
1691                         if (G.debug & G_DEBUG)
1692                                 printf("Error: No frame created (gpencil_paint_init)\n");
1693                         return;
1694                 }
1695                 else {
1696                         p->gpf->flag |= GP_FRAME_PAINT;
1697                 }
1698         }
1699         
1700         /* set 'eraser' for this stroke if using eraser */
1701         p->paintmode = paintmode;
1702         if (p->paintmode == GP_PAINTMODE_ERASER) {
1703                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1704                 
1705                 /* check if we should respect depth while erasing */
1706                 if (p->sa->spacetype == SPACE_VIEW3D) {
1707                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1708                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1709                         }
1710                 }
1711         }
1712         else {
1713                 /* disable eraser flags - so that we can switch modes during a session */
1714                 p->gpd->sbuffer_sflag &= ~GP_STROKE_ERASER;
1715                 
1716                 if (p->sa->spacetype == SPACE_VIEW3D) {
1717                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1718                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
1719                         }
1720                 }
1721         }
1722         
1723         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1724         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1725         
1726         
1727         /* when drawing in the camera view, in 2D space, set the subrect */
1728         p->subrect = NULL;
1729         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
1730                 if (p->sa->spacetype == SPACE_VIEW3D) {
1731                         View3D *v3d = p->sa->spacedata.first;
1732                         RegionView3D *rv3d = p->ar->regiondata;
1733                         
1734                         /* for camera view set the subrect */
1735                         if (rv3d->persp == RV3D_CAMOB) {
1736                                 ED_view3d_calc_camera_border(p->scene, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1737                                 p->subrect = &p->subrect_data;
1738                         }
1739                 }
1740         }
1741         
1742         /* init stroke point space-conversion settings... */
1743         p->gsc.gpd = p->gpd;
1744         p->gsc.gpl = p->gpl;
1745         
1746         p->gsc.sa = p->sa;
1747         p->gsc.ar = p->ar;
1748         p->gsc.v2d = p->v2d;
1749         
1750         p->gsc.subrect_data = p->subrect_data;
1751         p->gsc.subrect = p->subrect;
1752         
1753         copy_m4_m4(p->gsc.mat, p->mat);
1754         
1755         
1756         /* check if points will need to be made in view-aligned space */
1757         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
1758                 switch (p->sa->spacetype) {
1759                         case SPACE_VIEW3D:
1760                         {
1761                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1762                                 break;
1763                         }
1764                         case SPACE_NODE:
1765                         {
1766                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1767                                 break;
1768                         }
1769                         case SPACE_SEQ:
1770                         {
1771                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1772                                 break;
1773                         }
1774                         case SPACE_IMAGE:
1775                         {
1776                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1777                                 
1778                                 /* only set these flags if the image editor doesn't have an image active,
1779                                  * otherwise user will be confused by strokes not appearing after they're drawn
1780                                  *
1781                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1782                                  */
1783                                 if (ELEM(NULL, sima, sima->image)) {
1784                                         /* make strokes be drawn in screen space */
1785                                         p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1786                                         *(p->align_flag) &= ~GP_PROJECT_VIEWSPACE;
1787                                 }
1788                                 else {
1789                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1790                                 }
1791                                 break;
1792                         }
1793                         case SPACE_CLIP:
1794                         {
1795                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1796                                 break;
1797                         }
1798                 }
1799         }
1800 }
1801
1802 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1803 static void gp_paint_strokeend(tGPsdata *p)
1804 {
1805         ToolSettings *ts = p->scene->toolsettings;
1806         /* for surface sketching, need to set the right OpenGL context stuff so that
1807          * the conversions will project the values correctly...
1808          */
1809         if (gpencil_project_check(p)) {
1810                 View3D *v3d = p->sa->spacedata.first;
1811                 
1812                 /* need to restore the original projection settings before packing up */
1813                 view3d_region_operator_needs_opengl(p->win, p->ar);
1814                 ED_view3d_autodist_init(p->graph, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
1815         }
1816         
1817         /* check if doing eraser or not */
1818         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1819                 /* simplify stroke before transferring? */
1820                 gp_stroke_simplify(p);
1821                 
1822                 /* transfer stroke to frame */
1823                 gp_stroke_newfrombuffer(p);
1824         }
1825         
1826         /* clean up buffer now */
1827         gp_session_validatebuffer(p);
1828 }
1829
1830 /* finish off stroke painting operation */
1831 static void gp_paint_cleanup(tGPsdata *p)
1832 {
1833         /* p->gpd==NULL happens when stroke failed to initialize,
1834          * for example when GP is hidden in current space (sergey)
1835          */
1836         if (p->gpd) {
1837                 /* finish off a stroke */
1838                 gp_paint_strokeend(p);
1839         }
1840         
1841         /* "unlock" frame */
1842         if (p->gpf)
1843                 p->gpf->flag &= ~GP_FRAME_PAINT;
1844 }
1845
1846 /* ------------------------------- */
1847
1848 /* Helper callback for drawing the cursor itself */
1849 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1850 {
1851         tGPsdata *p = (tGPsdata *)p_ptr;
1852
1853         if (p->paintmode == GP_PAINTMODE_ERASER) {
1854                 Gwn_VertFormat *format = immVertexFormat();
1855                 const uint shdr_pos = GWN_vertformat_attr_add(format, "pos", GWN_COMP_F32, 2, GWN_FETCH_FLOAT);
1856                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1857
1858                 glEnable(GL_LINE_SMOOTH);
1859                 glEnable(GL_BLEND);
1860                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1861
1862                 immUniformColor4ub(255, 100, 100, 20);
1863                 imm_draw_circle_fill(shdr_pos, x, y, p->radius, 40);
1864
1865                 immUnbindProgram();
1866
1867                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_COLOR);
1868
1869                 float viewport_size[4];
1870                 glGetFloatv(GL_VIEWPORT, viewport_size);
1871                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
1872
1873                 immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
1874                 immUniform1i("num_colors", 0);  /* "simple" mode */
1875                 immUniform1f("dash_width", 12.0f);
1876                 immUniform1f("dash_factor", 0.5f);
1877
1878                 imm_draw_circle_wire(shdr_pos, x, y, p->radius,
1879                                      /* XXX Dashed shader gives bad results with sets of small segments currently,
1880                                       *     temp hack around the issue. :( */
1881                                      max_ii(8, p->radius / 2));  /* was fixed 40 */
1882
1883                 immUnbindProgram();
1884
1885                 glDisable(GL_BLEND);
1886                 glDisable(GL_LINE_SMOOTH);
1887         }
1888 }
1889
1890 /* Turn brush cursor in 3D view on/off */
1891 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1892 {
1893         if (p->erasercursor && !enable) {
1894                 /* clear cursor */
1895                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1896                 p->erasercursor = NULL;
1897         }
1898         else if (enable && !p->erasercursor) {
1899                 /* enable cursor */
1900                 p->erasercursor = WM_paint_cursor_activate(CTX_wm_manager(C),
1901                                                            NULL, /* XXX */
1902                                                            gpencil_draw_eraser, p);
1903         }
1904 }
1905
1906 /* Check if tablet eraser is being used (when processing events) */
1907 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
1908 {
1909         if (event->tablet_data) {
1910                 const wmTabletData *wmtab = event->tablet_data;
1911                 return (wmtab->Active == EVT_TABLET_ERASER);
1912         }
1913         
1914         return false;
1915 }
1916
1917 /* ------------------------------- */
1918
1919 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1920 {
1921         tGPsdata *p = op->customdata;
1922         
1923         /* clear undo stack */
1924         gpencil_undo_finish();
1925         
1926         /* restore cursor to indicate end of drawing */
1927         WM_cursor_modal_restore(CTX_wm_window(C));
1928         
1929         /* don't assume that operator data exists at all */
1930         if (p) {
1931                 /* check size of buffer before cleanup, to determine if anything happened here */
1932                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1933                         /* turn off radial brush cursor */
1934                         gpencil_draw_toggle_eraser_cursor(C, p, false);
1935                 }
1936
1937                 /* always store the new eraser size to be used again next time
1938                  * NOTE: Do this even when not in eraser mode, as eraser may
1939                  *       have been toggled at some point.
1940                  */
1941                 U.gp_eraser = p->radius;
1942                 
1943                 /* cleanup */
1944                 gp_paint_cleanup(p);
1945                 gp_session_cleanup(p);
1946                 
1947                 /* finally, free the temp data */
1948                 MEM_freeN(p);
1949         }
1950         
1951         op->customdata = NULL;
1952 }
1953
1954 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
1955 {
1956         /* this is just a wrapper around exit() */
1957         gpencil_draw_exit(C, op);
1958 }
1959
1960 /* ------------------------------- */
1961
1962
1963 static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
1964 {
1965         tGPsdata *p;
1966         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
1967         
1968         /* check context */
1969         p = op->customdata = gp_session_initpaint(C);
1970         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1971                 /* something wasn't set correctly in context */
1972                 gpencil_draw_exit(C, op);
1973                 return 0;
1974         }
1975         
1976         /* init painting data */
1977         gp_paint_initstroke(p, paintmode);
1978         if (p->status == GP_STATUS_ERROR) {
1979                 gpencil_draw_exit(C, op);
1980                 return 0;
1981         }
1982
1983         if (event != NULL) {
1984                 p->keymodifier = event->keymodifier;
1985         }
1986         else {
1987                 p->keymodifier = -1;
1988         }
1989         
1990         /* everything is now setup ok */
1991         return 1;
1992 }
1993
1994
1995 /* ------------------------------- */
1996
1997 /* ensure that the correct cursor icon is set */
1998 static void gpencil_draw_cursor_set(tGPsdata *p)
1999 {
2000         if (p->paintmode == GP_PAINTMODE_ERASER)
2001                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
2002         else
2003                 WM_cursor_modal_set(p->win, BC_PAINTBRUSHCURSOR);
2004 }
2005
2006 /* update UI indicators of status, including cursor and header prints */
2007 static void gpencil_draw_status_indicators(tGPsdata *p)
2008 {
2009         /* header prints */
2010         switch (p->status) {
2011                 case GP_STATUS_PAINTING:
2012                         /* only print this for paint-sessions, otherwise it gets annoying */
2013                         if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
2014                                 ED_area_headerprint(p->sa, IFACE_("Grease Pencil: Drawing/erasing stroke... Release to end stroke"));
2015                         break;
2016                 
2017                 case GP_STATUS_IDLING:
2018                         /* print status info */
2019                         switch (p->paintmode) {
2020                                 case GP_PAINTMODE_ERASER:
2021                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
2022                                                                           "ESC/Enter to end  (or click outside this area)"));
2023                                         break;
2024                                 case GP_PAINTMODE_DRAW_STRAIGHT:
2025                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
2026                                                                           "ESC/Enter to end  (or click outside this area)"));
2027                                         break;
2028                                 case GP_PAINTMODE_DRAW:
2029                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
2030                                                                           "E/ESC/Enter to end  (or click outside this area)"));
2031                                         break;
2032                                 case GP_PAINTMODE_DRAW_POLY:
2033                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2034                                                                           "ESC/Enter to end  (or click outside this area)"));
2035                                         break;
2036                                 
2037                                 default: /* unhandled future cases */
2038                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2039                                         break;
2040                         }
2041                         break;
2042                 
2043                 case GP_STATUS_ERROR:
2044                 case GP_STATUS_DONE:
2045                         /* clear status string */
2046                         ED_area_headerprint(p->sa, NULL);
2047                         break;
2048         }
2049 }
2050
2051 /* ------------------------------- */
2052
2053 /* create a new stroke point at the point indicated by the painting context */
2054 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p)
2055 {
2056         /* handle drawing/erasing -> test for erasing first */
2057         if (p->paintmode == GP_PAINTMODE_ERASER) {
2058                 /* do 'live' erasing now */
2059                 gp_stroke_doeraser(p);
2060                 
2061                 /* store used values */
2062                 p->mvalo[0] = p->mval[0];
2063                 p->mvalo[1] = p->mval[1];
2064                 p->opressure = p->pressure;
2065         }
2066         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2067         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2068                 /* try to add point */
2069                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2070                 
2071                 /* handle errors while adding point */
2072                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2073                         /* finish off old stroke */
2074                         gp_paint_strokeend(p);
2075                         /* And start a new one!!! Else, projection errors! */
2076                         gp_paint_initstroke(p, p->paintmode);
2077                         
2078                         /* start a new stroke, starting from previous point */
2079                         /* XXX Must manually reset inittime... */
2080                         /* XXX We only need to reuse previous point if overflow! */
2081                         if (ok == GP_STROKEADD_OVERFLOW) {
2082                                 p->inittime = p->ocurtime;
2083                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2084                         }
2085                         else {
2086                                 p->inittime = p->curtime;
2087                         }
2088                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2089                 }
2090                 else if (ok == GP_STROKEADD_INVALID) {
2091                         /* the painting operation cannot continue... */
2092                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2093                         p->status = GP_STATUS_ERROR;
2094                         
2095                         if (G.debug & G_DEBUG)
2096                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2097                         return;
2098                 }
2099                 
2100                 /* store used values */
2101                 p->mvalo[0] = p->mval[0];
2102                 p->mvalo[1] = p->mval[1];
2103                 p->opressure = p->pressure;
2104                 p->ocurtime = p->curtime;
2105         }
2106 }
2107
2108 /* handle draw event */
2109 static void gpencil_draw_apply_event(wmOperator *op, const wmEvent *event)
2110 {
2111         tGPsdata *p = op->customdata;
2112         PointerRNA itemptr;
2113         float mousef[2];
2114         int tablet = 0;
2115         
2116         /* convert from window-space to area-space mouse coordinates
2117          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
2118          */
2119         p->mval[0] = event->mval[0] + 1;
2120         p->mval[1] = event->mval[1] + 1;
2121         
2122         /* verify key status for straight lines */
2123         if ((event->ctrl > 0) || (event->alt > 0)) {
2124                 if (p->straight[0] == 0) {
2125                         int dx = abs(p->mval[0] - p->mvalo[0]);
2126                         int dy = abs(p->mval[1] - p->mvalo[1]);
2127                         if ((dx > 0) || (dy > 0)) {
2128                                 /* check mouse direction to replace the other coordinate with previous values */
2129                                 if (dx >= dy) {
2130                                         /* horizontal */
2131                                         p->straight[0] = 1;
2132                                         p->straight[1] = p->mval[1]; /* save y */
2133                                 }
2134                                 else {
2135                                         /* vertical */
2136                                         p->straight[0] = 2;
2137                                         p->straight[1] = p->mval[0]; /* save x */
2138                                 }
2139                         }
2140                 }
2141         }
2142         else {
2143                 p->straight[0] = 0;
2144         }
2145
2146         p->curtime = PIL_check_seconds_timer();
2147         
2148         /* handle pressure sensitivity (which is supplied by tablets) */
2149         if (event->tablet_data) {
2150                 const wmTabletData *wmtab = event->tablet_data;
2151                 
2152                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2153                 p->pressure = wmtab->Pressure;
2154                 
2155                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2156                  *  The pen has to float over the tablet surface, resulting in
2157                  *  zero pressure (T47101). Ignore pressure values if floating
2158                  *  (i.e. "effectively zero" pressure), and only when the "active"
2159                  *  end is the stylus (i.e. the default when not eraser)
2160                  */
2161                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2162                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2163                                 p->pressure = 1.0f;
2164                         }
2165                 }
2166         }
2167         else {
2168                 /* No tablet data -> No pressure info is available */
2169                 p->pressure = 1.0f;
2170         }
2171         
2172         /* special exception for start of strokes (i.e. maybe for just a dot) */
2173         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2174                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2175                 
2176                 p->mvalo[0] = p->mval[0];
2177                 p->mvalo[1] = p->mval[1];
2178                 p->opressure = p->pressure;
2179                 p->inittime = p->ocurtime = p->curtime;
2180                 p->straight[0] = 0;
2181                 p->straight[1] = 0;
2182
2183                 /* special exception here for too high pressure values on first touch in
2184                  *  windows for some tablets, then we just skip first touch...
2185                  */
2186                 if (tablet && (p->pressure >= 0.99f))
2187                         return;
2188         }
2189         
2190         /* check if alt key is pressed and limit to straight lines */
2191         if (p->straight[0] != 0) {
2192                 if (p->straight[0] == 1) {
2193                         /* horizontal */
2194                         p->mval[1] = p->straight[1]; /* replace y */
2195                 }
2196                 else {
2197                         /* vertical */
2198                         p->mval[0] = p->straight[1]; /* replace x */
2199                 }
2200         }
2201
2202         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2203         RNA_collection_add(op->ptr, "stroke", &itemptr);
2204         
2205         mousef[0] = p->mval[0];
2206         mousef[1] = p->mval[1];
2207         RNA_float_set_array(&itemptr, "mouse", mousef);
2208         RNA_float_set(&itemptr, "pressure", p->pressure);
2209         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2210         
2211         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2212         
2213         /* apply the current latest drawing point */
2214         gpencil_draw_apply(op, p);
2215         
2216         /* force refresh */
2217         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2218 }
2219
2220 /* ------------------------------- */
2221
2222 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2223 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2224 {
2225         tGPsdata *p = NULL;
2226         
2227         /* printf("GPencil - Starting Re-Drawing\n"); */
2228         
2229         /* try to initialize context data needed while drawing */
2230         if (!gpencil_draw_init(C, op, NULL)) {
2231                 if (op->customdata) MEM_freeN(op->customdata);
2232                 /* printf("\tGP - no valid data\n"); */
2233                 return OPERATOR_CANCELLED;
2234         }
2235         else
2236                 p = op->customdata;
2237         
2238         /* printf("\tGP - Start redrawing stroke\n"); */
2239         
2240         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
2241          * setting the relevant values in context at each step, then applying
2242          */
2243         RNA_BEGIN (op->ptr, itemptr, "stroke")
2244         {
2245                 float mousef[2];
2246                 
2247                 /* printf("\t\tGP - stroke elem\n"); */
2248                 
2249                 /* get relevant data for this point from stroke */
2250                 RNA_float_get_array(&itemptr, "mouse", mousef);
2251                 p->mval[0] = (int)mousef[0];
2252                 p->mval[1] = (int)mousef[1];
2253                 p->pressure = RNA_float_get(&itemptr, "pressure");
2254                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
2255                 
2256                 if (RNA_boolean_get(&itemptr, "is_start")) {
2257                         /* if first-run flag isn't set already (i.e. not true first stroke),
2258                          * then we must terminate the previous one first before continuing
2259                          */
2260                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
2261                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
2262                                 gp_paint_strokeend(p);
2263                                 gp_paint_initstroke(p, p->paintmode);
2264                         }
2265                 }
2266                 
2267                 /* if first run, set previous data too */
2268                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2269                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2270                         
2271                         p->mvalo[0] = p->mval[0];
2272                         p->mvalo[1] = p->mval[1];
2273                         p->opressure = p->pressure;
2274                         p->ocurtime = p->curtime;
2275                 }
2276                 
2277                 /* apply this data as necessary now (as per usual) */
2278                 gpencil_draw_apply(op, p);
2279         }
2280         RNA_END;
2281                 
2282         /* printf("\tGP - done\n"); */
2283         
2284         /* cleanup */
2285         gpencil_draw_exit(C, op);
2286         
2287         /* refreshes */
2288         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2289         
2290         /* done */
2291         return OPERATOR_FINISHED;
2292 }
2293
2294 /* ------------------------------- */
2295
2296 /* start of interactive drawing part of operator */
2297 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2298 {
2299         tGPsdata *p = NULL;
2300         
2301         if (G.debug & G_DEBUG)
2302                 printf("GPencil - Starting Drawing\n");
2303         
2304         /* try to initialize context data needed while drawing */
2305         if (!gpencil_draw_init(C, op, event)) {
2306                 if (op->customdata)
2307                         MEM_freeN(op->customdata);
2308                 if (G.debug & G_DEBUG)
2309                         printf("\tGP - no valid data\n");
2310                 return OPERATOR_CANCELLED;
2311         }
2312         else
2313                 p = op->customdata;
2314         
2315         /* TODO: set any additional settings that we can take from the events?
2316          * TODO? if tablet is erasing, force eraser to be on? */
2317         
2318         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
2319         
2320         /* if eraser is on, draw radial aid */
2321         if (p->paintmode == GP_PAINTMODE_ERASER) {
2322                 gpencil_draw_toggle_eraser_cursor(C, p, true);
2323         }
2324         /* set cursor 
2325          * NOTE: This may change later (i.e. intentionally via brush toggle,
2326          *       or unintentionally if the user scrolls outside the area)...
2327          */
2328         gpencil_draw_cursor_set(p);
2329
2330         /* only start drawing immediately if we're allowed to do so... */
2331         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
2332                 /* hotkey invoked - start drawing */
2333                 /* printf("\tGP - set first spot\n"); */
2334                 p->status = GP_STATUS_PAINTING;
2335
2336                 /* handle the initial drawing - i.e. for just doing a simple dot */
2337                 gpencil_draw_apply_event(op, event);
2338                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2339         }
2340         else {
2341                 /* toolbar invoked - don't start drawing yet... */
2342                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
2343                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2344         }
2345         
2346         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2347         /* add a modal handler for this operator, so that we can then draw continuous strokes */
2348         WM_event_add_modal_handler(C, op);
2349         return OPERATOR_RUNNING_MODAL;
2350 }
2351
2352 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2353 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
2354 {
2355         bScreen *sc = CTX_wm_screen(C);
2356         return (BLI_findindex(&sc->areabase, sa_test) != -1);
2357 }
2358
2359 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
2360 {
2361         tGPsdata *p = op->customdata;
2362         
2363         /* we must check that we're still within the area that we're set up to work from
2364          * otherwise we could crash (see bug #20586)
2365          */
2366         if (CTX_wm_area(C) != p->sa) {
2367                 printf("\t\t\tGP - wrong area execution abort!\n");
2368                 p->status = GP_STATUS_ERROR;
2369         }
2370         
2371         /* printf("\t\tGP - start stroke\n"); */
2372         
2373         /* we may need to set up paint env again if we're resuming */
2374         /* XXX: watch it with the paintmode! in future,
2375          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
2376         
2377         if (gp_session_initdata(C, p))
2378                 gp_paint_initstroke(p, p->paintmode);
2379         
2380         if (p->status != GP_STATUS_ERROR) {
2381                 p->status = GP_STATUS_PAINTING;
2382                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
2383         }
2384         
2385         return op->customdata;
2386 }
2387
2388 static void gpencil_stroke_end(wmOperator *op)
2389 {
2390         tGPsdata *p = op->customdata;
2391         
2392         gp_paint_cleanup(p);
2393         
2394         gpencil_undo_push(p->gpd);
2395         
2396         gp_session_cleanup(p);
2397         
2398         p->status = GP_STATUS_IDLING;
2399         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2400         
2401         p->gpd = NULL;
2402         p->gpl = NULL;
2403         p->gpf = NULL;
2404 }
2405
2406 /* Move last stroke in the listbase to the head to be drawn below all previous strokes in the layer */
2407 static void gpencil_move_last_stroke_to_back(bContext *C)
2408 {
2409         /* move last stroke (the polygon) to head of the listbase stroke to draw on back of all previous strokes */
2410         bGPdata *gpd = ED_gpencil_data_get_active(C);
2411         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
2412
2413         /* sanity checks */
2414         if (ELEM(NULL, gpd, gpl, gpl->actframe)) {
2415                 return;
2416         }
2417
2418         bGPDframe *gpf = gpl->actframe;
2419         bGPDstroke *gps = gpf->strokes.last;
2420         if (ELEM(NULL, gps)) {
2421                 return;
2422         }
2423
2424         BLI_remlink(&gpf->strokes, gps);
2425         BLI_insertlinkbefore(&gpf->strokes, gpf->strokes.first, gps);
2426 }
2427
2428 /* events handling during interactive drawing part of operator */
2429 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2430 {
2431         tGPsdata *p = op->customdata;
2432         ToolSettings *ts = CTX_data_tool_settings(C);
2433         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2434         
2435         /* if (event->type == NDOF_MOTION)
2436          *    return OPERATOR_PASS_THROUGH;
2437          * -------------------------------
2438          * [mce] Not quite what I was looking
2439          * for, but a good start! GP continues to
2440          * draw on the screen while the 3D mouse
2441          * moves the viewpoint. Problem is that
2442          * the stroke is converted to 3D only after
2443          * it is finished. This approach should work
2444          * better in tools that immediately apply
2445          * in 3D space.
2446          */
2447         
2448         if (p->status == GP_STATUS_IDLING) {
2449                 ARegion *ar = CTX_wm_region(C);
2450                 p->ar = ar;
2451         }
2452
2453         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2454         if (ISKEYBOARD(event->type)) {
2455                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2456                         /* allow some keys:
2457                          *   - for frame changing [#33412]
2458                          *   - for undo (during sketching sessions)
2459                          */
2460                 }
2461                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2462                         /* allow numpad keys so that camera/view manipulations can still take place
2463                          * - PAD0 in particular is really important for Grease Pencil drawing,
2464                          *   as animators may be working "to camera", so having this working
2465                          *   is essential for ensuring that they can quickly return to that view
2466                          */
2467                 }
2468                 else if ((ELEM(event->type, p->keymodifier)) && (event->val == KM_RELEASE)) {
2469                         /* enable continuous if release D key in mid drawing */
2470                         p->scene->toolsettings->gpencil_flags |= GP_TOOL_FLAG_PAINTSESSIONS_ON;
2471                 }
2472                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2473                         /* Add Blank Frame
2474                          * - Since this operator is non-modal, we can just call it here, and keep going...
2475                  * - This operator is especially useful when animating
2476                          */
2477                         WM_operator_name_call(C, "GPENCIL_OT_blank_frame_add", WM_OP_EXEC_DEFAULT, NULL);
2478                         estate = OPERATOR_RUNNING_MODAL;
2479                 }
2480                 else {
2481                         estate = OPERATOR_RUNNING_MODAL;
2482                 }
2483         }
2484         
2485         //printf("\tGP - handle modal event...\n");
2486         
2487         /* exit painting mode (and/or end current stroke)
2488          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
2489          */
2490         if (ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, EKEY)) {
2491                 /* exit() ends the current stroke before cleaning up */
2492                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
2493                 /* if drawing polygon and enable on back, must move stroke */
2494                 if (ts) {
2495                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2496                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2497                                         gpencil_move_last_stroke_to_back(C);
2498                                 }
2499                         }
2500                 }
2501                 p->status = GP_STATUS_DONE;
2502                 estate = OPERATOR_FINISHED;
2503         }
2504         
2505         /* toggle painting mode upon mouse-button movement
2506          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
2507          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
2508          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
2509          * also making sure we have a valid event value, to not exit too early
2510          */
2511         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE) && (event->val != KM_NOTHING)) {
2512                 /* if painting, end stroke */
2513                 if (p->status == GP_STATUS_PAINTING) {
2514                         int sketch = 0;
2515                         
2516                         /* basically, this should be mouse-button up = end stroke
2517                          * BUT what happens next depends on whether we 'painting sessions' is enabled
2518                          */
2519                         sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
2520                         /* polyline drawing is also 'sketching' -- all knots should be added during one session */
2521                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
2522                         
2523                         if (sketch) {
2524                                 /* end stroke only, and then wait to resume painting soon */
2525                                 /* printf("\t\tGP - end stroke only\n"); */
2526                                 gpencil_stroke_end(op);
2527                                 
2528                                 /* If eraser mode is on, turn it off after the stroke finishes
2529                                  * NOTE: This just makes it nicer to work with drawing sessions
2530                                  */
2531                                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2532                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2533                                         
2534                                         /* if the original mode was *still* eraser,
2535                                          * we'll let it say for now, since this gives
2536                                          * users an opportunity to have visual feedback
2537                                          * when adjusting eraser size
2538                                          */
2539                                         if (p->paintmode != GP_PAINTMODE_ERASER) {      
2540                                                 /* turn off cursor...
2541                                                  * NOTE: this should be enough for now
2542                                                  *       Just hiding this makes it seem like
2543                                                  *       you can paint again...
2544                                                  */
2545                                                 gpencil_draw_toggle_eraser_cursor(C, p, false);
2546                                         }
2547                                 }
2548                                 
2549                                 /* we've just entered idling state, so this event was processed (but no others yet) */
2550                                 estate = OPERATOR_RUNNING_MODAL;
2551                                 
2552                                 /* stroke could be smoothed, send notifier to refresh screen */
2553                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2554                         }
2555                         else {
2556                                 /* printf("\t\tGP - end of stroke + op\n"); */
2557                                 /* if drawing polygon and enable on back, must move stroke */
2558                                 if (ts) {
2559                                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2560                                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2561                                                         gpencil_move_last_stroke_to_back(C);
2562                                                 }
2563                                         }
2564                                 }
2565                                 p->status = GP_STATUS_DONE;
2566                                 estate = OPERATOR_FINISHED;
2567                         }
2568                 }
2569                 else if (event->val == KM_PRESS) {
2570                         bool in_bounds = false;
2571                         
2572                         /* Check if we're outside the bounds of the active region
2573                          * NOTE: An exception here is that if launched from the toolbar,
2574                          *       whatever region we're now in should become the new region
2575                          */
2576                         if ((p->ar) && (p->ar->regiontype == RGN_TYPE_TOOLS)) {
2577                                 /* Change to whatever region is now under the mouse */
2578                                 ARegion *current_region = BKE_area_find_region_xy(p->sa, RGN_TYPE_ANY, event->x, event->y);
2579                                 
2580                                 if (G.debug & G_DEBUG) {
2581                                         printf("found alternative region %p (old was %p) - at %d %d (sa: %d %d -> %d %d)\n",
2582                                                 current_region, p->ar, event->x, event->y,
2583                                                 p->sa->totrct.xmin, p->sa->totrct.ymin, p->sa->totrct.xmax, p->sa->totrct.ymax);
2584                                 }
2585                                 
2586                                 if (current_region) {
2587                                         /* Assume that since we found the cursor in here, it is in bounds
2588                                          * and that this should be the region that we begin drawing in
2589                                          */
2590                                         p->ar = current_region;
2591                                         in_bounds = true;
2592                                 }
2593                                 else {
2594                                         /* Out of bounds, or invalid in some other way */
2595                                         p->status = GP_STATUS_ERROR;
2596                                         estate = OPERATOR_CANCELLED;
2597                                         
2598                                         if (G.debug & G_DEBUG)
2599                                                 printf("%s: Region under cursor is out of bounds, so cannot be drawn on\n", __func__);
2600                                 }
2601                         }
2602                         else if (p->ar) {
2603                                 rcti region_rect;
2604                                 
2605                                 /* Perform bounds check using  */
2606                                 ED_region_visible_rect(p->ar, &region_rect);
2607                                 in_bounds = BLI_rcti_isect_pt_v(&region_rect, event->mval);
2608                         }
2609                         else {
2610                                 /* No region */
2611                                 p->status = GP_STATUS_ERROR;
2612                                 estate = OPERATOR_CANCELLED;
2613                                 
2614                                 if (G.debug & G_DEBUG)
2615                                         printf("%s: No active region found in GP Paint session data\n", __func__);
2616                         }
2617                         
2618                         if (in_bounds) {
2619                                 /* Switch paintmode (temporarily if need be) based on which button was used
2620                                  * NOTE: This is to make it more convenient to erase strokes when using drawing sessions
2621                                  */
2622                                 if ((event->type == RIGHTMOUSE) || gpencil_is_tablet_eraser_active(event)) {
2623                                         /* turn on eraser */
2624                                         p->paintmode = GP_PAINTMODE_ERASER;
2625                                 }
2626                                 else if (event->type == LEFTMOUSE) {
2627                                         /* restore drawmode to default */
2628                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2629                                 }
2630                                 
2631                                 gpencil_draw_toggle_eraser_cursor(C, p, p->paintmode == GP_PAINTMODE_ERASER);
2632                                 
2633                                 /* not painting, so start stroke (this should be mouse-button down) */
2634                                 p = gpencil_stroke_begin(C, op);
2635                                 
2636                                 if (p->status == GP_STATUS_ERROR) {
2637                                         estate = OPERATOR_CANCELLED;
2638                                 }
2639                         }
2640                         else if (p->status != GP_STATUS_ERROR) {
2641                                 /* User clicked outside bounds of window while idling, so exit paintmode 
2642                                  * NOTE: Don't enter this case if an error occurred while finding the
2643                                  *       region (as above)
2644                                  */
2645                                 /* if drawing polygon and enable on back, must move stroke */
2646                                 if (ts) {
2647                                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2648                                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2649                                                         gpencil_move_last_stroke_to_back(C);
2650                                                 }
2651                                         }
2652                                 }
2653                                 p->status = GP_STATUS_DONE;
2654                                 estate = OPERATOR_FINISHED;
2655                         }
2656                 }
2657                 else {
2658                         p->status = GP_STATUS_IDLING;
2659                         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2660                 }
2661         }
2662         
2663         /* handle mode-specific events */
2664         if (p->status == GP_STATUS_PAINTING) {
2665                 /* handle painting mouse-movements? */
2666                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
2667                         /* handle drawing event */
2668                         /* printf("\t\tGP - add point\n"); */
2669                         gpencil_draw_apply_event(op, event);
2670                         
2671                         /* finish painting operation if anything went wrong just now */
2672                         if (p->status == GP_STATUS_ERROR) {
2673                                 printf("\t\t\t\tGP - add error done!\n");
2674                                 estate = OPERATOR_CANCELLED;
2675                         }
2676                         else {
2677                                 /* event handled, so just tag as running modal */
2678                                 /* printf("\t\t\t\tGP - add point handled!\n"); */
2679                                 estate = OPERATOR_RUNNING_MODAL;
2680                         }
2681                 }
2682                 /* eraser size */
2683                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
2684                          ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
2685                 {
2686                         /* just resize the brush (local version)
2687                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
2688                          */
2689                         /* printf("\t\tGP - resize eraser\n"); */
2690                         switch (event->type) {
2691                                 case WHEELDOWNMOUSE: /* larger */
2692                                 case PADPLUSKEY:
2693                                         p->radius += 5;
2694                                         break;
2695                                 
2696                                 case WHEELUPMOUSE: /* smaller */
2697                                 case PADMINUS:
2698                                         p->radius -= 5;
2699                                         
2700                                         if (p->radius <= 0)
2701                                                 p->radius = 1;
2702                                         break;
2703                         }
2704                         
2705                         /* force refresh */
2706                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2707                         
2708                         /* event handled, so just tag as running modal */
2709                         estate = OPERATOR_RUNNING_MODAL;
2710                 }
2711                 /* there shouldn't be any other events, but just in case there are, let's swallow them
2712                  * (i.e. to prevent problems with undo)
2713                  */
2714                 else {
2715                         /* swallow event to save ourselves trouble */
2716                         estate = OPERATOR_RUNNING_MODAL;
2717                 }
2718         }
2719         
2720         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2721         if (0 == gpencil_area_exists(C, p->sa))
2722                 estate = OPERATOR_CANCELLED;
2723         else {
2724                 /* update status indicators - cursor, header, etc. */
2725                 gpencil_draw_status_indicators(p);
2726                 gpencil_draw_cursor_set(p); /* cursor may have changed outside our control - T44084 */
2727         }
2728         
2729         /* process last operations before exiting */
2730         switch (estate) {
2731                 case OPERATOR_FINISHED:
2732                         /* one last flush before we're done */
2733                         gpencil_draw_exit(C, op);
2734                         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2735                         break;
2736                 
2737                 case OPERATOR_CANCELLED:
2738                         gpencil_draw_exit(C, op);
2739                         break;
2740                 
2741                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
2742                         /* event doesn't need to be handled */
2743 #if 0
2744                         printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
2745                                event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
2746 #endif
2747                         break;
2748         }
2749         
2750         /* return status code */
2751         return estate;
2752 }
2753
2754 /* ------------------------------- */
2755
2756 static EnumPropertyItem prop_gpencil_drawmodes[] = {
2757         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
2758         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
2759         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
2760         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Grease Pencil strokes"},
2761         {0, NULL, 0, NULL, NULL}
2762 };
2763
2764 void GPENCIL_OT_draw(wmOperatorType *ot)
2765 {
2766         /* identifiers */
2767         ot->name = "Grease Pencil Draw";
2768         ot->idname = "GPENCIL_OT_draw";
2769         ot->description = "Make annotations on the active data";
2770         
2771         /* api callbacks */
2772         ot->exec = gpencil_draw_exec;
2773         ot->invoke = gpencil_draw_invoke;
2774         ot->modal = gpencil_draw_modal;
2775         ot->cancel = gpencil_draw_cancel;
2776         ot->poll = gpencil_draw_poll;
2777         
2778         /* flags */
2779         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2780         
2781         /* settings for drawing */
2782         ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
2783         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2784         
2785         /* NOTE: wait for input is enabled by default, so that all UI code can work properly without needing users to know about this */
2786         RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
2787 }