vectorutils.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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>
  33. double LengthSquared(const Vector<Dimension>& v) {
  34. return Dot(v, v);
  35. }
  36. // Returns the geometric length of a Vector.
  37. template <int Dimension>
  38. double Length(const Vector<Dimension>& v) {
  39. return sqrt(LengthSquared(v));
  40. }
  41. // the Vector untouched and returns false.
  42. template <int Dimension>
  43. bool Normalize(Vector<Dimension>* v) {
  44. const double len = Length(*v);
  45. if(len == 0) {
  46. return false;
  47. } else {
  48. (*v) /= len;
  49. return true;
  50. }
  51. }
  52. // Returns a unit-length version of a Vector. If the given Vector has no
  53. // length, this returns a Zero() Vector.
  54. template <int Dimension>
  55. Vector<Dimension> Normalized(const Vector<Dimension>& v) {
  56. Vector<Dimension> result = v;
  57. if(Normalize(&result))
  58. return result;
  59. else
  60. return Vector<Dimension>::Zero();
  61. }
  62. } // namespace cardboard
  63. #endif // CARDBOARD_SDK_UTIL_VECTORUTILS_H_