Fix T60022: Crash when adding grease pencil object to a collection disabled in viewport.
[blender.git] / source / blender / editors / gpencil / gpencil_utils.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) 2014, Blender Foundation
19  *
20  * Contributor(s): Joshua Leung, Antonio Vazquez
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/editors/gpencil/gpencil_utils.c
26  *  \ingroup edgpencil
27  */
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <stddef.h>
33 #include <math.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "BLI_math.h"
38 #include "BLI_blenlib.h"
39 #include "BLI_utildefines.h"
40 #include "BLT_translation.h"
41 #include "BLI_rand.h"
42
43 #include "DNA_meshdata_types.h"
44 #include "DNA_gpencil_types.h"
45 #include "DNA_brush_types.h"
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_screen_types.h"
49 #include "DNA_space_types.h"
50 #include "DNA_view3d_types.h"
51
52 #include "BKE_action.h"
53 #include "BKE_colortools.h"
54 #include "BKE_deform.h"
55 #include "BKE_main.h"
56 #include "BKE_brush.h"
57 #include "BKE_context.h"
58 #include "BKE_gpencil.h"
59 #include "BKE_object.h"
60 #include "BKE_paint.h"
61 #include "BKE_material.h"
62 #include "BKE_tracking.h"
63
64 #include "WM_api.h"
65 #include "WM_toolsystem.h"
66
67 #include "RNA_access.h"
68 #include "RNA_define.h"
69 #include "RNA_enum_types.h"
70
71 #include "UI_resources.h"
72 #include "UI_view2d.h"
73
74 #include "ED_gpencil.h"
75 #include "ED_clip.h"
76 #include "ED_view3d.h"
77 #include "ED_object.h"
78 #include "ED_screen.h"
79
80 #include "GPU_immediate.h"
81 #include "GPU_immediate_util.h"
82
83 #include "DEG_depsgraph.h"
84 #include "DEG_depsgraph_query.h"
85
86 #include "gpencil_intern.h"
87
88 /* ******************************************************** */
89 /* Context Wrangling... */
90
91 /* Get pointer to active Grease Pencil datablock, and an RNA-pointer to trace back to whatever owns it,
92  * when context info is not available.
93  */
94 bGPdata **ED_gpencil_data_get_pointers_direct(ID *screen_id, ScrArea *sa, Scene *scene, Object *ob, PointerRNA *r_ptr)
95 {
96         /* if there's an active area, check if the particular editor may
97          * have defined any special Grease Pencil context for editing...
98          */
99         if (sa) {
100                 SpaceLink *sl = sa->spacedata.first;
101
102                 switch (sa->spacetype) {
103                         /* XXX: Should we reduce reliance on context.gpencil_data for these cases? */
104                         case SPACE_BUTS: /* properties */
105                         case SPACE_INFO: /* header info (needed after workspaces merge) */
106                         {
107                                 if (ob && (ob->type == OB_GPENCIL)) {
108                                         /* GP Object */
109                                         if (r_ptr) RNA_id_pointer_create(&ob->id, r_ptr);
110                                         return (bGPdata **)&ob->data;
111                                 }
112                                 else {
113                                         return NULL;
114                                 }
115
116                                 break;
117                         }
118
119                         case SPACE_TOPBAR: /* Topbar (needed after topbar merge) */
120                         case SPACE_VIEW3D: /* 3D-View */
121                         {
122                                 if (ob && (ob->type == OB_GPENCIL)) {
123                                         /* GP Object */
124                                         if (r_ptr) RNA_id_pointer_create(&ob->id, r_ptr);
125                                         return (bGPdata **)&ob->data;
126                                 }
127                                 else {
128                                         /* Annotations */
129                                         /* XXX: */
130                                         if (r_ptr) RNA_id_pointer_create(&scene->id, r_ptr);
131                                         return &scene->gpd;
132                                 }
133
134                                 break;
135                         }
136                         case SPACE_NODE: /* Nodes Editor */
137                         {
138                                 SpaceNode *snode = (SpaceNode *)sl;
139
140                                 /* return the GP data for the active node block/node */
141                                 if (snode && snode->nodetree) {
142                                         /* for now, as long as there's an active node tree, default to using that in the Nodes Editor */
143                                         if (r_ptr) RNA_id_pointer_create(&snode->nodetree->id, r_ptr);
144                                         return &snode->nodetree->gpd;
145                                 }
146
147                                 /* even when there is no node-tree, don't allow this to flow to scene */
148                                 return NULL;
149                         }
150                         case SPACE_SEQ: /* Sequencer */
151                         {
152                                 SpaceSeq *sseq = (SpaceSeq *)sl;
153
154                                 /* for now, Grease Pencil data is associated with the space (actually preview region only) */
155                                 /* XXX our convention for everything else is to link to data though... */
156                                 if (r_ptr) RNA_pointer_create(screen_id, &RNA_SpaceSequenceEditor, sseq, r_ptr);
157                                 return &sseq->gpd;
158                         }
159                         case SPACE_IMAGE: /* Image/UV Editor */
160                         {
161                                 SpaceImage *sima = (SpaceImage *)sl;
162
163                                 /* for now, Grease Pencil data is associated with the space... */
164                                 /* XXX our convention for everything else is to link to data though... */
165                                 if (r_ptr) RNA_pointer_create(screen_id, &RNA_SpaceImageEditor, sima, r_ptr);
166                                 return &sima->gpd;
167                         }
168                         case SPACE_CLIP: /* Nodes Editor */
169                         {
170                                 SpaceClip *sc = (SpaceClip *)sl;
171                                 MovieClip *clip = ED_space_clip_get_clip(sc);
172
173                                 if (clip) {
174                                         if (sc->gpencil_src == SC_GPENCIL_SRC_TRACK) {
175                                                 MovieTrackingTrack *track = BKE_tracking_track_get_active(&clip->tracking);
176
177                                                 if (!track)
178                                                         return NULL;
179
180                                                 if (r_ptr) RNA_pointer_create(&clip->id, &RNA_MovieTrackingTrack, track, r_ptr);
181                                                 return &track->gpd;
182                                         }
183                                         else {
184                                                 if (r_ptr) RNA_id_pointer_create(&clip->id, r_ptr);
185                                                 return &clip->gpd;
186                                         }
187                                 }
188                                 break;
189                         }
190                         default: /* unsupported space */
191                                 return NULL;
192                 }
193         }
194
195         return NULL;
196 }
197
198 /* Get pointer to active Grease Pencil datablock, and an RNA-pointer to trace back to whatever owns it */
199 bGPdata **ED_gpencil_data_get_pointers(const bContext *C, PointerRNA *r_ptr)
200 {
201         ID *screen_id = (ID *)CTX_wm_screen(C);
202         Scene *scene = CTX_data_scene(C);
203         ScrArea *sa = CTX_wm_area(C);
204         Object *ob = CTX_data_active_object(C);
205
206         return ED_gpencil_data_get_pointers_direct(screen_id, sa, scene, ob, r_ptr);
207 }
208
209 /* -------------------------------------------------------- */
210
211 /* Get the active Grease Pencil datablock, when context is not available */
212 bGPdata *ED_gpencil_data_get_active_direct(ID *screen_id, ScrArea *sa, Scene *scene, Object *ob)
213 {
214         bGPdata **gpd_ptr = ED_gpencil_data_get_pointers_direct(screen_id, sa, scene, ob, NULL);
215         return (gpd_ptr) ? *(gpd_ptr) : NULL;
216 }
217
218 /**
219  * Get the active Grease Pencil datablock
220  * \note This is the original (bmain) copy of the datablock, stored in files.
221  *       Do not use for reading evaluated copies of GP Objects data
222  */
223 bGPdata *ED_gpencil_data_get_active(const bContext *C)
224 {
225         bGPdata **gpd_ptr = ED_gpencil_data_get_pointers(C, NULL);
226         return (gpd_ptr) ? *(gpd_ptr) : NULL;
227 }
228
229 /**
230  * Get the evaluated copy of the active Grease Pencil datablock (where applicable)
231  * - For the 3D View (i.e. "GP Objects"), this gives the evaluated copy of the GP datablock
232  *   (i.e. a copy of the active GP datablock for the active object, where modifiers have been
233  *   applied). This is needed to correctly work with "Copy-on-Write"
234  * - For all other editors (i.e. "GP Annotations"), this just gives the active datablock
235  *   like for ED_gpencil_data_get_active()
236  */
237 bGPdata *ED_gpencil_data_get_active_evaluated(const bContext *C)
238 {
239         ID *screen_id = (ID *)CTX_wm_screen(C);
240         ScrArea *sa = CTX_wm_area(C);
241
242         const Depsgraph *depsgraph = CTX_data_depsgraph(C);
243         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
244         Object *ob = CTX_data_active_object(C);
245         Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob);
246
247         /* if (ob && ob->type == OB_GPENCIL) BLI_assert(ob_eval->data == DEG_get_evaluated_id(ob->data)); */
248         return ED_gpencil_data_get_active_direct(screen_id, sa, scene_eval, ob_eval);
249 }
250
251 /* -------------------------------------------------------- */
252
253 /**
254  * Utility to check whether the r_ptr output of ED_gpencil_data_get_pointers()
255  * is for annotation usage.
256  */
257 bool ED_gpencil_data_owner_is_annotation(PointerRNA *owner_ptr)
258 {
259         /* Key Assumption: If the pointer is an object, we're dealing with a GP Object's data.
260          * Otherwise, the GP datablock is being used for annotations (i.e. everywhere else)
261          */
262         return ((owner_ptr) && (owner_ptr->type != &RNA_Object));
263 }
264
265 /* -------------------------------------------------------- */
266
267 // XXX: this should be removed... We really shouldn't duplicate logic like this!
268 bGPdata *ED_gpencil_data_get_active_v3d(ViewLayer *view_layer, View3D *v3d)
269 {
270         Base *base = view_layer->basact;
271         bGPdata *gpd = NULL;
272
273         /* We have to make sure active object is actually visible and selected, else we must use default scene gpd,
274          * to be consistent with ED_gpencil_data_get_active's behavior.
275          */
276         if (base && TESTBASE(v3d, base)) {
277                 if (base->object->type == OB_GPENCIL)
278                         gpd = base->object->data;
279         }
280         return gpd ? gpd : NULL;
281 }
282
283 /* ******************************************************** */
284 /* Keyframe Indicator Checks */
285
286 /* Check whether there's an active GP keyframe on the current frame */
287 bool ED_gpencil_has_keyframe_v3d(Scene *UNUSED(scene), Object *ob, int cfra)
288 {
289         if (ob && ob->data && (ob->type == OB_GPENCIL)) {
290                 bGPDlayer *gpl = BKE_gpencil_layer_getactive(ob->data);
291                 if (gpl) {
292                         if (gpl->actframe) {
293                                 // XXX: assumes that frame has been fetched already
294                                 return (gpl->actframe->framenum == cfra);
295                         }
296                         else {
297                                 /* XXX: disabled as could be too much of a penalty */
298                                 /* return BKE_gpencil_layer_find_frame(gpl, cfra); */
299                         }
300                 }
301         }
302
303         return false;
304 }
305
306 /* ******************************************************** */
307 /* Poll Callbacks */
308
309 /* poll callback for adding data/layers - special */
310 bool gp_add_poll(bContext *C)
311 {
312         /* the base line we have is that we have somewhere to add Grease Pencil data */
313         return ED_gpencil_data_get_pointers(C, NULL) != NULL;
314 }
315
316 /* poll callback for checking if there is an active layer */
317 bool gp_active_layer_poll(bContext *C)
318 {
319         bGPdata *gpd = ED_gpencil_data_get_active(C);
320         bGPDlayer *gpl = BKE_gpencil_layer_getactive(gpd);
321
322         return (gpl != NULL);
323 }
324
325 /* poll callback for checking if there is an active brush */
326 bool gp_active_brush_poll(bContext *C)
327 {
328         ToolSettings *ts = CTX_data_tool_settings(C);
329         Paint *paint = &ts->gp_paint->paint;
330         if (paint) {
331                 return (paint->brush != NULL);
332         }
333         else {
334                 return false;
335         }
336 }
337
338 /* ******************************************************** */
339 /* Dynamic Enums of GP Layers */
340 /* NOTE: These include an option to create a new layer and use that... */
341
342 /* Just existing layers */
343 const EnumPropertyItem *ED_gpencil_layers_enum_itemf(
344         bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
345 {
346         bGPdata *gpd = CTX_data_gpencil_data(C);
347         bGPDlayer *gpl;
348         EnumPropertyItem *item = NULL, item_tmp = {0};
349         int totitem = 0;
350         int i = 0;
351
352         if (ELEM(NULL, C, gpd)) {
353                 return DummyRNA_DEFAULT_items;
354         }
355
356         /* Existing layers */
357         for (gpl = gpd->layers.first; gpl; gpl = gpl->next, i++) {
358                 item_tmp.identifier = gpl->info;
359                 item_tmp.name = gpl->info;
360                 item_tmp.value = i;
361
362                 if (gpl->flag & GP_LAYER_ACTIVE)
363                         item_tmp.icon = ICON_GREASEPENCIL;
364                 else
365                         item_tmp.icon = ICON_NONE;
366
367                 RNA_enum_item_add(&item, &totitem, &item_tmp);
368         }
369
370         RNA_enum_item_end(&item, &totitem);
371         *r_free = true;
372
373         return item;
374 }
375
376 /* Existing + Option to add/use new layer */
377 const EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(
378         bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
379 {
380         bGPdata *gpd = CTX_data_gpencil_data(C);
381         bGPDlayer *gpl;
382         EnumPropertyItem *item = NULL, item_tmp = {0};
383         int totitem = 0;
384         int i = 0;
385
386         if (ELEM(NULL, C, gpd)) {
387                 return DummyRNA_DEFAULT_items;
388         }
389
390         /* Create new layer */
391         /* TODO: have some way of specifying that we don't want this? */
392         {
393                 /* "New Layer" entry */
394                 item_tmp.identifier = "__CREATE__";
395                 item_tmp.name = "New Layer";
396                 item_tmp.value = -1;
397                 item_tmp.icon = ICON_ADD;
398                 RNA_enum_item_add(&item, &totitem, &item_tmp);
399
400                 /* separator */
401                 RNA_enum_item_add_separator(&item, &totitem);
402         }
403         const int tot = BLI_listbase_count(&gpd->layers);
404         /* Existing layers */
405         for (gpl = gpd->layers.last, i = 0; gpl; gpl = gpl->prev, i++) {
406                 item_tmp.identifier = gpl->info;
407                 item_tmp.name = gpl->info;
408                 item_tmp.value = tot - i - 1;
409
410                 if (gpl->flag & GP_LAYER_ACTIVE)
411                         item_tmp.icon = ICON_GREASEPENCIL;
412                 else
413                         item_tmp.icon = ICON_NONE;
414
415                 RNA_enum_item_add(&item, &totitem, &item_tmp);
416         }
417
418         RNA_enum_item_end(&item, &totitem);
419         *r_free = true;
420
421         return item;
422 }
423
424
425 /* ******************************************************** */
426 /* Brush Tool Core */
427
428 /**
429  * Check whether a given stroke segment is inside a circular brush
430  *
431  * \param mval: The current screen-space coordinates (midpoint) of the brush
432  * \param mvalo: The previous screen-space coordinates (midpoint) of the brush (NOT CURRENTLY USED)
433  * \param rad: The radius of the brush
434  *
435  * \param x0, y0: The screen-space x and y coordinates of the start of the stroke segment
436  * \param x1, y1: The screen-space x and y coordinates of the end of the stroke segment
437  */
438 bool gp_stroke_inside_circle(
439         const float mval[2], const float UNUSED(mvalo[2]),
440         int rad, int x0, int y0, int x1, int y1)
441 {
442         /* simple within-radius check for now */
443         const float screen_co_a[2] = {x0, y0};
444         const float screen_co_b[2] = {x1, y1};
445
446         if (edge_inside_circle(mval, rad, screen_co_a, screen_co_b)) {
447                 return true;
448         }
449
450         /* not inside */
451         return false;
452 }
453
454 /* ******************************************************** */
455 /* Stroke Validity Testing */
456
457 /* Check whether given stroke can be edited given the supplied context */
458 /* TODO: do we need additional flags for screenspace vs dataspace? */
459 bool ED_gpencil_stroke_can_use_direct(const ScrArea *sa, const bGPDstroke *gps)
460 {
461         /* sanity check */
462         if (ELEM(NULL, sa, gps))
463                 return false;
464
465         /* filter stroke types by flags + spacetype */
466         if (gps->flag & GP_STROKE_3DSPACE) {
467                 /* 3D strokes - only in 3D view */
468                 return ((sa->spacetype == SPACE_VIEW3D) || (sa->spacetype == SPACE_BUTS));
469         }
470         else if (gps->flag & GP_STROKE_2DIMAGE) {
471                 /* Special "image" strokes - only in Image Editor */
472                 return (sa->spacetype == SPACE_IMAGE);
473         }
474         else if (gps->flag & GP_STROKE_2DSPACE) {
475                 /* 2D strokes (dataspace) - for any 2D view (i.e. everything other than 3D view) */
476                 return (sa->spacetype != SPACE_VIEW3D);
477         }
478         else {
479                 /* view aligned - anything goes */
480                 return true;
481         }
482 }
483
484 /* Check whether given stroke can be edited in the current context */
485 bool ED_gpencil_stroke_can_use(const bContext *C, const bGPDstroke *gps)
486 {
487         ScrArea *sa = CTX_wm_area(C);
488         return ED_gpencil_stroke_can_use_direct(sa, gps);
489 }
490
491 /* Check whether given stroke can be edited for the current color */
492 bool ED_gpencil_stroke_color_use(Object *ob, const bGPDlayer *gpl, const bGPDstroke *gps)
493 {
494         /* check if the color is editable */
495         MaterialGPencilStyle *gp_style = BKE_material_gpencil_settings_get(ob, gps->mat_nr + 1);
496
497         if (gp_style != NULL) {
498                 if (gp_style->flag & GP_STYLE_COLOR_HIDE)
499                         return false;
500                 if (((gpl->flag & GP_LAYER_UNLOCK_COLOR) == 0) && (gp_style->flag & GP_STYLE_COLOR_LOCKED))
501                         return false;
502         }
503
504         return true;
505 }
506
507 /* ******************************************************** */
508 /* Space Conversion */
509
510 /**
511  * Init settings for stroke point space conversions
512  *
513  * \param r_gsc: [out] The space conversion settings struct, populated with necessary params
514  */
515 void gp_point_conversion_init(bContext *C, GP_SpaceConversion *r_gsc)
516 {
517         ScrArea *sa = CTX_wm_area(C);
518         ARegion *ar = CTX_wm_region(C);
519
520         /* zero out the storage (just in case) */
521         memset(r_gsc, 0, sizeof(GP_SpaceConversion));
522         unit_m4(r_gsc->mat);
523
524         /* store settings */
525         r_gsc->scene = CTX_data_scene(C);
526         r_gsc->ob = CTX_data_active_object(C);
527
528         r_gsc->sa = sa;
529         r_gsc->ar = ar;
530         r_gsc->v2d = &ar->v2d;
531
532         /* init region-specific stuff */
533         if (sa->spacetype == SPACE_VIEW3D) {
534                 wmWindow *win = CTX_wm_window(C);
535                 Scene *scene = CTX_data_scene(C);
536                 struct Depsgraph *depsgraph = CTX_data_depsgraph(C);
537                 View3D *v3d = (View3D *)CTX_wm_space_data(C);
538                 RegionView3D *rv3d = ar->regiondata;
539
540                 /* init 3d depth buffers */
541                 view3d_operator_needs_opengl(C);
542
543                 view3d_region_operator_needs_opengl(win, ar);
544                 ED_view3d_autodist_init(depsgraph, ar, v3d, 0);
545
546                 /* for camera view set the subrect */
547                 if (rv3d->persp == RV3D_CAMOB) {
548                         ED_view3d_calc_camera_border(scene, CTX_data_depsgraph(C), ar, v3d, rv3d, &r_gsc->subrect_data, true); /* no shift */
549                         r_gsc->subrect = &r_gsc->subrect_data;
550                 }
551         }
552 }
553
554 /**
555  * Convert point to parent space
556  *
557  * \param pt: Original point
558  * \param diff_mat: Matrix with the difference between original parent matrix
559  * \param[out] r_pt: Pointer to new point after apply matrix
560  */
561 void gp_point_to_parent_space(const bGPDspoint *pt, const float diff_mat[4][4], bGPDspoint *r_pt)
562 {
563         float fpt[3];
564
565         mul_v3_m4v3(fpt, diff_mat, &pt->x);
566         copy_v3_v3(&r_pt->x, fpt);
567 }
568
569 /**
570  * Change position relative to parent object
571  */
572 void gp_apply_parent(Depsgraph *depsgraph, Object *obact, bGPdata *gpd, bGPDlayer *gpl, bGPDstroke *gps)
573 {
574         bGPDspoint *pt;
575         int i;
576
577         /* undo matrix */
578         float diff_mat[4][4];
579         float inverse_diff_mat[4][4];
580         float fpt[3];
581
582         ED_gpencil_parent_location(depsgraph, obact, gpd, gpl, diff_mat);
583         invert_m4_m4(inverse_diff_mat, diff_mat);
584
585         for (i = 0; i < gps->totpoints; i++) {
586                 pt = &gps->points[i];
587                 mul_v3_m4v3(fpt, inverse_diff_mat, &pt->x);
588                 copy_v3_v3(&pt->x, fpt);
589         }
590 }
591
592 /**
593  * Change point position relative to parent object
594  */
595 void gp_apply_parent_point(Depsgraph *depsgraph, Object *obact, bGPdata *gpd, bGPDlayer *gpl, bGPDspoint *pt)
596 {
597         /* undo matrix */
598         float diff_mat[4][4];
599         float inverse_diff_mat[4][4];
600         float fpt[3];
601
602         ED_gpencil_parent_location(depsgraph, obact, gpd, gpl, diff_mat);
603         invert_m4_m4(inverse_diff_mat, diff_mat);
604
605         mul_v3_m4v3(fpt, inverse_diff_mat, &pt->x);
606         copy_v3_v3(&pt->x, fpt);
607 }
608
609 /**
610  * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
611  *
612  * \param[out] r_x  The screen-space x-coordinate of the point
613  * \param[out] r_y  The screen-space y-coordinate of the point
614  *
615  * \warning This assumes that the caller has already checked whether the stroke in question can be drawn.
616  */
617 void gp_point_to_xy(
618         const GP_SpaceConversion *gsc, const bGPDstroke *gps, const bGPDspoint *pt,
619         int *r_x, int *r_y)
620 {
621         const ARegion *ar = gsc->ar;
622         const View2D *v2d = gsc->v2d;
623         const rctf *subrect = gsc->subrect;
624         int xyval[2];
625
626         /* sanity checks */
627         BLI_assert(!(gps->flag & GP_STROKE_3DSPACE) || (gsc->sa->spacetype == SPACE_VIEW3D));
628         BLI_assert(!(gps->flag & GP_STROKE_2DSPACE) || (gsc->sa->spacetype != SPACE_VIEW3D));
629
630
631         if (gps->flag & GP_STROKE_3DSPACE) {
632                 if (ED_view3d_project_int_global(ar, &pt->x, xyval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
633                         *r_x = xyval[0];
634                         *r_y = xyval[1];
635                 }
636                 else {
637                         *r_x = V2D_IS_CLIPPED;
638                         *r_y = V2D_IS_CLIPPED;
639                 }
640         }
641         else if (gps->flag & GP_STROKE_2DSPACE) {
642                 float vec[3] = {pt->x, pt->y, 0.0f};
643                 mul_m4_v3(gsc->mat, vec);
644                 UI_view2d_view_to_region_clip(v2d, vec[0], vec[1], r_x, r_y);
645         }
646         else {
647                 if (subrect == NULL) {
648                         /* normal 3D view (or view space) */
649                         *r_x = (int)(pt->x / 100 * ar->winx);
650                         *r_y = (int)(pt->y / 100 * ar->winy);
651                 }
652                 else {
653                         /* camera view, use subrect */
654                         *r_x = (int)((pt->x / 100) * BLI_rctf_size_x(subrect)) + subrect->xmin;
655                         *r_y = (int)((pt->y / 100) * BLI_rctf_size_y(subrect)) + subrect->ymin;
656                 }
657         }
658 }
659
660 /**
661  * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
662  *
663  * Just like gp_point_to_xy(), except the resulting coordinates are floats not ints.
664  * Use this version to solve "stair-step" artifacts which may arise when roundtripping the calculations.
665  *
666  * \param r_x: [out] The screen-space x-coordinate of the point
667  * \param r_y: [out] The screen-space y-coordinate of the point
668  *
669  * \warning This assumes that the caller has already checked whether the stroke in question can be drawn
670  */
671 void gp_point_to_xy_fl(
672         const GP_SpaceConversion *gsc, const bGPDstroke *gps, const bGPDspoint *pt,
673         float *r_x, float *r_y)
674 {
675         const ARegion *ar = gsc->ar;
676         const View2D *v2d = gsc->v2d;
677         const rctf *subrect = gsc->subrect;
678         float xyval[2];
679
680         /* sanity checks */
681         BLI_assert(!(gps->flag & GP_STROKE_3DSPACE) || (gsc->sa->spacetype == SPACE_VIEW3D));
682         BLI_assert(!(gps->flag & GP_STROKE_2DSPACE) || (gsc->sa->spacetype != SPACE_VIEW3D));
683
684
685         if (gps->flag & GP_STROKE_3DSPACE) {
686                 if (ED_view3d_project_float_global(ar, &pt->x, xyval, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
687                         *r_x = xyval[0];
688                         *r_y = xyval[1];
689                 }
690                 else {
691                         *r_x = 0.0f;
692                         *r_y = 0.0f;
693                 }
694         }
695         else if (gps->flag & GP_STROKE_2DSPACE) {
696                 float vec[3] = {pt->x, pt->y, 0.0f};
697                 int t_x, t_y;
698
699                 mul_m4_v3(gsc->mat, vec);
700                 UI_view2d_view_to_region_clip(v2d, vec[0], vec[1], &t_x, &t_y);
701
702                 if ((t_x == t_y) && (t_x == V2D_IS_CLIPPED)) {
703                         /* XXX: Or should we just always use the values as-is? */
704                         *r_x = 0.0f;
705                         *r_y = 0.0f;
706                 }
707                 else {
708                         *r_x = (float)t_x;
709                         *r_y = (float)t_y;
710                 }
711         }
712         else {
713                 if (subrect == NULL) {
714                         /* normal 3D view (or view space) */
715                         *r_x = (pt->x / 100.0f * ar->winx);
716                         *r_y = (pt->y / 100.0f * ar->winy);
717                 }
718                 else {
719                         /* camera view, use subrect */
720                         *r_x = ((pt->x / 100.0f) * BLI_rctf_size_x(subrect)) + subrect->xmin;
721                         *r_y = ((pt->y / 100.0f) * BLI_rctf_size_y(subrect)) + subrect->ymin;
722                 }
723         }
724 }
725
726 /**
727  * Project screenspace coordinates to 3D-space
728  *
729  * For use with editing tools where it is easier to perform the operations in 2D,
730  * and then later convert the transformed points back to 3D.
731  *
732  * \param screen_co: The screenspace 2D coordinates to convert to
733  * \param r_out: The resulting 3D coordinates of the input point
734  *
735  * \note We include this as a utility function, since the standard method
736  * involves quite a few steps, which are invariably always the same
737  * for all GPencil operations. So, it's nicer to just centralize these.
738  *
739  * \warning Assumes that it is getting called in a 3D view only.
740  */
741 bool gp_point_xy_to_3d(GP_SpaceConversion *gsc, Scene *scene, const float screen_co[2], float r_out[3])
742 {
743         const RegionView3D *rv3d = gsc->ar->regiondata;
744         float rvec[3];
745
746         ED_gp_get_drawing_reference(scene, gsc->ob, gsc->gpl,
747                 scene->toolsettings->gpencil_v3d_align, rvec);
748
749         float zfac = ED_view3d_calc_zfac(rv3d, rvec, NULL);
750
751         float mval_f[2], mval_prj[2];
752         float dvec[3];
753
754         copy_v2_v2(mval_f, screen_co);
755
756         if (ED_view3d_project_float_global(gsc->ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
757                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
758                 ED_view3d_win_to_delta(gsc->ar, mval_f, dvec, zfac);
759                 sub_v3_v3v3(r_out, rvec, dvec);
760
761                 return true;
762         }
763         else {
764                 zero_v3(r_out);
765
766                 return false;
767         }
768 }
769
770 /**
771  * Convert tGPspoint (temporary 2D/screenspace point data used by GP modal operators)
772  * to 3D coordinates.
773  *
774  * \param point2D: The screenspace 2D point data to convert
775  * \param depth: Depth array (via ED_view3d_autodist_depth())
776  * \param[out] r_out: The resulting 2D point data
777  */
778 void gp_stroke_convertcoords_tpoint(
779         Scene *scene, ARegion *ar,
780         Object *ob, bGPDlayer *gpl,
781         const tGPspoint *point2D, float *depth,
782         float r_out[3])
783 {
784         ToolSettings *ts = scene->toolsettings;
785
786         int mval_i[2];
787         round_v2i_v2fl(mval_i, &point2D->x);
788
789         if ((depth != NULL) && (ED_view3d_autodist_simple(ar, mval_i, r_out, 0, depth))) {
790                 /* projecting onto 3D-Geometry
791                  * - nothing more needs to be done here, since view_autodist_simple() has already done it
792                  */
793         }
794         else {
795                 float mval_f[2] = {point2D->x, point2D->y};
796                 float mval_prj[2];
797                 float rvec[3], dvec[3];
798                 float zfac;
799
800                 /* Current method just converts each point in screen-coordinates to
801                  * 3D-coordinates using the 3D-cursor as reference.
802                  */
803                 ED_gp_get_drawing_reference(scene, ob, gpl, ts->gpencil_v3d_align, rvec);
804                 zfac = ED_view3d_calc_zfac(ar->regiondata, rvec, NULL);
805
806                 if (ED_view3d_project_float_global(ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
807                         sub_v2_v2v2(mval_f, mval_prj, mval_f);
808                         ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
809                         sub_v3_v3v3(r_out, rvec, dvec);
810                 }
811                 else {
812                         zero_v3(r_out);
813                 }
814         }
815 }
816
817 /**
818  * Get drawing reference point for conversion or projection of the stroke
819  * \param[out] r_vec : Reference point found
820  */
821 void ED_gp_get_drawing_reference(
822         const Scene *scene, const Object *ob, bGPDlayer *UNUSED(gpl),
823         char align_flag, float r_vec[3])
824 {
825         const float *fp = scene->cursor.location;
826
827         /* if using a gpencil object at cursor mode, can use the location of the object */
828         if (align_flag & GP_PROJECT_VIEWSPACE) {
829                 if (ob && (ob->type == OB_GPENCIL)) {
830                         /* fallback (no strokes) - use cursor or object location */
831                         if (align_flag & GP_PROJECT_CURSOR) {
832                                 /* use 3D-cursor */
833                                 copy_v3_v3(r_vec, fp);
834                         }
835                         else {
836                                 /* use object location */
837                                 copy_v3_v3(r_vec, ob->obmat[3]);
838                         }
839                 }
840         }
841         else {
842                 /* use 3D-cursor */
843                 copy_v3_v3(r_vec, fp);
844         }
845 }
846
847 void ED_gpencil_project_stroke_to_view(bContext *C, bGPDlayer *gpl, bGPDstroke *gps)
848 {
849         Scene *scene = CTX_data_scene(C);
850         Depsgraph *depsgraph = CTX_data_depsgraph(C);
851         Object *ob = CTX_data_active_object(C);
852         bGPdata *gpd = (bGPdata *)ob->data;
853         GP_SpaceConversion gsc = { NULL };
854
855         bGPDspoint *pt;
856         int i;
857         float diff_mat[4][4];
858         float inverse_diff_mat[4][4];
859
860         /* init space conversion stuff */
861         gp_point_conversion_init(C, &gsc);
862
863         ED_gpencil_parent_location(depsgraph, ob, gpd, gpl, diff_mat);
864         invert_m4_m4(inverse_diff_mat, diff_mat);
865
866         /* Adjust each point */
867         for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
868                 float xy[2];
869
870                 bGPDspoint pt2;
871                 gp_point_to_parent_space(pt, diff_mat, &pt2);
872                 gp_point_to_xy_fl(&gsc, gps, &pt2, &xy[0], &xy[1]);
873
874                 /* Planar - All on same plane parallel to the viewplane */
875                 gp_point_xy_to_3d(&gsc, scene, xy, &pt->x);
876
877                 /* Unapply parent corrections */
878                 mul_m4_v3(inverse_diff_mat, &pt->x);
879         }
880 }
881
882 /**
883  * Reproject all points of the stroke to a plane locked to axis to avoid stroke offset
884  */
885 void ED_gp_project_stroke_to_plane(
886         const Object *ob, const RegionView3D *rv3d, bGPDstroke *gps, const float origin[3], const int axis)
887 {
888         float plane_normal[3];
889         float vn[3];
890
891         float ray[3];
892         float rpoint[3];
893
894         /* normal vector for a plane locked to axis */
895         zero_v3(plane_normal);
896         if (axis < 0) {
897                 /* if the axis is not locked, need a vector to the view direction
898                  * in order to get the right size of the stroke.
899                  */
900                 ED_view3d_global_to_vector(rv3d, origin, plane_normal);
901         }
902         else {
903                 plane_normal[axis] = 1.0f;
904                 /* if object, apply object rotation */
905                 if (ob && (ob->type == OB_GPENCIL)) {
906                         mul_mat3_m4_v3(ob->obmat, plane_normal);
907                 }
908         }
909
910         /* Reproject the points in the plane */
911         for (int i = 0; i < gps->totpoints; i++) {
912                 bGPDspoint *pt = &gps->points[i];
913
914                 /* get a vector from the point with the current view direction of the viewport */
915                 ED_view3d_global_to_vector(rv3d, &pt->x, vn);
916
917                 /* calculate line extreme point to create a ray that cross the plane */
918                 mul_v3_fl(vn, -50.0f);
919                 add_v3_v3v3(ray, &pt->x, vn);
920
921                 /* if the line never intersect, the point is not changed */
922                 if (isect_line_plane_v3(rpoint, &pt->x, ray, origin, plane_normal)) {
923                         copy_v3_v3(&pt->x, rpoint);
924                 }
925         }
926 }
927
928 /**
929  * Reproject given point to a plane locked to axis to avoid stroke offset
930  * \param[in, out] pt : Point to affect
931  */
932 void ED_gp_project_point_to_plane(
933         const Object *ob, const RegionView3D *rv3d, const float origin[3], const int axis, bGPDspoint *pt)
934 {
935         float plane_normal[3];
936         float vn[3];
937
938         float ray[3];
939         float rpoint[3];
940
941         /* normal vector for a plane locked to axis */
942         zero_v3(plane_normal);
943         if (axis < 0) {
944                 /* if the axis is not locked, need a vector to the view direction
945                  * in order to get the right size of the stroke.
946                  */
947                 ED_view3d_global_to_vector(rv3d, origin, plane_normal);
948         }
949         else {
950                 plane_normal[axis] = 1.0f;
951                 /* if object, apply object rotation */
952                 if (ob && (ob->type == OB_GPENCIL)) {
953                         mul_mat3_m4_v3(ob->obmat, plane_normal);
954                 }
955         }
956
957
958         /* Reproject the points in the plane */
959         /* get a vector from the point with the current view direction of the viewport */
960         ED_view3d_global_to_vector(rv3d, &pt->x, vn);
961
962         /* calculate line extrem point to create a ray that cross the plane */
963         mul_v3_fl(vn, -50.0f);
964         add_v3_v3v3(ray, &pt->x, vn);
965
966         /* if the line never intersect, the point is not changed */
967         if (isect_line_plane_v3(rpoint, &pt->x, ray, origin, plane_normal)) {
968                 copy_v3_v3(&pt->x, rpoint);
969         }
970 }
971
972 /* ******************************************************** */
973 /* Stroke Operations */
974 // XXX: Check if these functions duplicate stuff in blenkernel, and/or whether we should just deduplicate
975
976 /**
977  * Subdivide a stroke once, by adding a point half way between each pair of existing points
978  * \param gps: Stroke data
979  * \param subdivide: Number of times to subdivide
980  */
981 void gp_subdivide_stroke(bGPDstroke *gps, const int subdivide)
982 {
983         bGPDspoint *temp_points;
984         int totnewpoints, oldtotpoints;
985         int i2;
986
987         /* loop as many times as levels */
988         for (int s = 0; s < subdivide; s++) {
989                 totnewpoints = gps->totpoints - 1;
990                 /* duplicate points in a temp area */
991                 temp_points = MEM_dupallocN(gps->points);
992                 oldtotpoints = gps->totpoints;
993
994                 /* resize the points arrays */
995                 gps->totpoints += totnewpoints;
996                 gps->points = MEM_recallocN(gps->points, sizeof(*gps->points) * gps->totpoints);
997                 if (gps->dvert != NULL) {
998                         gps->dvert = MEM_recallocN(gps->dvert, sizeof(*gps->dvert) * gps->totpoints);
999                 }
1000                 gps->flag |= GP_STROKE_RECALC_GEOMETRY;
1001
1002                 /* move points from last to first to new place */
1003                 i2 = gps->totpoints - 1;
1004                 for (int i = oldtotpoints - 1; i > 0; i--) {
1005                         bGPDspoint *pt = &temp_points[i];
1006                         bGPDspoint *pt_final = &gps->points[i2];
1007
1008                         copy_v3_v3(&pt_final->x, &pt->x);
1009                         pt_final->pressure = pt->pressure;
1010                         pt_final->strength = pt->strength;
1011                         pt_final->time = pt->time;
1012                         pt_final->flag = pt->flag;
1013                         pt_final->uv_fac = pt->uv_fac;
1014                         pt_final->uv_rot = pt->uv_rot;
1015
1016                         if (gps->dvert != NULL) {
1017                                 MDeformVert *dvert = &gps->dvert[i];
1018                                 MDeformVert *dvert_final = &gps->dvert[i2];
1019
1020                                 dvert_final->totweight = dvert->totweight;
1021                                 dvert_final->dw = dvert->dw;
1022                         }
1023
1024                         i2 -= 2;
1025                 }
1026                 /* interpolate mid points */
1027                 i2 = 1;
1028                 for (int i = 0; i < oldtotpoints - 1; i++) {
1029                         bGPDspoint *pt = &temp_points[i];
1030                         bGPDspoint *next = &temp_points[i + 1];
1031                         bGPDspoint *pt_final = &gps->points[i2];
1032
1033                         /* add a half way point */
1034                         interp_v3_v3v3(&pt_final->x, &pt->x, &next->x, 0.5f);
1035                         pt_final->pressure = interpf(pt->pressure, next->pressure, 0.5f);
1036                         pt_final->strength = interpf(pt->strength, next->strength, 0.5f);
1037                         CLAMP(pt_final->strength, GPENCIL_STRENGTH_MIN, 1.0f);
1038                         pt_final->time = interpf(pt->time, next->time, 0.5f);
1039                         pt_final->uv_fac = interpf(pt->uv_fac, next->uv_fac, 0.5f);
1040                         pt_final->uv_rot = interpf(pt->uv_rot, next->uv_rot, 0.5f);
1041
1042                         if (gps->dvert != NULL) {
1043                                 MDeformVert *dvert_final = &gps->dvert[i2];
1044                                 dvert_final->totweight = 0;
1045                                 dvert_final->dw = NULL;
1046                         }
1047
1048                         i2 += 2;
1049                 }
1050
1051                 MEM_SAFE_FREE(temp_points);
1052
1053                 /* move points to smooth stroke */
1054                 /* duplicate points in a temp area with the new subdivide data */
1055                 temp_points = MEM_dupallocN(gps->points);
1056
1057                 /* extreme points are not changed */
1058                 for (int i = 0; i < gps->totpoints - 2; i++) {
1059                         bGPDspoint *pt = &temp_points[i];
1060                         bGPDspoint *next = &temp_points[i + 1];
1061                         bGPDspoint *pt_final = &gps->points[i + 1];
1062
1063                         /* move point */
1064                         interp_v3_v3v3(&pt_final->x, &pt->x, &next->x, 0.5f);
1065                 }
1066                 /* free temp memory */
1067                 MEM_SAFE_FREE(temp_points);
1068         }
1069 }
1070
1071 /**
1072  * Add randomness to stroke
1073  * \param gps: Stroke data
1074  * \param brush: Brush data
1075  */
1076 void gp_randomize_stroke(bGPDstroke *gps, Brush *brush, RNG *rng)
1077 {
1078         bGPDspoint *pt1, *pt2, *pt3;
1079         float v1[3];
1080         float v2[3];
1081         if (gps->totpoints < 3) {
1082                 return;
1083         }
1084
1085         /* get two vectors using 3 points */
1086         pt1 = &gps->points[0];
1087         pt2 = &gps->points[1];
1088         pt3 = &gps->points[(int)(gps->totpoints * 0.75)];
1089
1090         sub_v3_v3v3(v1, &pt2->x, &pt1->x);
1091         sub_v3_v3v3(v2, &pt3->x, &pt2->x);
1092         normalize_v3(v1);
1093         normalize_v3(v2);
1094
1095         /* get normal vector to plane created by two vectors */
1096         float normal[3];
1097         cross_v3_v3v3(normal, v1, v2);
1098         normalize_v3(normal);
1099
1100         /* get orthogonal vector to plane to rotate random effect */
1101         float ortho[3];
1102         cross_v3_v3v3(ortho, v1, normal);
1103         normalize_v3(ortho);
1104
1105         /* Read all points and apply shift vector (first and last point not modified) */
1106         for (int i = 1; i < gps->totpoints - 1; i++) {
1107                 bGPDspoint *pt = &gps->points[i];
1108                 /* get vector with shift (apply a division because random is too sensitive */
1109                 const float fac = BLI_rng_get_float(rng) * (brush->gpencil_settings->draw_random_sub / 10.0f);
1110                 float svec[3];
1111                 copy_v3_v3(svec, ortho);
1112                 if (BLI_rng_get_float(rng) > 0.5f) {
1113                         mul_v3_fl(svec, -fac);
1114                 }
1115                 else {
1116                         mul_v3_fl(svec, fac);
1117                 }
1118
1119                 /* apply shift */
1120                 add_v3_v3(&pt->x, svec);
1121         }
1122 }
1123
1124 /* ******************************************************** */
1125 /* Layer Parenting  - Compute Parent Transforms */
1126
1127 /* calculate difference matrix */
1128 void ED_gpencil_parent_location(
1129         const Depsgraph *depsgraph, Object *obact, bGPdata *UNUSED(gpd),
1130         bGPDlayer *gpl, float diff_mat[4][4])
1131 {
1132         Object *ob_eval = depsgraph != NULL ? DEG_get_evaluated_object(depsgraph, obact) : obact;
1133         Object *obparent = gpl->parent;
1134         Object *obparent_eval = depsgraph != NULL ? DEG_get_evaluated_object(depsgraph, obparent) : obparent;
1135
1136         /* if not layer parented, try with object parented */
1137         if (obparent_eval == NULL) {
1138                 if (ob_eval != NULL) {
1139                         if (ob_eval->type == OB_GPENCIL) {
1140                                 copy_m4_m4(diff_mat, ob_eval->obmat);
1141                                 return;
1142                         }
1143                 }
1144                 /* not gpencil object */
1145                 unit_m4(diff_mat);
1146                 return;
1147         }
1148         else {
1149                 if ((gpl->partype == PAROBJECT) || (gpl->partype == PARSKEL)) {
1150                         mul_m4_m4m4(diff_mat, obparent_eval->obmat, gpl->inverse);
1151                         return;
1152                 }
1153                 else if (gpl->partype == PARBONE) {
1154                         bPoseChannel *pchan = BKE_pose_channel_find_name(obparent_eval->pose, gpl->parsubstr);
1155                         if (pchan) {
1156                                 float tmp_mat[4][4];
1157                                 mul_m4_m4m4(tmp_mat, obparent_eval->obmat, pchan->pose_mat);
1158                                 mul_m4_m4m4(diff_mat, tmp_mat, gpl->inverse);
1159                         }
1160                         else {
1161                                 mul_m4_m4m4(diff_mat, obparent_eval->obmat, gpl->inverse); /* if bone not found use object (armature) */
1162                         }
1163                         return;
1164                 }
1165                 else {
1166                         unit_m4(diff_mat); /* not defined type */
1167                 }
1168         }
1169 }
1170
1171 /* reset parent matrix for all layers */
1172 void ED_gpencil_reset_layers_parent(Depsgraph *depsgraph, Object *obact, bGPdata *gpd)
1173 {
1174         bGPDspoint *pt;
1175         int i;
1176         float diff_mat[4][4];
1177         float cur_mat[4][4];
1178
1179         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1180                 if (gpl->parent != NULL) {
1181                         /* calculate new matrix */
1182                         if ((gpl->partype == PAROBJECT) || (gpl->partype == PARSKEL)) {
1183                                 invert_m4_m4(cur_mat, gpl->parent->obmat);
1184                         }
1185                         else if (gpl->partype == PARBONE) {
1186                                 bPoseChannel *pchan = BKE_pose_channel_find_name(gpl->parent->pose, gpl->parsubstr);
1187                                 if (pchan) {
1188                                         float tmp_mat[4][4];
1189                                         mul_m4_m4m4(tmp_mat, gpl->parent->obmat, pchan->pose_mat);
1190                                         invert_m4_m4(cur_mat, tmp_mat);
1191                                 }
1192                         }
1193
1194                         /* only redo if any change */
1195                         if (!equals_m4m4(gpl->inverse, cur_mat)) {
1196                                 /* first apply current transformation to all strokes */
1197                                 ED_gpencil_parent_location(depsgraph, obact, gpd, gpl, diff_mat);
1198                                 for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
1199                                         for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
1200                                                 for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
1201                                                         mul_m4_v3(diff_mat, &pt->x);
1202                                                 }
1203                                         }
1204                                 }
1205                                 /* set new parent matrix */
1206                                 copy_m4_m4(gpl->inverse, cur_mat);
1207                         }
1208                 }
1209         }
1210 }
1211 /* ******************************************************** */
1212 /* GP Object Stuff */
1213
1214 /* Helper function to create new OB_GPENCIL Object */
1215 Object *ED_gpencil_add_object(bContext *C, Scene *UNUSED(scene), const float loc[3], ushort local_view_bits)
1216 {
1217         float rot[3] = {0.0f};
1218
1219         Object *ob = ED_object_add_type(C, OB_GPENCIL, NULL, loc, rot, false, local_view_bits);
1220
1221         /* define size */
1222         BKE_object_obdata_size_init(ob, GP_OBGPENCIL_DEFAULT_SIZE);
1223         /* create default brushes and colors */
1224         ED_gpencil_add_defaults(C, ob);
1225
1226         return ob;
1227 }
1228
1229 /* Helper function to create default colors and drawing brushes */
1230 void ED_gpencil_add_defaults(bContext *C, Object *ob)
1231 {
1232         Main *bmain = CTX_data_main(C);
1233         ToolSettings *ts = CTX_data_tool_settings(C);
1234
1235         /* first try to reuse default material */
1236         if (ob->actcol > 0) {
1237                 Material *ma = give_current_material(ob, ob->actcol);
1238                 if ((ma) && (ma->gp_style == NULL)) {
1239                         BKE_material_init_gpencil_settings(ma);
1240                 }
1241         }
1242
1243         /* ensure color exist */
1244         BKE_gpencil_material_ensure(bmain, ob);
1245
1246         BKE_paint_ensure(ts, (Paint **)&ts->gp_paint);
1247         Paint *paint = &ts->gp_paint->paint;
1248         /* if not exist, create a new one */
1249         if (paint->brush == NULL) {
1250                 /* create new brushes */
1251                 BKE_brush_gpencil_presets(C);
1252         }
1253
1254         /* ensure multiframe falloff curve */
1255         if (ts->gp_sculpt.cur_falloff == NULL) {
1256                 ts->gp_sculpt.cur_falloff = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
1257                 CurveMapping *gp_falloff_curve = ts->gp_sculpt.cur_falloff;
1258                 curvemapping_initialize(gp_falloff_curve);
1259                 curvemap_reset(
1260                         gp_falloff_curve->cm,
1261                         &gp_falloff_curve->clipr,
1262                         CURVE_PRESET_GAUSS,
1263                         CURVEMAP_SLOPE_POSITIVE);
1264         }
1265 }
1266
1267 /* ******************************************************** */
1268 /* Vertex Groups */
1269
1270 /* assign points to vertex group */
1271 void ED_gpencil_vgroup_assign(bContext *C, Object *ob, float weight)
1272 {
1273         bGPdata *gpd = (bGPdata *)ob->data;
1274         const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
1275         const int def_nr = ob->actdef - 1;
1276         if (!BLI_findlink(&ob->defbase, def_nr))
1277                 return;
1278
1279         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1280         {
1281                 bGPDframe *init_gpf = gpl->actframe;
1282                 bGPDstroke *gps = NULL;
1283                 if (is_multiedit) {
1284                         init_gpf = gpl->frames.first;
1285                 }
1286
1287                 for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
1288                         if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
1289                                 if (gpf == NULL)
1290                                         continue;
1291
1292                                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
1293
1294                                         /* skip strokes that are invalid for current view */
1295                                         if (ED_gpencil_stroke_can_use(C, gps) == false)
1296                                                 continue;
1297
1298                                         if (gps->flag & GP_STROKE_SELECT) {
1299                                                 /* verify the weight array is created */
1300                                                 BKE_gpencil_dvert_ensure(gps);
1301
1302                                                 for (int i = 0; i < gps->totpoints; i++) {
1303                                                         bGPDspoint *pt = &gps->points[i];
1304                                                         MDeformVert *dvert = &gps->dvert[i];
1305                                                         if (pt->flag & GP_SPOINT_SELECT) {
1306                                                                 MDeformWeight *dw = defvert_verify_index(dvert, def_nr);
1307                                                                 if (dw) {
1308                                                                         dw->weight = weight;
1309                                                                 }
1310                                                         }
1311                                                 }
1312                                         }
1313                                 }
1314                         }
1315
1316                         /* if not multiedit, exit loop*/
1317                         if (!is_multiedit) {
1318                                 break;
1319                         }
1320                 }
1321         }
1322         CTX_DATA_END;
1323 }
1324
1325 /* remove points from vertex group */
1326 void ED_gpencil_vgroup_remove(bContext *C, Object *ob)
1327 {
1328         bGPdata *gpd = (bGPdata *)ob->data;
1329         const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
1330         const int def_nr = ob->actdef - 1;
1331         if (!BLI_findlink(&ob->defbase, def_nr))
1332                 return;
1333
1334         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1335         {
1336                 bGPDframe *init_gpf = gpl->actframe;
1337                 bGPDstroke *gps = NULL;
1338                 if (is_multiedit) {
1339                         init_gpf = gpl->frames.first;
1340                 }
1341
1342                 for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
1343                         if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
1344                                 if (gpf == NULL)
1345                                         continue;
1346
1347                                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
1348
1349                                         /* skip strokes that are invalid for current view */
1350                                         if (ED_gpencil_stroke_can_use(C, gps) == false)
1351                                                 continue;
1352
1353                                         for (int i = 0; i < gps->totpoints; i++) {
1354                                                 bGPDspoint *pt = &gps->points[i];
1355                                                 if (gps->dvert == NULL) {
1356                                                         continue;
1357                                                 }
1358                                                 MDeformVert *dvert = &gps->dvert[i];
1359
1360                                                 if ((pt->flag & GP_SPOINT_SELECT) && (dvert->totweight > 0)) {
1361                                                         MDeformWeight *dw = defvert_find_index(dvert, def_nr);
1362                                                         if (dw != NULL) {
1363                                                                 defvert_remove_group(dvert, dw);
1364                                                         }
1365                                                 }
1366                                         }
1367                                 }
1368                         }
1369
1370                         /* if not multiedit, exit loop*/
1371                         if (!is_multiedit) {
1372                                 break;
1373                         }
1374                 }
1375         }
1376         CTX_DATA_END;
1377 }
1378
1379 /* select points of vertex group */
1380 void ED_gpencil_vgroup_select(bContext *C, Object *ob)
1381 {
1382         bGPdata *gpd = (bGPdata *)ob->data;
1383         const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
1384         const int def_nr = ob->actdef - 1;
1385         if (!BLI_findlink(&ob->defbase, def_nr))
1386                 return;
1387
1388         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1389         {
1390                 bGPDframe *init_gpf = gpl->actframe;
1391                 bGPDstroke *gps = NULL;
1392                 if (is_multiedit) {
1393                         init_gpf = gpl->frames.first;
1394                 }
1395
1396                 for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
1397                         if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
1398                                 if (gpf == NULL)
1399                                         continue;
1400
1401                                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
1402
1403                                         /* skip strokes that are invalid for current view */
1404                                         if (ED_gpencil_stroke_can_use(C, gps) == false)
1405                                                 continue;
1406
1407                                         for (int i = 0; i < gps->totpoints; i++) {
1408                                                 bGPDspoint *pt = &gps->points[i];
1409                                                 if (gps->dvert == NULL) {
1410                                                         continue;
1411                                                 }
1412                                                 MDeformVert *dvert = &gps->dvert[i];
1413
1414                                                 if (defvert_find_index(dvert, def_nr) != NULL) {
1415                                                         pt->flag |= GP_SPOINT_SELECT;
1416                                                         gps->flag |= GP_STROKE_SELECT;
1417                                                 }
1418                                         }
1419                                 }
1420                         }
1421
1422                         /* if not multiedit, exit loop*/
1423                         if (!is_multiedit) {
1424                                 break;
1425                         }
1426                 }
1427         }
1428         CTX_DATA_END;
1429 }
1430
1431 /* unselect points of vertex group */
1432 void ED_gpencil_vgroup_deselect(bContext *C, Object *ob)
1433 {
1434         bGPdata *gpd = (bGPdata *)ob->data;
1435         const bool is_multiedit = (bool)GPENCIL_MULTIEDIT_SESSIONS_ON(gpd);
1436         const int def_nr = ob->actdef - 1;
1437         if (!BLI_findlink(&ob->defbase, def_nr))
1438                 return;
1439
1440         CTX_DATA_BEGIN(C, bGPDlayer *, gpl, editable_gpencil_layers)
1441         {
1442                 bGPDframe *init_gpf = gpl->actframe;
1443                 bGPDstroke *gps = NULL;
1444                 if (is_multiedit) {
1445                         init_gpf = gpl->frames.first;
1446                 }
1447
1448                 for (bGPDframe *gpf = init_gpf; gpf; gpf = gpf->next) {
1449                         if ((gpf == gpl->actframe) || ((gpf->flag & GP_FRAME_SELECT) && (is_multiedit))) {
1450                                 if (gpf == NULL)
1451                                         continue;
1452
1453                                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
1454
1455                                         /* skip strokes that are invalid for current view */
1456                                         if (ED_gpencil_stroke_can_use(C, gps) == false)
1457                                                 continue;
1458
1459                                         for (int i = 0; i < gps->totpoints; i++) {
1460                                                 bGPDspoint *pt = &gps->points[i];
1461                                                 if (gps->dvert == NULL) {
1462                                                         continue;
1463                                                 }
1464                                                 MDeformVert *dvert = &gps->dvert[i];
1465
1466                                                 if (defvert_find_index(dvert, def_nr) != NULL) {
1467                                                         pt->flag &= ~GP_SPOINT_SELECT;
1468                                                 }
1469                                         }
1470                                 }
1471                         }
1472
1473                         /* if not multiedit, exit loop*/
1474                         if (!is_multiedit) {
1475                                 break;
1476                         }
1477                 }
1478         }
1479         CTX_DATA_END;
1480 }
1481
1482 /* ******************************************************** */
1483 /* Cursor drawing */
1484
1485 /* check if cursor is in drawing region */
1486 static bool gp_check_cursor_region(bContext *C, int mval_i[2])
1487 {
1488         ARegion *ar = CTX_wm_region(C);
1489         ScrArea *sa = CTX_wm_area(C);
1490         Object *ob = CTX_data_active_object(C);
1491
1492         if ((ob == NULL) ||
1493             (!ELEM(ob->mode, OB_MODE_PAINT_GPENCIL, OB_MODE_SCULPT_GPENCIL, OB_MODE_WEIGHT_GPENCIL)))
1494         {
1495                 return false;
1496         }
1497
1498         /* TODO: add more spacetypes */
1499         if (!ELEM(sa->spacetype, SPACE_VIEW3D)) {
1500                 return false;
1501         }
1502         if ((ar) && (ar->regiontype != RGN_TYPE_WINDOW)) {
1503                 return false;
1504         }
1505         else if (ar) {
1506                 return BLI_rcti_isect_pt_v(&ar->winrct, mval_i);
1507         }
1508         else {
1509                 return false;
1510         }
1511 }
1512
1513 /* draw eraser cursor */
1514 void ED_gpencil_brush_draw_eraser(Brush *brush, int x, int y)
1515 {
1516         short radius = (short)brush->size;
1517
1518         GPUVertFormat *format = immVertexFormat();
1519         const uint shdr_pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
1520         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1521
1522         glEnable(GL_LINE_SMOOTH);
1523         glEnable(GL_BLEND);
1524         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1525
1526         immUniformColor4ub(255, 100, 100, 20);
1527         imm_draw_circle_fill_2d(shdr_pos, x, y, radius, 40);
1528
1529         immUnbindProgram();
1530
1531         immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
1532
1533         float viewport_size[4];
1534         glGetFloatv(GL_VIEWPORT, viewport_size);
1535         immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
1536
1537         immUniformColor4f(1.0f, 0.39f, 0.39f, 0.78f);
1538         immUniform1i("colors_len", 0);  /* "simple" mode */
1539         immUniform1f("dash_width", 12.0f);
1540         immUniform1f("dash_factor", 0.5f);
1541
1542         imm_draw_circle_wire_2d(
1543                 shdr_pos, x, y, radius,
1544                 /* XXX Dashed shader gives bad results with sets of small segments currently,
1545                  *     temp hack around the issue. :( */
1546                 max_ii(8, radius / 2));  /* was fixed 40 */
1547
1548         immUnbindProgram();
1549
1550         glDisable(GL_BLEND);
1551         glDisable(GL_LINE_SMOOTH);
1552 }
1553
1554 static bool gp_brush_cursor_poll(bContext *C)
1555 {
1556    if (WM_toolsystem_active_tool_is_brush(C)) {
1557        return true;
1558    }
1559    return false;
1560 }
1561
1562 /* Helper callback for drawing the cursor itself */
1563 static void gp_brush_cursor_draw(bContext *C, int x, int y, void *customdata)
1564 {
1565         Main *bmain = CTX_data_main(C);
1566         Scene *scene = CTX_data_scene(C);
1567         Object *ob = CTX_data_active_object(C);
1568         ARegion *ar = CTX_wm_region(C);
1569
1570         GP_Sculpt_Settings *gset = &scene->toolsettings->gp_sculpt;
1571         bGPdata *gpd = ED_gpencil_data_get_active(C);
1572         GP_Sculpt_Data *gp_brush = NULL;
1573         Brush *brush = NULL;
1574         Material *ma = NULL;
1575         MaterialGPencilStyle *gp_style = NULL;
1576         float *last_mouse_position = customdata;
1577
1578         if ((gpd) && (gpd->flag & GP_DATA_STROKE_WEIGHTMODE)) {
1579                 gp_brush = &gset->brush[gset->weighttype];
1580         }
1581         else {
1582                 gp_brush = &gset->brush[gset->brushtype];
1583         }
1584
1585         /* default radius and color */
1586         float color[3] = {1.0f, 1.0f, 1.0f};
1587         float darkcolor[3];
1588         float radius = 3.0f;
1589
1590         int mval_i[2] = {x, y};
1591         /* check if cursor is in drawing region and has valid datablock */
1592         if ((!gp_check_cursor_region(C, mval_i)) || (gpd == NULL)) {
1593                 return;
1594         }
1595
1596         /* for paint use paint brush size and color */
1597         if (gpd->flag & GP_DATA_STROKE_PAINTMODE) {
1598                 brush = scene->toolsettings->gp_paint->paint.brush;
1599                 /* while drawing hide */
1600                 if ((gpd->runtime.sbuffer_size > 0) &&
1601                     (brush) && ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE) == 0) &&
1602                     ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) == 0))
1603                 {
1604                         return;
1605                 }
1606
1607                 if (brush) {
1608                         if ((brush->gpencil_settings->flag & GP_BRUSH_ENABLE_CURSOR) == 0) {
1609                                 return;
1610                         }
1611
1612                         /* eraser has special shape and use a different shader program */
1613                         if (brush->gpencil_tool == GPAINT_TOOL_ERASE) {
1614                                 ED_gpencil_brush_draw_eraser(brush, x, y);
1615                                 return;
1616                         }
1617
1618                         /* get current drawing color */
1619                         ma = BKE_gpencil_get_material_from_brush(brush);
1620                         if (ma == NULL) {
1621                                 BKE_gpencil_material_ensure(bmain, ob);
1622                                 /* assign the first material to the brush */
1623                                 ma = give_current_material(ob, 1);
1624                                 brush->gpencil_settings->material = ma;
1625                         }
1626                         gp_style = ma->gp_style;
1627
1628                         /* after some testing, display the size of the brush is not practical because
1629                          * is too disruptive and the size of cursor does not change with zoom factor.
1630                          * The decision was to use a fix size, instead of brush->thickness value.
1631                          */
1632                         if ((gp_style) && (GPENCIL_PAINT_MODE(gpd)) &&
1633                             ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE) == 0) &&
1634                             ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) == 0) &&
1635                             (brush->gpencil_tool == GPAINT_TOOL_DRAW))
1636                         {
1637                                 radius = 2.0f;
1638                                 copy_v3_v3(color, gp_style->stroke_rgba);
1639                         }
1640                         else {
1641                                 radius = 5.0f;
1642                                 copy_v3_v3(color, brush->add_col);
1643                         }
1644                 }
1645                 else {
1646                         return;
1647                 }
1648         }
1649
1650         /* for sculpt use sculpt brush size */
1651         if (GPENCIL_SCULPT_OR_WEIGHT_MODE(gpd)) {
1652                 if (gp_brush) {
1653                         if ((gp_brush->flag & GP_SCULPT_FLAG_ENABLE_CURSOR) == 0) {
1654                                 return;
1655                         }
1656
1657                         radius = gp_brush->size;
1658                         if (gp_brush->flag & (GP_SCULPT_FLAG_INVERT | GP_SCULPT_FLAG_TMP_INVERT)) {
1659                                 copy_v3_v3(color, gp_brush->curcolor_sub);
1660                         }
1661                         else {
1662                                 copy_v3_v3(color, gp_brush->curcolor_add);
1663                         }
1664                 }
1665         }
1666
1667         /* draw icon */
1668         GPUVertFormat *format = immVertexFormat();
1669         uint pos = GPU_vertformat_attr_add(format, "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
1670         immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
1671
1672         glEnable(GL_LINE_SMOOTH);
1673         glEnable(GL_BLEND);
1674
1675         /* Inner Ring: Color from UI panel */
1676         immUniformColor4f(color[0], color[1], color[2], 0.8f);
1677         if ((gp_style) && (GPENCIL_PAINT_MODE(gpd)) &&
1678             ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE) == 0) &&
1679             ((brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP) == 0) &&
1680             (brush->gpencil_tool == GPAINT_TOOL_DRAW))
1681         {
1682                 imm_draw_circle_fill_2d(pos, x, y, radius, 40);
1683         }
1684         else {
1685                 imm_draw_circle_wire_2d(pos, x, y, radius, 40);
1686         }
1687
1688         /* Outer Ring: Dark color for contrast on light backgrounds (e.g. gray on white) */
1689         mul_v3_v3fl(darkcolor, color, 0.40f);
1690         immUniformColor4f(darkcolor[0], darkcolor[1], darkcolor[2], 0.8f);
1691         imm_draw_circle_wire_2d(pos, x, y, radius + 1, 40);
1692
1693         glDisable(GL_BLEND);
1694         glDisable(GL_LINE_SMOOTH);
1695
1696         /* Draw line for lazy mouse */
1697         if ((last_mouse_position) &&
1698             (brush->gpencil_settings->flag & GP_BRUSH_STABILIZE_MOUSE_TEMP))
1699         {
1700                 glEnable(GL_LINE_SMOOTH);
1701                 glEnable(GL_BLEND);
1702
1703                 copy_v3_v3(color, brush->add_col);
1704                 immUniformColor4f(color[0], color[1], color[2], 0.8f);
1705
1706                 immBegin(GPU_PRIM_LINES, 2);
1707                 immVertex2f(pos, x, y);
1708                 immVertex2f(
1709                         pos,
1710                         last_mouse_position[0] + ar->winrct.xmin,
1711                         last_mouse_position[1] + ar->winrct.ymin);
1712                 immEnd();
1713
1714                 glDisable(GL_BLEND);
1715                 glDisable(GL_LINE_SMOOTH);
1716         }
1717
1718         immUnbindProgram();
1719 }
1720
1721 /* Turn brush cursor in on/off */
1722 void ED_gpencil_toggle_brush_cursor(bContext *C, bool enable, void *customdata)
1723 {
1724         Scene *scene = CTX_data_scene(C);
1725         GP_Sculpt_Settings *gset = &scene->toolsettings->gp_sculpt;
1726         float *lastpost = customdata;
1727
1728         if (gset->paintcursor && !enable) {
1729                 /* clear cursor */
1730                 WM_paint_cursor_end(CTX_wm_manager(C), gset->paintcursor);
1731                 gset->paintcursor = NULL;
1732         }
1733         else if (enable) {
1734                 /* in some situations cursor could be duplicated, so it is better disable first if exist */
1735                 if (gset->paintcursor) {
1736                         /* clear cursor */
1737                         WM_paint_cursor_end(CTX_wm_manager(C), gset->paintcursor);
1738                         gset->paintcursor = NULL;
1739                 }
1740                 /* enable cursor */
1741                 gset->paintcursor = WM_paint_cursor_activate(
1742                         CTX_wm_manager(C),
1743                         SPACE_TYPE_ANY, RGN_TYPE_ANY,
1744                         gp_brush_cursor_poll,
1745                         gp_brush_cursor_draw,
1746                         (lastpost) ? customdata : NULL);
1747         }
1748 }
1749
1750 /* verify if is using the right brush */
1751 static void gpencil_verify_brush_type(bContext *C, int newmode)
1752 {
1753         ToolSettings *ts = CTX_data_tool_settings(C);
1754         GP_Sculpt_Settings *gset = &ts->gp_sculpt;
1755
1756         switch (newmode) {
1757                 case OB_MODE_SCULPT_GPENCIL:
1758                         gset->flag &= ~GP_SCULPT_SETT_FLAG_WEIGHT_MODE;
1759                         if ((gset->brushtype < 0) || (gset->brushtype >= GP_SCULPT_TYPE_WEIGHT)) {
1760                                 gset->brushtype = GP_SCULPT_TYPE_PUSH;
1761                         }
1762                         break;
1763                 case OB_MODE_WEIGHT_GPENCIL:
1764                         gset->flag |= GP_SCULPT_SETT_FLAG_WEIGHT_MODE;
1765                         if ((gset->weighttype < GP_SCULPT_TYPE_WEIGHT) || (gset->weighttype >= GP_SCULPT_TYPE_MAX)) {
1766                                 gset->weighttype = GP_SCULPT_TYPE_WEIGHT;
1767                         }
1768                         break;
1769                 default:
1770                         break;
1771         }
1772 }
1773
1774 /* set object modes */
1775 void ED_gpencil_setup_modes(bContext *C, bGPdata *gpd, int newmode)
1776 {
1777         if (!gpd) {
1778                 return;
1779         }
1780
1781         switch (newmode) {
1782                 case OB_MODE_EDIT_GPENCIL:
1783                         gpd->flag |= GP_DATA_STROKE_EDITMODE;
1784                         gpd->flag &= ~GP_DATA_STROKE_PAINTMODE;
1785                         gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
1786                         gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
1787                         ED_gpencil_toggle_brush_cursor(C, false, NULL);
1788                         break;
1789                 case OB_MODE_PAINT_GPENCIL:
1790                         gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
1791                         gpd->flag |= GP_DATA_STROKE_PAINTMODE;
1792                         gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
1793                         gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
1794                         ED_gpencil_toggle_brush_cursor(C, true, NULL);
1795                         break;
1796                 case OB_MODE_SCULPT_GPENCIL:
1797                         gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
1798                         gpd->flag &= ~GP_DATA_STROKE_PAINTMODE;
1799                         gpd->flag |= GP_DATA_STROKE_SCULPTMODE;
1800                         gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
1801                         gpencil_verify_brush_type(C, OB_MODE_SCULPT_GPENCIL);
1802                         ED_gpencil_toggle_brush_cursor(C, true, NULL);
1803                         break;
1804                 case OB_MODE_WEIGHT_GPENCIL:
1805                         gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
1806                         gpd->flag &= ~GP_DATA_STROKE_PAINTMODE;
1807                         gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
1808                         gpd->flag |= GP_DATA_STROKE_WEIGHTMODE;
1809                         gpencil_verify_brush_type(C, OB_MODE_WEIGHT_GPENCIL);
1810                         ED_gpencil_toggle_brush_cursor(C, true, NULL);
1811                         break;
1812                 default:
1813                         gpd->flag &= ~GP_DATA_STROKE_EDITMODE;
1814                         gpd->flag &= ~GP_DATA_STROKE_PAINTMODE;
1815                         gpd->flag &= ~GP_DATA_STROKE_SCULPTMODE;
1816                         gpd->flag &= ~GP_DATA_STROKE_WEIGHTMODE;
1817                         ED_gpencil_toggle_brush_cursor(C, false, NULL);
1818                         break;
1819         }
1820 }
1821
1822 /* helper to convert 2d to 3d for simple drawing buffer */
1823 static void gpencil_stroke_convertcoords(ARegion *ar, const tGPspoint *point2D, float origin[3], float out[3])
1824 {
1825         float mval_f[2] = { (float)point2D->x, (float)point2D->y };
1826         float mval_prj[2];
1827         float rvec[3], dvec[3];
1828         float zfac;
1829
1830         copy_v3_v3(rvec, origin);
1831
1832         zfac = ED_view3d_calc_zfac(ar->regiondata, rvec, NULL);
1833
1834         if (ED_view3d_project_float_global(ar, rvec, mval_prj, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) {
1835                 sub_v2_v2v2(mval_f, mval_prj, mval_f);
1836                 ED_view3d_win_to_delta(ar, mval_f, dvec, zfac);
1837                 sub_v3_v3v3(out, rvec, dvec);
1838         }
1839         else {
1840                 zero_v3(out);
1841         }
1842 }
1843
1844 /* convert 2d tGPspoint to 3d bGPDspoint */
1845 void ED_gpencil_tpoint_to_point(ARegion *ar, float origin[3], const tGPspoint *tpt, bGPDspoint *pt)
1846 {
1847         float p3d[3];
1848         /* conversion to 3d format */
1849         gpencil_stroke_convertcoords(ar, tpt, origin, p3d);
1850         copy_v3_v3(&pt->x, p3d);
1851
1852         pt->pressure = tpt->pressure;
1853         pt->strength = tpt->strength;
1854         pt->uv_fac = tpt->uv_fac;
1855         pt->uv_rot = tpt->uv_rot;
1856 }
1857
1858 /* texture coordinate utilities */
1859 void ED_gpencil_calc_stroke_uv(Object *ob, bGPDstroke *gps)
1860 {
1861         if (gps == NULL) {
1862                 return;
1863         }
1864         MaterialGPencilStyle *gp_style = BKE_material_gpencil_settings_get(ob, gps->mat_nr + 1);
1865         float pixsize;
1866         if (gp_style) {
1867                 pixsize = gp_style->texture_pixsize / 1000000.0f;
1868         }
1869         else {
1870                 /* use this value by default */
1871                 pixsize = 0.0001f;
1872         }
1873         pixsize = MAX2(pixsize, 0.0000001f);
1874
1875         bGPDspoint *pt = NULL;
1876         bGPDspoint *ptb = NULL;
1877         int i;
1878         float totlen = 0.0f;
1879
1880         /* first read all points and calc distance */
1881         for (i = 0; i < gps->totpoints; i++) {
1882                 pt = &gps->points[i];
1883                 /* first point */
1884                 if (i == 0) {
1885                         pt->uv_fac = 0.0f;
1886                         continue;
1887                 }
1888
1889                 ptb = &gps->points[i - 1];
1890                 totlen += len_v3v3(&pt->x, &ptb->x) / pixsize;
1891                 pt->uv_fac = totlen;
1892         }
1893
1894         /* normalize the distance using a factor */
1895         float factor;
1896
1897         /* if image, use texture width */
1898         if ((gp_style) && (gp_style->stroke_style == GP_STYLE_STROKE_STYLE_TEXTURE) &&
1899             (gp_style->sima))
1900         {
1901                 factor = gp_style->sima->gen_x;
1902         }
1903         else if (totlen == 0) {
1904                 return;
1905         }
1906         else {
1907                 factor = totlen;
1908         }
1909
1910         for (i = 0; i < gps->totpoints; i++) {
1911                 pt = &gps->points[i];
1912                 pt->uv_fac /= factor;
1913         }
1914 }
1915
1916 /* recalc uv for any stroke using the material */
1917 void ED_gpencil_update_color_uv(Main *bmain, Material *mat)
1918 {
1919         Material *gps_ma = NULL;
1920         /* read all strokes  */
1921         for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
1922                 if (ob->type == OB_GPENCIL) {
1923                         bGPdata *gpd = ob->data;
1924                         if (gpd == NULL) {
1925                                 continue;
1926                         }
1927
1928                         for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
1929                                 /* only editable and visible layers are considered */
1930                                 if (gpencil_layer_is_editable(gpl)) {
1931                                         for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
1932                                                 for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
1933                                                         /* check if it is editable */
1934                                                         if (ED_gpencil_stroke_color_use(ob, gpl, gps) == false) {
1935                                                                 continue;
1936                                                         }
1937                                                         gps_ma = give_current_material(ob, gps->mat_nr + 1);
1938                                                         /* update */
1939                                                         if ((gps_ma) && (gps_ma == mat)) {
1940                                                                 ED_gpencil_calc_stroke_uv(ob, gps);
1941                                                         }
1942                                                 }
1943                                         }
1944                                 }
1945                         }
1946                 }
1947         }
1948 }
1949 /* ******************************************************** */