Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / space_view3d / view3d_gizmo_ruler.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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/space_view3d/view3d_gizmo_ruler.c
22  *  \ingroup spview3d
23  */
24
25 #include "BLI_listbase.h"
26 #include "BLI_string.h"
27 #include "BLI_rect.h"
28 #include "BLI_math.h"
29 #include "BLI_utildefines.h"
30
31 #include "BLT_translation.h"
32
33 #include "BKE_context.h"
34 #include "BKE_gpencil.h"
35 #include "BKE_main.h"
36
37 #include "BKE_object.h"
38 #include "BKE_unit.h"
39 #include "BKE_material.h"
40
41 #include "DNA_meshdata_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_gpencil_types.h"
44 #include "DNA_view3d_types.h"
45
46 #include "BIF_gl.h"
47
48 #include "ED_gpencil.h"
49 #include "ED_screen.h"
50 #include "ED_transform_snap_object_context.h"
51 #include "ED_view3d.h"
52
53 #include "UI_resources.h"
54 #include "UI_interface.h"
55
56 #include "MEM_guardedalloc.h"
57
58 #include "RNA_access.h"
59
60 #include "WM_api.h"
61 #include "WM_types.h"
62 #include "WM_toolsystem.h"
63
64 #include "view3d_intern.h"  /* own include */
65
66 #include "GPU_immediate.h"
67 #include "GPU_immediate_util.h"
68 #include "GPU_select.h"
69 #include "GPU_state.h"
70
71 #include "BLF_api.h"
72
73
74 static const char *view3d_gzgt_ruler_id = "VIEW3D_GGT_ruler";
75
76
77 #define MVAL_MAX_PX_DIST 12.0f
78
79 /* -------------------------------------------------------------------- */
80 /* Ruler Item (we can have many) */
81 enum {
82         RULERITEM_USE_ANGLE = (1 << 0),  /* use protractor */
83         RULERITEM_USE_RAYCAST = (1 << 1)
84 };
85
86 enum {
87         RULERITEM_DIRECTION_IN = 0,
88         RULERITEM_DIRECTION_OUT
89 };
90
91 /* keep smaller then selection, since we may want click elsewhere without selecting a ruler */
92 #define RULER_PICK_DIST 12.0f
93 #define RULER_PICK_DIST_SQ (RULER_PICK_DIST * RULER_PICK_DIST)
94
95 /* not clicking on a point */
96 #define PART_LINE 0xff
97
98 /* -------------------------------------------------------------------- */
99 /* Ruler Info (wmGizmoGroup customdata) */
100
101 enum {
102         RULER_STATE_NORMAL = 0,
103         RULER_STATE_DRAG
104 };
105
106 enum {
107         RULER_SNAP_OK = (1 << 0),
108 };
109
110 typedef struct RulerInfo {
111         // ListBase items;
112         int      item_active;
113         int flag;
114         int snap_flag;
115         int state;
116
117         struct SnapObjectContext *snap_context;
118
119         /* wm state */
120         wmWindow *win;
121         ScrArea *sa;
122         ARegion *ar;  /* re-assigned every modal update */
123 } RulerInfo;
124
125 /* -------------------------------------------------------------------- */
126 /* Ruler Item (two or three points) */
127
128 typedef struct RulerItem {
129         wmGizmo gz;
130
131         /* worldspace coords, middle being optional */
132         float co[3][3];
133
134         int   flag;
135         int   raycast_dir;  /* RULER_DIRECTION_* */
136 } RulerItem;
137
138 typedef struct RulerInteraction {
139         /* selected coord */
140         char  co_index; /* 0 -> 2 */
141         float drag_start_co[3];
142         uint inside_region : 1;
143 } RulerInteraction;
144
145 /* -------------------------------------------------------------------- */
146 /** \name Internal Ruler Utilities
147  * \{ */
148
149 static RulerItem *ruler_item_add(wmGizmoGroup *gzgroup)
150 {
151         /* could pass this as an arg */
152         const wmGizmoType *gzt_ruler = WM_gizmotype_find("VIEW3D_GT_ruler_item", true);
153         RulerItem *ruler_item = (RulerItem *)WM_gizmo_new_ptr(gzt_ruler, gzgroup, NULL);
154         WM_gizmo_set_flag(&ruler_item->gz, WM_GIZMO_DRAW_MODAL, true);
155         return ruler_item;
156 }
157
158 static void ruler_item_remove(bContext *C, wmGizmoGroup *gzgroup, RulerItem *ruler_item)
159 {
160         WM_gizmo_unlink(&gzgroup->gizmos, gzgroup->parent_gzmap, &ruler_item->gz, C);
161 }
162
163 static void ruler_item_as_string(RulerItem *ruler_item, UnitSettings *unit,
164                                  char *numstr, size_t numstr_size, int prec)
165 {
166         const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
167
168         if (ruler_item->flag & RULERITEM_USE_ANGLE) {
169                 const float ruler_angle = angle_v3v3v3(ruler_item->co[0],
170                                                        ruler_item->co[1],
171                                                        ruler_item->co[2]);
172
173                 if (unit->system == USER_UNIT_NONE) {
174                         BLI_snprintf(numstr, numstr_size, "%.*f°", prec, RAD2DEGF(ruler_angle));
175                 }
176                 else {
177                         bUnit_AsString(numstr, numstr_size,
178                                        (double)ruler_angle,
179                                        prec, unit->system, B_UNIT_ROTATION, do_split, false);
180                 }
181         }
182         else {
183                 const float ruler_len = len_v3v3(ruler_item->co[0],
184                                                  ruler_item->co[2]);
185
186                 if (unit->system == USER_UNIT_NONE) {
187                         BLI_snprintf(numstr, numstr_size, "%.*f", prec, ruler_len);
188                 }
189                 else {
190                         bUnit_AsString(numstr, numstr_size,
191                                        (double)(ruler_len * unit->scale_length),
192                                        prec, unit->system, B_UNIT_LENGTH, do_split, false);
193                 }
194         }
195 }
196
197 static bool view3d_ruler_pick(
198         wmGizmoGroup *gzgroup, RulerItem *ruler_item, const float mval[2],
199         int *r_co_index)
200 {
201         RulerInfo *ruler_info = gzgroup->customdata;
202         ARegion *ar = ruler_info->ar;
203         bool found = false;
204
205         float dist_best = RULER_PICK_DIST_SQ;
206         int co_index_best = -1;
207
208         {
209                 float co_ss[3][2];
210                 float dist;
211                 int j;
212
213                 /* should these be checked? - ok for now not to */
214                 for (j = 0; j < 3; j++) {
215                         ED_view3d_project_float_global(ar, ruler_item->co[j], co_ss[j], V3D_PROJ_TEST_NOP);
216                 }
217
218                 if (ruler_item->flag & RULERITEM_USE_ANGLE) {
219                         dist = min_ff(dist_squared_to_line_segment_v2(mval, co_ss[0], co_ss[1]),
220                                       dist_squared_to_line_segment_v2(mval, co_ss[1], co_ss[2]));
221                         if (dist < dist_best) {
222                                 dist_best = dist;
223                                 found = true;
224
225                                 {
226                                         const float dist_points[3] = {
227                                             len_squared_v2v2(co_ss[0], mval),
228                                             len_squared_v2v2(co_ss[1], mval),
229                                             len_squared_v2v2(co_ss[2], mval),
230                                         };
231                                         if (min_fff(UNPACK3(dist_points)) < RULER_PICK_DIST_SQ) {
232                                                 co_index_best = min_axis_v3(dist_points);
233                                         }
234                                         else {
235                                                 co_index_best = -1;
236                                         }
237                                 }
238                         }
239                 }
240                 else {
241                         dist = dist_squared_to_line_segment_v2(mval, co_ss[0], co_ss[2]);
242                         if (dist < dist_best) {
243                                 dist_best = dist;
244                                 found = true;
245
246                                 {
247                                         const float dist_points[2] = {
248                                             len_squared_v2v2(co_ss[0], mval),
249                                             len_squared_v2v2(co_ss[2], mval),
250                                         };
251                                         if (min_ff(UNPACK2(dist_points)) < RULER_PICK_DIST_SQ) {
252                                                 co_index_best = (dist_points[0] < dist_points[1]) ? 0 : 2;
253                                         }
254                                         else {
255                                                 co_index_best = -1;
256                                         }
257                                 }
258                         }
259                 }
260         }
261
262         *r_co_index = co_index_best;
263         return found;
264 }
265
266 /**
267  * Ensure the 'snap_context' is only cached while dragging,
268  * needed since the user may toggle modes between tool use.
269  */
270 static void ruler_state_set(bContext *C, RulerInfo *ruler_info, int state)
271 {
272         Main *bmain = CTX_data_main(C);
273         if (state == ruler_info->state) {
274                 return;
275         }
276
277         /* always remove */
278         if (ruler_info->snap_context) {
279                 ED_transform_snap_object_context_destroy(ruler_info->snap_context);
280                 ruler_info->snap_context = NULL;
281         }
282
283         if (state == RULER_STATE_NORMAL) {
284                 /* pass */
285         }
286         else if (state == RULER_STATE_DRAG) {
287                 ruler_info->snap_context = ED_transform_snap_object_context_create_view3d(
288                         bmain, CTX_data_scene(C), CTX_data_depsgraph(C), 0,
289                         ruler_info->ar, CTX_wm_view3d(C));
290         }
291         else {
292                 BLI_assert(0);
293         }
294
295         ruler_info->state = state;
296 }
297
298 static void view3d_ruler_item_project(
299         RulerInfo *ruler_info, float r_co[3],
300         const int xy[2])
301 {
302         ED_view3d_win_to_3d_int(ruler_info->sa->spacedata.first, ruler_info->ar, r_co, xy, r_co);
303 }
304
305 /* use for mousemove events */
306 static bool view3d_ruler_item_mousemove(
307         RulerInfo *ruler_info, RulerItem *ruler_item, const int mval[2],
308         const bool do_thickness, const bool do_snap)
309 {
310         RulerInteraction *inter = ruler_item->gz.interaction_data;
311         const float eps_bias = 0.0002f;
312         float dist_px = MVAL_MAX_PX_DIST * U.pixelsize;  /* snap dist */
313
314         ruler_info->snap_flag &= ~RULER_SNAP_OK;
315
316         if (ruler_item) {
317                 float *co = ruler_item->co[inter->co_index];
318                 /* restore the initial depth */
319                 copy_v3_v3(co, inter->drag_start_co);
320                 view3d_ruler_item_project(ruler_info, co, mval);
321                 if (do_thickness && inter->co_index != 1) {
322                         // Scene *scene = CTX_data_scene(C);
323                         // View3D *v3d = ruler_info->sa->spacedata.first;
324                         const float mval_fl[2] = {UNPACK2(mval)};
325                         float ray_normal[3];
326                         float ray_start[3];
327                         float *co_other;
328
329                         co_other = ruler_item->co[inter->co_index == 0 ? 2 : 0];
330
331                         if (ED_transform_snap_object_project_view3d(
332                                 ruler_info->snap_context,
333                                 SCE_SNAP_MODE_FACE,
334                                 &(const struct SnapObjectParams){
335                                     .snap_select = SNAP_ALL,
336                                     .use_object_edit_cage = true,
337                                 },
338                                 mval_fl, &dist_px,
339                                 co, ray_normal))
340                         {
341                                 negate_v3(ray_normal);
342                                 /* add some bias */
343                                 madd_v3_v3v3fl(ray_start, co, ray_normal, eps_bias);
344                                 ED_transform_snap_object_project_ray(
345                                         ruler_info->snap_context,
346                                         &(const struct SnapObjectParams){
347                                             .snap_select = SNAP_ALL,
348                                             .use_object_edit_cage = true,
349                                         },
350                                         ray_start, ray_normal, NULL,
351                                         co_other, NULL);
352                         }
353                 }
354                 else if (do_snap) {
355                         const float mval_fl[2] = {UNPACK2(mval)};
356
357                         if (ED_transform_snap_object_project_view3d(
358                                 ruler_info->snap_context,
359                                 (SCE_SNAP_MODE_VERTEX | SCE_SNAP_MODE_EDGE | SCE_SNAP_MODE_FACE),
360                                 &(const struct SnapObjectParams){
361                                     .snap_select = SNAP_ALL,
362                                     .use_object_edit_cage = true,
363                                     .use_occlusion_test = true,
364                                 },
365                                 mval_fl, &dist_px,
366                                 co, NULL))
367                         {
368                                 ruler_info->snap_flag |= RULER_SNAP_OK;
369                         }
370                 }
371                 return true;
372         }
373         else {
374                 return false;
375         }
376 }
377
378
379 /** \} */
380
381 /* -------------------------------------------------------------------- */
382 /** \name Ruler/Grease Pencil Conversion
383  * \{ */
384
385 #define RULER_ID "RulerData3D"
386 static bool view3d_ruler_to_gpencil(bContext *C, wmGizmoGroup *gzgroup)
387 {
388         // RulerInfo *ruler_info = gzgroup->customdata;
389         Main *bmain = CTX_data_main(C);
390         Scene *scene = CTX_data_scene(C);
391
392         bGPdata *gpd;
393         bGPDlayer *gpl;
394         bGPDframe *gpf;
395         bGPDstroke *gps;
396         RulerItem *ruler_item;
397         const char *ruler_name = RULER_ID;
398         bool changed = false;
399
400         if (scene->gpd == NULL) {
401                 scene->gpd = BKE_gpencil_data_addnew(bmain, "Annotations");
402         }
403         gpd = scene->gpd;
404
405         gpl = BLI_findstring(&gpd->layers, ruler_name, offsetof(bGPDlayer, info));
406         if (gpl == NULL) {
407                 gpl = BKE_gpencil_layer_addnew(gpd, ruler_name, false);
408                 copy_v4_v4(gpl->color, U.gpencil_new_layer_col);
409                 gpl->thickness = 1;
410                 gpl->flag |= GP_LAYER_HIDE;
411         }
412
413         gpf = BKE_gpencil_layer_getframe(gpl, CFRA, GP_GETFRAME_ADD_NEW);
414         BKE_gpencil_free_strokes(gpf);
415
416         for (ruler_item = gzgroup->gizmos.first; ruler_item; ruler_item = (RulerItem *)ruler_item->gz.next) {
417                 bGPDspoint *pt;
418                 int j;
419
420                 /* allocate memory for a new stroke */
421                 gps = MEM_callocN(sizeof(bGPDstroke), "gp_stroke");
422                 if (ruler_item->flag & RULERITEM_USE_ANGLE) {
423                         gps->totpoints = 3;
424                         pt = gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
425                         for (j = 0; j < 3; j++) {
426                                 copy_v3_v3(&pt->x, ruler_item->co[j]);
427                                 pt->pressure = 1.0f;
428                                 pt->strength = 1.0f;
429                                 pt++;
430                         }
431                 }
432                 else {
433                         gps->totpoints = 2;
434                         pt = gps->points = MEM_callocN(sizeof(bGPDspoint) * gps->totpoints, "gp_stroke_points");
435                         for (j = 0; j < 3; j += 2) {
436                                 copy_v3_v3(&pt->x, ruler_item->co[j]);
437                                 pt->pressure = 1.0f;
438                                 pt->strength = 1.0f;
439                                 pt++;
440                         }
441                 }
442                 gps->flag = GP_STROKE_3DSPACE;
443                 gps->thickness = 3;
444
445                 BLI_addtail(&gpf->strokes, gps);
446                 changed = true;
447         }
448
449         return changed;
450 }
451
452 static bool view3d_ruler_from_gpencil(const bContext *C, wmGizmoGroup *gzgroup)
453 {
454         Scene *scene = CTX_data_scene(C);
455         bool changed = false;
456
457         if (scene->gpd) {
458                 bGPDlayer *gpl;
459                 const char *ruler_name = RULER_ID;
460                 gpl = BLI_findstring(&scene->gpd->layers, ruler_name, offsetof(bGPDlayer, info));
461                 if (gpl) {
462                         bGPDframe *gpf;
463                         gpf = BKE_gpencil_layer_getframe(gpl, CFRA, GP_GETFRAME_USE_PREV);
464                         if (gpf) {
465                                 bGPDstroke *gps;
466                                 for (gps = gpf->strokes.first; gps; gps = gps->next) {
467                                         bGPDspoint *pt = gps->points;
468                                         int j;
469                                         RulerItem *ruler_item = NULL;
470                                         if (gps->totpoints == 3) {
471                                                 ruler_item = ruler_item_add(gzgroup);
472                                                 for (j = 0; j < 3; j++) {
473                                                         copy_v3_v3(ruler_item->co[j], &pt->x);
474                                                         pt++;
475                                                 }
476                                                 ruler_item->flag |= RULERITEM_USE_ANGLE;
477                                                 changed = true;
478                                         }
479                                         else if (gps->totpoints == 2) {
480                                                 ruler_item = ruler_item_add(gzgroup);
481                                                 for (j = 0; j < 3; j += 2) {
482                                                         copy_v3_v3(ruler_item->co[j], &pt->x);
483                                                         pt++;
484                                                 }
485                                                 changed = true;
486                                         }
487                                 }
488                         }
489                 }
490         }
491
492         return changed;
493 }
494
495 /** \} */
496
497 /* -------------------------------------------------------------------- */
498 /** \name Ruler Item Gizmo Type
499  * \{ */
500
501 static void gizmo_ruler_draw(const bContext *C, wmGizmo *gz)
502 {
503         Scene *scene = CTX_data_scene(C);
504         UnitSettings *unit = &scene->unit;
505         RulerInfo *ruler_info = gz->parent_gzgroup->customdata;
506         RulerItem *ruler_item = (RulerItem *)gz;
507         ARegion *ar = ruler_info->ar;
508         RegionView3D *rv3d = ar->regiondata;
509         const float cap_size = 4.0f;
510         const float bg_margin = 4.0f * U.pixelsize;
511         const float bg_radius = 4.0f * U.pixelsize;
512         const float arc_size = 64.0f * U.pixelsize;
513 #define ARC_STEPS 24
514         const int arc_steps = ARC_STEPS;
515         const float color_act[4] = {1.0f, 1.0f, 1.0f, 1.0f};
516         const float color_base[4] = {0.0f, 0.0f, 0.0f, 1.0f};
517         unsigned char color_text[3];
518         unsigned char color_wire[3];
519         float color_back[4] = {1.0f, 1.0f, 1.0f, 0.5f};
520
521         /* anti-aliased lines for more consistent appearance */
522         GPU_line_smooth(true);
523
524         BLF_enable(blf_mono_font, BLF_ROTATION);
525         BLF_size(blf_mono_font, 14 * U.pixelsize, U.dpi);
526         BLF_rotation(blf_mono_font, 0.0f);
527
528         UI_GetThemeColor3ubv(TH_TEXT, color_text);
529         UI_GetThemeColor3ubv(TH_WIRE, color_wire);
530
531         const bool is_act = (gz->flag & WM_GIZMO_DRAW_HOVER);
532         float dir_ruler[2];
533         float co_ss[3][2];
534         int j;
535
536         /* should these be checked? - ok for now not to */
537         for (j = 0; j < 3; j++) {
538                 ED_view3d_project_float_global(ar, ruler_item->co[j], co_ss[j], V3D_PROJ_TEST_NOP);
539         }
540
541         GPU_blend(true);
542
543         const uint shdr_pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
544
545         if (ruler_item->flag & RULERITEM_USE_ANGLE) {
546                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
547
548                 float viewport_size[4];
549                 GPU_viewport_size_get_f(viewport_size);
550                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
551
552                 immUniform1i("colors_len", 2);  /* "advanced" mode */
553                 const float *col = is_act ? color_act : color_base;
554                 immUniformArray4fv("colors", (float *)(float[][4]){{0.67f, 0.67f, 0.67f, 1.0f}, {col[0], col[1], col[2], col[3]}}, 2);
555                 immUniform1f("dash_width", 6.0f);
556
557                 immBegin(GPU_PRIM_LINE_STRIP, 3);
558
559                 immVertex2fv(shdr_pos, co_ss[0]);
560                 immVertex2fv(shdr_pos, co_ss[1]);
561                 immVertex2fv(shdr_pos, co_ss[2]);
562
563                 immEnd();
564
565                 immUnbindProgram();
566
567                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
568
569                 /* arc */
570                 {
571                         float dir_tmp[3];
572                         float co_tmp[3];
573                         float arc_ss_coord[2];
574
575                         float dir_a[3];
576                         float dir_b[3];
577                         float quat[4];
578                         float axis[3];
579                         float angle;
580                         const float px_scale = (ED_view3d_pixel_size_no_ui_scale(rv3d, ruler_item->co[1]) *
581                                                 min_fff(arc_size,
582                                                         len_v2v2(co_ss[0], co_ss[1]) / 2.0f,
583                                                         len_v2v2(co_ss[2], co_ss[1]) / 2.0f));
584
585                         sub_v3_v3v3(dir_a, ruler_item->co[0], ruler_item->co[1]);
586                         sub_v3_v3v3(dir_b, ruler_item->co[2], ruler_item->co[1]);
587                         normalize_v3(dir_a);
588                         normalize_v3(dir_b);
589
590                         cross_v3_v3v3(axis, dir_a, dir_b);
591                         angle = angle_normalized_v3v3(dir_a, dir_b);
592
593                         axis_angle_to_quat(quat, axis, angle / arc_steps);
594
595                         copy_v3_v3(dir_tmp, dir_a);
596
597                         immUniformColor3ubv(color_wire);
598
599                         immBegin(GPU_PRIM_LINE_STRIP, arc_steps + 1);
600
601                         for (j = 0; j <= arc_steps; j++) {
602                                 madd_v3_v3v3fl(co_tmp, ruler_item->co[1], dir_tmp, px_scale);
603                                 ED_view3d_project_float_global(ar, co_tmp, arc_ss_coord, V3D_PROJ_TEST_NOP);
604                                 mul_qt_v3(quat, dir_tmp);
605
606                                 immVertex2fv(shdr_pos, arc_ss_coord);
607                         }
608
609                         immEnd();
610                 }
611
612                 /* capping */
613                 {
614                         float rot_90_vec_a[2];
615                         float rot_90_vec_b[2];
616                         float cap[2];
617
618                         sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[1]);
619                         rot_90_vec_a[0] = -dir_ruler[1];
620                         rot_90_vec_a[1] =  dir_ruler[0];
621                         normalize_v2(rot_90_vec_a);
622
623                         sub_v2_v2v2(dir_ruler, co_ss[1], co_ss[2]);
624                         rot_90_vec_b[0] = -dir_ruler[1];
625                         rot_90_vec_b[1] =  dir_ruler[0];
626                         normalize_v2(rot_90_vec_b);
627
628                         GPU_blend(true);
629
630                         immUniformColor3ubv(color_wire);
631
632                         immBegin(GPU_PRIM_LINES, 8);
633
634                         madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, cap_size);
635                         immVertex2fv(shdr_pos, cap);
636                         madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, -cap_size);
637                         immVertex2fv(shdr_pos, cap);
638
639                         madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, cap_size);
640                         immVertex2fv(shdr_pos, cap);
641                         madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, -cap_size);
642                         immVertex2fv(shdr_pos, cap);
643
644                         /* angle vertex */
645                         immVertex2f(shdr_pos, co_ss[1][0] - cap_size, co_ss[1][1] - cap_size);
646                         immVertex2f(shdr_pos, co_ss[1][0] + cap_size, co_ss[1][1] + cap_size);
647                         immVertex2f(shdr_pos, co_ss[1][0] - cap_size, co_ss[1][1] + cap_size);
648                         immVertex2f(shdr_pos, co_ss[1][0] + cap_size, co_ss[1][1] - cap_size);
649
650                         immEnd();
651
652                         GPU_blend(false);
653                 }
654
655                 immUnbindProgram();
656
657                 /* text */
658                 {
659                         char numstr[256];
660                         float numstr_size[2];
661                         float posit[2];
662                         const int prec = 2;  /* XXX, todo, make optional */
663
664                         ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);
665
666                         BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);
667
668                         posit[0] = co_ss[1][0] + (cap_size * 2.0f);
669                         posit[1] = co_ss[1][1] - (numstr_size[1] / 2.0f);
670
671                         /* draw text (bg) */
672                         UI_draw_roundbox_corner_set(UI_CNR_ALL);
673                         UI_draw_roundbox_aa(
674                                 true,
675                                 posit[0] - bg_margin,                  posit[1] - bg_margin,
676                                 posit[0] + bg_margin + numstr_size[0], posit[1] + bg_margin + numstr_size[1],
677                                 bg_radius, color_back);
678                         /* draw text */
679                         BLF_color3ubv(blf_mono_font, color_text);
680                         BLF_position(blf_mono_font, posit[0], posit[1], 0.0f);
681                         BLF_rotation(blf_mono_font, 0.0f);
682                         BLF_draw(blf_mono_font, numstr, sizeof(numstr));
683                 }
684         }
685         else {
686                 immBindBuiltinProgram(GPU_SHADER_2D_LINE_DASHED_UNIFORM_COLOR);
687
688                 float viewport_size[4];
689                 GPU_viewport_size_get_f(viewport_size);
690                 immUniform2f("viewport_size", viewport_size[2], viewport_size[3]);
691
692                 immUniform1i("colors_len", 2);  /* "advanced" mode */
693                 const float *col = is_act ? color_act : color_base;
694                 immUniformArray4fv("colors", (float *)(float[][4]){{0.67f, 0.67f, 0.67f, 1.0f}, {col[0], col[1], col[2], col[3]}}, 2);
695                 immUniform1f("dash_width", 6.0f);
696
697                 immBegin(GPU_PRIM_LINES, 2);
698
699                 immVertex2fv(shdr_pos, co_ss[0]);
700                 immVertex2fv(shdr_pos, co_ss[2]);
701
702                 immEnd();
703
704                 immUnbindProgram();
705
706                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
707
708                 sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[2]);
709
710                 /* capping */
711                 {
712                         float rot_90_vec[2] = {-dir_ruler[1], dir_ruler[0]};
713                         float cap[2];
714
715                         normalize_v2(rot_90_vec);
716
717                         GPU_blend(true);
718
719                         immUniformColor3ubv(color_wire);
720
721                         immBegin(GPU_PRIM_LINES, 4);
722
723                         madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, cap_size);
724                         immVertex2fv(shdr_pos, cap);
725                         madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, -cap_size);
726                         immVertex2fv(shdr_pos, cap);
727
728                         madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, cap_size);
729                         immVertex2fv(shdr_pos, cap);
730                         madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, -cap_size);
731                         immVertex2fv(shdr_pos, cap);
732
733                         immEnd();
734
735                         GPU_blend(false);
736                 }
737
738                 immUnbindProgram();
739
740                 /* text */
741                 {
742                         char numstr[256];
743                         float numstr_size[2];
744                         const int prec = 6;  /* XXX, todo, make optional */
745                         float posit[2];
746
747                         ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);
748
749                         BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);
750
751                         mid_v2_v2v2(posit, co_ss[0], co_ss[2]);
752
753                         /* center text */
754                         posit[0] -= numstr_size[0] / 2.0f;
755                         posit[1] -= numstr_size[1] / 2.0f;
756
757                         /* draw text (bg) */
758                         UI_draw_roundbox_corner_set(UI_CNR_ALL);
759                         UI_draw_roundbox_aa(
760                                 true,
761                                 posit[0] - bg_margin,                  posit[1] - bg_margin,
762                                 posit[0] + bg_margin + numstr_size[0], posit[1] + bg_margin + numstr_size[1],
763                                 bg_radius, color_back);
764                         /* draw text */
765                         BLF_color3ubv(blf_mono_font, color_text);
766                         BLF_position(blf_mono_font, posit[0], posit[1], 0.0f);
767                         BLF_draw(blf_mono_font, numstr, sizeof(numstr));
768                 }
769         }
770
771         GPU_line_smooth(false);
772
773         BLF_disable(blf_mono_font, BLF_ROTATION);
774
775 #undef ARC_STEPS
776
777         /* draw snap */
778         if ((ruler_info->snap_flag & RULER_SNAP_OK) &&
779             (ruler_info->state == RULER_STATE_DRAG) &&
780             (ruler_item->gz.interaction_data != NULL))
781         {
782                 RulerInteraction *inter = ruler_item->gz.interaction_data;
783                 /* size from drawSnapping */
784                 const float size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
785                 float co_ss_snap[3];
786                 ED_view3d_project_float_global(ar, ruler_item->co[inter->co_index], co_ss_snap, V3D_PROJ_TEST_NOP);
787
788                 uint pos = GPU_vertformat_attr_add(immVertexFormat(), "pos", GPU_COMP_F32, 2, GPU_FETCH_FLOAT);
789
790                 immBindBuiltinProgram(GPU_SHADER_2D_UNIFORM_COLOR);
791                 immUniformColor4fv(color_act);
792
793                 imm_draw_circle_wire_2d(pos, co_ss_snap[0], co_ss_snap[1], size * U.pixelsize, 32);
794
795                 immUnbindProgram();
796         }
797 }
798
799 static int gizmo_ruler_test_select(
800         bContext *UNUSED(C), wmGizmo *gz, const int mval[2])
801 {
802         RulerItem *ruler_item_pick = (RulerItem *)gz;
803         float mval_fl[2] = {UNPACK2(mval)};
804         int co_index;
805
806         /* select and drag */
807         if (view3d_ruler_pick(gz->parent_gzgroup, ruler_item_pick, mval_fl, &co_index)) {
808                 if (co_index == -1) {
809                         if ((ruler_item_pick->flag & RULERITEM_USE_ANGLE) == 0) {
810                                 return PART_LINE;
811                         }
812                 }
813                 else {
814                         return co_index;
815                 }
816         }
817         return -1;
818 }
819
820 static int gizmo_ruler_modal(
821         bContext *C, wmGizmo *gz, const wmEvent *event,
822         eWM_GizmoFlagTweak UNUSED(tweak_flag))
823 {
824         bool do_draw = false;
825         int exit_code = OPERATOR_RUNNING_MODAL;
826         RulerInfo *ruler_info = gz->parent_gzgroup->customdata;
827         RulerItem *ruler_item = (RulerItem *)gz;
828         RulerInteraction *inter = ruler_item->gz.interaction_data;
829         ARegion *ar = CTX_wm_region(C);
830
831         ruler_info->ar = ar;
832
833         switch (event->type) {
834                 case MOUSEMOVE:
835                 {
836                         if (ruler_info->state == RULER_STATE_DRAG) {
837                                 if (view3d_ruler_item_mousemove(
838                                         ruler_info, ruler_item, event->mval,
839                                         event->shift != 0, event->ctrl != 0))
840                                 {
841                                         do_draw = true;
842                                 }
843                                 inter->inside_region = BLI_rcti_isect_pt_v(&ar->winrct, &event->x);
844                         }
845                         break;
846                 }
847         }
848         if (do_draw) {
849                 ED_region_tag_redraw(ar);
850         }
851         return exit_code;
852 }
853
854 static int gizmo_ruler_invoke(
855         bContext *C, wmGizmo *gz, const wmEvent *event)
856 {
857         wmGizmoGroup *gzgroup = gz->parent_gzgroup;
858         RulerInfo *ruler_info = gzgroup->customdata;
859         RulerItem *ruler_item_pick = (RulerItem *)gz;
860         RulerInteraction *inter = MEM_callocN(sizeof(RulerInteraction), __func__);
861         gz->interaction_data = inter;
862
863         ARegion *ar = ruler_info->ar;
864
865         const float mval_fl[2] = {UNPACK2(event->mval)};
866
867         /* select and drag */
868         if (gz->highlight_part == PART_LINE) {
869                 if ((ruler_item_pick->flag & RULERITEM_USE_ANGLE) == 0) {
870                         /* Add Center Point */
871                         ruler_item_pick->flag |= RULERITEM_USE_ANGLE;
872                         inter->co_index = 1;
873                         ruler_state_set(C, ruler_info, RULER_STATE_DRAG);
874
875                         /* find the factor */
876                         {
877                                 float co_ss[2][2];
878                                 float fac;
879
880                                 ED_view3d_project_float_global(ar, ruler_item_pick->co[0], co_ss[0], V3D_PROJ_TEST_NOP);
881                                 ED_view3d_project_float_global(ar, ruler_item_pick->co[2], co_ss[1], V3D_PROJ_TEST_NOP);
882
883                                 fac = line_point_factor_v2(mval_fl, co_ss[0], co_ss[1]);
884                                 CLAMP(fac, 0.0f, 1.0f);
885
886                                 interp_v3_v3v3(ruler_item_pick->co[1],
887                                                ruler_item_pick->co[0],
888                                                ruler_item_pick->co[2], fac);
889                         }
890
891                         /* update the new location */
892                         view3d_ruler_item_mousemove(
893                                 ruler_info, ruler_item_pick, event->mval,
894                                 event->shift != 0, event->ctrl != 0);
895                 }
896         }
897         else {
898                 inter->co_index = gz->highlight_part;
899                 ruler_state_set(C, ruler_info, RULER_STATE_DRAG);
900
901                 /* store the initial depth */
902                 copy_v3_v3(inter->drag_start_co, ruler_item_pick->co[inter->co_index]);
903         }
904
905         return OPERATOR_RUNNING_MODAL;
906 }
907
908 static void gizmo_ruler_exit(bContext *C, wmGizmo *gz, const bool cancel)
909 {
910         wmGizmoGroup *gzgroup = gz->parent_gzgroup;
911         RulerInfo *ruler_info = gzgroup->customdata;
912
913         if (!cancel) {
914                 if (ruler_info->state == RULER_STATE_DRAG) {
915                         RulerItem *ruler_item = (RulerItem *)gz;
916                         RulerInteraction *inter = gz->interaction_data;
917                         /* rubber-band angle removal */
918                         if (!inter->inside_region) {
919                                 if ((inter->co_index == 1) && (ruler_item->flag & RULERITEM_USE_ANGLE)) {
920                                         ruler_item->flag &= ~RULERITEM_USE_ANGLE;
921                                 }
922                                 else {
923                                         /* Not ideal, since the ruler isn't a mode and we don't want to override delete key
924                                          * use dragging out of the view for removal. */
925                                         ruler_item_remove(C, gzgroup, ruler_item);
926                                         ruler_item = NULL;
927                                         gz = NULL;
928                                         inter = NULL;
929                                 }
930                         }
931                         if (ruler_info->snap_flag & RULER_SNAP_OK) {
932                                 ruler_info->snap_flag &= ~RULER_SNAP_OK;
933                         }
934                         ruler_state_set(C, ruler_info, RULER_STATE_NORMAL);
935                 }
936                 /* We could convert only the current gizmo, for now just re-generate. */
937                 view3d_ruler_to_gpencil(C, gzgroup);
938         }
939
940         if (gz) {
941                 MEM_SAFE_FREE(gz->interaction_data);
942         }
943
944         ruler_state_set(C, ruler_info, RULER_STATE_NORMAL);
945 }
946
947 static int gizmo_ruler_cursor_get(wmGizmo *gz)
948 {
949         if (gz->highlight_part == PART_LINE) {
950                 return BC_CROSSCURSOR;
951         }
952         return BC_NSEW_SCROLLCURSOR;
953 }
954
955 void VIEW3D_GT_ruler_item(wmGizmoType *gzt)
956 {
957         /* identifiers */
958         gzt->idname = "VIEW3D_GT_ruler_item";
959
960         /* api callbacks */
961         gzt->draw = gizmo_ruler_draw;
962         gzt->test_select = gizmo_ruler_test_select;
963         gzt->modal = gizmo_ruler_modal;
964         gzt->invoke = gizmo_ruler_invoke;
965         gzt->exit = gizmo_ruler_exit;
966         gzt->cursor_get = gizmo_ruler_cursor_get;
967
968         gzt->struct_size = sizeof(RulerItem);
969 }
970
971 /** \} */
972
973 /* -------------------------------------------------------------------- */
974 /** \name Ruler Gizmo Group
975  * \{ */
976
977 static bool WIDGETGROUP_ruler_poll(const bContext *C, wmGizmoGroupType *gzgt)
978 {
979         bToolRef_Runtime *tref_rt = WM_toolsystem_runtime_from_context((bContext *)C);
980         if ((tref_rt == NULL) ||
981             !STREQ(gzgt->idname, tref_rt->gizmo_group))
982         {
983                 WM_gizmo_group_type_unlink_delayed_ptr(gzgt);
984                 return false;
985         }
986         return true;
987 }
988
989 static void WIDGETGROUP_ruler_setup(const bContext *C, wmGizmoGroup *gzgroup)
990 {
991         RulerInfo *ruler_info = MEM_callocN(sizeof(RulerInfo), __func__);
992
993         if (view3d_ruler_from_gpencil(C, gzgroup)) {
994                 /* nop */
995         }
996
997         wmWindow *win = CTX_wm_window(C);
998         ScrArea *sa = CTX_wm_area(C);
999         ARegion *ar = CTX_wm_region(C);
1000         ruler_info->win = win;
1001         ruler_info->sa = sa;
1002         ruler_info->ar = ar;
1003
1004         gzgroup->customdata = ruler_info;
1005 }
1006
1007 void VIEW3D_GGT_ruler(wmGizmoGroupType *gzgt)
1008 {
1009         gzgt->name = "Ruler Widgets";
1010         gzgt->idname = view3d_gzgt_ruler_id;
1011
1012         gzgt->flag |= WM_GIZMOGROUPTYPE_SCALE | WM_GIZMOGROUPTYPE_DRAW_MODAL_ALL;
1013
1014         gzgt->gzmap_params.spaceid = SPACE_VIEW3D;
1015         gzgt->gzmap_params.regionid = RGN_TYPE_WINDOW;
1016
1017         gzgt->poll = WIDGETGROUP_ruler_poll;
1018         gzgt->setup = WIDGETGROUP_ruler_setup;
1019 }
1020
1021 /** \} */
1022
1023 /* -------------------------------------------------------------------- */
1024 /** \name Add Ruler Operator
1025  * \{ */
1026
1027 static bool view3d_ruler_poll(bContext *C)
1028 {
1029         bToolRef_Runtime *tref_rt = WM_toolsystem_runtime_from_context((bContext *)C);
1030         if ((tref_rt == NULL) ||
1031             !STREQ(view3d_gzgt_ruler_id, tref_rt->gizmo_group) ||
1032             CTX_wm_region_view3d(C) == NULL)
1033         {
1034                 return false;
1035         }
1036         return true;
1037 }
1038
1039 static int view3d_ruler_add_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
1040 {
1041         ARegion *ar = CTX_wm_region(C);
1042         View3D *v3d = CTX_wm_view3d(C);
1043         RegionView3D *rv3d = ar->regiondata;
1044
1045         wmGizmoMap *gzmap = ar->gizmo_map;
1046         wmGizmoGroup *gzgroup = WM_gizmomap_group_find(gzmap, view3d_gzgt_ruler_id);
1047         const bool use_depth = (v3d->shading.type >= OB_SOLID);
1048
1049         /* Create new line */
1050         RulerItem *ruler_item;
1051         ruler_item = ruler_item_add(gzgroup);
1052
1053         /* This is a little weak, but there is no real good way to tweak directly. */
1054         WM_gizmo_highlight_set(gzmap, &ruler_item->gz);
1055         if (WM_operator_name_call(
1056                 C, "GIZMOGROUP_OT_gizmo_tweak",
1057                 WM_OP_INVOKE_REGION_WIN, NULL) == OPERATOR_RUNNING_MODAL)
1058         {
1059                 RulerInfo *ruler_info = gzgroup->customdata;
1060                 RulerInteraction *inter = ruler_item->gz.interaction_data;
1061                 if (use_depth) {
1062                         /* snap the first point added, not essential but handy */
1063                         inter->co_index = 0;
1064                         view3d_ruler_item_mousemove(ruler_info, ruler_item, event->mval, false, true);
1065                         copy_v3_v3(inter->drag_start_co, ruler_item->co[inter->co_index]);
1066                 }
1067                 else {
1068                         negate_v3_v3(inter->drag_start_co, rv3d->ofs);
1069                         copy_v3_v3(ruler_item->co[0], inter->drag_start_co);
1070                         view3d_ruler_item_project(ruler_info, ruler_item->co[0], event->mval);
1071                 }
1072
1073                 copy_v3_v3(ruler_item->co[2], ruler_item->co[0]);
1074                 ruler_item->gz.highlight_part = inter->co_index = 2;
1075         }
1076         return OPERATOR_FINISHED;
1077 }
1078
1079 void VIEW3D_OT_ruler_add(wmOperatorType *ot)
1080 {
1081         /* identifiers */
1082         ot->name = "Ruler Add";
1083         ot->idname = "VIEW3D_OT_ruler_add";
1084         ot->description = "";
1085
1086         ot->invoke = view3d_ruler_add_invoke;
1087         ot->poll = view3d_ruler_poll;
1088
1089         /* flags */
1090         ot->flag = OPTYPE_UNDO | OPTYPE_INTERNAL;
1091 }
1092
1093 /** \} */