cgv
Loading...
Searching...
No Matches
transformation_gizmo.cxx
1#include "transformation_gizmo.h"
2
3#include <cgv/math/intersection.h>
4
5using namespace cgv::render;
6
7namespace cgv {
8namespace app {
9
10transformation_gizmo::transformation_gizmo() {
11 _boxes.style.illumination_mode = IM_OFF;
12 _boxes.style.map_color_to_material = CM_COLOR_AND_OPACITY;
13 _boxes.style.default_extent = _handle_size;
14
15 _cones.style.illumination_mode = IM_OFF;
16 _cones.style.map_color_to_material = CM_COLOR_AND_OPACITY;
17 _cones.style.radius = 0.02f;
18
19 _sphere.style.illumination_mode = IM_OFF;
20 _sphere.style.map_color_to_material = CM_COLOR_AND_OPACITY;
21 _sphere.style.halo_color = { 1.0f };
22
23 _rectangles.style.illumination_mode = IM_OFF;
24 _rectangles.style.map_color_to_material = CM_COLOR_AND_OPACITY;
25
26 // calculate ring points for rotation handles
27 for(size_t i = 0; i < _ring_segment_count; ++i) {
28 float t = static_cast<float>(i) / static_cast<float>(_ring_segment_count - 1);
29 t *= 2.0f * M_PI;
30 _ring_points.push_back({ std::cos(t), std::sin(t) });
31 }
32 _ring_points.back() = _ring_points.front();
33}
34
36 bool success = true;
37
38 success &= _box_renderer.init(ctx);
39 success &= _cone_renderer.init(ctx);
40 success &= _rectangle_renderer.init(ctx);
41 success &= _sphere_renderer.init(ctx);
42
43 success &= _boxes.init(ctx);
44 success &= _cones.init(ctx);
45 success &= _rectangles.init(ctx);
46 success &= _sphere.init(ctx);
47
48 return success;
49}
50
52 _box_renderer.clear(ctx);
53 _cone_renderer.clear(ctx);
54 _rectangle_renderer.clear(ctx);
55 _sphere_renderer.clear(ctx);
56
57 _boxes.destruct(ctx);
58 _cones.destruct(ctx);
59 _rectangles.destruct(ctx);
60 _sphere.destruct(ctx);
61}
62
63transformation_gizmo::Mode transformation_gizmo::get_mode() const {
64 return _mode;
65}
66
67void transformation_gizmo::set_mode(Mode mode) {
68 _mode = mode;
69 set_geometry_out_of_date();
71}
72
73vec3 transformation_gizmo::get_scale() const {
74 return _scale;
75}
76
77void transformation_gizmo::set_scale(const vec3& scale) {
78 _scale = scale;
80}
81
82void transformation_gizmo::create_geometry() {
84
85 const vec3 v0(0.0f);
86 const vec3 vx(1.0f, 0.0f, 0.0f);
87 const vec3 vy(0.0f, 1.0f, 0.0f);
88 const vec3 vz(0.0f, 0.0f, 1.0f);
89
90 hls red = rgb(1.0f, 0.0f, 0.0f);
91 hls green = rgb(0.0f, 1.0f, 0.0f);
92 hls blue = rgb(0.0f, 0.0f, 1.0f);
93
94 const float saturation = 0.9f;
95 const float lightness = 0.3f;
96
97 red.S() = saturation;
98 green.S() = saturation;
99 blue.S() = saturation;
100 red.L() = lightness;
101 green.L() = lightness;
102 blue.L() = lightness;
103
104 const rgb x_color = red;
105 const rgb y_color = green;
106 const rgb z_color = blue;
107
108 _boxes.clear();
109 _cones.clear();
110 _rectangles.clear();
111 _sphere.clear();
112
113 bool use_axes =
114 _mode == Mode::kTranslation ||
115 _mode == Mode::kScale ||
116 _mode == Mode::kModel;
117
118 bool has_translation =
119 _mode == Mode::kTranslation ||
120 _mode == Mode::kModel;
121
122 bool has_rotation =
123 _mode == Mode::kRotation ||
124 _mode == Mode::kModel;
125
126 bool has_scale =
127 _mode == Mode::kScale ||
128 _mode == Mode::kModel;
129
130 if(use_axes) {
131 float axis_length = 1.0f;
132
133 if(has_translation && has_scale)
134 axis_length -= 2.0f * _handle_size;
135 else if(has_translation)
136 axis_length -= 2.0f * _handle_size;
137 else if(has_scale)
138 axis_length -= _handle_size;
139
140 vec3 hx = axis_length * vx;
141 vec3 hy = axis_length * vy;
142 vec3 hz = axis_length * vz;
143
144 _cones.add(v0 + _center_radius * vx, hx);
145 _cones.add(v0 + _center_radius * vy, hy);
146 _cones.add(v0 + _center_radius * vz, hz);
147 _cones.fill_radii(_axis_radius);
148 _cones.add_segment_color({ x_color, 1.0f });
149 _cones.add_segment_color({ y_color, 1.0f });
150 _cones.add_segment_color({ z_color, 1.0f });
151
152 float arrow_offset = has_scale ? 3.0f * _handle_size : 0.0f;
153
154 if(has_translation) {
155 // create axis handles as arrow tips
156 _cones.add(hx + arrow_offset * vx, (1.0f + arrow_offset) * vx);
157 _cones.add(hy + arrow_offset * vy, (1.0f + arrow_offset) * vy);
158 _cones.add(hz + arrow_offset * vz, (1.0f + arrow_offset) * vz);
159 _cones.add(0.5f * _handle_size, 0.0f);
160 _cones.add(0.5f * _handle_size, 0.0f);
161 _cones.add(0.5f * _handle_size, 0.0f);
162 _cones.add_segment_color({ x_color, 1.0f });
163 _cones.add_segment_color({ y_color, 1.0f });
164 _cones.add_segment_color({ z_color, 1.0f });
165 }
166
167 if(has_scale) {
168 // create axis handles as boxes
169 float box_offset = axis_length + 0.5f * _handle_size;
170
171 _boxes.add_position(v0 + box_offset * vx);
172 _boxes.add_position(v0 + box_offset * vy);
173 _boxes.add_position(v0 + box_offset * vz);
174 _boxes.add_color({ x_color, 1.0f });
175 _boxes.add_color({ y_color, 1.0f });
176 _boxes.add_color({ z_color, 1.0f });
177 }
178 }
179
180 if(has_rotation) {
181 // create rings
182 const auto add_ring = [this](auto transform, const rgba& color) {
183 for(size_t i = 0; i < _ring_points.size(); ++i)
184 _cones.add(transform(_ring_points[i]), transform(_ring_points[(i + 1) % _ring_points.size()]));
185 _cones.fill_colors(color);
186 };
187
188 add_ring([](vec2 p) { return vec3(0.0f, p.x(), p.y()); }, { x_color, 1.0f }); // yz plane
189 add_ring([](vec2 p) { return vec3(p.x(), 0.0f, p.y()); }, { y_color, 1.0f }); // xz plane
190 add_ring([](vec2 p) { return vec3(p.x(), p.y(), 0.0f); }, { z_color, 1.0f }); // xy plane
191 _cones.fill_radii(_axis_radius);
192 }
193
194 // create plane handles
195 if(_mode == Mode::kTranslation || _mode == Mode::kScale) {
196 _rectangles.add_position(v0 + 0.5f * (vy + vz));
197 _rectangles.add_position(v0 + 0.5f * (vx + vz));
198 _rectangles.add_position(v0 + 0.5f * (vx + vy));
199 _rectangles.fill_extents(vec2(_plane_size));
200
201 _rectangles.add_color({ x_color, 0.5f });
202 _rectangles.add_color({ y_color, 0.5f });
203 _rectangles.add_color({ z_color, 0.5f });
204
205 _rectangles.add_border_color({ x_color, 1.0f });
206 _rectangles.add_border_color({ y_color, 1.0f });
207 _rectangles.add_border_color({ z_color, 1.0f });
208
209 _rectangles.add_rotation(quat(vy, cgv::math::deg2rad(90.0f)));
210 _rectangles.add_rotation(quat(vx, cgv::math::deg2rad(-90.0f)));
211 _rectangles.add_rotation(quat());
212 }
213
214 // create center sphere
215 _sphere.add(v0, _axis_radius);
216 _sphere.colors.push_back({ 1.0f });
217
218 _sphere.add(v0, _center_radius);
219 _sphere.colors.push_back({ 0.7f, 0.7f, 0.7f, 0.0f });
220
221 if(!is_hovered())
222 return;
223
224 // set colors based on hover state
225 const auto saturate_color = [](rgba& color) {
227 hls.S() = 0.95f;
228 hls.L() = 0.52f;
229 color = { rgb(hls), color.alpha() };
230 };
231
232 int axis_idx = axis_id_to_index(_interaction_axis_id);
233 switch(_interaction_feature) {
234 case InteractionFeature::kAxis:
235 if(use_axes) {
236 size_t base_idx = 2.0f * axis_idx;
237 if(has_translation && has_scale && _interaction_mode == Mode::kScale || has_translation != has_scale) {
238 saturate_color(_cones.colors[base_idx]);
239 saturate_color(_cones.colors[base_idx + 1]);
240 }
241
242 if(_interaction_mode == Mode::kTranslation) {
243 saturate_color(_cones.colors[base_idx + 6]);
244 saturate_color(_cones.colors[base_idx + 7]);
245 }
246
247 if(_interaction_mode == Mode::kScale)
248 saturate_color(_boxes.colors[axis_idx]);
249 }
250 break;
251 case InteractionFeature::kPlane:
252 if(has_rotation) {
253 size_t base_idx = static_cast<size_t>(axis_idx) * 2 * _ring_segment_count;
254 if(_mode == Mode::kModel)
255 base_idx += 12;
256
257 for(size_t i = 0; i < 2 * _ring_segment_count; ++i)
258 saturate_color(_cones.colors[base_idx + i]);
259 } else {
260 saturate_color(_rectangles.colors[axis_idx]);
261 saturate_color(_rectangles.border_colors[axis_idx]);
262 }
263 break;
264 case InteractionFeature::kCenter:
265 _sphere.colors.back().alpha() = 0.2f;
266 break;
267 default:
268 break;
269 }
270}
271
272void transformation_gizmo::draw_geometry(context& ctx) {
273 // Pass the y view angle to the renderers so pixel measurements are computed correctly
274 _rectangle_renderer.set_y_view_angle(get_view()->get_y_view_angle());
275 _sphere_renderer.set_y_view_angle(get_view()->get_y_view_angle());
276
277 // Since we use scaling in the modelview matrix we also need to adjust the pixel measures
278 // in the render styles based on the scale of the gizmo.
279 const float size = get_size();
280
281 _sphere.style.halo_width_in_pixel = -3.0f / size;
282 _sphere.style.blend_width_in_pixel = 1.0f / size;
283
284 _rectangles.style.border_width_in_pixel = -3.0f / size;
285 _rectangles.style.pixel_blend = 2.0f / size;
286
287 _sphere.render(ctx, _sphere_renderer);
288 _rectangles.render(ctx, _rectangle_renderer);
289 _cones.render(ctx, _cone_renderer);
290 _boxes.render(ctx, _box_renderer);
291}
292
293bool transformation_gizmo::intersect_bounding_box(const cgv::math::ray3& ray) {
294 vec3 min = { 0.0f };
295 vec3 max = { 1.0f };
296
297 if(_mode == Mode::kRotation || _mode == Mode::kModel)
298 min = -1.0f;
299 else
300 min -= _center_radius;
301
302 if(_mode == Mode::kModel)
303 max += 3.0f * _handle_size;
304
305 min -= 0.1f;
306 max += 0.1f;
307
308 vec2 t = std::numeric_limits<float>::max();
309 return cgv::math::ray_box_intersection(ray, min, max, t) != 0;
310}
311
312bool transformation_gizmo::intersect(const cgv::math::ray3& ray) {
313 float min_t = std::numeric_limits<float>::max();
314
315 const auto update_t_if_closer = [this, &min_t](float t, Mode transformation, InteractionFeature feature, AxisId axis_id) {
316 if(t >= 0.0f && t < min_t) {
317 min_t = t;
318 _interaction_mode = transformation;
319 _interaction_feature = feature;
320 _interaction_axis_id = axis_id;
321 }
322 };
323
324 if(_mode == Mode::kRotation || _mode == Mode::kModel) {
325 // test rings for planes
326 size_t start_offset = _mode == Mode::kModel ? 12 : 0;
327 for(size_t i = start_offset; i < _cones.size(); i += 2) {
328 vec3 pa = _cones.positions[i];
329 vec3 pb = _cones.positions[i + 1];
330
331 float t = std::numeric_limits<float>::max();
332 if(cgv::math::ray_cylinder_intersection2(ray, pa, pb, 3.0f * _axis_radius, t)) {
333 int axis_idx = static_cast<int>((i - start_offset) / (2 * _ring_segment_count));
334 update_t_if_closer(t, Mode::kRotation, InteractionFeature::kPlane, index_to_axis_id(axis_idx));
335 }
336 }
337 }
338
339
340 std::array<std::pair<vec3, vec3>, 6> cylinders;
341 cylinders.fill({ 0.0f, 0.0f });
342 size_t cylinder_count = 0;
343 float axis_length = 1.0f;
344
345 if(_mode == Mode::kModel) {
346 axis_length -= _handle_size;
347 }
348
349 if(_mode == Mode::kTranslation || _mode == Mode::kScale || _mode == Mode::kModel) {
350 cylinder_count += 3;
351 for(unsigned i = 0; i < 3; ++i) {
352 cylinders[i].first[i] = _center_radius;
353 cylinders[i].second[i] = axis_length;
354 }
355 }
356
357 if(_mode == Mode::kModel) {
358 cylinder_count += 3;
359 for(size_t i = 0; i < 3; ++i) {
360 cylinders[i + 3].first[i] = axis_length + 2.0f * _handle_size;
361 cylinders[i + 3].second[i] = axis_length + 4.0f * _handle_size;
362 }
363 }
364
365 for(size_t i = 0; i < cylinder_count; ++i) {
366 float t = std::numeric_limits<float>::max();
367 if(cgv::math::ray_cylinder_intersection2(ray, cylinders[i].first, cylinders[i].second, _handle_size, t)) {
368 Mode transformation = _mode;
369 if(cylinder_count > 3)
370 transformation = i < 3 ? Mode::kScale : Mode::kTranslation;
371
372 update_t_if_closer(t, transformation, InteractionFeature::kAxis, index_to_axis_id(static_cast<int>(i % 3)));
373 }
374 }
375
376 // test rectangles for planes
377 if(_mode == Mode::kTranslation || _mode == Mode::kScale) {
378 float t = std::numeric_limits<float>::max();
379 for(size_t i = 0; i < 3; ++i) {
380 vec3 position = { 0.5f };
381 position[i] = 0.0f;
382 if(cgv::math::ray_axis_aligned_rectangle_intersection(ray, position, { _plane_size }, static_cast<int>(i), t))
383 update_t_if_closer(t, _mode, InteractionFeature::kPlane, index_to_axis_id(static_cast<int>(i)));
384 }
385 }
386
387 // test sphere for center
388 vec2 ts(std::numeric_limits<float>::max());
389 if(cgv::math::ray_sphere_intersection(ray, { 0.0f }, _center_radius, ts)) {
390 Mode transformation = _mode == Mode::kModel ? Mode::kTranslation : _mode;
391 update_t_if_closer(ts.x(), transformation, InteractionFeature::kCenter, AxisId::kX);
392 }
393
394 return min_t > 0.0f && min_t < std::numeric_limits<float>::max();
395}
396
397bool transformation_gizmo::start_drag(const cgv::math::ray3& ray) {
398 int axis_idx = axis_id_to_index(_interaction_axis_id);
399 vec3 axis = get_axis(axis_idx);
400
401 const vec3 view_dir = get_view()->get_view_dir();
402
403 _interaction_plane.origin = get_position();
404
405 const auto get_rotated_axis = [this](const vec3& axis) {
406 vec3 rotated = axis;
407 get_rotation().rotate(rotated);
408 return rotated;
409 };
410
411 if(_interaction_mode == Mode::kRotation) {
412 switch(_interaction_feature) {
413 case InteractionFeature::kPlane:
414 {
415 _interaction_plane.normal = get_rotated_axis(axis);
416 // if the ray direction is close to parallel to the plane, choose the screen aligned plane instead
417 float threshold_angle = std::cos(cgv::math::deg2rad(75.0f));
418
419 float incident_angle = dot(_interaction_plane.normal, ray.direction);
420 if(std::abs(incident_angle) < threshold_angle)
421 _interaction_plane.normal = incident_angle < 0.0f ? -view_dir : view_dir;
422 break;
423 }
424 case InteractionFeature::kCenter:
425 _interaction_plane.normal = view_dir;
426 break;
427 default:
428 return false;
429 }
430 } else {
431 switch(_interaction_feature) {
432 case InteractionFeature::kAxis:
433 {
434 // the plane is not actually needed for axis interaction, so we just chose one that will
435 // always produce an intersection with the mouse ray
436 _interaction_plane.normal = view_dir;
437 break;
438 }
439 case InteractionFeature::kPlane:
440 _interaction_plane.normal = get_rotated_axis(axis);
441 break;
442 case InteractionFeature::kCenter:
443 _interaction_plane.normal = view_dir;
444 break;
445 default:
446 return false;
447 }
448 }
449
450 float t = -1.0f;
451 if(!cgv::math::ray_plane_intersection(ray, _interaction_plane.origin, _interaction_plane.normal, t))
452 return false;
453
454 _drag_start_t = t;
455 _drag_start_position = get_position();
456 _drag_start_scale = _scale;
457 _drag_start_rotation = get_rotation();
458
459 if(on_change)
460 on_change(GizmoAction::kDragStart, _interaction_mode);
461
462 return true;
463}
464
465bool transformation_gizmo::drag(const cgv::math::ray3& ray) {
466 int axis_idx = axis_id_to_index(_interaction_axis_id);
467 vec3 axis = get_axis(axis_idx);
468
469 const vec3 position = get_position();
470
471 if(!_interaction_plane.valid())
472 return false;
473
474 float t = -1.0f;
475 if(!cgv::math::ray_plane_intersection(ray, _interaction_plane.origin, _interaction_plane.normal, t) || t < 0.0f) {
476 // restore drag start transforms if no valid intersection with the interaction plane is found
477 set_position(_drag_start_position);
478 set_scale(_drag_start_scale);
479 set_rotation(_drag_start_rotation);
480 } else {
481 vec3 start_intersection_position = _drag_start_ray.position(_drag_start_t);
482 vec3 intersection_position = ray.position(t);
483
484 if(get_orientation() == GizmoOrientation::kLocal)
485 _drag_start_rotation.rotate(axis);
486
487 switch(_interaction_mode) {
488 case Mode::kTranslation:
489 {
490 // TODO: FIXME: This is not optimal and only works well when the mouse position is pointing close to the manipulated axis.
491 cgv::math::ray3 axis_ray = { _drag_start_position, axis };
492
493 float start_offset = ray_ray_closest_approach(_drag_start_ray, axis_ray).second;
494 float offset = ray_ray_closest_approach(ray, axis_ray).second;
495
496 vec3 new_position = _drag_start_position;
497 if(_interaction_feature == InteractionFeature::kAxis)
498 new_position += (offset - start_offset) * axis;
499 else
500 new_position += intersection_position - start_intersection_position;// _local_offset;
501
502 set_position(new_position);
503 break;
504 }
505 case Mode::kScale:
506 {
507 // TODO: FIXME: Scaling does not work corectly for rotated coordinate frames (local gizmo orientation).
508 vec3 new_local_offset = start_intersection_position - _drag_start_position;
509 if(_interaction_feature == InteractionFeature::kAxis)
510 new_local_offset[axis_idx] = (intersection_position - position)[axis_idx];
511 else
512 new_local_offset = intersection_position - position;
513
514 vec3 scale_mult = new_local_offset / (start_intersection_position - _drag_start_position);
515
516 vec3 new_scale = _drag_start_scale;
517 switch(_interaction_feature) {
518 case InteractionFeature::kAxis:
519 new_scale[axis_idx] *= scale_mult[axis_idx];
520 break;
521 case InteractionFeature::kPlane:
522 for(int i = 0; i < 3; ++i) {
523 if(i != axis_idx)
524 new_scale[i] *= scale_mult[i];
525 }
526 break;
527 case InteractionFeature::kCenter:
528 new_scale *= length(scale_mult);
529 break;
530 default:
531 break;
532 }
533
534 set_scale(new_scale);
535 break;
536 }
537 case Mode::kRotation:
538 {
539 vec3 start_dir = start_intersection_position - _drag_start_position;
540 vec3 end_dir = intersection_position - position;
541
542 // check length and skip if too short
543 if(start_dir.normalize() < 0.01f)
544 return true;
545 if(end_dir.normalize() < 0.01f)
546 return true;
547
548 vec3 plane_tangent = normalize(cross(_interaction_plane.normal, start_dir));
549
550 float cos_theta = dot(start_dir, end_dir);
551 cos_theta = cgv::math::clamp(cos_theta, -1.0f, 1.0f);
552 float angle = std::acos(cos_theta);
553
554 // check for side and bring angle in range [0,2pi];
555 if(dot(plane_tangent, end_dir) < 0.0f)
556 angle = 2.0f * M_PI - angle;
557
558 vec3 rotaton_axis = _interaction_feature == InteractionFeature::kCenter ? _interaction_plane.normal : axis;
559
560 quat new_rotation = quat(rotaton_axis, angle) * _drag_start_rotation;
561
562 set_rotation(new_rotation);
563 break;
564 }
565 default:
566 return false;
567 }
568 }
569
570 if(on_change)
571 on_change(GizmoAction::kDrag, _interaction_mode);
572
573 return true;
574}
575
576void transformation_gizmo::end_drag(const cgv::math::ray3& ray) {
577 if(on_change)
578 on_change(GizmoAction::kDragEnd, _interaction_mode);
579}
580
581std::pair<float, float> transformation_gizmo::ray_ray_closest_approach(const cgv::math::ray3& r0, const cgv::math::ray3& r1) const {
582 vec3 ba = r1.direction;
583 vec3 oa = r0.origin - r1.origin;
584
585 float a = dot(ba, ba);
586 float b = dot(r0.direction, ba);
587 float c = dot(oa, ba);
588 float e = dot(oa, r0.direction);
589
590 vec2 st = vec2(c - b * e, b * c - a * e) / (a - b * b);
591
592 return { st.y(), st.x() };
593}
594
595}
596}
void clear(cgv::render::context &) override
clear all objects living in the context like textures or display lists
bool init(cgv::render::context &) override
this method is called after creation or recreation of the context, return whether all necessary funct...
T & y()
second element
Definition fvec.h:159
T normalize()
normalize the vector using the L2-Norm and return the length
Definition fvec.h:302
T & x()
first element
Definition fvec.h:155
void rotate(vec_type &v) const
rotate vector according to quaternion
Definition quaternion.h:198
This class defines a template for n-dimensional rays with arbitrary data type defined by origin and d...
Definition ray.h:14
fvec< T, N > position(float t) const
Returns the position of the ray at the given distance (ray parameter t) from its origin.
Definition ray.h:29
represent a color with components of given type and color and alpha model as specified.
Definition color.h:574
virtual void clear(const context &ctx)
the clear function destructs the shader program and resets the texture pointers
base class for all drawables, which is independent of the used rendering API.
Definition context.h:621
void post_redraw()
posts a redraw event to the current context if one is available
Definition drawable.cxx:43
bool init(context &ctx)
call init() once before using renderer
virtual bool init(context &ctx)
call init() once before using renderer
Definition renderer.cxx:173
virtual void clear(const context &ctx)
the clear function destructs the shader program
Definition renderer.cxx:349
const dvec3 & get_view_dir() const
query current view direction
Definition view.cxx:58
namespace for api independent GPU programming
the cgv namespace
Definition print.h:11
cgv::math::quaternion< float > quat
declare type of quaternion
Definition quaternion.h:370
cgv::media::color< float, cgv::media::RGB > rgb
declare rgb color type with 32 bit components
Definition color.h:853
cgv::math::fvec< float, 2 > vec2
declare type of 2d single precision floating point vectors
Definition fvec.h:667
cgv::math::fvec< float, 3 > vec3
declare type of 3d single precision floating point vectors
Definition fvec.h:669
T S() const
convert color to HLS and return S component
Definition color.h:448
T L() const
convert color to HLS and return L component
Definition color.h:446