transformNode.ts 55 KB

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