NetworkGamer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. using Microsoft.Xna.Framework.GamerServices;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Net;
  6. namespace Microsoft.Xna.Framework.Net
  7. {
  8. /// <summary>
  9. /// Represents a player in a network session.
  10. /// </summary>
  11. public class NetworkGamer
  12. {
  13. private static NetworkGamer localGamer;
  14. private readonly NetworkSession session;
  15. private readonly string id;
  16. private readonly bool isLocal;
  17. private readonly bool isHost;
  18. private string gamertag;
  19. private bool isReady;
  20. private object tag;
  21. // Network performance properties
  22. private TimeSpan roundtripTime = TimeSpan.Zero;
  23. /// <summary>
  24. /// Gets the unique identifier for this gamer.
  25. /// </summary>
  26. public string Id => id;
  27. /// <summary>
  28. /// Gets whether this gamer is the local player.
  29. /// </summary>
  30. public bool IsLocal => isLocal;
  31. /// <summary>
  32. /// Gets whether this gamer is the host of the session.
  33. /// </summary>
  34. public bool IsHost => isHost;
  35. /// <summary>
  36. /// Gets or sets the gamertag for this gamer.
  37. /// </summary>
  38. public string Gamertag
  39. {
  40. get => gamertag;
  41. set => gamertag = value ?? throw new ArgumentNullException(nameof(value));
  42. }
  43. /// <summary>
  44. /// Gets or sets whether this gamer is ready to start the game.
  45. /// </summary>
  46. public bool IsReady
  47. {
  48. get => isReady;
  49. set
  50. {
  51. if (isReady != value)
  52. {
  53. isReady = value;
  54. // Notify session of readiness change if this is the local gamer
  55. if (isLocal)
  56. {
  57. session?.NotifyReadinessChanged(this);
  58. }
  59. }
  60. }
  61. }
  62. /// <summary>
  63. /// Gets or sets custom data associated with this gamer.
  64. /// </summary>
  65. public object Tag
  66. {
  67. get => tag;
  68. set => tag = value;
  69. }
  70. /// <summary>
  71. /// Gets the machine for this network gamer.
  72. /// </summary>
  73. public NetworkMachine Machine => null; // Mock implementation
  74. /// <summary>
  75. /// Gets whether data is available to be received from this gamer.
  76. /// </summary>
  77. public bool IsDataAvailable => incomingPackets.Count > 0;
  78. /// <summary>
  79. /// Gets the SignedInGamer associated with this NetworkGamer.
  80. /// </summary>
  81. public SignedInGamer SignedInGamer => SignedInGamer.Current;
  82. /// <summary>
  83. /// Gets whether this gamer is muted by the local user.
  84. /// </summary>
  85. public bool IsMutedByLocalUser => false; // Mock implementation
  86. /// <summary>
  87. /// Gets whether this gamer is currently talking.
  88. /// </summary>
  89. public bool IsTalking => false; // Mock implementation
  90. /// <summary>
  91. /// Gets whether this gamer has voice capabilities.
  92. /// </summary>
  93. public bool HasVoice => false; // Mock implementation
  94. // Add to NetworkGamer class
  95. private readonly Queue<(byte[] Data, NetworkGamer Sender)> incomingPackets = new Queue<(byte[], NetworkGamer)>();
  96. internal NetworkGamer(NetworkSession session, string id, bool isLocal, bool isHost, string gamertag)
  97. {
  98. this.session = session;
  99. this.id = id;
  100. this.isLocal = isLocal;
  101. this.isHost = isHost;
  102. this.gamertag = gamertag;
  103. }
  104. /// <summary>
  105. /// Receives data from this gamer.
  106. /// </summary>
  107. /// <param name="data">Array to receive the data into.</param>
  108. /// <param name="sender">The gamer who sent the data.</param>
  109. /// <returns>The number of bytes received.</returns>
  110. public int ReceiveData(byte[] data, out NetworkGamer sender)
  111. {
  112. if (data == null)
  113. throw new ArgumentNullException(nameof(data));
  114. sender = null;
  115. // Check if data is available
  116. if (!IsDataAvailable)
  117. return 0;
  118. var packet = incomingPackets.Dequeue();
  119. sender = packet.Sender;
  120. int length = Math.Min(data.Length, packet.Data.Length);
  121. Array.Copy(packet.Data, data, length);
  122. return length;
  123. }
  124. public int ReceiveData(byte[] data, int offset, out NetworkGamer sender)
  125. {
  126. if (data == null)
  127. throw new ArgumentNullException(nameof(data));
  128. if (offset < 0 || offset >= data.Length)
  129. throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be within the bounds of the data array.");
  130. sender = null;
  131. // Check if data is available
  132. if (!IsDataAvailable)
  133. return 0;
  134. var packet = incomingPackets.Dequeue();
  135. sender = packet.Sender;
  136. int length = Math.Min(data.Length - offset, packet.Data.Length);
  137. Array.Copy(packet.Data, 0, data, offset, length);
  138. return length;
  139. }
  140. /// <summary>
  141. /// Receives data from this gamer using PacketReader.
  142. /// </summary>
  143. /// <param name="data">Array to receive the data into.</param>
  144. /// <param name="sender">The gamer who sent the data.</param>
  145. /// <returns>The number of bytes received.</returns>
  146. public int ReceiveData(PacketReader reader, out NetworkGamer sender)
  147. {
  148. // Ensure the session is valid
  149. if (session == null)
  150. throw new InvalidOperationException("Network session is not initialized.");
  151. reader = null;
  152. sender = null;
  153. // Check if data is available
  154. if (!IsDataAvailable)
  155. return 0;
  156. var packet = incomingPackets.Dequeue();
  157. sender = packet.Sender;
  158. reader = new PacketReader(packet.Data);
  159. return packet.Data.Length;
  160. }
  161. /// <summary>
  162. /// Sends data to other gamers in the session.
  163. /// </summary>
  164. /// <param name="data">The data to send.</param>
  165. /// <param name="options">Send options.</param>
  166. public void SendData(byte[] data, SendDataOptions options)
  167. {
  168. if (data == null)
  169. throw new ArgumentNullException(nameof(data));
  170. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  171. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  172. SendDataInternal(data, options, session.AllGamers);
  173. }
  174. /// <summary>
  175. /// Sends data to specific gamers in the session.
  176. /// </summary>
  177. /// <param name="data">The data to send.</param>
  178. /// <param name="options">Send options.</param>
  179. /// <param name="recipients">The gamers to send to.</param>
  180. public void SendData(byte[] data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  181. {
  182. if (data == null)
  183. throw new ArgumentNullException(nameof(data));
  184. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  185. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  186. SendDataInternal(data, options, recipients);
  187. }
  188. /// <summary>
  189. /// Sends data using PacketWriter.
  190. /// </summary>
  191. /// <param name="data">The data to send.</param>
  192. /// <param name="options">Send options.</param>
  193. public void SendData(PacketWriter data, SendDataOptions options)
  194. {
  195. if (data == null)
  196. throw new ArgumentNullException(nameof(data), "PacketWriter cannot be null.");
  197. if (!Enum.IsDefined(typeof(SendDataOptions), options))
  198. throw new ArgumentOutOfRangeException(nameof(options), "Invalid send data option.");
  199. byte[] serializedData = data.GetData();
  200. SendDataInternal(serializedData, options, session.AllGamers);
  201. }
  202. /// <summary>
  203. /// Sends data using PacketWriter to specific recipients.
  204. /// </summary>
  205. /// <param name="data">The data to send.</param>
  206. /// <param name="options">Send options.</param>
  207. /// <param name="recipients">The gamers to send to.</param>
  208. public void SendData(PacketWriter data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  209. {
  210. if (data == null)
  211. throw new ArgumentNullException(nameof(data), "PacketWriter cannot be null.");
  212. if (recipients == null)
  213. throw new ArgumentNullException(nameof(recipients));
  214. byte[] serializedData = data.GetData();
  215. SendDataInternal(serializedData, options, recipients);
  216. }
  217. /// <summary>
  218. /// Sends data using PacketWriter to a specific recipient.
  219. /// </summary>
  220. /// <param name="data">The data to send.</param>
  221. /// <param name="options">Send options.</param>
  222. /// <param name="recipient">The gamer to send to.</param>
  223. public void SendData(PacketWriter data, SendDataOptions options, NetworkGamer recipient)
  224. {
  225. SendData(data, options, new[] { recipient });
  226. }
  227. /// <summary>
  228. /// Sends byte array data to a specific recipient.
  229. /// </summary>
  230. /// <param name="data">The data to send.</param>
  231. /// <param name="options">Send options.</param>
  232. /// <param name="recipient">The gamer to send to.</param>
  233. public void SendData(byte[] data, SendDataOptions options, NetworkGamer recipient)
  234. {
  235. SendData(data, options, new[] { recipient });
  236. }
  237. /// <summary>
  238. /// Gets the current round-trip time for network communication with this gamer.
  239. /// </summary>
  240. public TimeSpan RoundtripTime => roundtripTime;
  241. /// <summary>
  242. /// Updates the round-trip time (internal use).
  243. /// </summary>
  244. internal void UpdateRoundtripTime(TimeSpan newRoundtripTime)
  245. {
  246. roundtripTime = newRoundtripTime;
  247. }
  248. public override string ToString()
  249. {
  250. return $"{Gamertag} ({(IsLocal ? "Local" : "Remote")}, {(IsHost ? "Host" : "Player")})";
  251. }
  252. public override bool Equals(object obj)
  253. {
  254. return obj is NetworkGamer other && Id == other.Id;
  255. }
  256. public override int GetHashCode()
  257. {
  258. return Id.GetHashCode();
  259. }
  260. /// <summary>
  261. /// Gets the local gamer.
  262. /// </summary>
  263. public static NetworkGamer LocalGamer
  264. {
  265. get => localGamer;
  266. internal set => localGamer = value;
  267. }
  268. /// <summary>
  269. /// Implicit conversion from NetworkGamer to SignedInGamer.
  270. /// </summary>
  271. public static implicit operator SignedInGamer(NetworkGamer gamer)
  272. {
  273. return gamer?.SignedInGamer;
  274. }
  275. private void SendDataInternal(byte[] data, SendDataOptions options, IEnumerable<NetworkGamer> recipients)
  276. {
  277. switch (session.SessionType)
  278. {
  279. case NetworkSessionType.SystemLink:
  280. foreach (var recipient in recipients)
  281. {
  282. session.SendDataToGamer(recipient, data, options);
  283. }
  284. break;
  285. case NetworkSessionType.Local:
  286. // TODO: session.ProcessIncomingMessages(); // Simulate message delivery
  287. break;
  288. case NetworkSessionType.PlayerMatch:
  289. // Placeholder for future implementation
  290. throw new NotImplementedException("PlayerMatch session type is not yet supported.");
  291. case NetworkSessionType.Ranked:
  292. // Placeholder for future implementation
  293. throw new NotImplementedException("Ranked session type is not yet supported.");
  294. default:
  295. throw new ArgumentOutOfRangeException(nameof(session.SessionType), $"Unsupported session type: {session.SessionType}");
  296. }
  297. }
  298. internal void EnqueueIncomingPacket(byte[] data, NetworkGamer sender)
  299. {
  300. lock (incomingPackets)
  301. {
  302. incomingPackets.Enqueue((data, sender));
  303. }
  304. }
  305. }
  306. }