babylon.node.ts 24 KB

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