transformNode.ts 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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. return this;
  456. }
  457. /**
  458. * Sets the mesh position in its local space.
  459. * @param vector3 the position to set in localspace
  460. * @returns the TransformNode.
  461. */
  462. public setPositionWithLocalVector(vector3: Vector3): TransformNode {
  463. this.computeWorldMatrix();
  464. this.position = Vector3.TransformNormal(vector3, this._localMatrix);
  465. return this;
  466. }
  467. /**
  468. * Returns the mesh position in the local space from the current World matrix values.
  469. * @returns a new Vector3.
  470. */
  471. public getPositionExpressedInLocalSpace(): Vector3 {
  472. this.computeWorldMatrix();
  473. const invLocalWorldMatrix = TmpVectors.Matrix[0];
  474. this._localMatrix.invertToRef(invLocalWorldMatrix);
  475. return Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  476. }
  477. /**
  478. * Translates the mesh along the passed Vector3 in its local space.
  479. * @param vector3 the distance to translate in localspace
  480. * @returns the TransformNode.
  481. */
  482. public locallyTranslate(vector3: Vector3): TransformNode {
  483. this.computeWorldMatrix(true);
  484. this.position = Vector3.TransformCoordinates(vector3, this._localMatrix);
  485. return this;
  486. }
  487. private static _lookAtVectorCache = new Vector3(0, 0, 0);
  488. /**
  489. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  490. * @param targetPoint the position (must be in same space as current mesh) to look at
  491. * @param yawCor optional yaw (y-axis) correction in radians
  492. * @param pitchCor optional pitch (x-axis) correction in radians
  493. * @param rollCor optional roll (z-axis) correction in radians
  494. * @param space the choosen space of the target
  495. * @returns the TransformNode.
  496. */
  497. public lookAt(targetPoint: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0, space: Space = Space.LOCAL): TransformNode {
  498. var dv = TransformNode._lookAtVectorCache;
  499. var pos = space === Space.LOCAL ? this.position : this.getAbsolutePosition();
  500. targetPoint.subtractToRef(pos, dv);
  501. this.setDirection(dv, yawCor, pitchCor, rollCor);
  502. // Correct for parent's rotation offset
  503. if (space === Space.WORLD && this.parent) {
  504. if (this.rotationQuaternion) {
  505. // Get local rotation matrix of the looking object
  506. var rotationMatrix = TmpVectors.Matrix[0];
  507. this.rotationQuaternion.toRotationMatrix(rotationMatrix);
  508. // Offset rotation by parent's inverted rotation matrix to correct in world space
  509. var parentRotationMatrix = TmpVectors.Matrix[1];
  510. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  511. parentRotationMatrix.invert();
  512. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  513. this.rotationQuaternion.fromRotationMatrix(rotationMatrix);
  514. } else {
  515. // Get local rotation matrix of the looking object
  516. var quaternionRotation = TmpVectors.Quaternion[0];
  517. Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation);
  518. var rotationMatrix = TmpVectors.Matrix[0];
  519. quaternionRotation.toRotationMatrix(rotationMatrix);
  520. // Offset rotation by parent's inverted rotation matrix to correct in world space
  521. var parentRotationMatrix = TmpVectors.Matrix[1];
  522. this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix);
  523. parentRotationMatrix.invert();
  524. rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix);
  525. quaternionRotation.fromRotationMatrix(rotationMatrix);
  526. quaternionRotation.toEulerAnglesToRef(this.rotation);
  527. }
  528. }
  529. return this;
  530. }
  531. /**
  532. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  533. * This Vector3 is expressed in the World space.
  534. * @param localAxis axis to rotate
  535. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  536. */
  537. public getDirection(localAxis: Vector3): Vector3 {
  538. var result = Vector3.Zero();
  539. this.getDirectionToRef(localAxis, result);
  540. return result;
  541. }
  542. /**
  543. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  544. * localAxis is expressed in the mesh local space.
  545. * result is computed in the Wordl space from the mesh World matrix.
  546. * @param localAxis axis to rotate
  547. * @param result the resulting transformnode
  548. * @returns this TransformNode.
  549. */
  550. public getDirectionToRef(localAxis: Vector3, result: Vector3): TransformNode {
  551. Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  552. return this;
  553. }
  554. /**
  555. * Sets this transform node rotation to the given local axis.
  556. * @param localAxis the axis in local space
  557. * @param yawCor optional yaw (y-axis) correction in radians
  558. * @param pitchCor optional pitch (x-axis) correction in radians
  559. * @param rollCor optional roll (z-axis) correction in radians
  560. * @returns this TransformNode
  561. */
  562. public setDirection(localAxis: Vector3, yawCor: number = 0, pitchCor: number = 0, rollCor: number = 0): TransformNode {
  563. var yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;
  564. var len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
  565. var pitch = -Math.atan2(localAxis.y, len);
  566. if (this.rotationQuaternion) {
  567. Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  568. }
  569. else {
  570. this.rotation.x = pitch + pitchCor;
  571. this.rotation.y = yaw + yawCor;
  572. this.rotation.z = rollCor;
  573. }
  574. return this;
  575. }
  576. /**
  577. * Sets a new pivot point to the current node
  578. * @param point defines the new pivot point to use
  579. * @param space defines if the point is in world or local space (local by default)
  580. * @returns the current TransformNode
  581. */
  582. public setPivotPoint(point: Vector3, space: Space = Space.LOCAL): TransformNode {
  583. if (this.getScene().getRenderId() == 0) {
  584. this.computeWorldMatrix(true);
  585. }
  586. var wm = this.getWorldMatrix();
  587. if (space == Space.WORLD) {
  588. var tmat = TmpVectors.Matrix[0];
  589. wm.invertToRef(tmat);
  590. point = Vector3.TransformCoordinates(point, tmat);
  591. }
  592. return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true);
  593. }
  594. /**
  595. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  596. * @returns the pivot point
  597. */
  598. public getPivotPoint(): Vector3 {
  599. var point = Vector3.Zero();
  600. this.getPivotPointToRef(point);
  601. return point;
  602. }
  603. /**
  604. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  605. * @param result the vector3 to store the result
  606. * @returns this TransformNode.
  607. */
  608. public getPivotPointToRef(result: Vector3): TransformNode {
  609. result.x = -this._pivotMatrix.m[12];
  610. result.y = -this._pivotMatrix.m[13];
  611. result.z = -this._pivotMatrix.m[14];
  612. return this;
  613. }
  614. /**
  615. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  616. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  617. */
  618. public getAbsolutePivotPoint(): Vector3 {
  619. var point = Vector3.Zero();
  620. this.getAbsolutePivotPointToRef(point);
  621. return point;
  622. }
  623. /**
  624. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  625. * @param result vector3 to store the result
  626. * @returns this TransformNode.
  627. */
  628. public getAbsolutePivotPointToRef(result: Vector3): TransformNode {
  629. result.x = this._pivotMatrix.m[12];
  630. result.y = this._pivotMatrix.m[13];
  631. result.z = this._pivotMatrix.m[14];
  632. this.getPivotPointToRef(result);
  633. Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  634. return this;
  635. }
  636. /**
  637. * Defines the passed node as the parent of the current node.
  638. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  639. * @see https://doc.babylonjs.com/how_to/parenting
  640. * @param node the node ot set as the parent
  641. * @returns this TransformNode.
  642. */
  643. public setParent(node: Nullable<Node>): TransformNode {
  644. if (!node && !this.parent) {
  645. return this;
  646. }
  647. var quatRotation = TmpVectors.Quaternion[0];
  648. var position = TmpVectors.Vector3[0];
  649. var scale = TmpVectors.Vector3[1];
  650. if (!node) {
  651. this.computeWorldMatrix(true);
  652. this.getWorldMatrix().decompose(scale, quatRotation, position);
  653. } else {
  654. var diffMatrix = TmpVectors.Matrix[0];
  655. var invParentMatrix = TmpVectors.Matrix[1];
  656. this.computeWorldMatrix(true);
  657. node.computeWorldMatrix(true);
  658. node.getWorldMatrix().invertToRef(invParentMatrix);
  659. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  660. diffMatrix.decompose(scale, quatRotation, position);
  661. }
  662. if (this.rotationQuaternion) {
  663. this.rotationQuaternion.copyFrom(quatRotation);
  664. } else {
  665. quatRotation.toEulerAnglesToRef(this.rotation);
  666. }
  667. this.scaling.copyFrom(scale);
  668. this.position.copyFrom(position);
  669. this.parent = node;
  670. return this;
  671. }
  672. private _nonUniformScaling = false;
  673. /**
  674. * True if the scaling property of this object is non uniform eg. (1,2,1)
  675. */
  676. public get nonUniformScaling(): boolean {
  677. return this._nonUniformScaling;
  678. }
  679. /** @hidden */
  680. public _updateNonUniformScalingState(value: boolean): boolean {
  681. if (this._nonUniformScaling === value) {
  682. return false;
  683. }
  684. this._nonUniformScaling = value;
  685. return true;
  686. }
  687. /**
  688. * Attach the current TransformNode to another TransformNode associated with a bone
  689. * @param bone Bone affecting the TransformNode
  690. * @param affectedTransformNode TransformNode associated with the bone
  691. * @returns this object
  692. */
  693. public attachToBone(bone: Bone, affectedTransformNode: TransformNode): TransformNode {
  694. this._transformToBoneReferal = affectedTransformNode;
  695. this.parent = bone;
  696. if (bone.getWorldMatrix().determinant() < 0) {
  697. this.scalingDeterminant *= -1;
  698. }
  699. return this;
  700. }
  701. /**
  702. * Detach the transform node if its associated with a bone
  703. * @returns this object
  704. */
  705. public detachFromBone(): TransformNode {
  706. if (!this.parent) {
  707. return this;
  708. }
  709. if (this.parent.getWorldMatrix().determinant() < 0) {
  710. this.scalingDeterminant *= -1;
  711. }
  712. this._transformToBoneReferal = null;
  713. this.parent = null;
  714. return this;
  715. }
  716. private static _rotationAxisCache = new Quaternion();
  717. /**
  718. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  719. * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.
  720. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  721. * The passed axis is also normalized.
  722. * @param axis the axis to rotate around
  723. * @param amount the amount to rotate in radians
  724. * @param space Space to rotate in (Default: local)
  725. * @returns the TransformNode.
  726. */
  727. public rotate(axis: Vector3, amount: number, space?: Space): TransformNode {
  728. axis.normalize();
  729. if (!this.rotationQuaternion) {
  730. this.rotationQuaternion = this.rotation.toQuaternion();
  731. this.rotation.setAll(0);
  732. }
  733. var rotationQuaternion: Quaternion;
  734. if (!space || (space as any) === Space.LOCAL) {
  735. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  736. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  737. }
  738. else {
  739. if (this.parent) {
  740. const invertParentWorldMatrix = TmpVectors.Matrix[0];
  741. this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix);
  742. axis = Vector3.TransformNormal(axis, invertParentWorldMatrix);
  743. }
  744. rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  745. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  746. }
  747. return this;
  748. }
  749. /**
  750. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  751. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  752. * The passed axis is also normalized. .
  753. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  754. * @param point the point to rotate around
  755. * @param axis the axis to rotate around
  756. * @param amount the amount to rotate in radians
  757. * @returns the TransformNode
  758. */
  759. public rotateAround(point: Vector3, axis: Vector3, amount: number): TransformNode {
  760. axis.normalize();
  761. if (!this.rotationQuaternion) {
  762. this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  763. this.rotation.setAll(0);
  764. }
  765. const tmpVector = TmpVectors.Vector3[0];
  766. const finalScale = TmpVectors.Vector3[1];
  767. const finalTranslation = TmpVectors.Vector3[2];
  768. const finalRotation = TmpVectors.Quaternion[0];
  769. const translationMatrix = TmpVectors.Matrix[0]; // T
  770. const translationMatrixInv = TmpVectors.Matrix[1]; // T'
  771. const rotationMatrix = TmpVectors.Matrix[2]; // R
  772. const finalMatrix = TmpVectors.Matrix[3]; // T' x R x T
  773. point.subtractToRef(this.position, tmpVector);
  774. Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); // T
  775. Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); // T'
  776. Matrix.RotationAxisToRef(axis, amount, rotationMatrix); // R
  777. translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); // T' x R
  778. finalMatrix.multiplyToRef(translationMatrix, finalMatrix); // T' x R x T
  779. finalMatrix.decompose(finalScale, finalRotation, finalTranslation);
  780. this.position.addInPlace(finalTranslation);
  781. finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  782. return this;
  783. }
  784. /**
  785. * Translates the mesh along the axis vector for the passed distance in the given space.
  786. * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD.
  787. * @param axis the axis to translate in
  788. * @param distance the distance to translate
  789. * @param space Space to rotate in (Default: local)
  790. * @returns the TransformNode.
  791. */
  792. public translate(axis: Vector3, distance: number, space?: Space): TransformNode {
  793. var displacementVector = axis.scale(distance);
  794. if (!space || (space as any) === Space.LOCAL) {
  795. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  796. this.setPositionWithLocalVector(tempV3);
  797. }
  798. else {
  799. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  800. }
  801. return this;
  802. }
  803. /**
  804. * Adds a rotation step to the mesh current rotation.
  805. * x, y, z are Euler angles expressed in radians.
  806. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  807. * This means this rotation is made in the mesh local space only.
  808. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  809. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  810. * ```javascript
  811. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  812. * ```
  813. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  814. * 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.
  815. * @param x Rotation to add
  816. * @param y Rotation to add
  817. * @param z Rotation to add
  818. * @returns the TransformNode.
  819. */
  820. public addRotation(x: number, y: number, z: number): TransformNode {
  821. var rotationQuaternion;
  822. if (this.rotationQuaternion) {
  823. rotationQuaternion = this.rotationQuaternion;
  824. }
  825. else {
  826. rotationQuaternion = TmpVectors.Quaternion[1];
  827. Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  828. }
  829. var accumulation = TmpVectors.Quaternion[0];
  830. Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  831. rotationQuaternion.multiplyInPlace(accumulation);
  832. if (!this.rotationQuaternion) {
  833. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  834. }
  835. return this;
  836. }
  837. /**
  838. * @hidden
  839. */
  840. protected _getEffectiveParent(): Nullable<Node> {
  841. return this.parent;
  842. }
  843. /**
  844. * Computes the world matrix of the node
  845. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  846. * @returns the world matrix
  847. */
  848. public computeWorldMatrix(force?: boolean): Matrix {
  849. if (this._isWorldMatrixFrozen && !this._isDirty) {
  850. return this._worldMatrix;
  851. }
  852. let currentRenderId = this.getScene().getRenderId();
  853. if (!this._isDirty && !force && this.isSynchronized()) {
  854. this._currentRenderId = currentRenderId;
  855. return this._worldMatrix;
  856. }
  857. let camera = (<Camera>this.getScene().activeCamera);
  858. const useBillboardPosition = (this._billboardMode & TransformNode.BILLBOARDMODE_USE_POSITION) !== 0;
  859. const useBillboardPath = this._billboardMode !== TransformNode.BILLBOARDMODE_NONE && !this.preserveParentRotationForBillboard;
  860. // Billboarding based on camera position
  861. if (useBillboardPath && camera && useBillboardPosition) {
  862. this.lookAt(camera.position);
  863. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
  864. this.rotation.x = 0;
  865. }
  866. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
  867. this.rotation.y = 0;
  868. }
  869. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
  870. this.rotation.z = 0;
  871. }
  872. }
  873. this._updateCache();
  874. let cache = this._cache;
  875. cache.pivotMatrixUpdated = false;
  876. cache.billboardMode = this.billboardMode;
  877. cache.infiniteDistance = this.infiniteDistance;
  878. this._currentRenderId = currentRenderId;
  879. this._childUpdateId++;
  880. this._isDirty = false;
  881. let parent = this._getEffectiveParent();
  882. // Scaling
  883. let scaling: Vector3 = cache.scaling;
  884. let translation: Vector3 = cache.position;
  885. // Translation
  886. if (this._infiniteDistance) {
  887. if (!this.parent && camera) {
  888. var cameraWorldMatrix = camera.getWorldMatrix();
  889. var cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  890. translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z);
  891. } else {
  892. translation.copyFrom(this._position);
  893. }
  894. } else {
  895. translation.copyFrom(this._position);
  896. }
  897. // Scaling
  898. scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant);
  899. // Rotation
  900. let rotation: Quaternion = cache.rotationQuaternion;
  901. if (this._rotationQuaternion) {
  902. if (this.reIntegrateRotationIntoRotationQuaternion) {
  903. var len = this.rotation.lengthSquared();
  904. if (len) {
  905. this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z));
  906. this._rotation.copyFromFloats(0, 0, 0);
  907. }
  908. }
  909. rotation.copyFrom(this._rotationQuaternion);
  910. } else {
  911. Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation);
  912. cache.rotation.copyFrom(this._rotation);
  913. }
  914. // Compose
  915. if (this._usePivotMatrix) {
  916. let scaleMatrix = TmpVectors.Matrix[1];
  917. Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix);
  918. // Rotation
  919. let rotationMatrix = TmpVectors.Matrix[0];
  920. rotation.toRotationMatrix(rotationMatrix);
  921. // Composing transformations
  922. this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]);
  923. TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix);
  924. // Post multiply inverse of pivotMatrix
  925. if (this._postMultiplyPivotMatrix) {
  926. this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix);
  927. }
  928. this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z);
  929. } else {
  930. Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix);
  931. }
  932. // Parent
  933. if (parent && parent.getWorldMatrix) {
  934. if (force) {
  935. parent.computeWorldMatrix();
  936. }
  937. if (useBillboardPath) {
  938. if (this._transformToBoneReferal) {
  939. parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]);
  940. } else {
  941. TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix());
  942. }
  943. // Extract scaling and translation from parent
  944. let translation = TmpVectors.Vector3[5];
  945. let scale = TmpVectors.Vector3[6];
  946. TmpVectors.Matrix[7].decompose(scale, undefined, translation);
  947. Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]);
  948. TmpVectors.Matrix[7].setTranslation(translation);
  949. this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix);
  950. } else {
  951. if (this._transformToBoneReferal) {
  952. this._localMatrix.multiplyToRef(parent.getWorldMatrix(), TmpVectors.Matrix[6]);
  953. TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  954. } else {
  955. this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix);
  956. }
  957. }
  958. this._markSyncedWithParent();
  959. } else {
  960. this._worldMatrix.copyFrom(this._localMatrix);
  961. }
  962. // Billboarding based on camera orientation (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  963. if (useBillboardPath && camera && this.billboardMode && !useBillboardPosition) {
  964. let storedTranslation = TmpVectors.Vector3[0];
  965. this._worldMatrix.getTranslationToRef(storedTranslation); // Save translation
  966. // Cancel camera rotation
  967. TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix());
  968. TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0);
  969. TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]);
  970. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  971. TmpVectors.Matrix[0].decompose(undefined, TmpVectors.Quaternion[0], undefined);
  972. let eulerAngles = TmpVectors.Vector3[1];
  973. TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles);
  974. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) !== TransformNode.BILLBOARDMODE_X) {
  975. eulerAngles.x = 0;
  976. }
  977. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) !== TransformNode.BILLBOARDMODE_Y) {
  978. eulerAngles.y = 0;
  979. }
  980. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) !== TransformNode.BILLBOARDMODE_Z) {
  981. eulerAngles.z = 0;
  982. }
  983. Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]);
  984. }
  985. this._worldMatrix.setTranslationFromFloats(0, 0, 0);
  986. this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix);
  987. // Restore translation
  988. this._worldMatrix.setTranslation(TmpVectors.Vector3[0]);
  989. }
  990. // Normal matrix
  991. if (!this.ignoreNonUniformScaling) {
  992. if (this._scaling.isNonUniform) {
  993. this._updateNonUniformScalingState(true);
  994. } else if (parent && (<TransformNode>parent)._nonUniformScaling) {
  995. this._updateNonUniformScalingState((<TransformNode>parent)._nonUniformScaling);
  996. } else {
  997. this._updateNonUniformScalingState(false);
  998. }
  999. } else {
  1000. this._updateNonUniformScalingState(false);
  1001. }
  1002. this._afterComputeWorldMatrix();
  1003. // Absolute position
  1004. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  1005. this._isAbsoluteSynced = false;
  1006. // Callbacks
  1007. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  1008. if (!this._poseMatrix) {
  1009. this._poseMatrix = Matrix.Invert(this._worldMatrix);
  1010. }
  1011. // Cache the determinant
  1012. this._worldMatrixDeterminantIsDirty = true;
  1013. return this._worldMatrix;
  1014. }
  1015. protected _afterComputeWorldMatrix(): void {
  1016. }
  1017. /**
  1018. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  1019. * @param func callback function to add
  1020. *
  1021. * @returns the TransformNode.
  1022. */
  1023. public registerAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  1024. this.onAfterWorldMatrixUpdateObservable.add(func);
  1025. return this;
  1026. }
  1027. /**
  1028. * Removes a registered callback function.
  1029. * @param func callback function to remove
  1030. * @returns the TransformNode.
  1031. */
  1032. public unregisterAfterWorldMatrixUpdate(func: (mesh: TransformNode) => void): TransformNode {
  1033. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  1034. return this;
  1035. }
  1036. /**
  1037. * Gets the position of the current mesh in camera space
  1038. * @param camera defines the camera to use
  1039. * @returns a position
  1040. */
  1041. public getPositionInCameraSpace(camera: Nullable<Camera> = null): Vector3 {
  1042. if (!camera) {
  1043. camera = (<Camera>this.getScene().activeCamera);
  1044. }
  1045. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  1046. }
  1047. /**
  1048. * Returns the distance from the mesh to the active camera
  1049. * @param camera defines the camera to use
  1050. * @returns the distance
  1051. */
  1052. public getDistanceToCamera(camera: Nullable<Camera> = null): number {
  1053. if (!camera) {
  1054. camera = (<Camera>this.getScene().activeCamera);
  1055. }
  1056. return this.absolutePosition.subtract(camera.globalPosition).length();
  1057. }
  1058. /**
  1059. * Clone the current transform node
  1060. * @param name Name of the new clone
  1061. * @param newParent New parent for the clone
  1062. * @param doNotCloneChildren Do not clone children hierarchy
  1063. * @returns the new transform node
  1064. */
  1065. public clone(name: string, newParent: Nullable<Node>, doNotCloneChildren?: boolean) : Nullable<TransformNode> {
  1066. var result = SerializationHelper.Clone(() => new TransformNode(name, this.getScene()), this);
  1067. result.name = name;
  1068. result.id = name;
  1069. if (newParent) {
  1070. result.parent = newParent;
  1071. }
  1072. if (!doNotCloneChildren) {
  1073. // Children
  1074. let directDescendants = this.getDescendants(true);
  1075. for (let index = 0; index < directDescendants.length; index++) {
  1076. var child = directDescendants[index];
  1077. if ((<any>child).clone) {
  1078. (<any>child).clone(name + "." + child.name, result);
  1079. }
  1080. }
  1081. }
  1082. return result;
  1083. }
  1084. /**
  1085. * Serializes the objects information.
  1086. * @param currentSerializationObject defines the object to serialize in
  1087. * @returns the serialized object
  1088. */
  1089. public serialize(currentSerializationObject?: any): any {
  1090. let serializationObject = SerializationHelper.Serialize(this, currentSerializationObject);
  1091. serializationObject.type = this.getClassName();
  1092. // Parent
  1093. if (this.parent) {
  1094. serializationObject.parentId = this.parent.id;
  1095. }
  1096. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  1097. serializationObject.isEnabled = this.isEnabled();
  1098. // Parent
  1099. if (this.parent) {
  1100. serializationObject.parentId = this.parent.id;
  1101. }
  1102. return serializationObject;
  1103. }
  1104. // Statics
  1105. /**
  1106. * Returns a new TransformNode object parsed from the source provided.
  1107. * @param parsedTransformNode is the source.
  1108. * @param scene the scne the object belongs to
  1109. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  1110. * @returns a new TransformNode object parsed from the source provided.
  1111. */
  1112. public static Parse(parsedTransformNode: any, scene: Scene, rootUrl: string): TransformNode {
  1113. var transformNode = SerializationHelper.Parse(() => new TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl);
  1114. if (parsedTransformNode.localMatrix) {
  1115. transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix));
  1116. } else if (parsedTransformNode.pivotMatrix) {
  1117. transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix));
  1118. }
  1119. transformNode.setEnabled(parsedTransformNode.isEnabled);
  1120. // Parent
  1121. if (parsedTransformNode.parentId) {
  1122. transformNode._waitingParentId = parsedTransformNode.parentId;
  1123. }
  1124. return transformNode;
  1125. }
  1126. /**
  1127. * Get all child-transformNodes of this node
  1128. * @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
  1129. * @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
  1130. * @returns an array of TransformNode
  1131. */
  1132. public getChildTransformNodes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): TransformNode[] {
  1133. var results: Array<TransformNode> = [];
  1134. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  1135. return ((!predicate || predicate(node)) && (node instanceof TransformNode));
  1136. });
  1137. return results;
  1138. }
  1139. /**
  1140. * Releases resources associated with this transform node.
  1141. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1142. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1143. */
  1144. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1145. // Animations
  1146. this.getScene().stopAnimation(this);
  1147. // Remove from scene
  1148. this.getScene().removeTransformNode(this);
  1149. this.onAfterWorldMatrixUpdateObservable.clear();
  1150. if (doNotRecurse) {
  1151. const transformNodes = this.getChildTransformNodes(true);
  1152. for (const transformNode of transformNodes) {
  1153. transformNode.parent = null;
  1154. transformNode.computeWorldMatrix(true);
  1155. }
  1156. }
  1157. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1158. }
  1159. /**
  1160. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  1161. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false
  1162. * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false
  1163. * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling
  1164. * @returns the current mesh
  1165. */
  1166. public normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate?: Nullable<(node: AbstractMesh) => boolean>): TransformNode {
  1167. let storedRotation: Nullable<Vector3> = null;
  1168. let storedRotationQuaternion: Nullable<Quaternion> = null;
  1169. if (ignoreRotation) {
  1170. if (this.rotationQuaternion) {
  1171. storedRotationQuaternion = this.rotationQuaternion.clone();
  1172. this.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  1173. } else if (this.rotation) {
  1174. storedRotation = this.rotation.clone();
  1175. this.rotation.copyFromFloats(0, 0, 0);
  1176. }
  1177. }
  1178. let boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate);
  1179. let sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  1180. let maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  1181. if (maxDimension === 0) {
  1182. return this;
  1183. }
  1184. let scale = 1 / maxDimension;
  1185. this.scaling.scaleInPlace(scale);
  1186. if (ignoreRotation) {
  1187. if (this.rotationQuaternion && storedRotationQuaternion) {
  1188. this.rotationQuaternion.copyFrom(storedRotationQuaternion);
  1189. } else if (this.rotation && storedRotation) {
  1190. this.rotation.copyFrom(storedRotation);
  1191. }
  1192. }
  1193. return this;
  1194. }
  1195. private _syncAbsoluteScalingAndRotation(): void {
  1196. if (!this._isAbsoluteSynced) {
  1197. this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion);
  1198. this._isAbsoluteSynced = true;
  1199. }
  1200. }
  1201. }