babylon.node.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. module BABYLON {
  2. /**
  3. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4. */
  5. export class Node implements IBehaviorAware<Node> {
  6. /**
  7. * Gets or sets the name of the node
  8. */
  9. @serialize()
  10. public name: string;
  11. /**
  12. * Gets or sets the id of the node
  13. */
  14. @serialize()
  15. public id: string;
  16. /**
  17. * Gets or sets the unique id of the node
  18. */
  19. @serialize()
  20. public uniqueId: number;
  21. /**
  22. * Gets or sets a string used to store user defined state for the node
  23. */
  24. @serialize()
  25. public state = "";
  26. /**
  27. * Gets or sets an object used to store user defined information for the node
  28. */
  29. @serialize()
  30. public metadata: any = null;
  31. /**
  32. * Gets or sets a boolean used to define if the node must be serialized
  33. */
  34. public doNotSerialize = false;
  35. /** @hidden */
  36. public _isDisposed = false;
  37. /**
  38. * Gets a list of Animations associated with the node
  39. */
  40. public animations = new Array<Animation>();
  41. private _ranges: { [name: string]: Nullable<AnimationRange> } = {};
  42. /**
  43. * Callback raised when the node is ready to be used
  44. */
  45. public onReady: (node: Node) => void;
  46. private _isEnabled = true;
  47. private _isReady = true;
  48. /** @hidden */
  49. public _currentRenderId = -1;
  50. private _parentRenderId = -1;
  51. protected _childRenderId = -1;
  52. /** @hidden */
  53. public _waitingParentId: Nullable<string>;
  54. private _scene: Scene;
  55. /** @hidden */
  56. public _cache: any;
  57. private _parentNode: Nullable<Node>;
  58. private _children: Node[];
  59. /**
  60. * Gets a boolean indicating if the node has been disposed
  61. * @returns true if the node was disposed
  62. */
  63. public isDisposed(): boolean {
  64. return this._isDisposed;
  65. }
  66. /**
  67. * Gets or sets the parent of the node
  68. */
  69. public set parent(parent: Nullable<Node>) {
  70. if (this._parentNode === parent) {
  71. return;
  72. }
  73. // Remove self from list of children of parent
  74. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  75. var index = this._parentNode._children.indexOf(this);
  76. if (index !== -1) {
  77. this._parentNode._children.splice(index, 1);
  78. }
  79. }
  80. // Store new parent
  81. this._parentNode = parent;
  82. // Add as child to new parent
  83. if (this._parentNode) {
  84. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  85. this._parentNode._children = new Array<Node>();
  86. }
  87. this._parentNode._children.push(this);
  88. }
  89. }
  90. public get parent(): Nullable<Node> {
  91. return this._parentNode;
  92. }
  93. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  94. /**
  95. * Gets or sets the animation properties override
  96. */
  97. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  98. if (!this._animationPropertiesOverride) {
  99. return this._scene.animationPropertiesOverride;
  100. }
  101. return this._animationPropertiesOverride;
  102. }
  103. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  104. this._animationPropertiesOverride = value;
  105. }
  106. /**
  107. * Gets a string idenfifying the name of the class
  108. * @returns "Node" string
  109. */
  110. public getClassName(): string {
  111. return "Node";
  112. }
  113. /**
  114. * An event triggered when the mesh is disposed
  115. */
  116. public onDisposeObservable = new Observable<Node>();
  117. private _onDisposeObserver: Nullable<Observer<Node>>;
  118. /**
  119. * Sets a callback that will be raised when the node will be disposed
  120. */
  121. public set onDispose(callback: () => void) {
  122. if (this._onDisposeObserver) {
  123. this.onDisposeObservable.remove(this._onDisposeObserver);
  124. }
  125. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  126. }
  127. /**
  128. * Creates a new Node
  129. * @param {string} name - the name and id to be given to this node
  130. * @param {BABYLON.Scene} the scene this node will be added to
  131. */
  132. constructor(name: string, scene: Nullable<Scene> = null) {
  133. this.name = name;
  134. this.id = name;
  135. this._scene = <Scene>(scene || Engine.LastCreatedScene);
  136. this.uniqueId = this._scene.getUniqueId();
  137. this._initCache();
  138. }
  139. /**
  140. * Gets the scene of the node
  141. * @returns a {BABYLON.Scene}
  142. */
  143. public getScene(): Scene {
  144. return this._scene;
  145. }
  146. /**
  147. * Gets the engine of the node
  148. * @returns a {BABYLON.Engine}
  149. */
  150. public getEngine(): Engine {
  151. return this._scene.getEngine();
  152. }
  153. // Behaviors
  154. private _behaviors = new Array<Behavior<Node>>();
  155. /**
  156. * Attach a behavior to the node
  157. * @see http://doc.babylonjs.com/features/behaviour
  158. * @param behavior defines the behavior to attach
  159. * @returns the current Node
  160. */
  161. public addBehavior(behavior: Behavior<Node>): Node {
  162. var index = this._behaviors.indexOf(behavior);
  163. if (index !== -1) {
  164. return this;
  165. }
  166. behavior.init();
  167. if (this._scene.isLoading) {
  168. // We defer the attach when the scene will be loaded
  169. this._scene.onDataLoadedObservable.addOnce(() => {
  170. behavior.attach(this);
  171. });
  172. } else {
  173. behavior.attach(this);
  174. }
  175. this._behaviors.push(behavior);
  176. return this;
  177. }
  178. /**
  179. * Remove an attached behavior
  180. * @see http://doc.babylonjs.com/features/behaviour
  181. * @param behavior defines the behavior to attach
  182. * @returns the current Node
  183. */
  184. public removeBehavior(behavior: Behavior<Node>): Node {
  185. var index = this._behaviors.indexOf(behavior);
  186. if (index === -1) {
  187. return this;
  188. }
  189. this._behaviors[index].detach();
  190. this._behaviors.splice(index, 1);
  191. return this;
  192. }
  193. /**
  194. * Gets the list of attached behaviors
  195. * @see http://doc.babylonjs.com/features/behaviour
  196. */
  197. public get behaviors(): Behavior<Node>[] {
  198. return this._behaviors;
  199. }
  200. /**
  201. * Gets an attached behavior by name
  202. * @param name defines the name of the behavior to look for
  203. * @see http://doc.babylonjs.com/features/behaviour
  204. * @returns null if behavior was not found else the requested behavior
  205. */
  206. public getBehaviorByName(name: string): Nullable<Behavior<Node>> {
  207. for (var behavior of this._behaviors) {
  208. if (behavior.name === name) {
  209. return behavior;
  210. }
  211. }
  212. return null;
  213. }
  214. /**
  215. * Returns the world matrix of the node
  216. * @returns a matrix containing the node's world matrix
  217. */
  218. public getWorldMatrix(): Matrix {
  219. return Matrix.Identity();
  220. }
  221. /** @hidden */
  222. public _getWorldMatrixDeterminant(): number {
  223. return 1;
  224. }
  225. // override it in derived class if you add new variables to the cache
  226. // and call the parent class method
  227. /** @hidden */
  228. public _initCache() {
  229. this._cache = {};
  230. this._cache.parent = undefined;
  231. }
  232. /** @hidden */
  233. public updateCache(force?: boolean): void {
  234. if (!force && this.isSynchronized())
  235. return;
  236. this._cache.parent = this.parent;
  237. this._updateCache();
  238. }
  239. // override it in derived class if you add new variables to the cache
  240. // and call the parent class method if !ignoreParentClass
  241. /** @hidden */
  242. public _updateCache(ignoreParentClass?: boolean): void {
  243. }
  244. // override it in derived class if you add new variables to the cache
  245. /** @hidden */
  246. public _isSynchronized(): boolean {
  247. return true;
  248. }
  249. /** @hidden */
  250. public _markSyncedWithParent() {
  251. if (this.parent) {
  252. this._parentRenderId = this.parent._childRenderId;
  253. }
  254. }
  255. /** @hidden */
  256. public isSynchronizedWithParent(): boolean {
  257. if (!this.parent) {
  258. return true;
  259. }
  260. if (this._parentRenderId !== this.parent._childRenderId) {
  261. return false;
  262. }
  263. return this.parent.isSynchronized();
  264. }
  265. /** @hidden */
  266. public isSynchronized(updateCache?: boolean): boolean {
  267. var check = this.hasNewParent();
  268. check = check || !this.isSynchronizedWithParent();
  269. check = check || !this._isSynchronized();
  270. if (updateCache)
  271. this.updateCache(true);
  272. return !check;
  273. }
  274. /** @hidden */
  275. public hasNewParent(update?: boolean): boolean {
  276. if (this._cache.parent === this.parent)
  277. return false;
  278. if (update)
  279. this._cache.parent = this.parent;
  280. return true;
  281. }
  282. /**
  283. * Is this node ready to be used/rendered
  284. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  285. * @return true if the node is ready
  286. */
  287. public isReady(completeCheck = false): boolean {
  288. return this._isReady;
  289. }
  290. /**
  291. * Is this node enabled?
  292. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
  293. * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
  294. * @return whether this node (and its parent) is enabled
  295. */
  296. public isEnabled(checkAncestors: boolean = true): boolean {
  297. if (checkAncestors === false) {
  298. return this._isEnabled;
  299. }
  300. if (this._isEnabled === false) {
  301. return false;
  302. }
  303. if (this.parent !== undefined && this.parent !== null) {
  304. return this.parent.isEnabled(checkAncestors);
  305. }
  306. return true;
  307. }
  308. /**
  309. * Set the enabled state of this node
  310. * @param value defines the new enabled state
  311. */
  312. public setEnabled(value: boolean): void {
  313. this._isEnabled = value;
  314. }
  315. /**
  316. * Is this node a descendant of the given node?
  317. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  318. * @param ancestor defines the parent node to inspect
  319. * @returns a boolean indicating if this node is a descendant of the given node
  320. */
  321. public isDescendantOf(ancestor: Node): boolean {
  322. if (this.parent) {
  323. if (this.parent === ancestor) {
  324. return true;
  325. }
  326. return this.parent.isDescendantOf(ancestor);
  327. }
  328. return false;
  329. }
  330. /** @hidden */
  331. public _getDescendants(results: Node[], directDescendantsOnly: boolean = false, predicate?: (node: Node) => boolean): void {
  332. if (!this._children) {
  333. return;
  334. }
  335. for (var index = 0; index < this._children.length; index++) {
  336. var item = this._children[index];
  337. if (!predicate || predicate(item)) {
  338. results.push(item);
  339. }
  340. if (!directDescendantsOnly) {
  341. item._getDescendants(results, false, predicate);
  342. }
  343. }
  344. }
  345. /**
  346. * Will return all nodes that have this node as ascendant
  347. * @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
  348. * @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
  349. * @return all children nodes of all types
  350. */
  351. public getDescendants(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): Node[] {
  352. var results = new Array<Node>();
  353. this._getDescendants(results, directDescendantsOnly, predicate);
  354. return results;
  355. }
  356. /**
  357. * Get all child-meshes of this node
  358. * @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
  359. * @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
  360. * @returns an array of {BABYLON.AbstractMesh}
  361. */
  362. public getChildMeshes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): AbstractMesh[] {
  363. var results: Array<AbstractMesh> = [];
  364. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  365. return ((!predicate || predicate(node)) && (node instanceof AbstractMesh));
  366. });
  367. return results;
  368. }
  369. /**
  370. * Get all child-transformNodes of this node
  371. * @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
  372. * @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
  373. * @returns an array of {BABYLON.TransformNode}
  374. */
  375. public getChildTransformNodes(directDescendantsOnly?: boolean, predicate?: (node: Node) => boolean): TransformNode[] {
  376. var results: Array<TransformNode> = [];
  377. this._getDescendants(results, directDescendantsOnly, (node: Node) => {
  378. return ((!predicate || predicate(node)) && (node instanceof TransformNode));
  379. });
  380. return results;
  381. }
  382. /**
  383. * Get all direct children of this node
  384. * @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
  385. * @returns an array of {BABYLON.Node}
  386. */
  387. public getChildren(predicate?: (node: Node) => boolean): Node[] {
  388. return this.getDescendants(true, predicate);
  389. }
  390. /** @hidden */
  391. public _setReady(state: boolean): void {
  392. if (state === this._isReady) {
  393. return;
  394. }
  395. if (!state) {
  396. this._isReady = false;
  397. return;
  398. }
  399. if (this.onReady) {
  400. this.onReady(this);
  401. }
  402. this._isReady = true;
  403. }
  404. /**
  405. * Get an animation by name
  406. * @param name defines the name of the animation to look for
  407. * @returns null if not found else the requested animation
  408. */
  409. public getAnimationByName(name: string): Nullable<Animation> {
  410. for (var i = 0; i < this.animations.length; i++) {
  411. var animation = this.animations[i];
  412. if (animation.name === name) {
  413. return animation;
  414. }
  415. }
  416. return null;
  417. }
  418. /**
  419. * Creates an animation range for this node
  420. * @param name defines the name of the range
  421. * @param from defines the starting key
  422. * @param to defines the end key
  423. */
  424. public createAnimationRange(name: string, from: number, to: number): void {
  425. // check name not already in use
  426. if (!this._ranges[name]) {
  427. this._ranges[name] = new AnimationRange(name, from, to);
  428. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  429. if (this.animations[i]) {
  430. this.animations[i].createRange(name, from, to);
  431. }
  432. }
  433. }
  434. }
  435. /**
  436. * Delete a specific animation range
  437. * @param name defines the name of the range to delete
  438. * @param deleteFrames defines if animation frames from the range must be deleted as well
  439. */
  440. public deleteAnimationRange(name: string, deleteFrames = true): void {
  441. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  442. if (this.animations[i]) {
  443. this.animations[i].deleteRange(name, deleteFrames);
  444. }
  445. }
  446. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  447. }
  448. /**
  449. * Get an animation range by name
  450. * @param name defines the name of the animation range to look for
  451. * @returns null if not found else the requested animation range
  452. */
  453. public getAnimationRange(name: string): Nullable<AnimationRange> {
  454. return this._ranges[name];
  455. }
  456. /**
  457. * Will start the animation sequence
  458. * @param name defines the range frames for animation sequence
  459. * @param loop defines if the animation should loop (false by default)
  460. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  461. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  462. * @returns the object created for this animation. If range does not exist, it will return null
  463. */
  464. public beginAnimation(name: string, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Nullable<Animatable> {
  465. var range = this.getAnimationRange(name);
  466. if (!range) {
  467. return null;
  468. }
  469. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  470. }
  471. /**
  472. * Serialize animation ranges into a JSON compatible object
  473. * @returns serialization object
  474. */
  475. public serializeAnimationRanges(): any {
  476. var serializationRanges = [];
  477. for (var name in this._ranges) {
  478. var localRange = this._ranges[name];
  479. if (!localRange) {
  480. continue;
  481. }
  482. var range: any = {};
  483. range.name = name;
  484. range.from = localRange.from;
  485. range.to = localRange.to;
  486. serializationRanges.push(range);
  487. }
  488. return serializationRanges;
  489. }
  490. /**
  491. * Computes the world matrix of the node
  492. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  493. * @returns the world matrix
  494. */
  495. public computeWorldMatrix(force?: boolean): Matrix {
  496. return Matrix.Identity();
  497. }
  498. /**
  499. * Releases resources associated with this node.
  500. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  501. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  502. */
  503. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  504. if (!doNotRecurse) {
  505. const nodes = this.getDescendants(true);
  506. for (const node of nodes) {
  507. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  508. }
  509. } else {
  510. const transformNodes = this.getChildTransformNodes(true);
  511. for (const transformNode of transformNodes) {
  512. transformNode.parent = null;
  513. transformNode.computeWorldMatrix(true);
  514. }
  515. }
  516. this.parent = null;
  517. // Callback
  518. this.onDisposeObservable.notifyObservers(this);
  519. this.onDisposeObservable.clear();
  520. // Behaviors
  521. for (var behavior of this._behaviors) {
  522. behavior.detach();
  523. }
  524. this._behaviors = [];
  525. this._isDisposed = true;
  526. }
  527. /**
  528. * Parse animation range data from a serialization object and store them into a given node
  529. * @param node defines where to store the animation ranges
  530. * @param parsedNode defines the serialization object to read data from
  531. * @param scene defines the hosting scene
  532. */
  533. public static ParseAnimationRanges(node: Node, parsedNode: any, scene: Scene): void {
  534. if (parsedNode.ranges) {
  535. for (var index = 0; index < parsedNode.ranges.length; index++) {
  536. var data = parsedNode.ranges[index];
  537. node.createAnimationRange(data.name, data.from, data.to);
  538. }
  539. }
  540. }
  541. }
  542. }