Node.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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. /// Return true if we need to update world transform due to parent change.
  287. /// </summary>
  288. private bool NeedUpdateDueToParentChange()
  289. {
  290. // no parent? if parent last transform version is not 0, it means we had a parent but now we don't.
  291. // still require update.
  292. if (_parent == null)
  293. {
  294. return _parentLastTransformVersion != 0;
  295. }
  296. // check if parent is dirty, or if our last parent transform version mismatch parent current transform version
  297. return (_parent._isDirty || _parentLastTransformVersion != _parent._transformVersion);
  298. }
  299. /// <summary>
  300. /// Calc final transformations for current frame.
  301. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  302. /// </summary>
  303. protected virtual void UpdateTransformations()
  304. {
  305. // if local transformations are dirty, we need to update them
  306. if (_isDirty)
  307. {
  308. _localTransform = _transformations.BuildMatrix();
  309. }
  310. // if local transformations are dirty or parent transformations are out-of-date, update world transformations
  311. if (_isDirty || NeedUpdateDueToParentChange())
  312. {
  313. // if we got parent, apply its transformations
  314. if (_parent != null)
  315. {
  316. // if parent need update, update it first
  317. if (_parent._isDirty)
  318. {
  319. _parent.UpdateTransformations();
  320. }
  321. // recalc world transform
  322. _worldTransform = _localTransform * _parent._worldTransform;
  323. _parentLastTransformVersion = _parent._transformVersion;
  324. }
  325. // if not, world transformations are the same as local, and reset parent last transformations version
  326. else
  327. {
  328. _worldTransform = _localTransform;
  329. _parentLastTransformVersion = 0;
  330. }
  331. // called the function that mark world matrix change (increase transformation version etc)
  332. OnWorldMatrixChange();
  333. }
  334. // no longer dirty
  335. _isDirty = false;
  336. }
  337. /// <summary>
  338. /// Return local transformations matrix (note: will recalculate if needed).
  339. /// </summary>
  340. public Matrix LocalTransformations
  341. {
  342. get { UpdateTransformations(); return _localTransform; }
  343. }
  344. /// <summary>
  345. /// Return world transformations matrix (note: will recalculate if needed).
  346. /// </summary>
  347. public Matrix WorldTransformations
  348. {
  349. get { UpdateTransformations(); return _worldTransform; }
  350. }
  351. /// <summary>
  352. /// Get position in world space.
  353. /// </summary>
  354. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  355. public virtual Vector3 WorldPosition
  356. {
  357. get
  358. {
  359. //Vector3 pos; Vector3 scale; Quaternion rot;
  360. //WorldTransformations.Decompose(out scale, out rot, out pos);
  361. return WorldTransformations.Translation;
  362. }
  363. }
  364. /// <summary>
  365. /// Get Rotastion in world space.
  366. /// </summary>
  367. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  368. public virtual Quaternion WorldRotation
  369. {
  370. get
  371. {
  372. Vector3 pos; Vector3 scale; Quaternion rot;
  373. WorldTransformations.Decompose(out scale, out rot, out pos);
  374. return rot;
  375. }
  376. }
  377. /// <summary>
  378. /// Get Scale in world space.
  379. /// </summary>
  380. /// <remarks>Naive implementation using world matrix decompose. For better performance, override this with your own cached version.</remarks>
  381. public virtual Vector3 WorldScale
  382. {
  383. get
  384. {
  385. Vector3 pos; Vector3 scale; Quaternion rot;
  386. WorldTransformations.Decompose(out scale, out rot, out pos);
  387. return scale;
  388. }
  389. }
  390. /// <summary>
  391. /// Force update transformations for this node and its children.
  392. /// </summary>
  393. /// <param name="recursive">If true, will also iterate and force-update children.</param>
  394. public void ForceUpdate(bool recursive = true)
  395. {
  396. // not visible? skip
  397. if (!Visible)
  398. {
  399. return;
  400. }
  401. // update transformations (only if needed, testing logic is inside)
  402. UpdateTransformations();
  403. // force-update all child nodes
  404. if (recursive)
  405. {
  406. foreach (Node node in _childNodes)
  407. {
  408. node.ForceUpdate(recursive);
  409. }
  410. }
  411. }
  412. /// <summary>
  413. /// Reset all local transformations.
  414. /// </summary>
  415. public void ResetTransformations()
  416. {
  417. _transformations = new Transformations();
  418. OnTransformationsSet();
  419. }
  420. /// <summary>
  421. /// Get / Set the order in which we apply local transformations in this node.
  422. /// </summary>
  423. public TransformOrder TransformationsOrder
  424. {
  425. get { return _transformations.TransformOrder; }
  426. set { _transformations.TransformOrder = value; OnTransformationsSet(); }
  427. }
  428. /// <summary>
  429. /// Get / Set the rotation type (euler / quaternion).
  430. /// </summary>
  431. public RotationType RotationType
  432. {
  433. get { return _transformations.RotationType; }
  434. set { _transformations.RotationType = value; OnTransformationsSet(); }
  435. }
  436. /// <summary>
  437. /// Get / Set the order in which we apply local rotation in this node.
  438. /// </summary>
  439. public RotationOrder RotationOrder
  440. {
  441. get { return _transformations.RotationOrder; }
  442. set { _transformations.RotationOrder = value; OnTransformationsSet(); }
  443. }
  444. /// <summary>
  445. /// Get / Set node local position.
  446. /// </summary>
  447. public Vector3 Position
  448. {
  449. get { return _transformations.Position; }
  450. set { if (_transformations.Position != value) OnTransformationsSet(); _transformations.Position = value; }
  451. }
  452. /// <summary>
  453. /// Get / Set node local scale.
  454. /// </summary>
  455. public Vector3 Scale
  456. {
  457. get { return _transformations.Scale; }
  458. set { if (_transformations.Scale != value) OnTransformationsSet(); _transformations.Scale = value; }
  459. }
  460. /// <summary>
  461. /// Get / Set node local rotation.
  462. /// </summary>
  463. public Vector3 Rotation
  464. {
  465. get { return _transformations.Rotation; }
  466. set { if (_transformations.Rotation != value) OnTransformationsSet(); _transformations.Rotation = value; }
  467. }
  468. /// <summary>
  469. /// Alias to access rotation X directly.
  470. /// </summary>
  471. public float RotationX
  472. {
  473. get { return _transformations.Rotation.X; }
  474. set { if (_transformations.Rotation.X != value) OnTransformationsSet(); _transformations.Rotation.X = value; }
  475. }
  476. /// <summary>
  477. /// Alias to access rotation Y directly.
  478. /// </summary>
  479. public float RotationY
  480. {
  481. get { return _transformations.Rotation.Y; }
  482. set { if (_transformations.Rotation.Y != value) OnTransformationsSet(); _transformations.Rotation.Y = value; }
  483. }
  484. /// <summary>
  485. /// Alias to access rotation Z directly.
  486. /// </summary>
  487. public float RotationZ
  488. {
  489. get { return _transformations.Rotation.Z; }
  490. set { if (_transformations.Rotation.Z != value) OnTransformationsSet(); _transformations.Rotation.Z = value; }
  491. }
  492. /// <summary>
  493. /// Alias to access scale X directly.
  494. /// </summary>
  495. public float ScaleX
  496. {
  497. get { return _transformations.Scale.X; }
  498. set { if (_transformations.Scale.X != value) OnTransformationsSet(); _transformations.Scale.X = value; }
  499. }
  500. /// <summary>
  501. /// Alias to access scale Y directly.
  502. /// </summary>
  503. public float ScaleY
  504. {
  505. get { return _transformations.Scale.Y; }
  506. set { if (_transformations.Scale.Y != value) OnTransformationsSet(); _transformations.Scale.Y = value; }
  507. }
  508. /// <summary>
  509. /// Alias to access scale Z directly.
  510. /// </summary>
  511. public float ScaleZ
  512. {
  513. get { return _transformations.Scale.Z; }
  514. set { if (_transformations.Scale.Z != value) OnTransformationsSet(); _transformations.Scale.Z = value; }
  515. }
  516. /// <summary>
  517. /// Alias to access position X directly.
  518. /// </summary>
  519. public float PositionX
  520. {
  521. get { return _transformations.Position.X; }
  522. set { if (_transformations.Position.X != value) OnTransformationsSet(); _transformations.Position.X = value; }
  523. }
  524. /// <summary>
  525. /// Alias to access position Y directly.
  526. /// </summary>
  527. public float PositionY
  528. {
  529. get { return _transformations.Position.Y; }
  530. set { if (_transformations.Position.Y != value) OnTransformationsSet(); _transformations.Position.Y = value; }
  531. }
  532. /// <summary>
  533. /// Alias to access position Z directly.
  534. /// </summary>
  535. public float PositionZ
  536. {
  537. get { return _transformations.Position.Z; }
  538. set { if (_transformations.Position.Z != value) OnTransformationsSet(); _transformations.Position.Z = value; }
  539. }
  540. /// <summary>
  541. /// Move position by vector.
  542. /// </summary>
  543. /// <param name="moveBy">Vector to translate by.</param>
  544. public void Translate(Vector3 moveBy)
  545. {
  546. _transformations.Position += moveBy;
  547. OnTransformationsSet();
  548. }
  549. /// <summary>
  550. /// Called every time one of the child nodes recalculate world transformations.
  551. /// </summary>
  552. /// <param name="node">The child node that updated.</param>
  553. public virtual void OnChildWorldMatrixChange(Node node)
  554. {
  555. }
  556. /// <summary>
  557. /// Return true if this node is empty.
  558. /// </summary>
  559. public bool Empty
  560. {
  561. get { return _childEntities.Count == 0 && _childNodes.Count == 0; }
  562. }
  563. /// <summary>
  564. /// Get if this node have any entities in it.
  565. /// </summary>
  566. public bool HaveEntities
  567. {
  568. get { return _childEntities.Count != 0; }
  569. }
  570. /// <summary>
  571. /// Get bounding box of this node and all its child nodes.
  572. /// </summary>
  573. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  574. /// <returns>Bounding box of the node and its children.</returns>
  575. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  576. {
  577. // if empty skip
  578. if (Empty)
  579. {
  580. return EmptyBoundingBox;
  581. }
  582. // make sure transformations are up-to-date
  583. UpdateTransformations();
  584. // list of points to build bounding box from
  585. List<Vector3> corners = new List<Vector3>();
  586. // apply all child nodes bounding boxes
  587. if (includeChildNodes)
  588. {
  589. foreach (Node child in _childNodes)
  590. {
  591. // skip invisible nodes
  592. if (!child.Visible)
  593. {
  594. continue;
  595. }
  596. // get bounding box
  597. BoundingBox currBox = child.GetBoundingBox();
  598. if (currBox.Min != currBox.Max)
  599. {
  600. corners.Add(currBox.Min);
  601. corners.Add(currBox.Max);
  602. }
  603. }
  604. }
  605. // apply all entities directly under this node
  606. foreach (IEntity entity in _childEntities)
  607. {
  608. // skip invisible entities
  609. if (!entity.Visible)
  610. {
  611. continue;
  612. }
  613. // get entity bounding box
  614. BoundingBox currBox = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  615. if (currBox.Min != currBox.Max)
  616. {
  617. corners.Add(currBox.Min);
  618. corners.Add(currBox.Max);
  619. }
  620. }
  621. // nothing in this node?
  622. if (corners.Count == 0)
  623. {
  624. return EmptyBoundingBox;
  625. }
  626. // return final bounding box
  627. return BoundingBox.CreateFromPoints(corners);
  628. }
  629. }
  630. }