babylon.transformNode.ts 39 KB

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