2 using System.Collections.Generic;
5 using Microsoft.Xna.Framework.Net;
6 using System.Diagnostics;
7 using Microsoft.Xna.Framework.GamerServices;
8 using Microsoft.Xna.Framework.Graphics;
9 using Microsoft.Xna.Framework;
10 using Microsoft.Xna.Framework.Input;
11 using System.Collections;
13 namespace CS_3505_Project_06
16 /// A manager class to handle network interactions between peers and
17 /// lobby/game switching.
19 public class NetworkGame
21 // Public methods and properties
22 #region Public Methods
25 /// Called when a session has been created or joined using CreateSession() or JoinSession().
27 /// <param name="session">The new session that was created or joined.</param>
28 /// <param name="networkGame">The NetworkGame that joined the session.</param>
29 public delegate void JoinedSessionDelegate(NetworkSession session, NetworkGame networkGame);
32 /// Called when sessions are found as a result of calling FindSessions().
34 /// <param name="sessions">A container of the available sessions.</param>
35 /// <param name="networkGame">The NetworkGame that searched for the sessions.</param>
36 public delegate void FoundSessionsDelegate(AvailableNetworkSessionCollection sessions, NetworkGame networkGame);
40 /// Construct a NetworkGame with a lobby and a game.
42 /// <param name="lobby">Provides an associated lobby to update and draw.</param>
43 /// <param name="game">Provides a game object to be played over the network.</param>
44 public NetworkGame(ILobby lobby, IDeterministicGame game)
46 Debug.Assert(lobby != null && game != null);
54 /// Get the Gamer object for the local player.
56 public LocalNetworkGamer LocalGamer
60 // TODO: Is this the correct way to get the single local gamer?
61 return mNetworkSession.LocalGamers[0];
66 /// Get all the gamers associated with the active network session.
68 public GamerCollection<NetworkGamer> NetworkGamers
72 return mNetworkSession.AllGamers;
78 /// Begin a new network session with the local gamer as the host. You must not
79 /// call this method or use JoinSession without first using LeaveSession.
81 /// <param name="callback">The delegate/method to call when the session is created.</param>
82 public void CreateSession(JoinedSessionDelegate callback)
84 CreateSession(mGame.MaximumSupportedPlayers, callback);
88 /// Begin a new network session with the local gamer as the host. You must not
89 /// call this method or use JoinSession without first using LeaveSession.
91 /// <param name="maxGamers">Provide the maximum number of players allowed to connect.</param>
92 /// <param name="callback">The delegate/method to call when the session is created.</param>
93 public void CreateSession(int maxGamers, JoinedSessionDelegate callback)
95 Debug.Assert(mNetworkSession == null);
97 mJoinedSessionDelegate = callback;
98 NetworkSession.BeginCreate(NetworkSessionType.SystemLink, 1, maxGamers, CreateSessionEnd, null);
100 private void CreateSessionEnd(IAsyncResult result)
102 Debug.Assert(mNetworkSession == null);
104 mNetworkSession = NetworkSession.EndCreate(result);
105 mNetworkSession.AllowHostMigration = true;
106 mNetworkSession.AllowJoinInProgress = false;
108 mJoinedSessionDelegate(mNetworkSession, this);
112 /// Determine whether or not the network game object is associated with any network session.
114 /// <returns>True if there exists a NetworkSession; false otherwise.</returns>
115 public bool HasActiveSession
119 return mNetworkSession != null;
125 /// Find available sessions to join. You should not already be in a session when
126 /// calling this method; call LeaveSession first.
128 /// <param name="callback">The delegate/method to call when the search finishes.</param>
129 public void FindSessions(FoundSessionsDelegate callback)
131 Debug.Assert(mNetworkSession == null);
133 mFoundSessionsDelegate = callback;
134 NetworkSession.BeginFind(NetworkSessionType.SystemLink, 1, null, new AsyncCallback(FindSessionsEnd), null);
136 private void FindSessionsEnd(IAsyncResult result)
138 AvailableNetworkSessionCollection sessions = NetworkSession.EndFind(result);
139 mFoundSessionsDelegate(sessions, this);
143 /// Join a network session found using FindSessions(). This is for joining a game that
144 /// somebody else has already started hosting. You must not already be in a session.
146 /// <param name="availableSession">Pass the session object to try to join.</param>
147 /// <param name="callback">The delegate/method to call when the search finishes.</param>
148 public void JoinSession(AvailableNetworkSession availableSession, JoinedSessionDelegate callback)
150 Debug.Assert(mNetworkSession == null);
152 mJoinedSessionDelegate = callback;
153 NetworkSession.BeginJoin(availableSession, JoinSessionEnd, null);
155 private void JoinSessionEnd(IAsyncResult result)
157 Debug.Assert(mNetworkSession == null);
159 mNetworkSession = NetworkSession.EndJoin(result);
161 mJoinedSessionDelegate(mNetworkSession, this);
162 mJoinedSessionDelegate = null;
167 /// Leave and dispose of any currently associated network session. You will find yourself
168 /// back in the lobby. You must already be in a session to leave it.
170 public void LeaveSession()
172 Debug.Assert(mNetworkSession != null);
174 mNetworkSession.Dispose();
175 mNetworkSession = null;
180 /// Set up the network session to simulate 200ms latency and 10% packet loss.
182 public void SimulateBadNetwork()
184 Debug.Assert(mNetworkSession != null);
186 mNetworkSession.SimulatedLatency = new TimeSpan(0, 0, 0, 0, 200);
187 mNetworkSession.SimulatedPacketLoss = 0.1f;
192 /// Indicate that the game should begin (moving players from the lobby to the game).
193 /// You must call CreateSession() before calling this.
195 public void StartGame()
197 Debug.Assert(mNetworkSession != null && mNetworkSession.IsHost &&
198 mNetworkSession.AllGamers.Count >= mGame.MinimumSupportedPlayers &&
199 mNetworkSession.IsEveryoneReady);
205 /// Indicate that the game should begin. This is like StartGame() without the sanity
206 /// checks. Use this for debugging.
208 public void ForceStartGame()
210 mNetworkSession.StartGame();
211 mNetworkSession.ResetReady();
218 /// Manages the network session and allows either the lobby or game to update.
220 /// <param name="gameTime">Pass the time away.</param>
221 public void Update(GameTime gameTime)
223 if (mNetworkSession == null)
225 mLobby.Update(gameTime, this);
229 mNetworkSession.Update();
230 HandleIncomingPackets();
232 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
234 mLobby.Update(gameTime, this);
236 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
238 //TODO reset needs to be called for all players, currently LocalGamerInfo throughs exception for all nonhosts
239 // because in start game reset is only called on hosts games thus other clients never get an updated list
243 //thoughs exeption see TODO above
244 //if (mGame.IsGameOver(LocalGamerInfo) || mGame.IsTerminated(LocalGamerInfo))
246 // // TODO: Should support moving back to the session lobby.
251 if (HaveNeededEvents)
253 if (IsLatencyAdjustmentFrame)
258 mLocalEvents.AddRange(GetEventsFromInput());
261 mGame.Update(mTargetTimeSpan);
267 if (mStallCount % 60 == 0)
269 Console.WriteLine("Stalled for " + mStallCount + " frames.");
272 /*if (mStallCount > StallTimeout)
277 else if (mStallCount == 1)
281 else if (mStallCount % 60 == 0)
290 /// Allows either the lobby or the game to draw, depending on the state
291 /// of the network connection and whether or not a game is in progress.
293 /// <param name="gameTime">Pass the time away.</param>
294 /// <param name="spriteBatch">The sprite batch.</param>
295 public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
297 if (mNetworkSession == null)
299 mLobby.Draw(spriteBatch);
303 if (mNetworkSession.SessionState == NetworkSessionState.Lobby)
305 mLobby.Draw(spriteBatch);
307 else if (mNetworkSession.SessionState == NetworkSessionState.Playing)
309 mGame.Draw(spriteBatch);
316 /// Get the chat messages that have been receive since the last time this
317 /// method was called.
319 /// <returns>List container of the chat messages.</returns>
320 public List<ChatInfo> ReceiveChats()
322 List<ChatInfo> chats = mChatPackets;
323 mChatPackets = new List<ChatInfo>();
328 /// Send a chat message to all gamers in the session. You should already be
329 /// in a session before calling this method.
331 /// <param name="message">The text of the message.</param>
332 public void SendChat(String message)
334 WriteChatPacket(message);
335 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder);
339 /// Send a chat message to a specific gamer in the session. You should already
340 /// be in a session before calling this method.
342 /// <param name="message">The text of the message.</param>
343 /// <param name="recipient">The gamer to receive the message.</param>
344 public void SendChat(String message, NetworkGamer recipient)
346 WriteChatPacket(message);
347 LocalGamer.SendData(mPacketWriter, SendDataOptions.ReliableInOrder, recipient);
353 // Private class variable members
354 #region Instance Variables
356 NetworkSession mNetworkSession;
357 PacketReader mPacketReader = new PacketReader();
358 PacketWriter mPacketWriter = new PacketWriter();
360 JoinedSessionDelegate mJoinedSessionDelegate;
361 FoundSessionsDelegate mFoundSessionsDelegate;
364 IDeterministicGame mGame;
366 List<ChatInfo> mChatPackets = new List<ChatInfo>();
368 List<EventInfo> mLocalEvents = new List<EventInfo>();
369 List<EventInfo> mLastLocalEvents = new List<EventInfo>();
371 List<Keys> mLastPressedKeys = new List<Keys>();
372 bool mLastLeftButtonPressed;
373 bool mLastRightButtonPressed;
374 bool mLastMiddleButtonPressed;
375 int mLastMousePositionX;
376 int mLastMousePositionY;
379 long mNextLatencyAdjustmentFrame;
383 TimeSpan mTargetTimeSpan = new TimeSpan(166666);
384 public TimeSpan TargetTimeSpan
388 return mTargetTimeSpan;
392 Dictionary<byte, GamerInfo> mGamers;
393 GamerInfo[] GamerArray
397 GamerInfo[] gamerList = mGamers.Values.ToArray();
398 Array.Sort(gamerList, delegate(GamerInfo a, GamerInfo b)
400 return a.Gamer.Id.CompareTo(b.Gamer.Id);
405 GamerInfo LocalGamerInfo
409 return mGamers[LocalGamer.Id];
416 // Private types for the implementation of the network protocol
417 #region Private Types
442 abstract class EventInfo
444 public NetworkGamer Gamer;
445 public long FrameOfApplication;
447 public EventInfo(NetworkGamer gamer, long frameNumber)
450 FrameOfApplication = frameNumber;
453 public abstract EventType Id
459 class KeyboardEventInfo : EventInfo
462 public bool IsKeyDown;
464 public KeyboardEventInfo(NetworkGamer gamer, long frameNumber, Keys key, bool isDown)
465 : base(gamer, frameNumber)
471 public override EventType Id
473 get { return IsKeyDown ? EventType.KeyDown : EventType.KeyUp; }
477 class MouseButtonEventInfo : EventInfo
479 public MouseButton Button;
480 public bool IsButtonDown;
482 public MouseButtonEventInfo(NetworkGamer gamer, long frameNumber, MouseButton button, bool isDown)
483 : base(gamer, frameNumber)
486 IsButtonDown = isDown;
489 public override EventType Id
491 get { return IsButtonDown ? EventType.MouseDown : EventType.MouseUp; }
495 class MouseMotionEventInfo : EventInfo
500 public MouseMotionEventInfo(NetworkGamer gamer, long frameNumber, int x, int y)
501 : base(gamer, frameNumber)
507 public override EventType Id
509 get { return EventType.MouseMove; }
515 public NetworkGamer Gamer;
516 public long HighestFrameNumber = 0;
517 public int StallCount = 0;
518 public int AverageOwd = 0;
519 public bool IsWaitedOn = false;
520 public List<EventInfo>[] Events = new List<EventInfo>[MaximumLatency];
522 public GamerInfo(NetworkGamer gamer)
528 const int MaximumLatency = 120;
529 const int StallTimeout = 900;
534 // Private implementation methods of the network protocol
535 #region Private Implementation Methods
538 /// Reinitialize the private variables in preparation for a new game to start.
543 mNextLatencyAdjustmentFrame = 1;
545 mAverageOwd = CurrentAverageOneWayDelay;
547 mGamers = new Dictionary<byte, GamerInfo>();
548 foreach (NetworkGamer gamer in NetworkGamers)
550 mGamers.Add(gamer.Id, new GamerInfo(gamer));
553 mGame.ResetGame(GamerArray, LocalGamerInfo);
557 void HandleIncomingPackets()
559 LocalNetworkGamer localGamer = LocalGamer;
561 while (localGamer.IsDataAvailable)
565 localGamer.ReceiveData(mPacketReader, out sender);
566 GamerInfo senderInfo = mGamers[sender.Id];
568 PacketType packetId = (PacketType)mPacketReader.ReadByte();
571 case PacketType.Chat:
573 short messageLength = mPacketReader.ReadInt16();
574 char[] message = mPacketReader.ReadChars(messageLength);
576 ChatInfo chatPacket = new ChatInfo(sender, new String(message));
577 mChatPackets.Add(chatPacket);
580 case PacketType.Event:
582 short stallCount = mPacketReader.ReadInt16();
583 short averageOwd = mPacketReader.ReadInt16();
584 int frameNumber = mPacketReader.ReadInt32();
585 byte numEvents = mPacketReader.ReadByte();
587 if (frameNumber <= senderInfo.HighestFrameNumber)
589 // we know about all these events, so don't bother reading them
593 for (byte i = 0; i < numEvents; ++i)
595 EventInfo eventInfo = ReadEvent(mPacketReader, sender);
597 if (eventInfo != null && eventInfo.FrameOfApplication < senderInfo.HighestFrameNumber)
599 int index = EventArrayIndex;
600 if (senderInfo.Events[index] == null) senderInfo.Events[index] = new List<EventInfo>();
601 senderInfo.Events[index].Add(eventInfo);
605 senderInfo.StallCount = stallCount;
606 senderInfo.AverageOwd = averageOwd;
607 senderInfo.HighestFrameNumber = frameNumber;
610 case PacketType.Stall:
612 byte numStalledPeers = mPacketReader.ReadByte();
613 byte[] stalledPeers = mPacketReader.ReadBytes(numStalledPeers);
621 Console.WriteLine("Received unknown packet type: " + (int)packetId);
630 get { return (int)(mGame.CurrentFrameNumber % MaximumLatency); }
633 EventInfo ReadEvent(PacketReader packetReader, NetworkGamer sender)
635 EventType eventId = (EventType)packetReader.ReadByte();
636 long frameNumber = packetReader.ReadInt32();
640 case EventType.KeyDown:
642 int keyCode1 = packetReader.ReadInt32();
643 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode1, true);
645 case EventType.KeyUp:
647 int keyCode2 = packetReader.ReadInt32();
648 return new KeyboardEventInfo(sender, frameNumber, (Keys)keyCode2, false);
650 case EventType.MouseDown:
652 byte buttonId1 = packetReader.ReadByte();
653 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId1, true);
655 case EventType.MouseUp:
657 byte buttonId2 = packetReader.ReadByte();
658 return new MouseButtonEventInfo(sender, frameNumber, (MouseButton)buttonId2, false);
660 case EventType.MouseMove:
662 short x = packetReader.ReadInt16();
663 short y = packetReader.ReadInt16();
664 return new MouseMotionEventInfo(sender, frameNumber, x, y);
668 Console.WriteLine("Received unknown event type: " + (int)eventId);
674 void WriteChatPacket(String message)
676 mPacketWriter.Write((byte)PacketType.Chat);
677 mPacketWriter.Write((short)message.Length);
678 mPacketWriter.Write(message.ToCharArray());
681 void WriteEventPacket(List<EventInfo> events)
683 mPacketWriter.Write((byte)PacketType.Event);
684 mPacketWriter.Write((short)mStallCount);
685 mPacketWriter.Write((short)mAverageOwd);
686 mPacketWriter.Write((int)(mGame.CurrentFrameNumber + mLatency));
687 mPacketWriter.Write((byte)events.Count);
689 foreach (EventInfo eventInfo in events)
691 mPacketWriter.Write((byte)eventInfo.Id);
692 mPacketWriter.Write((int)eventInfo.FrameOfApplication);
694 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
695 if (keyboardEventInfo != null)
697 mPacketWriter.Write((int)keyboardEventInfo.Key);
701 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
702 if (mouseButtonEventInfo != null)
704 mPacketWriter.Write((byte)mouseButtonEventInfo.Button);
708 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
709 if (mouseMotionEventInfo != null)
711 mPacketWriter.Write((short)mouseMotionEventInfo.X);
712 mPacketWriter.Write((short)mouseMotionEventInfo.Y);
719 bool IsLatencyAdjustmentFrame
723 return mNextLatencyAdjustmentFrame == mGame.CurrentFrameNumber;
729 Debug.Assert(IsLatencyAdjustmentFrame);
731 int maxStallCount = 0;
732 int maxAverageOwd = 0;
734 foreach (GamerInfo gamerInfo in GamerArray)
736 if (gamerInfo.StallCount > maxStallCount) maxStallCount = gamerInfo.StallCount;
737 if (gamerInfo.AverageOwd > maxAverageOwd) maxAverageOwd = gamerInfo.AverageOwd;
741 int prevLatency = mLatency;
743 if (maxStallCount > 0)
745 mLatency += maxStallCount;
749 mLatency = (int)(0.6 * (double)(mLatency - maxAverageOwd) + 1.0);
753 if (prevLatency != mLatency) Console.WriteLine("Latency readjusted to " + mLatency);
755 if (mLatency < 1) mLatency = 1;
756 if (mLatency > MaximumLatency) mLatency = MaximumLatency;
758 mNextLatencyAdjustmentFrame = mGame.CurrentFrameNumber + mLatency;
759 mAverageOwd = CurrentAverageOneWayDelay;
761 mLastLocalEvents = mLocalEvents;
762 mLocalEvents = new List<EventInfo>();
767 List<EventInfo> GetEventsFromInput()
769 List<EventInfo> events = new List<EventInfo>();
771 // 1. Find the keyboard differences; written by Peter.
773 KeyboardState keyState = Keyboard.GetState();
775 List<Keys> pressedKeys = new List<Keys>();
776 List<Keys> releasedKeys = new List<Keys>();
778 Keys[] pressedKeysArray = keyState.GetPressedKeys();
779 foreach (Keys k in pressedKeysArray)
781 if (!mLastPressedKeys.Contains(k)) pressedKeys.Add(k);
782 else mLastPressedKeys.Remove(k);
785 releasedKeys = mLastPressedKeys;
787 foreach (Keys key in pressedKeys)
789 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, true));
791 foreach (Keys key in releasedKeys)
793 events.Add(new KeyboardEventInfo(LocalGamer, mGame.CurrentFrameNumber, key, false));
796 // 2. Find the mouse differences.
798 MouseState mouseState = Mouse.GetState();
800 bool leftButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
801 if (leftButtonPressed != mLastLeftButtonPressed)
803 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Left, leftButtonPressed));
806 bool rightButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
807 if (rightButtonPressed != mLastRightButtonPressed)
809 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Right, rightButtonPressed));
812 bool middleButtonPressed = mouseState.LeftButton == ButtonState.Pressed;
813 if (middleButtonPressed != mLastMiddleButtonPressed)
815 events.Add(new MouseButtonEventInfo(LocalGamer, mGame.CurrentFrameNumber, MouseButton.Middle, middleButtonPressed));
818 int mousePositionX = mouseState.X;
819 int mousePositionY = mouseState.Y;
820 if (mousePositionX != mLastMousePositionX || mousePositionY != mLastMousePositionY)
822 events.Add(new MouseMotionEventInfo(LocalGamer, mGame.CurrentFrameNumber, mousePositionX, mousePositionY));
825 // 3. Save the current peripheral state.
827 mLastPressedKeys = new List<Keys>(pressedKeysArray);
828 mLastLeftButtonPressed = leftButtonPressed;
829 mLastRightButtonPressed = rightButtonPressed;
830 mLastMiddleButtonPressed = middleButtonPressed;
831 mLastMousePositionX = mousePositionX;
832 mLastMousePositionY = mousePositionY;
837 void SendLocalEvents()
839 SendLocalEvents((NetworkGamer)null);
842 void SendLocalEvents(List<NetworkGamer> recipicents)
844 foreach (NetworkGamer gamer in recipicents)
846 SendLocalEvents(gamer);
850 void SendLocalEvents(NetworkGamer recipient)
852 List<EventInfo> events = new List<EventInfo>(mLocalEvents);
853 events.AddRange(mLastLocalEvents);
855 WriteEventPacket(events);
857 if (recipient != null)
859 LocalGamer.SendData(mPacketWriter, SendDataOptions.Reliable, recipient);
863 LocalGamer.SendData(mPacketWriter, SendDataOptions.None);
868 bool HaveNeededEvents
872 long currentFrame = mGame.CurrentFrameNumber;
874 foreach (GamerInfo gamerInfo in mGamers.Values)
876 if (gamerInfo.HighestFrameNumber < currentFrame) return false;
885 int index = EventArrayIndex;
887 foreach (GamerInfo gamerInfo in GamerArray)
889 if (gamerInfo.Events[index] == null) continue;
891 foreach (EventInfo eventInfo in gamerInfo.Events[index])
893 KeyboardEventInfo keyboardEventInfo = eventInfo as KeyboardEventInfo;
894 if (keyboardEventInfo != null)
896 mGame.ApplyKeyInput(gamerInfo, keyboardEventInfo.Key, keyboardEventInfo.IsKeyDown);
900 MouseButtonEventInfo mouseButtonEventInfo = eventInfo as MouseButtonEventInfo;
901 if (mouseButtonEventInfo != null)
903 mGame.ApplyMouseButtonInput(gamerInfo, mouseButtonEventInfo.IsButtonDown);
907 MouseMotionEventInfo mouseMotionEventInfo = eventInfo as MouseMotionEventInfo;
908 if (mouseMotionEventInfo != null)
910 mGame.ApplyMouseLocationInput(gamerInfo, mouseMotionEventInfo.X, mouseMotionEventInfo.Y);
915 gamerInfo.Events[index] = null;
920 int CurrentAverageOneWayDelay
924 Debug.Assert(mNetworkSession != null);
926 double numRemoteGamersTwice = 2 * mNetworkSession.RemoteGamers.Count;
927 double averageOwd = 0;
929 foreach (NetworkGamer gamer in mNetworkSession.RemoteGamers)
931 TimeSpan timeSpan = gamer.RoundtripTime;
932 averageOwd += timeSpan.TotalMilliseconds;
935 return (int)(averageOwd / numRemoteGamersTwice / 16.6666);