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