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