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