5879306b06cab11ff209dc69f52d6da9c72f17ea
[blender.git] / source / blender / editors / gpencil / gpencil_paint.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008, Blender Foundation, Joshua Leung
19  * This is a new part of Blender
20  *
21  * Contributor(s): Joshua Leung, Antonio Vazquez
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/gpencil/gpencil_paint.c
27  *  \ingroup edgpencil
28  */
29
30
31 #include <stdio.h>
32 #include <stddef.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <math.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_blenlib.h"
40 #include "BLI_math.h"
41 #include "BLI_utildefines.h"
42 #include "BLI_rand.h"
43 #include "BLI_math_geom.h"
44
45 #include "BLT_translation.h"
46
47 #include "PIL_time.h"
48
49 #include "BKE_main.h"
50 #include "BKE_paint.h"
51 #include "BKE_gpencil.h"
52 #include "BKE_context.h"
53 #include "BKE_global.h"
54 #include "BKE_report.h"
55 #include "BKE_screen.h"
56 #include "BKE_tracking.h"
57 #include "BKE_colortools.h"
58
59 #include "DNA_object_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_gpencil_types.h"
62 #include "DNA_brush_types.h"
63 #include "DNA_windowmanager_types.h"
64
65 #include "UI_view2d.h"
66
67 #include "ED_gpencil.h"
68 #include "ED_screen.h"
69 #include "ED_view3d.h"
70 #include "ED_clip.h"
71
72 #include "BIF_gl.h"
73 #include "BIF_glutil.h"
74
75 #include "RNA_access.h"
76 #include "RNA_define.h"
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 #include "gpencil_intern.h"
82
83 /* ******************************************* */
84 /* 'Globals' and Defines */
85
86 /* values for tGPsdata->status */
87 typedef enum eGPencil_PaintStatus {
88         GP_STATUS_IDLING = 0,   /* stroke isn't in progress yet */
89         GP_STATUS_PAINTING,     /* a stroke is in progress */
90         GP_STATUS_ERROR,        /* something wasn't correctly set up */
91         GP_STATUS_DONE          /* painting done */
92 } eGPencil_PaintStatus;
93
94 /* Return flags for adding points to stroke buffer */
95 typedef enum eGP_StrokeAdd_Result {
96         GP_STROKEADD_INVALID    = -2,       /* error occurred - insufficient info to do so */
97         GP_STROKEADD_OVERFLOW   = -1,       /* error occurred - cannot fit any more points */
98         GP_STROKEADD_NORMAL,                /* point was successfully added */
99         GP_STROKEADD_FULL                   /* cannot add any more points to buffer */
100 } eGP_StrokeAdd_Result;
101
102 /* Runtime flags */
103 typedef enum eGPencil_PaintFlags {
104         GP_PAINTFLAG_FIRSTRUN       = (1 << 0),    /* operator just started */
105         GP_PAINTFLAG_STROKEADDED    = (1 << 1),
106         GP_PAINTFLAG_V3D_ERASER_DEPTH = (1 << 2),
107         GP_PAINTFLAG_SELECTMASK     = (1 << 3),
108 } eGPencil_PaintFlags;
109
110
111 /* Temporary 'Stroke' Operation data
112  *   "p" = op->customdata
113  */
114 typedef struct tGPsdata {
115         Scene *scene;       /* current scene from context */
116         
117         wmWindow *win;      /* window where painting originated */
118         ScrArea *sa;        /* area where painting originated */
119         ARegion *ar;        /* region where painting originated */
120         View2D *v2d;        /* needed for GP_STROKE_2DSPACE */
121         rctf *subrect;      /* for using the camera rect within the 3d view */
122         rctf subrect_data;
123         
124         GP_SpaceConversion gsc; /* settings to pass to gp_points_to_xy() */
125         
126         PointerRNA ownerPtr; /* pointer to owner of gp-datablock */
127         bGPdata *gpd;       /* gp-datablock layer comes from */
128         bGPDlayer *gpl;     /* layer we're working on */
129         bGPDframe *gpf;     /* frame we're working on */
130         
131         char *align_flag;   /* projection-mode flags (toolsettings - eGPencil_Placement_Flags) */
132         
133         eGPencil_PaintStatus status;     /* current status of painting */
134         eGPencil_PaintModes  paintmode;  /* mode for painting */
135         eGPencil_PaintFlags  flags;      /* flags that can get set during runtime (eGPencil_PaintFlags) */
136         
137         short radius;       /* radius of influence for eraser */
138         
139         int mval[2];        /* current mouse-position */
140         int mvalo[2];       /* previous recorded mouse-position */
141         
142         float pressure;     /* current stylus pressure */
143         float opressure;    /* previous stylus pressure */
144         
145         /* These need to be doubles, as (at least under unix) they are in seconds since epoch,
146          * float (and its 7 digits precision) is definitively not enough here!
147          * double, with its 15 digits precision, ensures us millisecond precision for a few centuries at least.
148          */
149         double inittime;    /* Used when converting to path */
150         double curtime;     /* Used when converting to path */
151         double ocurtime;    /* Used when converting to path */
152         
153         float imat[4][4];   /* inverted transformation matrix applying when converting coords from screen-space
154                              * to region space */
155         float mat[4][4];
156         
157         float custom_color[4]; /* custom color - hack for enforcing a particular color for track/mask editing */
158         
159         void *erasercursor; /* radial cursor data for drawing eraser */
160
161         bGPDpalettecolor *palettecolor; /* current palette color */
162         bGPDbrush *brush; /* current drawing brush */
163         short straight[2];   /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
164         int lock_axis;       /* lock drawing to one axis */
165 } tGPsdata;
166
167 /* ------ */
168
169 /* Macros for accessing sensitivity thresholds... */
170 /* minimum number of pixels mouse should move before new point created */
171 #define MIN_MANHATTEN_PX    (U.gp_manhattendist)
172 /* minimum length of new segment before new point can be added */
173 #define MIN_EUCLIDEAN_PX    (U.gp_euclideandist)
174
175 static bool gp_stroke_added_check(tGPsdata *p)
176 {
177         return (p->gpf && p->gpf->strokes.last && p->flags & GP_PAINTFLAG_STROKEADDED);
178 }
179
180 static void gp_stroke_added_enable(tGPsdata *p)
181 {
182         BLI_assert(p->gpf->strokes.last != NULL);
183         p->flags |= GP_PAINTFLAG_STROKEADDED;
184 }
185
186 /* ------ */
187 /* Forward defines for some functions... */
188
189 static void gp_session_validatebuffer(tGPsdata *p);
190
191 /* ******************************************* */
192 /* Context Wrangling... */
193
194 /* check if context is suitable for drawing */
195 static int gpencil_draw_poll(bContext *C)
196 {
197         if (ED_operator_regionactive(C)) {
198                 /* check if current context can support GPencil data */
199                 if (ED_gpencil_data_get_pointers(C, NULL) != NULL) {
200                         /* check if Grease Pencil isn't already running */
201                         if (ED_gpencil_session_active() == 0)
202                                 return 1;
203                         else
204                                 CTX_wm_operator_poll_msg_set(C, "Grease Pencil operator is already active");
205                 }
206                 else {
207                         CTX_wm_operator_poll_msg_set(C, "Failed to find Grease Pencil data to draw into");
208                 }
209         }
210         else {
211                 CTX_wm_operator_poll_msg_set(C, "Active region not set");
212         }
213         
214         return 0;
215 }
216
217 /* check if projecting strokes into 3d-geometry in the 3D-View */
218 static bool gpencil_project_check(tGPsdata *p)
219 {
220         bGPdata *gpd = p->gpd;
221         return ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) && (*p->align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE)));
222 }
223
224 /* ******************************************* */
225 /* Calculations/Conversions */
226
227 /* Utilities --------------------------------- */
228
229 /* get the reference point for stroke-point conversions */
230 static void gp_get_3d_reference(tGPsdata *p, float vec[3])
231 {
232         View3D *v3d = p->sa->spacedata.first;
233         const float *fp = ED_view3d_cursor3d_get(p->scene, v3d);
234         
235         /* the reference point used depends on the owner... */
236 #if 0 /* XXX: disabled for now, since we can't draw relative to the owner yet */
237         if (p->ownerPtr.type == &RNA_Object) {
238                 Object *ob = (Object *)p->ownerPtr.data;
239                 
240                 /* active Object
241                  *  - use relative distance of 3D-cursor from object center
242                  */
243                 sub_v3_v3v3(vec, fp, ob->loc);
244         }
245         else
246 #endif
247         {
248                 /* use 3D-cursor */
249                 copy_v3_v3(vec, fp);
250         }
251 }
252
253 /* Stroke Editing ---------------------------- */
254
255 /* check if the current mouse position is suitable for adding a new point */
256 static bool gp_stroke_filtermval(tGPsdata *p, const int mval[2], int pmval[2])
257 {
258         int dx = abs(mval[0] - pmval[0]);
259         int dy = abs(mval[1] - pmval[1]);
260         
261         /* if buffer is empty, just let this go through (i.e. so that dots will work) */
262         if (p->gpd->sbuffer_size == 0)
263                 return true;
264         
265         /* check if mouse moved at least certain distance on both axes (best case)
266          *      - aims to eliminate some jitter-noise from input when trying to draw straight lines freehand
267          */
268         else if ((dx > MIN_MANHATTEN_PX) && (dy > MIN_MANHATTEN_PX))
269                 return true;
270         
271         /* check if the distance since the last point is significant enough
272          *      - prevents points being added too densely
273          *      - distance here doesn't use sqrt to prevent slowness... we should still be safe from overflows though
274          */
275         else if ((dx * dx + dy * dy) > MIN_EUCLIDEAN_PX * MIN_EUCLIDEAN_PX)
276                 return true;
277         
278         /* mouse 'didn't move' */
279         else
280                 return false;
281 }
282
283 /* reproject the points of the stroke to a plane locked to axis to avoid stroke offset */
284 static void gp_project_points_to_plane(RegionView3D *rv3d, bGPDstroke *gps, const float origin[3], const int axis)
285 {
286         float plane_normal[3];
287         float vn[3];
288
289         float ray[3];
290         float rpoint[3];
291
292         /* normal vector for a plane locked to axis */
293         zero_v3(plane_normal);
294         plane_normal[axis] = 1.0f;
295
296         /* Reproject the points in the plane */
297         for (int i = 0; i < gps->totpoints; i++) {
298                 bGPDspoint *pt = &gps->points[i];
299
300                 /* get a vector from the point with the current view direction of the viewport */
301                 ED_view3d_global_to_vector(rv3d, &pt->x, vn);
302
303                 /* calculate line extrem point to create a ray that cross the plane */
304                 mul_v3_fl(vn, -50.0f);
305                 add_v3_v3v3(ray, &pt->x, vn);
306
307                 /* if the line never intersect, the point is not changed */
308                 if (isect_line_plane_v3(rpoint, &pt->x, ray, origin, plane_normal)) {
309                         copy_v3_v3(&pt->x, rpoint);
310                 }
311         }
312 }
313
314 /* reproject stroke to plane locked to axis in 3d cursor location */
315 static void gp_reproject_toplane(tGPsdata *p, bGPDstroke *gps)
316 {
317         bGPdata *gpd = p->gpd;
318         float origin[3];
319         float cursor[3];
320         RegionView3D *rv3d = p->ar->regiondata;
321
322         /* verify the stroke mode is CURSOR 3d space mode */
323         if ((gpd->sbuffer_sflag & GP_STROKE_3DSPACE) == 0) {
324                 return;
325         }
326         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
327                 return;
328         }
329         if ((*p->align_flag & GP_PROJECT_DEPTH_VIEW) || (*p->align_flag & GP_PROJECT_DEPTH_STROKE)) {
330                 return;
331         }
332
333         /* get 3d cursor and set origin for locked axis only. Uses axis-1 because the enum for XYZ start with 1 */
334         gp_get_3d_reference(p, cursor);
335         zero_v3(origin);
336         origin[p->lock_axis - 1] = cursor[p->lock_axis - 1];
337
338         gp_project_points_to_plane(rv3d, gps, origin, p->lock_axis - 1);
339 }
340
341 /* convert screen-coordinates to buffer-coordinates */
342 /* XXX this method needs a total overhaul! */
343 static void gp_stroke_convertcoords(tGPsdata *p, const int mval[2], float out[3], float *depth)
344 {
345         bGPdata *gpd = p->gpd;
346         
347         /* in 3d-space - pt->x/y/z are 3 side-by-side floats */
348         if (gpd->sbuffer_sflag & GP_STROKE_3DSPACE) {
349                 if (gpencil_project_check(p) && (ED_view3d_autodist_simple(p->ar, mval, out, 0, depth))) {
350                         /* projecting onto 3D-Geometry
351                          *      - nothing more needs to be done here, since view_autodist_simple() has already done it
352                          */
353                 }
354                 else {
355                         float mval_prj[2];
356                         float rvec[3], dvec[3];
357                         float mval_f[2] = {UNPACK2(mval)};
358                         float zfac;
359                 
360                         /* Current method just converts each point in screen-coordinates to
361                          * 3D-coordinates using the 3D-cursor as reference. In general, this
362                          * works OK, but it could of course be improved.
363                          *
364                          * TODO:
365                          *      - investigate using nearest point(s) on a previous stroke as
366                          *        reference point instead or as offset, for easier stroke matching
367                          */
368                         
369                         gp_get_3d_reference(p, rvec);
370                         zfac = ED_view3d_calc_zfac(p->ar->regiondata, rvec, NULL);
371                         
372                         if (ED_view3d_project_float_global(p->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
373                                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
374                                 ED_view3d_win_to_delta(p->ar, mval_f, dvec, zfac);
375                                 sub_v3_v3v3(out, rvec, dvec);
376                         }
377                         else {
378                                 zero_v3(out);
379                         }
380                 }
381         }
382         
383         /* 2d - on 'canvas' (assume that p->v2d is set) */
384         else if ((gpd->sbuffer_sflag & GP_STROKE_2DSPACE) && (p->v2d)) {
385                 UI_view2d_region_to_view(p->v2d, mval[0], mval[1], &out[0], &out[1]);
386                 mul_v3_m4v3(out, p->imat, out);
387         }
388         
389         /* 2d - relative to screen (viewport area) */
390         else {
391                 if (p->subrect == NULL) { /* normal 3D view */
392                         out[0] = (float)(mval[0]) / (float)(p->ar->winx) * 100;
393                         out[1] = (float)(mval[1]) / (float)(p->ar->winy) * 100;
394                 }
395                 else { /* camera view, use subrect */
396                         out[0] = ((mval[0] - p->subrect->xmin) / BLI_rctf_size_x(p->subrect)) * 100;
397                         out[1] = ((mval[1] - p->subrect->ymin) / BLI_rctf_size_y(p->subrect)) * 100;
398                 }
399         }
400 }
401
402 /* apply jitter to stroke */
403 static void gp_brush_jitter(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2], int r_mval[2])
404 {
405         float pressure = pt->pressure;
406         float tmp_pressure = pt->pressure;
407         if (brush->draw_jitter > 0.0f) {
408                 float curvef = curvemapping_evaluateF(brush->cur_jitter, 0, pressure);
409                 tmp_pressure = curvef * brush->draw_sensitivity;
410         }
411         const float exfactor = (brush->draw_jitter + 2.0f) * (brush->draw_jitter + 2.0f); /* exponential value */
412         const float fac = BLI_frand() * exfactor * tmp_pressure;
413         /* Jitter is applied perpendicular to the mouse movement vector (2D space) */
414         float mvec[2], svec[2];
415         /* mouse movement in ints -> floats */
416         if (gpd->sbuffer_size > 1) {
417                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
418                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
419                 normalize_v2(mvec);
420         }
421         else {
422                 mvec[0] = 0.0f;
423                 mvec[1] = 0.0f;
424         }
425         /* rotate mvec by 90 degrees... */
426         svec[0] = -mvec[1];
427         svec[1] = mvec[0];
428         /* scale the displacement by the random, and apply */
429         if (BLI_frand() > 0.5f) {
430                 mul_v2_fl(svec, -fac);
431         }
432         else {
433                 mul_v2_fl(svec, fac);
434         }
435
436         r_mval[0] = mval[0] + svec[0];
437         r_mval[1] = mval[1] + svec[1];
438
439 }
440
441 /* apply pressure change depending of the angle of the stroke to simulate a pen with shape */
442 static void gp_brush_angle(bGPdata *gpd, bGPDbrush *brush, tGPspoint *pt, const int mval[2])
443 {
444         float mvec[2];
445         float sen = brush->draw_angle_factor; /* sensitivity */;
446         float fac;
447         float mpressure;
448
449         float angle = brush->draw_angle; /* default angle of brush in radians */;
450         float v0[2] = { cos(angle), sin(angle) }; /* angle vector of the brush with full thickness */
451
452         /* Apply to first point (only if there are 2 points because before no data to do it ) */
453         if (gpd->sbuffer_size == 1) {
454                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
455                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
456                 normalize_v2(mvec);
457
458                 /* uses > 1.0f to get a smooth transition in first point */
459                 fac = 1.4f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
460                 (pt - 1)->pressure = (pt - 1)->pressure - (sen * fac);
461
462                 CLAMP((pt - 1)->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
463         }
464
465         /* apply from second point */
466         if (gpd->sbuffer_size >= 1) {
467                 mvec[0] = (float)(mval[0] - (pt - 1)->x);
468                 mvec[1] = (float)(mval[1] - (pt - 1)->y);
469                 normalize_v2(mvec);
470
471                 fac = 1.0f - fabs(dot_v2v2(v0, mvec)); /* 0.0 to 1.0 */
472                 /* interpolate with previous point for smoother transitions */
473                 mpressure = interpf(pt->pressure - (sen * fac), (pt - 1)->pressure, 0.3f);
474                 pt->pressure = mpressure; 
475
476                 CLAMP(pt->pressure, GPENCIL_ALPHA_OPACITY_THRESH, 1.0f);
477         }
478
479 }
480
481 /* add current stroke-point to buffer (returns whether point was successfully added) */
482 static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure, double curtime)
483 {
484         bGPdata *gpd = p->gpd;
485         bGPDbrush *brush = p->brush;
486         tGPspoint *pt;
487         
488         /* check painting mode */
489         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
490                 /* straight lines only - i.e. only store start and end point in buffer */
491                 if (gpd->sbuffer_size == 0) {
492                         /* first point in buffer (start point) */
493                         pt = (tGPspoint *)(gpd->sbuffer);
494                         
495                         /* store settings */
496                         copy_v2_v2_int(&pt->x, mval);
497                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
498                         pt->strength = 1.0f;
499                         pt->time = (float)(curtime - p->inittime);
500                         
501                         /* increment buffer size */
502                         gpd->sbuffer_size++;
503                 }
504                 else {
505                         /* just reset the endpoint to the latest value
506                          *      - assume that pointers for this are always valid...
507                          */
508                         pt = ((tGPspoint *)(gpd->sbuffer) + 1);
509                         
510                         /* store settings */
511                         copy_v2_v2_int(&pt->x, mval);
512                         pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
513                         pt->strength = 1.0f;
514                         pt->time = (float)(curtime - p->inittime);
515                         
516                         /* now the buffer has 2 points (and shouldn't be allowed to get any larger) */
517                         gpd->sbuffer_size = 2;
518                 }
519                 
520                 /* can keep carrying on this way :) */
521                 return GP_STROKEADD_NORMAL;
522         }
523         else if (p->paintmode == GP_PAINTMODE_DRAW) { /* normal drawing */
524                 /* check if still room in buffer */
525                 if (gpd->sbuffer_size >= GP_STROKE_BUFFER_MAX)
526                         return GP_STROKEADD_OVERFLOW;
527                 
528                 /* get pointer to destination point */
529                 pt = ((tGPspoint *)(gpd->sbuffer) + gpd->sbuffer_size);
530                 
531                 /* store settings */
532                 /* pressure */
533                 if (brush->flag & GP_BRUSH_USE_PRESSURE) {
534                         float curvef = curvemapping_evaluateF(brush->cur_sensitivity, 0, pressure);
535                         pt->pressure = curvef * brush->draw_sensitivity;
536                 }
537                 else {
538                         pt->pressure = 1.0f;
539                 }
540                 /* Apply jitter to position */
541                 if (brush->draw_jitter > 0.0f) {
542                         int r_mval[2];
543                         gp_brush_jitter(gpd, brush, pt, mval, r_mval);
544                         copy_v2_v2_int(&pt->x, r_mval);
545                 }
546                 else {
547                         copy_v2_v2_int(&pt->x, mval);
548                 }
549                 /* apply randomness to pressure */
550                 if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_PRESSURE)) {
551                         float curvef = curvemapping_evaluateF(brush->cur_sensitivity, 0, pressure);
552                         float tmp_pressure = curvef * brush->draw_sensitivity;
553                         if (BLI_frand() > 0.5f) {
554                                 pt->pressure -= tmp_pressure * brush->draw_random_press * BLI_frand();
555                         }
556                         else {
557                                 pt->pressure += tmp_pressure * brush->draw_random_press * BLI_frand();
558                         }
559                         CLAMP(pt->pressure, GPENCIL_STRENGTH_MIN, 1.0f);
560                 }
561
562                 /* apply angle of stroke to brush size */
563                 if (brush->draw_angle_factor > 0.0f) {
564                         gp_brush_angle(gpd, brush, pt, mval);
565                 }
566
567                 /* color strength */
568                 if (brush->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
569                         float curvef = curvemapping_evaluateF(brush->cur_strength, 0, pressure);
570                         float tmp_pressure = curvef * brush->draw_sensitivity;
571
572                         pt->strength = tmp_pressure * brush->draw_strength;
573                 }
574                 else {
575                         pt->strength = brush->draw_strength;
576                 }
577                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
578
579                 /* apply randomness to color strength */
580                 if ((brush->draw_random_press > 0.0f) && (brush->flag & GP_BRUSH_USE_RANDOM_STRENGTH)) {
581                         if (BLI_frand() > 0.5f) {
582                                 pt->strength -= pt->strength * brush->draw_random_press * BLI_frand();
583                         }
584                         else {
585                                 pt->strength += pt->strength * brush->draw_random_press * BLI_frand();
586                         }
587                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
588                 }
589
590                 /* point time */
591                 pt->time = (float)(curtime - p->inittime);
592                 
593                 /* increment counters */
594                 gpd->sbuffer_size++;
595                 
596                 /* check if another operation can still occur */
597                 if (gpd->sbuffer_size == GP_STROKE_BUFFER_MAX)
598                         return GP_STROKEADD_FULL;
599                 else
600                         return GP_STROKEADD_NORMAL;
601         }
602         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
603                 
604                 bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
605                 /* get pointer to destination point */
606                 pt = (tGPspoint *)(gpd->sbuffer);
607                 
608                 /* store settings */
609                 copy_v2_v2_int(&pt->x, mval);
610                 pt->pressure = 1.0f; /* T44932 - Pressure vals are unreliable, so ignore for now */
611                 pt->strength = 1.0f;
612                 pt->time = (float)(curtime - p->inittime);
613                 
614                 /* if there's stroke for this poly line session add (or replace last) point
615                  * to stroke. This allows to draw lines more interactively (see new segment
616                  * during mouse slide, e.g.)
617                  */
618                 if (gp_stroke_added_check(p)) {
619                         bGPDstroke *gps = p->gpf->strokes.last;
620                         bGPDspoint *pts;
621                         
622                         /* first time point is adding to temporary buffer -- need to allocate new point in stroke */
623                         if (gpd->sbuffer_size == 0) {
624                                 gps->points = MEM_reallocN(gps->points, sizeof(bGPDspoint) * (gps->totpoints + 1));
625                                 gps->totpoints++;
626                         }
627                         
628                         pts = &gps->points[gps->totpoints - 1];
629                         
630                         /* special case for poly lines: normally,
631                          * depth is needed only when creating new stroke from buffer,
632                          * but poly lines are converting to stroke instantly,
633                          * so initialize depth buffer before converting coordinates
634                          */
635                         if (gpencil_project_check(p)) {
636                                 View3D *v3d = p->sa->spacedata.first;
637                                 
638                                 view3d_region_operator_needs_opengl(p->win, p->ar);
639                                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
640                         }
641                         
642                         /* convert screen-coordinates to appropriate coordinates (and store them) */
643                         gp_stroke_convertcoords(p, &pt->x, &pts->x, NULL);
644                         /* if axis locked, reproject to plane locked (only in 3d space) */
645                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
646                                 gp_reproject_toplane(p, gps);
647                         }
648                         /* if parented change position relative to parent object */
649                         if (gpl->parent != NULL) {
650                                 gp_apply_parent_point(gpl, pts);
651                         }
652                         /* copy pressure and time */
653                         pts->pressure = pt->pressure;
654                         pts->strength = pt->strength;
655                         pts->time = pt->time;
656                         /* force fill recalc */
657                         gps->flag |= GP_STROKE_RECALC_CACHES;
658                 }
659                 
660                 /* increment counters */
661                 if (gpd->sbuffer_size == 0)
662                         gpd->sbuffer_size++;
663                 
664                 return GP_STROKEADD_NORMAL;
665         }
666
667         /* return invalid state for now... */
668         return GP_STROKEADD_INVALID;
669 }
670
671 /* simplify a stroke (in buffer) before storing it
672  *      - applies a reverse Chaikin filter
673  *      - code adapted from etch-a-ton branch (editarmature_sketch.c)
674  */
675 static void gp_stroke_simplify(tGPsdata *p)
676 {
677         bGPdata *gpd = p->gpd;
678         tGPspoint *old_points = (tGPspoint *)gpd->sbuffer;
679         short num_points = gpd->sbuffer_size;
680         short flag = gpd->sbuffer_sflag;
681         short i, j;
682         
683         /* only simplify if simplification is enabled, and we're not doing a straight line */
684         if (!(U.gp_settings & GP_PAINT_DOSIMPLIFY) || (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT))
685                 return;
686         
687         /* don't simplify if less than 4 points in buffer */
688         if ((num_points <= 4) || (old_points == NULL))
689                 return;
690         
691         /* clear buffer (but don't free mem yet) so that we can write to it
692          *      - firstly set sbuffer to NULL, so a new one is allocated
693          *      - secondly, reset flag after, as it gets cleared auto
694          */
695         gpd->sbuffer = NULL;
696         gp_session_validatebuffer(p);
697         gpd->sbuffer_sflag = flag;
698         
699 /* macro used in loop to get position of new point
700  *      - used due to the mixture of datatypes in use here
701  */
702 #define GP_SIMPLIFY_AVPOINT(offs, sfac) \
703         { \
704                 co[0] += (float)(old_points[offs].x * sfac); \
705                 co[1] += (float)(old_points[offs].y * sfac); \
706                 pressure += old_points[offs].pressure * sfac; \
707                 time += old_points[offs].time * sfac; \
708         } (void)0
709         
710         /* XXX Here too, do not lose start and end points! */
711         gp_stroke_addpoint(p, &old_points->x, old_points->pressure, p->inittime + (double)old_points->time);
712         for (i = 0, j = 0; i < num_points; i++) {
713                 if (i - j == 3) {
714                         float co[2], pressure, time;
715                         int mco[2];
716                         
717                         /* initialize values */
718                         co[0] = 0.0f;
719                         co[1] = 0.0f;
720                         pressure = 0.0f;
721                         time = 0.0f;
722                         
723                         /* using macro, calculate new point */
724                         GP_SIMPLIFY_AVPOINT(j, -0.25f);
725                         GP_SIMPLIFY_AVPOINT(j + 1, 0.75f);
726                         GP_SIMPLIFY_AVPOINT(j + 2, 0.75f);
727                         GP_SIMPLIFY_AVPOINT(j + 3, -0.25f);
728                         
729                         /* set values for adding */
730                         mco[0] = (int)co[0];
731                         mco[1] = (int)co[1];
732                         
733                         /* ignore return values on this... assume to be ok for now */
734                         gp_stroke_addpoint(p, mco, pressure, p->inittime + (double)time);
735                         
736                         j += 2;
737                 }
738         }
739         gp_stroke_addpoint(p, &old_points[num_points - 1].x, old_points[num_points - 1].pressure,
740                            p->inittime + (double)old_points[num_points - 1].time);
741         
742         /* free old buffer */
743         MEM_freeN(old_points);
744 }
745
746 /* make a new stroke from the buffer data */
747 static void gp_stroke_newfrombuffer(tGPsdata *p)
748 {
749         bGPdata *gpd = p->gpd;
750         bGPDlayer *gpl = p->gpl;
751         bGPDstroke *gps;
752         bGPDspoint *pt;
753         tGPspoint *ptc;
754         bGPDbrush *brush = p->brush;
755         ToolSettings *ts = p->scene->toolsettings;
756         
757         int i, totelem;
758         /* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
759         int depth_margin = (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 4 : 0;
760         
761         /* get total number of points to allocate space for
762          *      - drawing straight-lines only requires the endpoints
763          */
764         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT)
765                 totelem = (gpd->sbuffer_size >= 2) ? 2 : gpd->sbuffer_size;
766         else
767                 totelem = gpd->sbuffer_size;
768         
769         /* exit with error if no valid points from this stroke */
770         if (totelem == 0) {
771                 if (G.debug & G_DEBUG)
772                         printf("Error: No valid points in stroke buffer to convert (tot=%d)\n", gpd->sbuffer_size);
773                 return;
774         }
775         
776         /* special case for poly line -- for already added stroke during session
777          * coordinates are getting added to stroke immediately to allow more
778          * interactive behavior
779          */
780         if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
781                 if (gp_stroke_added_check(p)) {
782                         return;
783                 }
784         }
785         
786         /* allocate memory for a new stroke */
787         gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
788         
789         /* copy appropriate settings for stroke */
790         gps->totpoints = totelem;
791         gps->thickness = brush->thickness;
792         gps->flag = gpd->sbuffer_sflag;
793         gps->inittime = p->inittime;
794         
795         /* enable recalculation flag by default (only used if hq fill) */
796         gps->flag |= GP_STROKE_RECALC_CACHES;
797
798         /* allocate enough memory for a continuous array for storage points */
799         int sublevel = brush->sublevel;
800         int new_totpoints = gps->totpoints;
801         
802         for (i = 0; i < sublevel; i++) {
803                 new_totpoints += new_totpoints - 1;
804         }
805         gps->points = MEM_callocN(sizeof(bGPDspoint) * new_totpoints, "gp_stroke_points");
806         /* initialize triangle memory to dummy data */
807         gps->triangles = MEM_callocN(sizeof(bGPDtriangle), "GP Stroke triangulation");
808         gps->flag |= GP_STROKE_RECALC_CACHES;
809         gps->tot_triangles = 0;
810         /* set pointer to first non-initialized point */
811         pt = gps->points + (gps->totpoints - totelem);
812         
813         /* copy points from the buffer to the stroke */
814         if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
815                 /* straight lines only -> only endpoints */
816                 {
817                         /* first point */
818                         ptc = gpd->sbuffer;
819                         
820                         /* convert screen-coordinates to appropriate coordinates (and store them) */
821                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
822                         /* if axis locked, reproject to plane locked (only in 3d space) */
823                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
824                                 gp_reproject_toplane(p, gps);
825                         }
826                         /* if parented change position relative to parent object */
827                         if (gpl->parent != NULL) {
828                                 gp_apply_parent_point(gpl, pt);
829                         }
830                         /* copy pressure and time */
831                         pt->pressure = ptc->pressure;
832                         pt->strength = ptc->strength;
833                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
834                         pt->time = ptc->time;
835                         
836                         pt++;
837                 }
838                 
839                 if (totelem == 2) {
840                         /* last point if applicable */
841                         ptc = ((tGPspoint *)gpd->sbuffer) + (gpd->sbuffer_size - 1);
842                         
843                         /* convert screen-coordinates to appropriate coordinates (and store them) */
844                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
845                         /* if axis locked, reproject to plane locked (only in 3d space) */
846                         if (p->lock_axis > GP_LOCKAXIS_NONE) {
847                                 gp_reproject_toplane(p, gps);
848                         }
849                         /* if parented change position relative to parent object */
850                         if (gpl->parent != NULL) {
851                                 gp_apply_parent_point(gpl, pt);
852                         }
853
854                         /* copy pressure and time */
855                         pt->pressure = ptc->pressure;
856                         pt->strength = ptc->strength;
857                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
858                         pt->time = ptc->time;
859                 }
860         }
861         else if (p->paintmode == GP_PAINTMODE_DRAW_POLY) {
862                 /* first point */
863                 ptc = gpd->sbuffer;
864                 
865                 /* convert screen-coordinates to appropriate coordinates (and store them) */
866                 gp_stroke_convertcoords(p, &ptc->x, &pt->x, NULL);
867                 /* if axis locked, reproject to plane locked (only in 3d space) */
868                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
869                         gp_reproject_toplane(p, gps);
870                 }
871                 /* if parented change position relative to parent object */
872                 if (gpl->parent != NULL) {
873                         gp_apply_parent_point(gpl, pt);
874                 }
875                 /* copy pressure and time */
876                 pt->pressure = ptc->pressure;
877                 pt->strength = ptc->strength;
878                 CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
879                 pt->time = ptc->time;
880         }
881         else {
882                 float *depth_arr = NULL;
883
884                 /* get an array of depths, far depths are blended */
885                 if (gpencil_project_check(p)) {
886                         int mval[2], mval_prev[2] = { 0 };
887                         int interp_depth = 0;
888                         int found_depth = 0;
889
890                         depth_arr = MEM_mallocN(sizeof(float) * gpd->sbuffer_size, "depth_points");
891
892                         for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size; i++, ptc++, pt++) {
893                                 copy_v2_v2_int(mval, &ptc->x);
894
895                                 if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
896                                         (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
897                                 {
898                                         interp_depth = true;
899                                 }
900                                 else {
901                                         found_depth = true;
902                                 }
903
904                                 copy_v2_v2_int(mval_prev, mval);
905                         }
906
907                         if (found_depth == false) {
908                                 /* eeh... not much we can do.. :/, ignore depth in this case, use the 3D cursor */
909                                 for (i = gpd->sbuffer_size - 1; i >= 0; i--)
910                                         depth_arr[i] = 0.9999f;
911                         }
912                         else {
913                                 if (p->gpd->flag & GP_DATA_DEPTH_STROKE_ENDPOINTS) {
914                                         /* remove all info between the valid endpoints */
915                                         int first_valid = 0;
916                                         int last_valid = 0;
917
918                                         for (i = 0; i < gpd->sbuffer_size; i++) {
919                                                 if (depth_arr[i] != FLT_MAX)
920                                                         break;
921                                         }
922                                         first_valid = i;
923
924                                         for (i = gpd->sbuffer_size - 1; i >= 0; i--) {
925                                                 if (depth_arr[i] != FLT_MAX)
926                                                         break;
927                                         }
928                                         last_valid = i;
929
930                                         /* invalidate non-endpoints, so only blend between first and last */
931                                         for (i = first_valid + 1; i < last_valid; i++)
932                                                 depth_arr[i] = FLT_MAX;
933
934                                         interp_depth = true;
935                                 }
936
937                                 if (interp_depth) {
938                                         interp_sparse_array(depth_arr, gpd->sbuffer_size, FLT_MAX);
939                                 }
940                         }
941                 }
942
943
944                 pt = gps->points;
945
946                 /* convert all points (normal behavior) */
947                 for (i = 0, ptc = gpd->sbuffer; i < gpd->sbuffer_size && ptc; i++, ptc++, pt++) {
948                         /* convert screen-coordinates to appropriate coordinates (and store them) */
949                         gp_stroke_convertcoords(p, &ptc->x, &pt->x, depth_arr ? depth_arr + i : NULL);
950
951                         /* copy pressure and time */
952                         pt->pressure = ptc->pressure;
953                         pt->strength = ptc->strength;
954                         CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
955                         pt->time = ptc->time;
956                 }
957
958                 /* subdivide the stroke */
959                 if (sublevel > 0) {
960                         int totpoints = gps->totpoints;
961                         for (i = 0; i < sublevel; i++) {
962                                 /* we're adding one new point between each pair of verts on each step */
963                                 totpoints += totpoints - 1;
964
965                                 gp_subdivide_stroke(gps, totpoints);
966                         }
967                 }
968                 /* apply randomness to stroke */
969                 if (brush->draw_random_sub > 0.0f) {
970                         gp_randomize_stroke(gps, brush);
971                 }
972
973                 /* smooth stroke after subdiv - only if there's something to do
974                  * for each iteration, the factor is reduced to get a better smoothing without changing too much
975                  * the original stroke
976                  */
977                 if (brush->draw_smoothfac > 0.0f) {
978                         float reduce = 0.0f;
979                         for (int r = 0; r < brush->draw_smoothlvl; ++r) {
980                                 for (i = 0; i < gps->totpoints; i++) {
981                                         /* NOTE: No pressure smoothing, or else we get annoying thickness changes while drawing... */
982                                         gp_smooth_stroke(gps, i, brush->draw_smoothfac - reduce, false);
983                                 }
984                                 reduce += 0.25f;  // reduce the factor
985                         }
986                 }
987
988                 /* if axis locked, reproject to plane locked (only in 3d space) */
989                 if (p->lock_axis > GP_LOCKAXIS_NONE) {
990                         gp_reproject_toplane(p, gps);
991                 }
992                 /* if parented change position relative to parent object */
993                 if (gpl->parent != NULL) {
994                         gp_apply_parent(gpl, gps);
995                 }
996
997                 if (depth_arr)
998                         MEM_freeN(depth_arr);
999         }
1000         /* Save palette color */
1001         bGPDpalette *palette = BKE_gpencil_palette_getactive(p->gpd);
1002         bGPDpalettecolor *palcolor = BKE_gpencil_palettecolor_getactive(palette);
1003         gps->palcolor = palcolor;
1004         BLI_strncpy(gps->colorname, palcolor->info, sizeof(gps->colorname));
1005
1006         /* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head 
1007         * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
1008         * when drawing the background
1009         */
1010         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
1011                 BLI_addhead(&p->gpf->strokes, gps);
1012         }
1013         else {
1014                 BLI_addtail(&p->gpf->strokes, gps);
1015         }
1016         gp_stroke_added_enable(p);
1017 }
1018
1019 /* --- 'Eraser' for 'Paint' Tool ------ */
1020
1021 /* which which point is infront (result should only be used for comparison) */
1022 static float view3d_point_depth(const RegionView3D *rv3d, const float co[3])
1023 {
1024         if (rv3d->is_persp) {
1025                 return ED_view3d_calc_zfac(rv3d, co, NULL);
1026         }
1027         else {
1028                 return -dot_v3v3(rv3d->viewinv[2], co);
1029         }
1030 }
1031
1032 /* only erase stroke points that are visible */
1033 static bool gp_stroke_eraser_is_occluded(tGPsdata *p, const bGPDspoint *pt, const int x, const int y)
1034 {
1035         if ((p->sa->spacetype == SPACE_VIEW3D) &&
1036             (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH))
1037         {
1038                 RegionView3D *rv3d = p->ar->regiondata;
1039                 bGPDlayer *gpl = p->gpl;
1040
1041                 const int mval[2] = {x, y};
1042                 float mval_3d[3];
1043                 float fpt[3];
1044
1045                 float diff_mat[4][4];
1046                 /* calculate difference matrix if parent object */
1047                 ED_gpencil_parent_location(gpl, diff_mat);
1048
1049                 if (ED_view3d_autodist_simple(p->ar, mval, mval_3d, 0, NULL)) {
1050                         const float depth_mval = view3d_point_depth(rv3d, mval_3d);
1051
1052                         mul_v3_m4v3(fpt, diff_mat, &pt->x);
1053                         const float depth_pt   = view3d_point_depth(rv3d, fpt);
1054                         
1055                         if (depth_pt > depth_mval) {
1056                                 return true;
1057                         }
1058                 }
1059         }
1060         return false;
1061 }
1062
1063 /* apply a falloff effect to brush strength, based on distance */
1064 static float gp_stroke_eraser_calc_influence(tGPsdata *p, const int mval[2], const int radius, const int co[2])
1065 {
1066         /* Linear Falloff... */
1067         float distance = (float)len_v2v2_int(mval, co);
1068         float fac;
1069         
1070         CLAMP(distance, 0.0f, (float)radius);
1071         fac = 1.0f - (distance / (float)radius);
1072         
1073         /* Control this further using pen pressure */
1074         fac *= p->pressure;
1075         
1076         /* Return influence factor computed here */
1077         return fac;
1078 }
1079
1080 /* eraser tool - evaluation per stroke */
1081 /* TODO: this could really do with some optimization (KD-Tree/BVH?) */
1082 static void gp_stroke_eraser_dostroke(tGPsdata *p,
1083                                       bGPDlayer *gpl, bGPDframe *gpf, bGPDstroke *gps,
1084                                       const int mval[2], const int mvalo[2],
1085                                       const int radius, const rcti *rect)
1086 {
1087         bGPDspoint *pt1, *pt2;
1088         int pc1[2] = {0};
1089         int pc2[2] = {0};
1090         int i;
1091         float diff_mat[4][4];
1092
1093         /* calculate difference matrix if parent object */
1094         if (gpl->parent != NULL) {
1095                 ED_gpencil_parent_location(gpl, diff_mat);
1096         }
1097
1098         if (gps->totpoints == 0) {
1099                 /* just free stroke */
1100                 if (gps->points)
1101                         MEM_freeN(gps->points);
1102                 if (gps->triangles)
1103                         MEM_freeN(gps->triangles);
1104                 BLI_freelinkN(&gpf->strokes, gps);
1105         }
1106         else if (gps->totpoints == 1) {
1107                 /* only process if it hasn't been masked out... */
1108                 if (!(p->flags & GP_PAINTFLAG_SELECTMASK) || (gps->points->flag & GP_SPOINT_SELECT)) {
1109                         if (gpl->parent == NULL) {
1110                                 gp_point_to_xy(&p->gsc, gps, gps->points, &pc1[0], &pc1[1]);
1111                         }
1112                         else {
1113                                 bGPDspoint pt_temp;
1114                                 gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1115                                 gp_point_to_xy(&p->gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1116                         }
1117                         /* do boundbox check first */
1118                         if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1119                                 /* only check if point is inside */
1120                                 if (len_v2v2_int(mval, pc1) <= radius) {
1121                                         /* free stroke */
1122                                         // XXX: pressure sensitive eraser should apply here too?
1123                                         MEM_freeN(gps->points);
1124                                         if (gps->triangles)
1125                                                 MEM_freeN(gps->triangles);
1126                                         BLI_freelinkN(&gpf->strokes, gps);
1127                                 }
1128                         }
1129                 }
1130         }
1131         else {
1132                 /* Pressure threshold at which stroke should be culled: Calculated as pressure value
1133                  * below which we would have invisible strokes
1134                  */
1135                 const float cull_thresh = (gps->thickness) ?  1.0f / ((float)gps->thickness)  : 1.0f;
1136                 
1137                 /* Amount to decrease the pressure of each point with each stroke */
1138                 // TODO: Fetch from toolsettings, or compute based on thickness instead?
1139                 const float strength = 0.1f;
1140                 
1141                 /* Perform culling? */
1142                 bool do_cull = false;
1143                 
1144                 
1145                 /* Clear Tags
1146                  *
1147                  * Note: It's better this way, as we are sure that
1148                  * we don't miss anything, though things will be
1149                  * slightly slower as a result
1150                  */
1151                 for (i = 0; i < gps->totpoints; i++) {
1152                         bGPDspoint *pt = &gps->points[i];
1153                         pt->flag &= ~GP_SPOINT_TAG;
1154                 }
1155                 
1156                 /* First Pass: Loop over the points in the stroke
1157                  *   1) Thin out parts of the stroke under the brush
1158                  *   2) Tag "too thin" parts for removal (in second pass)
1159                  */
1160                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1161                         /* get points to work with */
1162                         pt1 = gps->points + i;
1163                         pt2 = gps->points + i + 1;
1164
1165                         /* only process if it hasn't been masked out... */
1166                         if ((p->flags & GP_PAINTFLAG_SELECTMASK) && !(gps->points->flag & GP_SPOINT_SELECT))
1167                                 continue;
1168                         
1169                         if (gpl->parent == NULL) {
1170                                 gp_point_to_xy(&p->gsc, gps, pt1, &pc1[0], &pc1[1]);
1171                                 gp_point_to_xy(&p->gsc, gps, pt2, &pc2[0], &pc2[1]);
1172                         }
1173                         else {
1174                                 bGPDspoint npt;
1175                                 gp_point_to_parent_space(pt1, diff_mat, &npt);
1176                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc1[0], &pc1[1]);
1177
1178                                 gp_point_to_parent_space(pt2, diff_mat, &npt);
1179                                 gp_point_to_xy(&p->gsc, gps, &npt, &pc2[0], &pc2[1]);
1180                         }
1181
1182                         /* Check that point segment of the boundbox of the eraser stroke */
1183                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1184                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1185                         {
1186                                 /* Check if point segment of stroke had anything to do with
1187                                  * eraser region  (either within stroke painted, or on its lines)
1188                                  *  - this assumes that linewidth is irrelevant
1189                                  */
1190                                 if (gp_stroke_inside_circle(mval, mvalo, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
1191                                         if ((gp_stroke_eraser_is_occluded(p, pt1, pc1[0], pc1[1]) == false) ||
1192                                             (gp_stroke_eraser_is_occluded(p, pt2, pc2[0], pc2[1]) == false))
1193                                         {
1194                                                 /* Point is affected: */
1195                                                 /* 1) Adjust thickness
1196                                                  *  - Influence of eraser falls off with distance from the middle of the eraser
1197                                                  *  - Second point gets less influence, as it might get hit again in the next segment
1198                                                  */
1199                                                 pt1->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc1) * strength;
1200                                                 pt2->pressure -= gp_stroke_eraser_calc_influence(p, mval, radius, pc2) * strength / 2.0f;
1201                                                 
1202                                                 /* 2) Tag any point with overly low influence for removal in the next pass */
1203                                                 if (pt1->pressure < cull_thresh) {
1204                                                         pt1->flag |= GP_SPOINT_TAG;
1205                                                         do_cull = true;
1206                                                 }
1207                                                 if (pt2->pressure < cull_thresh) {
1208                                                         pt2->flag |= GP_SPOINT_TAG;
1209                                                         do_cull = true;
1210                                                 }
1211                                         }
1212                                 }
1213                         }
1214                 }
1215                 
1216                 /* Second Pass: Remove any points that are tagged */
1217                 if (do_cull) {
1218                         gp_stroke_delete_tagged_points(gpf, gps, gps->next, GP_SPOINT_TAG);
1219                 }
1220         }
1221 }
1222
1223 /* erase strokes which fall under the eraser strokes */
1224 static void gp_stroke_doeraser(tGPsdata *p)
1225 {
1226         bGPDlayer *gpl;
1227         bGPDstroke *gps, *gpn;
1228         rcti rect;
1229         
1230         /* rect is rectangle of eraser */
1231         rect.xmin = p->mval[0] - p->radius;
1232         rect.ymin = p->mval[1] - p->radius;
1233         rect.xmax = p->mval[0] + p->radius;
1234         rect.ymax = p->mval[1] + p->radius;
1235         
1236         if (p->sa->spacetype == SPACE_VIEW3D) {
1237                 if (p->flags & GP_PAINTFLAG_V3D_ERASER_DEPTH) {
1238                         View3D *v3d = p->sa->spacedata.first;
1239                         
1240                         view3d_region_operator_needs_opengl(p->win, p->ar);
1241                         ED_view3d_autodist_init(p->scene, p->ar, v3d, 0);
1242                 }
1243         }
1244         
1245         /* loop over all layers too, since while it's easy to restrict editing to
1246          * only a subset of layers, it is harder to perform the same erase operation
1247          * on multiple layers...
1248          */
1249         for (gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1250                 bGPDframe *gpf = gpl->actframe;
1251                 
1252                 /* only affect layer if it's editable (and visible) */
1253                 if (gpencil_layer_is_editable(gpl) == false) {
1254                         continue;
1255                 }
1256                 else if (gpf == NULL) {
1257                         continue;
1258                 }
1259                 
1260                 /* loop over strokes, checking segments for intersections */
1261                 for (gps = gpf->strokes.first; gps; gps = gpn) {
1262                         gpn = gps->next;
1263                         /* check if the color is editable */
1264                         if (ED_gpencil_stroke_color_use(gpl, gps) == false) {
1265                                 continue;
1266                         }
1267                         /* Not all strokes in the datablock may be valid in the current editor/context
1268                          * (e.g. 2D space strokes in the 3D view, if the same datablock is shared)
1269                          */
1270                         if (ED_gpencil_stroke_can_use_direct(p->sa, gps)) {
1271                                 gp_stroke_eraser_dostroke(p, gpl, gpf, gps, p->mval, p->mvalo, p->radius, &rect);
1272                         }
1273                 }
1274         }
1275 }
1276
1277 /* ******************************************* */
1278 /* Sketching Operator */
1279
1280 /* clear the session buffers (call this before AND after a paint operation) */
1281 static void gp_session_validatebuffer(tGPsdata *p)
1282 {
1283         bGPdata *gpd = p->gpd;
1284         
1285         /* clear memory of buffer (or allocate it if starting a new session) */
1286         if (gpd->sbuffer) {
1287                 /* printf("\t\tGP - reset sbuffer\n"); */
1288                 memset(gpd->sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
1289         }
1290         else {
1291                 /* printf("\t\tGP - allocate sbuffer\n"); */
1292                 gpd->sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
1293         }
1294         
1295         /* reset indices */
1296         gpd->sbuffer_size = 0;
1297         
1298         /* reset flags */
1299         gpd->sbuffer_sflag = 0;
1300         
1301         /* reset inittime */
1302         p->inittime = 0.0;
1303 }
1304
1305 /* create a new palette color */
1306 static bGPDpalettecolor *gp_create_new_color(bGPDpalette *palette)
1307 {
1308         bGPDpalettecolor *palcolor;
1309
1310         palcolor = BKE_gpencil_palettecolor_addnew(palette, DATA_("Color"), true);
1311         
1312         return palcolor;
1313 }
1314
1315 /* initialize a drawing brush */
1316 static void gp_init_drawing_brush(ToolSettings *ts, tGPsdata *p)
1317 {
1318         bGPDbrush *brush;
1319
1320         /* if not exist, create a new one */
1321         if (BLI_listbase_is_empty(&ts->gp_brushes)) {
1322                 /* create new brushes */
1323                 BKE_gpencil_brush_init_presets(ts);
1324                 brush = BKE_gpencil_brush_getactive(ts);
1325         }
1326         else {
1327                 /* Use the current */
1328                 brush = BKE_gpencil_brush_getactive(ts);
1329         }
1330         /* be sure curves are initializated */
1331         curvemapping_initialize(brush->cur_sensitivity);
1332         curvemapping_initialize(brush->cur_strength);
1333         curvemapping_initialize(brush->cur_jitter);
1334
1335         /* asign to temp tGPsdata */
1336         p->brush = brush;
1337 }
1338
1339
1340 /* initialize a paint palette brush and a default color if not exist */
1341 static void gp_init_palette(tGPsdata *p)
1342 {
1343         bGPdata *gpd;
1344         bGPDpalette *palette;
1345         bGPDpalettecolor *palcolor;
1346
1347         gpd = p->gpd;
1348
1349         /* if not exist, create a new palette */
1350         if (BLI_listbase_is_empty(&gpd->palettes)) {
1351                 /* create new palette */
1352                 palette = BKE_gpencil_palette_addnew(gpd, DATA_("GP_Palette"), true);
1353                 /* now create a default color */
1354                 palcolor = gp_create_new_color(palette);
1355         }
1356         else {
1357                 /* Use the current palette and color */
1358                 palette = BKE_gpencil_palette_getactive(gpd);
1359                 /* the palette needs one color */
1360                 if (BLI_listbase_is_empty(&palette->colors)) {
1361                         palcolor = gp_create_new_color(palette);
1362                 }
1363                 else {
1364                         palcolor = BKE_gpencil_palettecolor_getactive(palette);
1365                 }
1366                 /* in some situations can be null, so use first */
1367                 if (palcolor == NULL) {
1368                         BKE_gpencil_palettecolor_setactive(palette, palette->colors.first);
1369                         palcolor = palette->colors.first;
1370                 }
1371         }
1372
1373         /* asign to temp tGPsdata */
1374         p->palettecolor = palcolor;
1375 }
1376
1377 /* (re)init new painting data */
1378 static bool gp_session_initdata(bContext *C, tGPsdata *p)
1379 {
1380         bGPdata **gpd_ptr = NULL;
1381         ScrArea *curarea = CTX_wm_area(C);
1382         ARegion *ar = CTX_wm_region(C);
1383         ToolSettings *ts = CTX_data_tool_settings(C);
1384         
1385         /* make sure the active view (at the starting time) is a 3d-view */
1386         if (curarea == NULL) {
1387                 p->status = GP_STATUS_ERROR;
1388                 if (G.debug & G_DEBUG)
1389                         printf("Error: No active view for painting\n");
1390                 return 0;
1391         }
1392         
1393         /* pass on current scene and window */
1394         p->scene = CTX_data_scene(C);
1395         p->win = CTX_wm_window(C);
1396         
1397         unit_m4(p->imat);
1398         unit_m4(p->mat);
1399         
1400         switch (curarea->spacetype) {
1401                 /* supported views first */
1402                 case SPACE_VIEW3D:
1403                 {
1404                         /* View3D *v3d = curarea->spacedata.first; */
1405                         /* RegionView3D *rv3d = ar->regiondata; */
1406                         
1407                         /* set current area
1408                          *      - must verify that region data is 3D-view (and not something else)
1409                          */
1410                         /* CAUTION: If this is the "toolbar", then this will change on the first stroke */
1411                         p->sa = curarea;
1412                         p->ar = ar;
1413                         p->align_flag = &ts->gpencil_v3d_align;
1414                         
1415                         if (ar->regiondata == NULL) {
1416                                 p->status = GP_STATUS_ERROR;
1417                                 if (G.debug & G_DEBUG)
1418                                         printf("Error: 3D-View active region doesn't have any region data, so cannot be drawable\n");
1419                                 return 0;
1420                         }
1421                         break;
1422                 }
1423                 case SPACE_NODE:
1424                 {
1425                         /* SpaceNode *snode = curarea->spacedata.first; */
1426                         
1427                         /* set current area */
1428                         p->sa = curarea;
1429                         p->ar = ar;
1430                         p->v2d = &ar->v2d;
1431                         p->align_flag = &ts->gpencil_v2d_align;
1432                         break;
1433                 }
1434                 case SPACE_SEQ:
1435                 {
1436                         SpaceSeq *sseq = curarea->spacedata.first;
1437                         
1438                         /* set current area */
1439                         p->sa = curarea;
1440                         p->ar = ar;
1441                         p->v2d = &ar->v2d;
1442                         p->align_flag = &ts->gpencil_seq_align;
1443                         
1444                         /* check that gpencil data is allowed to be drawn */
1445                         if (sseq->mainb == SEQ_DRAW_SEQUENCE) {
1446                                 p->status = GP_STATUS_ERROR;
1447                                 if (G.debug & G_DEBUG)
1448                                         printf("Error: In active view (sequencer), active mode doesn't support Grease Pencil\n");
1449                                 return 0;
1450                         }
1451                         break;
1452                 }
1453                 case SPACE_IMAGE:
1454                 {
1455                         /* SpaceImage *sima = curarea->spacedata.first; */
1456                         
1457                         /* set the current area */
1458                         p->sa = curarea;
1459                         p->ar = ar;
1460                         p->v2d = &ar->v2d;
1461                         p->align_flag = &ts->gpencil_ima_align;
1462                         break;
1463                 }
1464                 case SPACE_CLIP:
1465                 {
1466                         SpaceClip *sc = curarea->spacedata.first;
1467                         MovieClip *clip = ED_space_clip_get_clip(sc);
1468                         
1469                         if (clip == NULL) {
1470                                 p->status = GP_STATUS_ERROR;
1471                                 return false;
1472                         }
1473
1474                         /* set the current area */
1475                         p->sa = curarea;
1476                         p->ar = ar;
1477                         p->v2d = &ar->v2d;
1478                         p->align_flag = &ts->gpencil_v2d_align;
1479                         
1480                         invert_m4_m4(p->imat, sc->unistabmat);
1481                         
1482                         /* custom color for new layer */
1483                         p->custom_color[0] = 1.0f;
1484                         p->custom_color[1] = 0.0f;
1485                         p->custom_color[2] = 0.5f;
1486                         p->custom_color[3] = 0.9f;
1487                         
1488                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
1489                                 int framenr = ED_space_clip_get_clip_frame_number(sc);
1490                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
1491                                 MovieTrackingMarker *marker = track ? BKE_tracking_marker_get(track, framenr) : NULL;
1492
1493                                 if (marker) {
1494                                         p->imat[3][0] -= marker->pos[0];
1495                                         p->imat[3][1] -= marker->pos[1];
1496                                 }
1497                                 else {
1498                                         p->status = GP_STATUS_ERROR;
1499                                         return false;
1500                                 }
1501                         }
1502                         
1503                         invert_m4_m4(p->mat, p->imat);
1504                         copy_m4_m4(p->gsc.mat, p->mat);
1505                         break;
1506                 }
1507                 /* unsupported views */
1508                 default:
1509                 {
1510                         p->status = GP_STATUS_ERROR;
1511                         if (G.debug & G_DEBUG)
1512                                 printf("Error: Active view not appropriate for Grease Pencil drawing\n");
1513                         return 0;
1514                 }
1515         }
1516         
1517         /* get gp-data */
1518         gpd_ptr = ED_gpencil_data_get_pointers(C, &p->ownerPtr);
1519         if (gpd_ptr == NULL) {
1520                 p->status = GP_STATUS_ERROR;
1521                 if (G.debug & G_DEBUG)
1522                         printf("Error: Current context doesn't allow for any Grease Pencil data\n");
1523                 return 0;
1524         }
1525         else {
1526                 /* if no existing GPencil block exists, add one */
1527                 if (*gpd_ptr == NULL)
1528                         *gpd_ptr = BKE_gpencil_data_addnew("GPencil");
1529                 p->gpd = *gpd_ptr;
1530         }
1531         
1532         if (ED_gpencil_session_active() == 0) {
1533                 /* initialize undo stack,
1534                  * also, existing undo stack would make buffer drawn
1535                  */
1536                 gpencil_undo_init(p->gpd);
1537         }
1538         
1539         /* clear out buffer (stored in gp-data), in case something contaminated it */
1540         gp_session_validatebuffer(p);
1541         /* set brush and create a new one if null */
1542         gp_init_drawing_brush(ts, p);
1543         /* set palette info and create a new one if null */
1544         gp_init_palette(p);
1545         /* set palette colors */
1546         bGPDpalettecolor *palcolor = p->palettecolor;
1547         bGPdata *pdata = p->gpd;
1548         copy_v4_v4(pdata->scolor, palcolor->color);
1549         pdata->sflag = palcolor->flag;
1550         /* lock axis */
1551         p->lock_axis = ts->gp_sculpt.lock_axis;
1552
1553         return 1;
1554 }
1555
1556 /* init new painting session */
1557 static tGPsdata *gp_session_initpaint(bContext *C)
1558 {
1559         tGPsdata *p = NULL;
1560         
1561         /* create new context data */
1562         p = MEM_callocN(sizeof(tGPsdata), "GPencil Drawing Data");
1563         
1564         gp_session_initdata(C, p);
1565         
1566         /* radius for eraser circle is defined in userprefs now */
1567         /* NOTE: we do this here, so that if we exit immediately,
1568          *       erase size won't get lost
1569          */
1570         p->radius = U.gp_eraser;
1571
1572         /* return context data for running paint operator */
1573         return p;
1574 }
1575
1576 /* cleanup after a painting session */
1577 static void gp_session_cleanup(tGPsdata *p)
1578 {
1579         bGPdata *gpd = (p) ? p->gpd : NULL;
1580         
1581         /* error checking */
1582         if (gpd == NULL)
1583                 return;
1584         
1585         /* free stroke buffer */
1586         if (gpd->sbuffer) {
1587                 /* printf("\t\tGP - free sbuffer\n"); */
1588                 MEM_freeN(gpd->sbuffer);
1589                 gpd->sbuffer = NULL;
1590         }
1591         
1592         /* clear flags */
1593         gpd->sbuffer_size = 0;
1594         gpd->sbuffer_sflag = 0;
1595         p->inittime = 0.0;
1596 }
1597
1598 /* init new stroke */
1599 static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode)
1600 {
1601         Scene *scene = p->scene;
1602         ToolSettings *ts = scene->toolsettings;
1603         
1604         /* get active layer (or add a new one if non-existent) */
1605         p->gpl = BKE_gpencil_layer_getactive(p->gpd);
1606         if (p->gpl == NULL) {
1607                 p->gpl = BKE_gpencil_layer_addnew(p->gpd, "GP_Layer", true);
1608                 
1609                 if (p->custom_color[3])
1610                         copy_v3_v3(p->gpl->color, p->custom_color);
1611         }
1612         if (p->gpl->flag & GP_LAYER_LOCKED) {
1613                 p->status = GP_STATUS_ERROR;
1614                 if (G.debug & G_DEBUG)
1615                         printf("Error: Cannot paint on locked layer\n");
1616                 return;
1617         }
1618         
1619         /* get active frame (add a new one if not matching frame) */
1620         if (paintmode == GP_PAINTMODE_ERASER) {
1621                 /* Eraser mode:
1622                  * 1) Add new frames to all frames that we might touch,
1623                  * 2) Ensure that p->gpf refers to the frame used for the active layer
1624                  *    (to avoid problems with other tools which expect it to exist)
1625                  */
1626                 bool has_layer_to_erase = false;
1627                 
1628                 for (bGPDlayer *gpl = p->gpd->layers.first; gpl; gpl = gpl->next) {
1629                         /* Skip if layer not editable */
1630                         if (gpencil_layer_is_editable(gpl) == false)
1631                                 continue;
1632                         
1633                         /* Add a new frame if needed (and based off the active frame,
1634                          * as we need some existing strokes to erase)
1635                          *
1636                          * Note: We don't add a new frame if there's nothing there now, so
1637                          *       -> If there are no frames at all, don't add one
1638                          *       -> If there are no strokes in that frame, don't add a new empty frame
1639                          */
1640                         if (gpl->actframe && gpl->actframe->strokes.first) {
1641                                 gpl->actframe = BKE_gpencil_layer_getframe(gpl, CFRA, GP_GETFRAME_ADD_COPY);
1642                                 has_layer_to_erase = true;
1643                         }
1644                         
1645                         /* XXX: we omit GP_FRAME_PAINT here for now,
1646                          * as it is only really useful for doing
1647                          * paintbuffer drawing
1648                          */
1649                 }
1650                 
1651                 /* Ensure this gets set... */
1652                 p->gpf = p->gpl->actframe;
1653                 
1654                 /* Restrict eraser to only affecting selected strokes, if the "selection mask" is on
1655                  * (though this is only available in editmode)
1656                  */
1657                 if (p->gpd->flag & GP_DATA_STROKE_EDITMODE) {
1658                         if (ts->gp_sculpt.flag & GP_BRUSHEDIT_FLAG_SELECT_MASK) {
1659                                 p->flags |= GP_PAINTFLAG_SELECTMASK;
1660                         }
1661                 }
1662                 
1663                 if (has_layer_to_erase == false) {
1664                         p->status = GP_STATUS_ERROR;
1665                         //if (G.debug & G_DEBUG)
1666                                 printf("Error: Eraser will not be affecting anything (gpencil_paint_init)\n");
1667                         return;
1668                 }
1669         }
1670         else {
1671                 /* Drawing Modes - Add a new frame if needed on the active layer */
1672                 short add_frame_mode;
1673                 
1674                 if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST)
1675                         add_frame_mode = GP_GETFRAME_ADD_COPY;
1676                 else
1677                         add_frame_mode = GP_GETFRAME_ADD_NEW;
1678                         
1679                 p->gpf = BKE_gpencil_layer_getframe(p->gpl, CFRA, add_frame_mode);
1680                 
1681                 if (p->gpf == NULL) {
1682                         p->status = GP_STATUS_ERROR;
1683                         if (G.debug & G_DEBUG)
1684                                 printf("Error: No frame created (gpencil_paint_init)\n");
1685                         return;
1686                 }
1687                 else {
1688                         p->gpf->flag |= GP_FRAME_PAINT;
1689                 }
1690         }
1691         
1692         /* set 'eraser' for this stroke if using eraser */
1693         p->paintmode = paintmode;
1694         if (p->paintmode == GP_PAINTMODE_ERASER) {
1695                 p->gpd->sbuffer_sflag |= GP_STROKE_ERASER;
1696                 
1697                 /* check if we should respect depth while erasing */
1698                 if (p->sa->spacetype == SPACE_VIEW3D) {
1699                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1700                                 p->flags |= GP_PAINTFLAG_V3D_ERASER_DEPTH;
1701                         }
1702                 }
1703         }
1704         else {
1705                 /* disable eraser flags - so that we can switch modes during a session */
1706                 p->gpd->sbuffer_sflag &= ~GP_STROKE_ERASER;
1707                 
1708                 if (p->sa->spacetype == SPACE_VIEW3D) {
1709                         if (p->gpl->flag & GP_LAYER_NO_XRAY) {
1710                                 p->flags &= ~GP_PAINTFLAG_V3D_ERASER_DEPTH;
1711                         }
1712                 }
1713         }
1714         
1715         /* set 'initial run' flag, which is only used to denote when a new stroke is starting */
1716         p->flags |= GP_PAINTFLAG_FIRSTRUN;
1717         
1718         
1719         /* when drawing in the camera view, in 2D space, set the subrect */
1720         p->subrect = NULL;
1721         if ((*p->align_flag & GP_PROJECT_VIEWSPACE) == 0) {
1722                 if (p->sa->spacetype == SPACE_VIEW3D) {
1723                         View3D *v3d = p->sa->spacedata.first;
1724                         RegionView3D *rv3d = p->ar->regiondata;
1725                         
1726                         /* for camera view set the subrect */
1727                         if (rv3d->persp == RV3D_CAMOB) {
1728                                 ED_view3d_calc_camera_border(p->scene, p->ar, v3d, rv3d, &p->subrect_data, true); /* no shift */
1729                                 p->subrect = &p->subrect_data;
1730                         }
1731                 }
1732         }
1733         
1734         /* init stroke point space-conversion settings... */
1735         p->gsc.gpd = p->gpd;
1736         p->gsc.gpl = p->gpl;
1737         
1738         p->gsc.sa = p->sa;
1739         p->gsc.ar = p->ar;
1740         p->gsc.v2d = p->v2d;
1741         
1742         p->gsc.subrect_data = p->subrect_data;
1743         p->gsc.subrect = p->subrect;
1744         
1745         copy_m4_m4(p->gsc.mat, p->mat);
1746         
1747         
1748         /* check if points will need to be made in view-aligned space */
1749         if (*p->align_flag & GP_PROJECT_VIEWSPACE) {
1750                 switch (p->sa->spacetype) {
1751                         case SPACE_VIEW3D:
1752                         {
1753                                 p->gpd->sbuffer_sflag |= GP_STROKE_3DSPACE;
1754                                 break;
1755                         }
1756                         case SPACE_NODE:
1757                         {
1758                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1759                                 break;
1760                         }
1761                         case SPACE_SEQ:
1762                         {
1763                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1764                                 break;
1765                         }
1766                         case SPACE_IMAGE:
1767                         {
1768                                 SpaceImage *sima = (SpaceImage *)p->sa->spacedata.first;
1769                                 
1770                                 /* only set these flags if the image editor doesn't have an image active,
1771                                  * otherwise user will be confused by strokes not appearing after they're drawn
1772                                  *
1773                                  * Admittedly, this is a bit hacky, but it works much nicer from an ergonomic standpoint!
1774                                  */
1775                                 if (ELEM(NULL, sima, sima->image)) {
1776                                         /* make strokes be drawn in screen space */
1777                                         p->gpd->sbuffer_sflag &= ~GP_STROKE_2DSPACE;
1778                                         *(p->align_flag) &= ~GP_PROJECT_VIEWSPACE;
1779                                 }
1780                                 else {
1781                                         p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1782                                 }
1783                                 break;
1784                         }
1785                         case SPACE_CLIP:
1786                         {
1787                                 p->gpd->sbuffer_sflag |= GP_STROKE_2DSPACE;
1788                                 break;
1789                         }
1790                 }
1791         }
1792 }
1793
1794 /* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
1795 static void gp_paint_strokeend(tGPsdata *p)
1796 {
1797         /* for surface sketching, need to set the right OpenGL context stuff so that
1798          * the conversions will project the values correctly...
1799          */
1800         if (gpencil_project_check(p)) {
1801                 View3D *v3d = p->sa->spacedata.first;
1802                 
1803                 /* need to restore the original projection settings before packing up */
1804                 view3d_region_operator_needs_opengl(p->win, p->ar);
1805                 ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
1806         }
1807         
1808         /* check if doing eraser or not */
1809         if ((p->gpd->sbuffer_sflag & GP_STROKE_ERASER) == 0) {
1810                 /* simplify stroke before transferring? */
1811                 gp_stroke_simplify(p);
1812                 
1813                 /* transfer stroke to frame */
1814                 gp_stroke_newfrombuffer(p);
1815         }
1816         
1817         /* clean up buffer now */
1818         gp_session_validatebuffer(p);
1819 }
1820
1821 /* finish off stroke painting operation */
1822 static void gp_paint_cleanup(tGPsdata *p)
1823 {
1824         /* p->gpd==NULL happens when stroke failed to initialize,
1825          * for example when GP is hidden in current space (sergey)
1826          */
1827         if (p->gpd) {
1828                 /* finish off a stroke */
1829                 gp_paint_strokeend(p);
1830         }
1831         
1832         /* "unlock" frame */
1833         if (p->gpf)
1834                 p->gpf->flag &= ~GP_FRAME_PAINT;
1835 }
1836
1837 /* ------------------------------- */
1838
1839 /* Helper callback for drawing the cursor itself */
1840 static void gpencil_draw_eraser(bContext *UNUSED(C), int x, int y, void *p_ptr)
1841 {
1842         tGPsdata *p = (tGPsdata *)p_ptr;
1843         
1844         if (p->paintmode == GP_PAINTMODE_ERASER) {
1845                 glPushMatrix();
1846                 
1847                 glTranslatef((float)x, (float)y, 0.0f);
1848                 
1849                 glEnable(GL_LINE_SMOOTH);
1850                 glEnable(GL_BLEND);
1851                 
1852                 glColor4ub(255, 100, 100, 20);
1853                 glutil_draw_filled_arc(0.0, M_PI * 2.0, p->radius, 40);
1854                 
1855                 setlinestyle(6);
1856                 
1857                 glColor4ub(255, 100, 100, 200);
1858                 glutil_draw_lined_arc(0.0, M_PI * 2.0, p->radius, 40);
1859                 
1860                 setlinestyle(0);
1861                 glDisable(GL_BLEND);
1862                 glDisable(GL_LINE_SMOOTH);
1863                 
1864                 glPopMatrix();
1865         }
1866 }
1867
1868 /* Turn brush cursor in 3D view on/off */
1869 static void gpencil_draw_toggle_eraser_cursor(bContext *C, tGPsdata *p, short enable)
1870 {
1871         if (p->erasercursor && !enable) {
1872                 /* clear cursor */
1873                 WM_paint_cursor_end(CTX_wm_manager(C), p->erasercursor);
1874                 p->erasercursor = NULL;
1875         }
1876         else if (enable && !p->erasercursor) {
1877                 /* enable cursor */
1878                 p->erasercursor = WM_paint_cursor_activate(CTX_wm_manager(C),
1879                                                            NULL, /* XXX */
1880                                                            gpencil_draw_eraser, p);
1881         }
1882 }
1883
1884 /* Check if tablet eraser is being used (when processing events) */
1885 static bool gpencil_is_tablet_eraser_active(const wmEvent *event)
1886 {
1887         if (event->tablet_data) {
1888                 const wmTabletData *wmtab = event->tablet_data;
1889                 return (wmtab->Active == EVT_TABLET_ERASER);
1890         }
1891         
1892         return false;
1893 }
1894
1895 /* ------------------------------- */
1896
1897 static void gpencil_draw_exit(bContext *C, wmOperator *op)
1898 {
1899         tGPsdata *p = op->customdata;
1900         
1901         /* clear undo stack */
1902         gpencil_undo_finish();
1903         
1904         /* restore cursor to indicate end of drawing */
1905         WM_cursor_modal_restore(CTX_wm_window(C));
1906         
1907         /* don't assume that operator data exists at all */
1908         if (p) {
1909                 /* check size of buffer before cleanup, to determine if anything happened here */
1910                 if (p->paintmode == GP_PAINTMODE_ERASER) {
1911                         /* turn off radial brush cursor */
1912                         gpencil_draw_toggle_eraser_cursor(C, p, false);
1913                 }
1914
1915                 /* always store the new eraser size to be used again next time
1916                  * NOTE: Do this even when not in eraser mode, as eraser may
1917                  *       have been toggled at some point.
1918                  */
1919                 U.gp_eraser = p->radius;
1920                 
1921                 /* cleanup */
1922                 gp_paint_cleanup(p);
1923                 gp_session_cleanup(p);
1924                 
1925                 /* finally, free the temp data */
1926                 MEM_freeN(p);
1927         }
1928         
1929         op->customdata = NULL;
1930 }
1931
1932 static void gpencil_draw_cancel(bContext *C, wmOperator *op)
1933 {
1934         /* this is just a wrapper around exit() */
1935         gpencil_draw_exit(C, op);
1936 }
1937
1938 /* ------------------------------- */
1939
1940
1941 static int gpencil_draw_init(bContext *C, wmOperator *op)
1942 {
1943         tGPsdata *p;
1944         eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
1945         
1946         /* check context */
1947         p = op->customdata = gp_session_initpaint(C);
1948         if ((p == NULL) || (p->status == GP_STATUS_ERROR)) {
1949                 /* something wasn't set correctly in context */
1950                 gpencil_draw_exit(C, op);
1951                 return 0;
1952         }
1953         
1954         /* init painting data */
1955         gp_paint_initstroke(p, paintmode);
1956         if (p->status == GP_STATUS_ERROR) {
1957                 gpencil_draw_exit(C, op);
1958                 return 0;
1959         }
1960         
1961         /* everything is now setup ok */
1962         return 1;
1963 }
1964
1965
1966 /* ------------------------------- */
1967
1968 /* ensure that the correct cursor icon is set */
1969 static void gpencil_draw_cursor_set(tGPsdata *p)
1970 {
1971         if (p->paintmode == GP_PAINTMODE_ERASER)
1972                 WM_cursor_modal_set(p->win, BC_CROSSCURSOR);  /* XXX need a better cursor */
1973         else
1974                 WM_cursor_modal_set(p->win, BC_PAINTBRUSHCURSOR);
1975 }
1976
1977 /* update UI indicators of status, including cursor and header prints */
1978 static void gpencil_draw_status_indicators(tGPsdata *p)
1979 {
1980         /* header prints */
1981         switch (p->status) {
1982                 case GP_STATUS_PAINTING:
1983                         /* only print this for paint-sessions, otherwise it gets annoying */
1984                         if (GPENCIL_SKETCH_SESSIONS_ON(p->scene))
1985                                 ED_area_headerprint(p->sa, IFACE_("Grease Pencil: Drawing/erasing stroke... Release to end stroke"));
1986                         break;
1987                 
1988                 case GP_STATUS_IDLING:
1989                         /* print status info */
1990                         switch (p->paintmode) {
1991                                 case GP_PAINTMODE_ERASER:
1992                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Erase Session: Hold and drag LMB or RMB to erase | "
1993                                                                           "ESC/Enter to end  (or click outside this area)"));
1994                                         break;
1995                                 case GP_PAINTMODE_DRAW_STRAIGHT:
1996                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Line Session: Hold and drag LMB to draw | "
1997                                                                           "ESC/Enter to end  (or click outside this area)"));
1998                                         break;
1999                                 case GP_PAINTMODE_DRAW:
2000                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Freehand Session: Hold and drag LMB to draw | "
2001                                                                           "E/ESC/Enter to end  (or click outside this area)"));
2002                                         break;
2003                                 case GP_PAINTMODE_DRAW_POLY:
2004                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Poly Session: LMB click to place next stroke vertex | "
2005                                                                           "ESC/Enter to end  (or click outside this area)"));
2006                                         break;
2007                                 
2008                                 default: /* unhandled future cases */
2009                                         ED_area_headerprint(p->sa, IFACE_("Grease Pencil Session: ESC/Enter to end   (or click outside this area)"));
2010                                         break;
2011                         }
2012                         break;
2013                 
2014                 case GP_STATUS_ERROR:
2015                 case GP_STATUS_DONE:
2016                         /* clear status string */
2017                         ED_area_headerprint(p->sa, NULL);
2018                         break;
2019         }
2020 }
2021
2022 /* ------------------------------- */
2023
2024 /* create a new stroke point at the point indicated by the painting context */
2025 static void gpencil_draw_apply(wmOperator *op, tGPsdata *p)
2026 {
2027         /* handle drawing/erasing -> test for erasing first */
2028         if (p->paintmode == GP_PAINTMODE_ERASER) {
2029                 /* do 'live' erasing now */
2030                 gp_stroke_doeraser(p);
2031                 
2032                 /* store used values */
2033                 p->mvalo[0] = p->mval[0];
2034                 p->mvalo[1] = p->mval[1];
2035                 p->opressure = p->pressure;
2036         }
2037         /* only add current point to buffer if mouse moved (even though we got an event, it might be just noise) */
2038         else if (gp_stroke_filtermval(p, p->mval, p->mvalo)) {
2039                 /* try to add point */
2040                 short ok = gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2041                 
2042                 /* handle errors while adding point */
2043                 if ((ok == GP_STROKEADD_FULL) || (ok == GP_STROKEADD_OVERFLOW)) {
2044                         /* finish off old stroke */
2045                         gp_paint_strokeend(p);
2046                         /* And start a new one!!! Else, projection errors! */
2047                         gp_paint_initstroke(p, p->paintmode);
2048                         
2049                         /* start a new stroke, starting from previous point */
2050                         /* XXX Must manually reset inittime... */
2051                         /* XXX We only need to reuse previous point if overflow! */
2052                         if (ok == GP_STROKEADD_OVERFLOW) {
2053                                 p->inittime = p->ocurtime;
2054                                 gp_stroke_addpoint(p, p->mvalo, p->opressure, p->ocurtime);
2055                         }
2056                         else {
2057                                 p->inittime = p->curtime;
2058                         }
2059                         gp_stroke_addpoint(p, p->mval, p->pressure, p->curtime);
2060                 }
2061                 else if (ok == GP_STROKEADD_INVALID) {
2062                         /* the painting operation cannot continue... */
2063                         BKE_report(op->reports, RPT_ERROR, "Cannot paint stroke");
2064                         p->status = GP_STATUS_ERROR;
2065                         
2066                         if (G.debug & G_DEBUG)
2067                                 printf("Error: Grease-Pencil Paint - Add Point Invalid\n");
2068                         return;
2069                 }
2070                 
2071                 /* store used values */
2072                 p->mvalo[0] = p->mval[0];
2073                 p->mvalo[1] = p->mval[1];
2074                 p->opressure = p->pressure;
2075                 p->ocurtime = p->curtime;
2076         }
2077 }
2078
2079 /* handle draw event */
2080 static void gpencil_draw_apply_event(wmOperator *op, const wmEvent *event)
2081 {
2082         tGPsdata *p = op->customdata;
2083         PointerRNA itemptr;
2084         float mousef[2];
2085         int tablet = 0;
2086         
2087         /* convert from window-space to area-space mouse coordinates
2088          * NOTE: float to ints conversions, +1 factor is probably used to ensure a bit more accurate rounding...
2089          */
2090         p->mval[0] = event->mval[0] + 1;
2091         p->mval[1] = event->mval[1] + 1;
2092         
2093         /* verify key status for straight lines */
2094         if ((event->ctrl > 0) || (event->alt > 0)) {
2095                 if (p->straight[0] == 0) {
2096                         int dx = abs(p->mval[0] - p->mvalo[0]);
2097                         int dy = abs(p->mval[1] - p->mvalo[1]);
2098                         if ((dx > 0) || (dy > 0)) {
2099                                 /* check mouse direction to replace the other coordinate with previous values */
2100                                 if (dx >= dy) {
2101                                         /* horizontal */
2102                                         p->straight[0] = 1;
2103                                         p->straight[1] = p->mval[1]; /* save y */
2104                                 }
2105                                 else {
2106                                         /* vertical */
2107                                         p->straight[0] = 2;
2108                                         p->straight[1] = p->mval[0]; /* save x */
2109                                 }
2110                         }
2111                 }
2112         }
2113         else {
2114                 p->straight[0] = 0;
2115         }
2116
2117         p->curtime = PIL_check_seconds_timer();
2118         
2119         /* handle pressure sensitivity (which is supplied by tablets) */
2120         if (event->tablet_data) {
2121                 const wmTabletData *wmtab = event->tablet_data;
2122                 
2123                 tablet = (wmtab->Active != EVT_TABLET_NONE);
2124                 p->pressure = wmtab->Pressure;
2125                 
2126                 /* Hack for pressure sensitive eraser on D+RMB when using a tablet:
2127                  *  The pen has to float over the tablet surface, resulting in
2128                  *  zero pressure (T47101). Ignore pressure values if floating
2129                  *  (i.e. "effectively zero" pressure), and only when the "active"
2130                  *  end is the stylus (i.e. the default when not eraser)
2131                  */
2132                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2133                         if ((wmtab->Active != EVT_TABLET_ERASER) && (p->pressure < 0.001f)) {
2134                                 p->pressure = 1.0f;
2135                         }
2136                 }
2137         }
2138         else {
2139                 /* No tablet data -> No pressure info is available */
2140                 p->pressure = 1.0f;
2141         }
2142         
2143         /* special exception for start of strokes (i.e. maybe for just a dot) */
2144         if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2145                 p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2146                 
2147                 p->mvalo[0] = p->mval[0];
2148                 p->mvalo[1] = p->mval[1];
2149                 p->opressure = p->pressure;
2150                 p->inittime = p->ocurtime = p->curtime;
2151                 p->straight[0] = 0;
2152                 p->straight[1] = 0;
2153
2154                 /* special exception here for too high pressure values on first touch in
2155                  *  windows for some tablets, then we just skip first touch...
2156                  */
2157                 if (tablet && (p->pressure >= 0.99f))
2158                         return;
2159         }
2160         
2161         /* check if alt key is pressed and limit to straight lines */
2162         if (p->straight[0] != 0) {
2163                 if (p->straight[0] == 1) {
2164                         /* horizontal */
2165                         p->mval[1] = p->straight[1]; /* replace y */
2166                 }
2167                 else {
2168                         /* vertical */
2169                         p->mval[0] = p->straight[1]; /* replace x */
2170                 }
2171         }
2172
2173         /* fill in stroke data (not actually used directly by gpencil_draw_apply) */
2174         RNA_collection_add(op->ptr, "stroke", &itemptr);
2175         
2176         mousef[0] = p->mval[0];
2177         mousef[1] = p->mval[1];
2178         RNA_float_set_array(&itemptr, "mouse", mousef);
2179         RNA_float_set(&itemptr, "pressure", p->pressure);
2180         RNA_boolean_set(&itemptr, "is_start", (p->flags & GP_PAINTFLAG_FIRSTRUN) != 0);
2181         
2182         RNA_float_set(&itemptr, "time", p->curtime - p->inittime);
2183         
2184         /* apply the current latest drawing point */
2185         gpencil_draw_apply(op, p);
2186         
2187         /* force refresh */
2188         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2189 }
2190
2191 /* ------------------------------- */
2192
2193 /* operator 'redo' (i.e. after changing some properties, but also for repeat last) */
2194 static int gpencil_draw_exec(bContext *C, wmOperator *op)
2195 {
2196         tGPsdata *p = NULL;
2197         
2198         /* printf("GPencil - Starting Re-Drawing\n"); */
2199         
2200         /* try to initialize context data needed while drawing */
2201         if (!gpencil_draw_init(C, op)) {
2202                 if (op->customdata) MEM_freeN(op->customdata);
2203                 /* printf("\tGP - no valid data\n"); */
2204                 return OPERATOR_CANCELLED;
2205         }
2206         else
2207                 p = op->customdata;
2208         
2209         /* printf("\tGP - Start redrawing stroke\n"); */
2210         
2211         /* loop over the stroke RNA elements recorded (i.e. progress of mouse movement),
2212          * setting the relevant values in context at each step, then applying
2213          */
2214         RNA_BEGIN (op->ptr, itemptr, "stroke")
2215         {
2216                 float mousef[2];
2217                 
2218                 /* printf("\t\tGP - stroke elem\n"); */
2219                 
2220                 /* get relevant data for this point from stroke */
2221                 RNA_float_get_array(&itemptr, "mouse", mousef);
2222                 p->mval[0] = (int)mousef[0];
2223                 p->mval[1] = (int)mousef[1];
2224                 p->pressure = RNA_float_get(&itemptr, "pressure");
2225                 p->curtime = (double)RNA_float_get(&itemptr, "time") + p->inittime;
2226                 
2227                 if (RNA_boolean_get(&itemptr, "is_start")) {
2228                         /* if first-run flag isn't set already (i.e. not true first stroke),
2229                          * then we must terminate the previous one first before continuing
2230                          */
2231                         if ((p->flags & GP_PAINTFLAG_FIRSTRUN) == 0) {
2232                                 /* TODO: both of these ops can set error-status, but we probably don't need to worry */
2233                                 gp_paint_strokeend(p);
2234                                 gp_paint_initstroke(p, p->paintmode);
2235                         }
2236                 }
2237                 
2238                 /* if first run, set previous data too */
2239                 if (p->flags & GP_PAINTFLAG_FIRSTRUN) {
2240                         p->flags &= ~GP_PAINTFLAG_FIRSTRUN;
2241                         
2242                         p->mvalo[0] = p->mval[0];
2243                         p->mvalo[1] = p->mval[1];
2244                         p->opressure = p->pressure;
2245                         p->ocurtime = p->curtime;
2246                 }
2247                 
2248                 /* apply this data as necessary now (as per usual) */
2249                 gpencil_draw_apply(op, p);
2250         }
2251         RNA_END;
2252                 
2253         /* printf("\tGP - done\n"); */
2254         
2255         /* cleanup */
2256         gpencil_draw_exit(C, op);
2257         
2258         /* refreshes */
2259         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2260         
2261         /* done */
2262         return OPERATOR_FINISHED;
2263 }
2264
2265 /* ------------------------------- */
2266
2267 /* start of interactive drawing part of operator */
2268 static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event)
2269 {
2270         tGPsdata *p = NULL;
2271         
2272         if (G.debug & G_DEBUG)
2273                 printf("GPencil - Starting Drawing\n");
2274         
2275         /* try to initialize context data needed while drawing */
2276         if (!gpencil_draw_init(C, op)) {
2277                 if (op->customdata)
2278                         MEM_freeN(op->customdata);
2279                 if (G.debug & G_DEBUG)
2280                         printf("\tGP - no valid data\n");
2281                 return OPERATOR_CANCELLED;
2282         }
2283         else
2284                 p = op->customdata;
2285         
2286         /* TODO: set any additional settings that we can take from the events?
2287          * TODO? if tablet is erasing, force eraser to be on? */
2288         
2289         /* TODO: move cursor setting stuff to stroke-start so that paintmode can be changed midway... */
2290         
2291         /* if eraser is on, draw radial aid */
2292         if (p->paintmode == GP_PAINTMODE_ERASER) {
2293                 gpencil_draw_toggle_eraser_cursor(C, p, true);
2294         }
2295         /* set cursor 
2296          * NOTE: This may change later (i.e. intentionally via brush toggle,
2297          *       or unintentionally if the user scrolls outside the area)...
2298          */
2299         gpencil_draw_cursor_set(p);
2300
2301         /* only start drawing immediately if we're allowed to do so... */
2302         if (RNA_boolean_get(op->ptr, "wait_for_input") == false) {
2303                 /* hotkey invoked - start drawing */
2304                 /* printf("\tGP - set first spot\n"); */
2305                 p->status = GP_STATUS_PAINTING;
2306
2307                 /* handle the initial drawing - i.e. for just doing a simple dot */
2308                 gpencil_draw_apply_event(op, event);
2309                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2310         }
2311         else {
2312                 /* toolbar invoked - don't start drawing yet... */
2313                 /* printf("\tGP - hotkey invoked... waiting for click-drag\n"); */
2314                 op->flag |= OP_IS_MODAL_CURSOR_REGION;
2315         }
2316         
2317         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2318         /* add a modal handler for this operator, so that we can then draw continuous strokes */
2319         WM_event_add_modal_handler(C, op);
2320         return OPERATOR_RUNNING_MODAL;
2321 }
2322
2323 /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2324 static bool gpencil_area_exists(bContext *C, ScrArea *sa_test)
2325 {
2326         bScreen *sc = CTX_wm_screen(C);
2327         return (BLI_findindex(&sc->areabase, sa_test) != -1);
2328 }
2329
2330 static tGPsdata *gpencil_stroke_begin(bContext *C, wmOperator *op)
2331 {
2332         tGPsdata *p = op->customdata;
2333         
2334         /* we must check that we're still within the area that we're set up to work from
2335          * otherwise we could crash (see bug #20586)
2336          */
2337         if (CTX_wm_area(C) != p->sa) {
2338                 printf("\t\t\tGP - wrong area execution abort!\n");
2339                 p->status = GP_STATUS_ERROR;
2340         }
2341         
2342         /* printf("\t\tGP - start stroke\n"); */
2343         
2344         /* we may need to set up paint env again if we're resuming */
2345         /* XXX: watch it with the paintmode! in future,
2346          *      it'd be nice to allow changing paint-mode when in sketching-sessions */
2347         
2348         if (gp_session_initdata(C, p))
2349                 gp_paint_initstroke(p, p->paintmode);
2350         
2351         if (p->status != GP_STATUS_ERROR) {
2352                 p->status = GP_STATUS_PAINTING;
2353                 op->flag &= ~OP_IS_MODAL_CURSOR_REGION;
2354         }
2355         
2356         return op->customdata;
2357 }
2358
2359 static void gpencil_stroke_end(wmOperator *op)
2360 {
2361         tGPsdata *p = op->customdata;
2362         
2363         gp_paint_cleanup(p);
2364         
2365         gpencil_undo_push(p->gpd);
2366         
2367         gp_session_cleanup(p);
2368         
2369         p->status = GP_STATUS_IDLING;
2370         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2371         
2372         p->gpd = NULL;
2373         p->gpl = NULL;
2374         p->gpf = NULL;
2375 }
2376
2377 /* Move last stroke in the listbase to the head to be drawn below all previous strokes in the layer */
2378 static void gpencil_move_last_stroke_to_back(bContext *C)
2379 {
2380         /* move last stroke (the polygon) to head of the listbase stroke to draw on back of all previous strokes */
2381         bGPdata *gpd = ED_gpencil_data_get_active(C);
2382         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
2383
2384         /* sanity checks */
2385         if (ELEM(NULL, gpd, gpl, gpl->actframe)) {
2386                 return;
2387         }
2388
2389         bGPDframe *gpf = gpl->actframe;
2390         bGPDstroke *gps = gpf->strokes.last;
2391         if (ELEM(NULL, gps)) {
2392                 return;
2393         }
2394
2395         BLI_remlink(&gpf->strokes, gps);
2396         BLI_insertlinkbefore(&gpf->strokes, gpf->strokes.first, gps);
2397 }
2398
2399 /* events handling during interactive drawing part of operator */
2400 static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
2401 {
2402         tGPsdata *p = op->customdata;
2403         ToolSettings *ts = CTX_data_tool_settings(C);
2404         int estate = OPERATOR_PASS_THROUGH; /* default exit state - pass through to support MMB view nav, etc. */
2405         
2406         /* if (event->type == NDOF_MOTION)
2407          *    return OPERATOR_PASS_THROUGH;
2408          * -------------------------------
2409          * [mce] Not quite what I was looking
2410          * for, but a good start! GP continues to
2411          * draw on the screen while the 3D mouse
2412          * moves the viewpoint. Problem is that
2413          * the stroke is converted to 3D only after
2414          * it is finished. This approach should work
2415          * better in tools that immediately apply
2416          * in 3D space.
2417          */
2418         
2419         if (p->status == GP_STATUS_IDLING) {
2420                 ARegion *ar = CTX_wm_region(C);
2421                 p->ar = ar;
2422         }
2423
2424         /* we don't pass on key events, GP is used with key-modifiers - prevents Dkey to insert drivers */
2425         if (ISKEYBOARD(event->type)) {
2426                 if (ELEM(event->type, LEFTARROWKEY, DOWNARROWKEY, RIGHTARROWKEY, UPARROWKEY, ZKEY)) {
2427                         /* allow some keys:
2428                          *   - for frame changing [#33412]
2429                          *   - for undo (during sketching sessions)
2430                          */
2431                 }
2432                 else if (ELEM(event->type, PAD0, PAD1, PAD2, PAD3, PAD4, PAD5, PAD6, PAD7, PAD8, PAD9)) {
2433                         /* allow numpad keys so that camera/view manipulations can still take place
2434                          * - PAD0 in particular is really important for Grease Pencil drawing,
2435                          *   as animators may be working "to camera", so having this working
2436                          *   is essential for ensuring that they can quickly return to that view
2437                          */
2438                 }
2439                 else if ((ELEM(event->type, DKEY)) && (event->val == KM_RELEASE)) {
2440                         /* enable continuous if release D key in mid drawing */
2441                         p->scene->toolsettings->gpencil_flags |= GP_TOOL_FLAG_PAINTSESSIONS_ON;
2442                 }
2443                 else if ((event->type == BKEY) && (event->val == KM_RELEASE)) {
2444                         /* Add Blank Frame
2445                          * - Since this operator is non-modal, we can just call it here, and keep going...
2446                  * - This operator is especially useful when animating
2447                          */
2448                         WM_operator_name_call(C, "GPENCIL_OT_blank_frame_add", WM_OP_EXEC_DEFAULT, NULL);
2449                         estate = OPERATOR_RUNNING_MODAL;
2450                 }
2451                 else {
2452                         estate = OPERATOR_RUNNING_MODAL;
2453                 }
2454         }
2455         
2456         //printf("\tGP - handle modal event...\n");
2457         
2458         /* exit painting mode (and/or end current stroke)
2459          * NOTE: cannot do RIGHTMOUSE (as is standard for canceling) as that would break polyline [#32647]
2460          */
2461         if (ELEM(event->type, RETKEY, PADENTER, ESCKEY, SPACEKEY, EKEY)) {
2462                 /* exit() ends the current stroke before cleaning up */
2463                 /* printf("\t\tGP - end of paint op + end of stroke\n"); */
2464                 /* if drawing polygon and enable on back, must move stroke */
2465                 if (ts) {
2466                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2467                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2468                                         gpencil_move_last_stroke_to_back(C);
2469                                 }
2470                         }
2471                 }
2472                 p->status = GP_STATUS_DONE;
2473                 estate = OPERATOR_FINISHED;
2474         }
2475         
2476         /* toggle painting mode upon mouse-button movement
2477          *  - LEFTMOUSE  = standard drawing (all) / straight line drawing (all) / polyline (toolbox only)
2478          *  - RIGHTMOUSE = polyline (hotkey) / eraser (all)
2479          *    (Disabling RIGHTMOUSE case here results in bugs like [#32647])
2480          * also making sure we have a valid event value, to not exit too early
2481          */
2482         if (ELEM(event->type, LEFTMOUSE, RIGHTMOUSE) && (event->val != KM_NOTHING)) {
2483                 /* if painting, end stroke */
2484                 if (p->status == GP_STATUS_PAINTING) {
2485                         int sketch = 0;
2486                         
2487                         /* basically, this should be mouse-button up = end stroke
2488                          * BUT what happens next depends on whether we 'painting sessions' is enabled
2489                          */
2490                         sketch |= GPENCIL_SKETCH_SESSIONS_ON(p->scene);
2491                         /* polyline drawing is also 'sketching' -- all knots should be added during one session */
2492                         sketch |= (p->paintmode == GP_PAINTMODE_DRAW_POLY);
2493                         
2494                         if (sketch) {
2495                                 /* end stroke only, and then wait to resume painting soon */
2496                                 /* printf("\t\tGP - end stroke only\n"); */
2497                                 gpencil_stroke_end(op);
2498                                 
2499                                 /* If eraser mode is on, turn it off after the stroke finishes
2500                                  * NOTE: This just makes it nicer to work with drawing sessions
2501                                  */
2502                                 if (p->paintmode == GP_PAINTMODE_ERASER) {
2503                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2504                                         
2505                                         /* if the original mode was *still* eraser,
2506                                          * we'll let it say for now, since this gives
2507                                          * users an opportunity to have visual feedback
2508                                          * when adjusting eraser size
2509                                          */
2510                                         if (p->paintmode != GP_PAINTMODE_ERASER) {      
2511                                                 /* turn off cursor...
2512                                                  * NOTE: this should be enough for now
2513                                                  *       Just hiding this makes it seem like
2514                                                  *       you can paint again...
2515                                                  */
2516                                                 gpencil_draw_toggle_eraser_cursor(C, p, false);
2517                                         }
2518                                 }
2519                                 
2520                                 /* we've just entered idling state, so this event was processed (but no others yet) */
2521                                 estate = OPERATOR_RUNNING_MODAL;
2522                                 
2523                                 /* stroke could be smoothed, send notifier to refresh screen */
2524                                 WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2525                         }
2526                         else {
2527                                 /* printf("\t\tGP - end of stroke + op\n"); */
2528                                 /* if drawing polygon and enable on back, must move stroke */
2529                                 if (ts) {
2530                                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2531                                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2532                                                         gpencil_move_last_stroke_to_back(C);
2533                                                 }
2534                                         }
2535                                 }
2536                                 p->status = GP_STATUS_DONE;
2537                                 estate = OPERATOR_FINISHED;
2538                         }
2539                 }
2540                 else if (event->val == KM_PRESS) {
2541                         bool in_bounds = false;
2542                         
2543                         /* Check if we're outside the bounds of the active region
2544                          * NOTE: An exception here is that if launched from the toolbar,
2545                          *       whatever region we're now in should become the new region
2546                          */
2547                         if ((p->ar) && (p->ar->regiontype == RGN_TYPE_TOOLS)) {
2548                                 /* Change to whatever region is now under the mouse */
2549                                 ARegion *current_region = BKE_area_find_region_xy(p->sa, RGN_TYPE_ANY, event->x, event->y);
2550                                 
2551                                 if (G.debug & G_DEBUG) {
2552                                         printf("found alternative region %p (old was %p) - at %d %d (sa: %d %d -> %d %d)\n",
2553                                                 current_region, p->ar, event->x, event->y,
2554                                                 p->sa->totrct.xmin, p->sa->totrct.ymin, p->sa->totrct.xmax, p->sa->totrct.ymax);
2555                                 }
2556                                 
2557                                 if (current_region) {
2558                                         /* Assume that since we found the cursor in here, it is in bounds
2559                                          * and that this should be the region that we begin drawing in
2560                                          */
2561                                         p->ar = current_region;
2562                                         in_bounds = true;
2563                                 }
2564                                 else {
2565                                         /* Out of bounds, or invalid in some other way */
2566                                         p->status = GP_STATUS_ERROR;
2567                                         estate = OPERATOR_CANCELLED;
2568                                         
2569                                         if (G.debug & G_DEBUG)
2570                                                 printf("%s: Region under cursor is out of bounds, so cannot be drawn on\n", __func__);
2571                                 }
2572                         }
2573                         else if (p->ar) {
2574                                 rcti region_rect;
2575                                 
2576                                 /* Perform bounds check using  */
2577                                 ED_region_visible_rect(p->ar, &region_rect);
2578                                 in_bounds = BLI_rcti_isect_pt_v(&region_rect, event->mval);
2579                         }
2580                         else {
2581                                 /* No region */
2582                                 p->status = GP_STATUS_ERROR;
2583                                 estate = OPERATOR_CANCELLED;
2584                                 
2585                                 if (G.debug & G_DEBUG)
2586                                         printf("%s: No active region found in GP Paint session data\n", __func__);
2587                         }
2588                         
2589                         if (in_bounds) {
2590                                 /* Switch paintmode (temporarily if need be) based on which button was used
2591                                  * NOTE: This is to make it more convenient to erase strokes when using drawing sessions
2592                                  */
2593                                 if ((event->type == RIGHTMOUSE) || gpencil_is_tablet_eraser_active(event)) {
2594                                         /* turn on eraser */
2595                                         p->paintmode = GP_PAINTMODE_ERASER;
2596                                 }
2597                                 else if (event->type == LEFTMOUSE) {
2598                                         /* restore drawmode to default */
2599                                         p->paintmode = RNA_enum_get(op->ptr, "mode");
2600                                 }
2601                                 
2602                                 gpencil_draw_toggle_eraser_cursor(C, p, p->paintmode == GP_PAINTMODE_ERASER);
2603                                 
2604                                 /* not painting, so start stroke (this should be mouse-button down) */
2605                                 p = gpencil_stroke_begin(C, op);
2606                                 
2607                                 if (p->status == GP_STATUS_ERROR) {
2608                                         estate = OPERATOR_CANCELLED;
2609                                 }
2610                         }
2611                         else if (p->status != GP_STATUS_ERROR) {
2612                                 /* User clicked outside bounds of window while idling, so exit paintmode 
2613                                  * NOTE: Don't enter this case if an error occurred while finding the
2614                                  *       region (as above)
2615                                  */
2616                                 /* if drawing polygon and enable on back, must move stroke */
2617                                 if (ts) {
2618                                         if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode == GP_PAINTMODE_DRAW_POLY)) {
2619                                                 if (p->flags & GP_PAINTFLAG_STROKEADDED) {
2620                                                         gpencil_move_last_stroke_to_back(C);
2621                                                 }
2622                                         }
2623                                 }
2624                                 p->status = GP_STATUS_DONE;
2625                                 estate = OPERATOR_FINISHED;
2626                         }
2627                 }
2628                 else {
2629                         p->status = GP_STATUS_IDLING;
2630                         op->flag |= OP_IS_MODAL_CURSOR_REGION;
2631                 }
2632         }
2633         
2634         /* handle mode-specific events */
2635         if (p->status == GP_STATUS_PAINTING) {
2636                 /* handle painting mouse-movements? */
2637                 if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE) || (p->flags & GP_PAINTFLAG_FIRSTRUN)) {
2638                         /* handle drawing event */
2639                         /* printf("\t\tGP - add point\n"); */
2640                         gpencil_draw_apply_event(op, event);
2641                         
2642                         /* finish painting operation if anything went wrong just now */
2643                         if (p->status == GP_STATUS_ERROR) {
2644                                 printf("\t\t\t\tGP - add error done!\n");
2645                                 estate = OPERATOR_CANCELLED;
2646                         }
2647                         else {
2648                                 /* event handled, so just tag as running modal */
2649                                 /* printf("\t\t\t\tGP - add point handled!\n"); */
2650                                 estate = OPERATOR_RUNNING_MODAL;
2651                         }
2652                 }
2653                 /* eraser size */
2654                 else if ((p->paintmode == GP_PAINTMODE_ERASER) &&
2655                          ELEM(event->type, WHEELUPMOUSE, WHEELDOWNMOUSE, PADPLUSKEY, PADMINUS))
2656                 {
2657                         /* just resize the brush (local version)
2658                          * TODO: fix the hardcoded size jumps (set to make a visible difference) and hardcoded keys
2659                          */
2660                         /* printf("\t\tGP - resize eraser\n"); */
2661                         switch (event->type) {
2662                                 case WHEELDOWNMOUSE: /* larger */
2663                                 case PADPLUSKEY:
2664                                         p->radius += 5;
2665                                         break;
2666                                 
2667                                 case WHEELUPMOUSE: /* smaller */
2668                                 case PADMINUS:
2669                                         p->radius -= 5;
2670                                         
2671                                         if (p->radius <= 0)
2672                                                 p->radius = 1;
2673                                         break;
2674                         }
2675                         
2676                         /* force refresh */
2677                         ED_region_tag_redraw(p->ar); /* just active area for now, since doing whole screen is too slow */
2678                         
2679                         /* event handled, so just tag as running modal */
2680                         estate = OPERATOR_RUNNING_MODAL;
2681                 }
2682                 /* there shouldn't be any other events, but just in case there are, let's swallow them
2683                  * (i.e. to prevent problems with undo)
2684                  */
2685                 else {
2686                         /* swallow event to save ourselves trouble */
2687                         estate = OPERATOR_RUNNING_MODAL;
2688                 }
2689         }
2690         
2691         /* gpencil modal operator stores area, which can be removed while using it (like fullscreen) */
2692         if (0 == gpencil_area_exists(C, p->sa))
2693                 estate = OPERATOR_CANCELLED;
2694         else {
2695                 /* update status indicators - cursor, header, etc. */
2696                 gpencil_draw_status_indicators(p);
2697                 gpencil_draw_cursor_set(p); /* cursor may have changed outside our control - T44084 */
2698         }
2699         
2700         /* process last operations before exiting */
2701         switch (estate) {
2702                 case OPERATOR_FINISHED:
2703                         /* one last flush before we're done */
2704                         gpencil_draw_exit(C, op);
2705                         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
2706                         break;
2707                 
2708                 case OPERATOR_CANCELLED:
2709                         gpencil_draw_exit(C, op);
2710                         break;
2711                 
2712                 case OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH:
2713                         /* event doesn't need to be handled */
2714 #if 0
2715                         printf("unhandled event -> %d (mmb? = %d | mmv? = %d)\n",
2716                                event->type, event->type == MIDDLEMOUSE, event->type==MOUSEMOVE);
2717 #endif
2718                         break;
2719         }
2720         
2721         /* return status code */
2722         return estate;
2723 }
2724
2725 /* ------------------------------- */
2726
2727 static EnumPropertyItem prop_gpencil_drawmodes[] = {
2728         {GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
2729         {GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
2730         {GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
2731         {GP_PAINTMODE_ERASER, "ERASER", 0, "Eraser", "Erase Grease Pencil strokes"},
2732         {0, NULL, 0, NULL, NULL}
2733 };
2734
2735 void GPENCIL_OT_draw(wmOperatorType *ot)
2736 {
2737         /* identifiers */
2738         ot->name = "Grease Pencil Draw";
2739         ot->idname = "GPENCIL_OT_draw";
2740         ot->description = "Make annotations on the active data";
2741         
2742         /* api callbacks */
2743         ot->exec = gpencil_draw_exec;
2744         ot->invoke = gpencil_draw_invoke;
2745         ot->modal = gpencil_draw_modal;
2746         ot->cancel = gpencil_draw_cancel;
2747         ot->poll = gpencil_draw_poll;
2748         
2749         /* flags */
2750         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
2751         
2752         /* settings for drawing */
2753         ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
2754         RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2755         
2756         /* NOTE: wait for input is enabled by default, so that all UI code can work properly without needing users to know about this */
2757         RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
2758 }