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