babylon.transformNode.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. module BABYLON {
  2. export class TransformNode extends Node {
  3. // Statics
  4. public static BILLBOARDMODE_NONE = 0;
  5. public static BILLBOARDMODE_X = 1;
  6. public static BILLBOARDMODE_Y = 2;
  7. public static BILLBOARDMODE_Z = 4;
  8. public static BILLBOARDMODE_ALL = 7;
  9. // Properties
  10. @serializeAsVector3()
  11. private _rotation = Vector3.Zero();
  12. @serializeAsQuaternion()
  13. private _rotationQuaternion: Nullable<Quaternion>;
  14. @serializeAsVector3()
  15. protected _scaling = Vector3.One();
  16. protected _isDirty = false;
  17. private _transformToBoneReferal: Nullable<TransformNode>;
  18. @serialize()
  19. public billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  20. @serialize()
  21. public scalingDeterminant = 1;
  22. @serialize()
  23. public infiniteDistance = false;
  24. @serializeAsVector3()
  25. public position = Vector3.Zero();
  26. // Cache
  27. public _poseMatrix: Matrix;
  28. private _localWorld = Matrix.Zero();
  29. public _worldMatrix = Matrix.Zero();
  30. private _absolutePosition = Vector3.Zero();
  31. private _pivotMatrix = Matrix.Identity();
  32. private _pivotMatrixInverse: Matrix;
  33. private _postMultiplyPivotMatrix = false;
  34. protected _isWorldMatrixFrozen = false;
  35. /**
  36. * An event triggered after the world matrix is updated
  37. * @type {BABYLON.Observable}
  38. */
  39. public onAfterWorldMatrixUpdateObservable = new Observable<TransformNode>();
  40. constructor(name: string, scene: Nullable<Scene> = null, isPure = true) {
  41. super(name, scene);
  42. if (isPure) {
  43. this.getScene().addTransformNode(this);
  44. }
  45. }
  46. /**
  47. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  48. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  49. * Default : (0.0, 0.0, 0.0)
  50. */
  51. public get rotation(): Vector3 {
  52. return this._rotation;
  53. }
  54. public set rotation(newRotation: Vector3) {
  55. this._rotation = newRotation;
  56. }
  57. /**
  58. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  59. * Default : (1.0, 1.0, 1.0)
  60. */
  61. public get scaling(): Vector3 {
  62. return this._scaling;
  63. }
  64. /**
  65. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  66. * Default : (1.0, 1.0, 1.0)
  67. */
  68. public set scaling(newScaling: Vector3) {
  69. this._scaling = newScaling;
  70. }
  71. /**
  72. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  73. * It's null by default.
  74. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  75. */
  76. public get rotationQuaternion(): Nullable<Quaternion> {
  77. return this._rotationQuaternion;
  78. }
  79. public set rotationQuaternion(quaternion: Nullable<Quaternion>) {
  80. this._rotationQuaternion = quaternion;
  81. //reset the rotation vector.
  82. if (quaternion && this.rotation.length()) {
  83. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  84. }
  85. }
  86. /**
  87. * Returns the latest update of the World matrix
  88. * Returns a Matrix.
  89. */
  90. public getWorldMatrix(): Matrix {
  91. if (this._currentRenderId !== this.getScene().getRenderId()) {
  92. this.computeWorldMatrix();
  93. }
  94. return this._worldMatrix;
  95. }
  96. /**
  97. * Returns directly the latest state of the mesh World matrix.
  98. * A Matrix is returned.
  99. */
  100. public get worldMatrixFromCache(): Matrix {
  101. return this._worldMatrix;
  102. }
  103. /**
  104. * Copies the paramater passed Matrix into the mesh Pose matrix.
  105. * Returns the AbstractMesh.
  106. */
  107. public updatePoseMatrix(matrix: Matrix): TransformNode {
  108. this._poseMatrix.copyFrom(matrix);
  109. return this;
  110. }
  111. /**
  112. * Returns the mesh Pose matrix.
  113. * Returned object : Matrix
  114. */
  115. public getPoseMatrix(): Matrix {
  116. return this._poseMatrix;
  117. }
  118. public _isSynchronized(): boolean {
  119. if (this._isDirty) {
  120. return false;
  121. }
  122. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  123. return false;
  124. if (this._cache.pivotMatrixUpdated) {
  125. return false;
  126. }
  127. if (this.infiniteDistance) {
  128. return false;
  129. }
  130. if (!this._cache.position.equals(this.position))
  131. return false;
  132. if (this.rotationQuaternion) {
  133. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  134. return false;
  135. }
  136. if (!this._cache.rotation.equals(this.rotation))
  137. return false;
  138. if (!this._cache.scaling.equals(this.scaling))
  139. return false;
  140. return true;
  141. }
  142. public _initCache() {
  143. super._initCache();
  144. this._cache.localMatrixUpdated = false;
  145. this._cache.position = Vector3.Zero();
  146. this._cache.scaling = Vector3.Zero();
  147. this._cache.rotation = Vector3.Zero();
  148. this._cache.rotationQuaternion = new Quaternion(0, 0, 0, 0);
  149. this._cache.billboardMode = -1;
  150. }
  151. public markAsDirty(property: string): TransformNode {
  152. if (property === "rotation") {
  153. this.rotationQuaternion = null;
  154. }
  155. this._currentRenderId = Number.MAX_VALUE;
  156. this._isDirty = true;
  157. return this;
  158. }
  159. /**
  160. * Returns the current mesh absolute position.
  161. * Retuns a Vector3.
  162. */
  163. public get absolutePosition(): Vector3 {
  164. return this._absolutePosition;
  165. }
  166. /**
  167. * Sets a new pivot matrix to the mesh.
  168. * Returns the AbstractMesh.
  169. */
  170. public setPivotMatrix(matrix: Matrix, postMultiplyPivotMatrix = false): TransformNode {
  171. this._pivotMatrix = matrix.clone();
  172. this._cache.pivotMatrixUpdated = true;
  173. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  174. if (this._postMultiplyPivotMatrix) {
  175. this._pivotMatrixInverse = Matrix.Invert(matrix);
  176. }
  177. return this;
  178. }
  179. /**
  180. * Returns the mesh pivot matrix.
  181. * Default : Identity.
  182. * A Matrix is returned.
  183. */
  184. public getPivotMatrix(): Matrix {
  185. return this._pivotMatrix;
  186. }
  187. /**
  188. * Prevents the World matrix to be computed any longer.
  189. * Returns the AbstractMesh.
  190. */
  191. public freezeWorldMatrix(): TransformNode {
  192. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  193. this.computeWorldMatrix(true);
  194. this._isWorldMatrixFrozen = true;
  195. return this;
  196. }
  197. /**
  198. * Allows back the World matrix computation.
  199. * Returns the AbstractMesh.
  200. */
  201. public unfreezeWorldMatrix() {
  202. this._isWorldMatrixFrozen = false;
  203. this.computeWorldMatrix(true);
  204. return this;
  205. }
  206. /**
  207. * True if the World matrix has been frozen.
  208. * Returns a boolean.
  209. */
  210. public get isWorldMatrixFrozen(): boolean {
  211. return this._isWorldMatrixFrozen;
  212. }
  213. /**
  214. * Retuns the mesh absolute position in the World.
  215. * Returns a Vector3.
  216. */
  217. public getAbsolutePosition(): Vector3 {
  218. this.computeWorldMatrix();
  219. return this._absolutePosition;
  220. }
  221. /**
  222. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  223. * Returns the AbstractMesh.
  224. */
  225. public setAbsolutePosition(absolutePosition: Vector3): TransformNode {
  226. if (!absolutePosition) {
  227. return this;
  228. }
  229. var absolutePositionX;
  230. var absolutePositionY;
  231. var absolutePositionZ;
  232. if (absolutePosition.x === undefined) {
  233. if (arguments.length < 3) {
  234. return this;
  235. }
  236. absolutePositionX = arguments[0];
  237. absolutePositionY = arguments[1];
  238. absolutePositionZ = arguments[2];
  239. }
  240. else {
  241. absolutePositionX = absolutePosition.x;
  242. absolutePositionY = absolutePosition.y;
  243. absolutePositionZ = absolutePosition.z;
  244. }
  245. if (this.parent) {
  246. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  247. invertParentWorldMatrix.invert();
  248. var worldPosition = new Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  249. this.position = Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  250. } else {
  251. this.position.x = absolutePositionX;
  252. this.position.y = absolutePositionY;
  253. this.position.z = absolutePositionZ;
  254. }
  255. return this;
  256. }
  257. /**
  258. * Sets the mesh position in its local space.
  259. * Returns the AbstractMesh.
  260. */
  261. public setPositionWithLocalVector(vector3: Vector3): TransformNode {
  262. this.computeWorldMatrix();
  263. this.position = Vector3.TransformNormal(vector3, this._localWorld);
  264. return this;
  265. }
  266. /**
  267. * Returns the mesh position in the local space from the current World matrix values.
  268. * Returns a new Vector3.
  269. */
  270. public getPositionExpressedInLocalSpace(): Vector3 {
  271. this.computeWorldMatrix();
  272. var invLocalWorldMatrix = this._localWorld.clone();
  273. invLocalWorldMatrix.invert();
  274. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  275. }
  276. /**
  277. * Translates the mesh along the passed Vector3 in its local space.
  278. * Returns the AbstractMesh.
  279. */
  280. public locallyTranslate(vector3: Vector3): TransformNode {
  281. this.computeWorldMatrix(true);
  282. this.position = Vector3.TransformCoordinates(vector3, this._localWorld);
  283. return this;
  284. }
  285. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  286. /**
  287. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  288. * @param targetPoint the position (must be in same space as current mesh) to look at
  289. * @param yawCor optional yaw (y-axis) correction in radians
  290. * @param pitchCor optional pitch (x-axis) correction in radians
  291. * @param rollCor optional roll (z-axis) correction in radians
  292. * @param space the choosen space of the target
  293. * @returns the TransformNode.
  294. */
  295. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): TransformNode {
  296. var dv = AbstractMesh._lookAtVectorCache;
  297. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  298. targetPoint.subtractToRef(pos, dv);
  299. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  300. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  301. var pitch = Math.atan2(dv.y, len);
  302. if (this.rotationQuaternion) {
  303. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  304. }
  305. else {
  306. this.rotation.x = pitch + pitchCor;
  307. this.rotation.y = yaw + yawCor;
  308. this.rotation.z = rollCor;
  309. }
  310. return this;
  311. }
  312. /**
  313. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  314. * This Vector3 is expressed in the World space.
  315. */
  316. public getDirection(localAxis: Vector3): Vector3 {
  317. var result = Vector3.Zero();
  318. this.getDirectionToRef(localAxis, result);
  319. return result;
  320. }
  321. /**
  322. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  323. * localAxis is expressed in the mesh local space.
  324. * result is computed in the Wordl space from the mesh World matrix.
  325. * Returns the AbstractMesh.
  326. */
  327. public getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode {
  328. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  329. return this;
  330. }
  331. public setPivotPoint(point: Vector3, space: Space = Space.LOCAL): TransformNode {
  332. if (this.getScene().getRenderId() == 0) {
  333. this.computeWorldMatrix(true);
  334. }
  335. var wm = this.getWorldMatrix();
  336. if (space == Space.WORLD) {
  337. var tmat = Tmp.Matrix[0];
  338. wm.invertToRef(tmat);
  339. point = Vector3.TransformCoordinates(point, tmat);
  340. }
  341. Vector3.TransformCoordinatesToRef(point, wm, this.position);
  342. this._pivotMatrix.m[12] = -point.x;
  343. this._pivotMatrix.m[13] = -point.y;
  344. this._pivotMatrix.m[14] = -point.z;
  345. this._cache.pivotMatrixUpdated = true;
  346. return this;
  347. }
  348. /**
  349. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  350. */
  351. public getPivotPoint(): Vector3 {
  352. var point = Vector3.Zero();
  353. this.getPivotPointToRef(point);
  354. return point;
  355. }
  356. /**
  357. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  358. * Returns the AbstractMesh.
  359. */
  360. public getPivotPointToRef(result: Vector3): TransformNode {
  361. result.x = -this._pivotMatrix.m[12];
  362. result.y = -this._pivotMatrix.m[13];
  363. result.z = -this._pivotMatrix.m[14];
  364. return this;
  365. }
  366. /**
  367. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  368. */
  369. public getAbsolutePivotPoint(): Vector3 {
  370. var point = Vector3.Zero();
  371. this.getAbsolutePivotPointToRef(point);
  372. return point;
  373. }
  374. /**
  375. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  376. * Returns the AbstractMesh.
  377. */
  378. public getAbsolutePivotPointToRef(result: Vector3): TransformNode {
  379. result.x = this._pivotMatrix.m[12];
  380. result.y = this._pivotMatrix.m[13];
  381. result.z = this._pivotMatrix.m[14];
  382. this.getPivotPointToRef(result);
  383. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  384. return this;
  385. }
  386. /**
  387. * Defines the passed node as the parent of the current node.
  388. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  389. * Returns the TransformNode.
  390. */
  391. public setParent(node: Nullable<TransformNode>): TransformNode {
  392. if (node == null) {
  393. var rotation = Tmp.Quaternion[0];
  394. var position = Tmp.Vector3[0];
  395. var scale = Tmp.Vector3[1];
  396. if (this.parent && (<TransformNode>this.parent).computeWorldMatrix) {
  397. (<TransformNode>this.parent).computeWorldMatrix(true);
  398. }
  399. this.computeWorldMatrix(true);
  400. this.getWorldMatrix().decompose(scale, rotation, position);
  401. if (this.rotationQuaternion) {
  402. this.rotationQuaternion.copyFrom(rotation);
  403. } else {
  404. rotation.toEulerAnglesToRef(this.rotation);
  405. }
  406. this.scaling.x = scale.x;
  407. this.scaling.y = scale.y;
  408. this.scaling.z = scale.z;
  409. this.position.x = position.x;
  410. this.position.y = position.y;
  411. this.position.z = position.z;
  412. } else {
  413. var rotation = Tmp.Quaternion[0];
  414. var position = Tmp.Vector3[0];
  415. var scale = Tmp.Vector3[1];
  416. var diffMatrix = Tmp.Matrix[0];
  417. var invParentMatrix = Tmp.Matrix[1];
  418. this.computeWorldMatrix(true);
  419. node.computeWorldMatrix(true);
  420. node.getWorldMatrix().invertToRef(invParentMatrix);
  421. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  422. diffMatrix.decompose(scale, rotation, position);
  423. if (this.rotationQuaternion) {
  424. this.rotationQuaternion.copyFrom(rotation);
  425. } else {
  426. rotation.toEulerAnglesToRef(this.rotation);
  427. }
  428. this.position.x = position.x;
  429. this.position.y = position.y;
  430. this.position.z = position.z;
  431. this.scaling.x = scale.x;
  432. this.scaling.y = scale.y;
  433. this.scaling.z = scale.z;
  434. }
  435. this.parent = node;
  436. return this;
  437. }
  438. private _nonUniformScaling = false;
  439. public get nonUniformScaling(): boolean {
  440. return this._nonUniformScaling;
  441. }
  442. public _updateNonUniformScalingState(value: boolean): boolean {
  443. if (this._nonUniformScaling === value) {
  444. return false;
  445. }
  446. this._nonUniformScaling = true;
  447. return true;
  448. }
  449. /**
  450. * Attach the current TransformNode to another TransformNode associated with a bone
  451. * @param bone Bone affecting the TransformNode
  452. * @param affectedTransformNode TransformNode associated with the bone
  453. */
  454. public attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode {
  455. this._transformToBoneReferal = affectedTransformNode;
  456. this.parent = bone;
  457. if (bone.getWorldMatrix().determinant() < 0) {
  458. this.scalingDeterminant *= -1;
  459. }
  460. return this;
  461. }
  462. public detachFromBone(): TransformNode {
  463. if (!this.parent) {
  464. return this;
  465. }
  466. if (this.parent.getWorldMatrix().determinant() < 0) {
  467. this.scalingDeterminant *= -1;
  468. }
  469. this._transformToBoneReferal = null;
  470. this.parent = null;
  471. return this;
  472. }
  473. private static _rotationAxisCache = new Quaternion();
  474. /**
  475. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  476. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  477. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  478. * The passed axis is also normalized.
  479. * Returns the AbstractMesh.
  480. */
  481. public rotate(axis: Vector3, amount: number, space?: Space): TransformNode {
  482. axis.normalize();
  483. if (!this.rotationQuaternion) {
  484. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  485. this.rotation = Vector3.Zero();
  486. }
  487. var rotationQuaternion: Quaternion;
  488. if (!space || (space as any) === Space.LOCAL) {
  489. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  490. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  491. }
  492. else {
  493. if (this.parent) {
  494. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  495. invertParentWorldMatrix.invert();
  496. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  497. }
  498. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  499. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  500. }
  501. return this;
  502. }
  503. /**
  504. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  505. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  506. * The passed axis is also normalized.
  507. * Returns the AbstractMesh.
  508. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  509. */
  510. public rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode {
  511. axis.normalize();
  512. if (!this.rotationQuaternion) {
  513. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  514. this.rotation.copyFromFloats(0, 0, 0);
  515. }
  516. point.subtractToRef(this.position, Tmp.Vector3[0]);
  517. Matrix.TranslationToRef(Tmp.Vector3[0].x, Tmp.Vector3[0].y, Tmp.Vector3[0].z, Tmp.Matrix[0]);
  518. Tmp.Matrix[0].invertToRef(Tmp.Matrix[2]);
  519. Matrix.RotationAxisToRef(axis, amount, Tmp.Matrix[1]);
  520. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[2]);
  521. Tmp.Matrix[2].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[2]);
  522. Tmp.Matrix[2].decompose(Tmp.Vector3[0], Tmp.Quaternion[0], Tmp.Vector3[1]);
  523. this.position.addInPlace(Tmp.Vector3[1]);
  524. Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  525. return this;
  526. }
  527. /**
  528. * Translates the mesh along the axis vector for the passed distance in the given space.
  529. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  530. * Returns the AbstractMesh.
  531. */
  532. public translate(axis: Vector3, distance: number, space?: Space): TransformNode {
  533. var displacementVector = axis.scale(distance);
  534. if (!space || (space as any) === Space.LOCAL) {
  535. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  536. this.setPositionWithLocalVector(tempV3);
  537. }
  538. else {
  539. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  540. }
  541. return this;
  542. }
  543. /**
  544. * Adds a rotation step to the mesh current rotation.
  545. * x, y, z are Euler angles expressed in radians.
  546. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  547. * This means this rotation is made in the mesh local space only.
  548. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  549. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  550. * ```javascript
  551. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  552. * ```
  553. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  554. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  555. * Returns the AbstractMesh.
  556. */
  557. public addRotation(x: number, y: number, z: number): TransformNode {
  558. var rotationQuaternion;
  559. if (this.rotationQuaternion) {
  560. rotationQuaternion = this.rotationQuaternion;
  561. }
  562. else {
  563. rotationQuaternion = Tmp.Quaternion[1];
  564. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  565. }
  566. var accumulation = BABYLON.Tmp.Quaternion[0];
  567. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  568. rotationQuaternion.multiplyInPlace(accumulation);
  569. if (!this.rotationQuaternion) {
  570. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  571. }
  572. return this;
  573. }
  574. /**
  575. * Computes the mesh World matrix and returns it.
  576. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  577. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  578. * If the parameter `force`is set to `true`, the actual computation is done.
  579. * Returns the mesh World Matrix.
  580. */
  581. public computeWorldMatrix(force?: boolean): Matrix {
  582. if (this._isWorldMatrixFrozen) {
  583. return this._worldMatrix;
  584. }
  585. if (!force && this.isSynchronized(true)) {
  586. return this._worldMatrix;
  587. }
  588. this._cache.position.copyFrom(this.position);
  589. this._cache.scaling.copyFrom(this.scaling);
  590. this._cache.pivotMatrixUpdated = false;
  591. this._cache.billboardMode = this.billboardMode;
  592. this._currentRenderId = this.getScene().getRenderId();
  593. this._isDirty = false;
  594. // Scaling
  595. Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, Tmp.Matrix[1]);
  596. // Rotation
  597. //rotate, if quaternion is set and rotation was used
  598. if (this.rotationQuaternion) {
  599. var len = this.rotation.length();
  600. if (len) {
  601. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z))
  602. this.rotation.copyFromFloats(0, 0, 0);
  603. }
  604. }
  605. if (this.rotationQuaternion) {
  606. this.rotationQuaternion.toRotationMatrix(Tmp.Matrix[0]);
  607. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  608. } else {
  609. Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, Tmp.Matrix[0]);
  610. this._cache.rotation.copyFrom(this.rotation);
  611. }
  612. // Translation
  613. let camera = (<Camera>this.getScene().activeCamera);
  614. if (this.infiniteDistance && !this.parent && camera) {
  615. var cameraWorldMatrix = camera.getWorldMatrix();
  616. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  617. Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y,
  618. this.position.z + cameraGlobalPosition.z, Tmp.Matrix[2]);
  619. } else {
  620. Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, Tmp.Matrix[2]);
  621. }
  622. // Composing transformations
  623. this._pivotMatrix.multiplyToRef(Tmp.Matrix[1], Tmp.Matrix[4]);
  624. Tmp.Matrix[4].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  625. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  626. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  627. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  628. // Need to decompose each rotation here
  629. var currentPosition = Tmp.Vector3[3];
  630. if (this.parent && this.parent.getWorldMatrix) {
  631. if (this._transformToBoneReferal) {
  632. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  633. Vector3.TransformCoordinatesToRef(this.position, Tmp.Matrix[6], currentPosition);
  634. } else {
  635. Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  636. }
  637. } else {
  638. currentPosition.copyFrom(this.position);
  639. }
  640. currentPosition.subtractInPlace(camera.globalPosition);
  641. var finalEuler = Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  642. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  643. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  644. }
  645. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  646. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  647. }
  648. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  649. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  650. }
  651. Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, Tmp.Matrix[0]);
  652. } else {
  653. Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  654. Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  655. Tmp.Matrix[1].invertToRef(Tmp.Matrix[0]);
  656. }
  657. Tmp.Matrix[1].copyFrom(Tmp.Matrix[5]);
  658. Tmp.Matrix[1].multiplyToRef(Tmp.Matrix[0], Tmp.Matrix[5]);
  659. }
  660. // Local world
  661. Tmp.Matrix[5].multiplyToRef(Tmp.Matrix[2], this._localWorld);
  662. // Parent
  663. if (this.parent && this.parent.getWorldMatrix) {
  664. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  665. if (this._transformToBoneReferal) {
  666. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), Tmp.Matrix[6]);
  667. Tmp.Matrix[5].copyFrom(Tmp.Matrix[6]);
  668. } else {
  669. Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  670. }
  671. this._localWorld.getTranslationToRef(Tmp.Vector3[5]);
  672. Vector3.TransformCoordinatesToRef(Tmp.Vector3[5], Tmp.Matrix[5], Tmp.Vector3[5]);
  673. this._worldMatrix.copyFrom(this._localWorld);
  674. this._worldMatrix.setTranslation(Tmp.Vector3[5]);
  675. } else {
  676. if (this._transformToBoneReferal) {
  677. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), Tmp.Matrix[6]);
  678. Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  679. } else {
  680. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  681. }
  682. }
  683. this._markSyncedWithParent();
  684. } else {
  685. this._worldMatrix.copyFrom(this._localWorld);
  686. }
  687. // Post multiply inverse of pivotMatrix
  688. if (this._postMultiplyPivotMatrix) {
  689. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  690. }
  691. // Normal matrix
  692. if (this.scaling.isNonUniform) {
  693. this._updateNonUniformScalingState(true);
  694. } else if (this.parent && (<TransformNode>this.parent)._nonUniformScaling) {
  695. this._updateNonUniformScalingState((<TransformNode>this.parent)._nonUniformScaling);
  696. } else {
  697. this._updateNonUniformScalingState(false);
  698. }
  699. this._afterComputeWorldMatrix();
  700. // Absolute position
  701. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  702. // Callbacks
  703. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  704. if (!this._poseMatrix) {
  705. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  706. }
  707. return this._worldMatrix;
  708. }
  709. protected _afterComputeWorldMatrix(): void {
  710. }
  711. /**
  712. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  713. * @param func: callback function to add
  714. *
  715. * Returns the TransformNode.
  716. */
  717. public registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  718. this.onAfterWorldMatrixUpdateObservable.add(func);
  719. return this;
  720. }
  721. /**
  722. * Removes a registered callback function.
  723. * Returns the TransformNode.
  724. */
  725. public unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  726. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  727. return this;
  728. }
  729. /**
  730. * Clone the current transform node
  731. * Returns the new transform node
  732. * @param name Name of the new clone
  733. * @param newParent New parent for the clone
  734. * @param doNotCloneChildren Do not clone children hierarchy
  735. */
  736. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<TransformNode> {
  737. var result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);
  738. result.name = name;
  739. result.id = name;
  740. if (newParent) {
  741. result.parent = newParent;
  742. }
  743. if (!doNotCloneChildren) {
  744. // Children
  745. let directDescendants = this.getDescendants(true);
  746. for (let index = 0; index < directDescendants.length; index++) {
  747. var child = directDescendants[index];
  748. if ((<any>child).clone) {
  749. (<any>child).clone(name + "." + child.name, result);
  750. }
  751. }
  752. }
  753. return result;
  754. }
  755. public serialize(currentSerializationObject?: any): any {
  756. let serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
  757. serializationObject.type = this.getClassName();
  758. // Parent
  759. if (this.parent) {
  760. serializationObject.parentId = this.parent.id;
  761. }
  762. if (Tags && Tags.HasTags(this)) {
  763. serializationObject.tags = Tags.GetTags(this);
  764. }
  765. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  766. serializationObject.isEnabled = this.isEnabled();
  767. // Parent
  768. if (this.parent) {
  769. serializationObject.parentId = this.parent.id;
  770. }
  771. return serializationObject;
  772. }
  773. // Statics
  774. /**
  775. * Returns a new TransformNode object parsed from the source provided.
  776. * The parameter `parsedMesh` is the source.
  777. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  778. */
  779. public static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode {
  780. var transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
  781. if (Tags) {
  782. Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  783. }
  784. if (parsedTransformNode.localMatrix) {
  785. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
  786. } else if (parsedTransformNode.pivotMatrix) {
  787. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
  788. }
  789. transformNode.setEnabled(parsedTransformNode.isEnabled);
  790. // Parent
  791. if (parsedTransformNode.parentId) {
  792. transformNode._waitingParentId = parsedTransformNode.parentId;
  793. }
  794. return transformNode;
  795. }
  796. /**
  797. * Disposes the TransformNode.
  798. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  799. * Returns nothing.
  800. */
  801. public dispose(doNotRecurse?: boolean): void {
  802. // Animations
  803. this.getScene().stopAnimation(this);
  804. // Remove from scene
  805. this.getScene().removeTransformNode(this);
  806. this._cache = null;
  807. if (!doNotRecurse) {
  808. // Children
  809. var objects = this.getDescendants(true);
  810. for (var index = 0; index < objects.length; index++) {
  811. objects[index].dispose();
  812. }
  813. } else {
  814. var childMeshes = this.getChildMeshes(true);
  815. for (index = 0; index < childMeshes.length; index++) {
  816. var child = childMeshes[index];
  817. child.parent = null;
  818. child.computeWorldMatrix(true);
  819. }
  820. }
  821. this.onAfterWorldMatrixUpdateObservable.clear();
  822. super.dispose();
  823. }
  824. }
  825. }