Node.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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 bool IsVisible = true;
  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. /// Draw the node and its children.
  91. /// </summary>
  92. public virtual void Draw()
  93. {
  94. // not visible? skip
  95. if (!IsVisible)
  96. {
  97. return;
  98. }
  99. // update transformations (only if needed, testing logic is inside)
  100. UpdateTransformations();
  101. // draw all child nodes
  102. foreach (Node node in _childNodes)
  103. {
  104. node.Draw();
  105. }
  106. // draw all child entities
  107. foreach (IEntity entity in _childEntities)
  108. {
  109. entity.Draw(this, _localTransform, _worldTransform);
  110. }
  111. }
  112. /// <summary>
  113. /// Add an entity to this node.
  114. /// </summary>
  115. /// <param name="entity">Entity to add.</param>
  116. public void AddEntity(IEntity entity)
  117. {
  118. _childEntities.Add(entity);
  119. }
  120. /// <summary>
  121. /// Remove an entity from this node.
  122. /// </summary>
  123. /// <param name="entity">Entity to add.</param>
  124. public void RemoveEntity(IEntity entity)
  125. {
  126. _childEntities.Remove(entity);
  127. }
  128. /// <summary>
  129. /// Add a child node to this node.
  130. /// </summary>
  131. /// <param name="node">Node to add.</param>
  132. public void AddChildNode(Node node)
  133. {
  134. // node already got a parent?
  135. if (node._parent != null)
  136. {
  137. throw new System.Exception("Can't add a node that already have a parent.");
  138. }
  139. // add node to children list
  140. _childNodes.Add(node);
  141. // set self as node's parent
  142. node.SetParent(this);
  143. }
  144. /// <summary>
  145. /// Remove a child node from this node.
  146. /// </summary>
  147. /// <param name="node">Node to add.</param>
  148. public void RemoveChildNode(Node node)
  149. {
  150. // make sure the node is a child of this node
  151. if (node._parent != this)
  152. {
  153. throw new System.Exception("Can't remove a node that don't belong to this parent.");
  154. }
  155. // remove node from children list
  156. _childNodes.Remove(node);
  157. // clear node parent
  158. node.SetParent(null);
  159. }
  160. /// <summary>
  161. /// Find and return first child node by identifier.
  162. /// </summary>
  163. /// <param name="identifier">Node identifier to search for.</param>
  164. /// <param name="searchInChildren">If true, will also search recurisvely in children.</param>
  165. /// <returns>Node with given identifier or null if not found.</returns>
  166. public Node FindChildNode(string identifier, bool searchInChildren = true)
  167. {
  168. foreach (Node node in _childNodes)
  169. {
  170. // search in direct children
  171. if (node.Identifier == identifier)
  172. {
  173. return node;
  174. }
  175. // recursive search
  176. if (searchInChildren)
  177. {
  178. Node foundInChild = node.FindChildNode(identifier, searchInChildren);
  179. if (foundInChild != null)
  180. {
  181. return foundInChild;
  182. }
  183. }
  184. }
  185. // if got here it means we didn't find any child node with given identifier
  186. return null;
  187. }
  188. /// <summary>
  189. /// Remove this node from its parent.
  190. /// </summary>
  191. public void RemoveFromParent()
  192. {
  193. // don't have a parent?
  194. if (_parent == null)
  195. {
  196. throw new System.Exception("Can't remove an orphan node from parent.");
  197. }
  198. // remove from parent
  199. _parent.RemoveChildNode(this);
  200. }
  201. /// <summary>
  202. /// Called when the world matrix of this node is actually recalculated (invoked after the calculation).
  203. /// </summary>
  204. protected virtual void OnWorldMatrixChange()
  205. {
  206. _transformVersion++;
  207. }
  208. /// <summary>
  209. /// Called when local transformations are set, eg when Position, Rotation, Scale etc. is changed.
  210. /// We use this to set this node as "dirty", eg that we need to update local transformations.
  211. /// </summary>
  212. protected virtual void OnTransformationsSet()
  213. {
  214. _isDirty = true;
  215. }
  216. /// <summary>
  217. /// Set the parent of this node.
  218. /// </summary>
  219. /// <param name="newParent">New parent node to set, or null for no parent.</param>
  220. protected virtual void SetParent(Node newParent)
  221. {
  222. // set parent
  223. _parent = newParent;
  224. // set our parents last transformations version to make sure we'll update world transformations next frame.
  225. _parentLastTransformVersion = newParent != null ? newParent._transformVersion - 1 : 1;
  226. }
  227. /// <summary>
  228. /// Calc final transformations for current frame.
  229. /// This uses an indicator to know if an update is needed, so no harm is done if you call it multiple times.
  230. /// </summary>
  231. protected virtual void UpdateTransformations()
  232. {
  233. // if local transformations are dirty, we need to update them
  234. if (_isDirty)
  235. {
  236. _localTransform = _transformations.BuildMatrix(_transformationsOrder, _rotationOrder);
  237. }
  238. // if local transformations are dirty, or parent transformations are out-of-date, update world transformations
  239. if (_isDirty ||
  240. (_parent != null && _parentLastTransformVersion != _parent._transformVersion) ||
  241. (_parent == null && _parentLastTransformVersion != 0))
  242. {
  243. // if we got parent, apply its transformations
  244. if (_parent != null)
  245. {
  246. _worldTransform = _localTransform * _parent._worldTransform;
  247. _parentLastTransformVersion = _parent._transformVersion;
  248. }
  249. // if not, world transformations are the same as local, and reset parent last transformations version
  250. else
  251. {
  252. _worldTransform = _localTransform;
  253. _parentLastTransformVersion = 0;
  254. }
  255. // called the function that mark world matrix change (increase transformation version etc)
  256. OnWorldMatrixChange();
  257. }
  258. // no longer dirty
  259. _isDirty = false;
  260. }
  261. /// <summary>
  262. /// Return local transformations matrix (note: will recalculate if needed).
  263. /// </summary>
  264. public Matrix LocalTransformations
  265. {
  266. get { UpdateTransformations(); return _localTransform; }
  267. }
  268. /// <summary>
  269. /// Return world transformations matrix (note: will recalculate if needed).
  270. /// </summary>
  271. public Matrix WorldTransformations
  272. {
  273. get { UpdateTransformations(); return _worldTransform; }
  274. }
  275. /// <summary>
  276. /// Reset all local transformations.
  277. /// </summary>
  278. public void ResetTransformations()
  279. {
  280. _transformations = new Transformations();
  281. OnTransformationsSet();
  282. }
  283. /// <summary>
  284. /// Get / Set the order in which we apply local transformations in this node.
  285. /// </summary>
  286. public TransformOrder TransformationsOrder
  287. {
  288. get { return _transformationsOrder; }
  289. set { _transformationsOrder = value; OnTransformationsSet(); }
  290. }
  291. /// <summary>
  292. /// Get / Set the order in which we apply local rotation in this node.
  293. /// </summary>
  294. public RotationOrder RotationOrder
  295. {
  296. get { return _rotationOrder; }
  297. set { _rotationOrder = value; OnTransformationsSet(); }
  298. }
  299. /// <summary>
  300. /// Get / Set node local position.
  301. /// </summary>
  302. public Vector3 Position
  303. {
  304. get { return _transformations.Position; }
  305. set { _transformations.Position = value; OnTransformationsSet(); }
  306. }
  307. /// <summary>
  308. /// Get / Set node local scale.
  309. /// </summary>
  310. public Vector3 Scale
  311. {
  312. get { return _transformations.Scale; }
  313. set { _transformations.Scale = value; OnTransformationsSet(); }
  314. }
  315. /// <summary>
  316. /// Get / Set node local rotation.
  317. /// </summary>
  318. public Vector3 Rotation
  319. {
  320. get { return _transformations.Rotation; }
  321. set { _transformations.Rotation = value; OnTransformationsSet(); }
  322. }
  323. /// <summary>
  324. /// Alias to access rotation X directly.
  325. /// </summary>
  326. public float RotationX
  327. {
  328. get { return _transformations.Rotation.X; }
  329. set { _transformations.Rotation.X = value; OnTransformationsSet(); }
  330. }
  331. /// <summary>
  332. /// Alias to access rotation Y directly.
  333. /// </summary>
  334. public float RotationY
  335. {
  336. get { return _transformations.Rotation.Y; }
  337. set { _transformations.Rotation.Y = value; OnTransformationsSet(); }
  338. }
  339. /// <summary>
  340. /// Alias to access rotation Z directly.
  341. /// </summary>
  342. public float RotationZ
  343. {
  344. get { return _transformations.Rotation.Z; }
  345. set { _transformations.Rotation.Z = value; OnTransformationsSet(); }
  346. }
  347. /// <summary>
  348. /// Alias to access scale X directly.
  349. /// </summary>
  350. public float ScaleX
  351. {
  352. get { return _transformations.Scale.X; }
  353. set { _transformations.Scale.X = value; OnTransformationsSet(); }
  354. }
  355. /// <summary>
  356. /// Alias to access scale Y directly.
  357. /// </summary>
  358. public float ScaleY
  359. {
  360. get { return _transformations.Scale.Y; }
  361. set { _transformations.Scale.Y = value; OnTransformationsSet(); }
  362. }
  363. /// <summary>
  364. /// Alias to access scale Z directly.
  365. /// </summary>
  366. public float ScaleZ
  367. {
  368. get { return _transformations.Scale.Z; }
  369. set { _transformations.Scale.Z = value; OnTransformationsSet(); }
  370. }
  371. /// <summary>
  372. /// Alias to access position X directly.
  373. /// </summary>
  374. public float PositionX
  375. {
  376. get { return _transformations.Position.X; }
  377. set { _transformations.Position.X = value; OnTransformationsSet(); }
  378. }
  379. /// <summary>
  380. /// Alias to access position Y directly.
  381. /// </summary>
  382. public float PositionY
  383. {
  384. get { return _transformations.Position.Y; }
  385. set { _transformations.Position.Y = value; OnTransformationsSet(); }
  386. }
  387. /// <summary>
  388. /// Alias to access position Z directly.
  389. /// </summary>
  390. public float PositionZ
  391. {
  392. get { return _transformations.Position.Z; }
  393. set { _transformations.Position.Z = value; OnTransformationsSet(); }
  394. }
  395. /// <summary>
  396. /// Move position by vector.
  397. /// </summary>
  398. /// <param name="moveBy">Vector to translate by.</param>
  399. public void Translate(Vector3 moveBy)
  400. {
  401. _transformations.Position += moveBy;
  402. OnTransformationsSet();
  403. }
  404. /// <summary>
  405. /// Get bounding box of this node and all its child nodes.
  406. /// </summary>
  407. /// <param name="includeChildNodes">If true, will include bounding box of child nodes. If false, only of entities directly attached to this node.</param>
  408. /// <returns>Bounding box of the node and its children.</returns>
  409. public virtual BoundingBox GetBoundingBox(bool includeChildNodes = true)
  410. {
  411. // initialize minimum and maximum corners of the bounding box to max and min values
  412. Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
  413. Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);
  414. // apply all child nodes bounding boxes
  415. if (includeChildNodes)
  416. {
  417. foreach (Node child in _childNodes)
  418. {
  419. BoundingBox curr = child.GetBoundingBox();
  420. min = Vector3.Min(min, curr.Min);
  421. max = Vector3.Max(max, curr.Max);
  422. }
  423. }
  424. // apply all entities directly under this node
  425. foreach (IEntity entity in _childEntities)
  426. {
  427. BoundingBox curr = entity.GetBoundingBox(this, _localTransform, _worldTransform);
  428. min = Vector3.Min(min, curr.Min);
  429. max = Vector3.Max(max, curr.Max);
  430. }
  431. // return final bounding box
  432. return new BoundingBox(min, max);
  433. }
  434. }
  435. }