math.path.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. import { DeepImmutable, Nullable } from '../types';
  2. import { Scalar } from './math.scalar';
  3. import { Vector2, Vector3 } from './math';
  4. import { Epsilon } from './math.constants';
  5. /**
  6. * Defines potential orientation for back face culling
  7. */
  8. export enum Orientation {
  9. /**
  10. * Clockwise
  11. */
  12. CW = 0,
  13. /** Counter clockwise */
  14. CCW = 1
  15. }
  16. /** Class used to represent a Bezier curve */
  17. export class BezierCurve {
  18. /**
  19. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  20. * @param t defines the time
  21. * @param x1 defines the left coordinate on X axis
  22. * @param y1 defines the left coordinate on Y axis
  23. * @param x2 defines the right coordinate on X axis
  24. * @param y2 defines the right coordinate on Y axis
  25. * @returns the interpolated value
  26. */
  27. public static Interpolate(t: number, x1: number, y1: number, x2: number, y2: number): number {
  28. // Extract X (which is equal to time here)
  29. var f0 = 1 - 3 * x2 + 3 * x1;
  30. var f1 = 3 * x2 - 6 * x1;
  31. var f2 = 3 * x1;
  32. var refinedT = t;
  33. for (var i = 0; i < 5; i++) {
  34. var refinedT2 = refinedT * refinedT;
  35. var refinedT3 = refinedT2 * refinedT;
  36. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  37. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  38. refinedT -= (x - t) * slope;
  39. refinedT = Math.min(1, Math.max(0, refinedT));
  40. }
  41. // Resolve cubic bezier for the given x
  42. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  43. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  44. Math.pow(refinedT, 3);
  45. }
  46. }
  47. /**
  48. * Defines angle representation
  49. */
  50. export class Angle {
  51. private _radians: number;
  52. /**
  53. * Creates an Angle object of "radians" radians (float).
  54. * @param radians the angle in radians
  55. */
  56. constructor(radians: number) {
  57. this._radians = radians;
  58. if (this._radians < 0.0) { this._radians += (2.0 * Math.PI); }
  59. }
  60. /**
  61. * Get value in degrees
  62. * @returns the Angle value in degrees (float)
  63. */
  64. public degrees() {
  65. return this._radians * 180.0 / Math.PI;
  66. }
  67. /**
  68. * Get value in radians
  69. * @returns the Angle value in radians (float)
  70. */
  71. public radians() {
  72. return this._radians;
  73. }
  74. /**
  75. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  76. * @param a defines first vector
  77. * @param b defines second vector
  78. * @returns a new Angle
  79. */
  80. public static BetweenTwoPoints(a: DeepImmutable<Vector2>, b: DeepImmutable<Vector2>): Angle {
  81. var delta = b.subtract(a);
  82. var theta = Math.atan2(delta.y, delta.x);
  83. return new Angle(theta);
  84. }
  85. /**
  86. * Gets a new Angle object from the given float in radians
  87. * @param radians defines the angle value in radians
  88. * @returns a new Angle
  89. */
  90. public static FromRadians(radians: number): Angle {
  91. return new Angle(radians);
  92. }
  93. /**
  94. * Gets a new Angle object from the given float in degrees
  95. * @param degrees defines the angle value in degrees
  96. * @returns a new Angle
  97. */
  98. public static FromDegrees(degrees: number): Angle {
  99. return new Angle(degrees * Math.PI / 180.0);
  100. }
  101. }
  102. /**
  103. * This represents an arc in a 2d space.
  104. */
  105. export class Arc2 {
  106. /**
  107. * Defines the center point of the arc.
  108. */
  109. public centerPoint: Vector2;
  110. /**
  111. * Defines the radius of the arc.
  112. */
  113. public radius: number;
  114. /**
  115. * Defines the angle of the arc (from mid point to end point).
  116. */
  117. public angle: Angle;
  118. /**
  119. * Defines the start angle of the arc (from start point to middle point).
  120. */
  121. public startAngle: Angle;
  122. /**
  123. * Defines the orientation of the arc (clock wise/counter clock wise).
  124. */
  125. public orientation: Orientation;
  126. /**
  127. * Creates an Arc object from the three given points : start, middle and end.
  128. * @param startPoint Defines the start point of the arc
  129. * @param midPoint Defines the midlle point of the arc
  130. * @param endPoint Defines the end point of the arc
  131. */
  132. constructor(
  133. /** Defines the start point of the arc */
  134. public startPoint: Vector2,
  135. /** Defines the mid point of the arc */
  136. public midPoint: Vector2,
  137. /** Defines the end point of the arc */
  138. public endPoint: Vector2) {
  139. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  140. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  141. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  142. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  143. this.centerPoint = new Vector2(
  144. (startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det,
  145. ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det
  146. );
  147. this.radius = this.centerPoint.subtract(this.startPoint).length();
  148. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  149. var a1 = this.startAngle.degrees();
  150. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  151. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  152. // angles correction
  153. if (a2 - a1 > +180.0) { a2 -= 360.0; }
  154. if (a2 - a1 < -180.0) { a2 += 360.0; }
  155. if (a3 - a2 > +180.0) { a3 -= 360.0; }
  156. if (a3 - a2 < -180.0) { a3 += 360.0; }
  157. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  158. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  159. }
  160. }
  161. /**
  162. * Represents a 2D path made up of multiple 2D points
  163. */
  164. export class Path2 {
  165. private _points = new Array<Vector2>();
  166. private _length = 0.0;
  167. /**
  168. * If the path start and end point are the same
  169. */
  170. public closed = false;
  171. /**
  172. * Creates a Path2 object from the starting 2D coordinates x and y.
  173. * @param x the starting points x value
  174. * @param y the starting points y value
  175. */
  176. constructor(x: number, y: number) {
  177. this._points.push(new Vector2(x, y));
  178. }
  179. /**
  180. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  181. * @param x the added points x value
  182. * @param y the added points y value
  183. * @returns the updated Path2.
  184. */
  185. public addLineTo(x: number, y: number): Path2 {
  186. if (this.closed) {
  187. return this;
  188. }
  189. var newPoint = new Vector2(x, y);
  190. var previousPoint = this._points[this._points.length - 1];
  191. this._points.push(newPoint);
  192. this._length += newPoint.subtract(previousPoint).length();
  193. return this;
  194. }
  195. /**
  196. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  197. * @param midX middle point x value
  198. * @param midY middle point y value
  199. * @param endX end point x value
  200. * @param endY end point y value
  201. * @param numberOfSegments (default: 36)
  202. * @returns the updated Path2.
  203. */
  204. public addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments = 36): Path2 {
  205. if (this.closed) {
  206. return this;
  207. }
  208. var startPoint = this._points[this._points.length - 1];
  209. var midPoint = new Vector2(midX, midY);
  210. var endPoint = new Vector2(endX, endY);
  211. var arc = new Arc2(startPoint, midPoint, endPoint);
  212. var increment = arc.angle.radians() / numberOfSegments;
  213. if (arc.orientation === Orientation.CW) { increment *= -1; }
  214. var currentAngle = arc.startAngle.radians() + increment;
  215. for (var i = 0; i < numberOfSegments; i++) {
  216. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  217. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  218. this.addLineTo(x, y);
  219. currentAngle += increment;
  220. }
  221. return this;
  222. }
  223. /**
  224. * Closes the Path2.
  225. * @returns the Path2.
  226. */
  227. public close(): Path2 {
  228. this.closed = true;
  229. return this;
  230. }
  231. /**
  232. * Gets the sum of the distance between each sequential point in the path
  233. * @returns the Path2 total length (float).
  234. */
  235. public length(): number {
  236. var result = this._length;
  237. if (!this.closed) {
  238. var lastPoint = this._points[this._points.length - 1];
  239. var firstPoint = this._points[0];
  240. result += (firstPoint.subtract(lastPoint).length());
  241. }
  242. return result;
  243. }
  244. /**
  245. * Gets the points which construct the path
  246. * @returns the Path2 internal array of points.
  247. */
  248. public getPoints(): Vector2[] {
  249. return this._points;
  250. }
  251. /**
  252. * Retreives the point at the distance aways from the starting point
  253. * @param normalizedLengthPosition the length along the path to retreive the point from
  254. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  255. */
  256. public getPointAtLengthPosition(normalizedLengthPosition: number): Vector2 {
  257. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  258. return Vector2.Zero();
  259. }
  260. var lengthPosition = normalizedLengthPosition * this.length();
  261. var previousOffset = 0;
  262. for (var i = 0; i < this._points.length; i++) {
  263. var j = (i + 1) % this._points.length;
  264. var a = this._points[i];
  265. var b = this._points[j];
  266. var bToA = b.subtract(a);
  267. var nextOffset = (bToA.length() + previousOffset);
  268. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  269. var dir = bToA.normalize();
  270. var localOffset = lengthPosition - previousOffset;
  271. return new Vector2(
  272. a.x + (dir.x * localOffset),
  273. a.y + (dir.y * localOffset)
  274. );
  275. }
  276. previousOffset = nextOffset;
  277. }
  278. return Vector2.Zero();
  279. }
  280. /**
  281. * Creates a new path starting from an x and y position
  282. * @param x starting x value
  283. * @param y starting y value
  284. * @returns a new Path2 starting at the coordinates (x, y).
  285. */
  286. public static StartingAt(x: number, y: number): Path2 {
  287. return new Path2(x, y);
  288. }
  289. }
  290. /**
  291. * Represents a 3D path made up of multiple 3D points
  292. */
  293. export class Path3D {
  294. private _curve = new Array<Vector3>();
  295. private _distances = new Array<number>();
  296. private _tangents = new Array<Vector3>();
  297. private _normals = new Array<Vector3>();
  298. private _binormals = new Array<Vector3>();
  299. private _raw: boolean;
  300. /**
  301. * new Path3D(path, normal, raw)
  302. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  303. * please read the description in the tutorial : https://doc.babylonjs.com/how_to/how_to_use_path3d
  304. * @param path an array of Vector3, the curve axis of the Path3D
  305. * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  306. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  307. */
  308. constructor(
  309. /**
  310. * an array of Vector3, the curve axis of the Path3D
  311. */
  312. public path: Vector3[],
  313. firstNormal: Nullable<Vector3> = null,
  314. raw?: boolean
  315. ) {
  316. for (var p = 0; p < path.length; p++) {
  317. this._curve[p] = path[p].clone(); // hard copy
  318. }
  319. this._raw = raw || false;
  320. this._compute(firstNormal);
  321. }
  322. /**
  323. * Returns the Path3D array of successive Vector3 designing its curve.
  324. * @returns the Path3D array of successive Vector3 designing its curve.
  325. */
  326. public getCurve(): Vector3[] {
  327. return this._curve;
  328. }
  329. /**
  330. * Returns an array populated with tangent vectors on each Path3D curve point.
  331. * @returns an array populated with tangent vectors on each Path3D curve point.
  332. */
  333. public getTangents(): Vector3[] {
  334. return this._tangents;
  335. }
  336. /**
  337. * Returns an array populated with normal vectors on each Path3D curve point.
  338. * @returns an array populated with normal vectors on each Path3D curve point.
  339. */
  340. public getNormals(): Vector3[] {
  341. return this._normals;
  342. }
  343. /**
  344. * Returns an array populated with binormal vectors on each Path3D curve point.
  345. * @returns an array populated with binormal vectors on each Path3D curve point.
  346. */
  347. public getBinormals(): Vector3[] {
  348. return this._binormals;
  349. }
  350. /**
  351. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  352. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  353. */
  354. public getDistances(): number[] {
  355. return this._distances;
  356. }
  357. /**
  358. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  359. * @param path path which all values are copied into the curves points
  360. * @param firstNormal which should be projected onto the curve
  361. * @returns the same object updated.
  362. */
  363. public update(path: Vector3[], firstNormal: Nullable<Vector3> = null): Path3D {
  364. for (var p = 0; p < path.length; p++) {
  365. this._curve[p].x = path[p].x;
  366. this._curve[p].y = path[p].y;
  367. this._curve[p].z = path[p].z;
  368. }
  369. this._compute(firstNormal);
  370. return this;
  371. }
  372. // private function compute() : computes tangents, normals and binormals
  373. private _compute(firstNormal: Nullable<Vector3>): void {
  374. var l = this._curve.length;
  375. // first and last tangents
  376. this._tangents[0] = this._getFirstNonNullVector(0);
  377. if (!this._raw) {
  378. this._tangents[0].normalize();
  379. }
  380. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  381. if (!this._raw) {
  382. this._tangents[l - 1].normalize();
  383. }
  384. // normals and binormals at first point : arbitrary vector with _normalVector()
  385. var tg0 = this._tangents[0];
  386. var pp0 = this._normalVector(tg0, firstNormal);
  387. this._normals[0] = pp0;
  388. if (!this._raw) {
  389. this._normals[0].normalize();
  390. }
  391. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  392. if (!this._raw) {
  393. this._binormals[0].normalize();
  394. }
  395. this._distances[0] = 0.0;
  396. // normals and binormals : next points
  397. var prev: Vector3; // previous vector (segment)
  398. var cur: Vector3; // current vector (segment)
  399. var curTang: Vector3; // current tangent
  400. // previous normal
  401. var prevBinor: Vector3; // previous binormal
  402. for (var i = 1; i < l; i++) {
  403. // tangents
  404. prev = this._getLastNonNullVector(i);
  405. if (i < l - 1) {
  406. cur = this._getFirstNonNullVector(i);
  407. this._tangents[i] = prev.add(cur);
  408. this._tangents[i].normalize();
  409. }
  410. this._distances[i] = this._distances[i - 1] + prev.length();
  411. // normals and binormals
  412. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  413. curTang = this._tangents[i];
  414. prevBinor = this._binormals[i - 1];
  415. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  416. if (!this._raw) {
  417. this._normals[i].normalize();
  418. }
  419. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  420. if (!this._raw) {
  421. this._binormals[i].normalize();
  422. }
  423. }
  424. }
  425. // private function getFirstNonNullVector(index)
  426. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  427. private _getFirstNonNullVector(index: number): Vector3 {
  428. var i = 1;
  429. var nNVector: Vector3 = this._curve[index + i].subtract(this._curve[index]);
  430. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  431. i++;
  432. nNVector = this._curve[index + i].subtract(this._curve[index]);
  433. }
  434. return nNVector;
  435. }
  436. // private function getLastNonNullVector(index)
  437. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  438. private _getLastNonNullVector(index: number): Vector3 {
  439. var i = 1;
  440. var nLVector: Vector3 = this._curve[index].subtract(this._curve[index - i]);
  441. while (nLVector.length() === 0 && index > i + 1) {
  442. i++;
  443. nLVector = this._curve[index].subtract(this._curve[index - i]);
  444. }
  445. return nLVector;
  446. }
  447. // private function normalVector(v0, vt, va) :
  448. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  449. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  450. private _normalVector(vt: Vector3, va: Nullable<Vector3>): Vector3 {
  451. var normal0: Vector3;
  452. var tgl = vt.length();
  453. if (tgl === 0.0) {
  454. tgl = 1.0;
  455. }
  456. if (va === undefined || va === null) {
  457. var point: Vector3;
  458. if (!Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, Epsilon)) { // search for a point in the plane
  459. point = new Vector3(0.0, -1.0, 0.0);
  460. }
  461. else if (!Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, Epsilon)) {
  462. point = new Vector3(1.0, 0.0, 0.0);
  463. }
  464. else if (!Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, Epsilon)) {
  465. point = new Vector3(0.0, 0.0, 1.0);
  466. }
  467. else {
  468. point = Vector3.Zero();
  469. }
  470. normal0 = Vector3.Cross(vt, point);
  471. }
  472. else {
  473. normal0 = Vector3.Cross(vt, va);
  474. Vector3.CrossToRef(normal0, vt, normal0);
  475. }
  476. normal0.normalize();
  477. return normal0;
  478. }
  479. }
  480. /**
  481. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  482. * A Curve3 is designed from a series of successive Vector3.
  483. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  484. */
  485. export class Curve3 {
  486. private _points: Vector3[];
  487. private _length: number = 0.0;
  488. /**
  489. * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#quadratic-bezier-curve
  490. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  491. * @param v1 (Vector3) the control point
  492. * @param v2 (Vector3) the end point of the Quadratic Bezier
  493. * @param nbPoints (integer) the wanted number of points in the curve
  494. * @returns the created Curve3
  495. */
  496. public static CreateQuadraticBezier(v0: DeepImmutable<Vector3>, v1: DeepImmutable<Vector3>, v2: DeepImmutable<Vector3>, nbPoints: number): Curve3 {
  497. nbPoints = nbPoints > 2 ? nbPoints : 3;
  498. var bez = new Array<Vector3>();
  499. var equation = (t: number, val0: number, val1: number, val2: number) => {
  500. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  501. return res;
  502. };
  503. for (var i = 0; i <= nbPoints; i++) {
  504. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  505. }
  506. return new Curve3(bez);
  507. }
  508. /**
  509. * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#cubic-bezier-curve
  510. * @param v0 (Vector3) the origin point of the Cubic Bezier
  511. * @param v1 (Vector3) the first control point
  512. * @param v2 (Vector3) the second control point
  513. * @param v3 (Vector3) the end point of the Cubic Bezier
  514. * @param nbPoints (integer) the wanted number of points in the curve
  515. * @returns the created Curve3
  516. */
  517. public static CreateCubicBezier(v0: DeepImmutable<Vector3>, v1: DeepImmutable<Vector3>, v2: DeepImmutable<Vector3>, v3: DeepImmutable<Vector3>, nbPoints: number): Curve3 {
  518. nbPoints = nbPoints > 3 ? nbPoints : 4;
  519. var bez = new Array<Vector3>();
  520. var equation = (t: number, val0: number, val1: number, val2: number, val3: number) => {
  521. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  522. return res;
  523. };
  524. for (var i = 0; i <= nbPoints; i++) {
  525. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  526. }
  527. return new Curve3(bez);
  528. }
  529. /**
  530. * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/how_to/how_to_use_curve3#hermite-spline
  531. * @param p1 (Vector3) the origin point of the Hermite Spline
  532. * @param t1 (Vector3) the tangent vector at the origin point
  533. * @param p2 (Vector3) the end point of the Hermite Spline
  534. * @param t2 (Vector3) the tangent vector at the end point
  535. * @param nbPoints (integer) the wanted number of points in the curve
  536. * @returns the created Curve3
  537. */
  538. public static CreateHermiteSpline(p1: DeepImmutable<Vector3>, t1: DeepImmutable<Vector3>, p2: DeepImmutable<Vector3>, t2: DeepImmutable<Vector3>, nbPoints: number): Curve3 {
  539. var hermite = new Array<Vector3>();
  540. var step = 1.0 / nbPoints;
  541. for (var i = 0; i <= nbPoints; i++) {
  542. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  543. }
  544. return new Curve3(hermite);
  545. }
  546. /**
  547. * Returns a Curve3 object along a CatmullRom Spline curve :
  548. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  549. * @param nbPoints (integer) the wanted number of points between each curve control points
  550. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  551. * @returns the created Curve3
  552. */
  553. public static CreateCatmullRomSpline(points: DeepImmutable<Vector3[]>, nbPoints: number, closed?: boolean): Curve3 {
  554. var catmullRom = new Array<Vector3>();
  555. var step = 1.0 / nbPoints;
  556. var amount = 0.0;
  557. if (closed) {
  558. var pointsCount = points.length;
  559. for (var i = 0; i < pointsCount; i++) {
  560. amount = 0;
  561. for (var c = 0; c < nbPoints; c++) {
  562. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  563. amount += step;
  564. }
  565. }
  566. catmullRom.push(catmullRom[0]);
  567. }
  568. else {
  569. var totalPoints = new Array<Vector3>();
  570. totalPoints.push(points[0].clone());
  571. Array.prototype.push.apply(totalPoints, points);
  572. totalPoints.push(points[points.length - 1].clone());
  573. for (var i = 0; i < totalPoints.length - 3; i++) {
  574. amount = 0;
  575. for (var c = 0; c < nbPoints; c++) {
  576. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  577. amount += step;
  578. }
  579. }
  580. i--;
  581. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  582. }
  583. return new Curve3(catmullRom);
  584. }
  585. /**
  586. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  587. * A Curve3 is designed from a series of successive Vector3.
  588. * Tuto : https://doc.babylonjs.com/how_to/how_to_use_curve3#curve3-object
  589. * @param points points which make up the curve
  590. */
  591. constructor(points: Vector3[]) {
  592. this._points = points;
  593. this._length = this._computeLength(points);
  594. }
  595. /**
  596. * @returns the Curve3 stored array of successive Vector3
  597. */
  598. public getPoints() {
  599. return this._points;
  600. }
  601. /**
  602. * @returns the computed length (float) of the curve.
  603. */
  604. public length() {
  605. return this._length;
  606. }
  607. /**
  608. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  609. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  610. * curveA and curveB keep unchanged.
  611. * @param curve the curve to continue from this curve
  612. * @returns the newly constructed curve
  613. */
  614. public continue(curve: DeepImmutable<Curve3>): Curve3 {
  615. var lastPoint = this._points[this._points.length - 1];
  616. var continuedPoints = this._points.slice();
  617. var curvePoints = curve.getPoints();
  618. for (var i = 1; i < curvePoints.length; i++) {
  619. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  620. }
  621. var continuedCurve = new Curve3(continuedPoints);
  622. return continuedCurve;
  623. }
  624. private _computeLength(path: DeepImmutable<Vector3[]>): number {
  625. var l = 0;
  626. for (var i = 1; i < path.length; i++) {
  627. l += (path[i].subtract(path[i - 1])).length();
  628. }
  629. return l;
  630. }
  631. }