You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.7 KiB

  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. #include "trackball.h"
  10. #include "camera.h"
  11. using namespace StormEigen;
  12. void Trackball::track(const Vector2i& point2D)
  13. {
  14. if (mpCamera==0)
  15. return;
  16. Vector3f newPoint3D;
  17. bool newPointOk = mapToSphere(point2D, newPoint3D);
  18. if (mLastPointOk && newPointOk)
  19. {
  20. Vector3f axis = mLastPoint3D.cross(newPoint3D).normalized();
  21. float cos_angle = mLastPoint3D.dot(newPoint3D);
  22. if ( std::abs(cos_angle) < 1.0 )
  23. {
  24. float angle = 2. * acos(cos_angle);
  25. if (mMode==Around)
  26. mpCamera->rotateAroundTarget(Quaternionf(AngleAxisf(angle, axis)));
  27. else
  28. mpCamera->localRotate(Quaternionf(AngleAxisf(-angle, axis)));
  29. }
  30. }
  31. mLastPoint3D = newPoint3D;
  32. mLastPointOk = newPointOk;
  33. }
  34. bool Trackball::mapToSphere(const Vector2i& p2, Vector3f& v3)
  35. {
  36. if ((p2.x() >= 0) && (p2.x() <= int(mpCamera->vpWidth())) &&
  37. (p2.y() >= 0) && (p2.y() <= int(mpCamera->vpHeight())) )
  38. {
  39. double x = (double)(p2.x() - 0.5*mpCamera->vpWidth()) / (double)mpCamera->vpWidth();
  40. double y = (double)(0.5*mpCamera->vpHeight() - p2.y()) / (double)mpCamera->vpHeight();
  41. double sinx = sin(M_PI * x * 0.5);
  42. double siny = sin(M_PI * y * 0.5);
  43. double sinx2siny2 = sinx * sinx + siny * siny;
  44. v3.x() = sinx;
  45. v3.y() = siny;
  46. v3.z() = sinx2siny2 < 1.0 ? sqrt(1.0 - sinx2siny2) : 0.0;
  47. return true;
  48. }
  49. else
  50. return false;
  51. }