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