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