babylon.node.ts 27 KB

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