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 {
  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. /** @ignore */
  36. public _isDisposed = false;
  37. /**
  38. * Gets a list of {BABYLON.Animation} 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. /** @ignore */
  49. public _currentRenderId = -1;
  50. private _parentRenderId = -1;
  51. /** @ignore */
  52. public _waitingParentId: Nullable<string>;
  53. private _scene: Scene;
  54. /** @ignore */
  55. public _cache: any;
  56. private _parentNode: Nullable<Node>;
  57. private _children: Node[];
  58. /**
  59. * Gets a boolean indicating if the node has been disposed
  60. * @returns true if the node was disposed
  61. */
  62. public isDisposed(): boolean {
  63. return this._isDisposed;
  64. }
  65. /**
  66. * Gets or sets the parent of the node
  67. */
  68. public set parent(parent: Nullable<Node>) {
  69. if (this._parentNode === parent) {
  70. return;
  71. }
  72. // Remove self from list of children of parent
  73. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  74. var index = this._parentNode._children.indexOf(this);
  75. if (index !== -1) {
  76. this._parentNode._children.splice(index, 1);
  77. }
  78. }
  79. // Store new parent
  80. this._parentNode = parent;
  81. // Add as child to new parent
  82. if (this._parentNode) {
  83. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  84. this._parentNode._children = new Array<Node>();
  85. }
  86. this._parentNode._children.push(this);
  87. }
  88. }
  89. public get parent(): Nullable<Node> {
  90. return this._parentNode;
  91. }
  92. private _animationPropertiesOverride: Nullable<AnimationPropertiesOverride> = null;
  93. /**
  94. * Gets or sets the animation properties override
  95. */
  96. public get animationPropertiesOverride(): Nullable<AnimationPropertiesOverride> {
  97. return this._animationPropertiesOverride;
  98. }
  99. public set animationPropertiesOverride(value: Nullable<AnimationPropertiesOverride>) {
  100. this._animationPropertiesOverride = value;
  101. }
  102. /**
  103. * Gets a string idenfifying the name of the class
  104. * @returns "Node" string
  105. */
  106. public getClassName(): string {
  107. return "Node";
  108. }
  109. /**
  110. * An event triggered when the mesh is disposed
  111. * @type {BABYLON.Observable}
  112. */
  113. public onDisposeObservable = new Observable<Node>();
  114. private _onDisposeObserver: Nullable<Observer<Node>>;
  115. /**
  116. * Sets a callback that will be raised when the node will be disposed
  117. */
  118. public set onDispose(callback: () => void) {
  119. if (this._onDisposeObserver) {
  120. this.onDisposeObservable.remove(this._onDisposeObserver);
  121. }
  122. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  123. }
  124. /**
  125. * Creates a new Node
  126. * @param {string} name - the name and id to be given to this node
  127. * @param {BABYLON.Scene} the scene this node will be added to
  128. */
  129. constructor(name: string, scene: Nullable<Scene> = null) {
  130. this.name = name;
  131. this.id = name;
  132. this._scene = <Scene>(scene || Engine.LastCreatedScene);
  133. this.uniqueId = this._scene.getUniqueId();
  134. this._initCache();
  135. }
  136. /**
  137. * Gets the scene of the node
  138. * @returns a {BABYLON.Scene}
  139. */
  140. public getScene(): Scene {
  141. return this._scene;
  142. }
  143. /**
  144. * Gets the engine of the node
  145. * @returns a {BABYLON.Engine}
  146. */
  147. public getEngine(): Engine {
  148. return this._scene.getEngine();
  149. }
  150. // Behaviors
  151. private _behaviors = new Array<Behavior<Node>>();
  152. /**
  153. * Attach a behavior to the node
  154. * @see http://doc.babylonjs.com/features/behaviour
  155. * @param behavior defines the behavior to attach
  156. * @returns the current Node
  157. */
  158. public addBehavior(behavior: Behavior<Node>): Node {
  159. var index = this._behaviors.indexOf(behavior);
  160. if (index !== -1) {
  161. return this;
  162. }
  163. behavior.init();
  164. if (this._scene.isLoading) {
  165. // We defer the attach when the scene will be loaded
  166. var observer = this._scene.onDataLoadedObservable.add(() => {
  167. behavior.attach(this);
  168. setTimeout(() => {
  169. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  170. this._scene.onDataLoadedObservable.remove(observer);
  171. }, 0);
  172. });
  173. } else {
  174. behavior.attach(this);
  175. }
  176. this._behaviors.push(behavior);
  177. return this;
  178. }
  179. /**
  180. * Remove an attached behavior
  181. * @see http://doc.babylonjs.com/features/behaviour
  182. * @param behavior defines the behavior to attach
  183. * @returns the current Node
  184. */
  185. public removeBehavior(behavior: Behavior<Node>): Node {
  186. var index = this._behaviors.indexOf(behavior);
  187. if (index === -1) {
  188. return this;
  189. }
  190. this._behaviors[index].detach();
  191. this._behaviors.splice(index, 1);
  192. return this;
  193. }
  194. /**
  195. * Gets the list of attached behaviors
  196. * @see http://doc.babylonjs.com/features/behaviour
  197. */
  198. public get behaviors(): Behavior<Node>[] {
  199. return this._behaviors;
  200. }
  201. /**
  202. * Gets an attached behavior by name
  203. * @param name defines the name of the behavior to look for
  204. * @see http://doc.babylonjs.com/features/behaviour
  205. * @returns null if behavior was not found else the requested behavior
  206. */
  207. public getBehaviorByName(name: string): Nullable<Behavior<Node>> {
  208. for (var behavior of this._behaviors) {
  209. if (behavior.name === name) {
  210. return behavior;
  211. }
  212. }
  213. return null;
  214. }
  215. /**
  216. * Returns the world matrix of the node
  217. * @returns a matrix containing the node's world matrix
  218. */
  219. public getWorldMatrix(): Matrix {
  220. return Matrix.Identity();
  221. }
  222. // override it in derived class if you add new variables to the cache
  223. // and call the parent class method
  224. /** @ignore */
  225. public _initCache() {
  226. this._cache = {};
  227. this._cache.parent = undefined;
  228. }
  229. /** @ignore */
  230. public updateCache(force?: boolean): void {
  231. if (!force && this.isSynchronized())
  232. return;
  233. this._cache.parent = this.parent;
  234. this._updateCache();
  235. }
  236. // override it in derived class if you add new variables to the cache
  237. // and call the parent class method if !ignoreParentClass
  238. /** @ignore */
  239. public _updateCache(ignoreParentClass?: boolean): void {
  240. }
  241. // override it in derived class if you add new variables to the cache
  242. /** @ignore */
  243. public _isSynchronized(): boolean {
  244. return true;
  245. }
  246. /** @ignore */
  247. public _markSyncedWithParent() {
  248. if (this.parent) {
  249. this._parentRenderId = this.parent._currentRenderId;
  250. }
  251. }
  252. /** @ignore */
  253. public isSynchronizedWithParent(): boolean {
  254. if (!this.parent) {
  255. return true;
  256. }
  257. if (this._parentRenderId !== this.parent._currentRenderId) {
  258. return false;
  259. }
  260. return this.parent.isSynchronized();
  261. }
  262. /** @ignore */
  263. public isSynchronized(updateCache?: boolean): boolean {
  264. var check = this.hasNewParent();
  265. check = check || !this.isSynchronizedWithParent();
  266. check = check || !this._isSynchronized();
  267. if (updateCache)
  268. this.updateCache(true);
  269. return !check;
  270. }
  271. /** @ignore */
  272. public hasNewParent(update?: boolean): boolean {
  273. if (this._cache.parent === this.parent)
  274. return false;
  275. if (update)
  276. this._cache.parent = this.parent;
  277. return true;
  278. }
  279. /**
  280. * Is this node ready to be used/rendered
  281. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  282. * @return true if the node is ready
  283. */
  284. public isReady(completeCheck = false): boolean {
  285. return this._isReady;
  286. }
  287. /**
  288. * Is this node enabled?
  289. * 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
  290. * @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
  291. * @return whether this node (and its parent) is enabled
  292. * @see setEnabled
  293. */
  294. public isEnabled(checkAncestors: boolean = true): boolean {
  295. if (checkAncestors === false) {
  296. return this._isEnabled;
  297. }
  298. if (this._isEnabled === false) {
  299. return false;
  300. }
  301. if (this.parent !== undefined && this.parent !== null) {
  302. return this.parent.isEnabled(checkAncestors);
  303. }
  304. return true;
  305. }
  306. /**
  307. * Set the enabled state of this node
  308. * @param value defines the new enabled state
  309. * @see isEnabled
  310. */
  311. public setEnabled(value: boolean): void {
  312. this._isEnabled = value;
  313. }
  314. /**
  315. * Is this node a descendant of the given node?
  316. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  317. * @param ancestor defines the parent node to inspect
  318. * @see parent
  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. /** @ignore */
  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. /** @ignore */
  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. }