transformNode.ts 49 KB

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