babylon.node.ts 26 KB

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