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