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