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