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