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