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