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