Vec2.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. /**
  2. Copyright 2013 BlackBerry Inc.
  3. Copyright (c) 2014-2017 Chukong Technologies
  4. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. Original file from GamePlay3D: http://gameplay3d.org
  15. This file was modified to fit the cocos2d-x project
  16. */
  17. #ifndef MATH_VEC2_H
  18. #define MATH_VEC2_H
  19. #include <algorithm>
  20. #include <functional>
  21. #include <cmath>
  22. #include "math/CCMathBase.h"
  23. /**
  24. * @addtogroup base
  25. * @{
  26. */
  27. NS_CC_MATH_BEGIN
  28. /** Clamp a value between from and to.
  29. */
  30. inline float clampf(float value, float min_inclusive, float max_inclusive)
  31. {
  32. if (min_inclusive > max_inclusive) {
  33. std::swap(min_inclusive, max_inclusive);
  34. }
  35. return value < min_inclusive ? min_inclusive : value < max_inclusive? value : max_inclusive;
  36. }
  37. class Mat4;
  38. /**
  39. * Defines a 2-element floating point vector.
  40. */
  41. class CC_DLL Vec2
  42. {
  43. public:
  44. /**
  45. * The x coordinate.
  46. */
  47. float x;
  48. /**
  49. * The y coordinate.
  50. */
  51. float y;
  52. /**
  53. * Constructs a new vector initialized to all zeros.
  54. */
  55. Vec2();
  56. /**
  57. * Constructs a new vector initialized to the specified values.
  58. *
  59. * @param xx The x coordinate.
  60. * @param yy The y coordinate.
  61. */
  62. Vec2(float xx, float yy);
  63. /**
  64. * Constructs a new vector from the values in the specified array.
  65. *
  66. * @param array An array containing the elements of the vector in the order x, y.
  67. */
  68. Vec2(const float* array);
  69. /**
  70. * Constructs a vector that describes the direction between the specified points.
  71. *
  72. * @param p1 The first point.
  73. * @param p2 The second point.
  74. */
  75. Vec2(const Vec2& p1, const Vec2& p2);
  76. /**
  77. * Constructs a new vector that is a copy of the specified vector.
  78. *
  79. * @param copy The vector to copy.
  80. */
  81. Vec2(const Vec2& copy);
  82. /**
  83. * Destructor.
  84. */
  85. ~Vec2();
  86. /**
  87. * Indicates whether this vector contains all zeros.
  88. *
  89. * @return true if this vector contains all zeros, false otherwise.
  90. */
  91. inline bool isZero() const;
  92. /**
  93. * Indicates whether this vector contains all ones.
  94. *
  95. * @return true if this vector contains all ones, false otherwise.
  96. */
  97. inline bool isOne() const;
  98. /**
  99. * Returns the angle (in radians) between the specified vectors.
  100. *
  101. * @param v1 The first vector.
  102. * @param v2 The second vector.
  103. *
  104. * @return The angle between the two vectors (in radians).
  105. */
  106. static float angle(const Vec2& v1, const Vec2& v2);
  107. /**
  108. * Adds the elements of the specified vector to this one.
  109. *
  110. * @param v The vector to add.
  111. */
  112. inline void add(const Vec2& v);
  113. /**
  114. * Adds the specified vectors and stores the result in dst.
  115. *
  116. * @param v1 The first vector.
  117. * @param v2 The second vector.
  118. * @param dst A vector to store the result in.
  119. */
  120. static void add(const Vec2& v1, const Vec2& v2, Vec2* dst);
  121. /**
  122. * Clamps this vector within the specified range.
  123. *
  124. * @param min The minimum value.
  125. * @param max The maximum value.
  126. */
  127. void clamp(const Vec2& min, const Vec2& max);
  128. /**
  129. * Clamps the specified vector within the specified range and returns it in dst.
  130. *
  131. * @param v The vector to clamp.
  132. * @param min The minimum value.
  133. * @param max The maximum value.
  134. * @param dst A vector to store the result in.
  135. */
  136. static void clamp(const Vec2& v, const Vec2& min, const Vec2& max, Vec2* dst);
  137. /**
  138. * Returns the distance between this vector and v.
  139. *
  140. * @param v The other vector.
  141. *
  142. * @return The distance between this vector and v.
  143. *
  144. * @see distanceSquared
  145. */
  146. float distance(const Vec2& v) const;
  147. /**
  148. * Returns the squared distance between this vector and v.
  149. *
  150. * When it is not necessary to get the exact distance between
  151. * two vectors (for example, when simply comparing the
  152. * distance between different vectors), it is advised to use
  153. * this method instead of distance.
  154. *
  155. * @param v The other vector.
  156. *
  157. * @return The squared distance between this vector and v.
  158. *
  159. * @see distance
  160. */
  161. inline float distanceSquared(const Vec2& v) const;
  162. /**
  163. * Returns the dot product of this vector and the specified vector.
  164. *
  165. * @param v The vector to compute the dot product with.
  166. *
  167. * @return The dot product.
  168. */
  169. inline float dot(const Vec2& v) const;
  170. /**
  171. * Returns the dot product between the specified vectors.
  172. *
  173. * @param v1 The first vector.
  174. * @param v2 The second vector.
  175. *
  176. * @return The dot product between the vectors.
  177. */
  178. static float dot(const Vec2& v1, const Vec2& v2);
  179. /**
  180. * Computes the length of this vector.
  181. *
  182. * @return The length of the vector.
  183. *
  184. * @see lengthSquared
  185. */
  186. float length() const;
  187. /**
  188. * Returns the squared length of this vector.
  189. *
  190. * When it is not necessary to get the exact length of a
  191. * vector (for example, when simply comparing the lengths of
  192. * different vectors), it is advised to use this method
  193. * instead of length.
  194. *
  195. * @return The squared length of the vector.
  196. *
  197. * @see length
  198. */
  199. inline float lengthSquared() const;
  200. /**
  201. * Negates this vector.
  202. */
  203. inline void negate();
  204. /**
  205. * Normalizes this vector.
  206. *
  207. * This method normalizes this Vec2 so that it is of
  208. * unit length (in other words, the length of the vector
  209. * after calling this method will be 1.0f). If the vector
  210. * already has unit length or if the length of the vector
  211. * is zero, this method does nothing.
  212. *
  213. * @return This vector, after the normalization occurs.
  214. */
  215. void normalize();
  216. /**
  217. Get the normalized vector.
  218. */
  219. Vec2 getNormalized() const;
  220. /**
  221. * Scales all elements of this vector by the specified value.
  222. *
  223. * @param scalar The scalar value.
  224. */
  225. inline void scale(float scalar);
  226. /**
  227. * Scales each element of this vector by the matching component of scale.
  228. *
  229. * @param scale The vector to scale by.
  230. */
  231. inline void scale(const Vec2& scale);
  232. /**
  233. * Rotates this vector by angle (specified in radians) around the given point.
  234. *
  235. * @param point The point to rotate around.
  236. * @param angle The angle to rotate by (in radians).
  237. */
  238. void rotate(const Vec2& point, float angle);
  239. /**
  240. * Sets the elements of this vector to the specified values.
  241. *
  242. * @param xx The new x coordinate.
  243. * @param yy The new y coordinate.
  244. */
  245. inline void set(float xx, float yy);
  246. /**
  247. * Sets the elements of this vector from the values in the specified array.
  248. *
  249. * @param array An array containing the elements of the vector in the order x, y.
  250. */
  251. void set(const float* array);
  252. /**
  253. * Sets the elements of this vector to those in the specified vector.
  254. *
  255. * @param v The vector to copy.
  256. */
  257. inline void set(const Vec2& v);
  258. /**
  259. * Sets this vector to the directional vector between the specified points.
  260. *
  261. * @param p1 The first point.
  262. * @param p2 The second point.
  263. */
  264. inline void set(const Vec2& p1, const Vec2& p2);
  265. /**
  266. * Sets the elements of this vector to zero.
  267. */
  268. inline void setZero();
  269. /**
  270. * Subtracts this vector and the specified vector as (this - v)
  271. * and stores the result in this vector.
  272. *
  273. * @param v The vector to subtract.
  274. */
  275. inline void subtract(const Vec2& v);
  276. /**
  277. * Subtracts the specified vectors and stores the result in dst.
  278. * The resulting vector is computed as (v1 - v2).
  279. *
  280. * @param v1 The first vector.
  281. * @param v2 The second vector.
  282. * @param dst The destination vector.
  283. */
  284. static void subtract(const Vec2& v1, const Vec2& v2, Vec2* dst);
  285. /**
  286. * Updates this vector towards the given target using a smoothing function.
  287. * The given response time determines the amount of smoothing (lag). A longer
  288. * response time yields a smoother result and more lag. To force this vector to
  289. * follow the target closely, provide a response time that is very small relative
  290. * to the given elapsed time.
  291. *
  292. * @param target target value.
  293. * @param elapsedTime elapsed time between calls.
  294. * @param responseTime response time (in the same units as elapsedTime).
  295. */
  296. inline void smooth(const Vec2& target, float elapsedTime, float responseTime);
  297. /**
  298. * Calculates the sum of this vector with the given vector.
  299. *
  300. * Note: this does not modify this vector.
  301. *
  302. * @param v The vector to add.
  303. * @return The vector sum.
  304. */
  305. inline Vec2 operator+(const Vec2& v) const;
  306. /**
  307. * Adds the given vector to this vector.
  308. *
  309. * @param v The vector to add.
  310. * @return This vector, after the addition occurs.
  311. */
  312. inline Vec2& operator+=(const Vec2& v);
  313. /**
  314. * Calculates the sum of this vector with the given vector.
  315. *
  316. * Note: this does not modify this vector.
  317. *
  318. * @param v The vector to add.
  319. * @return The vector sum.
  320. */
  321. inline Vec2 operator-(const Vec2& v) const;
  322. /**
  323. * Subtracts the given vector from this vector.
  324. *
  325. * @param v The vector to subtract.
  326. * @return This vector, after the subtraction occurs.
  327. */
  328. inline Vec2& operator-=(const Vec2& v);
  329. /**
  330. * Calculates the negation of this vector.
  331. *
  332. * Note: this does not modify this vector.
  333. *
  334. * @return The negation of this vector.
  335. */
  336. inline Vec2 operator-() const;
  337. /**
  338. * Calculates the scalar product of this vector with the given value.
  339. *
  340. * Note: this does not modify this vector.
  341. *
  342. * @param s The value to scale by.
  343. * @return The scaled vector.
  344. */
  345. inline Vec2 operator*(float s) const;
  346. /**
  347. * Scales this vector by the given value.
  348. *
  349. * @param s The value to scale by.
  350. * @return This vector, after the scale occurs.
  351. */
  352. inline Vec2& operator*=(float s);
  353. /**
  354. * Returns the components of this vector divided by the given constant
  355. *
  356. * Note: this does not modify this vector.
  357. *
  358. * @param s the constant to divide this vector with
  359. * @return a smaller vector
  360. */
  361. inline Vec2 operator/(float s) const;
  362. /**
  363. * Determines if this vector is less than the given vector.
  364. *
  365. * @param v The vector to compare against.
  366. *
  367. * @return True if this vector is less than the given vector, false otherwise.
  368. */
  369. inline bool operator<(const Vec2& v) const;
  370. /**
  371. * Determines if this vector is greater than the given vector.
  372. *
  373. * @param v The vector to compare against.
  374. *
  375. * @return True if this vector is greater than the given vector, false otherwise.
  376. */
  377. inline bool operator>(const Vec2& v) const;
  378. /**
  379. * Determines if this vector is equal to the given vector.
  380. *
  381. * @param v The vector to compare against.
  382. *
  383. * @return True if this vector is equal to the given vector, false otherwise.
  384. */
  385. inline bool operator==(const Vec2& v) const;
  386. /**
  387. * Determines if this vector is not equal to the given vector.
  388. *
  389. * @param v The vector to compare against.
  390. *
  391. * @return True if this vector is not equal to the given vector, false otherwise.
  392. */
  393. inline bool operator!=(const Vec2& v) const;
  394. //code added compatible for Point
  395. public:
  396. /**
  397. * @js NA
  398. * @lua NA
  399. */
  400. inline void setPoint(float xx, float yy);
  401. /**
  402. * @js NA
  403. */
  404. bool equals(const Vec2& target) const;
  405. /** @returns if points have fuzzy equality which means equal with some degree of variance.
  406. @since v2.1.4
  407. * @js NA
  408. * @lua NA
  409. */
  410. bool fuzzyEquals(const Vec2& target, float variance) const;
  411. /** Calculates distance between point an origin
  412. @return float
  413. @since v2.1.4
  414. * @js NA
  415. * @lua NA
  416. */
  417. inline float getLength() const {
  418. return sqrtf(x*x + y*y);
  419. }
  420. /** Calculates the square length of a Vec2 (not calling sqrt() )
  421. @return float
  422. @since v2.1.4
  423. * @js NA
  424. * @lua NA
  425. */
  426. inline float getLengthSq() const {
  427. return dot(*this); //x*x + y*y;
  428. }
  429. /** Calculates the square distance between two points (not calling sqrt() )
  430. @return float
  431. @since v2.1.4
  432. * @js NA
  433. * @lua NA
  434. */
  435. inline float getDistanceSq(const Vec2& other) const {
  436. return (*this - other).getLengthSq();
  437. }
  438. /** Calculates the distance between two points
  439. @return float
  440. @since v2.1.4
  441. * @js NA
  442. * @lua NA
  443. */
  444. inline float getDistance(const Vec2& other) const {
  445. return (*this - other).getLength();
  446. }
  447. /** @returns the angle in radians between this vector and the x axis
  448. @since v2.1.4
  449. * @js NA
  450. * @lua NA
  451. */
  452. inline float getAngle() const {
  453. return atan2f(y, x);
  454. }
  455. /** @returns the angle in radians between two vector directions
  456. @since v2.1.4
  457. * @js NA
  458. * @lua NA
  459. */
  460. float getAngle(const Vec2& other) const;
  461. /** Calculates cross product of two points.
  462. @return float
  463. @since v2.1.4
  464. * @js NA
  465. * @lua NA
  466. */
  467. inline float cross(const Vec2& other) const {
  468. return x*other.y - y*other.x;
  469. }
  470. /** Calculates perpendicular of v, rotated 90 degrees counter-clockwise -- cross(v, perp(v)) >= 0
  471. @return Vec2
  472. @since v2.1.4
  473. * @js NA
  474. * @lua NA
  475. */
  476. inline Vec2 getPerp() const {
  477. return Vec2(-y, x);
  478. }
  479. /** Calculates midpoint between two points.
  480. @return Vec2
  481. @since v3.0
  482. * @js NA
  483. * @lua NA
  484. */
  485. inline Vec2 getMidpoint(const Vec2& other) const
  486. {
  487. return Vec2((x + other.x) / 2.0f, (y + other.y) / 2.0f);
  488. }
  489. /** Clamp a point between from and to.
  490. @since v3.0
  491. * @js NA
  492. * @lua NA
  493. */
  494. inline Vec2 getClampPoint(const Vec2& min_inclusive, const Vec2& max_inclusive) const
  495. {
  496. return Vec2(clampf(x,min_inclusive.x,max_inclusive.x), clampf(y, min_inclusive.y, max_inclusive.y));
  497. }
  498. /** Run a math operation function on each point component
  499. * absf, floorf, ceilf, roundf
  500. * any function that has the signature: float func(float);
  501. * For example: let's try to take the floor of x,y
  502. * p.compOp(floorf);
  503. @since v3.0
  504. * @js NA
  505. * @lua NA
  506. */
  507. inline Vec2 compOp(std::function<float(float)> function) const
  508. {
  509. return Vec2(function(x), function(y));
  510. }
  511. /** Calculates perpendicular of v, rotated 90 degrees clockwise -- cross(v, rperp(v)) <= 0
  512. @return Vec2
  513. @since v2.1.4
  514. * @js NA
  515. * @lua NA
  516. */
  517. inline Vec2 getRPerp() const {
  518. return Vec2(y, -x);
  519. }
  520. /** Calculates the projection of this over other.
  521. @return Vec2
  522. @since v2.1.4
  523. * @js NA
  524. * @lua NA
  525. */
  526. inline Vec2 project(const Vec2& other) const {
  527. return other * (dot(other)/other.dot(other));
  528. }
  529. /** Complex multiplication of two points ("rotates" two points).
  530. @return Vec2 vector with an angle of this.getAngle() + other.getAngle(),
  531. and a length of this.getLength() * other.getLength().
  532. @since v2.1.4
  533. * @js NA
  534. * @lua NA
  535. */
  536. inline Vec2 rotate(const Vec2& other) const {
  537. return Vec2(x*other.x - y*other.y, x*other.y + y*other.x);
  538. }
  539. /** Unrotates two points.
  540. @return Vec2 vector with an angle of this.getAngle() - other.getAngle(),
  541. and a length of this.getLength() * other.getLength().
  542. @since v2.1.4
  543. * @js NA
  544. * @lua NA
  545. */
  546. inline Vec2 unrotate(const Vec2& other) const {
  547. return Vec2(x*other.x + y*other.y, y*other.x - x*other.y);
  548. }
  549. /** Linear Interpolation between two points a and b
  550. @returns
  551. alpha == 0 ? a
  552. alpha == 1 ? b
  553. otherwise a value between a..b
  554. @since v2.1.4
  555. * @js NA
  556. * @lua NA
  557. */
  558. inline Vec2 lerp(const Vec2& other, float alpha) const {
  559. return *this * (1.f - alpha) + other * alpha;
  560. }
  561. /** Rotates a point counter clockwise by the angle around a pivot
  562. @param pivot is the pivot, naturally
  563. @param angle is the angle of rotation ccw in radians
  564. @returns the rotated point
  565. @since v2.1.4
  566. * @js NA
  567. * @lua NA
  568. */
  569. Vec2 rotateByAngle(const Vec2& pivot, float angle) const;
  570. /**
  571. * @js NA
  572. * @lua NA
  573. */
  574. static inline Vec2 forAngle(const float a)
  575. {
  576. return Vec2(cosf(a), sinf(a));
  577. }
  578. /** A general line-line intersection test
  579. @param A the startpoint for the first line L1 = (A - B)
  580. @param B the endpoint for the first line L1 = (A - B)
  581. @param C the startpoint for the second line L2 = (C - D)
  582. @param D the endpoint for the second line L2 = (C - D)
  583. @param S the range for a hitpoint in L1 (p = A + S*(B - A))
  584. @param T the range for a hitpoint in L2 (p = C + T*(D - C))
  585. @return whether these two lines intersects.
  586. Note that to truly test intersection for segments we have to make
  587. sure that S & T lie within [0..1] and for rays, make sure S & T > 0
  588. the hit point is C + T * (D - C);
  589. the hit point also is A + S * (B - A);
  590. @since 3.0
  591. * @js NA
  592. * @lua NA
  593. */
  594. static bool isLineIntersect(const Vec2& A, const Vec2& B,
  595. const Vec2& C, const Vec2& D,
  596. float *S = nullptr, float *T = nullptr);
  597. /**
  598. returns true if Line A-B overlap with segment C-D
  599. @since v3.0
  600. * @js NA
  601. * @lua NA
  602. */
  603. static bool isLineOverlap(const Vec2& A, const Vec2& B,
  604. const Vec2& C, const Vec2& D);
  605. /**
  606. returns true if Line A-B parallel with segment C-D
  607. @since v3.0
  608. * @js NA
  609. * @lua NA
  610. */
  611. static bool isLineParallel(const Vec2& A, const Vec2& B,
  612. const Vec2& C, const Vec2& D);
  613. /**
  614. returns true if Segment A-B overlap with segment C-D
  615. @since v3.0
  616. * @js NA
  617. * @lua NA
  618. */
  619. static bool isSegmentOverlap(const Vec2& A, const Vec2& B,
  620. const Vec2& C, const Vec2& D,
  621. Vec2* S = nullptr, Vec2* E = nullptr);
  622. /**
  623. returns true if Segment A-B intersects with segment C-D
  624. @since v3.0
  625. * @js NA
  626. * @lua NA
  627. */
  628. static bool isSegmentIntersect(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D);
  629. /**
  630. returns the intersection point of line A-B, C-D
  631. @since v3.0
  632. * @js NA
  633. * @lua NA
  634. */
  635. static Vec2 getIntersectPoint(const Vec2& A, const Vec2& B, const Vec2& C, const Vec2& D);
  636. /** equals to Vec2(0,0) */
  637. static const Vec2 ZERO;
  638. /** equals to Vec2(1,1) */
  639. static const Vec2 ONE;
  640. /** equals to Vec2(1,0) */
  641. static const Vec2 UNIT_X;
  642. /** equals to Vec2(0,1) */
  643. static const Vec2 UNIT_Y;
  644. /** equals to Vec2(0.5, 0.5) */
  645. static const Vec2 ANCHOR_MIDDLE;
  646. /** equals to Vec2(0, 0) */
  647. static const Vec2 ANCHOR_BOTTOM_LEFT;
  648. /** equals to Vec2(0, 1) */
  649. static const Vec2 ANCHOR_TOP_LEFT;
  650. /** equals to Vec2(1, 0) */
  651. static const Vec2 ANCHOR_BOTTOM_RIGHT;
  652. /** equals to Vec2(1, 1) */
  653. static const Vec2 ANCHOR_TOP_RIGHT;
  654. /** equals to Vec2(1, 0.5) */
  655. static const Vec2 ANCHOR_MIDDLE_RIGHT;
  656. /** equals to Vec2(0, 0.5) */
  657. static const Vec2 ANCHOR_MIDDLE_LEFT;
  658. /** equals to Vec2(0.5, 1) */
  659. static const Vec2 ANCHOR_MIDDLE_TOP;
  660. /** equals to Vec2(0.5, 0) */
  661. static const Vec2 ANCHOR_MIDDLE_BOTTOM;
  662. };
  663. /**
  664. * Calculates the scalar product of the given vector with the given value.
  665. *
  666. * @param x The value to scale by.
  667. * @param v The vector to scale.
  668. * @return The scaled vector.
  669. */
  670. inline Vec2 operator*(float x, const Vec2& v);
  671. typedef Vec2 Point;
  672. NS_CC_MATH_END
  673. /**
  674. end of base group
  675. @}
  676. */
  677. #include "math/Vec2.inl"
  678. #endif // MATH_VEC2_H