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