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