Node.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // A node is the basic container in the scene graph. Its basically a point in
  4. // transformations that can contain child nodes (and inherit transformations),
  5. // and contain renderable entities to draw inside.
  6. //
  7. // Author: Ronen Ness.
  8. // Since: 2017.
  9. //-----------------------------------------------------------------------------
  10. #endregion
  11. using Microsoft.Xna.Framework;
  12. using System.Collections.Generic;
  13. namespace MonoGameSceneGraph
  14. {
  15. /// <summary>
  16. /// A callback function you can register on different node-related events.
  17. /// </summary>
  18. /// <param name="node">The node instance the event came from.</param>
  19. public delegate void NodeEventCallback(Node node);
  20. /// <summary>
  21. /// A node with transformations, you can attach renderable entities to it, or append
  22. /// child nodes to inherit transformations.
  23. /// </summary>
  24. public class Node
  25. {
  26. /// <summary>
  27. /// Parent node.
  28. /// </summary>
  29. protected Node _parent = null;
  30. /// <summary>
  31. /// Callback that triggers every time a node updates its matrix.
  32. /// </summary>
  33. public static NodeEventCallback OnTransformationsUpdate;
  34. /// <summary>
  35. /// Callback that triggers every time a node is rendered.
  36. /// Note: nodes that are culled out should not trigger this.
  37. /// </summary>
  38. public static NodeEventCallback OnDraw;
  39. /// <summary>
  40. /// Node's transformations.
  41. /// </summary>
  42. protected Transformations _transformations = new Transformations();
  43. /// <summary>
  44. /// Is this node currently visible?
  45. /// </summary>
  46. public virtual bool Visible { get; set; }
  47. /// <summary>
  48. /// Optional identifier we can give to nodes.
  49. /// </summary>
  50. public string Identifier;
  51. /// <summary>
  52. /// Optional user data we can attach to nodes.
  53. /// </summary>
  54. public object UserData;
  55. /// <summary>
  56. /// Const return value for null bounding box.
  57. /// </summary>
  58. private static readonly BoundingBox EmptyBoundingBox = new BoundingBox();
  59. /// <summary>
  60. /// Local transformations matrix, eg the result of the current local transformations.
  61. /// </summary>
  62. protected Matrix _localTransform = Matrix.Identity;
  63. /// <summary>
  64. /// World transformations matrix, eg the result of the local transformations multiplied with parent transformations.
  65. /// </summary>
  66. protected Matrix _worldTransform = Matrix.Identity;
  67. /// <summary>
  68. /// Child nodes under this node.
  69. /// </summary>
  70. protected List<Node> _childNodes = new List<Node>();
  71. /// <summary>
  72. /// Child entities under this node.
  73. /// </summary>
  74. protected List<IEntity> _childEntities = new List<IEntity>();
  75. /// <summary>
  76. /// Turns true when the transformations of this node changes.
  77. /// </summary>
  78. protected bool _isDirty = true;
  79. /// <summary>
  80. /// This number increment every time we update transformations.
  81. /// We use it to check if our parent's transformations had been changed since last
  82. /// time this node was rendered, and if so, we re-apply parent updated transformations.
  83. /// </summary>
  84. protected uint _transformVersion = 0;
  85. /// <summary>
  86. /// The last transformations version we got from our parent.
  87. /// </summary>
  88. protected uint _parentLastTransformVersion = 0;
  89. /// <summary>
  90. /// Get parent node.
  91. /// </summary>
  92. public Node Parent { get { return _parent; } }
  93. /// <summary>
  94. /// Transformation version is a special identifier that changes whenever the world transformations
  95. /// of this node changes. Its not necessarily a sequence, but if you check this number for changes every
  96. /// frame its a good indication of transformation change.
  97. /// </summary>
  98. public uint TransformVersion { get { return _transformVersion; } }
  99. /// <summary>
  100. /// Create the new node.
  101. /// </summary>
  102. public Node()
  103. {
  104. Visible = true;
  105. }
  106. /// <summary>
  107. /// Clone this scene node.
  108. /// </summary>
  109. /// <returns>Node copy.</returns>
  110. public virtual Node Clone()
  111. {
  112. Node ret = new Node();
  113. ret._transformations = _transformations.Clone();
  114. ret.Visible = Visible;
  115. return ret;
  116. }
  117. /// <summary>
  118. /// Draw the node and its children.
  119. /// </summary>
  120. public virtual void Draw()
  121. {
  122. // not visible? skip
  123. if (!Visible)
  124. {
  125. return;
  126. }
  127. // update transformations (only if needed, testing logic is inside)
  128. UpdateTransformations();
  129. // draw all child nodes
  130. foreach (Node node in _childNodes)
  131. {
  132. node.Draw();
  133. }
  134. // trigger draw event
  135. OnDraw?.Invoke(this);
  136. // draw all child entities
  137. foreach (IEntity entity in _childEntities)
  138. {
  139. entity.Draw(this, _localTransform, _worldTransform);
  140. }
  141. }
  142. /// <summary>
  143. /// Add an entity to this node.
  144. /// </summary>
  145. /// <param name="entity">Entity to add.</param>
  146. public void AddEntity(IEntity entity)
  147. {
  148. _childEntities.Add(entity);
  149. OnEntitiesListChange(entity, true);
  150. }
  151. /// <summary>
  152. /// Remove an entity from this node.
  153. /// </summary>
  154. /// <param name="entity">Entity to add.</param>
  155. public void RemoveEntity(IEntity entity)
  156. {
  157. _childEntities.Remove(entity);
  158. OnEntitiesListChange(entity, false);
  159. }
  160. /// <summary>
  161. /// Called whenever a child node was added / removed from this node.
  162. /// </summary>
  163. /// <param name="entity">Entity that was added / removed.</param>
  164. /// <param name="wasAdded">If true its an entity that was added, if false, an entity that was removed.</param>
  165. virtual protected void OnEntitiesListChange(IEntity entity, bool wasAdded)
  166. {
  167. }
  168. /// <summary>
  169. /// Called whenever an entity was added / removed from this node.
  170. /// </summary>
  171. /// <param name="node">Node that was added / removed.</param>
  172. /// <param name="wasAdded">If true its a node that was added, if false, a node that was removed.</param>
  173. virtual protected void OnChildNodesListChange(Node node, bool wasAdded)
  174. {
  175. }
  176. /// <summary>
  177. /// Add a child node to this node.
  178. /// </summary>
  179. /// <param name="node">Node to add.</param>
  180. public void AddChildNode(Node node)
  181. {
  182. // node already got a parent?
  183. if (node._parent != null)
  184. {
  185. throw new System.Exception("Can't add a node that already have a parent.");
  186. }
  187. // add node to children list
  188. _childNodes.Add(node);
  189. // set self as node's parent
  190. node.SetParent(this);
  191. OnChildNodesListChange(node, true);
  192. }
  193. /// <summary>
  194. /// Remove a child node from this node.
  195. /// </summary>
  196. /// <param name="node">Node to add.</param>
  197. public void RemoveChildNode(Node node)
  198. {
  199. // make sure the node is a child of this node
  200. if (node._parent != this)
  201. {
  202. throw new System.Exception("Can't remove a node that don't belong to this parent.");
  203. }
  204. // remove node from children list
  205. _childNodes.Remove(node);
  206. // clear node parent
  207. node.SetParent(null);
  208. OnChildNodesListChange(node, false);
  209. }
  210. /// <summary>
  211. /// Find and return first child node by identifier.
  212. /// </summary>
  213. /// <param name="identifier">Node identifier to search for.</param>
  214. /// <param name="searchInChildren">If true, will also search recurisvely in children.</param>
  215. /// <returns>Node with given identifier or null if not found.</returns>
  216. public Node FindChildNode(string identifier, bool searchInChildren = true)
  217. {
  218. foreach (Node node in _childNodes)
  219. {
  220. // search in direct children
  221. if (node.Identifier == identifier)
  222. {
  223. return node;
  224. }
  225. // recursive search
  226. if (searchInChildren)
  227. {
  228. Node foundInChild = node.FindChildNode(identifier, searchInChildren);
  229. if (foundInChild != null)
  230. {
  231. return foundInChild;
  232. }
  233. }
  234. }
  235. // if got here it means we didn't find any child node with given identifier
  236. return null;
  237. }
  238. /// <summary>
  239. /// Remove this node from its parent.
  240. /// </summary>
  241. public void RemoveFromParent()
  242. {
  243. // don't have a parent?
  244. if (_parent == null)
  245. {
  246. throw new System.Exception("Can't remove an orphan node from parent.");
  247. }
  248. // remove from parent
  249. _parent.RemoveChildNode(this);
  250. }
  251. /// <summary>
  252. /// Called when the world matrix of this node is actually recalculated (invoked after the calculation).
  253. /// </summary>
  254. protected virtual void OnWorldMatrixChange()
  255. {
  256. // update transformations version
  257. _transformVersion++;
  258. // trigger update event
  259. OnTransformationsUpdate?.Invoke(this);
  260. // notify parent
  261. if (_parent != null)
  262. {
  263. _parent.OnChildWorldMatrixChange(this);
  264. }
  265. }
  266. /// <summary>
  267. /// Called when local transformations are set, eg when Position, Rotation, Scale etc. is changed.
  268. /// We use this to set this node as "dirty", eg that we need to update local transformations.
  269. /// </summary>
  270. protected virtual void OnTransformationsSet()
  271. {
  272. _isDirty = true;
  273. }
  274. /// <summary>
  275. /// Set the parent of this node.
  276. /// </summary>
  277. /// <param name="newParent">New parent node to set, or null for no parent.</param>
  278. protected virtual void SetParent(Node newParent)
  279. {
  280. // set parent
  281. _parent = newParent;
  282. // set our parents last transformations version to make sure we'll update world transformations next frame.
  283. _parentLastTransformVersion = newParent != null ? newParent._transformVersion - 1 : 1;
  284. }
  285. /// <summary>
  286. /// Calc final transformations for current frame.
  287. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  288. /// </summary>
  289. protected virtual void UpdateTransformations()
  290. {
  291. // if local transformations are dirty, we need to update them
  292. if (_isDirty)
  293. {
  294. _localTransform = _transformations.BuildMatrix();
  295. }
  296. // if local transformations are dirty, or parent transformations are out-of-date, update world transformations
  297. if (_isDirty ||
  298. (_parent != null && _parentLastTransformVersion != _parent._transformVersion) ||
  299. (_parent == null && _parentLastTransformVersion != 0))
  300. {
  301. // if we got parent, apply its transformations
  302. if (_parent != null)
  303. {
  304. _worldTransform = _localTransform * _parent._worldTransform;
  305. _parentLastTransformVersion = _parent._transformVersion;
  306. }
  307. // if not, world transformations are the same as local, and reset parent last transformations version
  308. else
  309. {
  310. _worldTransform = _localTransform;
  311. _parentLastTransformVersion = 0;
  312. }
  313. // called the function that mark world matrix change (increase transformation version etc)
  314. OnWorldMatrixChange();
  315. }
  316. // no longer dirty
  317. _isDirty = false;
  318. }
  319. /// <summary>
  320. /// Return local transformations matrix (note: will recalculate if needed).
  321. /// </summary>
  322. public Matrix LocalTransformations
  323. {
  324. get { UpdateTransformations(); return _localTransform; }
  325. }
  326. /// <summary>
  327. /// Return world transformations matrix (note: will recalculate if needed).
  328. /// </summary>
  329. public Matrix WorldTransformations
  330. {
  331. get { UpdateTransformations(); return _worldTransform; }
  332. }
  333. /// <summary>
  334. /// Get position in world space.
  335. /// </summary>
  336. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  337. public virtual Vector3 WorldPosition
  338. {
  339. get
  340. {
  341. //Vector3 pos; Vector3 scale; Quaternion rot;
  342. //WorldTransformations.Decompose(out scale, out rot, out pos);
  343. return WorldTransformations.Translation;
  344. }
  345. }
  346. /// <summary>
  347. /// Get Rotastion in world space.
  348. /// </summary>
  349. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  350. public virtual Quaternion WorldRotation
  351. {
  352. get
  353. {
  354. Vector3 pos; Vector3 scale; Quaternion rot;
  355. WorldTransformations.Decompose(out scale, out rot, out pos);
  356. return rot;
  357. }
  358. }
  359. /// <summary>
  360. /// Get Scale in world space.
  361. /// </summary>
  362. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  363. public virtual Vector3 WorldScale
  364. {
  365. get
  366. {
  367. Vector3 pos; Vector3 scale; Quaternion rot;
  368. WorldTransformations.Decompose(out scale, out rot, out pos);
  369. return scale;
  370. }
  371. }
  372. /// <summary>
  373. /// Force update transformations for this node and its children.
  374. /// </summary>
  375. /// <param name="recursive">If true, will also iterate and force-update children.</param>
  376. public void ForceUpdate(bool recursive = true)
  377. {
  378. // not visible? skip
  379. if (!Visible)
  380. {
  381. return;
  382. }
  383. // update transformations (only if needed, testing logic is inside)
  384. UpdateTransformations();
  385. // force-update all child nodes
  386. if (recursive)
  387. {
  388. foreach (Node node in _childNodes)
  389. {
  390. node.ForceUpdate(recursive);
  391. }
  392. }
  393. }
  394. /// <summary>
  395. /// Reset all local transformations.
  396. /// </summary>
  397. public void ResetTransformations()
  398. {
  399. _transformations = new Transformations();
  400. OnTransformationsSet();
  401. }
  402. /// <summary>
  403. /// Get / Set the order in which we apply local transformations in this node.
  404. /// </summary>
  405. public TransformOrder TransformationsOrder
  406. {
  407. get { return _transformations.TransformOrder; }
  408. set { _transformations.TransformOrder = value; OnTransformationsSet(); }
  409. }
  410. /// <summary>
  411. /// Get / Set the rotation type (euler / quaternion).
  412. /// </summary>
  413. public RotationType RotationType
  414. {
  415. get { return _transformations.RotationType; }
  416. set { _transformations.RotationType = value; OnTransformationsSet(); }
  417. }
  418. /// <summary>
  419. /// Get / Set the order in which we apply local rotation in this node.
  420. /// </summary>
  421. public RotationOrder RotationOrder
  422. {
  423. get { return _transformations.RotationOrder; }
  424. set { _transformations.RotationOrder = value; OnTransformationsSet(); }
  425. }
  426. /// <summary>
  427. /// Get / Set node local position.
  428. /// </summary>
  429. public Vector3 Position
  430. {
  431. get { return _transformations.Position; }
  432. set { if (_transformations.Position != value) OnTransformationsSet(); _transformations.Position = value; }
  433. }
  434. /// <summary>
  435. /// Get / Set node local scale.
  436. /// </summary>
  437. public Vector3 Scale
  438. {
  439. get { return _transformations.Scale; }
  440. set { if (_transformations.Scale != value) OnTransformationsSet(); _transformations.Scale = value; }
  441. }
  442. /// <summary>
  443. /// Get / Set node local rotation.
  444. /// </summary>
  445. public Vector3 Rotation
  446. {
  447. get { return _transformations.Rotation; }
  448. set { if (_transformations.Rotation != value) OnTransformationsSet(); _transformations.Rotation = value; }
  449. }
  450. /// <summary>
  451. /// Alias to access rotation X directly.
  452. /// </summary>
  453. public float RotationX
  454. {
  455. get { return _transformations.Rotation.X; }
  456. set { if (_transformations.Rotation.X != value) OnTransformationsSet(); _transformations.Rotation.X = value; }
  457. }
  458. /// <summary>
  459. /// Alias to access rotation Y directly.
  460. /// </summary>
  461. public float RotationY
  462. {
  463. get { return _transformations.Rotation.Y; }
  464. set { if (_transformations.Rotation.Y != value) OnTransformationsSet(); _transformations.Rotation.Y = value; }
  465. }
  466. /// <summary>
  467. /// Alias to access rotation Z directly.
  468. /// </summary>
  469. public float RotationZ
  470. {
  471. get { return _transformations.Rotation.Z; }
  472. set { if (_transformations.Rotation.Z != value) OnTransformationsSet(); _transformations.Rotation.Z = value; }
  473. }
  474. /// <summary>
  475. /// Alias to access scale X directly.
  476. /// </summary>
  477. public float ScaleX
  478. {
  479. get { return _transformations.Scale.X; }
  480. set { if (_transformations.Scale.X != value) OnTransformationsSet(); _transformations.Scale.X = value; }
  481. }
  482. /// <summary>
  483. /// Alias to access scale Y directly.
  484. /// </summary>
  485. public float ScaleY
  486. {
  487. get { return _transformations.Scale.Y; }
  488. set { if (_transformations.Scale.Y != value) OnTransformationsSet(); _transformations.Scale.Y = value; }
  489. }
  490. /// <summary>
  491. /// Alias to access scale Z directly.
  492. /// </summary>
  493. public float ScaleZ
  494. {
  495. get { return _transformations.Scale.Z; }
  496. set { if (_transformations.Scale.Z != value) OnTransformationsSet(); _transformations.Scale.Z = value; }
  497. }
  498. /// <summary>
  499. /// Alias to access position X directly.
  500. /// </summary>
  501. public float PositionX
  502. {
  503. get { return _transformations.Position.X; }
  504. set { if (_transformations.Position.X != value) OnTransformationsSet(); _transformations.Position.X = value; }
  505. }
  506. /// <summary>
  507. /// Alias to access position Y directly.
  508. /// </summary>
  509. public float PositionY
  510. {
  511. get { return _transformations.Position.Y; }
  512. set { if (_transformations.Position.Y != value) OnTransformationsSet(); _transformations.Position.Y = value; }
  513. }
  514. /// <summary>
  515. /// Alias to access position Z directly.
  516. /// </summary>
  517. public float PositionZ
  518. {
  519. get { return _transformations.Position.Z; }
  520. set { if (_transformations.Position.Z != value) OnTransformationsSet(); _transformations.Position.Z = value; }
  521. }
  522. /// <summary>
  523. /// Move position by vector.
  524. /// </summary>
  525. /// <param name="moveBy">Vector to translate by.</param>
  526. public void Translate(Vector3 moveBy)
  527. {
  528. _transformations.Position += moveBy;
  529. OnTransformationsSet();
  530. }
  531. /// <summary>
  532. /// Called every time one of the child nodes recalculate world transformations.
  533. /// </summary>
  534. /// <param name="node">The child node that updated.</param>
  535. public virtual void OnChildWorldMatrixChange(Node node)
  536. {
  537. }
  538. /// <summary>
  539. /// Return true if this node is empty.
  540. /// </summary>
  541. public bool Empty
  542. {
  543. get { return _childEntities.Count == 0 && _childNodes.Count == 0; }
  544. }
  545. /// <summary>
  546. /// Get if this node have any entities in it.
  547. /// </summary>
  548. public bool HaveEntities
  549. {
  550. get { return _childEntities.Count != 0; }
  551. }
  552. /// <summary>
  553. /// Get bounding box of this node and all its child nodes.
  554. /// </summary>
  555. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  556. /// <returns>Bounding box of the node and its children.</returns>
  557. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  558. {
  559. // if empty skip
  560. if (Empty)
  561. {
  562. return EmptyBoundingBox;
  563. }
  564. // make sure transformations are up-to-date
  565. UpdateTransformations();
  566. // list of points to build bounding box from
  567. List<Vector3> corners = new List<Vector3>();
  568. // apply all child nodes bounding boxes
  569. if (includeChildNodes)
  570. {
  571. foreach (Node child in _childNodes)
  572. {
  573. // skip invisible nodes
  574. if (!child.Visible)
  575. {
  576. continue;
  577. }
  578. // get bounding box
  579. BoundingBox currBox = child.GetBoundingBox();
  580. if (currBox.Min != currBox.Max)
  581. {
  582. corners.Add(currBox.Min);
  583. corners.Add(currBox.Max);
  584. }
  585. }
  586. }
  587. // apply all entities directly under this node
  588. foreach (IEntity entity in _childEntities)
  589. {
  590. // skip invisible entities
  591. if (!entity.Visible)
  592. {
  593. continue;
  594. }
  595. // get entity bounding box
  596. BoundingBox currBox = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  597. if (currBox.Min != currBox.Max)
  598. {
  599. corners.Add(currBox.Min);
  600. corners.Add(currBox.Max);
  601. }
  602. }
  603. // nothing in this node?
  604. if (corners.Count == 0)
  605. {
  606. return EmptyBoundingBox;
  607. }
  608. // return final bounding box
  609. return BoundingBox.CreateFromPoints(corners);
  610. }
  611. }
  612. }