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