Vector2.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. import { clamp } from './MathUtils.js';
  2. /**
  3. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  4. * (labeled x and y), which can be used to represent a number of things, such as:
  5. *
  6. * - A point in 2D space (i.e. a position on a plane).
  7. * - A direction and length across a plane. In three.js the length will
  8. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  9. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  10. * - Any arbitrary ordered pair of numbers.
  11. *
  12. * There are other things a 2D vector can be used to represent, such as
  13. * momentum vectors, complex numbers and so on, however these are the most
  14. * common uses in three.js.
  15. *
  16. * Iterating through a vector instance will yield its components `(x, y)` in
  17. * the corresponding order.
  18. * ```js
  19. * const a = new THREE.Vector2( 0, 1 );
  20. *
  21. * //no arguments; will be initialised to (0, 0)
  22. * const b = new THREE.Vector2( );
  23. *
  24. * const d = a.distanceTo( b );
  25. * ```
  26. */
  27. class Vector2 {
  28. /**
  29. * Constructs a new 2D vector.
  30. *
  31. * @param {number} [x=0] - The x value of this vector.
  32. * @param {number} [y=0] - The y value of this vector.
  33. */
  34. constructor( x = 0, y = 0 ) {
  35. /**
  36. * This flag can be used for type testing.
  37. *
  38. * @type {boolean}
  39. * @readonly
  40. * @default true
  41. */
  42. Vector2.prototype.isVector2 = true;
  43. /**
  44. * The x value of this vector.
  45. *
  46. * @type {number}
  47. */
  48. this.x = x;
  49. /**
  50. * The y value of this vector.
  51. *
  52. * @type {number}
  53. */
  54. this.y = y;
  55. }
  56. /**
  57. * Alias for {@link Vector2#x}.
  58. *
  59. * @type {number}
  60. */
  61. get width() {
  62. return this.x;
  63. }
  64. set width( value ) {
  65. this.x = value;
  66. }
  67. /**
  68. * Alias for {@link Vector2#y}.
  69. *
  70. * @type {number}
  71. */
  72. get height() {
  73. return this.y;
  74. }
  75. set height( value ) {
  76. this.y = value;
  77. }
  78. /**
  79. * Sets the vector components.
  80. *
  81. * @param {number} x - The value of the x component.
  82. * @param {number} y - The value of the y component.
  83. * @return {Vector2} A reference to this vector.
  84. */
  85. set( x, y ) {
  86. this.x = x;
  87. this.y = y;
  88. return this;
  89. }
  90. /**
  91. * Sets the vector components to the same value.
  92. *
  93. * @param {number} scalar - The value to set for all vector components.
  94. * @return {Vector2} A reference to this vector.
  95. */
  96. setScalar( scalar ) {
  97. this.x = scalar;
  98. this.y = scalar;
  99. return this;
  100. }
  101. /**
  102. * Sets the vector's x component to the given value
  103. *
  104. * @param {number} x - The value to set.
  105. * @return {Vector2} A reference to this vector.
  106. */
  107. setX( x ) {
  108. this.x = x;
  109. return this;
  110. }
  111. /**
  112. * Sets the vector's y component to the given value
  113. *
  114. * @param {number} y - The value to set.
  115. * @return {Vector2} A reference to this vector.
  116. */
  117. setY( y ) {
  118. this.y = y;
  119. return this;
  120. }
  121. /**
  122. * Allows to set a vector component with an index.
  123. *
  124. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  125. * @param {number} value - The value to set.
  126. * @return {Vector2} A reference to this vector.
  127. */
  128. setComponent( index, value ) {
  129. switch ( index ) {
  130. case 0: this.x = value; break;
  131. case 1: this.y = value; break;
  132. default: throw new Error( 'index is out of range: ' + index );
  133. }
  134. return this;
  135. }
  136. /**
  137. * Returns the value of the vector component which matches the given index.
  138. *
  139. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  140. * @return {number} A vector component value.
  141. */
  142. getComponent( index ) {
  143. switch ( index ) {
  144. case 0: return this.x;
  145. case 1: return this.y;
  146. default: throw new Error( 'index is out of range: ' + index );
  147. }
  148. }
  149. /**
  150. * Returns a new vector with copied values from this instance.
  151. *
  152. * @return {Vector2} A clone of this instance.
  153. */
  154. clone() {
  155. return new this.constructor( this.x, this.y );
  156. }
  157. /**
  158. * Copies the values of the given vector to this instance.
  159. *
  160. * @param {Vector2} v - The vector to copy.
  161. * @return {Vector2} A reference to this vector.
  162. */
  163. copy( v ) {
  164. this.x = v.x;
  165. this.y = v.y;
  166. return this;
  167. }
  168. /**
  169. * Adds the given vector to this instance.
  170. *
  171. * @param {Vector2} v - The vector to add.
  172. * @return {Vector2} A reference to this vector.
  173. */
  174. add( v ) {
  175. this.x += v.x;
  176. this.y += v.y;
  177. return this;
  178. }
  179. /**
  180. * Adds the given scalar value to all components of this instance.
  181. *
  182. * @param {number} s - The scalar to add.
  183. * @return {Vector2} A reference to this vector.
  184. */
  185. addScalar( s ) {
  186. this.x += s;
  187. this.y += s;
  188. return this;
  189. }
  190. /**
  191. * Adds the given vectors and stores the result in this instance.
  192. *
  193. * @param {Vector2} a - The first vector.
  194. * @param {Vector2} b - The second vector.
  195. * @return {Vector2} A reference to this vector.
  196. */
  197. addVectors( a, b ) {
  198. this.x = a.x + b.x;
  199. this.y = a.y + b.y;
  200. return this;
  201. }
  202. /**
  203. * Adds the given vector scaled by the given factor to this instance.
  204. *
  205. * @param {Vector2} v - The vector.
  206. * @param {number} s - The factor that scales `v`.
  207. * @return {Vector2} A reference to this vector.
  208. */
  209. addScaledVector( v, s ) {
  210. this.x += v.x * s;
  211. this.y += v.y * s;
  212. return this;
  213. }
  214. /**
  215. * Subtracts the given vector from this instance.
  216. *
  217. * @param {Vector2} v - The vector to subtract.
  218. * @return {Vector2} A reference to this vector.
  219. */
  220. sub( v ) {
  221. this.x -= v.x;
  222. this.y -= v.y;
  223. return this;
  224. }
  225. /**
  226. * Subtracts the given scalar value from all components of this instance.
  227. *
  228. * @param {number} s - The scalar to subtract.
  229. * @return {Vector2} A reference to this vector.
  230. */
  231. subScalar( s ) {
  232. this.x -= s;
  233. this.y -= s;
  234. return this;
  235. }
  236. /**
  237. * Subtracts the given vectors and stores the result in this instance.
  238. *
  239. * @param {Vector2} a - The first vector.
  240. * @param {Vector2} b - The second vector.
  241. * @return {Vector2} A reference to this vector.
  242. */
  243. subVectors( a, b ) {
  244. this.x = a.x - b.x;
  245. this.y = a.y - b.y;
  246. return this;
  247. }
  248. /**
  249. * Multiplies the given vector with this instance.
  250. *
  251. * @param {Vector2} v - The vector to multiply.
  252. * @return {Vector2} A reference to this vector.
  253. */
  254. multiply( v ) {
  255. this.x *= v.x;
  256. this.y *= v.y;
  257. return this;
  258. }
  259. /**
  260. * Multiplies the given scalar value with all components of this instance.
  261. *
  262. * @param {number} scalar - The scalar to multiply.
  263. * @return {Vector2} A reference to this vector.
  264. */
  265. multiplyScalar( scalar ) {
  266. this.x *= scalar;
  267. this.y *= scalar;
  268. return this;
  269. }
  270. /**
  271. * Divides this instance by the given vector.
  272. *
  273. * @param {Vector2} v - The vector to divide.
  274. * @return {Vector2} A reference to this vector.
  275. */
  276. divide( v ) {
  277. this.x /= v.x;
  278. this.y /= v.y;
  279. return this;
  280. }
  281. /**
  282. * Divides this vector by the given scalar.
  283. *
  284. * @param {number} scalar - The scalar to divide.
  285. * @return {Vector2} A reference to this vector.
  286. */
  287. divideScalar( scalar ) {
  288. return this.multiplyScalar( 1 / scalar );
  289. }
  290. /**
  291. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  292. * the given 3x3 matrix.
  293. *
  294. * @param {Matrix3} m - The matrix to apply.
  295. * @return {Vector2} A reference to this vector.
  296. */
  297. applyMatrix3( m ) {
  298. const x = this.x, y = this.y;
  299. const e = m.elements;
  300. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  301. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  302. return this;
  303. }
  304. /**
  305. * If this vector's x or y value is greater than the given vector's x or y
  306. * value, replace that value with the corresponding min value.
  307. *
  308. * @param {Vector2} v - The vector.
  309. * @return {Vector2} A reference to this vector.
  310. */
  311. min( v ) {
  312. this.x = Math.min( this.x, v.x );
  313. this.y = Math.min( this.y, v.y );
  314. return this;
  315. }
  316. /**
  317. * If this vector's x or y value is less than the given vector's x or y
  318. * value, replace that value with the corresponding max value.
  319. *
  320. * @param {Vector2} v - The vector.
  321. * @return {Vector2} A reference to this vector.
  322. */
  323. max( v ) {
  324. this.x = Math.max( this.x, v.x );
  325. this.y = Math.max( this.y, v.y );
  326. return this;
  327. }
  328. /**
  329. * If this vector's x or y value is greater than the max vector's x or y
  330. * value, it is replaced by the corresponding value.
  331. * If this vector's x or y value is less than the min vector's x or y value,
  332. * it is replaced by the corresponding value.
  333. *
  334. * @param {Vector2} min - The minimum x and y values.
  335. * @param {Vector2} max - The maximum x and y values in the desired range.
  336. * @return {Vector2} A reference to this vector.
  337. */
  338. clamp( min, max ) {
  339. // assumes min < max, componentwise
  340. this.x = clamp( this.x, min.x, max.x );
  341. this.y = clamp( this.y, min.y, max.y );
  342. return this;
  343. }
  344. /**
  345. * If this vector's x or y values are greater than the max value, they are
  346. * replaced by the max value.
  347. * If this vector's x or y values are less than the min value, they are
  348. * replaced by the min value.
  349. *
  350. * @param {number} minVal - The minimum value the components will be clamped to.
  351. * @param {number} maxVal - The maximum value the components will be clamped to.
  352. * @return {Vector2} A reference to this vector.
  353. */
  354. clampScalar( minVal, maxVal ) {
  355. this.x = clamp( this.x, minVal, maxVal );
  356. this.y = clamp( this.y, minVal, maxVal );
  357. return this;
  358. }
  359. /**
  360. * If this vector's length is greater than the max value, it is replaced by
  361. * the max value.
  362. * If this vector's length is less than the min value, it is replaced by the
  363. * min value.
  364. *
  365. * @param {number} min - The minimum value the vector length will be clamped to.
  366. * @param {number} max - The maximum value the vector length will be clamped to.
  367. * @return {Vector2} A reference to this vector.
  368. */
  369. clampLength( min, max ) {
  370. const length = this.length();
  371. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  372. }
  373. /**
  374. * The components of this vector are rounded down to the nearest integer value.
  375. *
  376. * @return {Vector2} A reference to this vector.
  377. */
  378. floor() {
  379. this.x = Math.floor( this.x );
  380. this.y = Math.floor( this.y );
  381. return this;
  382. }
  383. /**
  384. * The components of this vector are rounded up to the nearest integer value.
  385. *
  386. * @return {Vector2} A reference to this vector.
  387. */
  388. ceil() {
  389. this.x = Math.ceil( this.x );
  390. this.y = Math.ceil( this.y );
  391. return this;
  392. }
  393. /**
  394. * The components of this vector are rounded to the nearest integer value
  395. *
  396. * @return {Vector2} A reference to this vector.
  397. */
  398. round() {
  399. this.x = Math.round( this.x );
  400. this.y = Math.round( this.y );
  401. return this;
  402. }
  403. /**
  404. * The components of this vector are rounded towards zero (up if negative,
  405. * down if positive) to an integer value.
  406. *
  407. * @return {Vector2} A reference to this vector.
  408. */
  409. roundToZero() {
  410. this.x = Math.trunc( this.x );
  411. this.y = Math.trunc( this.y );
  412. return this;
  413. }
  414. /**
  415. * Inverts this vector - i.e. sets x = -x and y = -y.
  416. *
  417. * @return {Vector2} A reference to this vector.
  418. */
  419. negate() {
  420. this.x = - this.x;
  421. this.y = - this.y;
  422. return this;
  423. }
  424. /**
  425. * Calculates the dot product of the given vector with this instance.
  426. *
  427. * @param {Vector2} v - The vector to compute the dot product with.
  428. * @return {number} The result of the dot product.
  429. */
  430. dot( v ) {
  431. return this.x * v.x + this.y * v.y;
  432. }
  433. /**
  434. * Calculates the cross product of the given vector with this instance.
  435. *
  436. * @param {Vector2} v - The vector to compute the cross product with.
  437. * @return {number} The result of the cross product.
  438. */
  439. cross( v ) {
  440. return this.x * v.y - this.y * v.x;
  441. }
  442. /**
  443. * Computes the square of the Euclidean length (straight-line length) from
  444. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  445. * compare the length squared instead as it is slightly more efficient to calculate.
  446. *
  447. * @return {number} The square length of this vector.
  448. */
  449. lengthSq() {
  450. return this.x * this.x + this.y * this.y;
  451. }
  452. /**
  453. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  454. *
  455. * @return {number} The length of this vector.
  456. */
  457. length() {
  458. return Math.sqrt( this.x * this.x + this.y * this.y );
  459. }
  460. /**
  461. * Computes the Manhattan length of this vector.
  462. *
  463. * @return {number} The length of this vector.
  464. */
  465. manhattanLength() {
  466. return Math.abs( this.x ) + Math.abs( this.y );
  467. }
  468. /**
  469. * Converts this vector to a unit vector - that is, sets it equal to a vector
  470. * with the same direction as this one, but with a vector length of `1`.
  471. *
  472. * @return {Vector2} A reference to this vector.
  473. */
  474. normalize() {
  475. return this.divideScalar( this.length() || 1 );
  476. }
  477. /**
  478. * Computes the angle in radians of this vector with respect to the positive x-axis.
  479. *
  480. * @return {number} The angle in radians.
  481. */
  482. angle() {
  483. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  484. return angle;
  485. }
  486. /**
  487. * Returns the angle between the given vector and this instance in radians.
  488. *
  489. * @param {Vector2} v - The vector to compute the angle with.
  490. * @return {number} The angle in radians.
  491. */
  492. angleTo( v ) {
  493. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  494. if ( denominator === 0 ) return Math.PI / 2;
  495. const theta = this.dot( v ) / denominator;
  496. // clamp, to handle numerical problems
  497. return Math.acos( clamp( theta, - 1, 1 ) );
  498. }
  499. /**
  500. * Computes the distance from the given vector to this instance.
  501. *
  502. * @param {Vector2} v - The vector to compute the distance to.
  503. * @return {number} The distance.
  504. */
  505. distanceTo( v ) {
  506. return Math.sqrt( this.distanceToSquared( v ) );
  507. }
  508. /**
  509. * Computes the squared distance from the given vector to this instance.
  510. * If you are just comparing the distance with another distance, you should compare
  511. * the distance squared instead as it is slightly more efficient to calculate.
  512. *
  513. * @param {Vector2} v - The vector to compute the squared distance to.
  514. * @return {number} The squared distance.
  515. */
  516. distanceToSquared( v ) {
  517. const dx = this.x - v.x, dy = this.y - v.y;
  518. return dx * dx + dy * dy;
  519. }
  520. /**
  521. * Computes the Manhattan distance from the given vector to this instance.
  522. *
  523. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  524. * @return {number} The Manhattan distance.
  525. */
  526. manhattanDistanceTo( v ) {
  527. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  528. }
  529. /**
  530. * Sets this vector to a vector with the same direction as this one, but
  531. * with the specified length.
  532. *
  533. * @param {number} length - The new length of this vector.
  534. * @return {Vector2} A reference to this vector.
  535. */
  536. setLength( length ) {
  537. return this.normalize().multiplyScalar( length );
  538. }
  539. /**
  540. * Linearly interpolates between the given vector and this instance, where
  541. * alpha is the percent distance along the line - alpha = 0 will be this
  542. * vector, and alpha = 1 will be the given one.
  543. *
  544. * @param {Vector2} v - The vector to interpolate towards.
  545. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  546. * @return {Vector2} A reference to this vector.
  547. */
  548. lerp( v, alpha ) {
  549. this.x += ( v.x - this.x ) * alpha;
  550. this.y += ( v.y - this.y ) * alpha;
  551. return this;
  552. }
  553. /**
  554. * Linearly interpolates between the given vectors, where alpha is the percent
  555. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  556. * be the second one. The result is stored in this instance.
  557. *
  558. * @param {Vector2} v1 - The first vector.
  559. * @param {Vector2} v2 - The second vector.
  560. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  561. * @return {Vector2} A reference to this vector.
  562. */
  563. lerpVectors( v1, v2, alpha ) {
  564. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  565. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  566. return this;
  567. }
  568. /**
  569. * Returns `true` if this vector is equal with the given one.
  570. *
  571. * @param {Vector2} v - The vector to test for equality.
  572. * @return {boolean} Whether this vector is equal with the given one.
  573. */
  574. equals( v ) {
  575. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  576. }
  577. /**
  578. * Sets this vector's x value to be `array[ offset ]` and y
  579. * value to be `array[ offset + 1 ]`.
  580. *
  581. * @param {Array<number>} array - An array holding the vector component values.
  582. * @param {number} [offset=0] - The offset into the array.
  583. * @return {Vector2} A reference to this vector.
  584. */
  585. fromArray( array, offset = 0 ) {
  586. this.x = array[ offset ];
  587. this.y = array[ offset + 1 ];
  588. return this;
  589. }
  590. /**
  591. * Writes the components of this vector to the given array. If no array is provided,
  592. * the method returns a new instance.
  593. *
  594. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  595. * @param {number} [offset=0] - Index of the first element in the array.
  596. * @return {Array<number>} The vector components.
  597. */
  598. toArray( array = [], offset = 0 ) {
  599. array[ offset ] = this.x;
  600. array[ offset + 1 ] = this.y;
  601. return array;
  602. }
  603. /**
  604. * Sets the components of this vector from the given buffer attribute.
  605. *
  606. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  607. * @param {number} index - The index into the attribute.
  608. * @return {Vector2} A reference to this vector.
  609. */
  610. fromBufferAttribute( attribute, index ) {
  611. this.x = attribute.getX( index );
  612. this.y = attribute.getY( index );
  613. return this;
  614. }
  615. /**
  616. * Rotates this vector around the given center by the given angle.
  617. *
  618. * @param {Vector2} center - The point around which to rotate.
  619. * @param {number} angle - The angle to rotate, in radians.
  620. * @return {Vector2} A reference to this vector.
  621. */
  622. rotateAround( center, angle ) {
  623. const c = Math.cos( angle ), s = Math.sin( angle );
  624. const x = this.x - center.x;
  625. const y = this.y - center.y;
  626. this.x = x * c - y * s + center.x;
  627. this.y = x * s + y * c + center.y;
  628. return this;
  629. }
  630. /**
  631. * Sets each component of this vector to a pseudo-random value between `0` and
  632. * `1`, excluding `1`.
  633. *
  634. * @return {Vector2} A reference to this vector.
  635. */
  636. random() {
  637. this.x = Math.random();
  638. this.y = Math.random();
  639. return this;
  640. }
  641. *[ Symbol.iterator ]() {
  642. yield this.x;
  643. yield this.y;
  644. }
  645. }
  646. export { Vector2 };