e7e6d7a5f7f09f10dbc306b836cfcaffaa22f78a
[blender.git] / source / blender / editors / gpencil / gpencil_brush.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2015, Blender Foundation
17  * This is a new part of Blender
18  * Brush based operators for editing Grease Pencil strokes
19  */
20
21 /** \file
22  * \ingroup edgpencil
23  */
24
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <stddef.h>
30 #include <math.h>
31
32 #include "MEM_guardedalloc.h"
33
34 #include "BLI_blenlib.h"
35 #include "BLI_ghash.h"
36 #include "BLI_math.h"
37 #include "BLI_rand.h"
38 #include "BLI_utildefines.h"
39
40 #include "PIL_time.h"
41
42 #include "BLT_translation.h"
43
44 #include "DNA_meshdata_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_space_types.h"
48 #include "DNA_view3d_types.h"
49 #include "DNA_gpencil_types.h"
50 #include "DNA_object_types.h"
51
52 #include "BKE_colortools.h"
53 #include "BKE_context.h"
54 #include "BKE_deform.h"
55 #include "BKE_gpencil.h"
56 #include "BKE_material.h"
57 #include "BKE_object_deform.h"
58 #include "BKE_report.h"
59
60 #include "UI_interface.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "RNA_access.h"
66 #include "RNA_define.h"
67 #include "RNA_enum_types.h"
68
69 #include "UI_view2d.h"
70
71 #include "ED_gpencil.h"
72 #include "ED_screen.h"
73 #include "ED_view3d.h"
74
75 #include "GPU_immediate.h"
76 #include "GPU_immediate_util.h"
77 #include "GPU_state.h"
78
79 #include "DEG_depsgraph.h"
80 #include "DEG_depsgraph_query.h"
81
82 #include "gpencil_intern.h"
83
84 /* ************************************************ */
85 /* General Brush Editing Context */
86
87 /* Context for brush operators */
88 typedef struct tGP_BrushEditData {
89         /* Current editor/region/etc. */
90         /* NOTE: This stuff is mainly needed to handle 3D view projection stuff... */
91         Depsgraph *depsgraph;
92         Scene *scene;
93         Object *object;
94
95         ScrArea *sa;
96         ARegion *ar;
97
98         /* Current GPencil datablock */
99         bGPdata *gpd;
100
101         /* Brush Settings */
102         GP_Sculpt_Settings *settings;
103         GP_Sculpt_Data *gp_brush;
104         GP_Sculpt_Data *gp_brush_old;
105
106         eGP_Sculpt_Types brush_type;
107         eGP_Sculpt_Types brush_type_old;
108         eGP_Sculpt_Flag  flag;
109
110         /* Space Conversion Data */
111         GP_SpaceConversion gsc;
112
113
114         /* Is the brush currently painting? */
115         bool is_painting;
116         bool is_weight_mode;
117
118         /* Start of new sculpt stroke */
119         bool first;
120
121         /* Is multiframe editing enabled, and are we using falloff for that? */
122         bool is_multiframe;
123         bool use_multiframe_falloff;
124
125         /* Current frame */
126         int cfra;
127
128
129         /* Brush Runtime Data: */
130         /* - position and pressure
131          * - the *_prev variants are the previous values
132          */
133         float   mval[2], mval_prev[2];
134         float pressure, pressure_prev;
135
136         /* - effect vector (e.g. 2D/3D translation for grab brush) */
137         float dvec[3];
138
139         /* - multiframe falloff factor */
140         float mf_falloff;
141
142         /* active vertex group */
143         int vrgroup;
144
145
146         /* brush geometry (bounding box) */
147         rcti brush_rect;
148
149         /* Custom data for certain brushes */
150         /* - map from bGPDstroke's to structs containing custom data about those strokes */
151         GHash *stroke_customdata;
152         /* - general customdata */
153         void *customdata;
154
155
156         /* Timer for in-place accumulation of brush effect */
157         wmTimer *timer;
158         bool timerTick; /* is this event from a timer */
159
160         RNG *rng;
161 } tGP_BrushEditData;
162
163
164 /* Callback for performing some brush operation on a single point */
165 typedef bool (*GP_BrushApplyCb)(
166         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
167         const int radius, const int co[2]);
168
169 /* ************************************************ */
170 /* Utility Functions */
171
172 /* apply lock axis reset */
173 static void gpsculpt_compute_lock_axis(tGP_BrushEditData *gso, bGPDspoint *pt, const float save_pt[3])
174 {
175         if (gso->sa->spacetype != SPACE_VIEW3D) {
176                 return;
177         }
178
179         const ToolSettings *ts = gso->scene->toolsettings;
180         const View3DCursor *cursor = &gso->scene->cursor;
181         const int axis = ts->gp_sculpt.lock_axis;
182
183         /* lock axis control */
184         switch (axis) {
185                 case GP_LOCKAXIS_X:
186                 {
187                         pt->x = save_pt[0];
188                         break;
189                 }
190                 case GP_LOCKAXIS_Y:
191                 {
192                         pt->y = save_pt[1];
193                         break;
194                 }
195                 case GP_LOCKAXIS_Z:
196                 {
197                         pt->z = save_pt[2];
198                         break;
199                 }
200                 case GP_LOCKAXIS_CURSOR:
201                 {
202                         /* compute a plane with cursor normal and position of the point
203                            before do the sculpt */
204                         const float scale[3] = { 1.0f, 1.0f, 1.0f };
205                         float plane_normal[3] = { 0.0f, 0.0f, 1.0f };
206                         float plane[4];
207                         float mat[4][4];
208                         float r_close[3];
209
210                         loc_eul_size_to_mat4(mat,
211                                 cursor->location,
212                                 cursor->rotation_euler,
213                                 scale);
214
215                         mul_mat3_m4_v3(mat, plane_normal);
216                         plane_from_point_normal_v3(plane, save_pt, plane_normal);
217
218                         /* find closest point to the plane with the new position */
219                         closest_to_plane_v3(r_close, plane, &pt->x);
220                         copy_v3_v3(&pt->x, r_close);
221                         break;
222                 }
223                 default:
224                 {
225                         break;
226                 }
227         }
228 }
229
230 /* Context ---------------------------------------- */
231
232 /* Get the sculpting settings */
233 static GP_Sculpt_Settings *gpsculpt_get_settings(Scene *scene)
234 {
235         return &scene->toolsettings->gp_sculpt;
236 }
237
238 /* Get the active brush */
239 static GP_Sculpt_Data *gpsculpt_get_brush(Scene *scene, bool is_weight_mode)
240 {
241         GP_Sculpt_Settings *gset = &scene->toolsettings->gp_sculpt;
242         GP_Sculpt_Data *gp_brush = NULL;
243         if (is_weight_mode) {
244                 gp_brush = &gset->brush[gset->weighttype];
245         }
246         else {
247                 gp_brush = &gset->brush[gset->brushtype];
248         }
249
250         return gp_brush;
251 }
252
253 /* Brush Operations ------------------------------- */
254
255 /* Invert behavior of brush? */
256 static bool gp_brush_invert_check(tGP_BrushEditData *gso)
257 {
258         /* The basic setting is the brush's setting (from the panel) */
259         bool invert = ((gso->gp_brush->flag & GP_SCULPT_FLAG_INVERT) != 0);
260
261         /* During runtime, the user can hold down the Ctrl key to invert the basic behavior */
262         if (gso->flag & GP_SCULPT_FLAG_INVERT) {
263                 invert ^= true;
264         }
265
266         /* set temporary status */
267         if (invert) {
268                 gso->gp_brush->flag |= GP_SCULPT_FLAG_TMP_INVERT;
269         }
270         else {
271                 gso->gp_brush->flag &= ~GP_SCULPT_FLAG_TMP_INVERT;
272         }
273
274         return invert;
275 }
276
277 /* Compute strength of effect */
278 static float gp_brush_influence_calc(tGP_BrushEditData *gso, const int radius, const int co[2])
279 {
280         GP_Sculpt_Data *gp_brush = gso->gp_brush;
281
282         /* basic strength factor from brush settings */
283         float influence = gp_brush->strength;
284
285         /* use pressure? */
286         if (gp_brush->flag & GP_SCULPT_FLAG_USE_PRESSURE) {
287                 influence *= gso->pressure;
288         }
289
290         /* distance fading */
291         if (gp_brush->flag & GP_SCULPT_FLAG_USE_FALLOFF) {
292                 int mval_i[2];
293                 round_v2i_v2fl(mval_i, gso->mval);
294                 float distance = (float)len_v2v2_int(mval_i, co);
295                 float fac;
296
297                 CLAMP(distance, 0.0f, (float)radius);
298                 fac = 1.0f - (distance / (float)radius);
299
300                 influence *= fac;
301         }
302
303         /* apply multiframe falloff */
304         influence *= gso->mf_falloff;
305
306         /* return influence */
307         return influence;
308 }
309
310 /* ************************************************ */
311 /* Brush Callbacks */
312 /* This section defines the callbacks used by each brush to perform their magic.
313  * These are called on each point within the brush's radius.
314  */
315
316 /* ----------------------------------------------- */
317 /* Smooth Brush */
318
319 /* A simple (but slower + inaccurate) smooth-brush implementation to test the algorithm for stroke smoothing */
320 static bool gp_brush_smooth_apply(
321         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
322         const int radius, const int co[2])
323 {
324         // GP_Sculpt_Data *gp_brush = gso->brush;
325         float inf = gp_brush_influence_calc(gso, radius, co);
326         /* need one flag enabled by default */
327         if ((gso->settings->flag &
328              (GP_SCULPT_SETT_FLAG_APPLY_POSITION |
329               GP_SCULPT_SETT_FLAG_APPLY_STRENGTH |
330               GP_SCULPT_SETT_FLAG_APPLY_THICKNESS |
331               GP_SCULPT_SETT_FLAG_APPLY_UV)) == 0)
332         {
333                 gso->settings->flag |= GP_SCULPT_SETT_FLAG_APPLY_POSITION;
334         }
335
336         /* perform smoothing */
337         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_POSITION) {
338                 BKE_gpencil_smooth_stroke(gps, pt_index, inf);
339         }
340         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_STRENGTH) {
341                 BKE_gpencil_smooth_stroke_strength(gps, pt_index, inf);
342         }
343         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_THICKNESS) {
344                 BKE_gpencil_smooth_stroke_thickness(gps, pt_index, inf);
345         }
346         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_UV) {
347                 BKE_gpencil_smooth_stroke_uv(gps, pt_index, inf);
348         }
349
350         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
351
352         return true;
353 }
354
355 /* ----------------------------------------------- */
356 /* Line Thickness Brush */
357
358 /* Make lines thicker or thinner by the specified amounts */
359 static bool gp_brush_thickness_apply(
360         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
361         const int radius, const int co[2])
362 {
363         bGPDspoint *pt = gps->points + pt_index;
364         float inf;
365
366         /* Compute strength of effect
367          * - We divide the strength by 10, so that users can set "sane" values.
368          *   Otherwise, good default values are in the range of 0.093
369          */
370         inf = gp_brush_influence_calc(gso, radius, co) / 10.0f;
371
372         /* apply */
373         // XXX: this is much too strong, and it should probably do some smoothing with the surrounding stuff
374         if (gp_brush_invert_check(gso)) {
375                 /* make line thinner - reduce stroke pressure */
376                 pt->pressure -= inf;
377         }
378         else {
379                 /* make line thicker - increase stroke pressure */
380                 pt->pressure += inf;
381         }
382
383         /* Pressure should stay within [0.0, 1.0]
384          * However, it is nice for volumetric strokes to be able to exceed
385          * the upper end of this range. Therefore, we don't actually clamp
386          * down on the upper end.
387          */
388         if (pt->pressure < 0.0f)
389                 pt->pressure = 0.0f;
390
391         return true;
392 }
393
394
395 /* ----------------------------------------------- */
396 /* Color Strength Brush */
397
398 /* Make color more or less transparent by the specified amounts */
399 static bool gp_brush_strength_apply(
400         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
401         const int radius, const int co[2])
402 {
403         bGPDspoint *pt = gps->points + pt_index;
404         float inf;
405
406         /* Compute strength of effect
407          * - We divide the strength, so that users can set "sane" values.
408          *   Otherwise, good default values are in the range of 0.093
409          */
410         inf = gp_brush_influence_calc(gso, radius, co) / 20.0f;
411
412         /* apply */
413         if (gp_brush_invert_check(gso)) {
414                 /* make line more transparent - reduce alpha factor */
415                 pt->strength -= inf;
416         }
417         else {
418                 /* make line more opaque - increase stroke strength */
419                 pt->strength += inf;
420         }
421         /* smooth the strength */
422         BKE_gpencil_smooth_stroke_strength(gps, pt_index, inf);
423
424         /* Strength should stay within [0.0, 1.0] */
425         CLAMP(pt->strength, 0.0f, 1.0f);
426
427         return true;
428 }
429
430
431 /* ----------------------------------------------- */
432 /* Grab Brush */
433
434 /* Custom data per stroke for the Grab Brush
435  *
436  * This basically defines the strength of the effect for each
437  * affected stroke point that was within the initial range of
438  * the brush region.
439  */
440 typedef struct tGPSB_Grab_StrokeData {
441         /* array of indices to corresponding points in the stroke */
442         int   *points;
443         /* array of influence weights for each of the included points */
444         float *weights;
445
446         /* capacity of the arrays */
447         int capacity;
448         /* actual number of items currently stored */
449         int size;
450 } tGPSB_Grab_StrokeData;
451
452 /* initialise custom data for handling this stroke */
453 static void gp_brush_grab_stroke_init(tGP_BrushEditData *gso, bGPDstroke *gps)
454 {
455         tGPSB_Grab_StrokeData *data = NULL;
456
457         BLI_assert(gps->totpoints > 0);
458
459         /* Check if there are buffers already (from a prior run) */
460         if (BLI_ghash_haskey(gso->stroke_customdata, gps)) {
461                 /* Ensure that the caches are empty
462                  * - Since we reuse these between different strokes, we don't
463                  *   want the previous invocation's data polluting the arrays
464                  */
465                 data = BLI_ghash_lookup(gso->stroke_customdata, gps);
466                 BLI_assert(data != NULL);
467
468                 data->size = 0; /* minimum requirement - so that we can repopulate again */
469
470                 memset(data->points, 0, sizeof(int) * data->capacity);
471                 memset(data->weights, 0, sizeof(float) * data->capacity);
472         }
473         else {
474                 /* Create new instance */
475                 data = MEM_callocN(sizeof(tGPSB_Grab_StrokeData), "GP Stroke Grab Data");
476
477                 data->capacity = gps->totpoints;
478                 data->size = 0;
479
480                 data->points  = MEM_callocN(sizeof(int) * data->capacity, "GP Stroke Grab Indices");
481                 data->weights = MEM_callocN(sizeof(float) * data->capacity, "GP Stroke Grab Weights");
482
483                 /* hook up to the cache */
484                 BLI_ghash_insert(gso->stroke_customdata, gps, data);
485         }
486 }
487
488 /* store references to stroke points in the initial stage */
489 static bool gp_brush_grab_store_points(
490         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
491         const int radius, const int co[2])
492 {
493         tGPSB_Grab_StrokeData *data = BLI_ghash_lookup(gso->stroke_customdata, gps);
494         float inf = gp_brush_influence_calc(gso, radius, co);
495
496         BLI_assert(data != NULL);
497         BLI_assert(data->size < data->capacity);
498
499         /* insert this point into the set of affected points */
500         data->points[data->size]  = pt_index;
501         data->weights[data->size] = inf;
502         data->size++;
503
504         /* done */
505         return true;
506 }
507
508 /* Compute effect vector for grab brush */
509 static void gp_brush_grab_calc_dvec(tGP_BrushEditData *gso)
510 {
511         /* Convert mouse-movements to movement vector */
512         // TODO: incorporate pressure into this?
513         // XXX: screen-space strokes in 3D space will suffer!
514         if (gso->sa->spacetype == SPACE_VIEW3D) {
515                 RegionView3D *rv3d = gso->ar->regiondata;
516                 float *rvec = gso->scene->cursor.location;
517                 float zfac = ED_view3d_calc_zfac(rv3d, rvec, NULL);
518
519                 float mval_f[2];
520
521                 /* convert from 2D screenspace to 3D... */
522                 mval_f[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
523                 mval_f[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
524
525                 ED_view3d_win_to_delta(gso->ar, mval_f, gso->dvec, zfac);
526         }
527         else {
528                 /* 2D - just copy */
529                 // XXX: view2d?
530                 gso->dvec[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
531                 gso->dvec[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
532                 gso->dvec[2] = 0.0f;  /* unused */
533         }
534 }
535
536 /* Apply grab transform to all relevant points of the affected strokes */
537 static void gp_brush_grab_apply_cached(
538         tGP_BrushEditData *gso, bGPDstroke *gps, float diff_mat[4][4])
539 {
540         tGPSB_Grab_StrokeData *data = BLI_ghash_lookup(gso->stroke_customdata, gps);
541         int i;
542
543         /* Apply dvec to all of the stored points */
544         for (i = 0; i < data->size; i++) {
545                 bGPDspoint *pt = &gps->points[data->points[i]];
546                 float delta[3] = {0.0f};
547
548                 /* adjust the amount of displacement to apply */
549                 mul_v3_v3fl(delta, gso->dvec, data->weights[i]);
550
551                 float fpt[3];
552                 float save_pt[3];
553                 copy_v3_v3(save_pt, &pt->x);
554                 /* apply transformation */
555                 mul_v3_m4v3(fpt, diff_mat, &pt->x);
556                 /* apply */
557                 add_v3_v3v3(&pt->x, fpt, delta);
558                 /* undo transformation to the init parent position */
559                 float inverse_diff_mat[4][4];
560                 invert_m4_m4(inverse_diff_mat, diff_mat);
561                 mul_m4_v3(inverse_diff_mat, &pt->x);
562
563                 /* compute lock axis */
564                 gpsculpt_compute_lock_axis(gso, pt, save_pt);
565         }
566         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
567 }
568
569 /* free customdata used for handling this stroke */
570 static void gp_brush_grab_stroke_free(void *ptr)
571 {
572         tGPSB_Grab_StrokeData *data = (tGPSB_Grab_StrokeData *)ptr;
573
574         /* free arrays */
575         MEM_freeN(data->points);
576         MEM_freeN(data->weights);
577
578         /* ... and this item itself, since it was also allocated */
579         MEM_freeN(data);
580 }
581
582 /* ----------------------------------------------- */
583 /* Push Brush */
584 /* NOTE: Depends on gp_brush_grab_calc_dvec() */
585
586 static bool gp_brush_push_apply(
587         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
588         const int radius, const int co[2])
589 {
590         bGPDspoint *pt = gps->points + pt_index;
591         float save_pt[3];
592         copy_v3_v3(save_pt, &pt->x);
593
594         float inf = gp_brush_influence_calc(gso, radius, co);
595         float delta[3] = {0.0f};
596
597         /* adjust the amount of displacement to apply */
598         mul_v3_v3fl(delta, gso->dvec, inf);
599
600         /* apply */
601         add_v3_v3(&pt->x, delta);
602
603         /* compute lock axis */
604         gpsculpt_compute_lock_axis(gso, pt, save_pt);
605
606         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
607
608         /* done */
609         return true;
610 }
611
612 /* ----------------------------------------------- */
613 /* Pinch Brush */
614
615 /* Compute reference midpoint for the brush - this is what we'll be moving towards */
616 static void gp_brush_calc_midpoint(tGP_BrushEditData *gso)
617 {
618         if (gso->sa->spacetype == SPACE_VIEW3D) {
619                 /* Convert mouse position to 3D space
620                  * See: gpencil_paint.c :: gp_stroke_convertcoords()
621                  */
622                 RegionView3D *rv3d = gso->ar->regiondata;
623                 const float *rvec = gso->scene->cursor.location;
624                 float zfac = ED_view3d_calc_zfac(rv3d, rvec, NULL);
625
626                 float mval_f[2];
627                 copy_v2_v2(mval_f, gso->mval);
628                 float mval_prj[2];
629                 float dvec[3];
630
631
632                 if (ED_view3d_project_float_global(gso->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
633                         sub_v2_v2v2(mval_f, mval_prj, mval_f);
634                         ED_view3d_win_to_delta(gso->ar, mval_f, dvec, zfac);
635                         sub_v3_v3v3(gso->dvec, rvec, dvec);
636                 }
637                 else {
638                         zero_v3(gso->dvec);
639                 }
640         }
641         else {
642                 /* Just 2D coordinates */
643                 // XXX: fix View2D offsets later
644                 gso->dvec[0] = (float)gso->mval[0];
645                 gso->dvec[1] = (float)gso->mval[1];
646                 gso->dvec[2] = 0.0f;
647         }
648 }
649
650 /* Shrink distance between midpoint and this point... */
651 static bool gp_brush_pinch_apply(
652         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
653         const int radius, const int co[2])
654 {
655         bGPDspoint *pt = gps->points + pt_index;
656         float fac, inf;
657         float vec[3];
658         float save_pt[3];
659         copy_v3_v3(save_pt, &pt->x);
660
661         /* Scale down standard influence value to get it more manageable...
662          * - No damping = Unmanageable at > 0.5 strength
663          * - Div 10     = Not enough effect
664          * - Div 5      = Happy medium... (by trial and error)
665          */
666         inf = gp_brush_influence_calc(gso, radius, co) / 5.0f;
667
668         /* 1) Make this point relative to the cursor/midpoint (dvec) */
669         sub_v3_v3v3(vec, &pt->x, gso->dvec);
670
671         /* 2) Shrink the distance by pulling the point towards the midpoint
672          *    (0.0 = at midpoint, 1 = at edge of brush region)
673          *                         OR
674          *    Increase the distance (if inverting the brush action!)
675          */
676         if (gp_brush_invert_check(gso)) {
677                 /* Inflate (inverse) */
678                 fac = 1.0f + (inf * inf); /* squared to temper the effect... */
679         }
680         else {
681                 /* Shrink (default) */
682                 fac = 1.0f - (inf * inf); /* squared to temper the effect... */
683         }
684         mul_v3_fl(vec, fac);
685
686         /* 3) Translate back to original space, with the shrinkage applied */
687         add_v3_v3v3(&pt->x, gso->dvec, vec);
688
689         /* compute lock axis */
690         gpsculpt_compute_lock_axis(gso, pt, save_pt);
691
692         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
693
694         /* done */
695         return true;
696 }
697
698 /* ----------------------------------------------- */
699 /* Twist Brush - Rotate Around midpoint */
700
701 /* Take the screenspace coordinates of the point, rotate this around the brush midpoint,
702  * convert the rotated point and convert it into "data" space
703  */
704
705 static bool gp_brush_twist_apply(
706         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
707         const int radius, const int co[2])
708 {
709         bGPDspoint *pt = gps->points + pt_index;
710         float angle, inf;
711         float save_pt[3];
712         copy_v3_v3(save_pt, &pt->x);
713
714         /* Angle to rotate by */
715         inf = gp_brush_influence_calc(gso, radius, co);
716         angle = DEG2RADF(1.0f) * inf;
717
718         if (gp_brush_invert_check(gso)) {
719                 /* invert angle that we rotate by */
720                 angle *= -1;
721         }
722
723         /* Rotate in 2D or 3D space? */
724         if (gps->flag & GP_STROKE_3DSPACE) {
725                 /* Perform rotation in 3D space... */
726                 RegionView3D *rv3d = gso->ar->regiondata;
727                 float rmat[3][3];
728                 float axis[3];
729                 float vec[3];
730
731                 /* Compute rotation matrix - rotate around view vector by angle */
732                 negate_v3_v3(axis, rv3d->persinv[2]);
733                 normalize_v3(axis);
734
735                 axis_angle_normalized_to_mat3(rmat, axis, angle);
736
737                 /* Rotate point (no matrix-space transforms needed, as GP points are in world space) */
738                 sub_v3_v3v3(vec, &pt->x, gso->dvec); /* make relative to center
739                                                       * (center is stored in dvec) */
740                 mul_m3_v3(rmat, vec);
741                 add_v3_v3v3(&pt->x, vec, gso->dvec); /* restore */
742
743                 /* compute lock axis */
744                 gpsculpt_compute_lock_axis(gso, pt, save_pt);
745         }
746         else {
747                 const float axis[3] = {0.0f, 0.0f, 1.0f};
748                 float vec[3] = {0.0f};
749                 float rmat[3][3];
750
751                 /* Express position of point relative to cursor, ready to rotate */
752                 // XXX: There is still some offset here, but it's close to working as expected...
753                 vec[0] = (float)(co[0] - gso->mval[0]);
754                 vec[1] = (float)(co[1] - gso->mval[1]);
755
756                 /* rotate point */
757                 axis_angle_normalized_to_mat3(rmat, axis, angle);
758                 mul_m3_v3(rmat, vec);
759
760                 /* Convert back to screen-coordinates */
761                 vec[0] += (float)gso->mval[0];
762                 vec[1] += (float)gso->mval[1];
763
764                 /* Map from screen-coordinates to final coordinate space */
765                 if (gps->flag & GP_STROKE_2DSPACE) {
766                         View2D *v2d = gso->gsc.v2d;
767                         UI_view2d_region_to_view(v2d, vec[0], vec[1], &pt->x, &pt->y);
768                 }
769                 else {
770                         // XXX
771                         copy_v2_v2(&pt->x, vec);
772                 }
773         }
774
775         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
776
777         /* done */
778         return true;
779 }
780
781
782 /* ----------------------------------------------- */
783 /* Randomize Brush */
784
785 /* Apply some random jitter to the point */
786 static bool gp_brush_randomize_apply(
787         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
788         const int radius, const int co[2])
789 {
790         bGPDspoint *pt = gps->points + pt_index;
791         float save_pt[3];
792         copy_v3_v3(save_pt, &pt->x);
793
794         /* Amount of jitter to apply depends on the distance of the point to the cursor,
795          * as well as the strength of the brush
796          */
797         const float inf = gp_brush_influence_calc(gso, radius, co) / 2.0f;
798         const float fac = BLI_rng_get_float(gso->rng) * inf;
799         /* need one flag enabled by default */
800         if ((gso->settings->flag &
801              (GP_SCULPT_SETT_FLAG_APPLY_POSITION |
802               GP_SCULPT_SETT_FLAG_APPLY_STRENGTH |
803               GP_SCULPT_SETT_FLAG_APPLY_THICKNESS |
804               GP_SCULPT_SETT_FLAG_APPLY_UV)) == 0)
805         {
806                 gso->settings->flag |= GP_SCULPT_SETT_FLAG_APPLY_POSITION;
807         }
808
809         /* apply random to position */
810         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_POSITION) {
811                 /* Jitter is applied perpendicular to the mouse movement vector
812                  * - We compute all effects in screenspace (since it's easier)
813                  *   and then project these to get the points/distances in
814                  *   view-space as needed.
815                  */
816                 float mvec[2], svec[2];
817
818                 /* mouse movement in ints -> floats */
819                 mvec[0] = (float)(gso->mval[0] - gso->mval_prev[0]);
820                 mvec[1] = (float)(gso->mval[1] - gso->mval_prev[1]);
821
822                 /* rotate mvec by 90 degrees... */
823                 svec[0] = -mvec[1];
824                 svec[1] =  mvec[0];
825
826                 /* scale the displacement by the random displacement, and apply */
827                 if (BLI_rng_get_float(gso->rng) > 0.5f) {
828                         mul_v2_fl(svec, -fac);
829                 }
830                 else {
831                         mul_v2_fl(svec, fac);
832                 }
833
834                 //printf("%f %f (%f), nco = {%f %f}, co = %d %d\n", svec[0], svec[1], fac, nco[0], nco[1], co[0], co[1]);
835
836                 /* convert to dataspace */
837                 if (gps->flag & GP_STROKE_3DSPACE) {
838                         /* 3D: Project to 3D space */
839                         if (gso->sa->spacetype == SPACE_VIEW3D) {
840                                 bool flip;
841                                 RegionView3D *rv3d = gso->ar->regiondata;
842                                 float zfac = ED_view3d_calc_zfac(rv3d, &pt->x, &flip);
843                                 if (flip == false) {
844                                         float dvec[3];
845                                         ED_view3d_win_to_delta(gso->gsc.ar, svec, dvec, zfac);
846                                         add_v3_v3(&pt->x, dvec);
847                                         /* compute lock axis */
848                                         gpsculpt_compute_lock_axis(gso, pt, save_pt);
849                                 }
850                         }
851                         else {
852                                 /* ERROR */
853                                 BLI_assert(!"3D stroke being sculpted in non-3D view");
854                         }
855                 }
856                 else {
857                         /* 2D: As-is */
858                         // XXX: v2d scaling/offset?
859                         float nco[2];
860                         nco[0] = (float)co[0] + svec[0];
861                         nco[1] = (float)co[1] + svec[1];
862
863                         copy_v2_v2(&pt->x, nco);
864                 }
865         }
866         /* apply random to strength */
867         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_STRENGTH) {
868                 if (BLI_rng_get_float(gso->rng) > 0.5f) {
869                         pt->strength += fac;
870                 }
871                 else {
872                         pt->strength -= fac;
873                 }
874                 CLAMP_MIN(pt->strength, 0.0f);
875                 CLAMP_MAX(pt->strength, 1.0f);
876         }
877         /* apply random to thickness (use pressure) */
878         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_THICKNESS) {
879                 if (BLI_rng_get_float(gso->rng) > 0.5f) {
880                         pt->pressure += fac;
881                 }
882                 else {
883                         pt->pressure -= fac;
884                 }
885                 /* only limit lower value */
886                 CLAMP_MIN(pt->pressure, 0.0f);
887         }
888         /* apply random to UV (use pressure) */
889         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_APPLY_UV) {
890                 if (BLI_rng_get_float(gso->rng) > 0.5f) {
891                         pt->uv_rot += fac;
892                 }
893                 else {
894                         pt->uv_rot -= fac;
895                 }
896                 CLAMP(pt->uv_rot, -M_PI_2, M_PI_2);
897         }
898
899         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
900
901         /* done */
902         return true;
903 }
904
905 /* Weight Paint Brush */
906
907 /* Change weight paint for vertex groups */
908 static bool gp_brush_weight_apply(
909         tGP_BrushEditData *gso, bGPDstroke *gps, int pt_index,
910         const int radius, const int co[2])
911 {
912         /* create dvert */
913         BKE_gpencil_dvert_ensure(gps);
914
915         bGPDspoint *pt = gps->points + pt_index;
916         MDeformVert *dvert = gps->dvert + pt_index;
917         float inf;
918
919         /* Compute strength of effect
920          * - We divide the strength by 10, so that users can set "sane" values.
921          *   Otherwise, good default values are in the range of 0.093
922          */
923         inf = gp_brush_influence_calc(gso, radius, co) / 10.0f;
924
925         /* need a vertex group */
926         if (gso->vrgroup == -1) {
927                 if (gso->object) {
928                         BKE_object_defgroup_add(gso->object);
929                         gso->vrgroup = 0;
930                 }
931         }
932         /* get current weight */
933         MDeformWeight *dw = defvert_verify_index(dvert, gso->vrgroup);
934         float curweight = dw ? dw->weight : 0.0f;
935
936         if (gp_brush_invert_check(gso)) {
937                 /* reduce weight */
938                 curweight -= inf;
939         }
940         else {
941                 /* increase weight */
942                 curweight += inf;
943         }
944
945         /* verify target weight */
946         CLAMP_MAX(curweight, gso->gp_brush->weight);
947
948         CLAMP(curweight, 0.0f, 1.0f);
949         if (dw) {
950                 dw->weight = curweight;
951         }
952
953         /* weight should stay within [0.0, 1.0] */
954         if (pt->pressure < 0.0f)
955                 pt->pressure = 0.0f;
956
957         return true;
958 }
959
960
961
962 /* ************************************************ */
963 /* Non Callback-Based Brushes */
964
965 /* Clone Brush ------------------------------------- */
966 /* How this brush currently works:
967  * - If this is start of the brush stroke, paste immediately under the cursor
968  *   by placing the midpoint of the buffer strokes under the cursor now
969  *
970  * - Otherwise, in:
971  *   "Stamp Mode" - Move the newly pasted strokes so that their center follows the cursor
972  *   "Continuous" - Repeatedly just paste new copies for where the brush is now
973  */
974
975 /* Custom state data for clone brush */
976 typedef struct tGPSB_CloneBrushData {
977         /* midpoint of the strokes on the clipboard */
978         float buffer_midpoint[3];
979
980         /* number of strokes in the paste buffer (and/or to be created each time) */
981         size_t totitems;
982
983         /* for "stamp" mode, the currently pasted brushes */
984         bGPDstroke **new_strokes;
985
986         /* mapping from colors referenced per stroke, to the new colours in the "pasted" strokes */
987         GHash *new_colors;
988 } tGPSB_CloneBrushData;
989
990 /* Initialise "clone" brush data */
991 static void gp_brush_clone_init(bContext *C, tGP_BrushEditData *gso)
992 {
993         tGPSB_CloneBrushData *data;
994         bGPDstroke *gps;
995
996         /* init custom data */
997         gso->customdata = data = MEM_callocN(sizeof(tGPSB_CloneBrushData), "CloneBrushData");
998
999         /* compute midpoint of strokes on clipboard */
1000         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
1001                 if (ED_gpencil_stroke_can_use(C, gps)) {
1002                         const float dfac = 1.0f / ((float)gps->totpoints);
1003                         float mid[3] = {0.0f};
1004
1005                         bGPDspoint *pt;
1006                         int i;
1007
1008                         /* compute midpoint of this stroke */
1009                         for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
1010                                 float co[3];
1011
1012                                 mul_v3_v3fl(co, &pt->x, dfac);
1013                                 add_v3_v3(mid, co);
1014                         }
1015
1016                         /* combine this stroke's data with the main data */
1017                         add_v3_v3(data->buffer_midpoint, mid);
1018                         data->totitems++;
1019                 }
1020         }
1021
1022         /* Divide the midpoint by the number of strokes, to finish averaging it */
1023         if (data->totitems > 1) {
1024                 mul_v3_fl(data->buffer_midpoint, 1.0f / (float)data->totitems);
1025         }
1026
1027         /* Create a buffer for storing the current strokes */
1028         if (1 /*gso->brush->mode == GP_EDITBRUSH_CLONE_MODE_STAMP*/) {
1029                 data->new_strokes = MEM_callocN(sizeof(bGPDstroke *) * data->totitems, "cloned strokes ptr array");
1030         }
1031
1032         /* Init colormap for mapping between the pasted stroke's source color (names)
1033          * and the final colours that will be used here instead.
1034          */
1035         data->new_colors = gp_copybuf_validate_colormap(C);
1036 }
1037
1038 /* Free custom data used for "clone" brush */
1039 static void gp_brush_clone_free(tGP_BrushEditData *gso)
1040 {
1041         tGPSB_CloneBrushData *data = gso->customdata;
1042
1043         /* free strokes array */
1044         if (data->new_strokes) {
1045                 MEM_freeN(data->new_strokes);
1046                 data->new_strokes = NULL;
1047         }
1048
1049         /* free copybuf colormap */
1050         if (data->new_colors) {
1051                 BLI_ghash_free(data->new_colors, NULL, NULL);
1052                 data->new_colors = NULL;
1053         }
1054
1055         /* free the customdata itself */
1056         MEM_freeN(data);
1057         gso->customdata = NULL;
1058 }
1059
1060 /* Create new copies of the strokes on the clipboard */
1061 static void gp_brush_clone_add(bContext *C, tGP_BrushEditData *gso)
1062 {
1063         tGPSB_CloneBrushData *data = gso->customdata;
1064
1065         Object *ob = CTX_data_active_object(C);
1066         bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
1067         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1068         int cfra_eval = (int)DEG_get_ctime(depsgraph);
1069
1070         bGPDframe *gpf = BKE_gpencil_layer_getframe(gpl, cfra_eval, GP_GETFRAME_ADD_NEW);
1071         bGPDstroke *gps;
1072
1073         float delta[3];
1074         size_t strokes_added = 0;
1075
1076         /* Compute amount to offset the points by */
1077         /* NOTE: This assumes that screenspace strokes are NOT used in the 3D view... */
1078
1079         gp_brush_calc_midpoint(gso); /* this puts the cursor location into gso->dvec */
1080         sub_v3_v3v3(delta, gso->dvec, data->buffer_midpoint);
1081
1082         /* Copy each stroke into the layer */
1083         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
1084                 if (ED_gpencil_stroke_can_use(C, gps)) {
1085                         bGPDstroke *new_stroke;
1086                         bGPDspoint *pt;
1087                         int i;
1088
1089                         /* Make a new stroke */
1090                         new_stroke = MEM_dupallocN(gps);
1091
1092                         new_stroke->points = MEM_dupallocN(gps->points);
1093                         if (gps->dvert != NULL) {
1094                                 new_stroke->dvert = MEM_dupallocN(gps->dvert);
1095                                 BKE_gpencil_stroke_weights_duplicate(gps, new_stroke);
1096                         }
1097                         new_stroke->triangles = MEM_dupallocN(gps->triangles);
1098
1099                         new_stroke->next = new_stroke->prev = NULL;
1100                         BLI_addtail(&gpf->strokes, new_stroke);
1101
1102                         /* Fix color references */
1103                         Material *ma = BLI_ghash_lookup(data->new_colors, &new_stroke->mat_nr);
1104                         gps->mat_nr = BKE_gpencil_object_material_get_index(ob, ma);
1105                         if (!ma || gps->mat_nr) {
1106                                 gps->mat_nr = 0;
1107                         }
1108                         /* Adjust all the stroke's points, so that the strokes
1109                          * get pasted relative to where the cursor is now
1110                          */
1111                         for (i = 0, pt = new_stroke->points; i < new_stroke->totpoints; i++, pt++) {
1112                                 /* assume that the delta can just be applied, and then everything works */
1113                                 add_v3_v3(&pt->x, delta);
1114                         }
1115
1116                         /* Store ref for later */
1117                         if ((data->new_strokes) && (strokes_added < data->totitems)) {
1118                                 data->new_strokes[strokes_added] = new_stroke;
1119                                 strokes_added++;
1120                         }
1121                 }
1122         }
1123 }
1124
1125 /* Move newly-added strokes around - "Stamp" mode of the Clone brush */
1126 static void gp_brush_clone_adjust(tGP_BrushEditData *gso)
1127 {
1128         tGPSB_CloneBrushData *data = gso->customdata;
1129         size_t snum;
1130
1131         /* Compute the amount of movement to apply (overwrites dvec) */
1132         gp_brush_grab_calc_dvec(gso);
1133
1134         /* For each of the stored strokes, apply the offset to each point */
1135         /* NOTE: Again this assumes that in the 3D view, we only have 3d space and not screenspace strokes... */
1136         for (snum = 0; snum < data->totitems; snum++) {
1137                 bGPDstroke *gps = data->new_strokes[snum];
1138                 bGPDspoint *pt;
1139                 int i;
1140
1141                 for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
1142                         if (gso->gp_brush->flag & GP_SCULPT_FLAG_USE_FALLOFF) {
1143                                 /* "Smudge" Effect when falloff is enabled */
1144                                 float delta[3] = {0.0f};
1145                                 int sco[2] = {0};
1146                                 float influence;
1147
1148                                 /* compute influence on point */
1149                                 gp_point_to_xy(&gso->gsc, gps, pt, &sco[0], &sco[1]);
1150                                 influence = gp_brush_influence_calc(gso, gso->gp_brush->size, sco);
1151
1152                                 /* adjust the amount of displacement to apply */
1153                                 mul_v3_v3fl(delta, gso->dvec, influence);
1154
1155                                 /* apply */
1156                                 add_v3_v3(&pt->x, delta);
1157                         }
1158                         else {
1159                                 /* Just apply the offset - All points move perfectly in sync with the cursor */
1160                                 add_v3_v3(&pt->x, gso->dvec);
1161                         }
1162                 }
1163         }
1164 }
1165
1166 /* Entrypoint for applying "clone" brush */
1167 static bool gpsculpt_brush_apply_clone(bContext *C, tGP_BrushEditData *gso)
1168 {
1169         /* Which "mode" are we operating in? */
1170         if (gso->first) {
1171                 /* Create initial clones */
1172                 gp_brush_clone_add(C, gso);
1173         }
1174         else {
1175                 /* Stamp or Continuous Mode */
1176                 if (1 /*gso->brush->mode == GP_EDITBRUSH_CLONE_MODE_STAMP*/) {
1177                         /* Stamp - Proceed to translate the newly added strokes */
1178                         gp_brush_clone_adjust(gso);
1179                 }
1180                 else {
1181                         /* Continuous - Just keep pasting everytime we move */
1182                         /* TODO: The spacing of repeat should be controlled using a "stepsize" or similar property? */
1183                         gp_brush_clone_add(C, gso);
1184                 }
1185         }
1186
1187         return true;
1188 }
1189
1190 /* ************************************************ */
1191 /* Header Info for GPencil Sculpt */
1192
1193 static void gpsculpt_brush_header_set(bContext *C, tGP_BrushEditData *gso)
1194 {
1195         const char *brush_name = NULL;
1196         char str[UI_MAX_DRAW_STR] = "";
1197
1198         RNA_enum_name(rna_enum_gpencil_sculpt_brush_items, gso->brush_type, &brush_name);
1199
1200         BLI_snprintf(str, sizeof(str),
1201                      IFACE_("GPencil Sculpt: %s Stroke  | LMB to paint | RMB/Escape to Exit"
1202                             " | Ctrl to Invert Action | Wheel Up/Down for Size "
1203                             " | Shift-Wheel Up/Down for Strength"),
1204                      (brush_name) ? brush_name : "<?>");
1205
1206         ED_workspace_status_text(C, str);
1207 }
1208
1209 /* ************************************************ */
1210 /* Grease Pencil Sculpting Operator */
1211
1212 /* Init/Exit ----------------------------------------------- */
1213
1214 static bool gpsculpt_brush_init(bContext *C, wmOperator *op)
1215 {
1216         Scene *scene = CTX_data_scene(C);
1217         ToolSettings *ts = CTX_data_tool_settings(C);
1218         Object *ob = CTX_data_active_object(C);
1219
1220         const bool is_weight_mode = ob->mode == OB_MODE_WEIGHT_GPENCIL;
1221         /* set the brush using the tool */
1222 #if 0
1223         GP_Sculpt_Settings *gset = &ts->gp_sculpt;
1224         eGP_Sculpt_Types mode = is_weight_mode ? gset->weighttype : gset->brushtype;
1225 #endif
1226         tGP_BrushEditData *gso;
1227
1228         /* setup operator data */
1229         gso = MEM_callocN(sizeof(tGP_BrushEditData), "tGP_BrushEditData");
1230         op->customdata = gso;
1231
1232         gso->depsgraph = CTX_data_depsgraph(C);
1233         /* store state */
1234         gso->settings = gpsculpt_get_settings(scene);
1235         gso->gp_brush = gpsculpt_get_brush(scene, is_weight_mode);
1236         gso->is_weight_mode = is_weight_mode;
1237
1238         if (is_weight_mode) {
1239                 gso->brush_type = gso->settings->weighttype;
1240         }
1241         else {
1242                 gso->brush_type = gso->settings->brushtype;
1243         }
1244
1245         /* Random generator, only init once. */
1246         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
1247         rng_seed ^= POINTER_AS_UINT(gso);
1248         gso->rng = BLI_rng_new(rng_seed);
1249
1250         gso->is_painting = false;
1251         gso->first = true;
1252
1253         gso->gpd = ED_gpencil_data_get_active(C);
1254         gso->cfra = INT_MAX; /* NOTE: So that first stroke will get handled in init_stroke() */
1255
1256         /* some brushes cannot use pressure for radius */
1257         if (ELEM(gso->brush_type, GP_SCULPT_TYPE_GRAB, GP_SCULPT_TYPE_CLONE)) {
1258                 gso->gp_brush->flag &= ~GP_SCULPT_FLAG_PRESSURE_RADIUS;
1259         }
1260
1261         gso->scene = scene;
1262         gso->object = ob;
1263         if (ob) {
1264                 gso->vrgroup = ob->actdef - 1;
1265                 if (!BLI_findlink(&ob->defbase, gso->vrgroup)) {
1266                         gso->vrgroup = -1;
1267                 }
1268         }
1269         else {
1270                 gso->vrgroup = - 1;
1271         }
1272
1273         gso->sa = CTX_wm_area(C);
1274         gso->ar = CTX_wm_region(C);
1275
1276         /* multiframe settings */
1277         gso->is_multiframe = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gso->gpd);
1278         gso->use_multiframe_falloff = (ts->gp_sculpt.flag & GP_SCULPT_SETT_FLAG_FRAME_FALLOFF) != 0;
1279
1280         /* Init multi-edit falloff curve data before doing anything,
1281          * so we won't have to do it again later. */
1282         if (gso->is_multiframe) {
1283                 curvemapping_initialize(ts->gp_sculpt.cur_falloff);
1284         }
1285
1286         /* initialise custom data for brushes */
1287         switch (gso->brush_type) {
1288                 case GP_SCULPT_TYPE_CLONE:
1289                 {
1290                         bGPDstroke *gps;
1291                         bool found = false;
1292
1293                         /* check that there are some usable strokes in the buffer */
1294                         for (gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
1295                                 if (ED_gpencil_stroke_can_use(C, gps)) {
1296                                         found = true;
1297                                         break;
1298                                 }
1299                         }
1300
1301                         if (found == false) {
1302                                 /* STOP HERE! Nothing to paste! */
1303                                 BKE_report(op->reports, RPT_ERROR,
1304                                            "Copy some strokes to the clipboard before using the Clone brush to paste copies of them");
1305
1306                                 MEM_freeN(gso);
1307                                 op->customdata = NULL;
1308                                 return false;
1309                         }
1310                         else {
1311                                 /* initialise customdata */
1312                                 gp_brush_clone_init(C, gso);
1313                         }
1314                         break;
1315                 }
1316
1317                 case GP_SCULPT_TYPE_GRAB:
1318                 {
1319                         /* initialise the cache needed for this brush */
1320                         gso->stroke_customdata = BLI_ghash_ptr_new("GP Grab Brush - Strokes Hash");
1321                         break;
1322                 }
1323
1324                 /* Others - No customdata needed */
1325                 default:
1326                         break;
1327         }
1328
1329
1330         /* setup space conversions */
1331         gp_point_conversion_init(C, &gso->gsc);
1332
1333         /* update header */
1334         gpsculpt_brush_header_set(C, gso);
1335
1336         /* setup cursor drawing */
1337         //WM_cursor_modal_set(CTX_wm_window(C), BC_CROSSCURSOR);
1338         if (gso->sa->spacetype != SPACE_VIEW3D) {
1339                 ED_gpencil_toggle_brush_cursor(C, true, NULL);
1340         }
1341         return true;
1342 }
1343
1344 static void gpsculpt_brush_exit(bContext *C, wmOperator *op)
1345 {
1346         tGP_BrushEditData *gso = op->customdata;
1347         wmWindow *win = CTX_wm_window(C);
1348
1349         /* free brush-specific data */
1350         switch (gso->brush_type) {
1351                 case GP_SCULPT_TYPE_GRAB:
1352                 {
1353                         /* Free per-stroke customdata
1354                          * - Keys don't need to be freed, as those are the strokes
1355                          * - Values assigned to those keys do, as they are custom structs
1356                          */
1357                         BLI_ghash_free(gso->stroke_customdata, NULL, gp_brush_grab_stroke_free);
1358                         break;
1359                 }
1360
1361                 case GP_SCULPT_TYPE_CLONE:
1362                 {
1363                         /* Free customdata */
1364                         gp_brush_clone_free(gso);
1365                         break;
1366                 }
1367
1368                 default:
1369                         break;
1370         }
1371
1372         /* unregister timer (only used for realtime) */
1373         if (gso->timer) {
1374                 WM_event_remove_timer(CTX_wm_manager(C), win, gso->timer);
1375         }
1376
1377         if (gso->rng != NULL) {
1378                 BLI_rng_free(gso->rng);
1379         }
1380
1381         /* disable cursor and headerprints */
1382         ED_workspace_status_text(C, NULL);
1383         WM_cursor_modal_restore(win);
1384         if (gso->sa->spacetype != SPACE_VIEW3D) {
1385                 ED_gpencil_toggle_brush_cursor(C, false, NULL);
1386         }
1387
1388         /* disable temp invert flag */
1389         gso->gp_brush->flag &= ~GP_SCULPT_FLAG_TMP_INVERT;
1390
1391         /* free operator data */
1392         MEM_freeN(gso);
1393         op->customdata = NULL;
1394 }
1395
1396 /* poll callback for stroke sculpting operator(s) */
1397 static bool gpsculpt_brush_poll(bContext *C)
1398 {
1399         /* NOTE: this is a bit slower, but is the most accurate... */
1400         return CTX_DATA_COUNT(C, editable_gpencil_strokes) != 0;
1401 }
1402
1403 /* Init Sculpt Stroke ---------------------------------- */
1404
1405 static void gpsculpt_brush_init_stroke(tGP_BrushEditData *gso)
1406 {
1407         bGPdata *gpd = gso->gpd;
1408
1409         bGPDlayer *gpl;
1410         int cfra_eval = (int)DEG_get_ctime(gso->depsgraph);
1411
1412         /* only try to add a new frame if this is the first stroke, or the frame has changed */
1413         if ((gpd == NULL) || (cfra_eval == gso->cfra))
1414                 return;
1415
1416         /* go through each layer, and ensure that we've got a valid frame to use */
1417         for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1418                 /* only editable and visible layers are considered */
1419                 if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
1420                         bGPDframe *gpf = gpl->actframe;
1421
1422                         /* Make a new frame to work on if the layer's frame and the current scene frame don't match up
1423                          * - This is useful when animating as it saves that "uh-oh" moment when you realize you've
1424                          *   spent too much time editing the wrong frame...
1425                          */
1426                         // XXX: should this be allowed when framelock is enabled?
1427                         if (gpf->framenum != cfra_eval) {
1428                                 BKE_gpencil_frame_addcopy(gpl, cfra_eval);
1429                         }
1430                 }
1431         }
1432
1433         /* save off new current frame, so that next update works fine */
1434         gso->cfra = cfra_eval;
1435 }
1436
1437 /* Apply ----------------------------------------------- */
1438
1439 /* Apply brush operation to points in this stroke */
1440 static bool gpsculpt_brush_do_stroke(
1441         tGP_BrushEditData *gso, bGPDstroke *gps,
1442         float diff_mat[4][4], GP_BrushApplyCb apply)
1443 {
1444         GP_SpaceConversion *gsc = &gso->gsc;
1445         rcti *rect = &gso->brush_rect;
1446         GP_Sculpt_Data *gp_brush = gso->gp_brush;
1447         const int radius = (gp_brush->flag & GP_SCULPT_FLAG_PRESSURE_RADIUS) ? gso->gp_brush->size * gso->pressure : gso->gp_brush->size;
1448
1449         bGPDspoint *pt1, *pt2;
1450         int pc1[2] = {0};
1451         int pc2[2] = {0};
1452         int i;
1453         bool include_last = false;
1454         bool changed = false;
1455
1456         if (gps->totpoints == 1) {
1457                 bGPDspoint pt_temp;
1458                 gp_point_to_parent_space(gps->points, diff_mat, &pt_temp);
1459                 gp_point_to_xy(gsc, gps, &pt_temp, &pc1[0], &pc1[1]);
1460
1461                 /* do boundbox check first */
1462                 if ((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) {
1463                         /* only check if point is inside */
1464                         int mval_i[2];
1465                         round_v2i_v2fl(mval_i, gso->mval);
1466                         if (len_v2v2_int(mval_i, pc1) <= radius) {
1467                                 /* apply operation to this point */
1468                                 changed = apply(gso, gps, 0, radius, pc1);
1469                         }
1470                 }
1471         }
1472         else {
1473                 /* Loop over the points in the stroke, checking for intersections
1474                  * - an intersection means that we touched the stroke
1475                  */
1476                 for (i = 0; (i + 1) < gps->totpoints; i++) {
1477                         /* Get points to work with */
1478                         pt1 = gps->points + i;
1479                         pt2 = gps->points + i + 1;
1480
1481                         /* Skip if neither one is selected (and we are only allowed to edit/consider selected points) */
1482                         if (gso->settings->flag & GP_SCULPT_SETT_FLAG_SELECT_MASK) {
1483                                 if (!(pt1->flag & GP_SPOINT_SELECT) && !(pt2->flag & GP_SPOINT_SELECT)) {
1484                                         include_last = false;
1485                                         continue;
1486                                 }
1487                         }
1488                         bGPDspoint npt;
1489                         gp_point_to_parent_space(pt1, diff_mat, &npt);
1490                         gp_point_to_xy(gsc, gps, &npt, &pc1[0], &pc1[1]);
1491
1492                         gp_point_to_parent_space(pt2, diff_mat, &npt);
1493                         gp_point_to_xy(gsc, gps, &npt, &pc2[0], &pc2[1]);
1494
1495                         /* Check that point segment of the boundbox of the selection stroke */
1496                         if (((!ELEM(V2D_IS_CLIPPED, pc1[0], pc1[1])) && BLI_rcti_isect_pt(rect, pc1[0], pc1[1])) ||
1497                             ((!ELEM(V2D_IS_CLIPPED, pc2[0], pc2[1])) && BLI_rcti_isect_pt(rect, pc2[0], pc2[1])))
1498                         {
1499                                 /* Check if point segment of stroke had anything to do with
1500                                  * brush region  (either within stroke painted, or on its lines)
1501                                  * - this assumes that linewidth is irrelevant
1502                                  */
1503                                 if (gp_stroke_inside_circle(gso->mval, gso->mval_prev, radius, pc1[0], pc1[1], pc2[0], pc2[1])) {
1504                                         /* Apply operation to these points */
1505                                         bool ok = false;
1506
1507                                         /* To each point individually... */
1508                                         ok = apply(gso, gps, i, radius, pc1);
1509
1510                                         /* Only do the second point if this is the last segment,
1511                                          * and it is unlikely that the point will get handled
1512                                          * otherwise.
1513                                          *
1514                                          * NOTE: There is a small risk here that the second point wasn't really
1515                                          *       actually in-range. In that case, it only got in because
1516                                          *       the line linking the points was!
1517                                          */
1518                                         if (i + 1 == gps->totpoints - 1) {
1519                                                 ok |= apply(gso, gps, i + 1, radius, pc2);
1520                                                 include_last = false;
1521                                         }
1522                                         else {
1523                                                 include_last = true;
1524                                         }
1525
1526                                         changed |= ok;
1527                                 }
1528                                 else if (include_last) {
1529                                         /* This case is for cases where for whatever reason the second vert (1st here) doesn't get included
1530                                          * because the whole edge isn't in bounds, but it would've qualified since it did with the
1531                                          * previous step (but wasn't added then, to avoid double-ups)
1532                                          */
1533                                         changed |= apply(gso, gps, i, radius, pc1);
1534                                         include_last = false;
1535                                 }
1536                         }
1537                 }
1538         }
1539
1540         return changed;
1541 }
1542
1543 /* Apply sculpt brushes to strokes in the given frame */
1544 static bool gpsculpt_brush_do_frame(
1545         bContext *C, tGP_BrushEditData *gso,
1546         bGPDlayer *gpl, bGPDframe *gpf,
1547         float diff_mat[4][4])
1548 {
1549         bool changed = false;
1550         Object *ob = CTX_data_active_object(C);
1551
1552         for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
1553                 /* skip strokes that are invalid for current view */
1554                 if (ED_gpencil_stroke_can_use(C, gps) == false) {
1555                         continue;
1556                 }
1557                 /* check if the color is editable */
1558                 if (ED_gpencil_stroke_color_use(ob, gpl, gps) == false) {
1559                         continue;
1560                 }
1561
1562                 switch (gso->brush_type) {
1563                         case GP_SCULPT_TYPE_SMOOTH: /* Smooth strokes */
1564                         {
1565                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_smooth_apply);
1566                                 break;
1567                         }
1568
1569                         case GP_SCULPT_TYPE_THICKNESS: /* Adjust stroke thickness */
1570                         {
1571                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_thickness_apply);
1572                                 break;
1573                         }
1574
1575                         case GP_SCULPT_TYPE_STRENGTH: /* Adjust stroke color strength */
1576                         {
1577                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_strength_apply);
1578                                 break;
1579                         }
1580
1581                         case GP_SCULPT_TYPE_GRAB: /* Grab points */
1582                         {
1583                                 if (gso->first) {
1584                                         /* First time this brush stroke is being applied:
1585                                          * 1) Prepare data buffers (init/clear) for this stroke
1586                                          * 2) Use the points now under the cursor
1587                                          */
1588                                         gp_brush_grab_stroke_init(gso, gps);
1589                                         changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_grab_store_points);
1590                                 }
1591                                 else {
1592                                         /* Apply effect to the stored points */
1593                                         gp_brush_grab_apply_cached(gso, gps, diff_mat);
1594                                         changed |= true;
1595                                 }
1596                                 break;
1597                         }
1598
1599                         case GP_SCULPT_TYPE_PUSH: /* Push points */
1600                         {
1601                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_push_apply);
1602                                 break;
1603                         }
1604
1605                         case GP_SCULPT_TYPE_PINCH: /* Pinch points */
1606                         {
1607                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_pinch_apply);
1608                                 break;
1609                         }
1610
1611                         case GP_SCULPT_TYPE_TWIST: /* Twist points around midpoint */
1612                         {
1613                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_twist_apply);
1614                                 break;
1615                         }
1616
1617                         case GP_SCULPT_TYPE_RANDOMIZE: /* Apply jitter */
1618                         {
1619                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_randomize_apply);
1620                                 break;
1621                         }
1622
1623                         case GP_SCULPT_TYPE_WEIGHT: /* Adjust vertex group weight */
1624                         {
1625                                 changed |= gpsculpt_brush_do_stroke(gso, gps, diff_mat, gp_brush_weight_apply);
1626                                 break;
1627                         }
1628
1629
1630                         default:
1631                                 printf("ERROR: Unknown type of GPencil Sculpt brush - %u\n", gso->brush_type);
1632                                 break;
1633                 }
1634                 /* Triangulation must be calculated if changed */
1635                 if (changed) {
1636                         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1637                         gps->tot_triangles = 0;
1638                 }
1639         }
1640
1641         return changed;
1642 }
1643
1644 /* Perform two-pass brushes which modify the existing strokes */
1645 static bool gpsculpt_brush_apply_standard(bContext *C, tGP_BrushEditData *gso)
1646 {
1647         ToolSettings *ts = CTX_data_tool_settings(C);
1648         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1649         Object *obact = gso->object;
1650         bGPdata *gpd = gso->gpd;
1651         bool changed = false;
1652
1653         /* Calculate brush-specific data which applies equally to all points */
1654         switch (gso->brush_type) {
1655                 case GP_SCULPT_TYPE_GRAB: /* Grab points */
1656                 case GP_SCULPT_TYPE_PUSH: /* Push points */
1657                 {
1658                         /* calculate amount of displacement to apply */
1659                         gp_brush_grab_calc_dvec(gso);
1660                         break;
1661                 }
1662
1663                 case GP_SCULPT_TYPE_PINCH: /* Pinch points */
1664                 case GP_SCULPT_TYPE_TWIST: /* Twist points around midpoint */
1665                 {
1666                         /* calculate midpoint of the brush (in data space) */
1667                         gp_brush_calc_midpoint(gso);
1668                         break;
1669                 }
1670
1671                 case GP_SCULPT_TYPE_RANDOMIZE: /* Random jitter */
1672                 {
1673                         /* compute the displacement vector for the cursor (in data space) */
1674                         gp_brush_grab_calc_dvec(gso);
1675                         break;
1676                 }
1677
1678                 default:
1679                         break;
1680         }
1681
1682
1683         /* Find visible strokes, and perform operations on those if hit */
1684         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1685         {
1686                 /* If no active frame, don't do anything... */
1687                 if (gpl->actframe == NULL) {
1688                         continue;
1689                 }
1690
1691                 /* calculate difference matrix */
1692                 float diff_mat[4][4];
1693                 ED_gpencil_parent_location(depsgraph, obact, gpd, gpl, diff_mat);
1694
1695                 /* Active Frame or MultiFrame? */
1696                 if (gso->is_multiframe) {
1697                         /* init multiframe falloff options */
1698                         int f_init = 0;
1699                         int f_end = 0;
1700
1701                         if (gso->use_multiframe_falloff) {
1702                                 BKE_gpencil_get_range_selected(gpl, &f_init, &f_end);
1703                         }
1704
1705                         for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
1706                                 /* Always do active frame; Otherwise, only include selected frames */
1707                                 if ((gpf == gpl->actframe) || (gpf->flag & GP_FRAME_SELECT)) {
1708                                         /* compute multiframe falloff factor */
1709                                         if (gso->use_multiframe_falloff) {
1710                                                 /* Faloff depends on distance to active frame (relative to the overall frame range) */
1711                                                 gso->mf_falloff = BKE_gpencil_multiframe_falloff_calc(
1712                                                         gpf, gpl->actframe->framenum,
1713                                                         f_init, f_end,
1714                                                         ts->gp_sculpt.cur_falloff);
1715                                         }
1716                                         else {
1717                                                 /* No falloff */
1718                                                 gso->mf_falloff = 1.0f;
1719                                         }
1720
1721                                         /* affect strokes in this frame */
1722                                         changed |= gpsculpt_brush_do_frame(C, gso, gpl, gpf, diff_mat);
1723                                 }
1724                         }
1725                 }
1726                 else {
1727                         /* Apply to active frame's strokes */
1728                         gso->mf_falloff = 1.0f;
1729                         changed |= gpsculpt_brush_do_frame(C, gso, gpl, gpl->actframe, diff_mat);
1730                 }
1731         }
1732         CTX_DATA_END;
1733
1734         return changed;
1735 }
1736
1737 /* Calculate settings for applying brush */
1738 static void gpsculpt_brush_apply(bContext *C, wmOperator *op, PointerRNA *itemptr)
1739 {
1740         tGP_BrushEditData *gso = op->customdata;
1741         GP_Sculpt_Data *gp_brush = gso->gp_brush;
1742         const int radius = (
1743                 (gp_brush->flag & GP_SCULPT_FLAG_PRESSURE_RADIUS) ?
1744                 gso->gp_brush->size * gso->pressure : gso->gp_brush->size);
1745         float mousef[2];
1746         int mouse[2];
1747         bool changed = false;
1748
1749         /* Get latest mouse coordinates */
1750         RNA_float_get_array(itemptr, "mouse", mousef);
1751         gso->mval[0] = mouse[0] = (int)(mousef[0]);
1752         gso->mval[1] = mouse[1] = (int)(mousef[1]);
1753
1754         gso->pressure = RNA_float_get(itemptr, "pressure");
1755
1756         if (RNA_boolean_get(itemptr, "pen_flip"))
1757                 gso->flag |= GP_SCULPT_FLAG_INVERT;
1758         else
1759                 gso->flag &= ~GP_SCULPT_FLAG_INVERT;
1760
1761
1762         /* Store coordinates as reference, if operator just started running */
1763         if (gso->first) {
1764                 gso->mval_prev[0]  = gso->mval[0];
1765                 gso->mval_prev[1]  = gso->mval[1];
1766                 gso->pressure_prev = gso->pressure;
1767         }
1768
1769         /* Update brush_rect, so that it represents the bounding rectangle of brush */
1770         gso->brush_rect.xmin = mouse[0] - radius;
1771         gso->brush_rect.ymin = mouse[1] - radius;
1772         gso->brush_rect.xmax = mouse[0] + radius;
1773         gso->brush_rect.ymax = mouse[1] + radius;
1774
1775
1776         /* Apply brush */
1777         if (gso->brush_type == GP_SCULPT_TYPE_CLONE) {
1778                 changed = gpsculpt_brush_apply_clone(C, gso);
1779         }
1780         else {
1781                 changed = gpsculpt_brush_apply_standard(C, gso);
1782         }
1783
1784
1785         /* Updates */
1786         if (changed) {
1787                 DEG_id_tag_update(&gso->gpd->id, ID_RECALC_GEOMETRY);
1788                 WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
1789         }
1790
1791         /* Store values for next step */
1792         gso->mval_prev[0]  = gso->mval[0];
1793         gso->mval_prev[1]  = gso->mval[1];
1794         gso->pressure_prev = gso->pressure;
1795         gso->first = false;
1796 }
1797
1798 /* Running --------------------------------------------- */
1799
1800 /* helper - a record stroke, and apply paint event */
1801 static void gpsculpt_brush_apply_event(bContext *C, wmOperator *op, const wmEvent *event)
1802 {
1803         tGP_BrushEditData *gso = op->customdata;
1804         ToolSettings *ts = CTX_data_tool_settings(C);
1805         GP_Sculpt_Settings *gset = &ts->gp_sculpt;
1806         PointerRNA itemptr;
1807         float mouse[2];
1808         int tablet = 0;
1809
1810         mouse[0] = event->mval[0] + 1;
1811         mouse[1] = event->mval[1] + 1;
1812
1813         /* fill in stroke */
1814         RNA_collection_add(op->ptr, "stroke", &itemptr);
1815
1816         RNA_float_set_array(&itemptr, "mouse", mouse);
1817         RNA_boolean_set(&itemptr, "pen_flip", event->ctrl != false);
1818         RNA_boolean_set(&itemptr, "is_start", gso->first);
1819
1820         /* handle pressure sensitivity (which is supplied by tablets) */
1821         if (event->tablet_data) {
1822                 const wmTabletData *wmtab = event->tablet_data;
1823                 float pressure = wmtab->Pressure;
1824
1825                 tablet = (wmtab->Active != EVT_TABLET_NONE);
1826
1827                 /* special exception here for too high pressure values on first touch in
1828                  * windows for some tablets: clamp the values to be sane
1829                  */
1830                 if (tablet && (pressure >= 0.99f)) {
1831                         pressure = 1.0f;
1832                 }
1833                 RNA_float_set(&itemptr, "pressure", pressure);
1834         }
1835         else {
1836                 RNA_float_set(&itemptr, "pressure", 1.0f);
1837         }
1838
1839         if (!gso->is_weight_mode) {
1840                 if (event->shift) {
1841                         gso->gp_brush_old = gso->gp_brush;
1842                         gso->brush_type_old = gso->brush_type;
1843
1844                         gso->gp_brush = &gset->brush[GP_SCULPT_TYPE_SMOOTH];
1845                         gso->brush_type = GP_SCULPT_TYPE_SMOOTH;
1846                 }
1847                 else {
1848                         if (gso->gp_brush_old != NULL) {
1849                                 gso->gp_brush = gso->gp_brush_old;
1850                                 gso->brush_type = gso->brush_type_old;
1851                         }
1852                 }
1853         }
1854
1855         /* apply */
1856         gpsculpt_brush_apply(C, op, &itemptr);
1857 }
1858
1859 /* reapply */
1860 static int gpsculpt_brush_exec(bContext *C, wmOperator *op)
1861 {
1862         if (!gpsculpt_brush_init(C, op))
1863                 return OPERATOR_CANCELLED;
1864
1865         RNA_BEGIN(op->ptr, itemptr, "stroke")
1866         {
1867                 gpsculpt_brush_apply(C, op, &itemptr);
1868         }
1869         RNA_END;
1870
1871         gpsculpt_brush_exit(C, op);
1872
1873         return OPERATOR_FINISHED;
1874 }
1875
1876
1877 /* start modal painting */
1878 static int gpsculpt_brush_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1879 {
1880         tGP_BrushEditData *gso = NULL;
1881         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1882         const bool is_playing = ED_screen_animation_playing(CTX_wm_manager(C)) != NULL;
1883         bool needs_timer = false;
1884         float brush_rate = 0.0f;
1885
1886         /* the operator cannot work while play animation */
1887         if (is_playing) {
1888                 BKE_report(op->reports, RPT_ERROR, "Cannot sculpt while play animation");
1889
1890                 return OPERATOR_CANCELLED;
1891         }
1892
1893         /* init painting data */
1894         if (!gpsculpt_brush_init(C, op))
1895                 return OPERATOR_CANCELLED;
1896
1897         gso = op->customdata;
1898
1899         /* initialise type-specific data (used for the entire session) */
1900         switch (gso->brush_type) {
1901                 /* Brushes requiring timer... */
1902                 case GP_SCULPT_TYPE_THICKNESS:
1903                         brush_rate = 0.01f; // XXX: hardcoded
1904                         needs_timer = true;
1905                         break;
1906
1907                 case GP_SCULPT_TYPE_STRENGTH:
1908                         brush_rate = 0.01f; // XXX: hardcoded
1909                         needs_timer = true;
1910                         break;
1911
1912                 case GP_SCULPT_TYPE_PINCH:
1913                         brush_rate = 0.001f; // XXX: hardcoded
1914                         needs_timer = true;
1915                         break;
1916
1917                 case GP_SCULPT_TYPE_TWIST:
1918                         brush_rate = 0.01f; // XXX: hardcoded
1919                         needs_timer = true;
1920                         break;
1921
1922                 default:
1923                         break;
1924         }
1925
1926         /* register timer for increasing influence by hovering over an area */
1927         if (needs_timer) {
1928                 gso->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, brush_rate);
1929         }
1930
1931         /* register modal handler */
1932         WM_event_add_modal_handler(C, op);
1933
1934         /* start drawing immediately? */
1935         if (is_modal == false) {
1936                 ARegion *ar = CTX_wm_region(C);
1937
1938                 /* ensure that we'll have a new frame to draw on */
1939                 gpsculpt_brush_init_stroke(gso);
1940
1941                 /* apply first dab... */
1942                 gso->is_painting = true;
1943                 gpsculpt_brush_apply_event(C, op, event);
1944
1945                 /* redraw view with feedback */
1946                 ED_region_tag_redraw(ar);
1947         }
1948
1949         return OPERATOR_RUNNING_MODAL;
1950 }
1951
1952 /* painting - handle events */
1953 static int gpsculpt_brush_modal(bContext *C, wmOperator *op, const wmEvent *event)
1954 {
1955         tGP_BrushEditData *gso = op->customdata;
1956         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1957         bool redraw_region = false;
1958         bool redraw_toolsettings = false;
1959
1960         /* The operator can be in 2 states: Painting and Idling */
1961         if (gso->is_painting) {
1962                 /* Painting  */
1963                 switch (event->type) {
1964                         /* Mouse Move = Apply somewhere else */
1965                         case MOUSEMOVE:
1966                         case INBETWEEN_MOUSEMOVE:
1967                                 /* apply brush effect at new position */
1968                                 gpsculpt_brush_apply_event(C, op, event);
1969
1970                                 /* force redraw, so that the cursor will at least be valid */
1971                                 redraw_region = true;
1972                                 break;
1973
1974                         /* Timer Tick - Only if this was our own timer */
1975                         case TIMER:
1976                                 if (event->customdata == gso->timer) {
1977                                         gso->timerTick = true;
1978                                         gpsculpt_brush_apply_event(C, op, event);
1979                                         gso->timerTick = false;
1980                                 }
1981                                 break;
1982
1983                         /* Adjust brush settings */
1984                         /* FIXME: Step increments and modifier keys are hardcoded here! */
1985                         case WHEELUPMOUSE:
1986                         case PADPLUSKEY:
1987                                 if (event->shift) {
1988                                         /* increase strength */
1989                                         gso->gp_brush->strength += 0.05f;
1990                                         CLAMP_MAX(gso->gp_brush->strength, 1.0f);
1991                                 }
1992                                 else {
1993                                         /* increase brush size */
1994                                         gso->gp_brush->size += 3;
1995                                         CLAMP_MAX(gso->gp_brush->size, 300);
1996                                 }
1997
1998                                 redraw_region = true;
1999                                 redraw_toolsettings = true;
2000                                 break;
2001
2002                         case WHEELDOWNMOUSE:
2003                         case PADMINUS:
2004                                 if (event->shift) {
2005                                         /* decrease strength */
2006                                         gso->gp_brush->strength -= 0.05f;
2007                                         CLAMP_MIN(gso->gp_brush->strength, 0.0f);
2008                                 }
2009                                 else {
2010                                         /* decrease brush size */
2011                                         gso->gp_brush->size -= 3;
2012                                         CLAMP_MIN(gso->gp_brush->size, 1);
2013                                 }
2014
2015                                 redraw_region = true;
2016                                 redraw_toolsettings = true;
2017                                 break;
2018
2019                         /* Painting mbut release = Stop painting (back to idle) */
2020                         case LEFTMOUSE:
2021                                 //BLI_assert(event->val == KM_RELEASE);
2022                                 if (is_modal) {
2023                                         /* go back to idling... */
2024                                         gso->is_painting = false;
2025                                 }
2026                                 else {
2027                                         /* end sculpt session, since we're not modal */
2028                                         gso->is_painting = false;
2029
2030                                         gpsculpt_brush_exit(C, op);
2031                                         return OPERATOR_FINISHED;
2032                                 }
2033                                 break;
2034
2035                         /* Abort painting if any of the usual things are tried */
2036                         case MIDDLEMOUSE:
2037                         case RIGHTMOUSE:
2038                         case ESCKEY:
2039                                 gpsculpt_brush_exit(C, op);
2040                                 return OPERATOR_FINISHED;
2041                 }
2042         }
2043         else {
2044                 /* Idling */
2045                 BLI_assert(is_modal == true);
2046
2047                 switch (event->type) {
2048                         /* Painting mbut press = Start painting (switch to painting state) */
2049                         case LEFTMOUSE:
2050                                 /* do initial "click" apply */
2051                                 gso->is_painting = true;
2052                                 gso->first = true;
2053
2054                                 gpsculpt_brush_init_stroke(gso);
2055                                 gpsculpt_brush_apply_event(C, op, event);
2056                                 break;
2057
2058                         /* Exit modal operator, based on the "standard" ops */
2059                         case RIGHTMOUSE:
2060                         case ESCKEY:
2061                                 gpsculpt_brush_exit(C, op);
2062                                 return OPERATOR_FINISHED;
2063
2064                         /* MMB is often used for view manipulations */
2065                         case MIDDLEMOUSE:
2066                                 return OPERATOR_PASS_THROUGH;
2067
2068                         /* Mouse movements should update the brush cursor - Just redraw the active region */
2069                         case MOUSEMOVE:
2070                         case INBETWEEN_MOUSEMOVE:
2071                                 redraw_region = true;
2072                                 break;
2073
2074                         /* Adjust brush settings */
2075                         /* FIXME: Step increments and modifier keys are hardcoded here! */
2076                         case WHEELUPMOUSE:
2077                         case PADPLUSKEY:
2078                                 if (event->shift) {
2079                                         /* increase strength */
2080                                         gso->gp_brush->strength += 0.05f;
2081                                         CLAMP_MAX(gso->gp_brush->strength, 1.0f);
2082                                 }
2083                                 else {
2084                                         /* increase brush size */
2085                                         gso->gp_brush->size += 3;
2086                                         CLAMP_MAX(gso->gp_brush->size, 300);
2087                                 }
2088
2089                                 redraw_region = true;
2090                                 redraw_toolsettings = true;
2091                                 break;
2092
2093                         case WHEELDOWNMOUSE:
2094                         case PADMINUS:
2095                                 if (event->shift) {
2096                                         /* decrease strength */
2097                                         gso->gp_brush->strength -= 0.05f;
2098                                         CLAMP_MIN(gso->gp_brush->strength, 0.0f);
2099                                 }
2100                                 else {
2101                                         /* decrease brush size */
2102                                         gso->gp_brush->size -= 3;
2103                                         CLAMP_MIN(gso->gp_brush->size, 1);
2104                                 }
2105
2106                                 redraw_region = true;
2107                                 redraw_toolsettings = true;
2108                                 break;
2109
2110                         /* Change Frame - Allowed */
2111                         case LEFTARROWKEY:
2112                         case RIGHTARROWKEY:
2113                         case UPARROWKEY:
2114                         case DOWNARROWKEY:
2115                                 return OPERATOR_PASS_THROUGH;
2116
2117                         /* Camera/View Gizmo's - Allowed */
2118                         /* (See rationale in gpencil_paint.c -> gpencil_draw_modal()) */
2119                         case PAD0:  case PAD1:  case PAD2:  case PAD3:  case PAD4:
2120                         case PAD5:  case PAD6:  case PAD7:  case PAD8:  case PAD9:
2121                                 return OPERATOR_PASS_THROUGH;
2122
2123                         /* Unhandled event */
2124                         default:
2125                                 break;
2126                 }
2127         }
2128
2129         /* Redraw region? */
2130         if (redraw_region) {
2131                 ARegion *ar = CTX_wm_region(C);
2132                 ED_region_tag_redraw(ar);
2133         }
2134
2135         /* Redraw toolsettings (brush settings)? */
2136         if (redraw_toolsettings) {
2137                 DEG_id_tag_update(&gso->gpd->id, ID_RECALC_GEOMETRY);
2138                 WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, NULL);
2139         }
2140
2141         return OPERATOR_RUNNING_MODAL;
2142 }
2143
2144 void GPENCIL_OT_sculpt_paint(wmOperatorType *ot)
2145 {
2146         /* identifiers */
2147         ot->name = "Stroke Sculpt";
2148         ot->idname = "GPENCIL_OT_sculpt_paint";
2149         ot->description = "Apply tweaks to strokes by painting over the strokes"; // XXX
2150
2151         /* api callbacks */
2152         ot->exec = gpsculpt_brush_exec;
2153         ot->invoke = gpsculpt_brush_invoke;
2154         ot->modal = gpsculpt_brush_modal;
2155         ot->cancel = gpsculpt_brush_exit;
2156         ot->poll = gpsculpt_brush_poll;
2157
2158         /* flags */
2159         ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
2160
2161         /* properties */
2162         PropertyRNA *prop;
2163         prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
2164         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2165
2166         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input",
2167                                "Enter a mini 'sculpt-mode' if enabled, otherwise, exit after drawing a single stroke");
2168         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
2169 }