* Grease Pencil drawing now works with Repeat Last operator. Stroke info is now saved...
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
21  * This is a new part of Blender
22  *
23  * Contributor(s): Joshua Leung
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 #include <stdio.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <math.h>
33
34 #include "MEM_guardedalloc.h"
35
36 #include "BLI_blenlib.h"
37 #include "BLI_math.h"
38
39 #include "BKE_gpencil.h"
40 #include "BKE_context.h"
41 #include "BKE_global.h"
42 #include "BKE_report.h"
43 #include "BKE_utildefines.h"
44
45 #include "DNA_gpencil_types.h"
46 #include "DNA_action_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_screen_types.h"
50 #include "DNA_space_types.h"
51 #include "DNA_view2d_types.h"
52 #include "DNA_view3d_types.h"
53 #include "DNA_windowmanager_types.h"
54
55 #include "UI_view2d.h"
56
57 #include "ED_armature.h"
58 #include "ED_gpencil.h"
59 #include "ED_sequencer.h"
60 #include "ED_screen.h"
61 #include "ED_view3d.h"
62
63 #include "RNA_access.h"
64
65 #include "RNA_define.h"
66 #include "WM_api.h"
67 #include "WM_types.h"
68
69 #include "gpencil_intern.h"
70
71 /* ******************************************* */
72 /* 'Globals' and Defines */
73
74 /* Temporary 'Stroke' Operation data */
75 typedef struct tGPsdata {
76         Scene *scene;       /* current scene from context */
77         ScrArea *sa;            /* area where painting originated */
78         ARegion *ar;        /* region where painting originated */
79         View2D *v2d;            /* needed for GP_STROKE_2DSPACE */
80         
81 #if 0 // XXX review this 2d image stuff...
82         ImBuf *ibuf;            /* needed for GP_STROKE_2DIMAGE */
83         struct IBufViewSettings {
84                 int offsx, offsy;                       /* offsets */
85                 int sizex, sizey;                       /* dimensions to use as scale-factor */
86         } im2d_settings;        /* needed for GP_STROKE_2DIMAGE */
87 #endif
88         
89         PointerRNA ownerPtr;/* pointer to owner of gp-datablock */
90         bGPdata *gpd;           /* gp-datablock layer comes from */
91         bGPDlayer *gpl;         /* layer we're working on */
92         bGPDframe *gpf;         /* frame we're working on */
93         
94         short status;           /* current status of painting */
95         short paintmode;        /* mode for painting */
96         
97         int mval[2];            /* current mouse-position */
98         int mvalo[2];           /* previous recorded mouse-position */
99         
100         float pressure;         /* current stylus pressure */
101         float opressure;        /* previous stylus pressure */
102         
103         short radius;           /* radius of influence for eraser */
104         short flags;            /* flags that can get set during runtime */
105 } tGPsdata;
106
107 /* values for tGPsdata->status */
108 enum {
109         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
110         GP_STATUS_PAINTING,             /* a stroke is in progress */
111         GP_STATUS_ERROR,                /* something wasn't correctly set up */
112         GP_STATUS_DONE                  /* painting done */
113 };
114
115 /* Return flags for adding points to stroke buffer */
116 enum {
117         GP_STROKEADD_INVALID    = -2,           /* error occurred - insufficient info to do so */
118         GP_STROKEADD_OVERFLOW   = -1,           /* error occurred - cannot fit any more points */
119         GP_STROKEADD_NORMAL,                            /* point was successfully added */
120         GP_STROKEADD_FULL                                       /* cannot add any more points to buffer */
121 };
122
123 /* Runtime flags */
124 enum {
125         GP_PAINTFLAG_FIRSTRUN           = (1<<0),       /* operator just started */
126 };
127
128 /* ------ */
129
130 /* maximum sizes of gp-session buffer */
131 #define GP_STROKE_BUFFER_MAX    5000
132
133 /* Macros for accessing sensitivity thresholds... */
134         /* minimum number of pixels mouse should move before new point created */
135 #define MIN_MANHATTEN_PX        (U.gp_manhattendist)
136         /* minimum length of new segment before new point can be added */
137 #define MIN_EUCLIDEAN_PX        (U.gp_euclideandist)
138
139 /* ------ */
140 /* Forward defines for some functions... */
141
142 static void gp_session_validatebuffer(tGPsdata *p);
143
144 /* ******************************************* */
145 /* Context Wrangling... */
146
147 /* check if context is suitable for drawing */
148 static int gpencil_draw_poll (bContext *C)
149 {
150         /* check if current context can support GPencil data */
151         return (gpencil_data_get_pointers(C, NULL) != NULL);
152 }
153
154 /* check if projecting strokes into 3d-geometry in the 3D-View */
155 static int gpencil_project_check (tGPsdata *p)
156 {
157         bGPdata *gpd= p->gpd;
158         
159         if(     (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) &&
160                 (p->scene->toolsettings->snap_mode==SCE_SNAP_MODE_FACE) &&
161                 (p->scene->toolsettings->snap_flag & SCE_SNAP_PROJECT) )
162         {
163                 return 1;
164         }
165
166         return 0;
167 }
168
169 /* ******************************************* */
170 /* Calculations/Conversions */
171
172 /* Utilities --------------------------------- */
173
174 /* get the reference point for stroke-point conversions */
175 static void gp_get_3d_reference (tGPsdata *p, float *vec)
176 {
177         View3D *v3d= p->sa->spacedata.first;
178         float *fp= give_cursor(p->scene, v3d);
179         
180         /* the reference point used depends on the owner... */
181         if (p->ownerPtr.type == &RNA_Object) {
182                 Object *ob= (Object *)p->ownerPtr.data;
183                 
184                 /* active Object 
185                  *      - use relative distance of 3D-cursor from object center 
186                  */
187                 sub_v3_v3v3(vec, fp, ob->loc);
188         }
189         else {
190                 /* use 3D-cursor */
191                 copy_v3_v3(vec, fp);
192         }
193 }
194
195 /* Stroke Editing ---------------------------- */
196
197 /* check if the current mouse position is suitable for adding a new point */
198 static short gp_stroke_filtermval (tGPsdata *p, int mval[2], int pmval[2])
199 {
200         int dx= abs(mval[0] - pmval[0]);
201         int dy= abs(mval[1] - pmval[1]);
202         
203         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
204         if (p->gpd->sbuffer_size == 0)
205                 return 1;
206         
207         /* check if mouse moved at least certain distance on both axes (best case) */
208         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
209                 return 1;
210         
211         /* check if the distance since the last point is significant enough */
212         // future optimisation: sqrt here may be too slow?
213         else if (sqrt(dx*dx + dy*dy) > MIN_EUCLIDEAN_PX)
214                 return 1;
215         
216         /* mouse 'didn't move' */
217         else
218                 return 0;
219 }
220
221 /* convert screen-coordinates to buffer-coordinates */
222 // XXX this method needs a total overhaul!
223 static void gp_stroke_convertcoords (tGPsdata *p, short mval[], float out[])
224 {
225         bGPdata *gpd= p->gpd;
226         
227         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
228         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
229                 if(gpencil_project_check(p) && (view_autodist_simple(p->ar, mval, out))) {
230                         /* projecting onto 3D-Geometry
231                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
232                          */
233                 }
234                 else {
235                         const short mx=mval[0], my=mval[1];
236                         float rvec[3], dvec[3];
237                         
238                         /* Current method just converts each point in screen-coordinates to
239                          * 3D-coordinates using the 3D-cursor as reference. In general, this
240                          * works OK, but it could of course be improved.
241                          *
242                          * TODO:
243                          *      - investigate using nearest point(s) on a previous stroke as
244                          *        reference point instead or as offset, for easier stroke matching
245                          */
246                         
247                         gp_get_3d_reference(p, rvec);
248                         
249                         /* method taken from editview.c - mouse_cursor() */
250                         project_short_noclip(p->ar, rvec, mval);
251                         window_to_3d_delta(p->ar, dvec, mval[0]-mx, mval[1]-my);
252                         sub_v3_v3v3(out, rvec, dvec);
253                 }
254         }
255         
256         /* 2d - on 'canvas' (assume that p->v2d is set) */
257         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
258                 float x, y;
259                 
260                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &x, &y);
261                 
262                 out[0]= x;
263                 out[1]= y;
264         }
265         
266 #if 0
267         /* 2d - on image 'canvas' (assume that p->v2d is set) */
268         else if (gpd->sbuffer_sflag & GP_STROKE_2DIMAGE) {
269                 int sizex, sizey, offsx, offsy;
270                 
271                 /* get stored settings 
272                  *      - assume that these have been set already (there are checks that set sane 'defaults' just in case)
273                  */
274                 sizex= p->im2d_settings.sizex;
275                 sizey= p->im2d_settings.sizey;
276                 offsx= p->im2d_settings.offsx;
277                 offsy= p->im2d_settings.offsy;
278                 
279                 /* calculate new points */
280                 out[0]= (float)(mval[0] - offsx) / (float)sizex;
281                 out[1]= (float)(mval[1] - offsy) / (float)sizey;
282         }
283 #endif
284         
285         /* 2d - relative to screen (viewport area) */
286         else {
287                 out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
288                 out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
289         }
290 }
291
292 /* add current stroke-point to buffer (returns whether point was successfully added) */
293 static short gp_stroke_addpoint (tGPsdata *p, int mval[2], float pressure)
294 {
295         bGPdata *gpd= p->gpd;
296         tGPspoint *pt;
297         
298         /* check painting mode */
299         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
300                 /* straight lines only - i.e. only store start and end point in buffer */
301                 if (gpd->sbuffer_size == 0) {
302                         /* first point in buffer (start point) */
303                         pt= (tGPspoint *)(gpd->sbuffer);
304                         
305                         /* store settings */
306                         pt->x= mval[0];
307                         pt->y= mval[1];
308                         pt->pressure= pressure;
309                         
310                         /* increment buffer size */
311                         gpd->sbuffer_size++;
312                 }
313                 else {
314                         /* normally, we just reset the endpoint to the latest value 
315                          *      - assume that pointers for this are always valid...
316                          */
317                         pt= ((tGPspoint *)(gpd->sbuffer) + 1);
318                         
319                         /* store settings */
320                         pt->x= mval[0];
321                         pt->y= mval[1];
322                         pt->pressure= pressure;
323                         
324                         /* if this is just the second point we've added, increment the buffer size
325                          * so that it will be drawn properly...
326                          * otherwise, just leave it alone, otherwise we get problems
327                          */
328                         if (gpd->sbuffer_size != 2)
329                                 gpd->sbuffer_size= 2;
330                 }
331                 
332                 /* can keep carrying on this way :) */
333                 return GP_STROKEADD_NORMAL;
334         }
335         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
336                 /* check if still room in buffer */
337                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
338                         return GP_STROKEADD_OVERFLOW;
339                 
340                 /* get pointer to destination point */
341                 pt= ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
342                 
343                 /* store settings */
344                 pt->x= mval[0];
345                 pt->y= mval[1];
346                 pt->pressure= pressure;
347                 
348                 /* increment counters */
349                 gpd->sbuffer_size++;
350                 
351                 /* check if another operation can still occur */
352                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
353                         return GP_STROKEADD_FULL;
354                 else
355                         return GP_STROKEADD_NORMAL;
356         }
357         
358         /* return invalid state for now... */
359         return GP_STROKEADD_INVALID;
360 }
361
362 /* smooth a stroke (in buffer) before storing it */
363 static void gp_stroke_smooth (tGPsdata *p)
364 {
365         bGPdata *gpd= p->gpd;
366         int i=0, cmx=gpd->sbuffer_size;
367         
368         /* only smooth if smoothing is enabled, and we're not doing a straight line */
369         if (!(U.gp_settings & GP_PAINT_DOSMOOTH) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
370                 return;
371         
372         /* don't try if less than 2 points in buffer */
373         if ((cmx <= 2) || (gpd->sbuffer == NULL))
374                 return;
375         
376         /* apply weighting-average (note doing this along path sequentially does introduce slight error) */
377         for (i=0; i < gpd->sbuffer_size; i++) {
378                 tGPspoint *pc= (((tGPspoint *)gpd->sbuffer) + i);
379                 tGPspoint *pb= (i-1 > 0)?(pc-1):(pc);
380                 tGPspoint *pa= (i-2 > 0)?(pc-2):(pb);
381                 tGPspoint *pd= (i+1 < cmx)?(pc+1):(pc);
382                 tGPspoint *pe= (i+2 < cmx)?(pc+2):(pd);
383                 
384                 pc->x= (short)(0.1*pa->x + 0.2*pb->x + 0.4*pc->x + 0.2*pd->x + 0.1*pe->x);
385                 pc->y= (short)(0.1*pa->y + 0.2*pb->y + 0.4*pc->y + 0.2*pd->y + 0.1*pe->y);
386         }
387 }
388
389 /* simplify a stroke (in buffer) before storing it 
390  *      - applies a reverse Chaikin filter
391  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
392  */
393 static void gp_stroke_simplify (tGPsdata *p)
394 {
395         bGPdata *gpd= p->gpd;
396         tGPspoint *old_points= (tGPspoint *)gpd->sbuffer;
397         short num_points= gpd->sbuffer_size;
398         short flag= gpd->sbuffer_sflag;
399         short i, j;
400         
401         /* only simplify if simlification is enabled, and we're not doing a straight line */
402         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
403                 return;
404         
405         /* don't simplify if less than 4 points in buffer */
406         if ((num_points <= 2) || (old_points == NULL))
407                 return;
408                 
409         /* clear buffer (but don't free mem yet) so that we can write to it 
410          *      - firstly set sbuffer to NULL, so a new one is allocated
411          *      - secondly, reset flag after, as it gets cleared auto
412          */
413         gpd->sbuffer= NULL;
414         gp_session_validatebuffer(p);
415         gpd->sbuffer_sflag = flag;
416         
417 /* macro used in loop to get position of new point
418  *      - used due to the mixture of datatypes in use here
419  */
420 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
421         { \
422                 co[0] += (float)(old_points[offs].x * sfac); \
423                 co[1] += (float)(old_points[offs].y * sfac); \
424                 pressure += old_points[offs].pressure * sfac; \
425         }
426         
427         for (i = 0, j = 0; i < num_points; i++)
428         {
429                 if (i - j == 3)
430                 {
431                         float co[2], pressure;
432                         int mco[2];
433                         
434                         /* initialise values */
435                         co[0]= 0;
436                         co[1]= 0;
437                         pressure = 0;
438                         
439                         /* using macro, calculate new point */
440                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
441                         GP_SIMPLIFY_AVPOINT(j+1, 0.75f);
442                         GP_SIMPLIFY_AVPOINT(j+2, 0.75f);
443                         GP_SIMPLIFY_AVPOINT(j+3, -0.25f);
444                         
445                         /* set values for adding */
446                         mco[0]= (int)co[0];
447                         mco[1]= (int)co[1];
448                         
449                         /* ignore return values on this... assume to be ok for now */
450                         gp_stroke_addpoint(p, mco, pressure);
451                         
452                         j += 2;
453                 }
454         } 
455         
456         /* free old buffer */
457         MEM_freeN(old_points);
458 }
459
460
461 /* make a new stroke from the buffer data */
462 static void gp_stroke_newfrombuffer (tGPsdata *p)
463 {
464         bGPdata *gpd= p->gpd;
465         bGPDstroke *gps;
466         bGPDspoint *pt;
467         tGPspoint *ptc;
468         int i, totelem;
469         
470         /* get total number of points to allocate space for 
471          *      - drawing straight-lines only requires the endpoints
472          */
473         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
474                 totelem = (gpd->sbuffer_size >= 2) ? 2: gpd->sbuffer_size;
475         else
476                 totelem = gpd->sbuffer_size;
477         
478         /* exit with error if no valid points from this stroke */
479         if (totelem == 0) {
480                 if (G.f & G_DEBUG) 
481                         printf("Error: No valid points in stroke buffer to convert (tot=%d) \n", gpd->sbuffer_size);
482                 return;
483         }
484         
485         /* allocate memory for a new stroke */
486         gps= MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
487         
488         /* allocate enough memory for a continuous array for storage points */
489         pt= gps->points= MEM_callocN(sizeof(bGPDspoint)*totelem, "gp_stroke_points");
490         
491         /* copy appropriate settings for stroke */
492         gps->totpoints= totelem;
493         gps->thickness= p->gpl->thickness;
494         gps->flag= gpd->sbuffer_sflag;
495         
496         /* copy points from the buffer to the stroke */
497         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
498                 /* straight lines only -> only endpoints */
499                 {
500                         /* first point */
501                         ptc= gpd->sbuffer;
502                         
503                         /* convert screen-coordinates to appropriate coordinates (and store them) */
504                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
505                         
506                         /* copy pressure */
507                         pt->pressure= ptc->pressure;
508                         
509                         pt++;
510                 }
511                         
512                 if (totelem == 2) {
513                         /* last point if applicable */
514                         ptc= ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
515                         
516                         /* convert screen-coordinates to appropriate coordinates (and store them) */
517                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
518                         
519                         /* copy pressure */
520                         pt->pressure= ptc->pressure;
521                 }
522         }
523         else {
524                 /* convert all points (normal behaviour) */
525                 for (i=0, ptc=gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++) {
526                         /* convert screen-coordinates to appropriate coordinates (and store them) */
527                         gp_stroke_convertcoords(p, &ptc->x, &pt->x);
528                         
529                         /* copy pressure */
530                         pt->pressure= ptc->pressure;
531                         
532                         pt++;
533                 }
534         }
535         
536         /* add stroke to frame */
537         BLI_addtail(&p->gpf->strokes, gps);
538 }
539
540 /* --- 'Eraser' for 'Paint' Tool ------ */
541
542 /* eraser tool - remove segment from stroke/split stroke (after lasso inside) */
543 static short gp_stroke_eraser_splitdel (bGPDframe *gpf, bGPDstroke *gps, int i)
544 {
545         bGPDspoint *pt_tmp= gps->points;
546         bGPDstroke *gsn = NULL;
547
548         /* if stroke only had two points, get rid of stroke */
549         if (gps->totpoints == 2) {
550                 /* free stroke points, then stroke */
551                 MEM_freeN(pt_tmp);
552                 BLI_freelinkN(&gpf->strokes, gps);
553                 
554                 /* nothing left in stroke, so stop */
555                 return 1;
556         }
557
558         /* if last segment, just remove segment from the stroke */
559         else if (i == gps->totpoints - 2) {
560                 /* allocate new points array, and assign most of the old stroke there */
561                 gps->totpoints--;
562                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
563                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*gps->totpoints);
564                 
565                 /* free temp buffer */
566                 MEM_freeN(pt_tmp);
567                 
568                 /* nothing left in stroke, so stop */
569                 return 1;
570         }
571
572         /* if first segment, just remove segment from the stroke */
573         else if (i == 0) {
574                 /* allocate new points array, and assign most of the old stroke there */
575                 gps->totpoints--;
576                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
577                 memcpy(gps->points, pt_tmp + 1, sizeof(bGPDspoint)*gps->totpoints);
578                 
579                 /* free temp buffer */
580                 MEM_freeN(pt_tmp);
581                 
582                 /* no break here, as there might still be stuff to remove in this stroke */
583                 return 0;
584         }
585
586         /* segment occurs in 'middle' of stroke, so split */
587         else {
588                 /* duplicate stroke, and assign 'later' data to that stroke */
589                 gsn= MEM_dupallocN(gps);
590                 gsn->prev= gsn->next= NULL;
591                 BLI_insertlinkafter(&gpf->strokes, gps, gsn);
592                 
593                 gsn->totpoints= gps->totpoints - i;
594                 gsn->points= MEM_callocN(sizeof(bGPDspoint)*gsn->totpoints, "gp_stroke_points");
595                 memcpy(gsn->points, pt_tmp + i, sizeof(bGPDspoint)*gsn->totpoints);
596                 
597                 /* adjust existing stroke  */
598                 gps->totpoints= i;
599                 gps->points= MEM_callocN(sizeof(bGPDspoint)*gps->totpoints, "gp_stroke_points");
600                 memcpy(gps->points, pt_tmp, sizeof(bGPDspoint)*i);
601                 
602                 /* free temp buffer */
603                 MEM_freeN(pt_tmp);
604                 
605                 /* nothing left in stroke, so stop */
606                 return 1;
607         }
608 }
609
610 /* eraser tool - check if part of stroke occurs within last segment drawn by eraser */
611 static short gp_stroke_eraser_strokeinside (int mval[], int mvalo[], short rad, short x0, short y0, short x1, short y1)
612 {
613         /* simple within-radius check for now */
614         if (edge_inside_circle(mval[0], mval[1], rad, x0, y0, x1, y1))
615                 return 1;
616         
617         /* not inside */
618         return 0;
619
620
621 /* eraser tool - evaluation per stroke */
622 // TODO: this could really do with some optimisation (KD-Tree/BVH?)
623 static void gp_stroke_eraser_dostroke (tGPsdata *p, int mval[], int mvalo[], short rad, rcti *rect, bGPDframe *gpf, bGPDstroke *gps)
624 {
625         bGPDspoint *pt1, *pt2;
626         int x0=0, y0=0, x1=0, y1=0;
627         short xyval[2];
628         int i;
629         
630         if (gps->totpoints == 0) {
631                 /* just free stroke */
632                 if (gps->points) 
633                         MEM_freeN(gps->points);
634                 BLI_freelinkN(&gpf->strokes, gps);
635         }
636         else if (gps->totpoints == 1) {
637                 /* get coordinates */
638                 if (gps->flag & GP_STROKE_3DSPACE) {
639                         project_short(p->ar, &gps->points->x, xyval);
640                         x0= xyval[0];
641                         y0= xyval[1];
642                 }
643                 else if (gps->flag & GP_STROKE_2DSPACE) {                       
644                         UI_view2d_view_to_region(p->v2d, gps->points->x, gps->points->y, &x0, &y0);
645                 }
646 #if 0
647                 else if (gps->flag & GP_STROKE_2DIMAGE) {                       
648                         int offsx, offsy, sizex, sizey;
649                         
650                         /* get stored settings */
651                         sizex= p->im2d_settings.sizex;
652                         sizey= p->im2d_settings.sizey;
653                         offsx= p->im2d_settings.offsx;
654                         offsy= p->im2d_settings.offsy;
655                         
656                         /* calculate new points */
657                         x0= (int)((gps->points->x * sizex) + offsx);
658                         y0= (int)((gps->points->y * sizey) + offsy);
659                 }
660 #endif
661                 else {
662                         x0= (int)(gps->points->x / 100 * p->ar->winx);
663                         y0= (int)(gps->points->y / 100 * p->ar->winy);
664                 }
665                 
666                 /* do boundbox check first */
667                 if (BLI_in_rcti(rect, x0, y0)) {
668                         /* only check if point is inside */
669                         if ( ((x0-mval[0])*(x0-mval[0]) + (y0-mval[1])*(y0-mval[1])) <= rad*rad ) {
670                                 /* free stroke */
671                                 MEM_freeN(gps->points);
672                                 BLI_freelinkN(&gpf->strokes, gps);
673                         }
674                 }
675         }
676         else {  
677                 /* loop over the points in the stroke, checking for intersections 
678                  *      - an intersection will require the stroke to be split
679                  */
680                 for (i=0; (i+1) < gps->totpoints; i++) {
681                         /* get points to work with */
682                         pt1= gps->points + i;
683                         pt2= gps->points + i + 1;
684                         
685                         /* get coordinates */
686                         if (gps->flag & GP_STROKE_3DSPACE) {
687                                 project_short(p->ar, &pt1->x, xyval);
688                                 x0= xyval[0];
689                                 y0= xyval[1];
690                                 
691                                 project_short(p->ar, &pt2->x, xyval);
692                                 x1= xyval[0];
693                                 y1= xyval[1];
694                         }
695                         else if (gps->flag & GP_STROKE_2DSPACE) {
696                                 UI_view2d_view_to_region(p->v2d, pt1->x, pt1->y, &x0, &y0);
697                                 
698                                 UI_view2d_view_to_region(p->v2d, pt2->x, pt2->y, &x1, &y1);
699                         }
700 #if 0
701                         else if (gps->flag & GP_STROKE_2DIMAGE) {
702                                 int offsx, offsy, sizex, sizey;
703                                 
704                                 /* get stored settings */
705                                 sizex= p->im2d_settings.sizex;
706                                 sizey= p->im2d_settings.sizey;
707                                 offsx= p->im2d_settings.offsx;
708                                 offsy= p->im2d_settings.offsy;
709                                 
710                                 /* calculate new points */
711                                 x0= (int)((pt1->x * sizex) + offsx);
712                                 y0= (int)((pt1->y * sizey) + offsy);
713                                 
714                                 x1= (int)((pt2->x * sizex) + offsx);
715                                 y1= (int)((pt2->y * sizey) + offsy);
716                         }
717 #endif
718                         else {
719                                 x0= (int)(pt1->x / 100 * p->ar->winx);
720                                 y0= (int)(pt1->y / 100 * p->ar->winy);
721                                 x1= (int)(pt2->x / 100 * p->ar->winx);
722                                 y1= (int)(pt2->y / 100 * p->ar->winy);
723                         }
724                         
725                         /* check that point segment of the boundbox of the eraser stroke */
726                         if (BLI_in_rcti(rect, x0, y0) || BLI_in_rcti(rect, x1, y1)) {
727                                 /* check if point segment of stroke had anything to do with
728                                  * eraser region  (either within stroke painted, or on its lines)
729                                  *      - this assumes that linewidth is irrelevant
730                                  */
731                                 if (gp_stroke_eraser_strokeinside(mval, mvalo, rad, x0, y0, x1, y1)) {
732                                         /* if function returns true, break this loop (as no more point to check) */
733                                         if (gp_stroke_eraser_splitdel(gpf, gps, i))
734                                                 break;
735                                 }
736                         }
737                 }
738         }
739 }
740
741 /* erase strokes which fall under the eraser strokes */
742 static void gp_stroke_doeraser (tGPsdata *p)
743 {
744         bGPDframe *gpf= p->gpf;
745         bGPDstroke *gps, *gpn;
746         rcti rect;
747         
748         /* rect is rectangle of eraser */
749         rect.xmin= p->mval[0] - p->radius;
750         rect.ymin= p->mval[1] - p->radius;
751         rect.xmax= p->mval[0] + p->radius;
752         rect.ymax= p->mval[1] + p->radius;
753         
754         /* loop over strokes, checking segments for intersections */
755         for (gps= gpf->strokes.first; gps; gps= gpn) {
756                 gpn= gps->next;
757                 gp_stroke_eraser_dostroke(p, p->mval, p->mvalo, p->radius, &rect, gpf, gps);
758         }
759 }
760
761 /* ******************************************* */
762 /* Sketching Operator */
763
764 /* clear the session buffers (call this before AND after a paint operation) */
765 static void gp_session_validatebuffer (tGPsdata *p)
766 {
767         bGPdata *gpd= p->gpd;
768         
769         /* clear memory of buffer (or allocate it if starting a new session) */
770         if (gpd->sbuffer)
771                 memset(gpd->sbuffer, 0, sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX);
772         else
773                 gpd->sbuffer= MEM_callocN(sizeof(tGPspoint)*GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
774         
775         /* reset indices */
776         gpd->sbuffer_size = 0;
777         
778         /* reset flags */
779         gpd->sbuffer_sflag= 0;
780 }
781
782 /* init new painting session */
783 static tGPsdata *gp_session_initpaint (bContext *C)
784 {
785         tGPsdata *p = NULL;
786         bGPdata **gpd_ptr = NULL;
787         ScrArea *curarea= CTX_wm_area(C);
788         ARegion *ar= CTX_wm_region(C);
789         
790         /* make sure the active view (at the starting time) is a 3d-view */
791         if (curarea == NULL) {
792                 if (G.f & G_DEBUG) 
793                         printf("Error: No active view for painting \n");
794                 return NULL;
795         }
796         
797         /* create new context data */
798         p= MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
799         
800         /* pass on current scene */
801         p->scene= CTX_data_scene(C);
802         
803         switch (curarea->spacetype) {
804                 /* supported views first */
805                 case SPACE_VIEW3D:
806                 {
807                         //View3D *v3d= curarea->spacedata.first;
808                         
809                         /* set current area 
810                          *      - must verify that region data is 3D-view (and not something else)
811                          */
812                         p->sa= curarea;
813                         p->ar= ar;
814                         
815                         if (ar->regiondata == NULL) {
816                                 p->status= GP_STATUS_ERROR;
817                                 if (G.f & G_DEBUG)
818                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable \n");
819                                 return p;
820                         }
821                         
822 #if 0 // XXX will this sort of antiquated stuff be restored?
823                         /* check that gpencil data is allowed to be drawn */
824                         if ((v3d->flag2 & V3D_DISPGP)==0) {
825                                 p->status= GP_STATUS_ERROR;
826                                 if (G.f & G_DEBUG) 
827                                         printf("Error: In active view, Grease Pencil not shown \n");
828                                 return p;
829                         }
830 #endif
831                 }
832                         break;
833
834                 case SPACE_NODE:
835                 {
836                         //SpaceNode *snode= curarea->spacedata.first;
837                         
838                         /* set current area */
839                         p->sa= curarea;
840                         p->ar= ar;
841                         p->v2d= &ar->v2d;
842                         
843 #if 0 // XXX will this sort of antiquated stuff be restored?
844                         /* check that gpencil data is allowed to be drawn */
845                         if ((snode->flag & SNODE_DISPGP)==0) {
846                                 p->status= GP_STATUS_ERROR;
847                                 if (G.f & G_DEBUG) 
848                                         printf("Error: In active view, Grease Pencil not shown \n");
849                                 return;
850                         }
851 #endif
852                 }
853                         break;
854 #if 0 // XXX these other spaces will come over time...
855                 case SPACE_SEQ:
856                 {
857                         SpaceSeq *sseq= curarea->spacedata.first;
858                         
859                         /* set current area */
860                         p->sa= curarea;
861                         p->ar= ar;
862                         p->v2d= &ar->v2d;
863                         
864                         /* check that gpencil data is allowed to be drawn */
865                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
866                                 p->status= GP_STATUS_ERROR;
867                                 if (G.f & G_DEBUG) 
868                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil \n");
869                                 return;
870                         }
871                         if ((sseq->flag & SEQ_DRAW_GPENCIL)==0) {
872                                 p->status= GP_STATUS_ERROR;
873                                 if (G.f & G_DEBUG) 
874                                         printf("Error: In active view, Grease Pencil not shown \n");
875                                 return;
876                         }
877                 }
878                         break;  
879 #endif
880                 case SPACE_IMAGE:
881                 {
882                         //SpaceImage *sima= curarea->spacedata.first;
883                         
884                         /* set the current area */
885                         p->sa= curarea;
886                         p->ar= ar;
887                         p->v2d= &ar->v2d;
888                         //p->ibuf= BKE_image_get_ibuf(sima->image, &sima->iuser);
889                         
890 #if 0 // XXX disabled for now
891                         /* check that gpencil data is allowed to be drawn */
892                         if ((sima->flag & SI_DISPGP)==0) {
893                                 p->status= GP_STATUS_ERROR;
894                                 if (G.f & G_DEBUG)
895                                         printf("Error: In active view, Grease Pencil not shown \n");
896                                 return p;
897                         }
898 #endif
899                 }
900                         break;
901
902                 /* unsupported views */
903                 default:
904                 {
905                         p->status= GP_STATUS_ERROR;
906                         if (G.f & G_DEBUG) 
907                                 printf("Error: Active view not appropriate for Grease Pencil drawing \n");
908                         return p;
909                 }
910                         break;
911         }
912         
913         /* get gp-data */
914         gpd_ptr= gpencil_data_get_pointers(C, &p->ownerPtr);
915         if (gpd_ptr == NULL) {
916                 p->status= GP_STATUS_ERROR;
917                 if (G.f & G_DEBUG)
918                         printf("Error: Current context doesn't allow for any Grease Pencil data \n");
919                 return p;
920         }
921         else {
922                 /* if no existing GPencil block exists, add one */
923                 if (*gpd_ptr == NULL)
924                         *gpd_ptr= gpencil_data_addnew("GPencil");
925                 p->gpd= *gpd_ptr;
926         }
927         
928         /* set edit flags - so that buffer will get drawn */
929         G.f |= G_GREASEPENCIL;
930         
931         /* set initial run flag */
932         p->flags |= GP_PAINTFLAG_FIRSTRUN;
933         
934         /* clear out buffer (stored in gp-data), in case something contaminated it */
935         gp_session_validatebuffer(p);
936         
937 #if 0
938         /* set 'default' im2d_settings just in case something that uses this doesn't set it */
939         p->im2d_settings.sizex= 1;
940         p->im2d_settings.sizey= 1;
941 #endif
942         
943         /* return context data for running paint operator */
944         return p;
945 }
946
947 /* cleanup after a painting session */
948 static void gp_session_cleanup (tGPsdata *p)
949 {
950         bGPdata *gpd= (p) ? p->gpd : NULL;
951         
952         /* error checking */
953         if (gpd == NULL)
954                 return;
955         
956         /* free stroke buffer */
957         if (gpd->sbuffer) {
958                 MEM_freeN(gpd->sbuffer);
959                 gpd->sbuffer= NULL;
960         }
961         
962         /* clear flags */
963         gpd->sbuffer_size= 0;
964         gpd->sbuffer_sflag= 0;
965 }
966
967 /* init new stroke */
968 static void gp_paint_initstroke (tGPsdata *p, short paintmode)
969 {       
970         /* get active layer (or add a new one if non-existent) */
971         p->gpl= gpencil_layer_getactive(p->gpd);
972         if (p->gpl == NULL)
973                 p->gpl= gpencil_layer_addnew(p->gpd);
974         if (p->gpl->flag & GP_LAYER_LOCKED) {
975                 p->status= GP_STATUS_ERROR;
976                 if (G.f & G_DEBUG)
977                         printf("Error: Cannot paint on locked layer \n");
978                 return;
979         }
980                 
981         /* get active frame (add a new one if not matching frame) */
982         p->gpf= gpencil_layer_getframe(p->gpl, p->scene->r.cfra, 1);
983         if (p->gpf == NULL) {
984                 p->status= GP_STATUS_ERROR;
985                 if (G.f & G_DEBUG) 
986                         printf("Error: No frame created (gpencil_paint_init) \n");
987                 return;
988         }
989         else
990                 p->gpf->flag |= GP_FRAME_PAINT;
991         
992         /* set 'eraser' for this stroke if using eraser */
993         p->paintmode= paintmode;
994         if (p->paintmode == GP_PAINTMODE_ERASER)
995                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
996         
997         /* check if points will need to be made in view-aligned space */
998         if (p->gpd->flag & GP_DATA_VIEWALIGN) {
999                 switch (p->sa->spacetype) {
1000                         case SPACE_VIEW3D:
1001                         {
1002                                 RegionView3D *rv3d= p->ar->regiondata;
1003                                 float rvec[3];
1004                                 
1005                                 gp_get_3d_reference(p, rvec);
1006                                 initgrabz(rv3d, rvec[0], rvec[1], rvec[2]);
1007                                 
1008                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1009                         }
1010                                 break;
1011                         
1012                         case SPACE_NODE:
1013                         {
1014                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1015                         }
1016                                 break;
1017 #if 0 // XXX other spacetypes to be restored in due course
1018                         case SPACE_SEQ:
1019                         {
1020                                 SpaceSeq *sseq= (SpaceSeq *)p->sa->spacedata.first;
1021                                 int rectx, recty;
1022                                 float zoom, zoomx, zoomy;
1023                                 
1024                                 /* set draw 2d-stroke flag */
1025                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DIMAGE;
1026                                 
1027                                 /* calculate zoom factor */
1028                                 zoom= (float)(SEQ_ZOOM_FAC(sseq->zoom));
1029                                 if (sseq->mainb == SEQ_DRAW_IMG_IMBUF) {
1030                                         zoomx = zoom * ((float)p->scene->r.xasp / (float)p->scene->r.yasp);
1031                                         zoomy = zoom;
1032                                 } 
1033                                 else
1034                                         zoomx = zoomy = zoom;
1035                                 
1036                                 /* calculate rect size to use to calculate the size of the drawing area
1037                                  *      - We use the size of the output image not the size of the ibuf being shown
1038                                  *        as it is too messy getting the ibuf (and could be too slow). This should be
1039                                  *        a reasonable for most cases anyway.
1040                                  */
1041                                 rectx= (p->scene->r.size * p->scene->r.xsch) / 100;
1042                                 recty= (p->scene->r.size * p->scene->r.ysch) / 100; 
1043                                 
1044                                 /* set offset and scale values for opertations to use */
1045                                 p->im2d_settings.sizex= (int)(zoomx * rectx);
1046                                 p->im2d_settings.sizey= (int)(zoomy * recty);
1047                                 p->im2d_settings.offsx= (int)((p->sa->winx-p->im2d_settings.sizex)/2 + sseq->xof);
1048                                 p->im2d_settings.offsy= (int)((p->sa->winy-p->im2d_settings.sizey)/2 + sseq->yof);
1049                         }
1050                                 break;
1051 #endif
1052                         case SPACE_IMAGE:
1053                         {
1054                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1055                         }
1056                                 break;
1057                 }
1058         }
1059 }
1060
1061 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1062 static void gp_paint_strokeend (tGPsdata *p)
1063 {
1064         /* check if doing eraser or not */
1065         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1066                 /* smooth stroke before transferring? */
1067                 gp_stroke_smooth(p);
1068                 
1069                 /* simplify stroke before transferring? */
1070                 gp_stroke_simplify(p);
1071                 
1072                 /* transfer stroke to frame */
1073                 gp_stroke_newfrombuffer(p);
1074         }
1075         
1076         /* clean up buffer now */
1077         gp_session_validatebuffer(p);
1078 }
1079
1080 /* finish off stroke painting operation */
1081 static void gp_paint_cleanup (tGPsdata *p)
1082 {
1083         /* finish off a stroke */
1084         gp_paint_strokeend(p);
1085         
1086         /* "unlock" frame */
1087         p->gpf->flag &= ~GP_FRAME_PAINT;
1088 }
1089
1090 /* ------------------------------- */
1091
1092
1093 static int gpencil_draw_init (bContext *C, wmOperator *op)
1094 {
1095         tGPsdata *p;
1096         int paintmode= RNA_enum_get(op->ptr, "mode");
1097         
1098         /* check context */
1099         p= op->customdata= gp_session_initpaint(C);
1100         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1101                 /* something wasn't set correctly in context */
1102                 gp_session_cleanup(p);
1103                 return 0;
1104         }
1105         
1106         /* init painting data */
1107         gp_paint_initstroke(p, paintmode);
1108         if (p->status == GP_STATUS_ERROR) {
1109                 gp_session_cleanup(p);
1110                 return 0;
1111         }
1112         
1113         /* radius for eraser circle is defined in userprefs now */
1114         p->radius= U.gp_eraser;
1115         
1116         /* everything is now setup ok */
1117         return 1;
1118 }
1119
1120 /* ------------------------------- */
1121
1122 static void gpencil_draw_exit (bContext *C, wmOperator *op)
1123 {
1124         tGPsdata *p= op->customdata;
1125         
1126         /* clear edit flags */
1127         G.f &= ~G_GREASEPENCIL;
1128         
1129         /* restore cursor to indicate end of drawing */
1130         WM_cursor_restore(CTX_wm_window(C));
1131         
1132         /* check size of buffer before cleanup, to determine if anything happened here */
1133         if (p->paintmode == GP_PAINTMODE_ERASER) {
1134                 // TODO clear radial cursor thing
1135                 // XXX draw_sel_circle(NULL, p.mvalo, 0, p.radius, 0);
1136         }
1137         
1138         /* cleanup */
1139         if(gpencil_project_check(p)) {
1140                 View3D *v3d= p->sa->spacedata.first;
1141                 
1142                 /* need to restore the original projection settings before packing up */
1143                 view3d_operator_needs_opengl(C);
1144                 view_autodist_init(p->scene, p->ar, v3d);
1145         }
1146
1147         gp_paint_cleanup(p);
1148         gp_session_cleanup(p);
1149         
1150         /* finally, free the temp data */
1151         MEM_freeN(p);
1152         op->customdata= NULL;
1153 }
1154
1155 static int gpencil_draw_cancel (bContext *C, wmOperator *op)
1156 {
1157         /* this is just a wrapper around exit() */
1158         gpencil_draw_exit(C, op);
1159         return OPERATOR_CANCELLED;
1160 }
1161
1162 /* ------------------------------- */
1163
1164 /* create a new stroke point at the point indicated by the painting context */
1165 static void gpencil_draw_apply (bContext *C, wmOperator *op, tGPsdata *p)
1166 {
1167         /* handle drawing/erasing -> test for erasing first */
1168         if (p->paintmode == GP_PAINTMODE_ERASER) {
1169                 /* do 'live' erasing now */
1170                 gp_stroke_doeraser(p);
1171                 
1172                 /* store used values */
1173                 p->mvalo[0]= p->mval[0];
1174                 p->mvalo[1]= p->mval[1];
1175                 p->opressure= p->pressure;
1176         }
1177         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
1178         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
1179                 /* try to add point */
1180                 short ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1181                 
1182                 /* handle errors while adding point */
1183                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
1184                         /* finish off old stroke */
1185                         gp_paint_strokeend(p);
1186                         
1187                         /* start a new stroke, starting from previous point */
1188                         gp_stroke_addpoint(p, p->mvalo, p->opressure);
1189                         ok= gp_stroke_addpoint(p, p->mval, p->pressure);
1190                 }
1191                 else if (ok == GP_STROKEADD_INVALID) {
1192                         /* the painting operation cannot continue... */
1193                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
1194                         p->status = GP_STATUS_ERROR;
1195                         
1196                         if (G.f & G_DEBUG) 
1197                                 printf("Error: Grease-Pencil Paint - Add Point Invalid \n");
1198                         return;
1199                 }
1200                 
1201                 /* store used values */
1202                 p->mvalo[0]= p->mval[0];
1203                 p->mvalo[1]= p->mval[1];
1204                 p->opressure= p->pressure;
1205         }
1206 }
1207
1208 /* handle draw event */
1209 static void gpencil_draw_apply_event (bContext *C, wmOperator *op, wmEvent *event)
1210 {
1211         tGPsdata *p= op->customdata;
1212         ARegion *ar= p->ar;
1213         PointerRNA itemptr;
1214         float mousef[2];
1215         int tablet=0;
1216
1217         /* convert from window-space to area-space mouse coordintes */
1218         // NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
1219         p->mval[0]= event->x - ar->winrct.xmin + 1;
1220         p->mval[1]= event->y - ar->winrct.ymin + 1;
1221         
1222         /* handle pressure sensitivity (which is supplied by tablets) */
1223         if (event->custom == EVT_DATA_TABLET) {
1224                 wmTabletData *wmtab= event->customdata;
1225                 
1226                 tablet= (wmtab->Active != EVT_TABLET_NONE);
1227                 p->pressure= wmtab->Pressure;
1228                 //if (wmtab->Active == EVT_TABLET_ERASER)
1229                         // TODO... this should get caught by the keymaps which call drawing in the first place
1230         }
1231         else
1232                 p->pressure= 1.0f;
1233         
1234         /* special exception for start of strokes (i.e. maybe for just a dot) */
1235         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1236                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1237                 
1238                 p->mvalo[0]= p->mval[0];
1239                 p->mvalo[1]= p->mval[1];
1240                 p->opressure= p->pressure;
1241                 
1242                 /* special exception here for too high pressure values on first touch in
1243                  *  windows for some tablets, then we just skip first touch ..  
1244                  */
1245                 if (tablet && (p->pressure >= 0.99f))
1246                         return;
1247         }
1248         
1249         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
1250         RNA_collection_add(op->ptr, "stroke", &itemptr);
1251
1252         mousef[0]= p->mval[0];
1253         mousef[1]= p->mval[1];
1254         RNA_float_set_array(&itemptr, "mouse", mousef);
1255         RNA_float_set(&itemptr, "pressure", p->pressure);
1256         
1257         /* apply the current latest drawing point */
1258         gpencil_draw_apply(C, op, p);
1259         
1260         /* force refresh */
1261         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
1262 }
1263
1264 /* ------------------------------- */
1265
1266 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
1267 static int gpencil_draw_exec (bContext *C, wmOperator *op)
1268 {
1269         tGPsdata *p = NULL;
1270         
1271         //printf("GPencil - Starting Re-Drawing \n");
1272         
1273         /* try to initialise context data needed while drawing */
1274         if (!gpencil_draw_init(C, op)) {
1275                 if (op->customdata) MEM_freeN(op->customdata);
1276                 //printf("\tGP - no valid data \n");
1277                 return OPERATOR_CANCELLED;
1278         }
1279         else
1280                 p= op->customdata;
1281         
1282         //printf("\tGP - Start redrawing stroke \n");
1283         
1284         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
1285          * setting the relevant values in context at each step, then applying
1286          */
1287         RNA_BEGIN(op->ptr, itemptr, "stroke") 
1288         {
1289                 float mousef[2];
1290                 
1291                 //printf("\t\tGP - stroke elem \n");
1292                 
1293                 /* get relevant data for this point from stroke */
1294                 RNA_float_get_array(&itemptr, "mouse", mousef);
1295                 p->mval[0] = (short)mousef[0];
1296                 p->mval[1] = (short)mousef[1];
1297                 p->pressure= RNA_float_get(&itemptr, "pressure");
1298                 
1299                 /* if first run, set previous data too */
1300                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
1301                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
1302                         
1303                         p->mvalo[0]= p->mval[0];
1304                         p->mvalo[1]= p->mval[1];
1305                         p->opressure= p->pressure;
1306                 }
1307                 
1308                 /* apply this data as necessary now (as per usual) */
1309                 gpencil_draw_apply(C, op, p);
1310         }
1311         RNA_END;
1312         
1313         //printf("\tGP - done \n");
1314         
1315         /* cleanup */
1316         gpencil_draw_exit(C, op);
1317         
1318         /* refreshes */
1319         WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work  
1320         
1321         /* done */
1322         return OPERATOR_FINISHED;
1323 }
1324
1325 /* ------------------------------- */
1326
1327 /* start of interactive drawing part of operator */
1328 static int gpencil_draw_invoke (bContext *C, wmOperator *op, wmEvent *event)
1329 {
1330         tGPsdata *p = NULL;
1331         wmWindow *win= CTX_wm_window(C);
1332         
1333         if (G.f & G_DEBUG)
1334                 printf("GPencil - Starting Drawing \n");
1335         
1336         /* try to initialise context data needed while drawing */
1337         if (!gpencil_draw_init(C, op)) {
1338                 if (op->customdata) 
1339                         MEM_freeN(op->customdata);
1340                 if (G.f & G_DEBUG)
1341                         printf("\tGP - no valid data \n");
1342                 return OPERATOR_CANCELLED;
1343         }
1344         else
1345                 p= op->customdata;
1346         
1347         // TODO: set any additional settings that we can take from the events?
1348         // TODO? if tablet is erasing, force eraser to be on?
1349         
1350         /* if eraser is on, draw radial aid */
1351         if (p->paintmode == GP_PAINTMODE_ERASER) {
1352                 // TODO: this involves mucking around with radial control, so we leave this for now..
1353         }
1354         
1355         /* set cursor */
1356         if (p->paintmode == GP_PAINTMODE_ERASER)
1357                 WM_cursor_modal(win, BC_CROSSCURSOR); // XXX need a better cursor
1358         else
1359                 WM_cursor_modal(win, BC_PAINTBRUSHCURSOR);
1360         
1361         /* special hack: if there was an initial event, then we were invoked via a hotkey, and 
1362          * painting should start immediately. Otherwise, this was called from a toolbar, in which
1363          * case we should wait for the mouse to be clicked.
1364          */
1365         if (event->type) {
1366                 /* hotkey invoked - start drawing */
1367                 //printf("\tGP - set first spot\n");
1368                 p->status= GP_STATUS_PAINTING;
1369                 
1370                 /* handle the initial drawing - i.e. for just doing a simple dot */
1371                 gpencil_draw_apply_event(C, op, event);
1372         }
1373         else {
1374                 /* toolbar invoked - don't start drawing yet... */
1375                 //printf("\tGP - hotkey invoked... waiting for click-drag\n");
1376         }
1377         
1378         /* add a modal handler for this operator, so that we can then draw continuous strokes */
1379         WM_event_add_modal_handler(C, op);
1380         return OPERATOR_RUNNING_MODAL;
1381 }
1382
1383 /* events handling during interactive drawing part of operator */
1384 static int gpencil_draw_modal (bContext *C, wmOperator *op, wmEvent *event)
1385 {
1386         tGPsdata *p= op->customdata;
1387         
1388         //printf("\tGP - handle modal event...\n");
1389         
1390         switch (event->type) {
1391                 /* end of stroke -> ONLY when a mouse-button release occurs 
1392                  * otherwise, carry on to mouse-move...
1393                  */
1394                 case LEFTMOUSE:
1395                 case RIGHTMOUSE: 
1396                         /* if painting, end stroke */
1397                         if (p->status == GP_STATUS_PAINTING) {
1398                                 /* basically, this should be mouse-button up */
1399                                 //printf("\t\tGP - end of stroke \n");
1400                                 gpencil_draw_exit(C, op);
1401                                 
1402                                 /* one last flush before we're done */
1403                                 WM_event_add_notifier(C, NC_SCREEN|ND_GPENCIL|NA_EDITED, NULL); // XXX need a nicer one that will work  
1404                                 
1405                                 return OPERATOR_FINISHED;
1406                         }
1407                         else {
1408                                 /* not painting, so start stroke (this should be mouse-button down) */
1409                                 //printf("\t\tGP - start stroke \n");
1410                                 p->status= GP_STATUS_PAINTING;
1411                                 /* no break now, since we should immediately start painting */
1412                         }
1413                 
1414                 /* moving mouse - assumed that mouse button is down if in painting status */
1415                 case MOUSEMOVE:
1416                         /* check if we're currently painting */
1417                         if (p->status == GP_STATUS_PAINTING) {
1418                                 /* handle drawing event */
1419                                 //printf("\t\tGP - add point\n");
1420                                 gpencil_draw_apply_event(C, op, event);
1421                                 
1422                                 /* finish painting operation if anything went wrong just now */
1423                                 if (p->status == GP_STATUS_ERROR) {
1424                                         //printf("\t\t\tGP - error done! \n");
1425                                         gpencil_draw_exit(C, op);
1426                                         return OPERATOR_CANCELLED;
1427                                 }
1428                         }
1429                         break;
1430                 
1431                 default:
1432                         //printf("\t\tGP unknown event - %d \n", event->type);
1433                         break;
1434         }
1435         
1436         return OPERATOR_RUNNING_MODAL;
1437 }
1438
1439 /* ------------------------------- */
1440
1441 static EnumPropertyItem prop_gpencil_drawmodes[] = {
1442         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", ""},
1443         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", ""},
1444         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", ""},
1445         {0, NULL, 0, NULL, NULL}
1446 };
1447
1448 void GPENCIL_OT_draw (wmOperatorType *ot)
1449 {
1450         /* identifiers */
1451         ot->name= "Grease Pencil Draw";
1452         ot->idname= "GPENCIL_OT_draw";
1453         ot->description= "Make annotations on the active data.";
1454         
1455         /* api callbacks */
1456         ot->exec= gpencil_draw_exec;
1457         ot->invoke= gpencil_draw_invoke;
1458         ot->modal= gpencil_draw_modal;
1459         ot->cancel= gpencil_draw_cancel;
1460         ot->poll= gpencil_draw_poll;
1461         
1462         /* flags */
1463         ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
1464         
1465         /* settings for drawing */
1466         RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to intepret mouse movements.");
1467         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
1468 }