mikk_float3.hh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /* SPDX-FileCopyrightText: 2020-2023 Blender Authors
  2. *
  3. * SPDX-License-Identifier: Apache-2.0 */
  4. /** \file
  5. * \ingroup mikktspace
  6. */
  7. #pragma once
  8. #include <cmath>
  9. namespace mikk {
  10. struct float3 {
  11. float x, y, z;
  12. float3() = default;
  13. float3(const float *ptr) : x{ptr[0]}, y{ptr[1]}, z{ptr[2]} {}
  14. float3(const float (*ptr)[3]) : float3((const float *)ptr) {}
  15. explicit float3(float value) : x(value), y(value), z(value) {}
  16. explicit float3(int value) : x((float)value), y((float)value), z((float)value) {}
  17. float3(float x_, float y_, float z_) : x{x_}, y{y_}, z{z_} {}
  18. static float3 zero()
  19. {
  20. return {0.0f, 0.0f, 0.0f};
  21. }
  22. friend float3 operator*(const float3 &a, float b)
  23. {
  24. return {a.x * b, a.y * b, a.z * b};
  25. }
  26. friend float3 operator*(float b, const float3 &a)
  27. {
  28. return {a.x * b, a.y * b, a.z * b};
  29. }
  30. friend float3 operator-(const float3 &a, const float3 &b)
  31. {
  32. return {a.x - b.x, a.y - b.y, a.z - b.z};
  33. }
  34. friend float3 operator-(const float3 &a)
  35. {
  36. return {-a.x, -a.y, -a.z};
  37. }
  38. friend bool operator==(const float3 &a, const float3 &b)
  39. {
  40. return a.x == b.x && a.y == b.y && a.z == b.z;
  41. }
  42. float length_squared() const
  43. {
  44. return x * x + y * y + z * z;
  45. }
  46. float length() const
  47. {
  48. return sqrt(length_squared());
  49. }
  50. static float distance(const float3 &a, const float3 &b)
  51. {
  52. return (a - b).length();
  53. }
  54. friend float3 operator+(const float3 &a, const float3 &b)
  55. {
  56. return {a.x + b.x, a.y + b.y, a.z + b.z};
  57. }
  58. void operator+=(const float3 &b)
  59. {
  60. this->x += b.x;
  61. this->y += b.y;
  62. this->z += b.z;
  63. }
  64. friend float3 operator*(const float3 &a, const float3 &b)
  65. {
  66. return {a.x * b.x, a.y * b.y, a.z * b.z};
  67. }
  68. float3 normalize() const
  69. {
  70. const float len = length();
  71. return (len != 0.0f) ? *this * (1.0f / len) : *this;
  72. }
  73. float reduce_add() const
  74. {
  75. return x + y + z;
  76. }
  77. };
  78. inline float dot(const float3 &a, const float3 &b)
  79. {
  80. return a.x * b.x + a.y * b.y + a.z * b.z;
  81. }
  82. inline float distance(const float3 &a, const float3 &b)
  83. {
  84. return float3::distance(a, b);
  85. }
  86. /* Projects v onto the surface with normal n. */
  87. inline float3 project(const float3 &n, const float3 &v)
  88. {
  89. return (v - n * dot(n, v)).normalize();
  90. }
  91. } // namespace mikk