vector3d.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. // Copyright (C) 2002-2012 Nikolaus Gebhardt
  2. // This file is part of the "Irrlicht Engine".
  3. // For conditions of distribution and use, see copyright notice in irrlicht.h
  4. #ifndef IRR_POINT_3D_H_INCLUDED
  5. #define IRR_POINT_3D_H_INCLUDED
  6. #include "irrMath.h"
  7. namespace irr
  8. {
  9. namespace core
  10. {
  11. //! 3d vector template class with lots of operators and methods.
  12. /** The vector3d class is used in Irrlicht for three main purposes:
  13. 1) As a direction vector (most of the methods assume this).
  14. 2) As a position in 3d space (which is synonymous with a direction vector from the origin to this position).
  15. 3) To hold three Euler rotations, where X is pitch, Y is yaw and Z is roll.
  16. */
  17. template <class T>
  18. class vector3d
  19. {
  20. public:
  21. //! Default constructor (null vector).
  22. vector3d() : X(0), Y(0), Z(0) {}
  23. //! Constructor with three different values
  24. vector3d(T nx, T ny, T nz) : X(nx), Y(ny), Z(nz) {}
  25. //! Constructor with the same value for all elements
  26. explicit vector3d(T n) : X(n), Y(n), Z(n) {}
  27. // operators
  28. vector3d<T> operator-() const { return vector3d<T>(-X, -Y, -Z); }
  29. vector3d<T> operator+(const vector3d<T>& other) const { return vector3d<T>(X + other.X, Y + other.Y, Z + other.Z); }
  30. vector3d<T>& operator+=(const vector3d<T>& other) { X+=other.X; Y+=other.Y; Z+=other.Z; return *this; }
  31. vector3d<T> operator+(const T val) const { return vector3d<T>(X + val, Y + val, Z + val); }
  32. vector3d<T>& operator+=(const T val) { X+=val; Y+=val; Z+=val; return *this; }
  33. vector3d<T> operator-(const vector3d<T>& other) const { return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z); }
  34. vector3d<T>& operator-=(const vector3d<T>& other) { X-=other.X; Y-=other.Y; Z-=other.Z; return *this; }
  35. vector3d<T> operator-(const T val) const { return vector3d<T>(X - val, Y - val, Z - val); }
  36. vector3d<T>& operator-=(const T val) { X-=val; Y-=val; Z-=val; return *this; }
  37. vector3d<T> operator*(const vector3d<T>& other) const { return vector3d<T>(X * other.X, Y * other.Y, Z * other.Z); }
  38. vector3d<T>& operator*=(const vector3d<T>& other) { X*=other.X; Y*=other.Y; Z*=other.Z; return *this; }
  39. vector3d<T> operator*(const T v) const { return vector3d<T>(X * v, Y * v, Z * v); }
  40. vector3d<T>& operator*=(const T v) { X*=v; Y*=v; Z*=v; return *this; }
  41. vector3d<T> operator/(const vector3d<T>& other) const { return vector3d<T>(X / other.X, Y / other.Y, Z / other.Z); }
  42. vector3d<T>& operator/=(const vector3d<T>& other) { X/=other.X; Y/=other.Y; Z/=other.Z; return *this; }
  43. vector3d<T> operator/(const T v) const { return vector3d<T>(X/v, Y/v, Z/v); }
  44. vector3d<T>& operator/=(const T v) { X/=v; Y/=v; Z/=v; return *this; }
  45. T& operator [](u32 index)
  46. {
  47. IRR_DEBUG_BREAK_IF(index>2) // access violation
  48. return *(&X+index);
  49. }
  50. const T& operator [](u32 index) const
  51. {
  52. IRR_DEBUG_BREAK_IF(index>2) // access violation
  53. return *(&X+index);
  54. }
  55. //! sort in order X, Y, Z. Equality with rounding tolerance.
  56. bool operator<=(const vector3d<T>&other) const
  57. {
  58. return (X<other.X || core::equals(X, other.X)) ||
  59. (core::equals(X, other.X) && (Y<other.Y || core::equals(Y, other.Y))) ||
  60. (core::equals(X, other.X) && core::equals(Y, other.Y) && (Z<other.Z || core::equals(Z, other.Z)));
  61. }
  62. //! sort in order X, Y, Z. Equality with rounding tolerance.
  63. bool operator>=(const vector3d<T>&other) const
  64. {
  65. return (X>other.X || core::equals(X, other.X)) ||
  66. (core::equals(X, other.X) && (Y>other.Y || core::equals(Y, other.Y))) ||
  67. (core::equals(X, other.X) && core::equals(Y, other.Y) && (Z>other.Z || core::equals(Z, other.Z)));
  68. }
  69. //! sort in order X, Y, Z. Difference must be above rounding tolerance.
  70. bool operator<(const vector3d<T>&other) const
  71. {
  72. return (X<other.X && !core::equals(X, other.X)) ||
  73. (core::equals(X, other.X) && Y<other.Y && !core::equals(Y, other.Y)) ||
  74. (core::equals(X, other.X) && core::equals(Y, other.Y) && Z<other.Z && !core::equals(Z, other.Z));
  75. }
  76. //! sort in order X, Y, Z. Difference must be above rounding tolerance.
  77. bool operator>(const vector3d<T>&other) const
  78. {
  79. return (X>other.X && !core::equals(X, other.X)) ||
  80. (core::equals(X, other.X) && Y>other.Y && !core::equals(Y, other.Y)) ||
  81. (core::equals(X, other.X) && core::equals(Y, other.Y) && Z>other.Z && !core::equals(Z, other.Z));
  82. }
  83. //! use weak float compare
  84. bool operator==(const vector3d<T>& other) const
  85. {
  86. return this->equals(other);
  87. }
  88. bool operator!=(const vector3d<T>& other) const
  89. {
  90. return !this->equals(other);
  91. }
  92. // functions
  93. //! returns if this vector equals the other one, taking floating point rounding errors into account
  94. bool equals(const vector3d<T>& other, const T tolerance = (T)ROUNDING_ERROR_f32 ) const
  95. {
  96. return core::equals(X, other.X, tolerance) &&
  97. core::equals(Y, other.Y, tolerance) &&
  98. core::equals(Z, other.Z, tolerance);
  99. }
  100. vector3d<T>& set(const T nx, const T ny, const T nz) {X=nx; Y=ny; Z=nz; return *this;}
  101. vector3d<T>& set(const vector3d<T>& p) {X=p.X; Y=p.Y; Z=p.Z;return *this;}
  102. //! Get length of the vector.
  103. T getLength() const { return core::squareroot( X*X + Y*Y + Z*Z ); }
  104. //! Get squared length of the vector.
  105. /** This is useful because it is much faster than getLength().
  106. \return Squared length of the vector. */
  107. T getLengthSQ() const { return X*X + Y*Y + Z*Z; }
  108. //! Get the dot product with another vector.
  109. T dotProduct(const vector3d<T>& other) const
  110. {
  111. return X*other.X + Y*other.Y + Z*other.Z;
  112. }
  113. //! Get distance from another point.
  114. /** Here, the vector is interpreted as point in 3 dimensional space. */
  115. T getDistanceFrom(const vector3d<T>& other) const
  116. {
  117. return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z).getLength();
  118. }
  119. //! Returns squared distance from another point.
  120. /** Here, the vector is interpreted as point in 3 dimensional space. */
  121. T getDistanceFromSQ(const vector3d<T>& other) const
  122. {
  123. return vector3d<T>(X - other.X, Y - other.Y, Z - other.Z).getLengthSQ();
  124. }
  125. //! Calculates the cross product with another vector.
  126. /** \param p Vector to multiply with.
  127. \return Cross product of this vector with p. */
  128. vector3d<T> crossProduct(const vector3d<T>& p) const
  129. {
  130. return vector3d<T>(Y * p.Z - Z * p.Y, Z * p.X - X * p.Z, X * p.Y - Y * p.X);
  131. }
  132. //! Returns if this vector interpreted as a point is on a line between two other points.
  133. /** It is assumed that the point is on the line.
  134. \param begin Beginning vector to compare between.
  135. \param end Ending vector to compare between.
  136. \return True if this vector is between begin and end, false if not. */
  137. bool isBetweenPoints(const vector3d<T>& begin, const vector3d<T>& end) const
  138. {
  139. const T f = (end - begin).getLengthSQ();
  140. return getDistanceFromSQ(begin) <= f &&
  141. getDistanceFromSQ(end) <= f;
  142. }
  143. //! Normalizes the vector.
  144. /** In case of the 0 vector the result is still 0, otherwise
  145. the length of the vector will be 1.
  146. \return Reference to this vector after normalization. */
  147. vector3d<T>& normalize()
  148. {
  149. f64 length = X*X + Y*Y + Z*Z;
  150. if (length == 0 ) // this check isn't an optimization but prevents getting NAN in the sqrt.
  151. return *this;
  152. length = core::reciprocal_squareroot(length);
  153. X = (T)(X * length);
  154. Y = (T)(Y * length);
  155. Z = (T)(Z * length);
  156. return *this;
  157. }
  158. //! Sets the length of the vector to a new value
  159. vector3d<T>& setLength(T newlength)
  160. {
  161. normalize();
  162. return (*this *= newlength);
  163. }
  164. #if defined(_IRR_COMPILE_WITH_90_DEGREE_CAMERA)
  165. vector3d<T>& normalize_camera_direction(const vector3d<T>& def)
  166. {
  167. f64 l = (f64)X * X + (f64)Y * Y + (f64)Z * Z;
  168. if (::fabs(l) < 0.000000001)
  169. {
  170. X = def.X;
  171. Y = def.Y;
  172. Z = def.Z;
  173. }
  174. else
  175. {
  176. l = 1.0 / ::sqrt(l);
  177. f64 v;
  178. v = X * l; X = ::fabs(v) < 0.00000001 ? (T)0 : (T)v;
  179. v = Y * l; Y = ::fabs(v) < 0.00000001 ? (T)0 : (T)v;
  180. v = Z * l; Z = ::fabs(v) < 0.00000001 ? (T)0 : (T)v;
  181. }
  182. return *this;
  183. }
  184. #define normalize_x() normalize_camera_direction(core::vector3df(1.f, 0.f, 0.f))
  185. #define normalize_z() normalize_camera_direction(core::vector3df(0.f, 0.f, 1.f))
  186. #define normalize_y(v) core::vector3df(v).normalize_camera_direction(core::vector3df(0.f, 1.f, 0.f))
  187. #else
  188. #define normalize_x() normalize()
  189. #define normalize_z() normalize()
  190. #define normalize_y(v) v
  191. #endif
  192. //! Inverts the vector.
  193. vector3d<T>& invert()
  194. {
  195. X *= -1;
  196. Y *= -1;
  197. Z *= -1;
  198. return *this;
  199. }
  200. //! Rotates the vector by a specified number of degrees around the Y axis and the specified center.
  201. /** CAREFUL: For historical reasons rotateXZBy uses a right-handed rotation
  202. (maybe to make it more similar to the 2D vector rotations which are counterclockwise).
  203. To have this work the same way as rest of Irrlicht (nodes, matrices, other rotateBy functions) pass -1*degrees in here.
  204. \param degrees Number of degrees to rotate around the Y axis.
  205. \param center The center of the rotation. */
  206. void rotateXZBy(f64 degrees, const vector3d<T>& center=vector3d<T>())
  207. {
  208. degrees *= DEGTORAD64;
  209. const f64 cs = cos(degrees);
  210. const f64 sn = sin(degrees);
  211. X -= center.X;
  212. Z -= center.Z;
  213. set((T)(X*cs - Z*sn), Y, (T)(X*sn + Z*cs));
  214. X += center.X;
  215. Z += center.Z;
  216. }
  217. //! Rotates the vector by a specified number of degrees around the Z axis and the specified center.
  218. /** \param degrees: Number of degrees to rotate around the Z axis.
  219. \param center: The center of the rotation. */
  220. void rotateXYBy(f64 degrees, const vector3d<T>& center=vector3d<T>())
  221. {
  222. degrees *= DEGTORAD64;
  223. const f64 cs = cos(degrees);
  224. const f64 sn = sin(degrees);
  225. X -= center.X;
  226. Y -= center.Y;
  227. set((T)(X*cs - Y*sn), (T)(X*sn + Y*cs), Z);
  228. X += center.X;
  229. Y += center.Y;
  230. }
  231. //! Rotates the vector by a specified number of degrees around the X axis and the specified center.
  232. /** \param degrees: Number of degrees to rotate around the X axis.
  233. \param center: The center of the rotation. */
  234. void rotateYZBy(f64 degrees, const vector3d<T>& center=vector3d<T>())
  235. {
  236. degrees *= DEGTORAD64;
  237. const f64 cs = cos(degrees);
  238. const f64 sn = sin(degrees);
  239. Z -= center.Z;
  240. Y -= center.Y;
  241. set(X, (T)(Y*cs - Z*sn), (T)(Y*sn + Z*cs));
  242. Z += center.Z;
  243. Y += center.Y;
  244. }
  245. //! Creates an interpolated vector between this vector and another vector.
  246. /** \param other The other vector to interpolate with.
  247. \param d Interpolation value between 0.0f (all the other vector) and 1.0f (all this vector).
  248. Note that this is the opposite direction of interpolation to getInterpolated_quadratic()
  249. \return An interpolated vector. This vector is not modified. */
  250. vector3d<T> getInterpolated(const vector3d<T>& other, f64 d) const
  251. {
  252. const f64 inv = 1.0 - d;
  253. return vector3d<T>((T)(other.X*inv + X*d), (T)(other.Y*inv + Y*d), (T)(other.Z*inv + Z*d));
  254. }
  255. //! Creates a quadratically interpolated vector between this and two other vectors.
  256. /** \param v2 Second vector to interpolate with.
  257. \param v3 Third vector to interpolate with (maximum at 1.0f)
  258. \param d Interpolation value between 0.0f (all this vector) and 1.0f (all the 3rd vector).
  259. Note that this is the opposite direction of interpolation to getInterpolated() and interpolate()
  260. \return An interpolated vector. This vector is not modified. */
  261. vector3d<T> getInterpolated_quadratic(const vector3d<T>& v2, const vector3d<T>& v3, f64 d) const
  262. {
  263. // this*(1-d)*(1-d) + 2 * v2 * (1-d) + v3 * d * d;
  264. const f64 inv = (T) 1.0 - d;
  265. const f64 mul0 = inv * inv;
  266. const f64 mul1 = (T) 2.0 * d * inv;
  267. const f64 mul2 = d * d;
  268. return vector3d<T> ((T)(X * mul0 + v2.X * mul1 + v3.X * mul2),
  269. (T)(Y * mul0 + v2.Y * mul1 + v3.Y * mul2),
  270. (T)(Z * mul0 + v2.Z * mul1 + v3.Z * mul2));
  271. }
  272. //! Sets this vector to the linearly interpolated vector between a and b.
  273. /** \param a first vector to interpolate with, maximum at 1.0f
  274. \param b second vector to interpolate with, maximum at 0.0f
  275. \param d Interpolation value between 0.0f (all vector b) and 1.0f (all vector a)
  276. Note that this is the opposite direction of interpolation to getInterpolated_quadratic()
  277. */
  278. vector3d<T>& interpolate(const vector3d<T>& a, const vector3d<T>& b, f64 d)
  279. {
  280. X = (T)((f64)b.X + ( ( a.X - b.X ) * d ));
  281. Y = (T)((f64)b.Y + ( ( a.Y - b.Y ) * d ));
  282. Z = (T)((f64)b.Z + ( ( a.Z - b.Z ) * d ));
  283. return *this;
  284. }
  285. //! Get the rotations that would make a (0,0,1) direction vector point in the same direction as this direction vector.
  286. /** Thanks to Arras on the Irrlicht forums for this method. This utility method is very useful for
  287. orienting scene nodes towards specific targets. For example, if this vector represents the difference
  288. between two scene nodes, then applying the result of getHorizontalAngle() to one scene node will point
  289. it at the other one.
  290. Example code:
  291. // Where target and seeker are of type ISceneNode*
  292. const vector3df toTarget(target->getAbsolutePosition() - seeker->getAbsolutePosition());
  293. const vector3df requiredRotation = toTarget.getHorizontalAngle();
  294. seeker->setRotation(requiredRotation);
  295. \return A rotation vector containing the X (pitch) and Y (raw) rotations (in degrees) that when applied to a
  296. +Z (e.g. 0, 0, 1) direction vector would make it point in the same direction as this vector. The Z (roll) rotation
  297. is always 0, since two Euler rotations are sufficient to point in any given direction. */
  298. vector3d<T> getHorizontalAngle() const
  299. {
  300. vector3d<T> angle;
  301. // tmp avoids some precision troubles on some compilers when working with T=s32
  302. f64 tmp = (atan2((f64)X, (f64)Z) * RADTODEG64);
  303. angle.Y = (T)tmp;
  304. if (angle.Y < 0)
  305. angle.Y += 360;
  306. if (angle.Y >= 360)
  307. angle.Y -= 360;
  308. const f64 z1 = core::squareroot(X*X + Z*Z);
  309. tmp = (atan2((f64)z1, (f64)Y) * RADTODEG64 - 90.0);
  310. angle.X = (T)tmp;
  311. if (angle.X < 0)
  312. angle.X += 360;
  313. if (angle.X >= 360)
  314. angle.X -= 360;
  315. return angle;
  316. }
  317. //! Get the spherical coordinate angles
  318. /** This returns Euler degrees for the point represented by
  319. this vector. The calculation assumes the pole at (0,1,0) and
  320. returns the angles in X and Y.
  321. */
  322. vector3d<T> getSphericalCoordinateAngles() const
  323. {
  324. vector3d<T> angle;
  325. const f64 length = X*X + Y*Y + Z*Z;
  326. if (length)
  327. {
  328. if (X!=0)
  329. {
  330. angle.Y = (T)(atan2((f64)Z,(f64)X) * RADTODEG64);
  331. }
  332. else if (Z<0)
  333. angle.Y=180;
  334. angle.X = (T)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64);
  335. }
  336. return angle;
  337. }
  338. //! Builds a direction vector from (this) rotation vector.
  339. /** This vector is assumed to be a rotation vector composed of 3 Euler angle rotations, in degrees.
  340. The implementation performs the same calculations as using a matrix to do the rotation.
  341. \param[in] forwards The direction representing "forwards" which will be rotated by this vector.
  342. If you do not provide a direction, then the +Z axis (0, 0, 1) will be assumed to be forwards.
  343. \return A direction vector calculated by rotating the forwards direction by the 3 Euler angles
  344. (in degrees) represented by this vector. */
  345. vector3d<T> rotationToDirection(const vector3d<T> & forwards = vector3d<T>(0, 0, 1)) const
  346. {
  347. const f64 cr = cos( core::DEGTORAD64 * X );
  348. const f64 sr = sin( core::DEGTORAD64 * X );
  349. const f64 cp = cos( core::DEGTORAD64 * Y );
  350. const f64 sp = sin( core::DEGTORAD64 * Y );
  351. const f64 cy = cos( core::DEGTORAD64 * Z );
  352. const f64 sy = sin( core::DEGTORAD64 * Z );
  353. const f64 srsp = sr*sp;
  354. const f64 crsp = cr*sp;
  355. const f64 pseudoMatrix[] = {
  356. ( cp*cy ), ( cp*sy ), ( -sp ),
  357. ( srsp*cy-cr*sy ), ( srsp*sy+cr*cy ), ( sr*cp ),
  358. ( crsp*cy+sr*sy ), ( crsp*sy-sr*cy ), ( cr*cp )};
  359. return vector3d<T>(
  360. (T)(forwards.X * pseudoMatrix[0] +
  361. forwards.Y * pseudoMatrix[3] +
  362. forwards.Z * pseudoMatrix[6]),
  363. (T)(forwards.X * pseudoMatrix[1] +
  364. forwards.Y * pseudoMatrix[4] +
  365. forwards.Z * pseudoMatrix[7]),
  366. (T)(forwards.X * pseudoMatrix[2] +
  367. forwards.Y * pseudoMatrix[5] +
  368. forwards.Z * pseudoMatrix[8]));
  369. }
  370. //! Fills an array of 4 values with the vector data (usually floats).
  371. /** Useful for setting in shader constants for example. The fourth value
  372. will always be 0. */
  373. void getAs4Values(T* array) const
  374. {
  375. array[0] = X;
  376. array[1] = Y;
  377. array[2] = Z;
  378. array[3] = 0;
  379. }
  380. //! Fills an array of 3 values with the vector data (usually floats).
  381. /** Useful for setting in shader constants for example.*/
  382. void getAs3Values(T* array) const
  383. {
  384. array[0] = X;
  385. array[1] = Y;
  386. array[2] = Z;
  387. }
  388. //! X coordinate of the vector
  389. T X;
  390. //! Y coordinate of the vector
  391. T Y;
  392. //! Z coordinate of the vector
  393. T Z;
  394. };
  395. //! partial specialization for integer vectors
  396. // Implementer note: inline keyword needed due to template specialization for s32. Otherwise put specialization into a .cpp
  397. template <>
  398. inline vector3d<s32> vector3d<s32>::operator /(s32 val) const {return core::vector3d<s32>(X/val,Y/val,Z/val);}
  399. template <>
  400. inline vector3d<s32>& vector3d<s32>::operator /=(s32 val) {X/=val;Y/=val;Z/=val; return *this;}
  401. template <>
  402. inline vector3d<s32> vector3d<s32>::getSphericalCoordinateAngles() const
  403. {
  404. vector3d<s32> angle;
  405. const f64 length = X*X + Y*Y + Z*Z;
  406. if (length)
  407. {
  408. if (X!=0)
  409. {
  410. angle.Y = round32((f32)(atan2((f64)Z,(f64)X) * RADTODEG64));
  411. }
  412. else if (Z<0)
  413. angle.Y=180;
  414. angle.X = round32((f32)(acos(Y * core::reciprocal_squareroot(length)) * RADTODEG64));
  415. }
  416. return angle;
  417. }
  418. //! Typedef for a f32 3d vector.
  419. typedef vector3d<f32> vector3df;
  420. //! Typedef for an integer 3d vector.
  421. typedef vector3d<s32> vector3di;
  422. //! Function multiplying a scalar and a vector component-wise.
  423. template<class S, class T>
  424. vector3d<T> operator*(const S scalar, const vector3d<T>& vector) { return vector*scalar; }
  425. } // end namespace core
  426. } // end namespace irr
  427. #endif