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