NodePort.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using UnityEngine;
  5. namespace XNode {
  6. [Serializable]
  7. public class NodePort {
  8. public enum IO { Input, Output }
  9. public int ConnectionCount { get { return connections.Count; } }
  10. /// <summary> Return the first non-null connection </summary>
  11. public NodePort Connection {
  12. get {
  13. for (int i = 0; i < connections.Count; i++) {
  14. if (connections[i] != null) return connections[i].Port;
  15. }
  16. return null;
  17. }
  18. }
  19. public IO direction { get { return _direction; } }
  20. public Node.ConnectionType connectionType { get { return _connectionType; } }
  21. public Node.TypeConstraint typeConstraint { get { return _typeConstraint; } }
  22. /// <summary> Is this port connected to anytihng? </summary>
  23. public bool IsConnected { get { return connections.Count != 0; } }
  24. public bool IsInput { get { return direction == IO.Input; } }
  25. public bool IsOutput { get { return direction == IO.Output; } }
  26. public string fieldName { get { return _fieldName; } }
  27. public Node node { get { return _node; } }
  28. public bool IsDynamic { get { return _dynamic; } }
  29. public bool IsStatic { get { return !_dynamic; } }
  30. public Type ValueType {
  31. get {
  32. if (valueType == null && !string.IsNullOrEmpty(_typeQualifiedName)) valueType = Type.GetType(_typeQualifiedName, false);
  33. return valueType;
  34. }
  35. set {
  36. valueType = value;
  37. if (value != null) _typeQualifiedName = value.AssemblyQualifiedName;
  38. }
  39. }
  40. private Type valueType;
  41. [SerializeField] private string _fieldName;
  42. [SerializeField] private Node _node;
  43. [SerializeField] private string _typeQualifiedName;
  44. [SerializeField] private List<PortConnection> connections = new List<PortConnection>();
  45. [SerializeField] private IO _direction;
  46. [SerializeField] private Node.ConnectionType _connectionType;
  47. [SerializeField] private Node.TypeConstraint _typeConstraint;
  48. [SerializeField] private bool _dynamic;
  49. /// <summary> Construct a static targetless nodeport. Used as a template. </summary>
  50. public NodePort(FieldInfo fieldInfo) {
  51. _fieldName = fieldInfo.Name;
  52. ValueType = fieldInfo.FieldType;
  53. _dynamic = false;
  54. var attribs = fieldInfo.GetCustomAttributes(false);
  55. for (int i = 0; i < attribs.Length; i++) {
  56. if (attribs[i] is Node.InputAttribute) {
  57. _direction = IO.Input;
  58. _connectionType = (attribs[i] as Node.InputAttribute).connectionType;
  59. _typeConstraint = (attribs[i] as Node.InputAttribute).typeConstraint;
  60. } else if (attribs[i] is Node.OutputAttribute) {
  61. _direction = IO.Output;
  62. _connectionType = (attribs[i] as Node.OutputAttribute).connectionType;
  63. _typeConstraint = (attribs[i] as Node.OutputAttribute).typeConstraint;
  64. }
  65. }
  66. }
  67. /// <summary> Copy a nodePort but assign it to another node. </summary>
  68. public NodePort(NodePort nodePort, Node node) {
  69. _fieldName = nodePort._fieldName;
  70. ValueType = nodePort.valueType;
  71. _direction = nodePort.direction;
  72. _dynamic = nodePort._dynamic;
  73. _connectionType = nodePort._connectionType;
  74. _typeConstraint = nodePort._typeConstraint;
  75. _node = node;
  76. }
  77. /// <summary> Construct a dynamic port. Dynamic ports are not forgotten on reimport, and is ideal for runtime-created ports. </summary>
  78. public NodePort(string fieldName, Type type, IO direction, Node.ConnectionType connectionType, Node.TypeConstraint typeConstraint, Node node) {
  79. _fieldName = fieldName;
  80. this.ValueType = type;
  81. _direction = direction;
  82. _node = node;
  83. _dynamic = true;
  84. _connectionType = connectionType;
  85. _typeConstraint = typeConstraint;
  86. }
  87. /// <summary> Checks all connections for invalid references, and removes them. </summary>
  88. public void VerifyConnections() {
  89. for (int i = connections.Count - 1; i >= 0; i--) {
  90. if (connections[i].node != null &&
  91. !string.IsNullOrEmpty(connections[i].fieldName) &&
  92. connections[i].node.GetPort(connections[i].fieldName) != null)
  93. continue;
  94. connections.RemoveAt(i);
  95. }
  96. }
  97. /// <summary> Return the output value of this node through its parent nodes GetValue override method. </summary>
  98. /// <returns> <see cref="Node.GetValue(NodePort)"/> </returns>
  99. public object GetOutputValue() {
  100. if (direction == IO.Input) return null;
  101. return node.GetValue(this);
  102. }
  103. /// <summary> Return the output value of the first connected port. Returns null if none found or invalid.</summary>
  104. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  105. public object GetInputValue() {
  106. NodePort connectedPort = Connection;
  107. if (connectedPort == null) return null;
  108. return connectedPort.GetOutputValue();
  109. }
  110. /// <summary> Return the output values of all connected ports. </summary>
  111. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  112. public object[] GetInputValues() {
  113. object[] objs = new object[ConnectionCount];
  114. for (int i = 0; i < ConnectionCount; i++) {
  115. NodePort connectedPort = connections[i].Port;
  116. if (connectedPort == null) { // if we happen to find a null port, remove it and look again
  117. connections.RemoveAt(i);
  118. i--;
  119. continue;
  120. }
  121. objs[i] = connectedPort.GetOutputValue();
  122. }
  123. return objs;
  124. }
  125. /// <summary> Return the output value of the first connected port. Returns null if none found or invalid. </summary>
  126. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  127. public T GetInputValue<T>() {
  128. object obj = GetInputValue();
  129. return obj is T ? (T) obj : default(T);
  130. }
  131. /// <summary> Return the output values of all connected ports. </summary>
  132. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  133. public T[] GetInputValues<T>() {
  134. object[] objs = GetInputValues();
  135. T[] ts = new T[objs.Length];
  136. for (int i = 0; i < objs.Length; i++) {
  137. if (objs[i] is T) ts[i] = (T) objs[i];
  138. }
  139. return ts;
  140. }
  141. /// <summary> Return true if port is connected and has a valid input. </summary>
  142. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  143. public bool TryGetInputValue<T>(out T value) {
  144. object obj = GetInputValue();
  145. if (obj is T) {
  146. value = (T) obj;
  147. return true;
  148. } else {
  149. value = default(T);
  150. return false;
  151. }
  152. }
  153. /// <summary> Return the sum of all inputs. </summary>
  154. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  155. public float GetInputSum(float fallback) {
  156. object[] objs = GetInputValues();
  157. if (objs.Length == 0) return fallback;
  158. float result = 0;
  159. for (int i = 0; i < objs.Length; i++) {
  160. if (objs[i] is float) result += (float) objs[i];
  161. }
  162. return result;
  163. }
  164. /// <summary> Return the sum of all inputs. </summary>
  165. /// <returns> <see cref="NodePort.GetOutputValue"/> </returns>
  166. public int GetInputSum(int fallback) {
  167. object[] objs = GetInputValues();
  168. if (objs.Length == 0) return fallback;
  169. int result = 0;
  170. for (int i = 0; i < objs.Length; i++) {
  171. if (objs[i] is int) result += (int) objs[i];
  172. }
  173. return result;
  174. }
  175. /// <summary> Connect this <see cref="NodePort"/> to another </summary>
  176. /// <param name="port">The <see cref="NodePort"/> to connect to</param>
  177. public void Connect(NodePort port) {
  178. if (connections == null) connections = new List<PortConnection>();
  179. if (port == null) { Debug.LogWarning("Cannot connect to null port"); return; }
  180. if (port == this) { Debug.LogWarning("Cannot connect port to self."); return; }
  181. if (IsConnectedTo(port)) { Debug.LogWarning("Port already connected. "); return; }
  182. if (direction == port.direction) { Debug.LogWarning("Cannot connect two " + (direction == IO.Input ? "input" : "output") + " connections"); return; }
  183. #if UNITY_EDITOR
  184. UnityEditor.Undo.RecordObject(node, "Connect Port");
  185. UnityEditor.Undo.RecordObject(port.node, "Connect Port");
  186. #endif
  187. if (port.connectionType == Node.ConnectionType.Override && port.ConnectionCount != 0) { port.ClearConnections(); }
  188. if (connectionType == Node.ConnectionType.Override && ConnectionCount != 0) { ClearConnections(); }
  189. connections.Add(new PortConnection(port));
  190. if (port.connections == null) port.connections = new List<PortConnection>();
  191. if (!port.IsConnectedTo(this)) port.connections.Add(new PortConnection(this));
  192. node.OnCreateConnection(this, port);
  193. port.node.OnCreateConnection(this, port);
  194. }
  195. public List<NodePort> GetConnections() {
  196. List<NodePort> result = new List<NodePort>();
  197. for (int i = 0; i < connections.Count; i++) {
  198. NodePort port = GetConnection(i);
  199. if (port != null) result.Add(port);
  200. }
  201. return result;
  202. }
  203. public NodePort GetConnection(int i) {
  204. //If the connection is broken for some reason, remove it.
  205. if (connections[i].node == null || string.IsNullOrEmpty(connections[i].fieldName)) {
  206. connections.RemoveAt(i);
  207. return null;
  208. }
  209. NodePort port = connections[i].node.GetPort(connections[i].fieldName);
  210. if (port == null) {
  211. connections.RemoveAt(i);
  212. return null;
  213. }
  214. return port;
  215. }
  216. /// <summary> Get index of the connection connecting this and specified ports </summary>
  217. public int GetConnectionIndex(NodePort port) {
  218. for (int i = 0; i < ConnectionCount; i++) {
  219. if (connections[i].Port == port) return i;
  220. }
  221. return -1;
  222. }
  223. public bool IsConnectedTo(NodePort port) {
  224. for (int i = 0; i < connections.Count; i++) {
  225. if (connections[i].Port == port) return true;
  226. }
  227. return false;
  228. }
  229. /// <summary> Returns true if this port can connect to specified port </summary>
  230. public bool CanConnectTo(NodePort port) {
  231. // Figure out which is input and which is output
  232. NodePort input = null, output = null;
  233. if (IsInput) input = this;
  234. else output = this;
  235. if (port.IsInput) input = port;
  236. else output = port;
  237. // If there isn't one of each, they can't connect
  238. if (input == null || output == null) return false;
  239. // Check input type constraints
  240. if (input.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
  241. if (input.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
  242. if (input.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
  243. // Check output type constraints
  244. if (output.typeConstraint == XNode.Node.TypeConstraint.Inherited && !input.ValueType.IsAssignableFrom(output.ValueType)) return false;
  245. if (output.typeConstraint == XNode.Node.TypeConstraint.Strict && input.ValueType != output.ValueType) return false;
  246. if (output.typeConstraint == XNode.Node.TypeConstraint.InheritedInverse && !output.ValueType.IsAssignableFrom(input.ValueType)) return false;
  247. // Success
  248. return true;
  249. }
  250. /// <summary> Disconnect this port from another port </summary>
  251. public void Disconnect(NodePort port) {
  252. // Remove this ports connection to the other
  253. for (int i = connections.Count - 1; i >= 0; i--) {
  254. if (connections[i].Port == port) {
  255. connections.RemoveAt(i);
  256. }
  257. }
  258. if (port != null) {
  259. // Remove the other ports connection to this port
  260. for (int i = 0; i < port.connections.Count; i++) {
  261. if (port.connections[i].Port == this) {
  262. port.connections.RemoveAt(i);
  263. }
  264. }
  265. }
  266. // Trigger OnRemoveConnection
  267. node.OnRemoveConnection(this);
  268. if (port != null) port.node.OnRemoveConnection(port);
  269. }
  270. /// <summary> Disconnect this port from another port </summary>
  271. public void Disconnect(int i) {
  272. // Remove the other ports connection to this port
  273. NodePort otherPort = connections[i].Port;
  274. if (otherPort != null) {
  275. for (int k = 0; k < otherPort.connections.Count; k++) {
  276. if (otherPort.connections[k].Port == this) {
  277. otherPort.connections.RemoveAt(i);
  278. }
  279. }
  280. }
  281. // Remove this ports connection to the other
  282. connections.RemoveAt(i);
  283. // Trigger OnRemoveConnection
  284. node.OnRemoveConnection(this);
  285. if (otherPort != null) otherPort.node.OnRemoveConnection(otherPort);
  286. }
  287. public void ClearConnections() {
  288. while (connections.Count > 0) {
  289. Disconnect(connections[0].Port);
  290. }
  291. }
  292. /// <summary> Get reroute points for a given connection. This is used for organization </summary>
  293. public List<Vector2> GetReroutePoints(int index) {
  294. return connections[index].reroutePoints;
  295. }
  296. /// <summary> Swap connections with another node </summary>
  297. public void SwapConnections(NodePort targetPort) {
  298. int aConnectionCount = connections.Count;
  299. int bConnectionCount = targetPort.connections.Count;
  300. List<NodePort> portConnections = new List<NodePort>();
  301. List<NodePort> targetPortConnections = new List<NodePort>();
  302. // Cache port connections
  303. for (int i = 0; i < aConnectionCount; i++)
  304. portConnections.Add(connections[i].Port);
  305. // Cache target port connections
  306. for (int i = 0; i < bConnectionCount; i++)
  307. targetPortConnections.Add(targetPort.connections[i].Port);
  308. ClearConnections();
  309. targetPort.ClearConnections();
  310. // Add port connections to targetPort
  311. for (int i = 0; i < portConnections.Count; i++)
  312. targetPort.Connect(portConnections[i]);
  313. // Add target port connections to this one
  314. for (int i = 0; i < targetPortConnections.Count; i++)
  315. Connect(targetPortConnections[i]);
  316. }
  317. /// <summary> Copy all connections pointing to a node and add them to this one </summary>
  318. public void AddConnections(NodePort targetPort) {
  319. int connectionCount = targetPort.ConnectionCount;
  320. for (int i = 0; i < connectionCount; i++) {
  321. PortConnection connection = targetPort.connections[i];
  322. NodePort otherPort = connection.Port;
  323. Connect(otherPort);
  324. }
  325. }
  326. /// <summary> Move all connections pointing to this node, to another node </summary>
  327. public void MoveConnections(NodePort targetPort) {
  328. int connectionCount = connections.Count;
  329. // Add connections to target port
  330. for (int i = 0; i < connectionCount; i++) {
  331. PortConnection connection = targetPort.connections[i];
  332. NodePort otherPort = connection.Port;
  333. Connect(otherPort);
  334. }
  335. ClearConnections();
  336. }
  337. /// <summary> Swap connected nodes from the old list with nodes from the new list </summary>
  338. public void Redirect(List<Node> oldNodes, List<Node> newNodes) {
  339. foreach (PortConnection connection in connections) {
  340. int index = oldNodes.IndexOf(connection.node);
  341. if (index >= 0) connection.node = newNodes[index];
  342. }
  343. }
  344. [Serializable]
  345. private class PortConnection {
  346. [SerializeField] public string fieldName;
  347. [SerializeField] public Node node;
  348. public NodePort Port { get { return port != null ? port : port = GetPort(); } }
  349. [NonSerialized] private NodePort port;
  350. /// <summary> Extra connection path points for organization </summary>
  351. [SerializeField] public List<Vector2> reroutePoints = new List<Vector2>();
  352. public PortConnection(NodePort port) {
  353. this.port = port;
  354. node = port.node;
  355. fieldName = port.fieldName;
  356. }
  357. /// <summary> Returns the port that this <see cref="PortConnection"/> points to </summary>
  358. private NodePort GetPort() {
  359. if (node == null || string.IsNullOrEmpty(fieldName)) return null;
  360. return node.GetPort(fieldName);
  361. }
  362. }
  363. }
  364. }