vectorutils.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2019 Google Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef CARDBOARD_SDK_UTIL_VECTORUTILS_H_
  17. #define CARDBOARD_SDK_UTIL_VECTORUTILS_H_
  18. //
  19. // This file contains free functions that operate on Vector instances.
  20. //
  21. #include <cmath>
  22. #include "vector.h"
  23. namespace cardboard {
  24. // Returns the dot (inner) product of two Vectors.
  25. double Dot(const Vector<3>& v0, const Vector<3>& v1);
  26. // Returns the dot (inner) product of two Vectors.
  27. double Dot(const Vector<4>& v0, const Vector<4>& v1);
  28. // Returns the 3-dimensional cross product of 2 Vectors. Note that this is
  29. // defined only for 3-dimensional Vectors.
  30. Vector<3> Cross(const Vector<3>& v0, const Vector<3>& v1);
  31. // Returns the square of the length of a Vector.
  32. template <int Dimension> double LengthSquared(const Vector<Dimension>& v) { return Dot(v, v); }
  33. // Returns the geometric length of a Vector.
  34. template <int Dimension> double Length(const Vector<Dimension>& v)
  35. {
  36. return sqrt(LengthSquared(v));
  37. }
  38. // the Vector untouched and returns false.
  39. template <int Dimension> bool Normalize(Vector<Dimension>* v)
  40. {
  41. const double len = Length(*v);
  42. if (len == 0) {
  43. return false;
  44. } else {
  45. (*v) /= len;
  46. return true;
  47. }
  48. }
  49. // Returns a unit-length version of a Vector. If the given Vector has no
  50. // length, this returns a Zero() Vector.
  51. template <int Dimension> Vector<Dimension> Normalized(const Vector<Dimension>& v)
  52. {
  53. Vector<Dimension> result = v;
  54. if (Normalize(&result))
  55. return result;
  56. else
  57. return Vector<Dimension>::Zero();
  58. }
  59. } // namespace cardboard
  60. #endif // CARDBOARD_SDK_UTIL_VECTORUTILS_H_