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