MatchmakingManager.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. namespace Oculus.Platform.Samples.VrBoardGame
  2. {
  3. using UnityEngine;
  4. using Oculus.Platform;
  5. using Oculus.Platform.Models;
  6. using UnityEngine.UI;
  7. using System.Collections.Generic;
  8. using System;
  9. using UnityEngine.Assertions;
  10. // This classes uses the Oculus Matchmaking Service to find opponents of a similar
  11. // skill and play a match with them. A skill pool is used with the matchmaking pool
  12. // to coordinate the skill matching. Follow the instructions in the Readme to setup
  13. // the matchmaking pools.
  14. // The Datastore for the Room is used to communicate between the clients. This only
  15. // works for relatively simple games with tolerance for latency. For more complex
  16. // or realtime requirements, you'll want to use the Oculus.Platform.Net API.
  17. public class MatchmakingManager : MonoBehaviour
  18. {
  19. // GameController to notify about match completions or early endings
  20. [SerializeField] private GameController m_gameController = null;
  21. // Text for the button that controls matchmaking
  22. [SerializeField] private Text m_matchButtonText = null;
  23. // Test widget to render matmaking statistics
  24. [SerializeField] private Text m_infoText = null;
  25. // name of the Quckmatch Pool configured on the Oculus Developer Dashboard
  26. // which is expected to have an associated skill pool
  27. private const string POOL = "VR_BOARD_GAME_POOL";
  28. // the ID of the room for the current match
  29. private ulong m_matchRoom;
  30. // opponent User data
  31. private User m_remotePlayer;
  32. // last time we've received a room update
  33. private float m_lastUpdateTime;
  34. // how long to wait before polling for updates
  35. private const float POLL_FREQUENCY = 30.0f;
  36. private enum MatchRoomState { None, Queued, Configuring, MyTurn, RemoteTurn }
  37. private MatchRoomState m_state;
  38. void Start()
  39. {
  40. Matchmaking.SetMatchFoundNotificationCallback(MatchFoundCallback);
  41. Rooms.SetUpdateNotificationCallback(MatchmakingRoomUpdateCallback);
  42. TransitionToState(MatchRoomState.None);
  43. }
  44. void Update()
  45. {
  46. switch (m_state)
  47. {
  48. case MatchRoomState.Configuring:
  49. case MatchRoomState.MyTurn:
  50. case MatchRoomState.RemoteTurn:
  51. // if we're expecting an update form the remote player and we haven't
  52. // heard from them in a while, check the datastore just-in-case
  53. if (POLL_FREQUENCY < (Time.time - m_lastUpdateTime))
  54. {
  55. Debug.Log("Polling Room");
  56. m_lastUpdateTime = Time.time;
  57. Rooms.Get(m_matchRoom).OnComplete(MatchmakingRoomUpdateCallback);
  58. }
  59. break;
  60. }
  61. }
  62. public void MatchButtonPressed()
  63. {
  64. switch (m_state)
  65. {
  66. case MatchRoomState.None:
  67. TransitionToState(MatchRoomState.Queued);
  68. break;
  69. default:
  70. TransitionToState(MatchRoomState.None);
  71. break;
  72. }
  73. }
  74. public void EndMatch(int localScore, int remoteScore)
  75. {
  76. switch (m_state)
  77. {
  78. case MatchRoomState.MyTurn:
  79. case MatchRoomState.RemoteTurn:
  80. var myID = PlatformManager.MyID.ToString();
  81. var remoteID = m_remotePlayer.ID.ToString();
  82. var rankings = new Dictionary<string, int>();
  83. if (localScore > remoteScore)
  84. {
  85. rankings[myID] = 1;
  86. rankings[remoteID] = 2;
  87. }
  88. else if (localScore < remoteScore)
  89. {
  90. rankings[myID] = 2;
  91. rankings[remoteID] = 1;
  92. }
  93. else
  94. {
  95. rankings[myID] = 1;
  96. rankings[remoteID] = 1;
  97. }
  98. // since there is no secure server to simulate the game and report
  99. // verifiable results, each client needs to independently report their
  100. // results for the service to compate for inconsistencies
  101. Matchmaking.ReportResultsInsecure(m_matchRoom, rankings)
  102. .OnComplete(GenericErrorCheckCallback);
  103. break;
  104. }
  105. TransitionToState(MatchRoomState.None);
  106. }
  107. void OnApplicationQuit()
  108. {
  109. // be a good matchmaking citizen and leave any queue immediately
  110. Matchmaking.Cancel();
  111. if (m_matchRoom != 0)
  112. {
  113. Rooms.Leave(m_matchRoom);
  114. }
  115. }
  116. private void TransitionToState(MatchRoomState state)
  117. {
  118. var m_oldState = m_state;
  119. m_state = state;
  120. switch (m_state)
  121. {
  122. case MatchRoomState.None:
  123. m_matchButtonText.text = "Find Match";
  124. // the player can abort from any of the other states to the None state
  125. // so we need to be careful to clean up all state variables
  126. m_remotePlayer = null;
  127. Matchmaking.Cancel();
  128. if (m_matchRoom != 0)
  129. {
  130. Rooms.Leave(m_matchRoom);
  131. m_matchRoom = 0;
  132. }
  133. break;
  134. case MatchRoomState.Queued:
  135. Assert.AreEqual(MatchRoomState.None, m_oldState);
  136. m_matchButtonText.text = "Leave Queue";
  137. Matchmaking.Enqueue2(POOL).OnComplete(MatchmakingEnqueueCallback);
  138. break;
  139. case MatchRoomState.Configuring:
  140. Assert.AreEqual(MatchRoomState.Queued, m_oldState);
  141. m_matchButtonText.text = "Cancel Match";
  142. break;
  143. case MatchRoomState.MyTurn:
  144. case MatchRoomState.RemoteTurn:
  145. Assert.AreNotEqual(MatchRoomState.None, m_oldState);
  146. Assert.AreNotEqual(MatchRoomState.Queued, m_oldState);
  147. m_matchButtonText.text = "Cancel Match";
  148. break;
  149. }
  150. }
  151. void MatchmakingEnqueueCallback(Message untyped_msg)
  152. {
  153. if (untyped_msg.IsError)
  154. {
  155. Debug.Log(untyped_msg.GetError().Message);
  156. TransitionToState(MatchRoomState.None);
  157. return;
  158. }
  159. Message<MatchmakingEnqueueResult> msg = (Message<MatchmakingEnqueueResult>)untyped_msg;
  160. MatchmakingEnqueueResult info = msg.Data;
  161. m_infoText.text = string.Format(
  162. "Avg Wait Time: {0}s\n" +
  163. "Max Expected Wait: {1}s\n" +
  164. "In Last Hour: {2}\n" +
  165. "Recent Percentage: {3}%",
  166. info.AverageWait, info.MaxExpectedWait, info.MatchesInLastHourCount,
  167. info.RecentMatchPercentage);
  168. }
  169. void MatchFoundCallback(Message<Room> msg)
  170. {
  171. if (msg.IsError)
  172. {
  173. Debug.Log(msg.GetError().Message);
  174. TransitionToState(MatchRoomState.None);
  175. return;
  176. }
  177. if (m_state != MatchRoomState.Queued)
  178. {
  179. // ignore callback - user already cancelled
  180. return;
  181. }
  182. // since this example communicates via updates to the datastore, it's vital that
  183. // we subscribe to room updates
  184. Matchmaking.JoinRoom(msg.Data.ID, true /* subscribe to update notifications */)
  185. .OnComplete(MatchmakingJoinRoomCallback);
  186. m_matchRoom = msg.Data.ID;
  187. }
  188. void MatchmakingJoinRoomCallback(Message<Room> msg)
  189. {
  190. if (msg.IsError)
  191. {
  192. Debug.Log(msg.GetError().Message);
  193. TransitionToState(MatchRoomState.None);
  194. return;
  195. }
  196. if (m_state != MatchRoomState.Queued)
  197. {
  198. // ignore callback - user already cancelled
  199. return;
  200. }
  201. int numUsers = (msg.Data.UsersOptional != null) ? msg.Data.UsersOptional.Count : 0;
  202. Debug.Log ("Match room joined: " + m_matchRoom + " count: " + numUsers);
  203. TransitionToState(MatchRoomState.Configuring);
  204. // only process the room data if the other user has already joined
  205. if (msg.Data.UsersOptional != null && msg.Data.UsersOptional.Count == 2)
  206. {
  207. ProcessRoomData(msg.Data);
  208. }
  209. }
  210. // Room Datastore updates are used to send moves between players. So if the MatchRoomState
  211. // is RemoteTurn I'm looking for the other player's move in the Datastore. If the
  212. // MatchRoomState is MyTurn I'm waiting for the room ownership to change so that
  213. // I have authority to write to the datastore.
  214. void MatchmakingRoomUpdateCallback(Message<Room> msg)
  215. {
  216. if (msg.IsError)
  217. {
  218. Debug.Log(msg.GetError().Message);
  219. TransitionToState(MatchRoomState.None);
  220. return;
  221. }
  222. string ownerOculusID = msg.Data.OwnerOptional != null ? msg.Data.OwnerOptional.OculusID : "";
  223. int numUsers = (msg.Data.UsersOptional != null) ? msg.Data.UsersOptional.Count : 0;
  224. Debug.LogFormat(
  225. "Room Update {0}\n" +
  226. " Owner {1}\n" +
  227. " User Count {2}\n" +
  228. " Datastore Count {3}\n",
  229. msg.Data.ID, ownerOculusID, numUsers, msg.Data.DataStore.Count);
  230. // check to make sure the room is valid as there are a few odd timing issues (for
  231. // example when leaving a room) that can trigger an uninteresting update
  232. if (msg.Data.ID != m_matchRoom)
  233. {
  234. Debug.Log("Unexpected room update from: " + msg.Data.ID);
  235. return;
  236. }
  237. ProcessRoomData(msg.Data);
  238. }
  239. private void ProcessRoomData(Room room)
  240. {
  241. m_lastUpdateTime = Time.time;
  242. if (m_state == MatchRoomState.Configuring)
  243. {
  244. // get the User info for the other player
  245. if (room.UsersOptional != null)
  246. {
  247. foreach (var user in room.UsersOptional)
  248. {
  249. if (PlatformManager.MyID != user.ID)
  250. {
  251. Debug.Log("Found remote user: " + user.OculusID);
  252. m_remotePlayer = user;
  253. break;
  254. }
  255. }
  256. }
  257. if (m_remotePlayer == null)
  258. return;
  259. bool i_go_first = DoesLocalUserGoFirst();
  260. TransitionToState(i_go_first ? MatchRoomState.MyTurn : MatchRoomState.RemoteTurn);
  261. Matchmaking.StartMatch(m_matchRoom).OnComplete(GenericErrorCheckCallback);
  262. m_gameController.StartOnlineMatch(m_remotePlayer.OculusID, i_go_first);
  263. }
  264. // if it's the remote player's turn, look for their move in the datastore
  265. if (m_state == MatchRoomState.RemoteTurn &&
  266. room.DataStore.ContainsKey(m_remotePlayer.OculusID) &&
  267. room.DataStore[m_remotePlayer.OculusID] != "")
  268. {
  269. // process remote move
  270. ProcessRemoteMove(room.DataStore[m_remotePlayer.OculusID]);
  271. TransitionToState(MatchRoomState.MyTurn);
  272. }
  273. // If the room ownership transferred to me, we can mark the remote turn complete.
  274. // We don't do this when the remote move comes in if we aren't yet the owner because
  275. // the local user will not be able to write to the datastore if they aren't the
  276. // owner of the room.
  277. if (m_state == MatchRoomState.MyTurn && room.OwnerOptional != null && room.OwnerOptional.ID == PlatformManager.MyID)
  278. {
  279. m_gameController.MarkRemoteTurnComplete();
  280. }
  281. if (room.UsersOptional == null || (room.UsersOptional != null && room.UsersOptional.Count != 2))
  282. {
  283. Debug.Log("Other user quit the room");
  284. m_gameController.RemoteMatchEnded();
  285. }
  286. }
  287. private void ProcessRemoteMove(string moveString)
  288. {
  289. Debug.Log("Processing remote move string: " + moveString);
  290. string[] tokens = moveString.Split(':');
  291. GamePiece.Piece piece = (GamePiece.Piece)Enum.Parse(typeof(GamePiece.Piece), tokens[0]);
  292. int x = Int32.Parse(tokens[1]);
  293. int y = Int32.Parse(tokens[2]);
  294. // swap the coordinates since each player assumes they are player 0
  295. x = GameBoard.LENGTH_X-1 - x;
  296. y = GameBoard.LENGTH_Y-1 - y;
  297. m_gameController.MakeRemoteMove(piece, x, y);
  298. }
  299. public void SendLocalMove(GamePiece.Piece piece, int boardX, int boardY)
  300. {
  301. string moveString = string.Format("{0}:{1}:{2}", piece.ToString(), boardX, boardY);
  302. Debug.Log("Sending move: " + moveString);
  303. var dict = new Dictionary<string, string>();
  304. dict[PlatformManager.MyOculusID] = moveString;
  305. dict[m_remotePlayer.OculusID] = "";
  306. Rooms.UpdateDataStore(m_matchRoom, dict).OnComplete(UpdateDataStoreCallback);
  307. TransitionToState(MatchRoomState.RemoteTurn);
  308. }
  309. private void UpdateDataStoreCallback(Message<Room> msg)
  310. {
  311. if (m_state != MatchRoomState.RemoteTurn)
  312. {
  313. // ignore calback - user already quit the match
  314. return;
  315. }
  316. // after I've updated the datastore with my move, change ownership so the other
  317. // user can perform their move
  318. Rooms.UpdateOwner(m_matchRoom, m_remotePlayer.ID);
  319. }
  320. // deterministic but somewhat random selection for who goes first
  321. private bool DoesLocalUserGoFirst()
  322. {
  323. // if the room ID is even, the lower ID goes first
  324. if (m_matchRoom % 2 == 0)
  325. {
  326. return PlatformManager.MyID < m_remotePlayer.ID;
  327. }
  328. // otherwise the higher ID goes first
  329. {
  330. return PlatformManager.MyID > m_remotePlayer.ID;
  331. }
  332. }
  333. private void GenericErrorCheckCallback(Message msg)
  334. {
  335. if (msg.IsError)
  336. {
  337. Debug.Log(msg.GetError().Message);
  338. TransitionToState(MatchRoomState.None);
  339. return;
  340. }
  341. }
  342. }
  343. }