Node.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 node with transformations, you can attach renderable entities to it, or append
  17. /// child nodes to inherit transformations.
  18. /// </summary>
  19. public class Node
  20. {
  21. /// <summary>
  22. /// Parent node.
  23. /// </summary>
  24. protected Node _parent = null;
  25. /// <summary>
  26. /// Node's transformations.
  27. /// </summary>
  28. protected Transformations _transformations = new Transformations();
  29. /// <summary>
  30. /// Is this node currently visible?
  31. /// </summary>
  32. public virtual bool Visible { get; set; }
  33. /// <summary>
  34. /// Optional identifier we can give to nodes.
  35. /// </summary>
  36. public string Identifier;
  37. /// <summary>
  38. /// Optional user data we can attach to nodes.
  39. /// </summary>
  40. public object UserData;
  41. /// <summary>
  42. /// The order in which we apply transformations when building the matrix for this node.
  43. /// </summary>
  44. protected TransformOrder _transformationsOrder = TransformOrder.ScaleRotationPosition;
  45. /// <summary>
  46. /// The order in which we apply rotation when building the matrix for this node.
  47. /// </summary>
  48. protected RotationOrder _rotationOrder = RotationOrder.RotateYXZ;
  49. /// <summary>
  50. /// Local transformations matrix, eg the result of the current local transformations.
  51. /// </summary>
  52. protected Matrix _localTransform = Matrix.Identity;
  53. /// <summary>
  54. /// World transformations matrix, eg the result of the local transformations multiplied with parent transformations.
  55. /// </summary>
  56. protected Matrix _worldTransform = Matrix.Identity;
  57. /// <summary>
  58. /// Child nodes under this node.
  59. /// </summary>
  60. protected List<Node> _childNodes = new List<Node>();
  61. /// <summary>
  62. /// Child entities under this node.
  63. /// </summary>
  64. protected List<IEntity> _childEntities = new List<IEntity>();
  65. /// <summary>
  66. /// Turns true when the transformations of this node changes.
  67. /// </summary>
  68. protected bool _isDirty = true;
  69. /// <summary>
  70. /// This number increment every time we update transformations.
  71. /// We use it to check if our parent's transformations had been changed since last
  72. /// time this node was rendered, and if so, we re-apply parent updated transformations.
  73. /// </summary>
  74. protected uint _transformVersion = 0;
  75. /// <summary>
  76. /// The last transformations version we got from our parent.
  77. /// </summary>
  78. protected uint _parentLastTransformVersion = 0;
  79. /// <summary>
  80. /// Get parent node.
  81. /// </summary>
  82. public Node Parent { get { return _parent; } }
  83. /// <summary>
  84. /// Transformation version is a special identifier that changes whenever the world transformations
  85. /// of this node changes. Its not necessarily a sequence, but if you check this number for changes every
  86. /// frame its a good indication of transformation change.
  87. /// </summary>
  88. public uint TransformVersion { get { return _transformVersion; } }
  89. /// <summary>
  90. /// Create the new node.
  91. /// </summary>
  92. public Node()
  93. {
  94. Visible = true;
  95. }
  96. /// <summary>
  97. /// Draw the node and its children.
  98. /// </summary>
  99. public virtual void Draw()
  100. {
  101. // not visible? skip
  102. if (!Visible)
  103. {
  104. return;
  105. }
  106. // update transformations (only if needed, testing logic is inside)
  107. UpdateTransformations();
  108. // draw all child nodes
  109. foreach (Node node in _childNodes)
  110. {
  111. node.Draw();
  112. }
  113. // draw all child entities
  114. foreach (IEntity entity in _childEntities)
  115. {
  116. entity.Draw(this, _localTransform, _worldTransform);
  117. }
  118. }
  119. /// <summary>
  120. /// Add an entity to this node.
  121. /// </summary>
  122. /// <param name="entity">Entity to add.</param>
  123. public void AddEntity(IEntity entity)
  124. {
  125. _childEntities.Add(entity);
  126. }
  127. /// <summary>
  128. /// Remove an entity from this node.
  129. /// </summary>
  130. /// <param name="entity">Entity to add.</param>
  131. public void RemoveEntity(IEntity entity)
  132. {
  133. _childEntities.Remove(entity);
  134. }
  135. /// <summary>
  136. /// Add a child node to this node.
  137. /// </summary>
  138. /// <param name="node">Node to add.</param>
  139. public void AddChildNode(Node node)
  140. {
  141. // node already got a parent?
  142. if (node._parent != null)
  143. {
  144. throw new System.Exception("Can't add a node that already have a parent.");
  145. }
  146. // add node to children list
  147. _childNodes.Add(node);
  148. // set self as node's parent
  149. node.SetParent(this);
  150. }
  151. /// <summary>
  152. /// Remove a child node from this node.
  153. /// </summary>
  154. /// <param name="node">Node to add.</param>
  155. public void RemoveChildNode(Node node)
  156. {
  157. // make sure the node is a child of this node
  158. if (node._parent != this)
  159. {
  160. throw new System.Exception("Can't remove a node that don't belong to this parent.");
  161. }
  162. // remove node from children list
  163. _childNodes.Remove(node);
  164. // clear node parent
  165. node.SetParent(null);
  166. }
  167. /// <summary>
  168. /// Find and return first child node by identifier.
  169. /// </summary>
  170. /// <param name="identifier">Node identifier to search for.</param>
  171. /// <param name="searchInChildren">If true, will also search recurisvely in children.</param>
  172. /// <returns>Node with given identifier or null if not found.</returns>
  173. public Node FindChildNode(string identifier, bool searchInChildren = true)
  174. {
  175. foreach (Node node in _childNodes)
  176. {
  177. // search in direct children
  178. if (node.Identifier == identifier)
  179. {
  180. return node;
  181. }
  182. // recursive search
  183. if (searchInChildren)
  184. {
  185. Node foundInChild = node.FindChildNode(identifier, searchInChildren);
  186. if (foundInChild != null)
  187. {
  188. return foundInChild;
  189. }
  190. }
  191. }
  192. // if got here it means we didn't find any child node with given identifier
  193. return null;
  194. }
  195. /// <summary>
  196. /// Remove this node from its parent.
  197. /// </summary>
  198. public void RemoveFromParent()
  199. {
  200. // don't have a parent?
  201. if (_parent == null)
  202. {
  203. throw new System.Exception("Can't remove an orphan node from parent.");
  204. }
  205. // remove from parent
  206. _parent.RemoveChildNode(this);
  207. }
  208. /// <summary>
  209. /// Called when the world matrix of this node is actually recalculated (invoked after the calculation).
  210. /// </summary>
  211. protected virtual void OnWorldMatrixChange()
  212. {
  213. // update transformations version
  214. _transformVersion++;
  215. // notify parent
  216. if (_parent != null)
  217. {
  218. _parent.OnChildWorldMatrixChange(this);
  219. }
  220. }
  221. /// <summary>
  222. /// Called when local transformations are set, eg when Position, Rotation, Scale etc. is changed.
  223. /// We use this to set this node as "dirty", eg that we need to update local transformations.
  224. /// </summary>
  225. protected virtual void OnTransformationsSet()
  226. {
  227. _isDirty = true;
  228. }
  229. /// <summary>
  230. /// Set the parent of this node.
  231. /// </summary>
  232. /// <param name="newParent">New parent node to set, or null for no parent.</param>
  233. protected virtual void SetParent(Node newParent)
  234. {
  235. // set parent
  236. _parent = newParent;
  237. // set our parents last transformations version to make sure we'll update world transformations next frame.
  238. _parentLastTransformVersion = newParent != null ? newParent._transformVersion - 1 : 1;
  239. }
  240. /// <summary>
  241. /// Calc final transformations for current frame.
  242. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  243. /// </summary>
  244. protected virtual void UpdateTransformations()
  245. {
  246. // if local transformations are dirty, we need to update them
  247. if (_isDirty)
  248. {
  249. _localTransform = _transformations.BuildMatrix(_transformationsOrder, _rotationOrder);
  250. }
  251. // if local transformations are dirty, or parent transformations are out-of-date, update world transformations
  252. if (_isDirty ||
  253. (_parent != null && _parentLastTransformVersion != _parent._transformVersion) ||
  254. (_parent == null && _parentLastTransformVersion != 0))
  255. {
  256. // if we got parent, apply its transformations
  257. if (_parent != null)
  258. {
  259. _worldTransform = _localTransform * _parent._worldTransform;
  260. _parentLastTransformVersion = _parent._transformVersion;
  261. }
  262. // if not, world transformations are the same as local, and reset parent last transformations version
  263. else
  264. {
  265. _worldTransform = _localTransform;
  266. _parentLastTransformVersion = 0;
  267. }
  268. // called the function that mark world matrix change (increase transformation version etc)
  269. OnWorldMatrixChange();
  270. }
  271. // no longer dirty
  272. _isDirty = false;
  273. }
  274. /// <summary>
  275. /// Return local transformations matrix (note: will recalculate if needed).
  276. /// </summary>
  277. public Matrix LocalTransformations
  278. {
  279. get { UpdateTransformations(); return _localTransform; }
  280. }
  281. /// <summary>
  282. /// Return world transformations matrix (note: will recalculate if needed).
  283. /// </summary>
  284. public Matrix WorldTransformations
  285. {
  286. get { UpdateTransformations(); return _worldTransform; }
  287. }
  288. /// <summary>
  289. /// Reset all local transformations.
  290. /// </summary>
  291. public void ResetTransformations()
  292. {
  293. _transformations = new Transformations();
  294. OnTransformationsSet();
  295. }
  296. /// <summary>
  297. /// Get / Set the order in which we apply local transformations in this node.
  298. /// </summary>
  299. public TransformOrder TransformationsOrder
  300. {
  301. get { return _transformationsOrder; }
  302. set { _transformationsOrder = value; OnTransformationsSet(); }
  303. }
  304. /// <summary>
  305. /// Get / Set the order in which we apply local rotation in this node.
  306. /// </summary>
  307. public RotationOrder RotationOrder
  308. {
  309. get { return _rotationOrder; }
  310. set { _rotationOrder = value; OnTransformationsSet(); }
  311. }
  312. /// <summary>
  313. /// Get / Set node local position.
  314. /// </summary>
  315. public Vector3 Position
  316. {
  317. get { return _transformations.Position; }
  318. set { _transformations.Position = value; OnTransformationsSet(); }
  319. }
  320. /// <summary>
  321. /// Get / Set node local scale.
  322. /// </summary>
  323. public Vector3 Scale
  324. {
  325. get { return _transformations.Scale; }
  326. set { _transformations.Scale = value; OnTransformationsSet(); }
  327. }
  328. /// <summary>
  329. /// Get / Set node local rotation.
  330. /// </summary>
  331. public Vector3 Rotation
  332. {
  333. get { return _transformations.Rotation; }
  334. set { _transformations.Rotation = value; OnTransformationsSet(); }
  335. }
  336. /// <summary>
  337. /// Alias to access rotation X directly.
  338. /// </summary>
  339. public float RotationX
  340. {
  341. get { return _transformations.Rotation.X; }
  342. set { _transformations.Rotation.X = value; OnTransformationsSet(); }
  343. }
  344. /// <summary>
  345. /// Alias to access rotation Y directly.
  346. /// </summary>
  347. public float RotationY
  348. {
  349. get { return _transformations.Rotation.Y; }
  350. set { _transformations.Rotation.Y = value; OnTransformationsSet(); }
  351. }
  352. /// <summary>
  353. /// Alias to access rotation Z directly.
  354. /// </summary>
  355. public float RotationZ
  356. {
  357. get { return _transformations.Rotation.Z; }
  358. set { _transformations.Rotation.Z = value; OnTransformationsSet(); }
  359. }
  360. /// <summary>
  361. /// Alias to access scale X directly.
  362. /// </summary>
  363. public float ScaleX
  364. {
  365. get { return _transformations.Scale.X; }
  366. set { _transformations.Scale.X = value; OnTransformationsSet(); }
  367. }
  368. /// <summary>
  369. /// Alias to access scale Y directly.
  370. /// </summary>
  371. public float ScaleY
  372. {
  373. get { return _transformations.Scale.Y; }
  374. set { _transformations.Scale.Y = value; OnTransformationsSet(); }
  375. }
  376. /// <summary>
  377. /// Alias to access scale Z directly.
  378. /// </summary>
  379. public float ScaleZ
  380. {
  381. get { return _transformations.Scale.Z; }
  382. set { _transformations.Scale.Z = value; OnTransformationsSet(); }
  383. }
  384. /// <summary>
  385. /// Alias to access position X directly.
  386. /// </summary>
  387. public float PositionX
  388. {
  389. get { return _transformations.Position.X; }
  390. set { _transformations.Position.X = value; OnTransformationsSet(); }
  391. }
  392. /// <summary>
  393. /// Alias to access position Y directly.
  394. /// </summary>
  395. public float PositionY
  396. {
  397. get { return _transformations.Position.Y; }
  398. set { _transformations.Position.Y = value; OnTransformationsSet(); }
  399. }
  400. /// <summary>
  401. /// Alias to access position Z directly.
  402. /// </summary>
  403. public float PositionZ
  404. {
  405. get { return _transformations.Position.Z; }
  406. set { _transformations.Position.Z = value; OnTransformationsSet(); }
  407. }
  408. /// <summary>
  409. /// Move position by vector.
  410. /// </summary>
  411. /// <param name="moveBy">Vector to translate by.</param>
  412. public void Translate(Vector3 moveBy)
  413. {
  414. _transformations.Position += moveBy;
  415. OnTransformationsSet();
  416. }
  417. /// <summary>
  418. /// Called every time one of the child nodes recalculate world transformations.
  419. /// </summary>
  420. /// <param name="node">The child node that updated.</param>
  421. public virtual void OnChildWorldMatrixChange(Node node)
  422. {
  423. }
  424. /// <summary>
  425. /// Get bounding box of this node and all its child nodes.
  426. /// </summary>
  427. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  428. /// <returns>Bounding box of the node and its children.</returns>
  429. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  430. {
  431. // make sure transformations are up-to-date
  432. UpdateTransformations();
  433. // list of points to build bounding box from
  434. List<Vector3> corners = new List<Vector3>();
  435. // apply all child nodes bounding boxes
  436. if (includeChildNodes)
  437. {
  438. foreach (Node child in _childNodes)
  439. {
  440. // skip invisible nodes
  441. if (!child.Visible)
  442. {
  443. continue;
  444. }
  445. // get bounding box
  446. BoundingBox currBox = child.GetBoundingBox();
  447. if (currBox.Min != currBox.Max)
  448. {
  449. corners.Add(currBox.Min);
  450. corners.Add(currBox.Max);
  451. }
  452. }
  453. }
  454. // apply all entities directly under this node
  455. foreach (IEntity entity in _childEntities)
  456. {
  457. // skip invisible entities
  458. if (!entity.Visible)
  459. {
  460. continue;
  461. }
  462. // get entity bounding box
  463. BoundingBox currBox = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  464. if (currBox.Min != currBox.Max)
  465. {
  466. corners.Add(currBox.Min);
  467. corners.Add(currBox.Max);
  468. }
  469. }
  470. // nothing in this node?
  471. if (corners.Count == 0)
  472. {
  473. return new BoundingBox();
  474. }
  475. // return final bounding box
  476. return BoundingBox.CreateFromPoints(corners);
  477. }
  478. }
  479. }