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