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