babylon.transformNode.ts 44 KB

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