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