style cleanup, brackets in else/if, some indentation.
[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                 Object *ob= (Object *)p->ownerPtr.data;
199                 
200                 /* active Object 
201                  *      - use relative distance of 3D-cursor from object center 
202                  */
203                 sub_v3_v3v3(vec, fp, ob->loc);
204         }
205         else
206 #endif  
207         {
208                 /* use 3D-cursor */
209                 copy_v3_v3(vec, fp);
210         }
211 }
212
213 /* Stroke Editing ---------------------------- */
214
215 /* check if the current mouse position is suitable for adding a new point */
216 static short gp_stroke_filtermval (tGPsdata *p, const int mval[2], int pmval[2])
217 {
218         int dx= abs(mval[0] - pmval[0]);
219         int dy= abs(mval[1] - pmval[1]);
220         
221         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
222         if (p->gpd->sbuffer_size == 0)
223                 return 1;
224         
225         /* check if mouse moved at least certain distance on both axes (best case) 
226          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
227          */
228         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
229                 return 1;
230         
231         /* check if the distance since the last point is significant enough 
232          *      - prevents points being added too densely
233          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
234          */
235         else if ((dx*dx + dy*dy) > MIN_EUCLIDEAN_PX*MIN_EUCLIDEAN_PX)
236                 return 1;
237         
238         /* mouse 'didn't move' */
239         else
240                 return 0;
241 }
242
243 /* convert screen-coordinates to buffer-coordinates */
244 // XXX this method needs a total overhaul!
245 static void gp_stroke_convertcoords (tGPsdata *p, const int mval[2], float out[3], float *depth)
246 {
247         bGPdata *gpd= p->gpd;
248         
249         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
250         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
251                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
252                         /* projecting onto 3D-Geometry
253                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
254                          */
255                 }
256                 else {
257                         int mval_prj[2];
258                         float rvec[3], dvec[3];
259                         float mval_f[2];
260
261                         /* Current method just converts each point in screen-coordinates to
262                          * 3D-coordinates using the 3D-cursor as reference. In general, this
263                          * works OK, but it could of course be improved.
264                          *
265                          * TODO:
266                          *      - investigate using nearest point(s) on a previous stroke as
267                          *        reference point instead or as offset, for easier stroke matching
268                          */
269                         
270                         gp_get_3d_reference(p, rvec);
271                         
272                         /* method taken from editview.c - mouse_cursor() */
273                         project_int_noclip(p->ar, rvec, mval_prj);
274
275                         VECSUB2D(mval_f, mval_prj, mval);
276                         ED_view3d_win_to_delta(p->ar, mval_f, dvec);
277                         sub_v3_v3v3(out, rvec, dvec);
278                 }
279         }
280         
281         /* 2d - on 'canvas' (assume that p->v2d is set) */
282         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
283                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
284                 mul_v3_m4v3(out, p->imat, out);
285         }
286         
287 #if 0
288         /* 2d - on image 'canvas' (assume that p->v2d is set) */
289         else if (gpd->sbuffer_sflag & GP_STROKE_2DIMAGE) {
290                 int sizex, sizey, offsx, offsy;
291                 
292                 /* get stored settings 
293                  *      - assume that these have been set already (there are checks that set sane 'defaults' just in case)
294                  */
295                 sizex= p->im2d_settings.sizex;
296                 sizey= p->im2d_settings.sizey;
297                 offsx= p->im2d_settings.offsx;
298                 offsy= p->im2d_settings.offsy;
299                 
300                 /* calculate new points */
301                 out[0]= (float)(mval[0] - offsx) / (float)sizex;
302                 out[1]= (float)(mval[1] - offsy) / (float)sizey;
303         }
304 #endif
305         
306         /* 2d - relative to screen (viewport area) */
307         else {
308                 if (p->subrect == NULL) { /* normal 3D view */
309                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
310                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
311                 }
312                 else { /* camera view, use subrect */
313                         out[0]= ((mval[0] - p->subrect->xmin) / ((p->subrect->xmax - p->subrect->xmin))) * 100;
314                         out[1]= ((mval[1] - p->subrect->ymin) / ((p->subrect->ymax - p->subrect->ymin))) * 100;
315                 }
316         }
317 }
318
319 /* add current stroke-point to buffer (returns whether point was successfully added) */
320 static short gp_stroke_addpoint (tGPsdata *p, const int mval[2], float pressure)
321 {
322         bGPdata *gpd= p->gpd;
323         tGPspoint *pt;
324         
325         /* check painting mode */
326         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
327                 /* straight lines only - i.e. only store start and end point in buffer */
328                 if (gpd->sbuffer_size == 0) {
329                         /* first point in buffer (start point) */
330                         pt= (tGPspoint *)(gpd->sbuffer);
331                         
332                         /* store settings */
333                         copy_v2_v2_int(&pt->x, mval);
334                         pt->pressure= pressure;
335                         
336                         /* increment buffer size */
337                         gpd->sbuffer_size++;
338                 }
339                 else {
340                         /* normally, we just reset the endpoint to the latest value 
341                          *      - assume that pointers for this are always valid...
342                          */
343                         pt= ((tGPspoint *)(gpd->sbuffer) + 1);
344                         
345                         /* store settings */
346                         copy_v2_v2_int(&pt->x, mval);
347                         pt->pressure= pressure;
348                         
349                         /* if this is just the second point we've added, increment the buffer size
350                          * so that it will be drawn properly...
351                          * otherwise, just leave it alone, otherwise we get problems
352                          */
353                         if (gpd->sbuffer_size != 2)
354                                 gpd->sbuffer_size= 2;
355                 }
356                 
357                 /* can keep carrying on this way :) */
358                 return GP_STROKEADD_NORMAL;
359         }
360         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
361                 /* check if still room in buffer */
362                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
363                         return GP_STROKEADD_OVERFLOW;
364                 
365                 /* get pointer to destination point */
366                 pt= ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
367                 
368                 /* store settings */
369                 copy_v2_v2_int(&pt->x, mval);
370                 pt->pressure= pressure;
371                 
372                 /* increment counters */
373                 gpd->sbuffer_size++;
374                 
375                 /* check if another operation can still occur */
376                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
377                         return GP_STROKEADD_FULL;
378                 else
379                         return GP_STROKEADD_NORMAL;
380         }
381         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
382                 /* get pointer to destination point */
383                 pt= (tGPspoint *)(gpd->sbuffer);
384
385                 /* store settings */
386                 copy_v2_v2_int(&pt->x, mval);
387                 pt->pressure= pressure;
388
389                 /* if there's stroke for this poly line session add (or replace last) point
390                  * to stroke. This allows to draw lines more interactively (see new segment
391                  * during mouse slide, i.e.) 
392                  */
393                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
394                         bGPDstroke *gps= p->gpf->strokes.last;
395                         bGPDspoint *pts;
396
397                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
398                         if (gpd->sbuffer_size == 0) {
399                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint)*(gps->totpoints+1));
400                                 gps->totpoints++;
401                         }
402
403                         pts = &gps->points[gps->totpoints-1];
404
405                         /* special case for poly lines: normally, depth is needed only when creating new stroke from buffer,
406                          * but poly lines are converting to stroke instantly, so initialize depth buffer before converting coordinates 
407                          */
408                         if (gpencil_project_check(p)) {
409                                 View3D *v3d= p->sa->spacedata.first;
410
411                                 view3d_region_operator_needs_opengl(p->win, p->ar);
412                                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1:0);
413                         }
414
415                         /* convert screen-coordinates to appropriate coordinates (and store them) */
416                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
417
418                         /* copy pressure */
419                         pts->pressure= pt->pressure;
420                 }
421
422                 /* increment counters */
423                 if (gpd->sbuffer_size == 0)
424                         gpd->sbuffer_size++;
425
426                 return GP_STROKEADD_NORMAL;
427         }
428         
429         /* return invalid state for now... */
430         return GP_STROKEADD_INVALID;
431 }
432
433
434 /* temp struct for gp_stroke_smooth() */
435 typedef struct tGpSmoothCo {
436         int x;
437         int y;
438 } tGpSmoothCo;
439
440 /* smooth a stroke (in buffer) before storing it */
441 static void gp_stroke_smooth (tGPsdata *p)
442 {
443         bGPdata *gpd= p->gpd;
444         tGpSmoothCo *smoothArray, *spc;
445         int i=0, cmx=gpd->sbuffer_size;
446         
447         /* only smooth if smoothing is enabled, and we're not doing a straight line */
448         if (!(U.gp_settings & GP_PAINT_DOSMOOTH) || ELEM(p->paintmode, GP_PAINTMODE_DRAW_STRAIGHT, GP_PAINTMODE_DRAW_POLY))
449                 return;
450         
451         /* don't try if less than 2 points in buffer */
452         if ((cmx <= 2) || (gpd->sbuffer == NULL))
453                 return;
454         
455         /* create a temporary smoothing coordinates buffer, use to store calculated values to prevent sequential error */
456         smoothArray = MEM_callocN(sizeof(tGpSmoothCo)*cmx, "gp_stroke_smooth smoothArray");
457         
458         /* first pass: calculate smoothing coordinates using weighted-averages */
459         for (i=0, spc=smoothArray; i < gpd->sbuffer_size; i++, spc++) {
460                 const tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
461                 const tGPspoint *pb= (i-1 > 0)?(pc-1):(pc);
462                 const tGPspoint *pa= (i-2 > 0)?(pc-2):(pb);
463                 const tGPspoint *pd= (i+1 < cmx)?(pc+1):(pc);
464                 const tGPspoint *pe= (i+2 < cmx)?(pc+2):(pd);
465                 
466                 spc->x= (int)(0.1*pa->x + 0.2*pb->x + 0.4*pc->x + 0.2*pd->x + 0.1*pe->x);
467                 spc->y= (int)(0.1*pa->y + 0.2*pb->y + 0.4*pc->y + 0.2*pd->y + 0.1*pe->y);
468         }
469         
470         /* second pass: apply smoothed coordinates */
471         for (i=0, spc=smoothArray; i < gpd->sbuffer_size; i++, spc++) {
472                 tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
473
474                 copy_v2_v2_int(&pc->x, &spc->x);
475         }
476         
477         /* free temp array */
478         MEM_freeN(smoothArray);
479 }
480
481 /* simplify a stroke (in buffer) before storing it 
482  *      - applies a reverse Chaikin filter
483  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
484  */
485 static void gp_stroke_simplify (tGPsdata *p)
486 {
487         bGPdata *gpd= p->gpd;
488         tGPspoint *old_points= (tGPspoint *)gpd->sbuffer;
489         short num_points= gpd->sbuffer_size;
490         short flag= gpd->sbuffer_sflag;
491         short i, j;
492         
493         /* only simplify if simplification is enabled, and we're not doing a straight line */
494         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
495                 return;
496         
497         /* don't simplify if less than 4 points in buffer */
498         if ((num_points <= 4) || (old_points == NULL))
499                 return;
500                 
501         /* clear buffer (but don't free mem yet) so that we can write to it 
502          *      - firstly set sbuffer to NULL, so a new one is allocated
503          *      - secondly, reset flag after, as it gets cleared auto
504          */
505         gpd->sbuffer= NULL;
506         gp_session_validatebuffer(p);
507         gpd->sbuffer_sflag = flag;
508         
509 /* macro used in loop to get position of new point
510  *      - used due to the mixture of datatypes in use here
511  */
512 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
513         { \
514                 co[0] += (float)(old_points[offs].x * sfac); \
515                 co[1] += (float)(old_points[offs].y * sfac); \
516                 pressure += old_points[offs].pressure * sfac; \
517         }
518         
519         for (i = 0, j = 0; i < num_points; i++) {
520                 if (i - j == 3) {
521                         float co[2], pressure;
522                         int mco[2];
523                         
524                         /* initialize 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 immediately 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                                 copy_v2_v2_int(mval, &ptc->x);
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                                 copy_v2_v2_int(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 behavior) */
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 optimization (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         unit_m4(p->imat);
1000         
1001         switch (curarea->spacetype) {
1002                 /* supported views first */
1003                 case SPACE_VIEW3D:
1004                 {
1005                         // View3D *v3d= curarea->spacedata.first;
1006                         // RegionView3D *rv3d= ar->regiondata;
1007                         
1008                         /* set current area 
1009                          *      - must verify that region data is 3D-view (and not something else)
1010                          */
1011                         p->sa= curarea;
1012                         p->ar= ar;
1013                         
1014                         if (ar->regiondata == NULL) {
1015                                 p->status= GP_STATUS_ERROR;
1016                                 if (G.f & G_DEBUG)
1017                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable \n");
1018                                 return 0;
1019                         }
1020
1021 #if 0 // XXX will this sort of antiquated stuff be restored?
1022                         /* check that gpencil data is allowed to be drawn */
1023                         if ((v3d->flag2 & V3D_DISPGP)==0) {
1024                                 p->status= GP_STATUS_ERROR;
1025                                 if (G.f & G_DEBUG) 
1026                                         printf("Error: In active view, Grease Pencil not shown \n");
1027                                 return 0;
1028                         }
1029 #endif
1030                 }
1031                         break;
1032
1033                 case SPACE_NODE:
1034                 {
1035                         //SpaceNode *snode= curarea->spacedata.first;
1036                         
1037                         /* set current area */
1038                         p->sa= curarea;
1039                         p->ar= ar;
1040                         p->v2d= &ar->v2d;
1041                         
1042 #if 0 // XXX will this sort of antiquated stuff be restored?
1043                         /* check that gpencil data is allowed to be drawn */
1044                         if ((snode->flag & SNODE_DISPGP)==0) {
1045                                 p->status= GP_STATUS_ERROR;
1046                                 if (G.f & G_DEBUG) 
1047                                         printf("Error: In active view, Grease Pencil not shown \n");
1048                                 return 0;
1049                         }
1050 #endif
1051                 }
1052                         break;
1053 #if 0 // XXX these other spaces will come over time...
1054                 case SPACE_SEQ:
1055                 {
1056                         SpaceSeq *sseq= curarea->spacedata.first;
1057                         
1058                         /* set current area */
1059                         p->sa= curarea;
1060                         p->ar= ar;
1061                         p->v2d= &ar->v2d;
1062                         
1063                         /* check that gpencil data is allowed to be drawn */
1064                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1065                                 p->status= GP_STATUS_ERROR;
1066                                 if (G.f & G_DEBUG) 
1067                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil \n");
1068                                 return 0;
1069                         }
1070                         if ((sseq->flag & SEQ_DRAW_GPENCIL)==0) {
1071                                 p->status= GP_STATUS_ERROR;
1072                                 if (G.f & G_DEBUG) 
1073                                         printf("Error: In active view, Grease Pencil not shown \n");
1074                                 return 0;
1075                         }
1076                 }
1077                         break;  
1078 #endif
1079                 case SPACE_IMAGE:
1080                 {
1081                         //SpaceImage *sima= curarea->spacedata.first;
1082                         
1083                         /* set the current area */
1084                         p->sa= curarea;
1085                         p->ar= ar;
1086                         p->v2d= &ar->v2d;
1087                         //p->ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1088                         
1089 #if 0 // XXX disabled for now
1090                         /* check that gpencil data is allowed to be drawn */
1091                         if ((sima->flag & SI_DISPGP)==0) {
1092                                 p->status= GP_STATUS_ERROR;
1093                                 if (G.f & G_DEBUG)
1094                                         printf("Error: In active view, Grease Pencil not shown \n");
1095                                 return 0;
1096                         }
1097 #endif
1098                 }
1099                         break;
1100                 case SPACE_CLIP:
1101                 {
1102                         SpaceClip *sc= curarea->spacedata.first;
1103
1104                         /* set the current area */
1105                         p->sa= curarea;
1106                         p->ar= ar;
1107                         p->v2d= &ar->v2d;
1108                         //p->ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
1109
1110                         invert_m4_m4(p->imat, sc->unistabmat);
1111
1112                         /* custom color for new layer */
1113                         p->custom_color[0]= 1.0f;
1114                         p->custom_color[1]= 0.0f;
1115                         p->custom_color[2]= 0.5f;
1116                         p->custom_color[3]= 0.9f;
1117                 }
1118                         break;
1119
1120                 /* unsupported views */
1121                 default:
1122                 {
1123                         p->status= GP_STATUS_ERROR;
1124                         if (G.f & G_DEBUG) 
1125                                 printf("Error: Active view not appropriate for Grease Pencil drawing \n");
1126                         return 0;
1127                 }
1128                         break;
1129         }
1130         
1131         /* get gp-data */
1132         gpd_ptr= gpencil_data_get_pointers(C, &p->ownerPtr);
1133         if (gpd_ptr == NULL) {
1134                 p->status= GP_STATUS_ERROR;
1135                 if (G.f & G_DEBUG)
1136                         printf("Error: Current context doesn't allow for any Grease Pencil data \n");
1137                 return 0;
1138         }
1139         else {
1140                 /* if no existing GPencil block exists, add one */
1141                 if (*gpd_ptr == NULL)
1142                         *gpd_ptr= gpencil_data_addnew("GPencil");
1143                 p->gpd= *gpd_ptr;
1144         }
1145         
1146         if (ED_gpencil_session_active()==0) {
1147                 /* initialize undo stack,
1148                  * also, existing undo stack would make buffer drawn */
1149                 gpencil_undo_init(p->gpd);
1150         }
1151         
1152         /* clear out buffer (stored in gp-data), in case something contaminated it */
1153         gp_session_validatebuffer(p);
1154         
1155 #if 0
1156         /* set 'default' im2d_settings just in case something that uses this doesn't set it */
1157         p->im2d_settings.sizex= 1;
1158         p->im2d_settings.sizey= 1;
1159 #endif
1160
1161         return 1;
1162 }
1163
1164 /* init new painting session */
1165 static tGPsdata *gp_session_initpaint (bContext *C)
1166 {
1167         tGPsdata *p = NULL;
1168
1169         /* create new context data */
1170         p= MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1171
1172         gp_session_initdata(C, p);
1173         
1174         /* return context data for running paint operator */
1175         return p;
1176 }
1177
1178 /* cleanup after a painting session */
1179 static void gp_session_cleanup (tGPsdata *p)
1180 {
1181         bGPdata *gpd= (p) ? p->gpd : NULL;
1182         
1183         /* error checking */
1184         if (gpd == NULL)
1185                 return;
1186         
1187         /* free stroke buffer */
1188         if (gpd->sbuffer) {
1189                 //printf("\t\tGP - free sbuffer\n");
1190                 MEM_freeN(gpd->sbuffer);
1191                 gpd->sbuffer= NULL;
1192         }
1193         
1194         /* clear flags */
1195         gpd->sbuffer_size= 0;
1196         gpd->sbuffer_sflag= 0;
1197 }
1198
1199 /* init new stroke */
1200 static void gp_paint_initstroke (tGPsdata *p, short paintmode)
1201 {       
1202         /* get active layer (or add a new one if non-existent) */
1203         p->gpl= gpencil_layer_getactive(p->gpd);
1204         if (p->gpl == NULL) {
1205                 p->gpl= gpencil_layer_addnew(p->gpd);
1206
1207                 if(p->custom_color[3])
1208                         copy_v3_v3(p->gpl->color, p->custom_color);
1209         }
1210         if (p->gpl->flag & GP_LAYER_LOCKED) {
1211                 p->status= GP_STATUS_ERROR;
1212                 if (G.f & G_DEBUG)
1213                         printf("Error: Cannot paint on locked layer \n");
1214                 return;
1215         }
1216                 
1217         /* get active frame (add a new one if not matching frame) */
1218         p->gpf= gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
1219         if (p->gpf == NULL) {
1220                 p->status= GP_STATUS_ERROR;
1221                 if (G.f & G_DEBUG) 
1222                         printf("Error: No frame created (gpencil_paint_init) \n");
1223                 return;
1224         }
1225         else
1226                 p->gpf->flag |= GP_FRAME_PAINT;
1227         
1228         /* set 'eraser' for this stroke if using eraser */
1229         p->paintmode= paintmode;
1230         if (p->paintmode == GP_PAINTMODE_ERASER)
1231                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1232                 
1233         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1234         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1235         
1236
1237         /* when drawing in the camera view, in 2D space, set the subrect */
1238         if (!(p->gpd->flag & GP_DATA_VIEWALIGN)) {
1239                 if (p->sa->spacetype == SPACE_VIEW3D) {
1240                         View3D *v3d= p->sa->spacedata.first;
1241                         RegionView3D *rv3d= p->ar->regiondata;
1242
1243                         /* for camera view set the subrect */
1244                         if (rv3d->persp == RV3D_CAMOB) {
1245                                 ED_view3d_calc_camera_border(p->scene, p->ar, v3d, rv3d, &p->subrect_data, TRUE); /* no shift */
1246                                 p->subrect= &p->subrect_data;
1247                         }
1248                 }
1249         }
1250
1251         /* check if points will need to be made in view-aligned space */
1252         if (p->gpd->flag & GP_DATA_VIEWALIGN) {
1253                 switch (p->sa->spacetype) {
1254                         case SPACE_VIEW3D:
1255                         {
1256                                 RegionView3D *rv3d= p->ar->regiondata;
1257                                 float rvec[3];
1258                                 
1259                                 /* get reference point for 3d space placement */
1260                                 gp_get_3d_reference(p, rvec);
1261                                 initgrabz(rv3d, rvec[0], rvec[1], rvec[2]);
1262                                 
1263                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1264                         }
1265                                 break;
1266                         
1267                         case SPACE_NODE:
1268                         {
1269                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1270                         }
1271                                 break;
1272 #if 0 // XXX other spacetypes to be restored in due course
1273                         case SPACE_SEQ:
1274                         {
1275                                 SpaceSeq *sseq= (SpaceSeq *)p->sa->spacedata.first;
1276                                 int rectx, recty;
1277                                 float zoom, zoomx, zoomy;
1278                                 
1279                                 /* set draw 2d-stroke flag */
1280                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DIMAGE;
1281                                 
1282                                 /* calculate zoom factor */
1283                                 zoom= (float)(SEQ_ZOOM_FAC(sseq->zoom));
1284                                 if (sseq->mainb == SEQ_DRAW_IMG_IMBUF) {
1285                                         zoomx = zoom * (p->scene->r.xasp / p->scene->r.yasp);
1286                                         zoomy = zoom;
1287                                 } 
1288                                 else
1289                                         zoomx = zoomy = zoom;
1290                                 
1291                                 /* calculate rect size to use to calculate the size of the drawing area
1292                                  *      - We use the size of the output image not the size of the ibuf being shown
1293                                  *        as it is too messy getting the ibuf (and could be too slow). This should be
1294                                  *        a reasonable for most cases anyway.
1295                                  */
1296                                 rectx= (p->scene->r.size * p->scene->r.xsch) / 100;
1297                                 recty= (p->scene->r.size * p->scene->r.ysch) / 100; 
1298                                 
1299                                 /* set offset and scale values for opertations to use */
1300                                 p->im2d_settings.sizex= (int)(zoomx * rectx);
1301                                 p->im2d_settings.sizey= (int)(zoomy * recty);
1302                                 p->im2d_settings.offsx= (int)((p->sa->winx-p->im2d_settings.sizex)/2 + sseq->xof);
1303                                 p->im2d_settings.offsy= (int)((p->sa->winy-p->im2d_settings.sizey)/2 + sseq->yof);
1304                         }
1305                                 break;
1306 #endif
1307                         case SPACE_IMAGE:
1308                         {
1309                                 SpaceImage *sima= (SpaceImage *)p->sa->spacedata.first;
1310                                 
1311                                 /* only set these flags if the image editor doesn't have an image active,
1312                                  * otherwise user will be confused by strokes not appearing after they're drawn
1313                                  *
1314                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1315                                  */
1316                                 if ELEM(NULL, sima, sima->image) {
1317                                         /* make strokes be drawn in screen space */
1318                                         p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1319                                         p->gpd->flag &= ~GP_DATA_VIEWALIGN;
1320                                 }       
1321                                 else
1322                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1323                         }
1324                                 break;
1325                                 
1326                         case SPACE_CLIP:
1327                         {
1328                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1329                         }
1330                                 break;
1331                 }
1332         }
1333 }
1334
1335 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1336 static void gp_paint_strokeend (tGPsdata *p)
1337 {
1338         /* for surface sketching, need to set the right OpenGL context stuff so that 
1339          * the conversions will project the values correctly...
1340          */
1341         if (gpencil_project_check(p)) {
1342                 View3D *v3d= p->sa->spacedata.first;
1343                 
1344                 /* need to restore the original projection settings before packing up */
1345                 view3d_region_operator_needs_opengl(p->win, p->ar);
1346                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1:0);
1347         }
1348         
1349         /* check if doing eraser or not */
1350         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1351                 /* smooth stroke before transferring? */
1352                 gp_stroke_smooth(p);
1353                 
1354                 /* simplify stroke before transferring? */
1355                 gp_stroke_simplify(p);
1356                 
1357                 /* transfer stroke to frame */
1358                 gp_stroke_newfrombuffer(p);
1359         }
1360         
1361         /* clean up buffer now */
1362         gp_session_validatebuffer(p);
1363 }
1364
1365 /* finish off stroke painting operation */
1366 static void gp_paint_cleanup (tGPsdata *p)
1367 {
1368         /* p->gpd==NULL happens when stroke failed to initialize,
1369          * for example. when GP is hidden in current space (sergey) */
1370         if (p->gpd) {
1371                 /* finish off a stroke */
1372                 gp_paint_strokeend(p);
1373         }
1374         
1375         /* "unlock" frame */
1376         if (p->gpf)
1377                 p->gpf->flag &= ~GP_FRAME_PAINT;
1378 }
1379
1380 /* ------------------------------- */
1381
1382 static void gpencil_draw_exit (bContext *C, wmOperator *op)
1383 {
1384         tGPsdata *p= op->customdata;
1385         
1386         /* clear undo stack */
1387         gpencil_undo_finish();
1388         
1389         /* restore cursor to indicate end of drawing */
1390         WM_cursor_restore(CTX_wm_window(C));
1391         
1392         /* don't assume that operator data exists at all */
1393         if (p) {
1394                 /* check size of buffer before cleanup, to determine if anything happened here */
1395                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1396                         // TODO clear radial cursor thing
1397                         // XXX draw_sel_circle(NULL, p.mvalo, 0, p.radius, 0);
1398                 }
1399                 
1400                 /* cleanup */
1401                 gp_paint_cleanup(p);
1402                 gp_session_cleanup(p);
1403                 
1404                 /* finally, free the temp data */
1405                 MEM_freeN(p);   
1406         }
1407         
1408         op->customdata= NULL;
1409 }
1410
1411 static int gpencil_draw_cancel (bContext *C, wmOperator *op)
1412 {
1413         /* this is just a wrapper around exit() */
1414         gpencil_draw_exit(C, op);
1415         return OPERATOR_CANCELLED;
1416 }
1417
1418 /* ------------------------------- */
1419
1420
1421 static int gpencil_draw_init (bContext *C, wmOperator *op)
1422 {
1423         tGPsdata *p;
1424         int paintmode= RNA_enum_get(op->ptr, "mode");
1425         
1426         /* check context */
1427         p= op->customdata= gp_session_initpaint(C);
1428         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1429                 /* something wasn't set correctly in context */
1430                 gpencil_draw_exit(C, op);
1431                 return 0;
1432         }
1433         
1434         /* init painting data */
1435         gp_paint_initstroke(p, paintmode);
1436         if (p->status == GP_STATUS_ERROR) {
1437                 gpencil_draw_exit(C, op);
1438                 return 0;
1439         }
1440         
1441         /* radius for eraser circle is defined in userprefs now */
1442         p->radius= U.gp_eraser;
1443         
1444         /* everything is now setup ok */
1445         return 1;
1446 }
1447
1448 /* ------------------------------- */
1449
1450 /* update UI indicators of status, including cursor and header prints */
1451 static void gpencil_draw_status_indicators (tGPsdata *p)
1452 {
1453         /* header prints */
1454         switch (p->status) {
1455                 case GP_STATUS_PAINTING:
1456                         /* only print this for paint-sessions, otherwise it gets annoying */
1457                         if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
1458                                 ED_area_headerprint(p->sa, "Grease Pencil: Drawing/erasing stroke... Release to end stroke");
1459                         break;
1460                 
1461                 case GP_STATUS_IDLING:
1462                         /* print status info */
1463                         switch (p->paintmode) {
1464                                 case GP_PAINTMODE_ERASER:
1465                                         ED_area_headerprint(p->sa, "Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | ESC/Enter to end");
1466                                         break;
1467                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1468                                         ED_area_headerprint(p->sa, "Grease Pencil Line Session: Hold and drag LMB to draw | ESC/Enter to end");
1469                                         break;
1470                                 case GP_PAINTMODE_DRAW:
1471                                         ED_area_headerprint(p->sa, "Grease Pencil Freehand Session: Hold and drag LMB to draw | ESC/Enter to end");
1472                                         break;
1473                                         
1474                                 default: /* unhandled future cases */
1475                                         ED_area_headerprint(p->sa, "Grease Pencil Session: ESC/Enter to end");
1476                                         break;
1477                         }
1478                         break;
1479                         
1480                 case GP_STATUS_ERROR:
1481                 case GP_STATUS_DONE:
1482                         /* clear status string */
1483                         ED_area_headerprint(p->sa, NULL);
1484                         break;
1485         }
1486 }
1487
1488 /* ------------------------------- */
1489
1490 /* create a new stroke point at the point indicated by the painting context */
1491 static void gpencil_draw_apply (wmOperator *op, tGPsdata *p)
1492 {
1493         /* handle drawing/erasing -> test for erasing first */
1494         if (p->paintmode == GP_PAINTMODE_ERASER) {
1495                 /* do 'live' erasing now */
1496                 gp_stroke_doeraser(p);
1497                 
1498                 /* store used values */
1499                 p->mvalo[0]= p->mval[0];
1500                 p->mvalo[1]= p->mval[1];
1501                 p->opressure= p->pressure;
1502         }
1503         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1504         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1505                 /* try to add point */
1506                 short ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1507                 
1508                 /* handle errors while adding point */
1509                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1510                         /* finish off old stroke */
1511                         gp_paint_strokeend(p);
1512                         
1513                         /* start a new stroke, starting from previous point */
1514                         gp_stroke_addpoint(p, p->mvalo, p->opressure);
1515                         gp_stroke_addpoint(p, p->mval, p->pressure);
1516                 }
1517                 else if (ok == GP_STROKEADD_INVALID) {
1518                         /* the painting operation cannot continue... */
1519                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1520                         p->status = GP_STATUS_ERROR;
1521                         
1522                         if (G.f & G_DEBUG) 
1523                                 printf("Error: Grease-Pencil Paint - Add Point Invalid \n");
1524                         return;
1525                 }
1526                 
1527                 /* store used values */
1528                 p->mvalo[0]= p->mval[0];
1529                 p->mvalo[1]= p->mval[1];
1530                 p->opressure= p->pressure;
1531         }
1532 }
1533
1534 /* handle draw event */
1535 static void gpencil_draw_apply_event (wmOperator *op, wmEvent *event)
1536 {
1537         tGPsdata *p= op->customdata;
1538         PointerRNA itemptr;
1539         float mousef[2];
1540         int tablet=0;
1541
1542         /* convert from window-space to area-space mouse coordintes */
1543         // NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1544         p->mval[0]= event->mval[0] + 1;
1545         p->mval[1]= event->mval[1] + 1;
1546
1547         /* handle pressure sensitivity (which is supplied by tablets) */
1548         if (event->custom == EVT_DATA_TABLET) {
1549                 wmTabletData *wmtab= event->customdata;
1550                 
1551                 tablet= (wmtab->Active != EVT_TABLET_NONE);
1552                 p->pressure= wmtab->Pressure;
1553                 
1554                 //if (wmtab->Active == EVT_TABLET_ERASER)
1555                         // TODO... this should get caught by the keymaps which call drawing in the first place
1556         }
1557         else
1558                 p->pressure= 1.0f;
1559         
1560         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1561         RNA_collection_add(op->ptr, "stroke", &itemptr);
1562         
1563         mousef[0]= p->mval[0];
1564         mousef[1]= p->mval[1];
1565         RNA_float_set_array(&itemptr, "mouse", mousef);
1566         RNA_float_set(&itemptr, "pressure", p->pressure);
1567         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN));
1568         
1569         /* special exception for start of strokes (i.e. maybe for just a dot) */
1570         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1571                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1572                 
1573                 p->mvalo[0]= p->mval[0];
1574                 p->mvalo[1]= p->mval[1];
1575                 p->opressure= p->pressure;
1576                 
1577                 /* special exception here for too high pressure values on first touch in
1578                  *  windows for some tablets, then we just skip first touch ..  
1579                  */
1580                 if (tablet && (p->pressure >= 0.99f))
1581                         return;
1582         }
1583         
1584         /* apply the current latest drawing point */
1585         gpencil_draw_apply(op, p);
1586         
1587         /* force refresh */
1588         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1589 }
1590
1591 /* ------------------------------- */
1592
1593 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1594 static int gpencil_draw_exec (bContext *C, wmOperator *op)
1595 {
1596         tGPsdata *p = NULL;
1597         
1598         //printf("GPencil - Starting Re-Drawing \n");
1599         
1600         /* try to initialize context data needed while drawing */
1601         if (!gpencil_draw_init(C, op)) {
1602                 if (op->customdata) MEM_freeN(op->customdata);
1603                 //printf("\tGP - no valid data \n");
1604                 return OPERATOR_CANCELLED;
1605         }
1606         else
1607                 p= op->customdata;
1608         
1609         //printf("\tGP - Start redrawing stroke \n");
1610         
1611         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1612          * setting the relevant values in context at each step, then applying
1613          */
1614         RNA_BEGIN(op->ptr, itemptr, "stroke") 
1615         {
1616                 float mousef[2];
1617                 
1618                 //printf("\t\tGP - stroke elem \n");
1619                 
1620                 /* get relevant data for this point from stroke */
1621                 RNA_float_get_array(&itemptr, "mouse", mousef);
1622                 p->mval[0] = (int)mousef[0];
1623                 p->mval[1] = (int)mousef[1];
1624                 p->pressure= RNA_float_get(&itemptr, "pressure");
1625                 
1626                 if (RNA_boolean_get(&itemptr, "is_start")) {
1627                         /* if first-run flag isn't set already (i.e. not true first stroke),
1628                          * then we must terminate the previous one first before continuing
1629                          */
1630                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
1631                                 // TODO: both of these ops can set error-status, but we probably don't need to worry
1632                                 gp_paint_strokeend(p);
1633                                 gp_paint_initstroke(p, p->paintmode);
1634                         }
1635                 }
1636                 
1637                 /* if first run, set previous data too */
1638                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1639                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1640                         
1641                         p->mvalo[0]= p->mval[0];
1642                         p->mvalo[1]= p->mval[1];
1643                         p->opressure= p->pressure;
1644                 }
1645                 
1646                 /* apply this data as necessary now (as per usual) */
1647                 gpencil_draw_apply(op, p);
1648         }
1649         RNA_END;
1650         
1651         //printf("\tGP - done \n");
1652         
1653         /* cleanup */
1654         gpencil_draw_exit(C, op);
1655         
1656         /* refreshes */
1657         WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work  
1658         
1659         /* done */
1660         return OPERATOR_FINISHED;
1661 }
1662
1663 /* ------------------------------- */
1664
1665 /* start of interactive drawing part of operator */
1666 static int gpencil_draw_invoke (bContext *C, wmOperator *op, wmEvent *event)
1667 {
1668         tGPsdata *p = NULL;
1669         wmWindow *win= CTX_wm_window(C);
1670         
1671         if (G.f & G_DEBUG)
1672                 printf("GPencil - Starting Drawing \n");
1673         
1674         /* try to initialize context data needed while drawing */
1675         if (!gpencil_draw_init(C, op)) {
1676                 if (op->customdata) 
1677                         MEM_freeN(op->customdata);
1678                 if (G.f & G_DEBUG)
1679                         printf("\tGP - no valid data \n");
1680                 return OPERATOR_CANCELLED;
1681         }
1682         else
1683                 p= op->customdata;
1684         
1685         // TODO: set any additional settings that we can take from the events?
1686         // TODO? if tablet is erasing, force eraser to be on?
1687         
1688         // TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway...
1689         
1690         /* if eraser is on, draw radial aid */
1691         if (p->paintmode == GP_PAINTMODE_ERASER) {
1692                 // TODO: this involves mucking around with radial control, so we leave this for now..
1693         }
1694         
1695         /* set cursor */
1696         if (p->paintmode == GP_PAINTMODE_ERASER)
1697                 WM_cursor_modal(win, BC_CROSSCURSOR); // XXX need a better cursor
1698         else
1699                 WM_cursor_modal(win, BC_PAINTBRUSHCURSOR);
1700         
1701         /* special hack: if there was an initial event, then we were invoked via a hotkey, and 
1702          * painting should start immediately. Otherwise, this was called from a toolbar, in which
1703          * case we should wait for the mouse to be clicked.
1704          */
1705         if (event->type) {
1706                 /* hotkey invoked - start drawing */
1707                 //printf("\tGP - set first spot\n");
1708                 p->status= GP_STATUS_PAINTING;
1709                 
1710                 /* handle the initial drawing - i.e. for just doing a simple dot */
1711                 gpencil_draw_apply_event(op, event);
1712         }
1713         else {
1714                 /* toolbar invoked - don't start drawing yet... */
1715                 //printf("\tGP - hotkey invoked... waiting for click-drag\n");
1716         }
1717         
1718         WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL, NULL);
1719         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1720         WM_event_add_modal_handler(C, op);
1721         return OPERATOR_RUNNING_MODAL;
1722 }
1723
1724 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1725 static int gpencil_area_exists(bContext *C, ScrArea *satest)
1726 {
1727         bScreen *sc= CTX_wm_screen(C);
1728         ScrArea *sa;
1729         
1730         for (sa= sc->areabase.first; sa; sa= sa->next) {
1731                 if (sa==satest)
1732                         return 1;
1733         }
1734         
1735         return 0;
1736 }
1737
1738 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
1739 {
1740         tGPsdata *p= op->customdata;
1741
1742         /* we must check that we're still within the area that we're set up to work from
1743          * otherwise we could crash (see bug #20586)
1744          */
1745         if (CTX_wm_area(C) != p->sa) {
1746                 printf("\t\t\tGP - wrong area execution abort! \n");
1747                 p->status= GP_STATUS_ERROR;
1748         }
1749
1750         //printf("\t\tGP - start stroke \n");
1751
1752         /* we may need to set up paint env again if we're resuming */
1753         // XXX: watch it with the paintmode! in future, it'd be nice to allow changing paint-mode when in sketching-sessions
1754         // XXX: with tablet events, we may event want to check for eraser here, for nicer tablet support
1755
1756         if (gp_session_initdata(C, p))
1757                 gp_paint_initstroke(p, p->paintmode);
1758
1759         if(p->status != GP_STATUS_ERROR)
1760                 p->status= GP_STATUS_PAINTING;
1761
1762         return op->customdata;
1763 }
1764
1765 static void gpencil_stroke_end(wmOperator *op)
1766 {
1767         tGPsdata *p= op->customdata;
1768
1769         gp_paint_cleanup(p);
1770
1771         gpencil_undo_push(p->gpd);
1772
1773         gp_session_cleanup(p);
1774
1775         p->status= GP_STATUS_IDLING;
1776
1777         p->gpd= NULL;
1778         p->gpl= NULL;
1779         p->gpf= NULL;
1780 }
1781
1782 /* events handling during interactive drawing part of operator */
1783 static int gpencil_draw_modal (bContext *C, wmOperator *op, wmEvent *event)
1784 {
1785         tGPsdata *p= op->customdata;
1786         int estate = OPERATOR_PASS_THROUGH; /* default exit state - not handled, so let others have a share of the pie */
1787         
1788         // if (event->type == NDOF_MOTION)
1789         //      return OPERATOR_PASS_THROUGH;
1790         // -------------------------------
1791         // [mce] Not quite what I was looking
1792         // for, but a good start! GP continues to
1793         // draw on the screen while the 3D mouse
1794         // moves the viewpoint. Problem is that
1795         // the stroke is converted to 3D only after
1796         // it is finished. This approach should work
1797         // better in tools that immediately apply
1798         // in 3D space.
1799
1800         //printf("\tGP - handle modal event...\n");
1801         
1802         /* exit painting mode (and/or end current stroke) */
1803         if (ELEM4(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY)) {
1804                 /* exit() ends the current stroke before cleaning up */
1805                 //printf("\t\tGP - end of paint op + end of stroke\n");
1806                 p->status= GP_STATUS_DONE;
1807                 estate = OPERATOR_FINISHED;
1808         }
1809         
1810         /* toggle painting mode upon mouse-button movement */
1811         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE)) {
1812                 /* if painting, end stroke */
1813                 if (p->status == GP_STATUS_PAINTING) {
1814                         int sketch= 0;
1815                         /* basically, this should be mouse-button up = end stroke 
1816                          * BUT what happens next depends on whether we 'painting sessions' is enabled
1817                          */
1818                         sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
1819                         /* polyline drawing is also 'sketching' -- all knots should be added during one session */
1820                         sketch |= p->paintmode == GP_PAINTMODE_DRAW_POLY;
1821
1822                         if (sketch) {
1823                                 /* end stroke only, and then wait to resume painting soon */
1824                                 //printf("\t\tGP - end stroke only\n");
1825                                 gpencil_stroke_end(op);
1826                                 
1827                                 /* we've just entered idling state, so this event was processed (but no others yet) */
1828                                 estate = OPERATOR_RUNNING_MODAL;
1829
1830                                 /* stroke could be smoothed, send notifier to refresh screen */
1831                                 WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL);
1832                         }
1833                         else {
1834                                 //printf("\t\tGP - end of stroke + op\n");
1835                                 p->status= GP_STATUS_DONE;
1836                                 estate = OPERATOR_FINISHED;
1837                         }
1838                 }
1839                 else if (event->val == KM_PRESS) {
1840                         /* not painting, so start stroke (this should be mouse-button down) */
1841                         p= gpencil_stroke_begin(C, op);
1842
1843                         if (p->status == GP_STATUS_ERROR) {
1844                                 estate = OPERATOR_CANCELLED;
1845                         }
1846                 } 
1847                 else {
1848                         p->status = GP_STATUS_IDLING;
1849                 }
1850         }
1851         
1852         /* handle mode-specific events */
1853         if (p->status == GP_STATUS_PAINTING) {
1854                 /* handle painting mouse-movements? */
1855                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
1856                         /* handle drawing event */
1857                         //printf("\t\tGP - add point\n");
1858                         gpencil_draw_apply_event(op, event);
1859                         
1860                         /* finish painting operation if anything went wrong just now */
1861                         if (p->status == GP_STATUS_ERROR) {
1862                                 printf("\t\t\t\tGP - add error done! \n");
1863                                 estate = OPERATOR_CANCELLED;
1864                         }
1865                         else {
1866                                 /* event handled, so just tag as running modal */
1867                                 //printf("\t\t\t\tGP - add point handled!\n");
1868                                 estate = OPERATOR_RUNNING_MODAL;
1869                         }
1870                 }
1871                 /* there shouldn't be any other events, but just in case there are, let's swallow them 
1872                  * (i.e. to prevent problems with with undo)
1873                  */
1874                 else {
1875                         /* swallow event to save ourselves trouble */
1876                         estate = OPERATOR_RUNNING_MODAL;
1877                 }
1878         }
1879         
1880         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
1881         if (0==gpencil_area_exists(C, p->sa))
1882                 estate= OPERATOR_CANCELLED;
1883         else
1884                 /* update status indicators - cursor, header, etc. */
1885                 gpencil_draw_status_indicators(p);
1886         
1887         /* process last operations before exiting */
1888         switch (estate) {
1889                 case OPERATOR_FINISHED:
1890                         /* one last flush before we're done */
1891                         gpencil_draw_exit(C, op);
1892                         WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work
1893                         break;
1894                         
1895                 case OPERATOR_CANCELLED:
1896                         gpencil_draw_exit(C, op);
1897                         break;
1898
1899                 case OPERATOR_RUNNING_MODAL|OPERATOR_PASS_THROUGH:
1900                         /* event doesn't need to be handled */
1901                         //printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n", event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
1902                         break;
1903         }
1904         
1905         /* return status code */
1906         return estate;
1907 }
1908
1909 /* ------------------------------- */
1910
1911 static EnumPropertyItem prop_gpencil_drawmodes[] = {
1912         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
1913         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
1914         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", ""},
1915         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
1916         {0, NULL, 0, NULL, NULL}
1917 };
1918
1919 void GPENCIL_OT_draw (wmOperatorType *ot)
1920 {
1921         /* identifiers */
1922         ot->name= "Grease Pencil Draw";
1923         ot->idname= "GPENCIL_OT_draw";
1924         ot->description= "Make annotations on the active data";
1925         
1926         /* api callbacks */
1927         ot->exec= gpencil_draw_exec;
1928         ot->invoke= gpencil_draw_invoke;
1929         ot->modal= gpencil_draw_modal;
1930         ot->cancel= gpencil_draw_cancel;
1931         ot->poll= gpencil_draw_poll;
1932         
1933         /* flags */
1934         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1935         
1936         /* settings for drawing */
1937         RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
1938         
1939         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1940 }