Merge branch 'blender2.7'
[blender.git] / source / blender / editors / gpencil / gpencil_primitive.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) 2017, Blender Foundation
17  * This is a new part of Blender
18  * Operators for creating new Grease Pencil primitives (boxes, circles, ...)
19  */
20
21 /** \file
22  * \ingroup edgpencil
23  */
24
25 #include <stdio.h>
26 #include <string.h>
27 #include <stdlib.h>
28 #include <stddef.h>
29 #include <math.h>
30
31 #include "MEM_guardedalloc.h"
32
33 #include "BLI_blenlib.h"
34 #include "BLI_utildefines.h"
35 #include "BLI_math.h"
36 #include "BLI_rand.h"
37
38 #include "BLT_translation.h"
39
40 #include "PIL_time.h"
41
42 #include "DNA_brush_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_meshdata_types.h"
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47 #include "DNA_screen_types.h"
48 #include "DNA_space_types.h"
49 #include "DNA_view3d_types.h"
50
51 #include "BKE_brush.h"
52 #include "BKE_colortools.h"
53 #include "BKE_context.h"
54 #include "BKE_deform.h"
55 #include "BKE_global.h"
56 #include "BKE_gpencil.h"
57 #include "BKE_main.h"
58 #include "BKE_material.h"
59 #include "BKE_paint.h"
60 #include "BKE_report.h"
61
62 #include "UI_interface.h"
63 #include "UI_resources.h"
64
65 #include "WM_api.h"
66 #include "WM_types.h"
67
68 #include "RNA_access.h"
69 #include "RNA_define.h"
70 #include "RNA_enum_types.h"
71
72 #include "ED_gpencil.h"
73 #include "ED_object.h"
74 #include "ED_screen.h"
75 #include "ED_view3d.h"
76 #include "ED_space_api.h"
77
78 #include "DEG_depsgraph.h"
79 #include "DEG_depsgraph_query.h"
80
81 #include "gpencil_intern.h"
82
83 #define MIN_EDGES 2
84 #define MAX_EDGES 128
85 #define MAX_CP 128
86
87 #define IDLE 0
88 #define IN_PROGRESS 1
89 #define IN_CURVE_EDIT 2
90 #define IN_MOVE 3
91 #define IN_BRUSH_SIZE 4
92 #define IN_BRUSH_STRENGTH 5
93
94 #define SELECT_NONE 0
95 #define SELECT_START 1
96 #define SELECT_CP1 2
97 #define SELECT_CP2 3
98 #define SELECT_END 4
99
100 #define BIG_SIZE_CTL    15
101 #define MID_SIZE_CTL    10
102 #define SMALL_SIZE_CTL   8
103
104 #define MOVE_NONE 0
105 #define MOVE_ENDS 1
106 #define MOVE_CP 2
107
108   /* ************************************************ */
109   /* Core/Shared Utilities */
110
111 /* clear the session buffers (call this before AND after a paint operation) */
112 static void gp_session_validatebuffer(tGPDprimitive *p)
113 {
114         bGPdata *gpd = p->gpd;
115
116         /* clear memory of buffer (or allocate it if starting a new session) */
117         if (gpd->runtime.sbuffer) {
118                 memset(gpd->runtime.sbuffer, 0, sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX);
119         }
120         else {
121                 gpd->runtime.sbuffer = MEM_callocN(sizeof(tGPspoint) * GP_STROKE_BUFFER_MAX, "gp_session_strokebuffer");
122         }
123
124         /* reset indices */
125         gpd->runtime.sbuffer_size = 0;
126
127         /* reset flags */
128         gpd->runtime.sbuffer_sflag = 0;
129         gpd->runtime.sbuffer_sflag |= GP_STROKE_3DSPACE;
130
131         if (ELEM(p->type, GP_STROKE_BOX, GP_STROKE_CIRCLE))
132                 gpd->runtime.sbuffer_sflag |= GP_STROKE_CYCLIC;
133 }
134
135 static void gp_init_colors(tGPDprimitive *p)
136 {
137         bGPdata *gpd = p->gpd;
138         Brush *brush = p->brush;
139
140         Material *ma = NULL;
141         MaterialGPencilStyle *gp_style = NULL;
142
143         /* use brush material */
144         ma = BKE_gpencil_get_material_from_brush(brush);
145
146         /* if no brush defaults, get material and color info */
147         if ((ma == NULL) || (ma->gp_style == NULL)) {
148                 BKE_gpencil_material_ensure(p->bmain, p->ob);
149
150                 /* assign always the first material to the brush */
151                 p->mat = give_current_material(p->ob, 1);
152                 brush->gpencil_settings->material = p->mat;
153         }
154         else {
155                 p->mat = ma;
156         }
157
158         /* check if the material is already on object material slots and add it if missing */
159         if (BKE_gpencil_get_material_index(p->ob, p->mat) == 0) {
160                 BKE_object_material_slot_add(p->bmain, p->ob);
161                 assign_material(p->bmain, p->ob, ma, p->ob->totcol, BKE_MAT_ASSIGN_USERPREF);
162         }
163
164         /* assign color information to temp data */
165         gp_style = p->mat->gp_style;
166         if (gp_style) {
167
168                 /* set colors */
169                 if (gp_style->flag & GP_STYLE_STROKE_SHOW) {
170                         copy_v4_v4(gpd->runtime.scolor, gp_style->stroke_rgba);
171                 }
172                 else {
173                         /* if no stroke, use fill */
174                         copy_v4_v4(gpd->runtime.scolor, gp_style->fill_rgba);
175                 }
176
177                 copy_v4_v4(gpd->runtime.sfill, gp_style->fill_rgba);
178                 /* add some alpha to make easy the filling without hide strokes */
179                 if (gpd->runtime.sfill[3] > 0.8f) {
180                         gpd->runtime.sfill[3] = 0.8f;
181                 }
182
183                 gpd->runtime.mode = (short)gp_style->mode;
184                 gpd->runtime.bstroke_style = gp_style->stroke_style;
185                 gpd->runtime.bfill_style = gp_style->fill_style;
186         }
187 }
188
189 /* Helper to square a primitive */
190 static void gpencil_primitive_to_square(tGPDprimitive *tgpi, const float x, const float y)
191 {
192         float w = fabsf(x);
193         float h = fabsf(y);
194         if ((x > 0 && y > 0) || (x < 0 && y < 0)) {
195                 if (w > h)
196                         tgpi->end[1] = tgpi->origin[1] + x;
197                 else
198                         tgpi->end[0] = tgpi->origin[0] + y;
199         }
200         else {
201                 if (w > h)
202                         tgpi->end[1] = tgpi->origin[1] - x;
203                 else
204                         tgpi->end[0] = tgpi->origin[0] - y;
205         }
206 }
207
208 /* Helper to rotate point around origin */
209 static void gp_rotate_v2_v2v2fl(float v[2], const float p[2], const float origin[2], const float angle)
210 {
211         float pt[2];
212         float r[2];
213         sub_v2_v2v2(pt, p, origin);
214         rotate_v2_v2fl(r, pt, angle);
215         add_v2_v2v2(v, r, origin);
216 }
217
218 /* Helper to rotate line around line centre */
219 static void gp_primitive_rotate_line(float va[2], float vb[2], const float a[2], const float b[2], const float angle)
220 {
221         float midpoint[2];
222         mid_v2_v2v2(midpoint, a, b);
223         gp_rotate_v2_v2v2fl(va, a, midpoint, angle);
224         gp_rotate_v2_v2v2fl(vb, b, midpoint, angle);
225 }
226
227 /* Helper to update cps */
228 static void gp_primitive_update_cps(tGPDprimitive *tgpi)
229 {
230         if (!tgpi->curve) {
231                 mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
232                 copy_v2_v2(tgpi->cp1, tgpi->midpoint);
233                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
234         }
235         else if (tgpi->type == GP_STROKE_CURVE) {
236                 mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
237                 copy_v2_v2(tgpi->cp1, tgpi->midpoint);
238                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
239         }
240         else if (tgpi->type == GP_STROKE_ARC) {
241                 if (tgpi->flip) {
242                         gp_primitive_rotate_line(tgpi->cp1, tgpi->cp2, tgpi->start, tgpi->end, M_PI_2);
243                 }
244                 else {
245                         gp_primitive_rotate_line(tgpi->cp1, tgpi->cp2, tgpi->end, tgpi->start, M_PI_2);
246                 }
247         }
248 }
249
250 /* Helper to reflect point */
251 static void UNUSED_FUNCTION(gp_reflect_point_v2_v2v2v2)(
252         float va[2], const float p[2], const float a[2], const float b[2])
253 {
254         float point[2];
255         closest_to_line_v2(point, p, a, b);
256         va[0] = point[0] - (p[0] - point[0]);
257         va[1] = point[1] - (p[1] - point[1]);
258 }
259
260   /* Poll callback for primitive operators */
261 static bool gpencil_primitive_add_poll(bContext *C)
262 {
263         /* only 3D view */
264         ScrArea *sa = CTX_wm_area(C);
265         if (sa && sa->spacetype != SPACE_VIEW3D) {
266                 return 0;
267         }
268
269         /* need data to create primitive */
270         bGPdata *gpd = CTX_data_gpencil_data(C);
271         if (gpd == NULL) {
272                 return 0;
273         }
274
275         /* only in edit and paint modes
276          * - paint as it's the "drawing/creation mode"
277          * - edit as this is more of an atomic editing operation
278          *   (similar to copy/paste), and also for consistency
279          */
280         if ((gpd->flag & (GP_DATA_STROKE_PAINTMODE | GP_DATA_STROKE_EDITMODE)) == 0) {
281                 CTX_wm_operator_poll_msg_set(C, "Primitives can only be added in Draw or Edit modes");
282                 return 0;
283         }
284
285         /* don't allow operator to function if the active layer is locked/hidden
286          * (BUT, if there isn't an active layer, we are free to add new layer when the time comes)
287          */
288         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
289         if ((gpl) && (gpl->flag & (GP_LAYER_LOCKED | GP_LAYER_HIDE))) {
290                 CTX_wm_operator_poll_msg_set(C, "Primitives cannot be added as active layer is locked or hidden");
291                 return 0;
292         }
293
294         return 1;
295 }
296
297 /* Allocate memory to stroke, adds MAX_EDGES on every call */
298 static void gpencil_primitive_allocate_memory(tGPDprimitive *tgpi)
299 {
300         tgpi->point_count += (tgpi->type == GP_STROKE_BOX) ? (MAX_EDGES * 4 + 1) : (MAX_EDGES + 1);
301         bGPDstroke *gpsf = tgpi->gpf->strokes.first;
302         gpsf->points = MEM_reallocN(gpsf->points, sizeof(bGPDspoint) * tgpi->point_count);
303         if (gpsf->dvert != NULL)
304                 gpsf->dvert = MEM_reallocN(gpsf->dvert, sizeof(MDeformVert) * tgpi->point_count);
305         tgpi->points = MEM_reallocN(tgpi->points, sizeof(tGPspoint) * tgpi->point_count);
306 }
307
308 /* ****************** Primitive Interactive *********************** */
309
310 /* Helper: Create internal strokes primitives data */
311 static void gp_primitive_set_initdata(bContext *C, tGPDprimitive *tgpi)
312 {
313         ToolSettings *ts = CTX_data_tool_settings(C);
314         Depsgraph *depsgraph = CTX_data_depsgraph(C);
315         int cfra_eval = (int)DEG_get_ctime(depsgraph);
316
317         bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
318
319         /* if brush doesn't exist, create a new one */
320         Paint *paint = &ts->gp_paint->paint;
321         /* if not exist, create a new one */
322         if (paint->brush == NULL) {
323                 /* create new brushes */
324                 BKE_brush_gpencil_presets(C);
325         }
326         tgpi->brush = paint->brush;
327
328         /* if layer doesn't exist, create a new one */
329         if (gpl == NULL) {
330                 gpl = BKE_gpencil_layer_addnew(tgpi->gpd, DATA_("Primitives"), true);
331         }
332         tgpi->gpl = gpl;
333
334         /* create a new temporary frame */
335         tgpi->gpf = MEM_callocN(sizeof(bGPDframe), "Temp bGPDframe");
336         tgpi->gpf->framenum = tgpi->cframe = cfra_eval;
337
338         /* create new temp stroke */
339         bGPDstroke *gps = MEM_callocN(sizeof(bGPDstroke), "Temp bGPDstroke");
340         gps->thickness = 2.0f;
341         gps->inittime = 0.0f;
342
343         /* enable recalculation flag by default */
344         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
345         gps->flag &= ~GP_STROKE_SELECT;
346         /* the polygon must be closed, so enabled cyclic */
347         if (ELEM(tgpi->type, GP_STROKE_BOX, GP_STROKE_CIRCLE)) {
348                 gps->flag |= GP_STROKE_CYCLIC;
349         }
350
351         gps->flag |= GP_STROKE_3DSPACE;
352
353         gps->mat_nr = BKE_gpencil_get_material_index(tgpi->ob, tgpi->mat) - 1;
354
355         /* allocate memory for storage points, but keep empty */
356         gps->totpoints = 0;
357         gps->points = MEM_callocN(sizeof(bGPDspoint), "gp_stroke_points");
358         /* initialize triangle memory to dummy data */
359         gps->tot_triangles = 0;
360         gps->triangles = NULL;
361         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
362
363         /* add to strokes */
364         BLI_addtail(&tgpi->gpf->strokes, gps);
365
366         /* allocate memory for storage points */
367         gpencil_primitive_allocate_memory(tgpi);
368
369         /* Random generator, only init once. */
370         uint rng_seed = (uint)(PIL_check_seconds_timer_i() & UINT_MAX);
371         tgpi->rng = BLI_rng_new(rng_seed);
372 }
373
374 /* add new segment to curve */
375 static void gpencil_primitive_add_segment(tGPDprimitive *tgpi)
376 {
377         if (tgpi->tot_stored_edges > 0) {
378                 tgpi->tot_stored_edges += (tgpi->tot_edges - 1);
379         }
380         else {
381                 tgpi->tot_stored_edges += tgpi->tot_edges;
382         }
383         gpencil_primitive_allocate_memory(tgpi);
384 }
385
386 /* Helper: set control point */
387 static void gp_primitive_set_cp(tGPDprimitive *tgpi, float p[2], float color[4], int size)
388 {
389         if (tgpi->flag == IN_PROGRESS) {
390                 return;
391         }
392
393         bGPDcontrolpoint *cp_points = tgpi->gpd->runtime.cp_points;
394
395         if (tgpi->gpd->runtime.tot_cp_points < MAX_CP) {
396                 CLAMP(size, 5, 20);
397                 bGPDcontrolpoint *cp = &cp_points[tgpi->gpd->runtime.tot_cp_points];
398                 copy_v2_v2(&cp->x, p);
399                 copy_v4_v4(cp->color, color);
400                 color[3] = 0.8f;
401                 cp->size = size;
402                 tgpi->gpd->runtime.tot_cp_points += 1;
403         }
404 }
405
406 /* Helper: Draw status message while the user is running the operator */
407 static void gpencil_primitive_status_indicators(bContext *C, tGPDprimitive *tgpi)
408 {
409         Scene *scene = tgpi->scene;
410         char status_str[UI_MAX_DRAW_STR];
411         char msg_str[UI_MAX_DRAW_STR];
412
413         if (tgpi->type == GP_STROKE_LINE) {
414                 BLI_strncpy(
415                         msg_str,
416                         IFACE_("Line: ESC to cancel, LMB set origin, Enter/MMB to confirm, WHEEL/+- to adjust subdivision number, Shift to align, Alt to center, E: extrude"),
417                         UI_MAX_DRAW_STR);
418         }
419         else if (tgpi->type == GP_STROKE_BOX) {
420                 BLI_strncpy(
421                         msg_str,
422                         IFACE_("Rectangle: ESC to cancel, LMB set origin, Enter/MMB to confirm, WHEEL/+- to adjust subdivision number, Shift to square, Alt to center"),
423                         UI_MAX_DRAW_STR);
424         }
425         else if (tgpi->type == GP_STROKE_CIRCLE) {
426                 BLI_strncpy(
427                         msg_str,
428                         IFACE_("Circle: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center"),
429                         UI_MAX_DRAW_STR);
430         }
431         else if (tgpi->type == GP_STROKE_ARC) {
432                 BLI_strncpy(
433                         msg_str,
434                         IFACE_("Arc: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center, M: Flip, E: extrude"),
435                         UI_MAX_DRAW_STR);
436         }
437         else if (tgpi->type == GP_STROKE_CURVE) {
438                 BLI_strncpy(
439                         msg_str,
440                         IFACE_("Curve: ESC to cancel, Enter/MMB to confirm, WHEEL/+- to adjust edge number, Shift to square, Alt to center, E: extrude"),
441                         UI_MAX_DRAW_STR);
442         }
443
444         if (ELEM(tgpi->type, GP_STROKE_CIRCLE, GP_STROKE_ARC, GP_STROKE_LINE, GP_STROKE_BOX)) {
445                 if (hasNumInput(&tgpi->num)) {
446                         char str_offs[NUM_STR_REP_LEN];
447
448                         outputNumInput(&tgpi->num, str_offs, &scene->unit);
449                         BLI_snprintf(status_str, sizeof(status_str), "%s: %s", msg_str, str_offs);
450                 }
451                 else {
452                         if (tgpi->flag == IN_PROGRESS) {
453                                 BLI_snprintf(
454                                         status_str, sizeof(status_str), "%s: %d (%d, %d) (%d, %d)", msg_str, tgpi->tot_edges,
455                                         (int)tgpi->start[0], (int)tgpi->start[1], (int)tgpi->end[0], (int)tgpi->end[1]);
456                         }
457                         else {
458                                 BLI_snprintf(
459                                         status_str, sizeof(status_str), "%s: %d (%d, %d)", msg_str, tgpi->tot_edges,
460                                         (int)tgpi->end[0], (int)tgpi->end[1]);
461                         }
462                 }
463         }
464         else {
465                 if (tgpi->flag == IN_PROGRESS) {
466                         BLI_snprintf(
467                                 status_str, sizeof(status_str), "%s: %d (%d, %d) (%d, %d)", msg_str, tgpi->tot_edges,
468                                 (int)tgpi->start[0], (int)tgpi->start[1], (int)tgpi->end[0], (int)tgpi->end[1]);
469                 }
470                 else {
471                         BLI_snprintf(
472                                 status_str, sizeof(status_str), "%s: (%d, %d)", msg_str,
473                                 (int)tgpi->end[0], (int)tgpi->end[1]);
474                 }
475         }
476         ED_workspace_status_text(C, status_str);
477 }
478
479 /* create a rectangle */
480 static void gp_primitive_rectangle(tGPDprimitive *tgpi, tGPspoint *points2D)
481 {
482         float coords[5][2];
483
484         coords[0][0] = tgpi->start[0];
485         coords[0][1] = tgpi->start[1];
486         coords[1][0] = tgpi->end[0];
487         coords[1][1] = tgpi->start[1];
488         coords[2][0] = tgpi->end[0];
489         coords[2][1] = tgpi->end[1];
490         coords[3][0] = tgpi->start[0];
491         coords[3][1] = tgpi->end[1];
492         coords[4][0] = tgpi->start[0];
493         coords[4][1] = tgpi->start[1];
494
495         const float step = 1.0f / (float)(tgpi->tot_edges);
496         int i = tgpi->tot_stored_edges;
497
498         for (int j = 0; j < 4; j++) {
499                 float a = 0.0f;
500                 for (int k = 0; k < tgpi->tot_edges; k++) {
501                         tGPspoint *p2d = &points2D[i];
502                         interp_v2_v2v2(&p2d->x, coords[j], coords[j + 1], a);
503                         a += step;
504                         i++;
505                 }
506         }
507
508         mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
509         float color[4];
510         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
511         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
512         if (tgpi->tot_stored_edges) {
513                 UI_GetThemeColor4fv(TH_REDALERT, color);
514                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
515         }
516         else {
517                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
518         }
519         UI_GetThemeColor4fv(TH_REDALERT, color);
520         gp_primitive_set_cp(tgpi, tgpi->midpoint, color, SMALL_SIZE_CTL);
521 }
522
523 /* create a line */
524 static void gp_primitive_line(tGPDprimitive *tgpi, tGPspoint *points2D)
525 {
526         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
527         const float step = 1.0f / (float)(tgpi->tot_edges - 1);
528         float a = tgpi->tot_stored_edges ? step : 0.0f;
529
530         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
531                 tGPspoint *p2d = &points2D[i];
532                 interp_v2_v2v2(&p2d->x, tgpi->start, tgpi->end, a);
533                 a += step;
534         }
535
536         float color[4];
537         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
538         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
539         if (tgpi->tot_stored_edges) {
540                 UI_GetThemeColor4fv(TH_REDALERT, color);
541                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
542         }
543         else {
544                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
545         }
546 }
547
548 /* create an arc */
549 static void gp_primitive_arc(tGPDprimitive *tgpi, tGPspoint *points2D)
550 {
551         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
552         const float step = M_PI_2 / (float)(tgpi->tot_edges - 1);
553         float start[2];
554         float end[2];
555         float cp1[2];
556         float corner[2];
557         float midpoint[2];
558         float a = tgpi->tot_stored_edges ? step : 0.0f;
559
560         mid_v2_v2v2(tgpi->midpoint, tgpi->start, tgpi->end);
561         copy_v2_v2(start, tgpi->start);
562         copy_v2_v2(end, tgpi->end);
563         copy_v2_v2(cp1, tgpi->cp1);
564         copy_v2_v2(midpoint, tgpi->midpoint);
565
566         corner[0] = midpoint[0] - (cp1[0] - midpoint[0]);
567         corner[1] = midpoint[1] - (cp1[1] - midpoint[1]);
568
569         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
570                 tGPspoint *p2d = &points2D[i];
571                 p2d->x = corner[0] + (end[0] - corner[0]) * sinf(a) + (start[0] - corner[0]) * cosf(a);
572                 p2d->y = corner[1] + (end[1] - corner[1]) * sinf(a) + (start[1] - corner[1]) * cosf(a);
573                 a += step;
574         }
575         float color[4];
576         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
577         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
578         if (tgpi->tot_stored_edges) {
579                 UI_GetThemeColor4fv(TH_REDALERT, color);
580                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
581         }
582         else {
583                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
584         }
585         UI_GetThemeColor4fv(TH_GIZMO_SECONDARY, color);
586         gp_primitive_set_cp(tgpi, tgpi->cp1, color, BIG_SIZE_CTL * 0.9f);
587 }
588
589 /* create a bezier */
590 static void gp_primitive_bezier(tGPDprimitive *tgpi, tGPspoint *points2D)
591 {
592         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
593         const float step = 1.0f / (float)(tgpi->tot_edges - 1);
594         float bcp1[2];
595         float bcp2[2];
596         float bcp3[2];
597         float bcp4[2];
598         float a = tgpi->tot_stored_edges ? step : 0.0f;
599
600         copy_v2_v2(bcp1, tgpi->start);
601         copy_v2_v2(bcp2, tgpi->cp1);
602         copy_v2_v2(bcp3, tgpi->cp2);
603         copy_v2_v2(bcp4, tgpi->end);
604
605         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
606                 tGPspoint *p2d = &points2D[i];
607                 interp_v2_v2v2v2v2_cubic(&p2d->x, bcp1, bcp2, bcp3, bcp4, a);
608                 a += step;
609         }
610         float color[4];
611         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
612         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
613         if (tgpi->tot_stored_edges) {
614                 UI_GetThemeColor4fv(TH_REDALERT, color);
615                 gp_primitive_set_cp(tgpi, tgpi->start, color, SMALL_SIZE_CTL);
616         }
617         else {
618                 gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
619         }
620         UI_GetThemeColor4fv(TH_GIZMO_SECONDARY, color);
621         gp_primitive_set_cp(tgpi, tgpi->cp1, color, BIG_SIZE_CTL * 0.9f);
622         gp_primitive_set_cp(tgpi, tgpi->cp2, color, BIG_SIZE_CTL * 0.9f);
623 }
624
625 /* create a circle */
626 static void gp_primitive_circle(tGPDprimitive *tgpi, tGPspoint *points2D)
627 {
628         const int totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
629         const float step = (2.0f * M_PI) / (float)(tgpi->tot_edges);
630         float center[2];
631         float radius[2];
632         float a = 0.0f;
633
634         center[0] = tgpi->start[0] + ((tgpi->end[0] - tgpi->start[0]) / 2.0f);
635         center[1] = tgpi->start[1] + ((tgpi->end[1] - tgpi->start[1]) / 2.0f);
636         radius[0] = fabsf(((tgpi->end[0] - tgpi->start[0]) / 2.0f));
637         radius[1] = fabsf(((tgpi->end[1] - tgpi->start[1]) / 2.0f));
638
639         for (int i = tgpi->tot_stored_edges; i < totpoints; i++) {
640                 tGPspoint *p2d = &points2D[i];
641                 p2d->x = (center[0] + cosf(a) * radius[0]);
642                 p2d->y = (center[1] + sinf(a) * radius[1]);
643                 a += step;
644         }
645         float color[4];
646         UI_GetThemeColor4fv(TH_GIZMO_PRIMARY, color);
647         gp_primitive_set_cp(tgpi, tgpi->end, color, BIG_SIZE_CTL);
648         gp_primitive_set_cp(tgpi, tgpi->start, color, BIG_SIZE_CTL);
649         UI_GetThemeColor4fv(TH_REDALERT, color);
650         gp_primitive_set_cp(tgpi, center, color, SMALL_SIZE_CTL);
651 }
652
653 /* Helper: Update shape of the stroke */
654 static void gp_primitive_update_strokes(bContext *C, tGPDprimitive *tgpi)
655 {
656         ToolSettings *ts = tgpi->scene->toolsettings;
657         bGPdata *gpd = tgpi->gpd;
658         Brush *brush = tgpi->brush;
659         bGPDstroke *gps = tgpi->gpf->strokes.first;
660         GP_Sculpt_Settings *gset = &ts->gp_sculpt;
661         int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
662         const char *align_flag = &ts->gpencil_v3d_align;
663         bool is_depth = (bool)(*align_flag & (GP_PROJECT_DEPTH_VIEW | GP_PROJECT_DEPTH_STROKE));
664         const bool is_camera = (bool)(ts->gp_sculpt.lock_axis == 0) &&
665                 (tgpi->rv3d->persp == RV3D_CAMOB) && (!is_depth);
666
667         if (tgpi->type == GP_STROKE_BOX)
668                 gps->totpoints = (tgpi->tot_edges * 4 + tgpi->tot_stored_edges);
669         else
670                 gps->totpoints = (tgpi->tot_edges + tgpi->tot_stored_edges);
671
672         if (tgpi->tot_stored_edges)
673                 gps->totpoints--;
674
675         tgpi->gpd->runtime.tot_cp_points = 0;
676
677         /* compute screen-space coordinates for points */
678         tGPspoint *points2D = tgpi->points;
679
680         if (tgpi->tot_edges > 1) {
681                 switch (tgpi->type) {
682                         case GP_STROKE_BOX:
683                                 gp_primitive_rectangle(tgpi, points2D);
684                                 break;
685                         case GP_STROKE_LINE:
686                                 gp_primitive_line(tgpi, points2D);
687                                 break;
688                         case GP_STROKE_CIRCLE:
689                                 gp_primitive_circle(tgpi, points2D);
690                                 break;
691                         case GP_STROKE_ARC:
692                                 gp_primitive_arc(tgpi, points2D);
693                                 break;
694                         case GP_STROKE_CURVE:
695                                 gp_primitive_bezier(tgpi, points2D);
696                         default:
697                                 break;
698                 }
699         }
700
701         /* convert screen-coordinates to 3D coordinates */
702         gp_session_validatebuffer(tgpi);
703         gp_init_colors(tgpi);
704         if (gset->flag & GP_SCULPT_SETT_FLAG_PRIMITIVE_CURVE) {
705                 curvemapping_initialize(ts->gp_sculpt.cur_primitive);
706         }
707         if (tgpi->brush->gpencil_settings->flag & GP_BRUSH_USE_JITTER_PRESSURE) {
708                 curvemapping_initialize(tgpi->brush->gpencil_settings->curve_jitter);
709         }
710         if (tgpi->brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
711                 curvemapping_initialize(tgpi->brush->gpencil_settings->curve_strength);
712         }
713
714         /* get an array of depths, far depths are blended */
715         float *depth_arr = NULL;
716         if (is_depth) {
717                 int i;
718                 int mval_i[2], mval_prev[2] = { 0 };
719                 bool interp_depth = false;
720                 bool found_depth = false;
721
722                 /* need to restore the original projection settings before packing up */
723                 view3d_region_operator_needs_opengl(tgpi->win, tgpi->ar);
724                 ED_view3d_autodist_init(
725                         tgpi->depsgraph, tgpi->ar, tgpi->v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
726
727                 depth_arr = MEM_mallocN(sizeof(float) * gps->totpoints, "depth_points");
728                 tGPspoint *ptc = &points2D[0];
729                 for (i = 0; i < gps->totpoints; i++, ptc++) {
730                         round_v2i_v2fl(mval_i, &ptc->x);
731                         if ((ED_view3d_autodist_depth(
732                                      tgpi->ar, mval_i, depth_margin, depth_arr + i) == 0) &&
733                             (i && (ED_view3d_autodist_depth_seg(
734                                            tgpi->ar, mval_i, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
735                         {
736                                 interp_depth = true;
737                         }
738                         else {
739                                 found_depth = true;
740                         }
741                         copy_v2_v2_int(mval_prev, mval_i);
742                 }
743
744                 if (!found_depth) {
745                         for (i = 0; i < gps->totpoints; i++) {
746                                 depth_arr[i] = 0.9999f;
747                         }
748                 }
749                 else {
750                         /* if all depth are too high disable */
751                         bool valid_depth = false;
752                         for (i = 0; i < gps->totpoints; i++) {
753                                 if (depth_arr[i] < 0.9999f) {
754                                         valid_depth = true;
755                                         break;
756                                 }
757                         }
758                         if (!valid_depth) {
759                                 MEM_SAFE_FREE(depth_arr);
760                                 is_depth = false;
761                         }
762                         else {
763                                 if ((ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) ||
764                                     (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST))
765                                 {
766                                         int first_valid = 0;
767                                         int last_valid = 0;
768
769                                         /* find first valid contact point */
770                                         for (i = 0; i < gps->totpoints; i++) {
771                                                 if (depth_arr[i] != FLT_MAX)
772                                                         break;
773                                         }
774                                         first_valid = i;
775
776                                         /* find last valid contact point */
777                                         if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_FIRST) {
778                                                 last_valid = first_valid;
779                                         }
780                                         else {
781                                                 for (i = gps->totpoints - 1; i >= 0; i--) {
782                                                         if (depth_arr[i] != FLT_MAX)
783                                                                 break;
784                                                 }
785                                                 last_valid = i;
786                                         }
787
788                                         /* invalidate any other point, to interpolate between
789                                          * first and last contact in an imaginary line between them */
790                                         for (i = 0; i < gps->totpoints; i++) {
791                                                 if ((i != first_valid) && (i != last_valid)) {
792                                                         depth_arr[i] = FLT_MAX;
793                                                 }
794                                         }
795                                         interp_depth = true;
796                                 }
797
798                                 if (interp_depth) {
799                                         interp_sparse_array(depth_arr, gps->totpoints, FLT_MAX);
800                                 }
801                         }
802                 }
803         }
804
805         /* load stroke points and sbuffer */
806         for (int i = 0; i < gps->totpoints; i++) {
807                 bGPDspoint *pt = &gps->points[i];
808                 tGPspoint *p2d = &points2D[i];
809
810                 /* set rnd value for reuse */
811                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) && (p2d->rnd_dirty != true)) {
812                         p2d->rnd[0] = BLI_rng_get_float(tgpi->rng);
813                         p2d->rnd[1] = BLI_rng_get_float(tgpi->rng);
814                         p2d->rnd[2] = BLI_rng_get_float(tgpi->rng);
815                         p2d->rnd_dirty = true;
816                 }
817
818                 /* Copy points to buffer */
819                 tGPspoint *tpt = ((tGPspoint *)(gpd->runtime.sbuffer) + gpd->runtime.sbuffer_size);
820
821                 /* Store original points */
822                 float tmp_xyp[2];
823                 copy_v2_v2(tmp_xyp, &p2d->x);
824
825                 /* calc pressure */
826                 float curve_pressure = 1.0;
827                 float pressure = 1.0;
828                 float strength = brush->gpencil_settings->draw_strength;
829
830                 /* normalize value to evaluate curve */
831                 if (gset->flag & GP_SCULPT_SETT_FLAG_PRIMITIVE_CURVE) {
832                         float value = (float)i / (gps->totpoints - 1);
833                         curve_pressure = curvemapping_evaluateF(gset->cur_primitive, 0, value);
834                         pressure = curve_pressure;
835                 }
836
837                 /* apply jitter to position */
838                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
839                     (brush->gpencil_settings->draw_jitter > 0.0f))
840                 {
841                         float jitter;
842
843                         if (brush->gpencil_settings->flag & GP_BRUSH_USE_JITTER_PRESSURE) {
844                                 jitter = curvemapping_evaluateF(brush->gpencil_settings->curve_jitter, 0, curve_pressure);
845                                 jitter *= brush->gpencil_settings->draw_sensitivity;
846                         }
847                         else {
848                                 jitter = brush->gpencil_settings->draw_jitter;
849                         }
850
851                         /* exponential value */
852                         const float exfactor = SQUARE(brush->gpencil_settings->draw_jitter + 2.0f);
853                         const float fac = p2d->rnd[0] * exfactor * jitter;
854
855                         /* vector */
856                         float mvec[2], svec[2];;
857                         if (i > 0) {
858                                 mvec[0] = (p2d->x - (p2d - 1)->x);
859                                 mvec[1] = (p2d->y - (p2d - 1)->y);
860                                 normalize_v2(mvec);
861                         }
862                         else {
863                                 zero_v2(mvec);
864                         }
865                         svec[0] = -mvec[1];
866                         svec[1] = mvec[0];
867
868                         if (p2d->rnd[1] > 0.5f) {
869                                 mul_v2_fl(svec, -fac);
870                         }
871                         else {
872                                 mul_v2_fl(svec, fac);
873                         }
874                         add_v2_v2(&p2d->x, svec);
875                 }
876
877                 /* apply randomness to pressure */
878                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
879                     (brush->gpencil_settings->draw_random_press > 0.0f))
880                 {
881                         if (p2d->rnd[0] > 0.5f) {
882                                 pressure -= brush->gpencil_settings->draw_random_press * p2d->rnd[1];
883                         }
884                         else {
885                                 pressure += brush->gpencil_settings->draw_random_press * p2d->rnd[2];
886                         }
887                 }
888
889                 /* color strength */
890                 if (brush->gpencil_settings->flag & GP_BRUSH_USE_STENGTH_PRESSURE) {
891                         float curvef = curvemapping_evaluateF(brush->gpencil_settings->curve_strength, 0, curve_pressure);
892                         strength *= curvef * brush->gpencil_settings->draw_sensitivity;
893                         strength *= brush->gpencil_settings->draw_strength;
894                 }
895
896                 CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
897
898                 /* apply randomness to color strength */
899                 if ((brush->gpencil_settings->flag & GP_BRUSH_GROUP_RANDOM) &&
900                     (brush->gpencil_settings->draw_random_strength > 0.0f))
901                 {
902                         if (p2d->rnd[2] > 0.5f) {
903                                 strength -= strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[0];
904                         }
905                         else {
906                                 strength += strength * brush->gpencil_settings->draw_random_strength * p2d->rnd[1];
907                         }
908                         CLAMP(strength, GPENCIL_STRENGTH_MIN, 1.0f);
909                 }
910
911                 copy_v2_v2(&tpt->x, &p2d->x);
912
913                 CLAMP_MIN(pressure, 0.1f);
914
915                 tpt->pressure = pressure;
916                 tpt->strength = strength;
917                 tpt->time = p2d->time;
918
919                 /* point uv */
920                 if (gpd->runtime.sbuffer_size > 0) {
921                         MaterialGPencilStyle *gp_style = tgpi->mat->gp_style;
922                         const float pixsize = gp_style->texture_pixsize / 1000000.0f;
923                         tGPspoint *tptb = (tGPspoint *)gpd->runtime.sbuffer + gpd->runtime.sbuffer_size - 1;
924                         bGPDspoint spt, spt2;
925
926                         /* get origin to reproject point */
927                         float origin[3];
928                         ED_gp_get_drawing_reference(
929                                 tgpi->scene, tgpi->ob, tgpi->gpl,
930                                 ts->gpencil_v3d_align, origin);
931                         /* reproject current */
932                         ED_gpencil_tpoint_to_point(tgpi->ar, origin, tpt, &spt);
933                         ED_gp_project_point_to_plane(
934                                 tgpi->scene, tgpi->ob, tgpi->rv3d,
935                                 origin, tgpi->lock_axis - 1, &spt);
936
937                         /* reproject previous */
938                         ED_gpencil_tpoint_to_point(tgpi->ar, origin, tptb, &spt2);
939                         ED_gp_project_point_to_plane(
940                                 tgpi->scene, tgpi->ob, tgpi->rv3d,
941                                 origin, tgpi->lock_axis - 1, &spt2);
942                         tgpi->totpixlen += len_v3v3(&spt.x, &spt2.x) / pixsize;
943                         tpt->uv_fac = tgpi->totpixlen;
944                         if ((gp_style) && (gp_style->sima)) {
945                                 tpt->uv_fac /= gp_style->sima->gen_x;
946                         }
947                 }
948                 else {
949                         tgpi->totpixlen = 0.0f;
950                         tpt->uv_fac = 0.0f;
951                 }
952
953                 tpt->uv_rot = p2d->uv_rot;
954
955                 gpd->runtime.sbuffer_size++;
956
957                 /* add small offset to keep stroke over the surface */
958                 if ((depth_arr) && (gpd->zdepth_offset > 0.0f)) {
959                         depth_arr[i] *= (1.0f - gpd->zdepth_offset);
960                 }
961
962                 /* convert screen-coordinates to 3D coordinates */
963                 gp_stroke_convertcoords_tpoint(
964                         tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl,
965                         p2d, depth_arr ? depth_arr + i : NULL,
966                         &pt->x);
967
968                 pt->pressure = pressure;
969                 pt->strength = strength;
970                 pt->time = 0.0f;
971                 pt->flag = 0;
972                 pt->uv_fac = tpt->uv_fac;
973
974                 if (gps->dvert != NULL) {
975                         MDeformVert *dvert = &gps->dvert[i];
976                         dvert->totweight = 0;
977                         dvert->dw = NULL;
978                 }
979
980                 /* Restore original points */
981                 copy_v2_v2(&p2d->x, tmp_xyp);
982         }
983
984         /* store cps and convert coords */
985         if (tgpi->gpd->runtime.tot_cp_points > 0) {
986                 bGPDcontrolpoint *cps = tgpi->gpd->runtime.cp_points;
987                 for (int i = 0; i < tgpi->gpd->runtime.tot_cp_points; i++) {
988                         bGPDcontrolpoint *cp = &cps[i];
989                         gp_stroke_convertcoords_tpoint(tgpi->scene, tgpi->ar, tgpi->ob, tgpi->gpl, (tGPspoint *)cp, NULL, &cp->x);
990                 }
991         }
992
993         /* reproject to plane */
994         if (!is_depth) {
995                 float origin[3];
996                 ED_gp_get_drawing_reference(
997                         tgpi->scene, tgpi->ob, tgpi->gpl,
998                         ts->gpencil_v3d_align, origin);
999                 ED_gp_project_stroke_to_plane(
1000                         tgpi->scene, tgpi->ob, tgpi->rv3d, gps,
1001                         origin, ts->gp_sculpt.lock_axis - 1);
1002         }
1003
1004         /* if parented change position relative to parent object */
1005         for (int i = 0; i < gps->totpoints; i++) {
1006                 bGPDspoint *pt = &gps->points[i];
1007                 gp_apply_parent_point(tgpi->depsgraph, tgpi->ob, tgpi->gpd, tgpi->gpl, pt);
1008         }
1009
1010         /* if camera view, reproject flat to view to avoid perspective effect */
1011         if (is_camera) {
1012                 ED_gpencil_project_stroke_to_view(C, tgpi->gpl, gps);
1013         }
1014
1015         /* force fill recalc */
1016         gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1017
1018         MEM_SAFE_FREE(depth_arr);
1019
1020         DEG_id_tag_update(&gpd->id, ID_RECALC_COPY_ON_WRITE);
1021         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1022         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1023 }
1024
1025 /* Update screen and stroke */
1026 static void gpencil_primitive_update(bContext *C, wmOperator *op, tGPDprimitive *tgpi)
1027 {
1028         /* update indicator in header */
1029         gpencil_primitive_status_indicators(C, tgpi);
1030         /* apply... */
1031         tgpi->type = RNA_enum_get(op->ptr, "type");
1032         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
1033         /* update points position */
1034         gp_primitive_update_strokes(C, tgpi);
1035 }
1036
1037 static void gpencil_primitive_interaction_begin(tGPDprimitive *tgpi, const wmEvent *event)
1038 {
1039         copy_v2fl_v2i(tgpi->mval, event->mval);
1040         copy_v2_v2(tgpi->origin, tgpi->mval);
1041         copy_v2_v2(tgpi->start, tgpi->mval);
1042         copy_v2_v2(tgpi->end, tgpi->mval);
1043         copy_v2_v2(tgpi->cp1, tgpi->mval);
1044         copy_v2_v2(tgpi->cp2, tgpi->mval);
1045 }
1046
1047 /* Exit and free memory */
1048 static void gpencil_primitive_exit(bContext *C, wmOperator *op)
1049 {
1050         tGPDprimitive *tgpi = op->customdata;
1051         bGPdata *gpd = tgpi->gpd;
1052
1053         /* don't assume that operator data exists at all */
1054         if (tgpi) {
1055                 /* clear status message area */
1056                 ED_workspace_status_text(C, NULL);
1057
1058                 MEM_SAFE_FREE(tgpi->points);
1059                 tgpi->gpd->runtime.tot_cp_points = 0;
1060                 MEM_SAFE_FREE(tgpi->gpd->runtime.cp_points);
1061                 /* finally, free memory used by temp data */
1062                 BKE_gpencil_free_strokes(tgpi->gpf);
1063                 MEM_SAFE_FREE(tgpi->gpf);
1064
1065                 /* free random seed */
1066                 if (tgpi->rng != NULL) {
1067                         BLI_rng_free(tgpi->rng);
1068                 }
1069
1070                 MEM_freeN(tgpi);
1071         }
1072
1073         /* free stroke buffer */
1074         if ((gpd != NULL) && (gpd->runtime.sbuffer)) {
1075                 MEM_SAFE_FREE(gpd->runtime.sbuffer);
1076                 gpd->runtime.sbuffer = NULL;
1077
1078                 /* clear flags */
1079                 gpd->runtime.sbuffer_size = 0;
1080                 gpd->runtime.sbuffer_sflag = 0;
1081         }
1082
1083         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY | ID_RECALC_COPY_ON_WRITE);
1084         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1085
1086         /* clear pointer */
1087         op->customdata = NULL;
1088 }
1089
1090 /* Init new temporary primitive data */
1091 static void gpencil_primitive_init(bContext *C, wmOperator *op)
1092 {
1093         ToolSettings *ts = CTX_data_tool_settings(C);
1094         bGPdata *gpd = CTX_data_gpencil_data(C);
1095         Main *bmain = CTX_data_main(C);
1096         Scene *scene = CTX_data_scene(C);
1097         Depsgraph *depsgraph = CTX_data_depsgraph(C);
1098         int cfra_eval = (int)DEG_get_ctime(depsgraph);
1099
1100         /* create temporary operator data */
1101         tGPDprimitive *tgpi = MEM_callocN(sizeof(tGPDprimitive), "GPencil Primitive Data");
1102         op->customdata = tgpi;
1103
1104         tgpi->points = MEM_callocN(sizeof(tGPspoint), "gp primitive points2D");
1105
1106         /* set current scene and window info */
1107         tgpi->bmain = CTX_data_main(C);
1108         tgpi->scene = scene;
1109         tgpi->ob = CTX_data_active_object(C);
1110         tgpi->sa = CTX_wm_area(C);
1111         tgpi->ar = CTX_wm_region(C);
1112         tgpi->rv3d = tgpi->ar->regiondata;
1113         tgpi->v3d = tgpi->sa->spacedata.first;
1114         tgpi->depsgraph = CTX_data_depsgraph(C);
1115         tgpi->win = CTX_wm_window(C);
1116
1117         /* save original type */
1118         tgpi->orign_type = RNA_enum_get(op->ptr, "type");
1119
1120         /* set current frame number */
1121         tgpi->cframe = cfra_eval;
1122
1123         /* set GP datablock */
1124         tgpi->gpd = gpd;
1125         /* region where paint was originated */
1126         tgpi->gpd->runtime.ar = tgpi->ar;
1127
1128         /* control points */
1129         tgpi->gpd->runtime.cp_points = MEM_callocN(sizeof(bGPDcontrolpoint) * MAX_CP, "gp primitive cpoint");
1130         tgpi->gpd->runtime.tot_cp_points = 0;
1131
1132         /* getcolor info */
1133         tgpi->mat = BKE_gpencil_material_ensure(bmain, tgpi->ob);
1134
1135         /* set parameters */
1136         tgpi->type = RNA_enum_get(op->ptr, "type");
1137
1138         if (ELEM(tgpi->type, GP_STROKE_ARC, GP_STROKE_CURVE)) {
1139                 tgpi->curve = true;
1140         }
1141         else {
1142                 tgpi->curve = false;
1143         }
1144
1145         /* set default edge count */
1146         switch (tgpi->type) {
1147                 case GP_STROKE_LINE:
1148                 {
1149                         RNA_int_set(op->ptr, "edges", 8);
1150                         break;
1151                 }
1152                 case GP_STROKE_BOX:
1153                 {
1154                         RNA_int_set(op->ptr, "edges", 8);
1155                         break;
1156                 }
1157                 case GP_STROKE_CIRCLE:
1158                 {
1159                         RNA_int_set(op->ptr, "edges", 96);
1160                         break;
1161                 }
1162                 default:
1163                 {
1164                         RNA_int_set(op->ptr, "edges", 64);
1165                         break;
1166                 }
1167         }
1168
1169         tgpi->tot_stored_edges = 0;
1170         tgpi->tot_edges = RNA_int_get(op->ptr, "edges");
1171         tgpi->flag = IDLE;
1172         tgpi->lock_axis = ts->gp_sculpt.lock_axis;
1173
1174         /* set temp layer, frame and stroke */
1175         gp_primitive_set_initdata(C, tgpi);
1176 }
1177
1178 /* Invoke handler: Initialize the operator */
1179 static int gpencil_primitive_invoke(bContext *C, wmOperator *op, const wmEvent *event)
1180 {
1181         wmWindow *win = CTX_wm_window(C);
1182         bGPdata *gpd = CTX_data_gpencil_data(C);
1183         tGPDprimitive *tgpi = NULL;
1184
1185         /* initialize operator runtime data */
1186         gpencil_primitive_init(C, op);
1187         tgpi = op->customdata;
1188
1189         const bool is_modal = RNA_boolean_get(op->ptr, "wait_for_input");
1190         if (!is_modal) {
1191                 tgpi->flag = IN_PROGRESS;
1192                 gpencil_primitive_interaction_begin(tgpi, event);
1193         }
1194
1195         /* if in tools region, wait till we get to the main (3d-space)
1196          * region before allowing drawing to take place.
1197          */
1198         op->flag |= OP_IS_MODAL_CURSOR_REGION;
1199
1200         /* set cursor to indicate modal */
1201         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1202
1203         /* update sindicator in header */
1204         gpencil_primitive_status_indicators(C, tgpi);
1205         DEG_id_tag_update(&gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1206         WM_event_add_notifier(C, NC_GPENCIL | NA_EDITED, NULL);
1207
1208         /* add a modal handler for this operator */
1209         WM_event_add_modal_handler(C, op);
1210
1211         return OPERATOR_RUNNING_MODAL;
1212 }
1213
1214 /* Helper to complete a primitive */
1215 static void gpencil_primitive_interaction_end(bContext *C, wmOperator *op, wmWindow *win, tGPDprimitive *tgpi)
1216 {
1217         bGPDframe *gpf;
1218         bGPDstroke *gps;
1219
1220         ToolSettings *ts = tgpi->scene->toolsettings;
1221
1222         const int def_nr = tgpi->ob->actdef - 1;
1223         const bool have_weight = (bool)BLI_findlink(&tgpi->ob->defbase, def_nr);
1224
1225         /* return to normal cursor and header status */
1226         ED_workspace_status_text(C, NULL);
1227         WM_cursor_modal_restore(win);
1228
1229         /* insert keyframes as required... */
1230         short add_frame_mode;
1231         if (ts->gpencil_flags & GP_TOOL_FLAG_RETAIN_LAST) {
1232                 add_frame_mode = GP_GETFRAME_ADD_COPY;
1233         }
1234         else {
1235                 add_frame_mode = GP_GETFRAME_ADD_NEW;
1236         }
1237
1238         gpf = BKE_gpencil_layer_getframe(tgpi->gpl, tgpi->cframe, add_frame_mode);
1239
1240         /* prepare stroke to get transferred */
1241         gps = tgpi->gpf->strokes.first;
1242         if (gps) {
1243                 gps->thickness = tgpi->brush->size;
1244                 gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1245                 gps->tot_triangles = 0;
1246
1247                 /* calculate UVs along the stroke */
1248                 ED_gpencil_calc_stroke_uv(tgpi->ob, gps);
1249         }
1250
1251         /* transfer stroke from temporary buffer to the actual frame */
1252         if (ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) {
1253                 BLI_movelisttolist_reverse(&gpf->strokes, &tgpi->gpf->strokes);
1254         }
1255         else {
1256                 BLI_movelisttolist(&gpf->strokes, &tgpi->gpf->strokes);
1257         }
1258         BLI_assert(BLI_listbase_is_empty(&tgpi->gpf->strokes));
1259
1260         /* add weights if required */
1261         if ((ts->gpencil_flags & GP_TOOL_FLAG_CREATE_WEIGHTS) && (have_weight)) {
1262                 BKE_gpencil_dvert_ensure(gps);
1263                 for (int i = 0; i < gps->totpoints; i++) {
1264                         MDeformVert *ve = &gps->dvert[i];
1265                         MDeformWeight *dw = defvert_verify_index(ve, def_nr);
1266                         if (dw) {
1267                                 dw->weight = ts->vgroup_weight;
1268                         }
1269                 }
1270         }
1271
1272         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_COPY_ON_WRITE);
1273         DEG_id_tag_update(&tgpi->gpd->id, ID_RECALC_TRANSFORM | ID_RECALC_GEOMETRY);
1274
1275         /* clean up temp data */
1276         gpencil_primitive_exit(C, op);
1277 }
1278
1279 /* edit event handling */
1280 static void gpencil_primitive_edit_event_handling(bContext *C, wmOperator *op, wmWindow *win, const wmEvent *event, tGPDprimitive *tgpi)
1281 {
1282         /* calculate nearest point then set cursor */
1283         int move = MOVE_NONE;
1284         float a = len_v2v2(tgpi->mval, tgpi->start);
1285         float b = len_v2v2(tgpi->mval, tgpi->end);
1286
1287         float c = len_v2v2(tgpi->mval, tgpi->cp1);
1288         float d = len_v2v2(tgpi->mval, tgpi->cp2);
1289
1290         if (tgpi->flag == IN_CURVE_EDIT) {
1291                 if ((a < BIG_SIZE_CTL && tgpi->tot_stored_edges == 0) || b < BIG_SIZE_CTL) {
1292                         move = MOVE_ENDS;
1293                         WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1294                 }
1295                 else if (tgpi->curve) {
1296                         move = MOVE_CP;
1297                         WM_cursor_modal_set(win, BC_HANDCURSOR);
1298                 }
1299                 else {
1300                         WM_cursor_modal_set(win, BC_CROSSCURSOR);
1301                 }
1302         }
1303         else if (tgpi->flag == IN_PROGRESS) {
1304                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1305         }
1306
1307         switch (event->type) {
1308                 case MOUSEMOVE:
1309                 {
1310                         if ((event->val == KM_PRESS) && tgpi->sel_cp != SELECT_NONE) {
1311                                 if (tgpi->sel_cp == SELECT_START && tgpi->tot_stored_edges == 0) {
1312                                         copy_v2_v2(tgpi->start, tgpi->mval);
1313                                 }
1314                                 else if (tgpi->sel_cp == SELECT_END) {
1315                                         copy_v2_v2(tgpi->end, tgpi->mval);
1316                                 }
1317                                 else if (tgpi->sel_cp == SELECT_CP1 || (tgpi->sel_cp == SELECT_CP2 && tgpi->type != GP_STROKE_CURVE)) {
1318                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1319                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1320                                         tgpi->cp1[0] += dx;
1321                                         tgpi->cp1[1] += dy;
1322                                         if (event->shift)
1323                                                 copy_v2_v2(tgpi->cp2, tgpi->cp1);
1324                                 }
1325                                 else if (tgpi->sel_cp == SELECT_CP2) {
1326                                         float dx = (tgpi->mval[0] - tgpi->mvalo[0]);
1327                                         float dy = (tgpi->mval[1] - tgpi->mvalo[1]);
1328                                         tgpi->cp2[0] += dx;
1329                                         tgpi->cp2[1] += dy;
1330                                         if (event->shift)
1331                                                 copy_v2_v2(tgpi->cp1, tgpi->cp2);
1332                                 }
1333                                 /* update screen */
1334                                 gpencil_primitive_update(C, op, tgpi);
1335                         }
1336                         break;
1337                 }
1338                 case LEFTMOUSE:
1339                 {
1340                         if ((event->val == KM_PRESS)) {
1341                                 /* find nearest cp based on stroke end points */
1342                                 if (move == MOVE_ENDS)
1343                                         tgpi->sel_cp = (a < b) ? SELECT_START : SELECT_END;
1344                                 else if (move == MOVE_CP)
1345                                         tgpi->sel_cp = (c < d) ? SELECT_CP1 : SELECT_CP2;
1346                                 else
1347                                         tgpi->sel_cp = SELECT_NONE;
1348                                 break;
1349                         }
1350                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1351                                 /* set control points and enter edit mode */
1352                                 tgpi->flag = IN_CURVE_EDIT;
1353                                 gp_primitive_update_cps(tgpi);
1354                                 gpencil_primitive_update(C, op, tgpi);
1355                         }
1356                         else {
1357                                 tgpi->sel_cp = SELECT_NONE;
1358                         }
1359                         break;
1360                 }
1361                 case MKEY:
1362                 {
1363                         if ((event->val == KM_PRESS) &&
1364                             (tgpi->curve) &&
1365                             (ELEM(tgpi->orign_type, GP_STROKE_ARC) ))
1366                         {
1367                                 tgpi->flip ^= 1;
1368                                 gp_primitive_update_cps(tgpi);
1369                                 gpencil_primitive_update(C, op, tgpi);
1370                         }
1371                         break;
1372                 }
1373                 case EKEY:
1374                 {
1375                         if (tgpi->flag == IN_CURVE_EDIT && !ELEM(tgpi->type, GP_STROKE_BOX, GP_STROKE_CIRCLE)) {
1376                                 tgpi->flag = IN_PROGRESS;
1377                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1378                                 gpencil_primitive_add_segment(tgpi);
1379                                 copy_v2_v2(tgpi->start, tgpi->end);
1380                                 copy_v2_v2(tgpi->origin, tgpi->start);
1381                                 gp_primitive_update_cps(tgpi);
1382                         }
1383                         break;
1384                 }
1385         }
1386 }
1387
1388 /* brush strength */
1389 static void gpencil_primitive_strength(tGPDprimitive *tgpi, bool reset)
1390 {
1391         Brush *brush = tgpi->brush;
1392         if (brush) {
1393                 if (reset) {
1394                         brush->gpencil_settings->draw_strength = tgpi->brush_strength;
1395                         tgpi->brush_strength = 0.0f;
1396                 }
1397                 else {
1398                         if (tgpi->brush_strength == 0.0f) {
1399                                 tgpi->brush_strength = brush->gpencil_settings->draw_strength;
1400                         }
1401                         float move[2];
1402                         sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1403                         float adjust = (move[1] > 0.0f) ? 0.01f : -0.01f;
1404                         brush->gpencil_settings->draw_strength += adjust * fabsf(len_manhattan_v2(move));
1405                 }
1406
1407                 /* limit low limit because below 0.2f the stroke is invisible */
1408                 CLAMP(brush->gpencil_settings->draw_strength, 0.2f, 1.0f);
1409         }
1410 }
1411
1412 /* brush size */
1413 static void gpencil_primitive_size(tGPDprimitive *tgpi, bool reset)
1414 {
1415         Brush *brush = tgpi->brush;
1416         if (brush) {
1417                 if (reset) {
1418                         brush->size = tgpi->brush_size;
1419                         tgpi->brush_size = 0;
1420                 }
1421                 else {
1422                         if (tgpi->brush_size == 0) {
1423                                 tgpi->brush_size = brush->size;
1424                         }
1425                         float move[2];
1426                         sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1427                         int adjust = (move[1] > 0.0f) ? 1 : -1;
1428                         brush->size += adjust * (int)fabsf(len_manhattan_v2(move));
1429                 }
1430                 CLAMP_MIN(brush->size, 1);
1431         }
1432 }
1433
1434 /* move */
1435 static void gpencil_primitive_move(tGPDprimitive *tgpi, bool reset)
1436 {
1437         float move[2];
1438         zero_v2(move);
1439
1440         if (reset) {
1441                 sub_v2_v2(move, tgpi->move);
1442                 zero_v2(tgpi->move);
1443         }
1444         else {
1445                 sub_v2_v2v2(move, tgpi->mval, tgpi->mvalo);
1446                 add_v2_v2(tgpi->move, move);
1447         }
1448
1449         bGPDstroke *gps = tgpi->gpf->strokes.first;
1450         tGPspoint *points2D = tgpi->points;
1451
1452         for (int i = 0; i < gps->totpoints; i++) {
1453                 tGPspoint *p2d = &points2D[i];
1454                 add_v2_v2(&p2d->x, move);
1455         }
1456
1457         add_v2_v2(tgpi->start, move);
1458         add_v2_v2(tgpi->end, move);
1459         add_v2_v2(tgpi->cp1, move);
1460         add_v2_v2(tgpi->cp2, move);
1461         add_v2_v2(tgpi->origin, move);
1462 }
1463
1464 /* Modal handler: Events handling during interactive part */
1465 static int gpencil_primitive_modal(bContext *C, wmOperator *op, const wmEvent *event)
1466 {
1467         tGPDprimitive *tgpi = op->customdata;
1468         wmWindow *win = CTX_wm_window(C);
1469         const bool has_numinput = hasNumInput(&tgpi->num);
1470
1471         copy_v2fl_v2i(tgpi->mval, event->mval);
1472
1473         if (tgpi->flag == IN_MOVE) {
1474
1475                 switch (event->type) {
1476                         case MOUSEMOVE:
1477                         {
1478                                 gpencil_primitive_move(tgpi, false);
1479                                 gpencil_primitive_update(C, op, tgpi);
1480                                 break;
1481                         }
1482                         case ESCKEY:
1483                         case LEFTMOUSE:
1484                         {
1485                                 zero_v2(tgpi->move);
1486                                 tgpi->flag = IN_CURVE_EDIT;
1487                                 break;
1488                         }
1489                         case RIGHTMOUSE:
1490                         {
1491                                 if (event->val == KM_RELEASE) {
1492                                         tgpi->flag = IN_CURVE_EDIT;
1493                                         gpencil_primitive_move(tgpi, true);
1494                                         gpencil_primitive_update(C, op, tgpi);
1495                                 }
1496                                 break;
1497                         }
1498                 }
1499                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1500                 return OPERATOR_RUNNING_MODAL;
1501         }
1502         else if (tgpi->flag == IN_BRUSH_SIZE) {
1503                 switch (event->type) {
1504                         case MOUSEMOVE:
1505                                 gpencil_primitive_size(tgpi, false);
1506                                 gpencil_primitive_update(C, op, tgpi);
1507                                 break;
1508                         case ESCKEY:
1509                         case MIDDLEMOUSE:
1510                         case LEFTMOUSE:
1511                                 tgpi->brush_size = 0;
1512                                 tgpi->flag = IN_CURVE_EDIT;
1513                                 break;
1514                         case RIGHTMOUSE:
1515                                 if (event->val == KM_RELEASE) {
1516                                         tgpi->flag = IN_CURVE_EDIT;
1517                                         gpencil_primitive_size(tgpi, true);
1518                                         gpencil_primitive_update(C, op, tgpi);
1519                                 }
1520                                 break;
1521                 }
1522                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1523                 return OPERATOR_RUNNING_MODAL;
1524         }
1525         else if (tgpi->flag == IN_BRUSH_STRENGTH) {
1526                 switch (event->type) {
1527                         case MOUSEMOVE:
1528                                 gpencil_primitive_strength(tgpi, false);
1529                                 gpencil_primitive_update(C, op, tgpi);
1530                                 break;
1531                         case ESCKEY:
1532                         case MIDDLEMOUSE:
1533                         case LEFTMOUSE:
1534                                 tgpi->brush_strength = 0.0f;
1535                                 tgpi->flag = IN_CURVE_EDIT;
1536                                 break;
1537                         case RIGHTMOUSE:
1538                                 if (event->val == KM_RELEASE) {
1539                                         tgpi->flag = IN_CURVE_EDIT;
1540                                         gpencil_primitive_strength(tgpi, true);
1541                                         gpencil_primitive_update(C, op, tgpi);
1542                                 }
1543                                 break;
1544                 }
1545                 copy_v2_v2(tgpi->mvalo, tgpi->mval);
1546                 return OPERATOR_RUNNING_MODAL;
1547         }
1548         else if (tgpi->flag != IDLE) {
1549                 gpencil_primitive_edit_event_handling(C, op, win, event, tgpi);
1550         }
1551
1552         switch (event->type) {
1553                 case LEFTMOUSE:
1554                 {
1555                         if ((event->val == KM_PRESS) && (tgpi->flag == IDLE)) {
1556                                 /* start drawing primitive */
1557                                 /* TODO: Ignore if not in main region yet */
1558                                 tgpi->flag = IN_PROGRESS;
1559                                 gpencil_primitive_interaction_begin(tgpi, event);
1560                         }
1561                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_MOVE)) {
1562                                 tgpi->flag = IN_CURVE_EDIT;
1563                         }
1564                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS)) {
1565                                 /* set control points and enter edit mode */
1566                                 tgpi->flag = IN_CURVE_EDIT;
1567                                 gp_primitive_update_cps(tgpi);
1568                                 gpencil_primitive_update(C, op, tgpi);
1569                         }
1570                         else if ((event->val == KM_RELEASE) && (tgpi->flag == IN_PROGRESS) && (tgpi->type != GP_STROKE_CURVE)) {
1571                                 /* stop drawing primitive */
1572                                 tgpi->flag = IDLE;
1573                                 gpencil_primitive_interaction_end(C, op, win, tgpi);
1574                                 /* done! */
1575                                 return OPERATOR_FINISHED;
1576                         }
1577                         else {
1578                                 if (G.debug & G_DEBUG) {
1579                                         printf("GP Add Primitive Modal: LEFTMOUSE %d, Status = %d\n", event->val, tgpi->flag);
1580                                 }
1581                         }
1582                         break;
1583                 }
1584                 case SPACEKEY:  /* confirm */
1585                 case MIDDLEMOUSE:
1586                 case RETKEY:
1587                 {
1588                         tgpi->flag = IDLE;
1589                         gpencil_primitive_interaction_end(C, op, win, tgpi);
1590                         /* done! */
1591                         return OPERATOR_FINISHED;
1592                 }
1593                 case RIGHTMOUSE:
1594                 {
1595                         /* exception to cancel current stroke when we have previous strokes in buffer */
1596                         if (tgpi->tot_stored_edges > 0) {
1597                                 tgpi->flag = IDLE;
1598                                 tgpi->tot_edges = 0;
1599                                 gp_primitive_update_strokes(C, tgpi);
1600                                 gpencil_primitive_interaction_end(C, op, win, tgpi);
1601                                 /* done! */
1602                                 return OPERATOR_FINISHED;
1603                         }
1604                         ATTR_FALLTHROUGH;
1605                 }
1606                 case ESCKEY:
1607                 {
1608                         /* return to normal cursor and header status */
1609                         ED_workspace_status_text(C, NULL);
1610                         WM_cursor_modal_restore(win);
1611
1612                         /* clean up temp data */
1613                         gpencil_primitive_exit(C, op);
1614
1615                         /* canceled! */
1616                         return OPERATOR_CANCELLED;
1617                 }
1618                 case PADPLUSKEY:
1619                 case WHEELUPMOUSE:
1620                 {
1621                         if ((event->val != KM_RELEASE)) {
1622                                 tgpi->tot_edges = tgpi->tot_edges + 1;
1623                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1624                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1625
1626                                 /* update screen */
1627                                 gpencil_primitive_update(C, op, tgpi);
1628                         }
1629                         break;
1630                 }
1631                 case PADMINUS:
1632                 case WHEELDOWNMOUSE:
1633                 {
1634                         if ((event->val != KM_RELEASE)) {
1635                                 tgpi->tot_edges = tgpi->tot_edges - 1;
1636                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1637                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1638
1639                                 /* update screen */
1640                                 gpencil_primitive_update(C, op, tgpi);
1641                         }
1642                         break;
1643                 }
1644                 case GKEY: /* grab mode */
1645                 {
1646                         if ((event->val == KM_PRESS)) {
1647                                 tgpi->flag = IN_MOVE;
1648                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1649                         }
1650                         break;
1651                 }
1652                 case FKEY: /* brush thickness/ brush strength */
1653                 {
1654                         if ((event->val == KM_PRESS)) {
1655                                 if (event->shift) {
1656                                         tgpi->flag = IN_BRUSH_STRENGTH;
1657                                 }
1658                                 else {
1659                                         tgpi->flag = IN_BRUSH_SIZE;
1660                                 }
1661                                 WM_cursor_modal_set(win, BC_NS_SCROLLCURSOR);
1662                         }
1663                         break;
1664                 }
1665                 case CKEY: /* curve mode */
1666                 {
1667                         if ((event->val == KM_PRESS) &&
1668                             (tgpi->orign_type == GP_STROKE_CURVE))
1669                         {
1670                                 switch (tgpi->type) {
1671                                         case GP_STROKE_CURVE:
1672                                                 tgpi->type = GP_STROKE_ARC;
1673                                                 break;
1674                                         default:
1675                                         case GP_STROKE_ARC:
1676                                                 tgpi->type = GP_STROKE_CURVE;
1677                                                 break;
1678                                 }
1679
1680                                 RNA_enum_set(op->ptr, "type", tgpi->type);
1681                                 gp_primitive_update_cps(tgpi);
1682                                 gpencil_primitive_update(C, op, tgpi);
1683                         }
1684                         break;
1685                 }
1686                 case TABKEY:
1687                 {
1688                         if (tgpi->flag == IN_CURVE_EDIT) {
1689                                 tgpi->flag = IN_PROGRESS;
1690                                 WM_cursor_modal_set(win, BC_NSEW_SCROLLCURSOR);
1691                                 gp_primitive_update_cps(tgpi);
1692                                 gpencil_primitive_update(C, op, tgpi);
1693                         }
1694                         break;
1695                 }
1696                 case MOUSEMOVE: /* calculate new position */
1697                 {
1698                         if (tgpi->flag == IN_CURVE_EDIT) {
1699                                 break;
1700                         }
1701                         /* only handle mousemove if not doing numinput */
1702                         if (has_numinput == false) {
1703                                 /* update position of mouse */
1704                                 copy_v2_v2(tgpi->end, tgpi->mval);
1705                                 copy_v2_v2(tgpi->start, tgpi->origin);
1706                                 if (tgpi->flag == IDLE) {
1707                                         copy_v2_v2(tgpi->origin, tgpi->mval);
1708                                 }
1709                                 /* Keep square if shift key */
1710                                 if (event->shift) {
1711                                         float x = tgpi->end[0] - tgpi->origin[0];
1712                                         float y = tgpi->end[1] - tgpi->origin[1];
1713                                         if (tgpi->type == GP_STROKE_LINE || tgpi->curve) {
1714                                                 float angle = fabsf(atan2f(y, x));
1715                                                 if (angle < 0.4f || angle > (M_PI - 0.4f)) {
1716                                                         tgpi->end[1] = tgpi->origin[1];
1717                                                 }
1718                                                 else if (angle > (M_PI_2 - 0.4f) && angle < (M_PI_2 + 0.4f)) {
1719                                                         tgpi->end[0] = tgpi->origin[0];
1720                                                 }
1721                                                 else {
1722                                                         gpencil_primitive_to_square(tgpi, x, y);
1723                                                 }
1724                                         }
1725                                         else {
1726                                                 gpencil_primitive_to_square(tgpi, x, y);
1727                                         }
1728                                 }
1729                                 /* Center primitive if alt key */
1730                                 if (event->alt) {
1731                                         tgpi->start[0] = tgpi->origin[0] - (tgpi->end[0] - tgpi->origin[0]);
1732                                         tgpi->start[1] = tgpi->origin[1] - (tgpi->end[1] - tgpi->origin[1]);
1733                                 }
1734                                 gp_primitive_update_cps(tgpi);
1735                                 /* update screen */
1736                                 gpencil_primitive_update(C, op, tgpi);
1737                         }
1738                         break;
1739                 }
1740                 default:
1741                 {
1742                         if (tgpi->flag != IN_CURVE_EDIT && (event->val == KM_PRESS) && handleNumInput(C, &tgpi->num, event)) {
1743                                 float value;
1744
1745                                 /* Grab data from numeric input, and store this new value (the user see an int) */
1746                                 value = tgpi->tot_edges;
1747                                 applyNumInput(&tgpi->num, &value);
1748                                 tgpi->tot_edges = value;
1749
1750                                 CLAMP(tgpi->tot_edges, MIN_EDGES, MAX_EDGES);
1751                                 RNA_int_set(op->ptr, "edges", tgpi->tot_edges);
1752
1753                                 /* update screen */
1754                                 gpencil_primitive_update(C, op, tgpi);
1755
1756                                 break;
1757                         }
1758                         else {
1759                                 /* unhandled event - allow to pass through */
1760                                 return OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH;
1761                         }
1762                 }
1763         }
1764
1765         copy_v2_v2(tgpi->mvalo, tgpi->mval);
1766         /* still running... */
1767         return OPERATOR_RUNNING_MODAL;
1768 }
1769
1770 /* Cancel handler */
1771 static void gpencil_primitive_cancel(bContext *C, wmOperator *op)
1772 {
1773         /* this is just a wrapper around exit() */
1774         gpencil_primitive_exit(C, op);
1775 }
1776
1777 void GPENCIL_OT_primitive(wmOperatorType *ot)
1778 {
1779         static EnumPropertyItem primitive_type[] = {
1780                 {GP_STROKE_BOX, "BOX", 0, "Box", ""},
1781                 {GP_STROKE_LINE, "LINE", 0, "Line", ""},
1782                 {GP_STROKE_CIRCLE, "CIRCLE", 0, "Circle", ""},
1783                 {GP_STROKE_ARC, "ARC", 0, "Arc", ""},
1784                 {GP_STROKE_CURVE, "CURVE", 0, "Curve", ""},
1785                 {0, NULL, 0, NULL, NULL},
1786         };
1787
1788         /* identifiers */
1789         ot->name = "Grease Pencil Shapes";
1790         ot->idname = "GPENCIL_OT_primitive";
1791         ot->description = "Create predefined grease pencil stroke shapes";
1792
1793         /* callbacks */
1794         ot->invoke = gpencil_primitive_invoke;
1795         ot->modal = gpencil_primitive_modal;
1796         ot->cancel = gpencil_primitive_cancel;
1797         ot->poll = gpencil_primitive_add_poll;
1798
1799         /* flags */
1800         ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
1801
1802         /* properties */
1803         PropertyRNA *prop;
1804
1805         prop = RNA_def_int(ot->srna, "edges", 4, MIN_EDGES, MAX_EDGES, "Edges", "Number of polygon edges", MIN_EDGES, MAX_EDGES);
1806         RNA_def_property_flag(prop, PROP_SKIP_SAVE);
1807
1808         RNA_def_enum(ot->srna, "type", primitive_type, GP_STROKE_BOX, "Type", "Type of shape");
1809
1810         prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
1811         RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
1812 }