From 5f22cd809362e8ccd758526ccc320628b78ccba8 Mon Sep 17 00:00:00 2001 From: Tropical <42101043+tropicaaal@users.noreply.github.com> Date: Sun, 22 Mar 2026 04:16:54 -0500 Subject: [PATCH] format Platform/Common/Network --- .../Common/Network/GameNetworkManager.cpp | 3094 +++++++++-------- .../Common/Network/GameNetworkManager.h | 324 +- .../Common/Network/NetworkPlayerInterface.h | 52 +- .../Network/PlatformNetworkManagerInterface.h | 188 +- .../Network/PlatformNetworkManagerStub.cpp | 965 +++-- .../Network/PlatformNetworkManagerStub.h | 315 +- .../Platform/Common/Network/SessionInfo.h | 164 +- .../Common/Network/Sony/NetworkPlayerSony.cpp | 130 +- .../Common/Network/Sony/NetworkPlayerSony.h | 59 +- .../Sony/PlatformNetworkManagerSony.cpp | 1906 +++++----- .../Network/Sony/PlatformNetworkManagerSony.h | 306 +- .../Common/Network/Sony/SQRNetworkManager.cpp | 5 +- .../Common/Network/Sony/SQRNetworkManager.h | 503 +-- .../Common/Network/Sony/SQRNetworkPlayer.cpp | 575 ++- .../Common/Network/Sony/SQRNetworkPlayer.h | 199 +- .../Common/Network/Sony/SonyCommerce.cpp | 2548 +++++++------- .../Common/Network/Sony/SonyCommerce.h | 361 +- .../Platform/Common/Network/Sony/SonyHttp.cpp | 19 +- .../Platform/Common/Network/Sony/SonyHttp.h | 12 +- .../Common/Network/Sony/SonyRemoteStorage.cpp | 464 ++- .../Common/Network/Sony/SonyRemoteStorage.h | 183 +- .../header/sceRemoteStorage.h | 239 +- .../header/sceRemoteStorageDefines.h | 286 +- 23 files changed, 6503 insertions(+), 6394 deletions(-) diff --git a/Minecraft.Client/Platform/Common/Network/GameNetworkManager.cpp b/Minecraft.Client/Platform/Common/Network/GameNetworkManager.cpp index 2948e1297..7e092141e 100644 --- a/Minecraft.Client/Platform/Common/Network/GameNetworkManager.cpp +++ b/Minecraft.Client/Platform/Common/Network/GameNetworkManager.cpp @@ -44,1734 +44,1820 @@ // Global instance CGameNetworkManager g_NetworkManager; -CPlatformNetworkManager *CGameNetworkManager::s_pPlatformNetworkManager; +CPlatformNetworkManager* CGameNetworkManager::s_pPlatformNetworkManager; __int64 CGameNetworkManager::messageQueue[512]; __int64 CGameNetworkManager::byteQueue[512]; int CGameNetworkManager::messageQueuePos = 0; -CGameNetworkManager::CGameNetworkManager() -{ - m_bInitialised = false; - m_bLastDisconnectWasLostRoomOnly = false; - m_bFullSessionMessageOnNextSessionChange = false; +CGameNetworkManager::CGameNetworkManager() { + m_bInitialised = false; + m_bLastDisconnectWasLostRoomOnly = false; + m_bFullSessionMessageOnNextSessionChange = false; #ifdef __ORBIS__ - m_pUpsell = NULL; - m_pInviteInfo = NULL; + m_pUpsell = NULL; + m_pInviteInfo = NULL; #endif } -void CGameNetworkManager::Initialise() -{ - ServerStoppedCreate( false ); - ServerReadyCreate( false ); - int flagIndexSize = LevelRenderer::getGlobalChunkCount() / (Level::maxBuildHeight / 16); // dividing here by number of renderer chunks in one column +void CGameNetworkManager::Initialise() { + ServerStoppedCreate(false); + ServerReadyCreate(false); + int flagIndexSize = + LevelRenderer::getGlobalChunkCount() / + (Level::maxBuildHeight / + 16); // dividing here by number of renderer chunks in one column #ifdef _XBOX - s_pPlatformNetworkManager = new CPlatformNetworkManagerXbox(); + s_pPlatformNetworkManager = new CPlatformNetworkManagerXbox(); #elif defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - s_pPlatformNetworkManager = new CPlatformNetworkManagerSony(); + s_pPlatformNetworkManager = new CPlatformNetworkManagerSony(); #elif defined _DURANGO - s_pPlatformNetworkManager = new CPlatformNetworkManagerDurango(); + s_pPlatformNetworkManager = new CPlatformNetworkManagerDurango(); #else - s_pPlatformNetworkManager = new CPlatformNetworkManagerStub(); + s_pPlatformNetworkManager = new CPlatformNetworkManagerStub(); #endif - s_pPlatformNetworkManager->Initialise( this, flagIndexSize ); - m_bNetworkThreadRunning = false; - m_bInitialised = true; + s_pPlatformNetworkManager->Initialise(this, flagIndexSize); + m_bNetworkThreadRunning = false; + m_bInitialised = true; } -void CGameNetworkManager::Terminate() -{ - if( m_bInitialised ) - { - s_pPlatformNetworkManager->Terminate(); - } +void CGameNetworkManager::Terminate() { + if (m_bInitialised) { + s_pPlatformNetworkManager->Terminate(); + } } -void CGameNetworkManager::DoWork() -{ +void CGameNetworkManager::DoWork() { #ifdef _XBOX - // did we get any notifications from the game listener? - if(app.GetNotifications()->size()!=0) - { - PNOTIFICATION pNotification=app.GetNotifications()->back(); + // did we get any notifications from the game listener? + if (app.GetNotifications()->size() != 0) { + PNOTIFICATION pNotification = app.GetNotifications()->back(); - switch(pNotification->dwNotification) - { - case XN_LIVE_LINK_STATE_CHANGED: - { - int iPrimaryPlayer = g_NetworkManager.GetPrimaryPad(); - bool bConnected = (pNotification->uiParam!=0)?true:false; - if((g_NetworkManager.GetLockedProfile()!=-1) && iPrimaryPlayer!=-1 && bConnected == false && g_NetworkManager.IsInSession() ) - { - app.SetAction(iPrimaryPlayer,eAppAction_EthernetDisconnected); - } - } - break; - case XN_LIVE_INVITE_ACCEPTED: - s_pPlatformNetworkManager->Notify(pNotification->dwNotification,pNotification->uiParam); - break; - } + switch (pNotification->dwNotification) { + case XN_LIVE_LINK_STATE_CHANGED: { + int iPrimaryPlayer = g_NetworkManager.GetPrimaryPad(); + bool bConnected = (pNotification->uiParam != 0) ? true : false; + if ((g_NetworkManager.GetLockedProfile() != -1) && + iPrimaryPlayer != -1 && bConnected == false && + g_NetworkManager.IsInSession()) { + app.SetAction(iPrimaryPlayer, + eAppAction_EthernetDisconnected); + } + } break; + case XN_LIVE_INVITE_ACCEPTED: + s_pPlatformNetworkManager->Notify(pNotification->dwNotification, + pNotification->uiParam); + break; + } - app.GetNotifications()->pop_back(); - delete pNotification; - } + app.GetNotifications()->pop_back(); + delete pNotification; + } #endif - s_pPlatformNetworkManager->DoWork(); + s_pPlatformNetworkManager->DoWork(); #ifdef __ORBIS__ - if (m_pUpsell != NULL && m_pUpsell->hasResponse()) - { - int iPad_invited = m_iPlayerInvited, iPad_checking = m_pUpsell->m_userIndex; + if (m_pUpsell != NULL && m_pUpsell->hasResponse()) { + int iPad_invited = m_iPlayerInvited, + iPad_checking = m_pUpsell->m_userIndex; - m_iPlayerInvited = -1; + m_iPlayerInvited = -1; - delete m_pUpsell; - m_pUpsell = NULL; + delete m_pUpsell; + m_pUpsell = NULL; - if (ProfileManager.HasPlayStationPlus(iPad_checking)) - { - this->GameInviteReceived(iPad_invited, m_pInviteInfo); + if (ProfileManager.HasPlayStationPlus(iPad_checking)) { + this->GameInviteReceived(iPad_invited, m_pInviteInfo); - // m_pInviteInfo deleted by GameInviteReceived. - m_pInviteInfo = NULL; - } - else - { - delete m_pInviteInfo; - m_pInviteInfo = NULL; - } - } + // m_pInviteInfo deleted by GameInviteReceived. + m_pInviteInfo = NULL; + } else { + delete m_pInviteInfo; + m_pInviteInfo = NULL; + } + } #endif } -bool CGameNetworkManager::_RunNetworkGame(void *lpParameter) -{ - bool success = true; +bool CGameNetworkManager::_RunNetworkGame(void* lpParameter) { + bool success = true; - bool isHost = g_NetworkManager.IsHost(); - // Start the network game - Minecraft *pMinecraft=Minecraft::GetInstance(); - success = StartNetworkGame(pMinecraft,lpParameter); + bool isHost = g_NetworkManager.IsHost(); + // Start the network game + Minecraft* pMinecraft = Minecraft::GetInstance(); + success = StartNetworkGame(pMinecraft, lpParameter); - if(!success) return false; + if (!success) return false; - if( isHost ) - { - // We do not have a lobby, so the only players in the game at this point are local ones. + if (isHost) { + // We do not have a lobby, so the only players in the game at this point + // are local ones. - success = s_pPlatformNetworkManager->_RunNetworkGame(); - if(!success) - { - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); - return true; - } - } - - if( g_NetworkManager.IsLeavingGame() ) return false; + success = s_pPlatformNetworkManager->_RunNetworkGame(); + if (!success) { + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ExitWorld, + (void*)TRUE); + return true; + } + } - app.SetGameStarted(true); + if (g_NetworkManager.IsLeavingGame()) return false; - // 4J-PB - if this is the trial game, start the trial timer - if(!ProfileManager.IsFullVersion()) - { - ui.SetTrialTimerLimitSecs(MinecraftDynamicConfigurations::GetTrialTime()); - app.SetTrialTimerStart(); - } - //app.CloseXuiScenes(ProfileManager.GetPrimaryPad()); + app.SetGameStarted(true); - return success; + // 4J-PB - if this is the trial game, start the trial timer + if (!ProfileManager.IsFullVersion()) { + ui.SetTrialTimerLimitSecs( + MinecraftDynamicConfigurations::GetTrialTime()); + app.SetTrialTimerStart(); + } + // app.CloseXuiScenes(ProfileManager.GetPrimaryPad()); + + return success; } -bool CGameNetworkManager::StartNetworkGame(Minecraft *minecraft, void *lpParameter) -{ +bool CGameNetworkManager::StartNetworkGame(Minecraft* minecraft, + void* lpParameter) { #ifdef _DURANGO - ProfileManager.SetDeferredSignoutEnabled(true); + ProfileManager.SetDeferredSignoutEnabled(true); #endif - __int64 seed = 0; - if(lpParameter != NULL) - { - NetworkGameInitData *param = (NetworkGameInitData *)lpParameter; - seed = param->seed; - - app.setLevelGenerationOptions(param->levelGen); - if(param->levelGen != NULL) - { - if(app.getLevelGenerationOptions() == NULL) - { - app.DebugPrintf("Game rule was not loaded, and seed is required. Exiting.\n"); - return false; - } - else - { - param->seed = seed = app.getLevelGenerationOptions()->getLevelSeed(); - } - } - } + __int64 seed = 0; + if (lpParameter != NULL) { + NetworkGameInitData* param = (NetworkGameInitData*)lpParameter; + seed = param->seed; - static __int64 sseed = seed; // Create static version so this will be valid until next call to this function & whilst thread is running + app.setLevelGenerationOptions(param->levelGen); + if (param->levelGen != NULL) { + if (app.getLevelGenerationOptions() == NULL) { + app.DebugPrintf( + "Game rule was not loaded, and seed is required. " + "Exiting.\n"); + return false; + } else { + param->seed = seed = + app.getLevelGenerationOptions()->getLevelSeed(); + } + } + } - ServerStoppedCreate(false); - if( g_NetworkManager.IsHost() ) - { - ServerStoppedCreate(true); - ServerReadyCreate(true); - // Ready to go - create actual networking thread & start hosting - C4JThread* thread = new C4JThread(&CGameNetworkManager::ServerThreadProc, lpParameter, "Server", 256 * 1024); + static __int64 sseed = + seed; // Create static version so this will be valid until next call to + // this function & whilst thread is running + + ServerStoppedCreate(false); + if (g_NetworkManager.IsHost()) { + ServerStoppedCreate(true); + ServerReadyCreate(true); + // Ready to go - create actual networking thread & start hosting + C4JThread* thread = + new C4JThread(&CGameNetworkManager::ServerThreadProc, lpParameter, + "Server", 256 * 1024); #if defined __PS3__ || defined __PSVITA__ - thread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); -#endif //__PS3__ + thread->SetPriority(THREAD_PRIORITY_BELOW_NORMAL); +#endif //__PS3__ - thread->SetProcessor(CPU_CORE_SERVER); - thread->Run(); + thread->SetProcessor(CPU_CORE_SERVER); + thread->Run(); - app.DebugPrintf("[NET] Waiting for server ready...\n"); - ServerReadyWait(); - ServerReadyDestroy(); - app.DebugPrintf("[NET] Server ready! serverHalted=%d\n", MinecraftServer::serverHalted()); + app.DebugPrintf("[NET] Waiting for server ready...\n"); + ServerReadyWait(); + ServerReadyDestroy(); + app.DebugPrintf("[NET] Server ready! serverHalted=%d\n", + MinecraftServer::serverHalted()); - if( MinecraftServer::serverHalted() ) - return false; + if (MinecraftServer::serverHalted()) return false; -// printf("Server ready to go!\n"); - } - else - { - Socket::Initialise(NULL); - } + // printf("Server ready to go!\n"); + } else { + Socket::Initialise(NULL); + } #ifndef _XBOX - Minecraft *pMinecraft = Minecraft::GetInstance(); - app.DebugPrintf("[NET] IsReadyToPlayOrIdle=%d IsInSession=%d\n", IsReadyToPlayOrIdle(), IsInSession()); - // Make sure that we have transitioned through any joining/creating stages and are actually playing the game, so that we know the players should be valid - bool changedMessage = false; - while(!IsReadyToPlayOrIdle()) - { - changedMessage = true; - pMinecraft->progressRenderer->progressStage( g_NetworkManager.CorrectErrorIDS(IDS_PROGRESS_SAVING_TO_DISC) ); // "Finalizing..." vaguest message I could find - pMinecraft->progressRenderer->progressStagePercentage( g_NetworkManager.GetJoiningReadyPercentage() ); - Sleep(10); - } - if( changedMessage ) - { - pMinecraft->progressRenderer->progressStagePercentage( 100 ); - } + Minecraft* pMinecraft = Minecraft::GetInstance(); + app.DebugPrintf("[NET] IsReadyToPlayOrIdle=%d IsInSession=%d\n", + IsReadyToPlayOrIdle(), IsInSession()); + // Make sure that we have transitioned through any joining/creating stages + // and are actually playing the game, so that we know the players should be + // valid + bool changedMessage = false; + while (!IsReadyToPlayOrIdle()) { + changedMessage = true; + pMinecraft->progressRenderer->progressStage( + g_NetworkManager.CorrectErrorIDS( + IDS_PROGRESS_SAVING_TO_DISC)); // "Finalizing..." vaguest + // message I could find + pMinecraft->progressRenderer->progressStagePercentage( + g_NetworkManager.GetJoiningReadyPercentage()); + Sleep(10); + } + if (changedMessage) { + pMinecraft->progressRenderer->progressStagePercentage(100); + } #endif - // If we aren't in session, then something bad must have happened - we aren't joining, creating or ready play - app.DebugPrintf("[NET] Checking IsInSession...=%d\n", IsInSession()); - if(!IsInSession() ) - { - app.DebugPrintf("[NET] NOT in session! Halting server.\n"); - MinecraftServer::HaltServer(); - return false; - } + // If we aren't in session, then something bad must have happened - we + // aren't joining, creating or ready play + app.DebugPrintf("[NET] Checking IsInSession...=%d\n", IsInSession()); + if (!IsInSession()) { + app.DebugPrintf("[NET] NOT in session! Halting server.\n"); + MinecraftServer::HaltServer(); + return false; + } - app.DebugPrintf("[NET] DLC check: completed=%d pending=%d\n", app.DLCInstallProcessCompleted(), app.DLCInstallPending()); - // 4J Stu - Wait a while to make sure that DLC is loaded. This is the last point before the network communication starts - // so the latest we can check this - while( !app.DLCInstallProcessCompleted() && app.DLCInstallPending() && !g_NetworkManager.IsLeavingGame() ) - { - Sleep( 10 ); - } - if( g_NetworkManager.IsLeavingGame() ) - { - MinecraftServer::HaltServer(); - return false; - } + app.DebugPrintf("[NET] DLC check: completed=%d pending=%d\n", + app.DLCInstallProcessCompleted(), app.DLCInstallPending()); + // 4J Stu - Wait a while to make sure that DLC is loaded. This is the last + // point before the network communication starts so the latest we can check + // this + while (!app.DLCInstallProcessCompleted() && app.DLCInstallPending() && + !g_NetworkManager.IsLeavingGame()) { + Sleep(10); + } + if (g_NetworkManager.IsLeavingGame()) { + MinecraftServer::HaltServer(); + return false; + } - // PRIMARY PLAYER + // PRIMARY PLAYER - app.DebugPrintf("[NET] Creating ClientConnection (IsHost=%d)...\n", g_NetworkManager.IsHost()); - std::vector createdConnections; - ClientConnection *connection; + app.DebugPrintf("[NET] Creating ClientConnection (IsHost=%d)...\n", + g_NetworkManager.IsHost()); + std::vector createdConnections; + ClientConnection* connection; - if( g_NetworkManager.IsHost() ) - { - connection = new ClientConnection(minecraft, NULL); - app.DebugPrintf("[NET] ClientConnection created, createdOk=%d\n", connection->createdOk); - } - else - { - INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(ProfileManager.GetLockedProfile()); - if(pNetworkPlayer == NULL) - { - MinecraftServer::HaltServer(); - app.DebugPrintf("%d\n",ProfileManager.GetLockedProfile()); - // If the player is NULL here then something went wrong in the session setup, and continuing will end up in a crash - return false; - } + if (g_NetworkManager.IsHost()) { + connection = new ClientConnection(minecraft, NULL); + app.DebugPrintf("[NET] ClientConnection created, createdOk=%d\n", + connection->createdOk); + } else { + INetworkPlayer* pNetworkPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex( + ProfileManager.GetLockedProfile()); + if (pNetworkPlayer == NULL) { + MinecraftServer::HaltServer(); + app.DebugPrintf("%d\n", ProfileManager.GetLockedProfile()); + // If the player is NULL here then something went wrong in the + // session setup, and continuing will end up in a crash + return false; + } - Socket *socket = pNetworkPlayer->GetSocket(); + Socket* socket = pNetworkPlayer->GetSocket(); - // Fix for #13259 - CRASH: Gameplay: loading process is halted when player loads saved data - if(socket == NULL) - { - assert(false); - MinecraftServer::HaltServer(); - // If the socket is NULL here then something went wrong in the session setup, and continuing will end up in a crash - return false; - } + // Fix for #13259 - CRASH: Gameplay: loading process is halted when + // player loads saved data + if (socket == NULL) { + assert(false); + MinecraftServer::HaltServer(); + // If the socket is NULL here then something went wrong in the + // session setup, and continuing will end up in a crash + return false; + } - connection = new ClientConnection(minecraft, socket); - } + connection = new ClientConnection(minecraft, socket); + } - if( !connection->createdOk ) - { - assert(false); - delete connection; - connection = NULL; - MinecraftServer::HaltServer(); - return false; - } + if (!connection->createdOk) { + assert(false); + delete connection; + connection = NULL; + MinecraftServer::HaltServer(); + return false; + } - app.DebugPrintf("[NET] Sending PreLoginPacket...\n"); - connection->send( std::shared_ptr( new PreLoginPacket(minecraft->user->name) ) ); - app.DebugPrintf("[NET] PreLoginPacket sent. Entering connection tick loop...\n"); + app.DebugPrintf("[NET] Sending PreLoginPacket...\n"); + connection->send(std::shared_ptr( + new PreLoginPacket(minecraft->user->name))); + app.DebugPrintf( + "[NET] PreLoginPacket sent. Entering connection tick loop...\n"); - // Tick connection until we're ready to go. The stages involved in this are: - // (1) Creating the ClientConnection sends a prelogin packet to the server - // (2) the server sends a prelogin back, which is handled by the clientConnection, and returns a login packet - // (3) the server sends a login back, which is handled by the client connection to start the game - if( !g_NetworkManager.IsHost() ) - { - Minecraft::GetInstance()->progressRenderer->progressStart(IDS_PROGRESS_CONNECTING); - } - else - { - // 4J Stu - Host needs to generate a unique multiplayer id for sentient telemetry reporting - int multiplayerInstanceId = TelemetryManager->GenerateMultiplayerInstanceId(); - TelemetryManager->SetMultiplayerInstanceId(multiplayerInstanceId); - } - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - do - { - app.DebugPrintf("ticking connection A\n"); - connection->tick(); + // Tick connection until we're ready to go. The stages involved in this are: + // (1) Creating the ClientConnection sends a prelogin packet to the server + // (2) the server sends a prelogin back, which is handled by the + // clientConnection, and returns a login packet (3) the server sends a login + // back, which is handled by the client connection to start the game + if (!g_NetworkManager.IsHost()) { + Minecraft::GetInstance()->progressRenderer->progressStart( + IDS_PROGRESS_CONNECTING); + } else { + // 4J Stu - Host needs to generate a unique multiplayer id for sentient + // telemetry reporting + int multiplayerInstanceId = + TelemetryManager->GenerateMultiplayerInstanceId(); + TelemetryManager->SetMultiplayerInstanceId(multiplayerInstanceId); + } + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + do { + app.DebugPrintf("ticking connection A\n"); + connection->tick(); - // 4J Stu - We were ticking this way too fast which could cause the connection to time out - // The connections should tick at 20 per second - Sleep(50); - } while ( (IsInSession() && !connection->isStarted() && !connection->isClosed() && !g_NetworkManager.IsLeavingGame()) || tPack->isLoadingData() || (Minecraft::GetInstance()->skins->needsUIUpdate() || ui.IsReloadingSkin()) ); - ui.CleanUpSkinReload(); + // 4J Stu - We were ticking this way too fast which could cause the + // connection to time out The connections should tick at 20 per second + Sleep(50); + } while ((IsInSession() && !connection->isStarted() && + !connection->isClosed() && !g_NetworkManager.IsLeavingGame()) || + tPack->isLoadingData() || + (Minecraft::GetInstance()->skins->needsUIUpdate() || + ui.IsReloadingSkin())); + ui.CleanUpSkinReload(); - // 4J Stu - Fix for #11279 - CRASH: TCR 001: BAS Game Stability: Signing out of game will cause title to crash - // We need to break out of the above loop if m_bLeavingGame is set, and close the connection - if( g_NetworkManager.IsLeavingGame() || !IsInSession() ) - { - connection->close(); - } + // 4J Stu - Fix for #11279 - CRASH: TCR 001: BAS Game Stability: Signing out + // of game will cause title to crash We need to break out of the above loop + // if m_bLeavingGame is set, and close the connection + if (g_NetworkManager.IsLeavingGame() || !IsInSession()) { + connection->close(); + } - if( connection->isStarted() && !connection->isClosed() ) - { - createdConnections.push_back( connection ); + if (connection->isStarted() && !connection->isClosed()) { + createdConnections.push_back(connection); - int primaryPad = ProfileManager.GetPrimaryPad(); - app.SetRichPresenceContext(primaryPad,CONTEXT_GAME_STATE_BLANK); - if (GetPlayerCount() > 1) // Are we offline or online, and how many players are there - { - if (IsLocalGame()) ProfileManager.SetCurrentGameActivity(primaryPad,CONTEXT_PRESENCE_MULTIPLAYEROFFLINE,false); - else ProfileManager.SetCurrentGameActivity(primaryPad,CONTEXT_PRESENCE_MULTIPLAYER,false); - } - else - { - if(IsLocalGame()) ProfileManager.SetCurrentGameActivity(primaryPad,CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE,false); - else ProfileManager.SetCurrentGameActivity(primaryPad,CONTEXT_PRESENCE_MULTIPLAYER_1P,false); - } + int primaryPad = ProfileManager.GetPrimaryPad(); + app.SetRichPresenceContext(primaryPad, CONTEXT_GAME_STATE_BLANK); + if (GetPlayerCount() > + 1) // Are we offline or online, and how many players are there + { + if (IsLocalGame()) + ProfileManager.SetCurrentGameActivity( + primaryPad, CONTEXT_PRESENCE_MULTIPLAYEROFFLINE, false); + else + ProfileManager.SetCurrentGameActivity( + primaryPad, CONTEXT_PRESENCE_MULTIPLAYER, false); + } else { + if (IsLocalGame()) + ProfileManager.SetCurrentGameActivity( + primaryPad, CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE, false); + else + ProfileManager.SetCurrentGameActivity( + primaryPad, CONTEXT_PRESENCE_MULTIPLAYER_1P, false); + } + // ALL OTHER LOCAL PLAYERS + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + // Already have setup the primary pad + if (idx == ProfileManager.GetPrimaryPad()) continue; - // ALL OTHER LOCAL PLAYERS - for(int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - // Already have setup the primary pad - if(idx == ProfileManager.GetPrimaryPad() ) continue; + if (GetLocalPlayerByUserIndex(idx) != NULL && + !ProfileManager.IsSignedIn(idx)) { + INetworkPlayer* pNetworkPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(idx); + Socket* socket = pNetworkPlayer->GetSocket(); + app.DebugPrintf( + "Closing socket due to player %d not being signed in any " + "more\n"); + if (!socket->close(false)) socket->close(true); - if( GetLocalPlayerByUserIndex(idx) != NULL && !ProfileManager.IsSignedIn(idx) ) - { - INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(idx); - Socket *socket = pNetworkPlayer->GetSocket(); - app.DebugPrintf("Closing socket due to player %d not being signed in any more\n"); - if( !socket->close(false) ) socket->close(true); + continue; + } - continue; - } + // By default when we host we only have the local player, but + // currently allow multiple local players to join when joining any + // other way, so just because they are signed in doesn't mean they + // are in the session 4J Stu - If they are in the session, then we + // should add them to the game. Otherwise we won't be able to add + // them later + INetworkPlayer* pNetworkPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(idx); + if (pNetworkPlayer == NULL) continue; - // By default when we host we only have the local player, but currently allow multiple local players to join - // when joining any other way, so just because they are signed in doesn't mean they are in the session - // 4J Stu - If they are in the session, then we should add them to the game. Otherwise we won't be able to add them later - INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(idx); - if( pNetworkPlayer == NULL ) - continue; + ClientConnection* connection; - ClientConnection *connection; + Socket* socket = pNetworkPlayer->GetSocket(); + connection = new ClientConnection(minecraft, socket, idx); - Socket *socket = pNetworkPlayer->GetSocket(); - connection = new ClientConnection(minecraft, socket, idx); + minecraft->addPendingLocalConnection(idx, connection); + // minecraft->createExtraLocalPlayer(idx, (convStringToWstring( + // ProfileManager.GetGamertag(idx) )).c_str(), idx, connection); - minecraft->addPendingLocalConnection(idx, connection); - //minecraft->createExtraLocalPlayer(idx, (convStringToWstring( ProfileManager.GetGamertag(idx) )).c_str(), idx, connection); + // Open the socket on the server end to accept incoming data + Socket::addIncomingSocket(socket); - // Open the socket on the server end to accept incoming data - Socket::addIncomingSocket(socket); + connection->send(std::shared_ptr(new PreLoginPacket( + convStringToWstring(ProfileManager.GetGamertag(idx))))); - connection->send( std::shared_ptr( new PreLoginPacket(convStringToWstring( ProfileManager.GetGamertag(idx) )) ) ); + createdConnections.push_back(connection); - createdConnections.push_back( connection ); + // Tick connection until we're ready to go. The stages involved in + // this are: (1) Creating the ClientConnection sends a prelogin + // packet to the server (2) the server sends a prelogin back, which + // is handled by the clientConnection, and returns a login packet + // (3) the server sends a login back, which is handled by the client + // connection to start the game + do { + // We need to keep ticking the connections for players that + // already logged in + for (AUTO_VAR(it, createdConnections.begin()); + it < createdConnections.end(); ++it) { + (*it)->tick(); + } - // Tick connection until we're ready to go. The stages involved in this are: - // (1) Creating the ClientConnection sends a prelogin packet to the server - // (2) the server sends a prelogin back, which is handled by the clientConnection, and returns a login packet - // (3) the server sends a login back, which is handled by the client connection to start the game - do - { - // We need to keep ticking the connections for players that already logged in - for(AUTO_VAR(it, createdConnections.begin()); it < createdConnections.end(); ++it) - { - (*it)->tick(); - } - - // 4J Stu - We were ticking this way too fast which could cause the connection to time out - // The connections should tick at 20 per second - Sleep(50); - app.DebugPrintf("<***> %d %d %d %d %d\n",IsInSession(), !connection->isStarted(),!connection->isClosed(),ProfileManager.IsSignedIn(idx),!g_NetworkManager.IsLeavingGame()); + // 4J Stu - We were ticking this way too fast which could cause + // the connection to time out The connections should tick at 20 + // per second + Sleep(50); + app.DebugPrintf("<***> %d %d %d %d %d\n", IsInSession(), + !connection->isStarted(), + !connection->isClosed(), + ProfileManager.IsSignedIn(idx), + !g_NetworkManager.IsLeavingGame()); #if defined _XBOX || __PS3__ - } while (IsInSession() && !connection->isStarted() && !connection->isClosed() && ProfileManager.IsSignedIn(idx) && !g_NetworkManager.IsLeavingGame() ); + } while (IsInSession() && !connection->isStarted() && + !connection->isClosed() && + ProfileManager.IsSignedIn(idx) && + !g_NetworkManager.IsLeavingGame()); #else - // TODO - This SHOULD be something just like the code above but temporarily changing here so that we don't have to depend on the profilemanager behaviour - } while (IsInSession() && !connection->isStarted() && !connection->isClosed() && !g_NetworkManager.IsLeavingGame() ); + // TODO - This SHOULD be something just like the code above but + // temporarily changing here so that we don't have to depend on + // the profilemanager behaviour + } while (IsInSession() && !connection->isStarted() && + !connection->isClosed() && + !g_NetworkManager.IsLeavingGame()); #endif - // 4J Stu - Fix for #11279 - CRASH: TCR 001: BAS Game Stability: Signing out of game will cause title to crash - // We need to break out of the above loop if m_bLeavingGame is set, and stop creating new connections - // The connections in the createdConnections vector get closed at the end of the thread - if( g_NetworkManager.IsLeavingGame() || !IsInSession() ) break; + // 4J Stu - Fix for #11279 - CRASH: TCR 001: BAS Game Stability: + // Signing out of game will cause title to crash We need to break + // out of the above loop if m_bLeavingGame is set, and stop creating + // new connections The connections in the createdConnections vector + // get closed at the end of the thread + if (g_NetworkManager.IsLeavingGame() || !IsInSession()) break; - if( ProfileManager.IsSignedIn(idx) && !connection->isClosed() ) - { - app.SetRichPresenceContext(idx,CONTEXT_GAME_STATE_BLANK); - if (IsLocalGame()) ProfileManager.SetCurrentGameActivity(idx,CONTEXT_PRESENCE_MULTIPLAYEROFFLINE,false); - else ProfileManager.SetCurrentGameActivity(idx,CONTEXT_PRESENCE_MULTIPLAYER,false); - } - else - { - connection->close(); - AUTO_VAR(it, find( createdConnections.begin(), createdConnections.end(), connection )); - if(it != createdConnections.end() ) createdConnections.erase( it ); - } - } + if (ProfileManager.IsSignedIn(idx) && !connection->isClosed()) { + app.SetRichPresenceContext(idx, CONTEXT_GAME_STATE_BLANK); + if (IsLocalGame()) + ProfileManager.SetCurrentGameActivity( + idx, CONTEXT_PRESENCE_MULTIPLAYEROFFLINE, false); + else + ProfileManager.SetCurrentGameActivity( + idx, CONTEXT_PRESENCE_MULTIPLAYER, false); + } else { + connection->close(); + AUTO_VAR(it, find(createdConnections.begin(), + createdConnections.end(), connection)); + if (it != createdConnections.end()) + createdConnections.erase(it); + } + } - app.SetGameMode( eMode_Multiplayer ); - } - else if ( connection->isClosed() || !IsInSession()) - { -// assert(false); - MinecraftServer::HaltServer(); - return false; - } + app.SetGameMode(eMode_Multiplayer); + } else if (connection->isClosed() || !IsInSession()) { + // assert(false); + MinecraftServer::HaltServer(); + return false; + } - - if(g_NetworkManager.IsLeavingGame() || !IsInSession() ) - { - for(AUTO_VAR(it, createdConnections.begin()); it < createdConnections.end(); ++it) - { - (*it)->close(); - } -// assert(false); - MinecraftServer::HaltServer(); - return false; - } + if (g_NetworkManager.IsLeavingGame() || !IsInSession()) { + for (AUTO_VAR(it, createdConnections.begin()); + it < createdConnections.end(); ++it) { + (*it)->close(); + } + // assert(false); + MinecraftServer::HaltServer(); + return false; + } - // Catch in-case server has been halted (by a player signout). - if ( MinecraftServer::serverHalted() ) - return false; + // Catch in-case server has been halted (by a player signout). + if (MinecraftServer::serverHalted()) return false; - return true; + return true; } -int CGameNetworkManager::CorrectErrorIDS(int IDS) -{ - return s_pPlatformNetworkManager->CorrectErrorIDS(IDS); +int CGameNetworkManager::CorrectErrorIDS(int IDS) { + return s_pPlatformNetworkManager->CorrectErrorIDS(IDS); } -int CGameNetworkManager::GetLocalPlayerMask(int playerIndex) -{ - return s_pPlatformNetworkManager->GetLocalPlayerMask( playerIndex ); +int CGameNetworkManager::GetLocalPlayerMask(int playerIndex) { + return s_pPlatformNetworkManager->GetLocalPlayerMask(playerIndex); } -int CGameNetworkManager::GetPlayerCount() -{ - return s_pPlatformNetworkManager->GetPlayerCount(); +int CGameNetworkManager::GetPlayerCount() { + return s_pPlatformNetworkManager->GetPlayerCount(); } -int CGameNetworkManager::GetOnlinePlayerCount() -{ - return s_pPlatformNetworkManager->GetOnlinePlayerCount(); +int CGameNetworkManager::GetOnlinePlayerCount() { + return s_pPlatformNetworkManager->GetOnlinePlayerCount(); } -bool CGameNetworkManager::AddLocalPlayerByUserIndex( int userIndex ) -{ - return s_pPlatformNetworkManager->AddLocalPlayerByUserIndex( userIndex ); +bool CGameNetworkManager::AddLocalPlayerByUserIndex(int userIndex) { + return s_pPlatformNetworkManager->AddLocalPlayerByUserIndex(userIndex); } -bool CGameNetworkManager::RemoveLocalPlayerByUserIndex( int userIndex ) -{ - return s_pPlatformNetworkManager->RemoveLocalPlayerByUserIndex( userIndex ); +bool CGameNetworkManager::RemoveLocalPlayerByUserIndex(int userIndex) { + return s_pPlatformNetworkManager->RemoveLocalPlayerByUserIndex(userIndex); } -INetworkPlayer *CGameNetworkManager::GetLocalPlayerByUserIndex(int userIndex ) -{ - return s_pPlatformNetworkManager->GetLocalPlayerByUserIndex( userIndex ); +INetworkPlayer* CGameNetworkManager::GetLocalPlayerByUserIndex(int userIndex) { + return s_pPlatformNetworkManager->GetLocalPlayerByUserIndex(userIndex); } -INetworkPlayer *CGameNetworkManager::GetPlayerByIndex(int playerIndex) -{ - return s_pPlatformNetworkManager->GetPlayerByIndex( playerIndex ); +INetworkPlayer* CGameNetworkManager::GetPlayerByIndex(int playerIndex) { + return s_pPlatformNetworkManager->GetPlayerByIndex(playerIndex); } -INetworkPlayer *CGameNetworkManager::GetPlayerByXuid(PlayerUID xuid) -{ - return s_pPlatformNetworkManager->GetPlayerByXuid( xuid ); +INetworkPlayer* CGameNetworkManager::GetPlayerByXuid(PlayerUID xuid) { + return s_pPlatformNetworkManager->GetPlayerByXuid(xuid); } -INetworkPlayer *CGameNetworkManager::GetPlayerBySmallId(unsigned char smallId) -{ - return s_pPlatformNetworkManager->GetPlayerBySmallId( smallId ); +INetworkPlayer* CGameNetworkManager::GetPlayerBySmallId(unsigned char smallId) { + return s_pPlatformNetworkManager->GetPlayerBySmallId(smallId); } #ifdef _DURANGO -std::wstring CGameNetworkManager::GetDisplayNameByGamertag(std::wstring gamertag) -{ - return s_pPlatformNetworkManager->GetDisplayNameByGamertag(gamertag); +std::wstring CGameNetworkManager::GetDisplayNameByGamertag( + std::wstring gamertag) { + return s_pPlatformNetworkManager->GetDisplayNameByGamertag(gamertag); } #endif -INetworkPlayer *CGameNetworkManager::GetHostPlayer() -{ - return s_pPlatformNetworkManager->GetHostPlayer(); +INetworkPlayer* CGameNetworkManager::GetHostPlayer() { + return s_pPlatformNetworkManager->GetHostPlayer(); } -void CGameNetworkManager::RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - s_pPlatformNetworkManager->RegisterPlayerChangedCallback( iPad, callback, callbackParam ); +void CGameNetworkManager::RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + s_pPlatformNetworkManager->RegisterPlayerChangedCallback(iPad, callback, + callbackParam); } -void CGameNetworkManager::UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - s_pPlatformNetworkManager->UnRegisterPlayerChangedCallback( iPad, callback, callbackParam ); +void CGameNetworkManager::UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + s_pPlatformNetworkManager->UnRegisterPlayerChangedCallback(iPad, callback, + callbackParam); } -void CGameNetworkManager::HandleSignInChange() -{ - s_pPlatformNetworkManager->HandleSignInChange(); +void CGameNetworkManager::HandleSignInChange() { + s_pPlatformNetworkManager->HandleSignInChange(); } -bool CGameNetworkManager::ShouldMessageForFullSession() -{ - return s_pPlatformNetworkManager->ShouldMessageForFullSession(); +bool CGameNetworkManager::ShouldMessageForFullSession() { + return s_pPlatformNetworkManager->ShouldMessageForFullSession(); } -bool CGameNetworkManager::IsInSession() -{ - return s_pPlatformNetworkManager->IsInSession(); +bool CGameNetworkManager::IsInSession() { + return s_pPlatformNetworkManager->IsInSession(); } -bool CGameNetworkManager::IsInGameplay() -{ - return s_pPlatformNetworkManager->IsInGameplay(); +bool CGameNetworkManager::IsInGameplay() { + return s_pPlatformNetworkManager->IsInGameplay(); } -bool CGameNetworkManager::IsReadyToPlayOrIdle() -{ - return s_pPlatformNetworkManager->IsReadyToPlayOrIdle(); +bool CGameNetworkManager::IsReadyToPlayOrIdle() { + return s_pPlatformNetworkManager->IsReadyToPlayOrIdle(); } -bool CGameNetworkManager::IsLeavingGame() -{ - return s_pPlatformNetworkManager->IsLeavingGame(); +bool CGameNetworkManager::IsLeavingGame() { + return s_pPlatformNetworkManager->IsLeavingGame(); } -bool CGameNetworkManager::SetLocalGame(bool isLocal) -{ - return s_pPlatformNetworkManager->SetLocalGame( isLocal ); +bool CGameNetworkManager::SetLocalGame(bool isLocal) { + return s_pPlatformNetworkManager->SetLocalGame(isLocal); } -bool CGameNetworkManager::IsLocalGame() -{ - return s_pPlatformNetworkManager->IsLocalGame(); +bool CGameNetworkManager::IsLocalGame() { + return s_pPlatformNetworkManager->IsLocalGame(); } -void CGameNetworkManager::SetPrivateGame(bool isPrivate) -{ - s_pPlatformNetworkManager->SetPrivateGame( isPrivate ); +void CGameNetworkManager::SetPrivateGame(bool isPrivate) { + s_pPlatformNetworkManager->SetPrivateGame(isPrivate); } -bool CGameNetworkManager::IsPrivateGame() -{ - return s_pPlatformNetworkManager->IsPrivateGame(); +bool CGameNetworkManager::IsPrivateGame() { + return s_pPlatformNetworkManager->IsPrivateGame(); } -void CGameNetworkManager::HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots, unsigned char privateSlots) -{ - // 4J Stu - clear any previous connection errors - Minecraft::GetInstance()->clearConnectionFailed(); +void CGameNetworkManager::HostGame(int localUsersMask, bool bOnlineGame, + bool bIsPrivate, unsigned char publicSlots, + unsigned char privateSlots) { + // 4J Stu - clear any previous connection errors + Minecraft::GetInstance()->clearConnectionFailed(); - s_pPlatformNetworkManager->HostGame( localUsersMask, bOnlineGame, bIsPrivate, publicSlots, privateSlots ); + s_pPlatformNetworkManager->HostGame(localUsersMask, bOnlineGame, bIsPrivate, + publicSlots, privateSlots); } -bool CGameNetworkManager::IsHost() -{ - return (s_pPlatformNetworkManager->IsHost() == TRUE); +bool CGameNetworkManager::IsHost() { + return (s_pPlatformNetworkManager->IsHost() == TRUE); } -bool CGameNetworkManager::IsInStatsEnabledSession() -{ - return s_pPlatformNetworkManager->IsInStatsEnabledSession(); +bool CGameNetworkManager::IsInStatsEnabledSession() { + return s_pPlatformNetworkManager->IsInStatsEnabledSession(); } -bool CGameNetworkManager::SessionHasSpace(unsigned int spaceRequired) -{ - return s_pPlatformNetworkManager->SessionHasSpace( spaceRequired ); +bool CGameNetworkManager::SessionHasSpace(unsigned int spaceRequired) { + return s_pPlatformNetworkManager->SessionHasSpace(spaceRequired); } -std::vector *CGameNetworkManager::GetSessionList(int iPad, int localPlayers, bool partyOnly) -{ - return s_pPlatformNetworkManager->GetSessionList( iPad, localPlayers, partyOnly ); +std::vector* CGameNetworkManager::GetSessionList( + int iPad, int localPlayers, bool partyOnly) { + return s_pPlatformNetworkManager->GetSessionList(iPad, localPlayers, + partyOnly); } -bool CGameNetworkManager::GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession) -{ - return s_pPlatformNetworkManager->GetGameSessionInfo( iPad, sessionId, foundSession ); +bool CGameNetworkManager::GetGameSessionInfo(int iPad, SessionID sessionId, + FriendSessionInfo* foundSession) { + return s_pPlatformNetworkManager->GetGameSessionInfo(iPad, sessionId, + foundSession); } -void CGameNetworkManager::SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ) -{ - s_pPlatformNetworkManager->SetSessionsUpdatedCallback( SessionsUpdatedCallback, pSearchParam ); +void CGameNetworkManager::SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam) { + s_pPlatformNetworkManager->SetSessionsUpdatedCallback( + SessionsUpdatedCallback, pSearchParam); } -void CGameNetworkManager::GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) -{ - s_pPlatformNetworkManager->GetFullFriendSessionInfo(foundSession, FriendSessionUpdatedFn, pParam); +void CGameNetworkManager::GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), void* pParam) { + s_pPlatformNetworkManager->GetFullFriendSessionInfo( + foundSession, FriendSessionUpdatedFn, pParam); } -void CGameNetworkManager::ForceFriendsSessionRefresh() -{ - s_pPlatformNetworkManager->ForceFriendsSessionRefresh(); +void CGameNetworkManager::ForceFriendsSessionRefresh() { + s_pPlatformNetworkManager->ForceFriendsSessionRefresh(); } -bool CGameNetworkManager::JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo) -{ - return s_pPlatformNetworkManager->JoinGameFromInviteInfo( userIndex, userMask, pInviteInfo ); +bool CGameNetworkManager::JoinGameFromInviteInfo( + int userIndex, int userMask, const INVITE_INFO* pInviteInfo) { + return s_pPlatformNetworkManager->JoinGameFromInviteInfo( + userIndex, userMask, pInviteInfo); } -CGameNetworkManager::eJoinGameResult CGameNetworkManager::JoinGame(FriendSessionInfo *searchResult, int localUsersMask) -{ - app.SetTutorialMode( false ); - g_NetworkManager.SetLocalGame(false); +CGameNetworkManager::eJoinGameResult CGameNetworkManager::JoinGame( + FriendSessionInfo* searchResult, int localUsersMask) { + app.SetTutorialMode(false); + g_NetworkManager.SetLocalGame(false); - int primaryUserIndex = ProfileManager.GetLockedProfile(); + int primaryUserIndex = ProfileManager.GetLockedProfile(); - // 4J-PB - clear any previous connection errors - Minecraft::GetInstance()->clearConnectionFailed(); + // 4J-PB - clear any previous connection errors + Minecraft::GetInstance()->clearConnectionFailed(); - // Make sure that the Primary Pad is in by default - localUsersMask |= GetLocalPlayerMask( ProfileManager.GetPrimaryPad() ); + // Make sure that the Primary Pad is in by default + localUsersMask |= GetLocalPlayerMask(ProfileManager.GetPrimaryPad()); - return (eJoinGameResult)(s_pPlatformNetworkManager->JoinGame( searchResult, localUsersMask, primaryUserIndex )); + return (eJoinGameResult)(s_pPlatformNetworkManager->JoinGame( + searchResult, localUsersMask, primaryUserIndex)); } -void CGameNetworkManager::CancelJoinGame(void *lpParam) -{ +void CGameNetworkManager::CancelJoinGame(void* lpParam) { #ifdef _XBOX_ONE - s_pPlatformNetworkManager->CancelJoinGame(); + s_pPlatformNetworkManager->CancelJoinGame(); #endif } -bool CGameNetworkManager::LeaveGame(bool bMigrateHost) -{ - Minecraft::GetInstance()->gui->clearMessages(); - return s_pPlatformNetworkManager->LeaveGame( bMigrateHost ); +bool CGameNetworkManager::LeaveGame(bool bMigrateHost) { + Minecraft::GetInstance()->gui->clearMessages(); + return s_pPlatformNetworkManager->LeaveGame(bMigrateHost); } -int CGameNetworkManager::JoinFromInvite_SignInReturned(void *pParam,bool bContinue, int iPad) -{ - INVITE_INFO * pInviteInfo = (INVITE_INFO *)pParam; +int CGameNetworkManager::JoinFromInvite_SignInReturned(void* pParam, + bool bContinue, + int iPad) { + INVITE_INFO* pInviteInfo = (INVITE_INFO*)pParam; - if(bContinue==true) - { + if (bContinue == true) { #ifdef __ORBIS__ - // Check if PSN is unavailable because of age restriction - int npAvailability = ProfileManager.getNPAvailability(iPad); - if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) - { - unsigned int uiIDA[1]; - uiIDA[0] = IDS_OK; - ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, iPad, NULL, NULL, app.GetStringTable()); + // Check if PSN is unavailable because of age restriction + int npAvailability = ProfileManager.getNPAvailability(iPad); + if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, + IDS_CONTENT_RESTRICTION, uiIDA, 1, iPad, NULL, + NULL, app.GetStringTable()); - return 0; - } + return 0; + } #endif - app.DebugPrintf("JoinFromInvite_SignInReturned, iPad %d\n",iPad); - // It's possible that the player has not signed in - they can back out - if(ProfileManager.IsSignedIn(iPad) && ProfileManager.IsSignedInLive(iPad) ) - { - app.DebugPrintf("JoinFromInvite_SignInReturned, passed sign-in tests\n"); - int localUsersMask = 0; - int joiningUsers = 0; + app.DebugPrintf("JoinFromInvite_SignInReturned, iPad %d\n", iPad); + // It's possible that the player has not signed in - they can back out + if (ProfileManager.IsSignedIn(iPad) && + ProfileManager.IsSignedInLive(iPad)) { + app.DebugPrintf( + "JoinFromInvite_SignInReturned, passed sign-in tests\n"); + int localUsersMask = 0; + int joiningUsers = 0; - bool noPrivileges = false; - for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) - { - if(ProfileManager.IsSignedIn(index) ) - { - ++joiningUsers; - if( !ProfileManager.AllowedToPlayMultiplayer(index) ) noPrivileges = true; - localUsersMask |= GetLocalPlayerMask( index ); - } - } + bool noPrivileges = false; + for (unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { + if (ProfileManager.IsSignedIn(index)) { + ++joiningUsers; + if (!ProfileManager.AllowedToPlayMultiplayer(index)) + noPrivileges = true; + localUsersMask |= GetLocalPlayerMask(index); + } + } - // Check if user-created content is allowed, as we cannot play multiplayer if it's not - bool noUGC = false; + // Check if user-created content is allowed, as we cannot play + // multiplayer if it's not + bool noUGC = false; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(iPad,false,&noUGC,NULL,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad, false, &noUGC, + NULL, NULL); #elif defined(__ORBIS__) - ProfileManager.GetChatAndContentRestrictions(iPad,false,NULL,&noUGC,NULL); + ProfileManager.GetChatAndContentRestrictions(iPad, false, NULL, + &noUGC, NULL); #endif - if(noUGC) - { - int messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL; - if(joiningUsers > 1) messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL; + if (noUGC) { + int messageText = + IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL; + if (joiningUsers > 1) + messageText = + IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL; - ui.RequestUGCMessageBox(IDS_CONNECTION_FAILED, messageText); - } - else if(noPrivileges) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); - } - else - { + ui.RequestUGCMessageBox(IDS_CONNECTION_FAILED, messageText); + } else if (noPrivileges) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, ProfileManager.GetPrimaryPad(), + NULL, NULL, app.GetStringTable()); + } else { #if defined(__ORBIS__) || defined(__PSVITA__) - bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(iPad,false,&chatRestricted,NULL,NULL); - if(chatRestricted) - { - ProfileManager.DisplaySystemMessage( 0, ProfileManager.GetPrimaryPad() ); - } + bool chatRestricted = false; + ProfileManager.GetChatAndContentRestrictions( + iPad, false, &chatRestricted, NULL, NULL); + if (chatRestricted) { + ProfileManager.DisplaySystemMessage( + 0, ProfileManager.GetPrimaryPad()); + } #endif - ProfileManager.SetLockedProfile(iPad); - ProfileManager.SetPrimaryPad(iPad); + ProfileManager.SetLockedProfile(iPad); + ProfileManager.SetPrimaryPad(iPad); - g_NetworkManager.SetLocalGame(false); - - // If the player was signed in before selecting play, we'll not have read the profile yet, so query the sign-in status to get this to happen - ProfileManager.QuerySigninStatus(); + g_NetworkManager.SetLocalGame(false); - // 4J-PB - clear any previous connection errors - Minecraft::GetInstance()->clearConnectionFailed(); + // If the player was signed in before selecting play, we'll not + // have read the profile yet, so query the sign-in status to get + // this to happen + ProfileManager.QuerySigninStatus(); - // change the minecraft player name - Minecraft::GetInstance()->user->name = convStringToWstring( ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); + // 4J-PB - clear any previous connection errors + Minecraft::GetInstance()->clearConnectionFailed(); - bool success = g_NetworkManager.JoinGameFromInviteInfo( - iPad, // dwUserIndex - localUsersMask, // dwUserMask - pInviteInfo ); // pInviteInfo - if( !success ) - { - app.DebugPrintf( "Failed joining game from invite\n" ); - } - } - } - else - { - app.DebugPrintf("JoinFromInvite_SignInReturned, failed sign-in tests :%d %d\n",ProfileManager.IsSignedIn(iPad),ProfileManager.IsSignedInLive(iPad)); - } - } - return 0; + // change the minecraft player name + Minecraft::GetInstance()->user->name = convStringToWstring( + ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); + bool success = g_NetworkManager.JoinGameFromInviteInfo( + iPad, // dwUserIndex + localUsersMask, // dwUserMask + pInviteInfo); // pInviteInfo + if (!success) { + app.DebugPrintf("Failed joining game from invite\n"); + } + } + } else { + app.DebugPrintf( + "JoinFromInvite_SignInReturned, failed sign-in tests :%d %d\n", + ProfileManager.IsSignedIn(iPad), + ProfileManager.IsSignedInLive(iPad)); + } + } + return 0; } -void CGameNetworkManager::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); - TexturePack *tPack = pMinecraft->skins->getSelected(); - s_pPlatformNetworkManager->SetSessionTexturePackParentId( tPack->getDLCParentPackId() ); - s_pPlatformNetworkManager->SetSessionSubTexturePackId( tPack->getDLCSubPackId() ); +void CGameNetworkManager::UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving) { + Minecraft* pMinecraft = Minecraft::GetInstance(); + TexturePack* tPack = pMinecraft->skins->getSelected(); + s_pPlatformNetworkManager->SetSessionTexturePackParentId( + tPack->getDLCParentPackId()); + s_pPlatformNetworkManager->SetSessionSubTexturePackId( + tPack->getDLCSubPackId()); - s_pPlatformNetworkManager->UpdateAndSetGameSessionData( pNetworkPlayerLeaving ); + s_pPlatformNetworkManager->UpdateAndSetGameSessionData( + pNetworkPlayerLeaving); } -void CGameNetworkManager::SendInviteGUI(int quadrant) -{ - s_pPlatformNetworkManager->SendInviteGUI(quadrant); +void CGameNetworkManager::SendInviteGUI(int quadrant) { + s_pPlatformNetworkManager->SendInviteGUI(quadrant); } -void CGameNetworkManager::ResetLeavingGame() -{ - s_pPlatformNetworkManager->ResetLeavingGame(); +void CGameNetworkManager::ResetLeavingGame() { + s_pPlatformNetworkManager->ResetLeavingGame(); } -bool CGameNetworkManager::IsNetworkThreadRunning() -{ - return m_bNetworkThreadRunning;; +bool CGameNetworkManager::IsNetworkThreadRunning() { + return m_bNetworkThreadRunning; + ; } -int CGameNetworkManager::RunNetworkGameThreadProc( void* lpParameter ) -{ - // Share AABB & Vec3 pools with default (main thread) - should be ok as long as we don't tick the main thread whilst this thread is running - AABB::UseDefaultThreadStorage(); - Vec3::UseDefaultThreadStorage(); - Compression::UseDefaultThreadStorage(); - Tile::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - - g_NetworkManager.m_bNetworkThreadRunning = true; - bool success = g_NetworkManager._RunNetworkGame(lpParameter); - g_NetworkManager.m_bNetworkThreadRunning = false; - if( !success) - { - TexturePack *tPack = Minecraft::GetInstance()->skins->getSelected(); - while ( tPack->isLoadingData() || (Minecraft::GetInstance()->skins->needsUIUpdate() || ui.IsReloadingSkin()) ) - { - Sleep(1); - } - ui.CleanUpSkinReload(); - if(app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) - { - app.SetDisconnectReason( DisconnectPacket::eDisconnect_ConnectionCreationFailed ); - } - // If we failed before the server started, clear the game rules. Otherwise the server will clear it up. - if(MinecraftServer::getInstance() == NULL) app.m_gameRules.unloadCurrentGameRules(); - Tile::ReleaseThreadStorage(); - return -1; - } +int CGameNetworkManager::RunNetworkGameThreadProc(void* lpParameter) { + // Share AABB & Vec3 pools with default (main thread) - should be ok as long + // as we don't tick the main thread whilst this thread is running + AABB::UseDefaultThreadStorage(); + Vec3::UseDefaultThreadStorage(); + Compression::UseDefaultThreadStorage(); + Tile::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + + g_NetworkManager.m_bNetworkThreadRunning = true; + bool success = g_NetworkManager._RunNetworkGame(lpParameter); + g_NetworkManager.m_bNetworkThreadRunning = false; + if (!success) { + TexturePack* tPack = Minecraft::GetInstance()->skins->getSelected(); + while (tPack->isLoadingData() || + (Minecraft::GetInstance()->skins->needsUIUpdate() || + ui.IsReloadingSkin())) { + Sleep(1); + } + ui.CleanUpSkinReload(); + if (app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) { + app.SetDisconnectReason( + DisconnectPacket::eDisconnect_ConnectionCreationFailed); + } + // If we failed before the server started, clear the game rules. + // Otherwise the server will clear it up. + if (MinecraftServer::getInstance() == NULL) + app.m_gameRules.unloadCurrentGameRules(); + Tile::ReleaseThreadStorage(); + return -1; + } #ifdef __PSVITA__ - // 4J-JEV: Wait for the loading/saving to finish. - while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) Sleep(10); + // 4J-JEV: Wait for the loading/saving to finish. + while (StorageManager.GetSaveState() != C4JStorage::ESaveGame_Idle) + Sleep(10); #endif - Tile::ReleaseThreadStorage(); - IntCache::ReleaseThreadStorage(); - return 0; + Tile::ReleaseThreadStorage(); + IntCache::ReleaseThreadStorage(); + return 0; } -int CGameNetworkManager::ServerThreadProc( void* lpParameter ) -{ - __int64 seed = 0; - if(lpParameter != NULL) - { - NetworkGameInitData *param = (NetworkGameInitData *)lpParameter; - seed = param->seed; - app.SetGameHostOption(eGameHostOption_All,param->settings); - } +int CGameNetworkManager::ServerThreadProc(void* lpParameter) { + __int64 seed = 0; + if (lpParameter != NULL) { + NetworkGameInitData* param = (NetworkGameInitData*)lpParameter; + seed = param->seed; + app.SetGameHostOption(eGameHostOption_All, param->settings); + } - SetThreadName(-1, "Minecraft Server thread"); - AABB::CreateNewThreadStorage(); - Vec3::CreateNewThreadStorage(); - IntCache::CreateNewThreadStorage(); - Compression::UseDefaultThreadStorage(); - OldChunkStorage::UseDefaultThreadStorage(); - Entity::useSmallIds(); - Level::enableLightingCache(); - Tile::CreateNewThreadStorage(); + SetThreadName(-1, "Minecraft Server thread"); + AABB::CreateNewThreadStorage(); + Vec3::CreateNewThreadStorage(); + IntCache::CreateNewThreadStorage(); + Compression::UseDefaultThreadStorage(); + OldChunkStorage::UseDefaultThreadStorage(); + Entity::useSmallIds(); + Level::enableLightingCache(); + Tile::CreateNewThreadStorage(); - MinecraftServer::main(seed, lpParameter); //saveData, app.GetGameHostOption(eGameHostOption_All)); - - Tile::ReleaseThreadStorage(); - AABB::ReleaseThreadStorage(); - Vec3::ReleaseThreadStorage(); - IntCache::ReleaseThreadStorage(); - Level::destroyLightingCache(); + MinecraftServer::main( + seed, + lpParameter); // saveData, app.GetGameHostOption(eGameHostOption_All)); - if(lpParameter != NULL) delete (NetworkGameInitData*)lpParameter; + Tile::ReleaseThreadStorage(); + AABB::ReleaseThreadStorage(); + Vec3::ReleaseThreadStorage(); + IntCache::ReleaseThreadStorage(); + Level::destroyLightingCache(); - return 0; + if (lpParameter != NULL) delete (NetworkGameInitData*)lpParameter; + + return 0; } -int CGameNetworkManager::ExitAndJoinFromInviteThreadProc( void* lpParam ) -{ - // Share AABB & Vec3 pools with default (main thread) - should be ok as long as we don't tick the main thread whilst this thread is running - AABB::UseDefaultThreadStorage(); - Vec3::UseDefaultThreadStorage(); - Compression::UseDefaultThreadStorage(); +int CGameNetworkManager::ExitAndJoinFromInviteThreadProc(void* lpParam) { + // Share AABB & Vec3 pools with default (main thread) - should be ok as long + // as we don't tick the main thread whilst this thread is running + AABB::UseDefaultThreadStorage(); + Vec3::UseDefaultThreadStorage(); + Compression::UseDefaultThreadStorage(); - //app.SetGameStarted(false); + // app.SetGameStarted(false); #ifndef __PSVITA__ - UIScene_PauseMenu::_ExitWorld(NULL); + UIScene_PauseMenu::_ExitWorld(NULL); #endif - while( g_NetworkManager.IsInSession() ) - { - Sleep(1); - } + while (g_NetworkManager.IsInSession()) { + Sleep(1); + } - // Xbox should always be online when receiving invites - on PS3 we need to check & ask the user to sign in + // Xbox should always be online when receiving invites - on PS3 we need to + // check & ask the user to sign in #ifndef __PS3__ - JoinFromInviteData *inviteData = (JoinFromInviteData *)lpParam; - app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, lpParam); + JoinFromInviteData* inviteData = (JoinFromInviteData*)lpParam; + app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, lpParam); #else - if(ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) - { - JoinFromInviteData *inviteData = (JoinFromInviteData *)lpParam; - app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, lpParam); - } - else - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_PRO_NOTONLINE_ACCEPT; - uiIDA[1]=IDS_PRO_NOTONLINE_DECLINE; - ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, ProfileManager.GetPrimaryPad(),&CGameNetworkManager::MustSignInReturned_0,lpParam, app.GetStringTable()); - } + if (ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) { + JoinFromInviteData* inviteData = (JoinFromInviteData*)lpParam; + app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, + lpParam); + } else { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; + uiIDA[1] = IDS_PRO_NOTONLINE_DECLINE; + ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, + uiIDA, 2, ProfileManager.GetPrimaryPad(), + &CGameNetworkManager::MustSignInReturned_0, + lpParam, app.GetStringTable()); + } #endif - return 0; + return 0; } #if defined __PS3__ || defined __PSVITA__ || defined __ORBIS__ -// This case happens when we have been returned from the game to the main menu after receiving an invite and are now trying to go back in to join the new game -// The pair of methods MustSignInReturned_0 & PSNSignInReturned_0 handle this -int CGameNetworkManager::MustSignInReturned_0(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - if(result==C4JStorage::EMessage_ResultAccept) - { +// This case happens when we have been returned from the game to the main menu +// after receiving an invite and are now trying to go back in to join the new +// game The pair of methods MustSignInReturned_0 & PSNSignInReturned_0 handle +// this +int CGameNetworkManager::MustSignInReturned_0( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + if (result == C4JStorage::EMessage_ResultAccept) { #ifdef __PS3__ - SQRNetworkManager_PS3::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_0, pParam,true); + SQRNetworkManager_PS3::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_0, pParam, true); #elif defined __PSVITA__ - SQRNetworkManager_Vita::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_0, pParam,true); + SQRNetworkManager_Vita::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_0, pParam, true); #elif defined __ORBIS__ - SQRNetworkManager_Orbis::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_0, pParam,true); + SQRNetworkManager_Orbis::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_0, pParam, true); #endif - } - else - { - app.SetAction(0,eAppAction_Idle); - ui.NavigateToHomeMenu(); - ui.UpdatePlayerBasePositions(); - } + } else { + app.SetAction(0, eAppAction_Idle); + ui.NavigateToHomeMenu(); + ui.UpdatePlayerBasePositions(); + } - return 0; + return 0; } -int CGameNetworkManager::PSNSignInReturned_0(void* pParam, bool bContinue, int iPad) -{ - JoinFromInviteData *inviteData = (JoinFromInviteData *)pParam; +int CGameNetworkManager::PSNSignInReturned_0(void* pParam, bool bContinue, + int iPad) { + JoinFromInviteData* inviteData = (JoinFromInviteData*)pParam; - // If the invite data isn't set up yet (indicated by it being all zeroes, easiest detected via the net version), then try and get it again... this can happen if we got - // the invite whilst signed out + // If the invite data isn't set up yet (indicated by it being all zeroes, + // easiest detected via the net version), then try and get it again... this + // can happen if we got the invite whilst signed out - if( bContinue ) - { - if(inviteData->pInviteInfo->netVersion == 0) - { + if (bContinue) { + if (inviteData->pInviteInfo->netVersion == 0) { #if defined __PS3__ || defined __VITA__ - if(!SQRNetworkManager_PS3::UpdateInviteData((SQRNetworkManager::PresenceSyncInfo *)inviteData->pInviteInfo)) - { - bContinue = false; - } + if (!SQRNetworkManager_PS3::UpdateInviteData( + (SQRNetworkManager::PresenceSyncInfo*) + inviteData->pInviteInfo)) { + bContinue = false; + } #elif defined __ORBIS__ - // TODO: No Orbis equivalent (should there be?) + // TODO: No Orbis equivalent (should there be?) #endif - } - } + } + } - if( bContinue ) - { - app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, pParam); - } - else - { - app.SetAction(inviteData->dwUserIndex,eAppAction_Idle); - ui.NavigateToHomeMenu(); - ui.UpdatePlayerBasePositions(); - } + if (bContinue) { + app.SetAction(inviteData->dwUserIndex, eAppAction_JoinFromInvite, + pParam); + } else { + app.SetAction(inviteData->dwUserIndex, eAppAction_Idle); + ui.NavigateToHomeMenu(); + ui.UpdatePlayerBasePositions(); + } - return 0; + return 0; } -// This case happens when we were in the main menus when we got an invite, and weren't signed in... now can proceed with the normal flow of code for this situation -// The pair of methods MustSignInReturned_1 & PSNSignInReturned_1 handle this -int CGameNetworkManager::MustSignInReturned_1(void *pParam,int iPad,C4JStorage::EMessageResult result) -{ - if(result==C4JStorage::EMessage_ResultAccept) - { +// This case happens when we were in the main menus when we got an invite, and +// weren't signed in... now can proceed with the normal flow of code for this +// situation The pair of methods MustSignInReturned_1 & PSNSignInReturned_1 +// handle this +int CGameNetworkManager::MustSignInReturned_1( + void* pParam, int iPad, C4JStorage::EMessageResult result) { + if (result == C4JStorage::EMessage_ResultAccept) { #ifdef __PS3__ - SQRNetworkManager_PS3::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_1, pParam,true); + SQRNetworkManager_PS3::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_1, pParam, true); #elif defined __PSVITA__ - SQRNetworkManager_Vita::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_1, pParam,true); + SQRNetworkManager_Vita::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_1, pParam, true); #elif defined __ORBIS__ - SQRNetworkManager_Orbis::AttemptPSNSignIn(&CGameNetworkManager::PSNSignInReturned_1, pParam,true); + SQRNetworkManager_Orbis::AttemptPSNSignIn( + &CGameNetworkManager::PSNSignInReturned_1, pParam, true); #endif - } - return 0; + } + return 0; } -int CGameNetworkManager::PSNSignInReturned_1(void* pParam, bool bContinue, int iPad) -{ - INVITE_INFO *inviteInfo = (INVITE_INFO *)pParam; +int CGameNetworkManager::PSNSignInReturned_1(void* pParam, bool bContinue, + int iPad) { + INVITE_INFO* inviteInfo = (INVITE_INFO*)pParam; - // If the invite data isn't set up yet (indicated by it being all zeroes, easiest detected via the net version), then try and get it again... this can happen if we got - // the invite whilst signed out + // If the invite data isn't set up yet (indicated by it being all zeroes, + // easiest detected via the net version), then try and get it again... this + // can happen if we got the invite whilst signed out - if( bContinue ) - { - if(inviteInfo->netVersion == 0) - { + if (bContinue) { + if (inviteInfo->netVersion == 0) { #if defined __PS3__ || defined __VITA__ - if(!SQRNetworkManager_PS3::UpdateInviteData((SQRNetworkManager::PresenceSyncInfo *)inviteInfo)) - { - bContinue = false; - } + if (!SQRNetworkManager_PS3::UpdateInviteData( + (SQRNetworkManager::PresenceSyncInfo*)inviteInfo)) { + bContinue = false; + } #elif defined __ORBIS__ - // TODO: No Orbis equivalent (should there be?) + // TODO: No Orbis equivalent (should there be?) #endif - - } - } + } + } - if( bContinue ) - { - g_NetworkManager.HandleInviteWhenInMenus(0, inviteInfo); - } + if (bContinue) { + g_NetworkManager.HandleInviteWhenInMenus(0, inviteInfo); + } - return 0; + return 0; } #endif -void CGameNetworkManager::_LeaveGame() -{ - s_pPlatformNetworkManager->_LeaveGame(false, true); +void CGameNetworkManager::_LeaveGame() { + s_pPlatformNetworkManager->_LeaveGame(false, true); } -int CGameNetworkManager::ChangeSessionTypeThreadProc( void* lpParam ) -{ - // Share AABB & Vec3 pools with default (main thread) - should be ok as long as we don't tick the main thread whilst this thread is running - AABB::UseDefaultThreadStorage(); - Vec3::UseDefaultThreadStorage(); - Compression::UseDefaultThreadStorage(); +int CGameNetworkManager::ChangeSessionTypeThreadProc(void* lpParam) { + // Share AABB & Vec3 pools with default (main thread) - should be ok as long + // as we don't tick the main thread whilst this thread is running + AABB::UseDefaultThreadStorage(); + Vec3::UseDefaultThreadStorage(); + Compression::UseDefaultThreadStorage(); - Minecraft *pMinecraft = Minecraft::GetInstance(); - MinecraftServer *pServer = MinecraftServer::getInstance(); + Minecraft* pMinecraft = Minecraft::GetInstance(); + MinecraftServer* pServer = MinecraftServer::getInstance(); #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - if( g_NetworkManager.m_bLastDisconnectWasLostRoomOnly ) - { - if(g_NetworkManager.m_bSignedOutofPSN) - { - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, IDS_ERROR_PSN_SIGN_OUT, uiIDA,1,ProfileManager.GetPrimaryPad()); - } - else - { - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, uiIDA,1,ProfileManager.GetPrimaryPad()); - } - } - else - { - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_CONNECTION_LOST, g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT), uiIDA,1,ProfileManager.GetPrimaryPad()); - } + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + if (g_NetworkManager.m_bLastDisconnectWasLostRoomOnly) { + if (g_NetworkManager.m_bSignedOutofPSN) { + C4JStorage::EMessageResult result = ui.RequestMessageBox( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, IDS_ERROR_PSN_SIGN_OUT, + uiIDA, 1, ProfileManager.GetPrimaryPad()); + } else { + C4JStorage::EMessageResult result = + ui.RequestMessageBox(IDS_ERROR_NETWORK_TITLE, + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, + uiIDA, 1, ProfileManager.GetPrimaryPad()); + } + } else { + C4JStorage::EMessageResult result = ui.RequestMessageBox( + IDS_CONNECTION_LOST, + g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT), + uiIDA, 1, ProfileManager.GetPrimaryPad()); + } - // Swap these two messages around as one is too long to display at 480 - pMinecraft->progressRenderer->progressStartNoAbort( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - pMinecraft->progressRenderer->progressStage( -1 ); //g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); + // Swap these two messages around as one is too long to display at 480 + pMinecraft->progressRenderer->progressStartNoAbort( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + pMinecraft->progressRenderer->progressStage(-1); // g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) + // ); #elif defined(_XBOX_ONE) - if( g_NetworkManager.m_bFullSessionMessageOnNextSessionChange ) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, IDS_IN_PARTY_SESSION_FULL, uiIDA,1,ProfileManager.GetPrimaryPad()); - pMinecraft->progressRenderer->progressStartNoAbort( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - pMinecraft->progressRenderer->progressStage( -1 ); - } - else - { - pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); - pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - } - + if (g_NetworkManager.m_bFullSessionMessageOnNextSessionChange) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + C4JStorage::EMessageResult result = ui.RequestMessageBox( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME, IDS_IN_PARTY_SESSION_FULL, + uiIDA, 1, ProfileManager.GetPrimaryPad()); + pMinecraft->progressRenderer->progressStartNoAbort( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + pMinecraft->progressRenderer->progressStage(-1); + } else { + pMinecraft->progressRenderer->progressStartNoAbort( + g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT)); + pMinecraft->progressRenderer->progressStage( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + } + #else - pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); - pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); + pMinecraft->progressRenderer->progressStartNoAbort( + g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT)); + pMinecraft->progressRenderer->progressStage( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); #endif - while( app.GetXuiServerAction(ProfileManager.GetPrimaryPad() ) != eXuiServerAction_Idle && !MinecraftServer::serverHalted() ) - { - Sleep(10); - } - app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_PauseServer,(void *)TRUE); + while (app.GetXuiServerAction(ProfileManager.GetPrimaryPad()) != + eXuiServerAction_Idle && + !MinecraftServer::serverHalted()) { + Sleep(10); + } + app.SetXuiServerAction(ProfileManager.GetPrimaryPad(), + eXuiServerAction_PauseServer, (void*)TRUE); + + // wait for the server to be in a non-ticking state + pServer->m_serverPausedEvent->WaitForSignal(INFINITE); - // wait for the server to be in a non-ticking state - pServer->m_serverPausedEvent->WaitForSignal(INFINITE); - #if defined(__PS3__) || defined(__ORBIS__) || defined __PSVITA__ - // Swap these two messages around as one is too long to display at 480 - pMinecraft->progressRenderer->progressStartNoAbort( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - pMinecraft->progressRenderer->progressStage( -1 ); //g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); + // Swap these two messages around as one is too long to display at 480 + pMinecraft->progressRenderer->progressStartNoAbort( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + pMinecraft->progressRenderer->progressStage(-1); // g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) + // ); #elif defined(_XBOX_ONE) - if( g_NetworkManager.m_bFullSessionMessageOnNextSessionChange ) - { - pMinecraft->progressRenderer->progressStartNoAbort( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - pMinecraft->progressRenderer->progressStage( -1 ); - } - else - { - pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); - pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); - } + if (g_NetworkManager.m_bFullSessionMessageOnNextSessionChange) { + pMinecraft->progressRenderer->progressStartNoAbort( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + pMinecraft->progressRenderer->progressStage(-1); + } else { + pMinecraft->progressRenderer->progressStartNoAbort( + g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT)); + pMinecraft->progressRenderer->progressStage( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); + } #else - pMinecraft->progressRenderer->progressStartNoAbort( g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT) ); - pMinecraft->progressRenderer->progressStage( IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME ); + pMinecraft->progressRenderer->progressStartNoAbort( + g_NetworkManager.CorrectErrorIDS(IDS_CONNECTION_LOST_LIVE_NO_EXIT)); + pMinecraft->progressRenderer->progressStage( + IDS_PROGRESS_CONVERTING_TO_OFFLINE_GAME); #endif - pMinecraft->progressRenderer->progressStagePercentage(25); + pMinecraft->progressRenderer->progressStagePercentage(25); #ifdef _XBOX_ONE - // wait for any players that were being added, to finish doing this. On XB1, if we don't do this then there's an async thread running doing this, - // which could then finish at any inappropriate time later - while( s_pPlatformNetworkManager->IsAddingPlayer() ) - { - Sleep(1); - } + // wait for any players that were being added, to finish doing this. On XB1, + // if we don't do this then there's an async thread running doing this, + // which could then finish at any inappropriate time later + while (s_pPlatformNetworkManager->IsAddingPlayer()) { + Sleep(1); + } #endif - // Null the network player of all the server players that are local, to stop them being removed from the server when removed from the session - if( pServer != NULL ) - { - PlayerList *players = pServer->getPlayers(); - for(AUTO_VAR(it, players->players.begin()); it < players->players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - if( servPlayer->connection->isLocal() && !servPlayer->connection->isGuest() ) - { - servPlayer->connection->connection->getSocket()->setPlayer(NULL); - } - } - } + // Null the network player of all the server players that are local, to stop + // them being removed from the server when removed from the session + if (pServer != NULL) { + PlayerList* players = pServer->getPlayers(); + for (AUTO_VAR(it, players->players.begin()); + it < players->players.end(); ++it) { + std::shared_ptr servPlayer = *it; + if (servPlayer->connection->isLocal() && + !servPlayer->connection->isGuest()) { + servPlayer->connection->connection->getSocket()->setPlayer( + NULL); + } + } + } - // delete the current session - if we weren't actually disconnected fully from the network but have just lost our room, then pass a bLeaveRoom flag of false - // here as by definition we don't need to leave the room (again). This is currently only an issue for sony platforms. - if( g_NetworkManager.m_bLastDisconnectWasLostRoomOnly ) - { - s_pPlatformNetworkManager->_LeaveGame(false, false); - } - else - { - s_pPlatformNetworkManager->_LeaveGame(false, true); - } + // delete the current session - if we weren't actually disconnected fully + // from the network but have just lost our room, then pass a bLeaveRoom flag + // of false here as by definition we don't need to leave the room (again). + // This is currently only an issue for sony platforms. + if (g_NetworkManager.m_bLastDisconnectWasLostRoomOnly) { + s_pPlatformNetworkManager->_LeaveGame(false, false); + } else { + s_pPlatformNetworkManager->_LeaveGame(false, true); + } - // wait for the current session to end - while( g_NetworkManager.IsInSession() ) - { - Sleep(1); - } - - // Reset this flag as the we don't need to know that we only lost the room only from this point onwards, the behaviour is exactly the same - g_NetworkManager.m_bLastDisconnectWasLostRoomOnly = false; - g_NetworkManager.m_bFullSessionMessageOnNextSessionChange = false; + // wait for the current session to end + while (g_NetworkManager.IsInSession()) { + Sleep(1); + } - pMinecraft->progressRenderer->progressStagePercentage(50); + // Reset this flag as the we don't need to know that we only lost the room + // only from this point onwards, the behaviour is exactly the same + g_NetworkManager.m_bLastDisconnectWasLostRoomOnly = false; + g_NetworkManager.m_bFullSessionMessageOnNextSessionChange = false; - // Defaulting to making this a local game - g_NetworkManager.SetLocalGame(true); + pMinecraft->progressRenderer->progressStagePercentage(50); - // Create a new session with all the players that were in the old one - int localUsersMask = 0; - char numLocalPlayers = 0; - for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) - { - if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != NULL ) - { - numLocalPlayers++; - localUsersMask |= GetLocalPlayerMask(index); - } - } + // Defaulting to making this a local game + g_NetworkManager.SetLocalGame(true); - s_pPlatformNetworkManager->_HostGame( localUsersMask ); + // Create a new session with all the players that were in the old one + int localUsersMask = 0; + char numLocalPlayers = 0; + for (unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { + if (ProfileManager.IsSignedIn(index) && + pMinecraft->localplayers[index] != NULL) { + numLocalPlayers++; + localUsersMask |= GetLocalPlayerMask(index); + } + } - pMinecraft->progressRenderer->progressStagePercentage(75); + s_pPlatformNetworkManager->_HostGame(localUsersMask); - // Wait for all the local players to rejoin the session - while( g_NetworkManager.GetPlayerCount() < numLocalPlayers ) - { - Sleep(1); - } - - // Restore the network player of all the server players that are local - if( pServer != NULL ) - { - for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) - { - if(ProfileManager.IsSignedIn(index) && pMinecraft->localplayers[index] != NULL ) - { - PlayerUID localPlayerXuid = pMinecraft->localplayers[index]->getXuid(); + pMinecraft->progressRenderer->progressStagePercentage(75); - PlayerList *players = pServer->getPlayers(); - for(AUTO_VAR(it, players->players.begin()); it < players->players.end(); ++it) - { - std::shared_ptr servPlayer = *it; - if( servPlayer->getXuid() == localPlayerXuid ) - { - servPlayer->connection->connection->getSocket()->setPlayer( g_NetworkManager.GetLocalPlayerByUserIndex(index) ); - } - } + // Wait for all the local players to rejoin the session + while (g_NetworkManager.GetPlayerCount() < numLocalPlayers) { + Sleep(1); + } - // Player might have a pending connection - if (pMinecraft->m_pendingLocalConnections[index] != NULL) - { - // Update the network player - pMinecraft->m_pendingLocalConnections[index]->getConnection()->getSocket()->setPlayer(g_NetworkManager.GetLocalPlayerByUserIndex(index)); - } - } - } - } - - pMinecraft->progressRenderer->progressStagePercentage(100); + // Restore the network player of all the server players that are local + if (pServer != NULL) { + for (unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { + if (ProfileManager.IsSignedIn(index) && + pMinecraft->localplayers[index] != NULL) { + PlayerUID localPlayerXuid = + pMinecraft->localplayers[index]->getXuid(); + + PlayerList* players = pServer->getPlayers(); + for (AUTO_VAR(it, players->players.begin()); + it < players->players.end(); ++it) { + std::shared_ptr servPlayer = *it; + if (servPlayer->getXuid() == localPlayerXuid) { + servPlayer->connection->connection->getSocket() + ->setPlayer( + g_NetworkManager.GetLocalPlayerByUserIndex( + index)); + } + } + + // Player might have a pending connection + if (pMinecraft->m_pendingLocalConnections[index] != NULL) { + // Update the network player + pMinecraft->m_pendingLocalConnections[index] + ->getConnection() + ->getSocket() + ->setPlayer( + g_NetworkManager.GetLocalPlayerByUserIndex(index)); + } + } + } + } + + pMinecraft->progressRenderer->progressStagePercentage(100); #ifndef _XBOX - // Make sure that we have transitioned through any joining/creating stages so we're actually ready to set to play - while(!s_pPlatformNetworkManager->IsReadyToPlayOrIdle()) - { - Sleep(10); - } + // Make sure that we have transitioned through any joining/creating stages + // so we're actually ready to set to play + while (!s_pPlatformNetworkManager->IsReadyToPlayOrIdle()) { + Sleep(10); + } #endif - s_pPlatformNetworkManager->_StartGame(); + s_pPlatformNetworkManager->_StartGame(); #ifndef _XBOX - // Wait until the message box has been closed - while(ui.IsSceneInStack(XUSER_INDEX_ANY, eUIScene_MessageBox)) - { - Sleep(10); - } + // Wait until the message box has been closed + while (ui.IsSceneInStack(XUSER_INDEX_ANY, eUIScene_MessageBox)) { + Sleep(10); + } #endif - // Start the game again - app.SetGameStarted(true); - app.SetXuiServerAction(ProfileManager.GetPrimaryPad(),eXuiServerAction_PauseServer,(void *)FALSE); - app.SetChangingSessionType(false); - app.SetReallyChangingSessionType(false); - - return 0; + // Start the game again + app.SetGameStarted(true); + app.SetXuiServerAction(ProfileManager.GetPrimaryPad(), + eXuiServerAction_PauseServer, (void*)FALSE); + app.SetChangingSessionType(false); + app.SetReallyChangingSessionType(false); + return 0; } -void CGameNetworkManager::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) -{ - s_pPlatformNetworkManager->SystemFlagSet( pNetworkPlayer, index ); +void CGameNetworkManager::SystemFlagSet(INetworkPlayer* pNetworkPlayer, + int index) { + s_pPlatformNetworkManager->SystemFlagSet(pNetworkPlayer, index); } -bool CGameNetworkManager::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) -{ - return s_pPlatformNetworkManager->SystemFlagGet( pNetworkPlayer, index ); +bool CGameNetworkManager::SystemFlagGet(INetworkPlayer* pNetworkPlayer, + int index) { + return s_pPlatformNetworkManager->SystemFlagGet(pNetworkPlayer, index); } -std::wstring CGameNetworkManager::GatherStats() -{ - return s_pPlatformNetworkManager->GatherStats(); +std::wstring CGameNetworkManager::GatherStats() { + return s_pPlatformNetworkManager->GatherStats(); } -void CGameNetworkManager::renderQueueMeter() -{ +void CGameNetworkManager::renderQueueMeter() { #ifdef _XBOX - int height = 720; + int height = 720; - CGameNetworkManager::byteQueue[(CGameNetworkManager::messageQueuePos) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeBytes(NULL, false); - CGameNetworkManager::messageQueue[(CGameNetworkManager::messageQueuePos++) & (CGameNetworkManager::messageQueue_length - 1)] = GetHostPlayer()->GetSendQueueSizeMessages(NULL, false); + CGameNetworkManager::byteQueue[(CGameNetworkManager::messageQueuePos) & + (CGameNetworkManager::messageQueue_length - + 1)] = + GetHostPlayer()->GetSendQueueSizeBytes(NULL, false); + CGameNetworkManager::messageQueue + [(CGameNetworkManager::messageQueuePos++) & + (CGameNetworkManager::messageQueue_length - 1)] = + GetHostPlayer()->GetSendQueueSizeMessages(NULL, false); - Minecraft *pMinecraft = Minecraft::GetInstance(); - pMinecraft->gui->renderGraph(CGameNetworkManager::messageQueue_length, CGameNetworkManager::messageQueuePos, CGameNetworkManager::messageQueue, 10, 1000, CGameNetworkManager::byteQueue, 100, 25000); + Minecraft* pMinecraft = Minecraft::GetInstance(); + pMinecraft->gui->renderGraph(CGameNetworkManager::messageQueue_length, + CGameNetworkManager::messageQueuePos, + CGameNetworkManager::messageQueue, 10, 1000, + CGameNetworkManager::byteQueue, 100, 25000); #endif } -std::wstring CGameNetworkManager::GatherRTTStats() -{ - return s_pPlatformNetworkManager->GatherRTTStats(); +std::wstring CGameNetworkManager::GatherRTTStats() { + return s_pPlatformNetworkManager->GatherRTTStats(); } -void CGameNetworkManager::StateChange_AnyToHosting() -{ - app.DebugPrintf("Disabling Guest Signin\n"); - XEnableGuestSignin(FALSE); - Minecraft::GetInstance()->clearPendingClientTextureRequests(); +void CGameNetworkManager::StateChange_AnyToHosting() { + app.DebugPrintf("Disabling Guest Signin\n"); + XEnableGuestSignin(FALSE); + Minecraft::GetInstance()->clearPendingClientTextureRequests(); } -void CGameNetworkManager::StateChange_AnyToJoining() -{ - app.DebugPrintf("Disabling Guest Signin\n"); - XEnableGuestSignin(FALSE); - Minecraft::GetInstance()->clearPendingClientTextureRequests(); - - ConnectionProgressParams *param = new ConnectionProgressParams(); - param->iPad = ProfileManager.GetPrimaryPad(); - param->stringId = -1; - param->showTooltips = false; - param->setFailTimer = true; - param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; +void CGameNetworkManager::StateChange_AnyToJoining() { + app.DebugPrintf("Disabling Guest Signin\n"); + XEnableGuestSignin(FALSE); + Minecraft::GetInstance()->clearPendingClientTextureRequests(); - ui.NavigateToScene(ProfileManager.GetPrimaryPad(), eUIScene_ConnectingProgress, param); + ConnectionProgressParams* param = new ConnectionProgressParams(); + param->iPad = ProfileManager.GetPrimaryPad(); + param->stringId = -1; + param->showTooltips = false; + param->setFailTimer = true; + param->timerTime = CONNECTING_PROGRESS_CHECK_TIME; + + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), + eUIScene_ConnectingProgress, param); } -void CGameNetworkManager::StateChange_JoiningToIdle(CPlatformNetworkManager::eJoinFailedReason reason) -{ - DisconnectPacket::eDisconnectReason disconnectReason; - switch(reason) - { - case CPlatformNetworkManager::JOIN_FAILED_SERVER_FULL: - disconnectReason = DisconnectPacket::eDisconnect_ServerFull; - break; - case CPlatformNetworkManager::JOIN_FAILED_INSUFFICIENT_PRIVILEGES: - disconnectReason = DisconnectPacket::eDisconnect_NoMultiplayerPrivilegesJoin; - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_FailedToJoinNoPrivileges); - break; - default: - disconnectReason = DisconnectPacket::eDisconnect_ConnectionCreationFailed; - break; - }; - Minecraft::GetInstance()->connectionDisconnected(ProfileManager.GetPrimaryPad(), disconnectReason); +void CGameNetworkManager::StateChange_JoiningToIdle( + CPlatformNetworkManager::eJoinFailedReason reason) { + DisconnectPacket::eDisconnectReason disconnectReason; + switch (reason) { + case CPlatformNetworkManager::JOIN_FAILED_SERVER_FULL: + disconnectReason = DisconnectPacket::eDisconnect_ServerFull; + break; + case CPlatformNetworkManager::JOIN_FAILED_INSUFFICIENT_PRIVILEGES: + disconnectReason = + DisconnectPacket::eDisconnect_NoMultiplayerPrivilegesJoin; + app.SetAction(ProfileManager.GetPrimaryPad(), + eAppAction_FailedToJoinNoPrivileges); + break; + default: + disconnectReason = + DisconnectPacket::eDisconnect_ConnectionCreationFailed; + break; + }; + Minecraft::GetInstance()->connectionDisconnected( + ProfileManager.GetPrimaryPad(), disconnectReason); } -void CGameNetworkManager::StateChange_AnyToStarting() -{ +void CGameNetworkManager::StateChange_AnyToStarting() { #if defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - app.getRemoteStorage()->shutdown(); // shut the remote storage lib down and hopefully get our 7mb back + app.getRemoteStorage()->shutdown(); // shut the remote storage lib down and + // hopefully get our 7mb back #endif - if(!g_NetworkManager.IsHost()) - { - LoadingInputParams *loadingParams = new LoadingInputParams(); - loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; - loadingParams->lpParam = NULL; + if (!g_NetworkManager.IsHost()) { + LoadingInputParams* loadingParams = new LoadingInputParams(); + loadingParams->func = &CGameNetworkManager::RunNetworkGameThreadProc; + loadingParams->lpParam = NULL; - UIFullscreenProgressCompletionData *completionData = new UIFullscreenProgressCompletionData(); - completionData->bShowBackground=TRUE; - completionData->bShowLogo=TRUE; - completionData->type = e_ProgressCompletion_CloseAllPlayersUIScenes; - completionData->iPad = ProfileManager.GetPrimaryPad(); - loadingParams->completionData = completionData; - - ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_FullscreenProgress, loadingParams); - } + UIFullscreenProgressCompletionData* completionData = + new UIFullscreenProgressCompletionData(); + completionData->bShowBackground = TRUE; + completionData->bShowLogo = TRUE; + completionData->type = e_ProgressCompletion_CloseAllPlayersUIScenes; + completionData->iPad = ProfileManager.GetPrimaryPad(); + loadingParams->completionData = completionData; + + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), + eUIScene_FullscreenProgress, loadingParams); + } } -void CGameNetworkManager::StateChange_AnyToEnding(bool bStateWasPlaying) -{ - // Kick off a stats write for players that are signed into LIVE, if this is a local game - if( bStateWasPlaying && g_NetworkManager.IsLocalGame() ) - { - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - INetworkPlayer *pNetworkPlayer = g_NetworkManager.GetLocalPlayerByUserIndex(i); - if(pNetworkPlayer != NULL && ProfileManager.IsSignedIn( i ) ) - { - app.DebugPrintf("Stats save for an offline game for the player at index %d\n", i ); - Minecraft::GetInstance()->forceStatsSave(pNetworkPlayer->GetUserIndex()); - } - } - } +void CGameNetworkManager::StateChange_AnyToEnding(bool bStateWasPlaying) { + // Kick off a stats write for players that are signed into LIVE, if this is + // a local game + if (bStateWasPlaying && g_NetworkManager.IsLocalGame()) { + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + INetworkPlayer* pNetworkPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(i); + if (pNetworkPlayer != NULL && ProfileManager.IsSignedIn(i)) { + app.DebugPrintf( + "Stats save for an offline game for the player at index " + "%d\n", + i); + Minecraft::GetInstance()->forceStatsSave( + pNetworkPlayer->GetUserIndex()); + } + } + } - Minecraft::GetInstance()->gui->clearMessages(); + Minecraft::GetInstance()->gui->clearMessages(); - if(!g_NetworkManager.IsHost() && !g_NetworkManager.IsLeavingGame() ) - { - // 4J Stu - If the host is saving then it might take a while to quite the session, so do it ourself - //m_bLeavingGame = true; + if (!g_NetworkManager.IsHost() && !g_NetworkManager.IsLeavingGame()) { + // 4J Stu - If the host is saving then it might take a while to quite + // the session, so do it ourself + // m_bLeavingGame = true; - // The host has notified that the game is about to end - if(app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) app.SetDisconnectReason( DisconnectPacket::eDisconnect_Quitting ); - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); - } + // The host has notified that the game is about to end + if (app.GetDisconnectReason() == DisconnectPacket::eDisconnect_None) + app.SetDisconnectReason(DisconnectPacket::eDisconnect_Quitting); + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ExitWorld, + (void*)TRUE); + } } -void CGameNetworkManager::StateChange_AnyToIdle() -{ - app.DebugPrintf("Enabling Guest Signin\n"); - XEnableGuestSignin(TRUE); - // Reset this here so that we can search for games again - // 4J Stu - If we are changing session type there is a race between that thread setting the game to local, and this setting it to not local - if(!app.GetChangingSessionType()) g_NetworkManager.SetLocalGame( false ); - +void CGameNetworkManager::StateChange_AnyToIdle() { + app.DebugPrintf("Enabling Guest Signin\n"); + XEnableGuestSignin(TRUE); + // Reset this here so that we can search for games again + // 4J Stu - If we are changing session type there is a race between that + // thread setting the game to local, and this setting it to not local + if (!app.GetChangingSessionType()) g_NetworkManager.SetLocalGame(false); } -void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool localPlayer ) -{ - Minecraft *pMinecraft = Minecraft::GetInstance(); +void CGameNetworkManager::CreateSocket(INetworkPlayer* pNetworkPlayer, + bool localPlayer) { + Minecraft* pMinecraft = Minecraft::GetInstance(); - Socket *socket = NULL; - std::shared_ptr mpPlayer = pMinecraft->localplayers[pNetworkPlayer->GetUserIndex()]; - if( localPlayer && mpPlayer != NULL && mpPlayer->connection != NULL) - { - // If we already have a MultiplayerLocalPlayer here then we are doing a session type change - socket = mpPlayer->connection->getSocket(); + Socket* socket = NULL; + std::shared_ptr mpPlayer = + pMinecraft->localplayers[pNetworkPlayer->GetUserIndex()]; + if (localPlayer && mpPlayer != NULL && mpPlayer->connection != NULL) { + // If we already have a MultiplayerLocalPlayer here then we are doing a + // session type change + socket = mpPlayer->connection->getSocket(); - // Pair this socket and network player - pNetworkPlayer->SetSocket( socket); - if( socket ) - { - socket->setPlayer( pNetworkPlayer ); - } - } - else - { - socket = new Socket( pNetworkPlayer, g_NetworkManager.IsHost(), g_NetworkManager.IsHost() && localPlayer ); - pNetworkPlayer->SetSocket( socket ); + // Pair this socket and network player + pNetworkPlayer->SetSocket(socket); + if (socket) { + socket->setPlayer(pNetworkPlayer); + } + } else { + socket = new Socket(pNetworkPlayer, g_NetworkManager.IsHost(), + g_NetworkManager.IsHost() && localPlayer); + pNetworkPlayer->SetSocket(socket); - // 4J Stu - May be other states we want to accept aswell - // Add this user to the game server if the game is started already - if( g_NetworkManager.IsHost() && g_NetworkManager.IsInGameplay() ) - { - Socket::addIncomingSocket(socket); - } + // 4J Stu - May be other states we want to accept aswell + // Add this user to the game server if the game is started already + if (g_NetworkManager.IsHost() && g_NetworkManager.IsInGameplay()) { + Socket::addIncomingSocket(socket); + } - // If this is a local player and we are already in the game, we need to setup a local connection and log - // the player in to the game server - if( localPlayer && g_NetworkManager.IsInGameplay() ) - { - int idx = pNetworkPlayer->GetUserIndex(); - app.DebugPrintf("Creating new client connection for idx: %d\n", idx); + // If this is a local player and we are already in the game, we need to + // setup a local connection and log the player in to the game server + if (localPlayer && g_NetworkManager.IsInGameplay()) { + int idx = pNetworkPlayer->GetUserIndex(); + app.DebugPrintf("Creating new client connection for idx: %d\n", + idx); - ClientConnection *connection; - connection = new ClientConnection(pMinecraft, socket, idx); - - if( connection->createdOk ) - { - connection->send( std::shared_ptr( new PreLoginPacket( pNetworkPlayer->GetOnlineName() ) ) ); - pMinecraft->addPendingLocalConnection(idx, connection); - } - else - { - pMinecraft->connectionDisconnected( idx , DisconnectPacket::eDisconnect_ConnectionCreationFailed ); - delete connection; - connection = NULL; - } - } - } + ClientConnection* connection; + connection = new ClientConnection(pMinecraft, socket, idx); + if (connection->createdOk) { + connection->send(std::shared_ptr( + new PreLoginPacket(pNetworkPlayer->GetOnlineName()))); + pMinecraft->addPendingLocalConnection(idx, connection); + } else { + pMinecraft->connectionDisconnected( + idx, + DisconnectPacket::eDisconnect_ConnectionCreationFailed); + delete connection; + connection = NULL; + } + } + } } -void CGameNetworkManager::CloseConnection( INetworkPlayer *pNetworkPlayer ) -{ - MinecraftServer *server = MinecraftServer::getInstance(); - if( server != NULL ) - { - PlayerList *players = server->getPlayers(); - if( players != NULL ) - { - players->closePlayerConnectionBySmallId(pNetworkPlayer->GetSmallId()); - } - } +void CGameNetworkManager::CloseConnection(INetworkPlayer* pNetworkPlayer) { + MinecraftServer* server = MinecraftServer::getInstance(); + if (server != NULL) { + PlayerList* players = server->getPlayers(); + if (players != NULL) { + players->closePlayerConnectionBySmallId( + pNetworkPlayer->GetSmallId()); + } + } } -void CGameNetworkManager::PlayerJoining( INetworkPlayer *pNetworkPlayer ) -{ - if (g_NetworkManager.IsInGameplay()) // 4J-JEV: Wait to do this at StartNetworkGame if not in-game yet. - { - // 4J-JEV: Update RichPresence when a player joins the game. - bool multiplayer = g_NetworkManager.GetPlayerCount() > 1, localgame = g_NetworkManager.IsLocalGame(); - for (int iPad=0; iPadIsLocal() ) +void CGameNetworkManager::PlayerJoining(INetworkPlayer* pNetworkPlayer) { + if (g_NetworkManager + .IsInGameplay()) // 4J-JEV: Wait to do this at StartNetworkGame if + // not in-game yet. { - TelemetryManager->RecordPlayerSessionStart(pNetworkPlayer->GetUserIndex()); + // 4J-JEV: Update RichPresence when a player joins the game. + bool multiplayer = g_NetworkManager.GetPlayerCount() > 1, + localgame = g_NetworkManager.IsLocalGame(); + for (int iPad = 0; iPad < XUSER_MAX_COUNT; ++iPad) { + INetworkPlayer* pNetworkPlayer = + g_NetworkManager.GetLocalPlayerByUserIndex(iPad); + if (pNetworkPlayer == NULL) continue; + + app.SetRichPresenceContext(iPad, CONTEXT_GAME_STATE_BLANK); + if (multiplayer) { + if (localgame) + ProfileManager.SetCurrentGameActivity( + iPad, CONTEXT_PRESENCE_MULTIPLAYEROFFLINE, false); + else + ProfileManager.SetCurrentGameActivity( + iPad, CONTEXT_PRESENCE_MULTIPLAYER, false); + } else { + if (localgame) + ProfileManager.SetCurrentGameActivity( + iPad, CONTEXT_PRESENCE_MULTIPLAYER_1POFFLINE, false); + else + ProfileManager.SetCurrentGameActivity( + iPad, CONTEXT_PRESENCE_MULTIPLAYER_1P, false); + } + } + } + + if (pNetworkPlayer->IsLocal()) { + TelemetryManager->RecordPlayerSessionStart( + pNetworkPlayer->GetUserIndex()); } #ifdef _XBOX - else - { - if( !pNetworkPlayer->IsHost() ) - { - for(int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(Minecraft::GetInstance()->localplayers[idx] != NULL) - { - TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); - } - } + else { + if (!pNetworkPlayer->IsHost()) { + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (Minecraft::GetInstance()->localplayers[idx] != NULL) { + TelemetryManager->RecordLevelStart( + idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->level->difficulty, + app.GetLocalPlayerCount(), + g_NetworkManager.GetOnlinePlayerCount()); + } + } } - } + } #endif } -void CGameNetworkManager::PlayerLeaving( INetworkPlayer *pNetworkPlayer ) -{ - if( pNetworkPlayer->IsLocal() ) - { - ProfileManager.SetCurrentGameActivity(pNetworkPlayer->GetUserIndex(),CONTEXT_PRESENCE_IDLE,false); +void CGameNetworkManager::PlayerLeaving(INetworkPlayer* pNetworkPlayer) { + if (pNetworkPlayer->IsLocal()) { + ProfileManager.SetCurrentGameActivity(pNetworkPlayer->GetUserIndex(), + CONTEXT_PRESENCE_IDLE, false); - TelemetryManager->RecordPlayerSessionExit(pNetworkPlayer->GetUserIndex(), app.GetDisconnectReason()); - } + TelemetryManager->RecordPlayerSessionExit( + pNetworkPlayer->GetUserIndex(), app.GetDisconnectReason()); + } #ifdef _XBOX - else - { - for(int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(Minecraft::GetInstance()->localplayers[idx] != NULL) - { - TelemetryManager->RecordLevelStart(idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, eSen_CompeteOrCoop_Coop_and_Competitive, Minecraft::GetInstance()->level->difficulty, app.GetLocalPlayerCount(), g_NetworkManager.GetOnlinePlayerCount()); - } - } - } + else { + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (Minecraft::GetInstance()->localplayers[idx] != NULL) { + TelemetryManager->RecordLevelStart( + idx, eSen_FriendOrMatch_Playing_With_Invited_Friends, + eSen_CompeteOrCoop_Coop_and_Competitive, + Minecraft::GetInstance()->level->difficulty, + app.GetLocalPlayerCount(), + g_NetworkManager.GetOnlinePlayerCount()); + } + } + } #endif } -void CGameNetworkManager::HostChanged() -{ - // Disable host migration - app.SetAction(ProfileManager.GetPrimaryPad(),eAppAction_ExitWorld,(void *)TRUE); +void CGameNetworkManager::HostChanged() { + // Disable host migration + app.SetAction(ProfileManager.GetPrimaryPad(), eAppAction_ExitWorld, + (void*)TRUE); } -void CGameNetworkManager::WriteStats( INetworkPlayer *pNetworkPlayer ) -{ - Minecraft::GetInstance()->forceStatsSave( pNetworkPlayer->GetUserIndex() ); +void CGameNetworkManager::WriteStats(INetworkPlayer* pNetworkPlayer) { + Minecraft::GetInstance()->forceStatsSave(pNetworkPlayer->GetUserIndex()); } -void CGameNetworkManager::GameInviteReceived( int userIndex, const INVITE_INFO *pInviteInfo) -{ +void CGameNetworkManager::GameInviteReceived(int userIndex, + const INVITE_INFO* pInviteInfo) { #ifdef __ORBIS__ - if (m_pUpsell != NULL) - { - delete pInviteInfo; - return; - } + if (m_pUpsell != NULL) { + delete pInviteInfo; + return; + } - // Need to check we're signed in to PSN - bool isSignedInLive = true; - bool isLocalMultiplayerAvailable = app.IsLocalMultiplayerAvailable(); - int iPadNotSignedInLive = -1; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; i++) - { - if (ProfileManager.IsSignedIn(i) && (i == ProfileManager.GetPrimaryPad() || isLocalMultiplayerAvailable)) - { - if (isSignedInLive && !ProfileManager.IsSignedInLive(i)) - { - // Record the first non signed in live pad - iPadNotSignedInLive = i; - } + // Need to check we're signed in to PSN + bool isSignedInLive = true; + bool isLocalMultiplayerAvailable = app.IsLocalMultiplayerAvailable(); + int iPadNotSignedInLive = -1; + for (unsigned int i = 0; i < XUSER_MAX_COUNT; i++) { + if (ProfileManager.IsSignedIn(i) && + (i == ProfileManager.GetPrimaryPad() || + isLocalMultiplayerAvailable)) { + if (isSignedInLive && !ProfileManager.IsSignedInLive(i)) { + // Record the first non signed in live pad + iPadNotSignedInLive = i; + } - isSignedInLive = isSignedInLive && ProfileManager.IsSignedInLive(i); - } - } + isSignedInLive = isSignedInLive && ProfileManager.IsSignedInLive(i); + } + } - if (!isSignedInLive) - { - // Determine why they're not "signed in live" + if (!isSignedInLive) { + // Determine why they're not "signed in live" - // Check if PSN is unavailable because of age restriction - int npAvailability = ProfileManager.getNPAvailability(iPadNotSignedInLive); - if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) - { - // 4J Stu - This is a bit messy and is due to the library incorrectly returning false for IsSignedInLive if the npAvailability isn't SCE_OK - unsigned int uiIDA[1]; - uiIDA[0]=IDS_OK; - ui.RequestMessageBox(IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, iPadNotSignedInLive, NULL, NULL, app.GetStringTable()); - } - else if (ProfileManager.isSignedInPSN(iPadNotSignedInLive)) - { - // Signed in to PSN but not connected (no internet access) - assert(!ProfileManager.isConnectedToPSN(iPadNotSignedInLive)); + // Check if PSN is unavailable because of age restriction + int npAvailability = + ProfileManager.getNPAvailability(iPadNotSignedInLive); + if (npAvailability == SCE_NP_ERROR_AGE_RESTRICTION) { + // 4J Stu - This is a bit messy and is due to the library + // incorrectly returning false for IsSignedInLive if the + // npAvailability isn't SCE_OK + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox( + IDS_ONLINE_SERVICE_TITLE, IDS_CONTENT_RESTRICTION, uiIDA, 1, + iPadNotSignedInLive, NULL, NULL, app.GetStringTable()); + } else if (ProfileManager.isSignedInPSN(iPadNotSignedInLive)) { + // Signed in to PSN but not connected (no internet access) + assert(!ProfileManager.isConnectedToPSN(iPadNotSignedInLive)); - unsigned int uiIDA[1]; - uiIDA[0] = IDS_OK; - ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, iPadNotSignedInLive, NULL, NULL, app.GetStringTable()); - } - else - { - // Not signed in to PSN - unsigned int uiIDA[1]; - uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; - ui.RequestMessageBox( IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, iPadNotSignedInLive, &CGameNetworkManager::MustSignInReturned_1, (void *)pInviteInfo, app.GetStringTable(), NULL, 0, false); - } - return; - } + unsigned int uiIDA[1]; + uiIDA[0] = IDS_OK; + ui.RequestMessageBox(IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, + uiIDA, 1, iPadNotSignedInLive, NULL, NULL, + app.GetStringTable()); + } else { + // Not signed in to PSN + unsigned int uiIDA[1]; + uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; + ui.RequestMessageBox( + IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, + iPadNotSignedInLive, &CGameNetworkManager::MustSignInReturned_1, + (void*)pInviteInfo, app.GetStringTable(), NULL, 0, false); + } + return; + } - // 4J-JEV: Check that all players are authorised for PsPlus, present upsell to players that aren't and try again. - for (unsigned int index = 0; index < XUSER_MAX_COUNT; index++) - { - if ( ProfileManager.IsSignedIn(index) - && !ProfileManager.HasPlayStationPlus(userIndex) ) - { - m_pInviteInfo = (INVITE_INFO *) pInviteInfo; - m_iPlayerInvited = userIndex; - - m_pUpsell = new PsPlusUpsellWrapper(index); - m_pUpsell->displayUpsell(); - - return; - } - } + // 4J-JEV: Check that all players are authorised for PsPlus, present upsell + // to players that aren't and try again. + for (unsigned int index = 0; index < XUSER_MAX_COUNT; index++) { + if (ProfileManager.IsSignedIn(index) && + !ProfileManager.HasPlayStationPlus(userIndex)) { + m_pInviteInfo = (INVITE_INFO*)pInviteInfo; + m_iPlayerInvited = userIndex; + + m_pUpsell = new PsPlusUpsellWrapper(index); + m_pUpsell->displayUpsell(); + + return; + } + } #endif #ifdef __PSVITA__ - // Need to check we're signed in to PSN - bool isSignedInLive = ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()); - if (!isSignedInLive) - { - // Determine why they're not "signed in live" - // MGH - we need to add a new message at some point for connecting when already signed in -// if (ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) -// { -// // Signed in to PSN but not connected (no internet access) -// unsigned int uiIDA[1]; -// uiIDA[0] = IDS_OK; -// ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, NULL, app.GetStringTable()); -// } -// else - { - // Not signed in to PSN - unsigned int uiIDA[1]; - uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; - ui.RequestMessageBox( IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, ProfileManager.GetPrimaryPad(), &CGameNetworkManager::MustSignInReturned_1, (void *)pInviteInfo, app.GetStringTable(), NULL, 0, false); - } - return; - } + // Need to check we're signed in to PSN + bool isSignedInLive = + ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad()); + if (!isSignedInLive) { + // Determine why they're not "signed in live" + // MGH - we need to add a new message at some point for connecting when + // already signed in + // if + // (ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) + // { + // // Signed in to PSN but not connected (no + // internet access) unsigned int uiIDA[1]; uiIDA[0] = IDS_OK; + // ui.RequestMessageBox( IDS_ERROR_NETWORK_TITLE, + // IDS_ERROR_NETWORK, uiIDA, 1, ProfileManager.GetPrimaryPad(), NULL, + // NULL, app.GetStringTable()); + // } + // else + { + // Not signed in to PSN + unsigned int uiIDA[1]; + uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; + ui.RequestMessageBox( + IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 1, + ProfileManager.GetPrimaryPad(), + &CGameNetworkManager::MustSignInReturned_1, (void*)pInviteInfo, + app.GetStringTable(), NULL, 0, false); + } + return; + } #endif + int localUsersMask = 0; + Minecraft* pMinecraft = Minecraft::GetInstance(); + int joiningUsers = 0; - int localUsersMask = 0; - Minecraft *pMinecraft = Minecraft::GetInstance(); - int joiningUsers = 0; + bool noPrivileges = false; + for (unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) { + if (ProfileManager.IsSignedIn(index)) { + // 4J-PB we shouldn't bring any inactive players into the game, + // except for the invited player (who may be an inactive player) 4J + // Stu - If we are not in a game, then bring in all players signed + // in + if (index == userIndex || pMinecraft->localplayers[index] != NULL) { + ++joiningUsers; + if (!ProfileManager.AllowedToPlayMultiplayer(index)) + noPrivileges = true; + localUsersMask |= GetLocalPlayerMask(index); + } + } + } - bool noPrivileges = false; - for(unsigned int index = 0; index < XUSER_MAX_COUNT; ++index) - { - if(ProfileManager.IsSignedIn(index) ) - { - // 4J-PB we shouldn't bring any inactive players into the game, except for the invited player (who may be an inactive player) - // 4J Stu - If we are not in a game, then bring in all players signed in - if(index==userIndex || pMinecraft->localplayers[index]!=NULL ) - { - ++joiningUsers; - if( !ProfileManager.AllowedToPlayMultiplayer(index) ) noPrivileges = true; - localUsersMask |= GetLocalPlayerMask( index ); - } - } - } - - // Check if user-created content is allowed, as we cannot play multiplayer if it's not - bool noUGC = false; - bool bContentRestricted=false; - bool pccAllowed = true; - bool pccFriendsAllowed = true; + // Check if user-created content is allowed, as we cannot play multiplayer + // if it's not + bool noUGC = false; + bool bContentRestricted = false; + bool pccAllowed = true; + bool pccFriendsAllowed = true; #if defined(__PS3__) || defined(__PSVITA__) - ProfileManager.GetChatAndContentRestrictions(userIndex,false,&noUGC,&bContentRestricted,NULL); + ProfileManager.GetChatAndContentRestrictions(userIndex, false, &noUGC, + &bContentRestricted, NULL); #else - ProfileManager.AllowedPlayerCreatedContent(ProfileManager.GetPrimaryPad(),false,&pccAllowed,&pccFriendsAllowed); - if(!pccAllowed && !pccFriendsAllowed) noUGC = true; + ProfileManager.AllowedPlayerCreatedContent( + ProfileManager.GetPrimaryPad(), false, &pccAllowed, &pccFriendsAllowed); + if (!pccAllowed && !pccFriendsAllowed) noUGC = true; #endif - + #if defined(_XBOX) || defined(__PS3__) - if(joiningUsers > 1 && !RenderManager.IsHiDef() && userIndex != ProfileManager.GetPrimaryPad()) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; + if (joiningUsers > 1 && !RenderManager.IsHiDef() && + userIndex != ProfileManager.GetPrimaryPad()) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; - // 4J-PB - it's possible there is no primary pad here, when accepting an invite from the dashboard - ui.RequestMessageBox( IDS_CONNECTION_FAILED, IDS_CONNECTION_FAILED_NO_SD_SPLITSCREEN, uiIDA,1,XUSER_INDEX_ANY,NULL,NULL, app.GetStringTable()); - } - else + // 4J-PB - it's possible there is no primary pad here, when accepting an + // invite from the dashboard + ui.RequestMessageBox(IDS_CONNECTION_FAILED, + IDS_CONNECTION_FAILED_NO_SD_SPLITSCREEN, uiIDA, 1, + XUSER_INDEX_ANY, NULL, NULL, app.GetStringTable()); + } else #endif - if( noUGC ) - { - int messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL; - if(joiningUsers > 1) messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL; + if (noUGC) { + int messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_SINGLE_LOCAL; + if (joiningUsers > 1) + messageText = IDS_NO_USER_CREATED_CONTENT_PRIVILEGE_ALL_LOCAL; - ui.RequestUGCMessageBox(IDS_CONNECTION_FAILED, messageText, XUSER_INDEX_ANY); - } + ui.RequestUGCMessageBox(IDS_CONNECTION_FAILED, messageText, + XUSER_INDEX_ANY); + } #if defined(__PS3__) || defined __PSVITA__ - else if(bContentRestricted) - { - int messageText = IDS_CONTENT_RESTRICTION; - if(joiningUsers > 1) messageText = IDS_CONTENT_RESTRICTION_MULTIPLAYER; + else if (bContentRestricted) { + int messageText = IDS_CONTENT_RESTRICTION; + if (joiningUsers > 1) messageText = IDS_CONTENT_RESTRICTION_MULTIPLAYER; - ui.RequestContentRestrictedMessageBox(IDS_CONNECTION_FAILED, messageText, XUSER_INDEX_ANY); - } + ui.RequestContentRestrictedMessageBox(IDS_CONNECTION_FAILED, + messageText, XUSER_INDEX_ANY); + } #endif - else if(noPrivileges) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; + else if (noPrivileges) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; - // 4J-PB - it's possible there is no primary pad here, when accepting an invite from the dashboard - //StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); - ui.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,XUSER_INDEX_ANY,NULL,NULL, app.GetStringTable()); - } - else - { + // 4J-PB - it's possible there is no primary pad here, when accepting an + // invite from the dashboard + // StorageManager.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + // IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + // uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, + // app.GetStringTable()); + ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA, 1, + XUSER_INDEX_ANY, NULL, NULL, app.GetStringTable()); + } else { #if defined(__ORBIS__) || defined(__PSVITA__) - bool chatRestricted = false; - ProfileManager.GetChatAndContentRestrictions(ProfileManager.GetPrimaryPad(),false,&chatRestricted,NULL,NULL); - if(chatRestricted) - { - ProfileManager.DisplaySystemMessage( SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, ProfileManager.GetPrimaryPad() ); - } + bool chatRestricted = false; + ProfileManager.GetChatAndContentRestrictions( + ProfileManager.GetPrimaryPad(), false, &chatRestricted, NULL, NULL); + if (chatRestricted) { + ProfileManager.DisplaySystemMessage( + SCE_MSG_DIALOG_SYSMSG_TYPE_TRC_PSN_CHAT_RESTRICTION, + ProfileManager.GetPrimaryPad()); + } #endif - if( !g_NetworkManager.IsInSession() ) - { + if (!g_NetworkManager.IsInSession()) { #ifndef __PS3__ - HandleInviteWhenInMenus(userIndex, pInviteInfo); + HandleInviteWhenInMenus(userIndex, pInviteInfo); #else - // PS3 is more complicated here - we need to make sure that the player is online. If they are then we can do the same as the xbox, if not we need to try and get them online and then, if they do sign in, go down the same path - if(ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) - { - HandleInviteWhenInMenus(userIndex, pInviteInfo); - } - else - { - unsigned int uiIDA[2]; - uiIDA[0]=IDS_PRO_NOTONLINE_ACCEPT; - uiIDA[1]=IDS_PRO_NOTONLINE_DECLINE; - ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, ProfileManager.GetPrimaryPad(),&CGameNetworkManager::MustSignInReturned_1,(void *)pInviteInfo, app.GetStringTable()); - } + // PS3 is more complicated here - we need to make sure that the + // player is online. If they are then we can do the same as the + // xbox, if not we need to try and get them online and then, if they + // do sign in, go down the same path + if (ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) { + HandleInviteWhenInMenus(userIndex, pInviteInfo); + } else { + unsigned int uiIDA[2]; + uiIDA[0] = IDS_PRO_NOTONLINE_ACCEPT; + uiIDA[1] = IDS_PRO_NOTONLINE_DECLINE; + ui.RequestMessageBox(IDS_PRO_NOTONLINE_TITLE, + IDS_PRO_NOTONLINE_TEXT, uiIDA, 2, + ProfileManager.GetPrimaryPad(), + &CGameNetworkManager::MustSignInReturned_1, + (void*)pInviteInfo, app.GetStringTable()); + } #endif - } - else - { - app.DebugPrintf("We are already in a multiplayer game...need to leave it\n"); + } else { + app.DebugPrintf( + "We are already in a multiplayer game...need to leave it\n"); -// JoinFromInviteData *joinData = new JoinFromInviteData(); -// joinData->dwUserIndex = dwUserIndex; -// joinData->dwLocalUsersMask = dwLocalUsersMask; -// joinData->pInviteInfo = pInviteInfo; + // JoinFromInviteData *joinData = new + // JoinFromInviteData(); joinData->dwUserIndex = dwUserIndex; + // joinData->dwLocalUsersMask = dwLocalUsersMask; + // joinData->pInviteInfo = pInviteInfo; - // tell the app to process this + // tell the app to process this #ifdef __PSVITA__ - if(((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager)->checkValidInviteData(pInviteInfo)) + if (((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager) + ->checkValidInviteData(pInviteInfo)) #endif - { - app.ProcessInvite(userIndex,localUsersMask,pInviteInfo); - } - } - } + { + app.ProcessInvite(userIndex, localUsersMask, pInviteInfo); + } + } + } } volatile bool waitHere = true; -void CGameNetworkManager::HandleInviteWhenInMenus( int userIndex, const INVITE_INFO *pInviteInfo) -{ - // We are in the root menus somewhere +void CGameNetworkManager::HandleInviteWhenInMenus( + int userIndex, const INVITE_INFO* pInviteInfo) { + // We are in the root menus somewhere #if 0 while( waitHere ) @@ -1780,262 +1866,248 @@ void CGameNetworkManager::HandleInviteWhenInMenus( int userIndex, const INVITE_I } #endif - // if this is the trial game, then we need the user to unlock the full game - if(!ProfileManager.IsFullVersion()) - { - // The marketplace will fail with the primary player set to -1 - ProfileManager.SetPrimaryPad(userIndex); + // if this is the trial game, then we need the user to unlock the full game + if (!ProfileManager.IsFullVersion()) { + // The marketplace will fail with the primary player set to -1 + ProfileManager.SetPrimaryPad(userIndex); - app.SetAction(userIndex,eAppAction_DashboardTrialJoinFromInvite); - } - else - { - ProfileManager.SetPrimaryPad(userIndex); + app.SetAction(userIndex, eAppAction_DashboardTrialJoinFromInvite); + } else { + ProfileManager.SetPrimaryPad(userIndex); - // 4J Stu - If we accept an invite from the main menu before going to play game we need to load the DLC - // These checks are done within the StartInstallDLCProcess - (!app.DLCInstallProcessCompleted() && !app.DLCInstallPending()) app.StartInstallDLCProcess(dwUserIndex); - app.StartInstallDLCProcess(userIndex); + // 4J Stu - If we accept an invite from the main menu before going to + // play game we need to load the DLC These checks are done within the + // StartInstallDLCProcess - (!app.DLCInstallProcessCompleted() && + // !app.DLCInstallPending()) app.StartInstallDLCProcess(dwUserIndex); + app.StartInstallDLCProcess(userIndex); - // 4J Stu - Fix for #10936 - MP Lab: TCR 001: Matchmaking: Player is stuck in a soft-locked state after selecting the guest account when prompted - // The locked profile should not be changed if we are in menus as the main player might sign out in the sign-in ui - //ProfileManager.SetLockedProfile(-1); + // 4J Stu - Fix for #10936 - MP Lab: TCR 001: Matchmaking: Player is + // stuck in a soft-locked state after selecting the guest account when + // prompted The locked profile should not be changed if we are in menus + // as the main player might sign out in the sign-in ui + // ProfileManager.SetLockedProfile(-1); - if(!app.IsLocalMultiplayerAvailable()) - { - bool noPrivileges=!ProfileManager.AllowedToPlayMultiplayer(userIndex); + if (!app.IsLocalMultiplayerAvailable()) { + bool noPrivileges = + !ProfileManager.AllowedToPlayMultiplayer(userIndex); - if(noPrivileges) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - ui.RequestMessageBox( IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, uiIDA,1,ProfileManager.GetPrimaryPad(),NULL,NULL, app.GetStringTable()); - } - else - { - ProfileManager.SetLockedProfile(userIndex); - ProfileManager.SetPrimaryPad(userIndex); + if (noPrivileges) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + ui.RequestMessageBox(IDS_NO_MULTIPLAYER_PRIVILEGE_TITLE, + IDS_NO_MULTIPLAYER_PRIVILEGE_JOIN_TEXT, + uiIDA, 1, ProfileManager.GetPrimaryPad(), + NULL, NULL, app.GetStringTable()); + } else { + ProfileManager.SetLockedProfile(userIndex); + ProfileManager.SetPrimaryPad(userIndex); - int localUsersMask=0; - localUsersMask |= GetLocalPlayerMask( userIndex ); + int localUsersMask = 0; + localUsersMask |= GetLocalPlayerMask(userIndex); - // If the player was signed in before selecting play, we'll not have read the profile yet, so query the sign-in status to get this to happen - ProfileManager.QuerySigninStatus(); + // If the player was signed in before selecting play, we'll not + // have read the profile yet, so query the sign-in status to get + // this to happen + ProfileManager.QuerySigninStatus(); - // 4J-PB - clear any previous connection errors - Minecraft::GetInstance()->clearConnectionFailed(); + // 4J-PB - clear any previous connection errors + Minecraft::GetInstance()->clearConnectionFailed(); - g_NetworkManager.SetLocalGame(false); + g_NetworkManager.SetLocalGame(false); - // change the minecraft player name - Minecraft::GetInstance()->user->name = convStringToWstring( ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); + // change the minecraft player name + Minecraft::GetInstance()->user->name = convStringToWstring( + ProfileManager.GetGamertag(ProfileManager.GetPrimaryPad())); - bool success = g_NetworkManager.JoinGameFromInviteInfo( userIndex, localUsersMask, pInviteInfo ); - if( !success ) - { - app.DebugPrintf( "Failed joining game from invite\n" ); - } - } - } - else - { - // the FromInvite will make the lib decide how many panes to display based on connected pads/signed in players + bool success = g_NetworkManager.JoinGameFromInviteInfo( + userIndex, localUsersMask, pInviteInfo); + if (!success) { + app.DebugPrintf("Failed joining game from invite\n"); + } + } + } else { + // the FromInvite will make the lib decide how many panes to display + // based on connected pads/signed in players #ifdef _XBOX - ProfileManager.RequestSignInUI(true, false, false, false, false,&CGameNetworkManager::JoinFromInvite_SignInReturned, (void *)pInviteInfo,userIndex); + ProfileManager.RequestSignInUI( + true, false, false, false, false, + &CGameNetworkManager::JoinFromInvite_SignInReturned, + (void*)pInviteInfo, userIndex); #else - SignInInfo info; - info.Func = &CGameNetworkManager::JoinFromInvite_SignInReturned; - info.lpParam = (void *)pInviteInfo; - info.requireOnline = true; - app.DebugPrintf("Using fullscreen layer\n"); - ui.NavigateToScene(ProfileManager.GetPrimaryPad(),eUIScene_QuadrantSignin,&info,eUILayer_Alert,eUIGroup_Fullscreen); + SignInInfo info; + info.Func = &CGameNetworkManager::JoinFromInvite_SignInReturned; + info.lpParam = (void*)pInviteInfo; + info.requireOnline = true; + app.DebugPrintf("Using fullscreen layer\n"); + ui.NavigateToScene(ProfileManager.GetPrimaryPad(), + eUIScene_QuadrantSignin, &info, eUILayer_Alert, + eUIGroup_Fullscreen); #endif - } - } + } + } } -void CGameNetworkManager::AddLocalPlayerFailed(int idx, bool serverFull/* = false*/) -{ - Minecraft::GetInstance()->connectionDisconnected(idx, serverFull ? DisconnectPacket::eDisconnect_ServerFull : DisconnectPacket::eDisconnect_ConnectionCreationFailed); +void CGameNetworkManager::AddLocalPlayerFailed(int idx, + bool serverFull /* = false*/) { + Minecraft::GetInstance()->connectionDisconnected( + idx, serverFull + ? DisconnectPacket::eDisconnect_ServerFull + : DisconnectPacket::eDisconnect_ConnectionCreationFailed); } #if defined __PS3__ || defined __PSVITA__ || defined __ORBIS__ -void CGameNetworkManager::HandleDisconnect(bool bLostRoomOnly,bool bPSNSignout) +void CGameNetworkManager::HandleDisconnect(bool bLostRoomOnly, bool bPSNSignout) #else void CGameNetworkManager::HandleDisconnect(bool bLostRoomOnly) #endif { - int iPrimaryPlayer = g_NetworkManager.GetPrimaryPad(); + int iPrimaryPlayer = g_NetworkManager.GetPrimaryPad(); - if((g_NetworkManager.GetLockedProfile()!=-1) && iPrimaryPlayer!=-1 && g_NetworkManager.IsInSession() ) - { - m_bLastDisconnectWasLostRoomOnly = bLostRoomOnly; + if ((g_NetworkManager.GetLockedProfile() != -1) && iPrimaryPlayer != -1 && + g_NetworkManager.IsInSession()) { + m_bLastDisconnectWasLostRoomOnly = bLostRoomOnly; #if defined __PS3__ || defined __PSVITA__ || defined __ORBIS__ - m_bSignedOutofPSN=bPSNSignout; + m_bSignedOutofPSN = bPSNSignout; #endif - app.SetAction(iPrimaryPlayer,eAppAction_EthernetDisconnected); - } - else - { - m_bLastDisconnectWasLostRoomOnly = false; - } + app.SetAction(iPrimaryPlayer, eAppAction_EthernetDisconnected); + } else { + m_bLastDisconnectWasLostRoomOnly = false; + } } -int CGameNetworkManager::GetPrimaryPad() -{ - return ProfileManager.GetPrimaryPad(); +int CGameNetworkManager::GetPrimaryPad() { + return ProfileManager.GetPrimaryPad(); } -int CGameNetworkManager::GetLockedProfile() -{ - return ProfileManager.GetLockedProfile(); +int CGameNetworkManager::GetLockedProfile() { + return ProfileManager.GetLockedProfile(); } -bool CGameNetworkManager::IsSignedInLive(int playerIdx) -{ - return ProfileManager.IsSignedInLive(playerIdx); +bool CGameNetworkManager::IsSignedInLive(int playerIdx) { + return ProfileManager.IsSignedInLive(playerIdx); } -bool CGameNetworkManager::AllowedToPlayMultiplayer(int playerIdx) -{ - return ProfileManager.AllowedToPlayMultiplayer(playerIdx); +bool CGameNetworkManager::AllowedToPlayMultiplayer(int playerIdx) { + return ProfileManager.AllowedToPlayMultiplayer(playerIdx); } -char *CGameNetworkManager::GetOnlineName(int playerIdx) -{ - return ProfileManager.GetGamertag(playerIdx); +char* CGameNetworkManager::GetOnlineName(int playerIdx) { + return ProfileManager.GetGamertag(playerIdx); } -void CGameNetworkManager::ServerReadyCreate(bool create) -{ - m_hServerReadyEvent = ( create ? ( new C4JThread::Event ) : NULL ); +void CGameNetworkManager::ServerReadyCreate(bool create) { + m_hServerReadyEvent = (create ? (new C4JThread::Event) : NULL); } -void CGameNetworkManager::ServerReady() -{ - if (m_hServerReadyEvent != NULL) - { - m_hServerReadyEvent->Set(); - } - else - { - app.DebugPrintf("[NET] Warning: ServerReady() called but m_hServerReadyEvent is NULL\n"); - } +void CGameNetworkManager::ServerReady() { + if (m_hServerReadyEvent != NULL) { + m_hServerReadyEvent->Set(); + } else { + app.DebugPrintf( + "[NET] Warning: ServerReady() called but m_hServerReadyEvent is " + "NULL\n"); + } } -void CGameNetworkManager::ServerReadyWait() -{ - if (m_hServerReadyEvent != NULL) - { - m_hServerReadyEvent->WaitForSignal(INFINITE); - } - else - { - app.DebugPrintf("[NET] Warning: ServerReadyWait() called but m_hServerReadyEvent is NULL\n"); - } +void CGameNetworkManager::ServerReadyWait() { + if (m_hServerReadyEvent != NULL) { + m_hServerReadyEvent->WaitForSignal(INFINITE); + } else { + app.DebugPrintf( + "[NET] Warning: ServerReadyWait() called but m_hServerReadyEvent " + "is NULL\n"); + } } -void CGameNetworkManager::ServerReadyDestroy() -{ - delete m_hServerReadyEvent; - m_hServerReadyEvent = NULL; +void CGameNetworkManager::ServerReadyDestroy() { + delete m_hServerReadyEvent; + m_hServerReadyEvent = NULL; } -bool CGameNetworkManager::ServerReadyValid() -{ - return ( m_hServerReadyEvent != NULL ); +bool CGameNetworkManager::ServerReadyValid() { + return (m_hServerReadyEvent != NULL); } -void CGameNetworkManager::ServerStoppedCreate(bool create) -{ - m_hServerStoppedEvent = ( create ? ( new C4JThread::Event ) : NULL ); +void CGameNetworkManager::ServerStoppedCreate(bool create) { + m_hServerStoppedEvent = (create ? (new C4JThread::Event) : NULL); } -void CGameNetworkManager::ServerStopped() -{ - if (m_hServerStoppedEvent != NULL) - { - m_hServerStoppedEvent->Set(); - } - else - { - app.DebugPrintf("[NET] Warning: ServerStopped() called but m_hServerStoppedEvent is NULL\n"); - } +void CGameNetworkManager::ServerStopped() { + if (m_hServerStoppedEvent != NULL) { + m_hServerStoppedEvent->Set(); + } else { + app.DebugPrintf( + "[NET] Warning: ServerStopped() called but m_hServerStoppedEvent " + "is NULL\n"); + } } -void CGameNetworkManager::ServerStoppedWait() -{ - // If this is called from the main thread, then this won't be ticking anything which can mean that the storage manager state can't progress. - // This means that the server thread we are waiting on won't ever finish, as it might be locked waiting for this to complete itself. - // Do some ticking here then if this is the case. - if( C4JThread::isMainThread() ) - { - int result = WAIT_TIMEOUT; - do - { +void CGameNetworkManager::ServerStoppedWait() { + // If this is called from the main thread, then this won't be ticking + // anything which can mean that the storage manager state can't progress. + // This means that the server thread we are waiting on won't ever finish, as + // it might be locked waiting for this to complete itself. Do some ticking + // here then if this is the case. + if (C4JThread::isMainThread()) { + int result = WAIT_TIMEOUT; + do { #ifndef _XBOX - RenderManager.StartFrame(); + RenderManager.StartFrame(); #endif - result = m_hServerStoppedEvent->WaitForSignal(20); - // Tick some simple things - ProfileManager.Tick(); - StorageManager.Tick(); - InputManager.Tick(); - RenderManager.Tick(); - ui.tick(); - ui.render(); - RenderManager.Present(); - } while( result == WAIT_TIMEOUT ); - } - else - { - if (m_hServerStoppedEvent != NULL) - { - m_hServerStoppedEvent->WaitForSignal(INFINITE); - } - else - { - app.DebugPrintf("[NET] Warning: ServerStoppedWait() called but m_hServerStoppedEvent is NULL\n"); - } - } + result = m_hServerStoppedEvent->WaitForSignal(20); + // Tick some simple things + ProfileManager.Tick(); + StorageManager.Tick(); + InputManager.Tick(); + RenderManager.Tick(); + ui.tick(); + ui.render(); + RenderManager.Present(); + } while (result == WAIT_TIMEOUT); + } else { + if (m_hServerStoppedEvent != NULL) { + m_hServerStoppedEvent->WaitForSignal(INFINITE); + } else { + app.DebugPrintf( + "[NET] Warning: ServerStoppedWait() called but " + "m_hServerStoppedEvent is NULL\n"); + } + } } -void CGameNetworkManager::ServerStoppedDestroy() -{ - delete m_hServerStoppedEvent; - m_hServerStoppedEvent = NULL; +void CGameNetworkManager::ServerStoppedDestroy() { + delete m_hServerStoppedEvent; + m_hServerStoppedEvent = NULL; } -bool CGameNetworkManager::ServerStoppedValid() -{ - return ( m_hServerStoppedEvent != NULL ); +bool CGameNetworkManager::ServerStoppedValid() { + return (m_hServerStoppedEvent != NULL); } -int CGameNetworkManager::GetJoiningReadyPercentage() -{ - return s_pPlatformNetworkManager->GetJoiningReadyPercentage(); +int CGameNetworkManager::GetJoiningReadyPercentage() { + return s_pPlatformNetworkManager->GetJoiningReadyPercentage(); } #ifndef _XBOX -void CGameNetworkManager::FakeLocalPlayerJoined() -{ - s_pPlatformNetworkManager->FakeLocalPlayerJoined(); +void CGameNetworkManager::FakeLocalPlayerJoined() { + s_pPlatformNetworkManager->FakeLocalPlayerJoined(); } #endif #ifdef __PSVITA__ -bool CGameNetworkManager::usingAdhocMode() -{ - return ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager)->usingAdhocMode(); +bool CGameNetworkManager::usingAdhocMode() { + return ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager) + ->usingAdhocMode(); } -void CGameNetworkManager::setAdhocMode(bool bAdhoc) -{ - ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager)->setAdhocMode(bAdhoc); +void CGameNetworkManager::setAdhocMode(bool bAdhoc) { + ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager) + ->setAdhocMode(bAdhoc); } -void CGameNetworkManager::startAdhocMatching() -{ - ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager)->startAdhocMatching(); +void CGameNetworkManager::startAdhocMatching() { + ((CPlatformNetworkManagerSony*)s_pPlatformNetworkManager) + ->startAdhocMatching(); } #endif diff --git a/Minecraft.Client/Platform/Common/Network/GameNetworkManager.h b/Minecraft.Client/Platform/Common/Network/GameNetworkManager.h index 7110b50ad..994dc11b2 100644 --- a/Minecraft.Client/Platform/Common/Network/GameNetworkManager.h +++ b/Minecraft.Client/Platform/Common/Network/GameNetworkManager.h @@ -1,5 +1,5 @@ #pragma once -//using namespace std; +// using namespace std; #include #ifndef __linux__ #include @@ -24,209 +24,235 @@ class ClientConnection; class Minecraft; +// This class implements the game-side interface to the networking system. As +// such, it is platform independent and may contain bits of game-side code where +// appropriate. It shouldn't ever reference any platform specifics of the +// network implementation (eg QNET), rather it should interface with an +// implementation of PlatformNetworkManager to provide this functionality. -// This class implements the game-side interface to the networking system. As such, it is platform independent and may contain bits of game-side code where appropriate. -// It shouldn't ever reference any platform specifics of the network implementation (eg QNET), rather it should interface with an implementation of PlatformNetworkManager to -// provide this functionality. - -class CGameNetworkManager -{ +class CGameNetworkManager { #ifdef _XBOX - friend class CPlatformNetworkManagerXbox; + friend class CPlatformNetworkManagerXbox; #elif defined __PS3__ || defined __ORBIS__ || defined __PSVITA__ - friend class CPlatformNetworkManagerSony; + friend class CPlatformNetworkManagerSony; #elif defined _DURANGO - friend class CPlatformNetworkManagerDurango; + friend class CPlatformNetworkManagerDurango; #else - friend class CPlatformNetworkManagerStub; + friend class CPlatformNetworkManagerStub; #endif public: - CGameNetworkManager(); - // Misc high level flow + CGameNetworkManager(); + // Misc high level flow - typedef enum - { - JOINGAME_SUCCESS, - JOINGAME_FAIL_GENERAL, - JOINGAME_FAIL_SERVER_FULL - } eJoinGameResult; + typedef enum { + JOINGAME_SUCCESS, + JOINGAME_FAIL_GENERAL, + JOINGAME_FAIL_SERVER_FULL + } eJoinGameResult; - void Initialise(); - void Terminate(); - void DoWork(); - bool _RunNetworkGame(void *lpParameter); - bool StartNetworkGame(Minecraft *minecraft, void *lpParameter); - int CorrectErrorIDS(int IDS); + void Initialise(); + void Terminate(); + void DoWork(); + bool _RunNetworkGame(void* lpParameter); + bool StartNetworkGame(Minecraft* minecraft, void* lpParameter); + int CorrectErrorIDS(int IDS); - // Player management + // Player management - static int GetLocalPlayerMask(int playerIndex); - int GetPlayerCount(); - int GetOnlinePlayerCount(); - bool AddLocalPlayerByUserIndex( int userIndex ); - bool RemoveLocalPlayerByUserIndex( int userIndex ); - INetworkPlayer *GetLocalPlayerByUserIndex(int userIndex ); - INetworkPlayer *GetPlayerByIndex(int playerIndex); - INetworkPlayer *GetPlayerByXuid(PlayerUID xuid); - INetworkPlayer *GetPlayerBySmallId(unsigned char smallId); - std::wstring GetDisplayNameByGamertag(std::wstring gamertag); - INetworkPlayer *GetHostPlayer(); - void RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); - void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); - void HandleSignInChange(); - bool ShouldMessageForFullSession(); + static int GetLocalPlayerMask(int playerIndex); + int GetPlayerCount(); + int GetOnlinePlayerCount(); + bool AddLocalPlayerByUserIndex(int userIndex); + bool RemoveLocalPlayerByUserIndex(int userIndex); + INetworkPlayer* GetLocalPlayerByUserIndex(int userIndex); + INetworkPlayer* GetPlayerByIndex(int playerIndex); + INetworkPlayer* GetPlayerByXuid(PlayerUID xuid); + INetworkPlayer* GetPlayerBySmallId(unsigned char smallId); + std::wstring GetDisplayNameByGamertag(std::wstring gamertag); + INetworkPlayer* GetHostPlayer(); + void RegisterPlayerChangedCallback(int iPad, + void (*callback)(void* callbackParam, + INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); + void UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); + void HandleSignInChange(); + bool ShouldMessageForFullSession(); - // State management + // State management - bool IsInSession(); - bool IsInGameplay(); - bool IsLeavingGame(); - bool IsReadyToPlayOrIdle(); + bool IsInSession(); + bool IsInGameplay(); + bool IsLeavingGame(); + bool IsReadyToPlayOrIdle(); - // Hosting and game type + // Hosting and game type - bool SetLocalGame(bool isLocal); - bool IsLocalGame(); - void SetPrivateGame(bool isPrivate); - bool IsPrivateGame(); - void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); - bool IsHost(); - bool IsInStatsEnabledSession(); + bool SetLocalGame(bool isLocal); + bool IsLocalGame(); + void SetPrivateGame(bool isPrivate); + bool IsPrivateGame(); + void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0); + bool IsHost(); + bool IsInStatsEnabledSession(); - // Client session discovery + // Client session discovery - bool SessionHasSpace(unsigned int spaceRequired = 1); - std::vector *GetSessionList(int iPad, int localPlayers, bool partyOnly); - bool GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession); - void SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ); - void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ); - void ForceFriendsSessionRefresh(); - - // Session joining and leaving + bool SessionHasSpace(unsigned int spaceRequired = 1); + std::vector* GetSessionList(int iPad, int localPlayers, + bool partyOnly); + bool GetGameSessionInfo(int iPad, SessionID sessionId, + FriendSessionInfo* foundSession); + void SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam); + void GetFullFriendSessionInfo(FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, + void* pParam), + void* pParam); + void ForceFriendsSessionRefresh(); - bool JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo); - eJoinGameResult JoinGame(FriendSessionInfo *searchResult, int localUsersMask); - static void CancelJoinGame(void *lpParam); // Not part of the shared interface - bool LeaveGame(bool bMigrateHost); - static int JoinFromInvite_SignInReturned(void *pParam,bool bContinue, int iPad); - void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); - void SendInviteGUI(int iPad); - void ResetLeavingGame(); + // Session joining and leaving - // Threads - - bool IsNetworkThreadRunning(); - static int RunNetworkGameThreadProc( void* lpParameter ); - static int ServerThreadProc( void* lpParameter ); - static int ExitAndJoinFromInviteThreadProc( void* lpParam ); + bool JoinGameFromInviteInfo(int userIndex, int userMask, + const INVITE_INFO* pInviteInfo); + eJoinGameResult JoinGame(FriendSessionInfo* searchResult, + int localUsersMask); + static void CancelJoinGame( + void* lpParam); // Not part of the shared interface + bool LeaveGame(bool bMigrateHost); + static int JoinFromInvite_SignInReturned(void* pParam, bool bContinue, + int iPad); + void UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving = NULL); + void SendInviteGUI(int iPad); + void ResetLeavingGame(); -#if (defined __PS3__) || (defined __ORBIS__) || (defined __PSVITA__) - static int MustSignInReturned_0(void *pParam,int iPad,C4JStorage::EMessageResult result); - static int PSNSignInReturned_0(void* pParam, bool bContinue, int iPad); + // Threads - static int MustSignInReturned_1(void *pParam,int iPad,C4JStorage::EMessageResult result); - static int PSNSignInReturned_1(void* pParam, bool bContinue, int iPad); + bool IsNetworkThreadRunning(); + static int RunNetworkGameThreadProc(void* lpParameter); + static int ServerThreadProc(void* lpParameter); + static int ExitAndJoinFromInviteThreadProc(void* lpParam); + +#if (defined __PS3__) || (defined __ORBIS__) || (defined __PSVITA__) + static int MustSignInReturned_0(void* pParam, int iPad, + C4JStorage::EMessageResult result); + static int PSNSignInReturned_0(void* pParam, bool bContinue, int iPad); + + static int MustSignInReturned_1(void* pParam, int iPad, + C4JStorage::EMessageResult result); + static int PSNSignInReturned_1(void* pParam, bool bContinue, int iPad); #endif - static void _LeaveGame(); - static int ChangeSessionTypeThreadProc( void* lpParam ); + static void _LeaveGame(); + static int ChangeSessionTypeThreadProc(void* lpParam); - // System flags + // System flags - void SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index); - bool SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index); + void SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index); + bool SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index); - // Events + // Events - void ServerReadyCreate(bool create); // Create the signal (or set to NULL) - void ServerReady(); // Signal that we are ready - void ServerReadyWait(); // Wait for the signal - void ServerReadyDestroy(); // Destroy signal - bool ServerReadyValid(); // Is non-NULL + void ServerReadyCreate(bool create); // Create the signal (or set to NULL) + void ServerReady(); // Signal that we are ready + void ServerReadyWait(); // Wait for the signal + void ServerReadyDestroy(); // Destroy signal + bool ServerReadyValid(); // Is non-NULL - void ServerStoppedCreate(bool create); // Create the signal - void ServerStopped(); // Signal that we are ready - void ServerStoppedWait(); // Wait for the signal - void ServerStoppedDestroy(); // Destroy signal - bool ServerStoppedValid(); // Is non-NULL + void ServerStoppedCreate(bool create); // Create the signal + void ServerStopped(); // Signal that we are ready + void ServerStoppedWait(); // Wait for the signal + void ServerStoppedDestroy(); // Destroy signal + bool ServerStoppedValid(); // Is non-NULL #ifdef __PSVITA__ - static bool usingAdhocMode(); - static void setAdhocMode(bool bAdhoc); - static void startAdhocMatching(); + static bool usingAdhocMode(); + static void setAdhocMode(bool bAdhoc); + static void startAdhocMatching(); #endif - // Debug output + // Debug output - std::wstring GatherStats(); - void renderQueueMeter(); - std::wstring GatherRTTStats(); + std::wstring GatherStats(); + void renderQueueMeter(); + std::wstring GatherRTTStats(); - // GUI debug output + // GUI debug output - // Used for debugging output - static const int messageQueue_length = 512; - static __int64 messageQueue[messageQueue_length]; - static const int byteQueue_length = 512; + // Used for debugging output + static const int messageQueue_length = 512; + static __int64 messageQueue[messageQueue_length]; + static const int byteQueue_length = 512; static __int64 byteQueue[byteQueue_length]; - static int messageQueuePos; + static int messageQueuePos; - // Methods called from PlatformNetworkManager + // Methods called from PlatformNetworkManager private: - void StateChange_AnyToHosting(); - void StateChange_AnyToJoining(); - void StateChange_JoiningToIdle(CPlatformNetworkManager::eJoinFailedReason reason); - void StateChange_AnyToStarting(); - void StateChange_AnyToEnding(bool bStateWasPlaying); - void StateChange_AnyToIdle(); - void CreateSocket( INetworkPlayer *pNetworkPlayer, bool localPlayer ); - void CloseConnection( INetworkPlayer *pNetworkPlayer ); - void PlayerJoining( INetworkPlayer *pNetworkPlayer ); - void PlayerLeaving( INetworkPlayer *pNetworkPlayer ); - void HostChanged(); - void WriteStats( INetworkPlayer *pNetworkPlayer ); - void GameInviteReceived( int userIndex, const INVITE_INFO *pInviteInfo); - void HandleInviteWhenInMenus( int userIndex, const INVITE_INFO *pInviteInfo); - void AddLocalPlayerFailed(int idx, bool serverFull = false); + void StateChange_AnyToHosting(); + void StateChange_AnyToJoining(); + void StateChange_JoiningToIdle( + CPlatformNetworkManager::eJoinFailedReason reason); + void StateChange_AnyToStarting(); + void StateChange_AnyToEnding(bool bStateWasPlaying); + void StateChange_AnyToIdle(); + void CreateSocket(INetworkPlayer* pNetworkPlayer, bool localPlayer); + void CloseConnection(INetworkPlayer* pNetworkPlayer); + void PlayerJoining(INetworkPlayer* pNetworkPlayer); + void PlayerLeaving(INetworkPlayer* pNetworkPlayer); + void HostChanged(); + void WriteStats(INetworkPlayer* pNetworkPlayer); + void GameInviteReceived(int userIndex, const INVITE_INFO* pInviteInfo); + void HandleInviteWhenInMenus(int userIndex, const INVITE_INFO* pInviteInfo); + void AddLocalPlayerFailed(int idx, bool serverFull = false); #if defined __PS3__ || defined __PSVITA__ || defined __ORBIS__ - void HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut); + void HandleDisconnect(bool bLostRoomOnly, bool bPSNSignOut); #else - void HandleDisconnect(bool bLostRoomOnly); + void HandleDisconnect(bool bLostRoomOnly); #endif - int GetPrimaryPad(); - int GetLockedProfile(); - bool IsSignedInLive(int playerIdx); - bool AllowedToPlayMultiplayer(int playerIdx); - char *GetOnlineName(int playerIdx); + int GetPrimaryPad(); + int GetLockedProfile(); + bool IsSignedInLive(int playerIdx); + bool AllowedToPlayMultiplayer(int playerIdx); + char* GetOnlineName(int playerIdx); - C4JThread::Event* m_hServerStoppedEvent; - C4JThread::Event* m_hServerReadyEvent; - bool m_bInitialised; + C4JThread::Event* m_hServerStoppedEvent; + C4JThread::Event* m_hServerReadyEvent; + bool m_bInitialised; #ifdef _XBOX_ONE public: - void SetFullSessionMessageOnNextSessionChange() { m_bFullSessionMessageOnNextSessionChange = true; } + void SetFullSessionMessageOnNextSessionChange() { + m_bFullSessionMessageOnNextSessionChange = true; + } #endif private: - float m_lastPlayerEventTimeStart; // For telemetry - static CPlatformNetworkManager *s_pPlatformNetworkManager; - bool m_bNetworkThreadRunning; - int GetJoiningReadyPercentage(); - bool m_bLastDisconnectWasLostRoomOnly; - bool m_bFullSessionMessageOnNextSessionChange; + float m_lastPlayerEventTimeStart; // For telemetry + static CPlatformNetworkManager* s_pPlatformNetworkManager; + bool m_bNetworkThreadRunning; + int GetJoiningReadyPercentage(); + bool m_bLastDisconnectWasLostRoomOnly; + bool m_bFullSessionMessageOnNextSessionChange; #if defined __PS3__ || defined __PSVITA__ || defined __ORBIS__ - bool m_bSignedOutofPSN; + bool m_bSignedOutofPSN; #endif #ifdef __ORBIS__ - PsPlusUpsellWrapper *m_pUpsell; - INVITE_INFO *m_pInviteInfo; - int m_iPlayerInvited; + PsPlusUpsellWrapper* m_pUpsell; + INVITE_INFO* m_pInviteInfo; + int m_iPlayerInvited; #endif public: #ifndef _XBOX - void FakeLocalPlayerJoined(); // Temporary method whilst we don't have real networking to make this happen + void FakeLocalPlayerJoined(); // Temporary method whilst we don't have real + // networking to make this happen #endif }; diff --git a/Minecraft.Client/Platform/Common/Network/NetworkPlayerInterface.h b/Minecraft.Client/Platform/Common/Network/NetworkPlayerInterface.h index 28db131e9..e63ac5870 100644 --- a/Minecraft.Client/Platform/Common/Network/NetworkPlayerInterface.h +++ b/Minecraft.Client/Platform/Common/Network/NetworkPlayerInterface.h @@ -2,30 +2,34 @@ class Socket; -// This is the platform independent interface for dealing with players within a network game. This should be used directly by game code (and GameNetworkManager) rather than the platform-specific implementations. +// This is the platform independent interface for dealing with players within a +// network game. This should be used directly by game code (and +// GameNetworkManager) rather than the platform-specific implementations. -class INetworkPlayer -{ +class INetworkPlayer { public: - virtual ~INetworkPlayer() {} - virtual unsigned char GetSmallId() = 0; - virtual void SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority) = 0; - virtual bool IsSameSystem(INetworkPlayer *player) = 0; - virtual int GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ) = 0; - virtual int GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ) = 0; - virtual int GetCurrentRtt() = 0; - virtual bool IsHost() = 0; - virtual bool IsGuest() = 0; - virtual bool IsLocal() = 0; - virtual int GetSessionIndex() = 0; - virtual bool IsTalking() = 0; - virtual bool IsMutedByLocalUser(int userIndex) = 0; - virtual bool HasVoice() = 0; - virtual bool HasCamera() = 0; - virtual int GetUserIndex() = 0; - virtual void SetSocket(Socket *pSocket) = 0; - virtual Socket *GetSocket() = 0; - virtual const wchar_t *GetOnlineName() = 0; - virtual std::wstring GetDisplayName() = 0; - virtual PlayerUID GetUID() = 0; + virtual ~INetworkPlayer() {} + virtual unsigned char GetSmallId() = 0; + virtual void SendData(INetworkPlayer* player, const void* pvData, + int dataSize, bool lowPriority) = 0; + virtual bool IsSameSystem(INetworkPlayer* player) = 0; + virtual int GetSendQueueSizeBytes(INetworkPlayer* player, + bool lowPriority) = 0; + virtual int GetSendQueueSizeMessages(INetworkPlayer* player, + bool lowPriority) = 0; + virtual int GetCurrentRtt() = 0; + virtual bool IsHost() = 0; + virtual bool IsGuest() = 0; + virtual bool IsLocal() = 0; + virtual int GetSessionIndex() = 0; + virtual bool IsTalking() = 0; + virtual bool IsMutedByLocalUser(int userIndex) = 0; + virtual bool HasVoice() = 0; + virtual bool HasCamera() = 0; + virtual int GetUserIndex() = 0; + virtual void SetSocket(Socket* pSocket) = 0; + virtual Socket* GetSocket() = 0; + virtual const wchar_t* GetOnlineName() = 0; + virtual std::wstring GetDisplayName() = 0; + virtual PlayerUID GetUID() = 0; }; diff --git a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerInterface.h b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerInterface.h index 6b9aa04bb..017c993dc 100644 --- a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerInterface.h +++ b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerInterface.h @@ -1,9 +1,9 @@ #pragma once -//using namespace std; +// using namespace std; #include #ifndef __linux__ #include -#endif // __linux__ +#endif // __linux__ #include "../../Minecraft.World/Util/C4JThread.h" #include "NetworkPlayerInterface.h" #include "SessionInfo.h" @@ -12,117 +12,139 @@ class ClientConnection; class Minecraft; class CGameNetworkManager; -// This is the interface to be implemented by the platform-specific versions of the PlatformNetworkManagers. This API is used directly by GameNetworkManager so that -// it can remain as platform independent as possible. +// This is the interface to be implemented by the platform-specific versions of +// the PlatformNetworkManagers. This API is used directly by GameNetworkManager +// so that it can remain as platform independent as possible. -// This value should be incremented if the server version changes, or the game session data changes +// This value should be incremented if the server version changes, or the game +// session data changes #define MINECRAFT_NET_VERSION VER_NETWORK - -typedef struct _SearchForGamesData -{ - unsigned int sessionIDCount; - XSESSION_SEARCHRESULT_HEADER *searchBuffer; - XNQOS **ppQos; - SessionID *sessionIDList; - XOVERLAPPED *pOverlapped; +typedef struct _SearchForGamesData { + unsigned int sessionIDCount; + XSESSION_SEARCHRESULT_HEADER* searchBuffer; + XNQOS** ppQos; + SessionID* sessionIDList; + XOVERLAPPED* pOverlapped; } SearchForGamesData; -class CPlatformNetworkManager -{ - friend class CGameNetworkManager; +class CPlatformNetworkManager { + friend class CGameNetworkManager; + public: + typedef enum { + JOIN_FAILED_SERVER_FULL, + JOIN_FAILED_INSUFFICIENT_PRIVILEGES, + JOIN_FAILED_NONSPECIFIC, + } eJoinFailedReason; - typedef enum - { - JOIN_FAILED_SERVER_FULL, - JOIN_FAILED_INSUFFICIENT_PRIVILEGES, - JOIN_FAILED_NONSPECIFIC, - } eJoinFailedReason; + virtual bool Initialise(CGameNetworkManager* pGameNetworkManager, + int flagIndexSize) = 0; + virtual void Terminate() = 0; + virtual int GetJoiningReadyPercentage() = 0; + virtual int CorrectErrorIDS(int IDS) = 0; - virtual bool Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize) = 0; - virtual void Terminate() = 0; - virtual int GetJoiningReadyPercentage() = 0; - virtual int CorrectErrorIDS(int IDS) = 0; + virtual void DoWork() = 0; + virtual int GetPlayerCount() = 0; + virtual int GetOnlinePlayerCount() = 0; + virtual int GetLocalPlayerMask(int playerIndex) = 0; + virtual bool AddLocalPlayerByUserIndex(int userIndex) = 0; + virtual bool RemoveLocalPlayerByUserIndex(int userIndex) = 0; + virtual INetworkPlayer* GetLocalPlayerByUserIndex(int userIndex) = 0; + virtual INetworkPlayer* GetPlayerByIndex(int playerIndex) = 0; + virtual INetworkPlayer* GetPlayerByXuid(PlayerUID xuid) = 0; + virtual INetworkPlayer* GetPlayerBySmallId(unsigned char smallId) = 0; + virtual bool ShouldMessageForFullSession() = 0; - virtual void DoWork() = 0; - virtual int GetPlayerCount() = 0; - virtual int GetOnlinePlayerCount() = 0; - virtual int GetLocalPlayerMask(int playerIndex) = 0; - virtual bool AddLocalPlayerByUserIndex( int userIndex ) = 0; - virtual bool RemoveLocalPlayerByUserIndex( int userIndex ) = 0; - virtual INetworkPlayer *GetLocalPlayerByUserIndex( int userIndex ) = 0; - virtual INetworkPlayer *GetPlayerByIndex(int playerIndex) = 0; - virtual INetworkPlayer * GetPlayerByXuid(PlayerUID xuid) = 0; - virtual INetworkPlayer * GetPlayerBySmallId(unsigned char smallId) = 0; - virtual bool ShouldMessageForFullSession() = 0; + virtual INetworkPlayer* GetHostPlayer() = 0; + virtual bool IsHost() = 0; + virtual bool JoinGameFromInviteInfo(int userIndex, int userMask, + const INVITE_INFO* pInviteInfo) = 0; + virtual bool LeaveGame(bool bMigrateHost) = 0; - virtual INetworkPlayer *GetHostPlayer() = 0; - virtual bool IsHost() = 0; - virtual bool JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo) = 0; - virtual bool LeaveGame(bool bMigrateHost) = 0; + virtual bool IsInSession() = 0; + virtual bool IsInGameplay() = 0; + virtual bool IsReadyToPlayOrIdle() = 0; + virtual bool IsInStatsEnabledSession() = 0; + virtual bool SessionHasSpace(unsigned int spaceRequired = 1) = 0; + virtual void SendInviteGUI(int quadrant) = 0; + virtual bool IsAddingPlayer() = 0; - virtual bool IsInSession() = 0; - virtual bool IsInGameplay() = 0; - virtual bool IsReadyToPlayOrIdle() = 0; - virtual bool IsInStatsEnabledSession() = 0; - virtual bool SessionHasSpace(unsigned int spaceRequired = 1) = 0; - virtual void SendInviteGUI(int quadrant) = 0; - virtual bool IsAddingPlayer() = 0; + virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0) = 0; + virtual int JoinGame(FriendSessionInfo* searchResult, int dwLocalUsersMask, + int dwPrimaryUserIndex) = 0; + virtual void CancelJoinGame() {}; + virtual bool SetLocalGame(bool isLocal) = 0; + virtual bool IsLocalGame() = 0; + virtual void SetPrivateGame(bool isPrivate) = 0; + virtual bool IsPrivateGame() = 0; + virtual bool IsLeavingGame() = 0; + virtual void ResetLeavingGame() = 0; - virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0) = 0; - virtual int JoinGame(FriendSessionInfo *searchResult, int dwLocalUsersMask, int dwPrimaryUserIndex ) = 0; - virtual void CancelJoinGame() {}; - virtual bool SetLocalGame(bool isLocal) = 0; - virtual bool IsLocalGame() = 0; - virtual void SetPrivateGame(bool isPrivate) = 0; - virtual bool IsPrivateGame() = 0; - virtual bool IsLeavingGame() = 0; - virtual void ResetLeavingGame() = 0; + virtual void RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) = 0; + virtual void UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) = 0; - virtual void RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) = 0; - virtual void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) = 0; + virtual void HandleSignInChange() = 0; - virtual void HandleSignInChange() = 0; - - virtual bool _RunNetworkGame() = 0; + virtual bool _RunNetworkGame() = 0; private: - virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom) = 0; - virtual void _HostGame(int usersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0) = 0; - virtual bool _StartGame() = 0; - + virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom) = 0; + virtual void _HostGame( + int usersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0) = 0; + virtual bool _StartGame() = 0; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL) = 0; + virtual void UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving = NULL) = 0; private: - virtual bool RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ) = 0; + virtual bool RemoveLocalPlayer(INetworkPlayer* pNetworkPlayer) = 0; public: - virtual void SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) = 0; - virtual bool SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) = 0; + virtual void SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index) = 0; + virtual bool SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index) = 0; - virtual std::wstring GatherStats() = 0; - virtual std::wstring GatherRTTStats() = 0; + virtual std::wstring GatherStats() = 0; + virtual std::wstring GatherRTTStats() = 0; -private: - virtual void SetSessionTexturePackParentId( int id ) = 0; - virtual void SetSessionSubTexturePackId( int id ) = 0; - virtual void Notify(int ID, ULONG_PTR Param) = 0; +private: + virtual void SetSessionTexturePackParentId(int id) = 0; + virtual void SetSessionSubTexturePackId(int id) = 0; + virtual void Notify(int ID, ULONG_PTR Param) = 0; public: - virtual std::vector *GetSessionList(int iPad, int localPlayers, bool partyOnly) = 0; - virtual bool GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession) = 0; - virtual void SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ) = 0; - virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) = 0; - virtual void ForceFriendsSessionRefresh() = 0; + virtual std::vector* GetSessionList(int iPad, + int localPlayers, + bool partyOnly) = 0; + virtual bool GetGameSessionInfo(int iPad, SessionID sessionId, + FriendSessionInfo* foundSession) = 0; + virtual void SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam) = 0; + virtual void GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), + void* pParam) = 0; + virtual void ForceFriendsSessionRefresh() = 0; #ifndef _XBOX - virtual void FakeLocalPlayerJoined() {}; // Temporary method whilst we don't have real networking to make this happen + virtual void FakeLocalPlayerJoined() { + }; // Temporary method whilst we don't have real networking to make this + // happen #endif #ifdef _DURANGO - virtual std::wstring GetDisplayNameByGamertag(std::wstring gamertag) = 0; + virtual std::wstring GetDisplayNameByGamertag(std::wstring gamertag) = 0; #endif }; diff --git a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.cpp b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.cpp index f50d09559..e8f35b3dc 100644 --- a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.cpp +++ b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.cpp @@ -1,649 +1,580 @@ -#include "../../Minecraft.World/Platform/stdafx.h" +#include "../../Minecraft.World/Platform/stdafx.h" #include "../../Minecraft.World/Network/Socket.h" #include "../../Minecraft.World/Util/StringHelpers.h" #include "PlatformNetworkManagerStub.h" -#include "../../Minecraft.Client/Platform/Xbox/Network/NetworkPlayerXbox.h" // TODO - stub version of this? +#include "../../Minecraft.Client/Platform/Xbox/Network/NetworkPlayerXbox.h" // TODO - stub version of this? -CPlatformNetworkManagerStub *g_pPlatformNetworkManager; +CPlatformNetworkManagerStub* g_pPlatformNetworkManager; +void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer* pQNetPlayer) { + const char* pszDescription; -void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) -{ - const char * pszDescription; + // 4J Stu - We create a fake socket for every where that we need an INBOUND + // queue of game data. Outbound is all handled by QNet so we don't need + // that. Therefore each client player has one, and the host has one for each + // client player. + bool createFakeSocket = false; + bool localPlayer = false; - // 4J Stu - We create a fake socket for every where that we need an INBOUND queue of game data. Outbound - // is all handled by QNet so we don't need that. Therefore each client player has one, and the host has one - // for each client player. - bool createFakeSocket = false; - bool localPlayer = false; + NetworkPlayerXbox* networkPlayer = + (NetworkPlayerXbox*)addNetworkPlayer(pQNetPlayer); - NetworkPlayerXbox *networkPlayer = (NetworkPlayerXbox *)addNetworkPlayer(pQNetPlayer); - - if( pQNetPlayer->IsLocal() ) - { - localPlayer = true; - if( pQNetPlayer->IsHost() ) - { + if (pQNetPlayer->IsLocal()) { + localPlayer = true; + if (pQNetPlayer->IsHost()) { pszDescription = "local host"; - // 4J Stu - No socket for the localhost as it uses a special loopback queue + // 4J Stu - No socket for the localhost as it uses a special + // loopback queue - m_machineQNetPrimaryPlayers.push_back( pQNetPlayer ); - } - else - { + m_machineQNetPrimaryPlayers.push_back(pQNetPlayer); + } else { pszDescription = "local"; - // We need an inbound queue on all local players to receive data from the host - createFakeSocket = true; + // We need an inbound queue on all local players to receive data + // from the host + createFakeSocket = true; } - } - else - { - if( pQNetPlayer->IsHost() ) - { + } else { + if (pQNetPlayer->IsHost()) { pszDescription = "remote host"; - } - else - { + } else { pszDescription = "remote"; - // If we are the host, then create a fake socket for every remote player - if( m_pIQNet->IsHost() ) - { - createFakeSocket = true; - } + // If we are the host, then create a fake socket for every remote + // player + if (m_pIQNet->IsHost()) { + createFakeSocket = true; + } } - if( m_pIQNet->IsHost() && !m_bHostChanged ) - { - // Do we already have a primary player for this system? - bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineQNetPrimaryPlayers.begin()); it < m_machineQNetPrimaryPlayers.end(); ++it) - { - IQNetPlayer *pQNetPrimaryPlayer = *it; - if( pQNetPlayer->IsSameSystem(pQNetPrimaryPlayer) ) - { - systemHasPrimaryPlayer = true; - break; - } - } - if( !systemHasPrimaryPlayer ) - m_machineQNetPrimaryPlayers.push_back( pQNetPlayer ); - } + if (m_pIQNet->IsHost() && !m_bHostChanged) { + // Do we already have a primary player for this system? + bool systemHasPrimaryPlayer = false; + for (AUTO_VAR(it, m_machineQNetPrimaryPlayers.begin()); + it < m_machineQNetPrimaryPlayers.end(); ++it) { + IQNetPlayer* pQNetPrimaryPlayer = *it; + if (pQNetPlayer->IsSameSystem(pQNetPrimaryPlayer)) { + systemHasPrimaryPlayer = true; + break; + } + } + if (!systemHasPrimaryPlayer) + m_machineQNetPrimaryPlayers.push_back(pQNetPlayer); + } } - g_NetworkManager.PlayerJoining( networkPlayer ); - - if( createFakeSocket == true && !m_bHostChanged ) - { - g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); - } + g_NetworkManager.PlayerJoining(networkPlayer); - app.DebugPrintf( "Player 0x%p \"%ls\" joined; %s; voice %i; camera %i.\n", - pQNetPlayer, - pQNetPlayer->GetGamertag(), - pszDescription, - (int) pQNetPlayer->HasVoice(), - (int) pQNetPlayer->HasCamera() ); + if (createFakeSocket == true && !m_bHostChanged) { + g_NetworkManager.CreateSocket(networkPlayer, localPlayer); + } + app.DebugPrintf("Player 0x%p \"%ls\" joined; %s; voice %i; camera %i.\n", + pQNetPlayer, pQNetPlayer->GetGamertag(), pszDescription, + (int)pQNetPlayer->HasVoice(), + (int)pQNetPlayer->HasCamera()); - if( m_pIQNet->IsHost() ) - { - // 4J-PB - only the host should do this -// g_NetworkManager.UpdateAndSetGameSessionData(); - SystemFlagAddPlayer( networkPlayer ); - } - - for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(playerChangedCallback[idx] != NULL) - playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); - } + if (m_pIQNet->IsHost()) { + // 4J-PB - only the host should do this + // g_NetworkManager.UpdateAndSetGameSessionData(); + SystemFlagAddPlayer(networkPlayer); + } - if(m_pIQNet->GetState() == QNET_STATE_GAME_PLAY) - { - int localPlayerCount = 0; - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( m_pIQNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; - } + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (playerChangedCallback[idx] != NULL) + playerChangedCallback[idx](playerChangedCallbackParam[idx], + networkPlayer, false); + } - float appTime = app.getAppTime(); + if (m_pIQNet->GetState() == QNET_STATE_GAME_PLAY) { + int localPlayerCount = 0; + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (m_pIQNet->GetLocalPlayerByUserIndex(idx) != NULL) + ++localPlayerCount; + } - // Only record stats for the primary player here - m_lastPlayerEventTimeStart = appTime; - } + float appTime = app.getAppTime(); + + // Only record stats for the primary player here + m_lastPlayerEventTimeStart = appTime; + } } -bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize) -{ - m_pGameNetworkManager = pGameNetworkManager; - m_flagIndexSize = flagIndexSize; - g_pPlatformNetworkManager = this; - // 4jcraft added this, as it was never called - m_pIQNet = new IQNet(); - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - playerChangedCallback[ i ] = NULL; - } - - m_bLeavingGame = false; - m_bLeaveGameOnTick = false; - m_bHostChanged = false; +bool CPlatformNetworkManagerStub::Initialise( + CGameNetworkManager* pGameNetworkManager, int flagIndexSize) { + m_pGameNetworkManager = pGameNetworkManager; + m_flagIndexSize = flagIndexSize; + g_pPlatformNetworkManager = this; + // 4jcraft added this, as it was never called + m_pIQNet = new IQNet(); + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + playerChangedCallback[i] = NULL; + } - m_bSearchResultsReady = false; - m_bSearchPending = false; + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; - m_bIsOfflineGame = false; - m_pSearchParam = nullptr; - m_SessionsUpdatedCallback = nullptr; + m_bSearchResultsReady = false; + m_bSearchPending = false; - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - m_searchResultsCount[i] = 0; - m_lastSearchStartTime[i] = 0; + m_bIsOfflineGame = false; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; - // The results that will be filled in with the current search - m_pSearchResults[i] = NULL; - m_pQoSResult[i] = NULL; - m_pCurrentSearchResults[i] = NULL; - m_pCurrentQoSResult[i] = NULL; - m_currentSearchResultsCount[i] = 0; - } + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + m_searchResultsCount[i] = 0; + m_lastSearchStartTime[i] = 0; + + // The results that will be filled in with the current search + m_pSearchResults[i] = NULL; + m_pQoSResult[i] = NULL; + m_pCurrentSearchResults[i] = NULL; + m_pCurrentQoSResult[i] = NULL; + m_currentSearchResultsCount[i] = 0; + } // Success! return true; } -void CPlatformNetworkManagerStub::Terminate() -{ - //TODO: 4jcraft, no release of ressources +void CPlatformNetworkManagerStub::Terminate() { + // TODO: 4jcraft, no release of ressources } -int CPlatformNetworkManagerStub::GetJoiningReadyPercentage() -{ - return 100; +int CPlatformNetworkManagerStub::GetJoiningReadyPercentage() { return 100; } + +int CPlatformNetworkManagerStub::CorrectErrorIDS(int IDS) { return IDS; } + +bool CPlatformNetworkManagerStub::isSystemPrimaryPlayer( + IQNetPlayer* pQNetPlayer) { + return true; } -int CPlatformNetworkManagerStub::CorrectErrorIDS(int IDS) -{ - return IDS; +// We call this twice a frame, either side of the render call so is a good place +// to "tick" things +void CPlatformNetworkManagerStub::DoWork() {} + +int CPlatformNetworkManagerStub::GetPlayerCount() { + return m_pIQNet->GetPlayerCount(); } -bool CPlatformNetworkManagerStub::isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer) -{ - return true; +bool CPlatformNetworkManagerStub::ShouldMessageForFullSession() { + return false; } -// We call this twice a frame, either side of the render call so is a good place to "tick" things -void CPlatformNetworkManagerStub::DoWork() -{ +int CPlatformNetworkManagerStub::GetOnlinePlayerCount() { return 1; } + +int CPlatformNetworkManagerStub::GetLocalPlayerMask(int playerIndex) { + return 1 << playerIndex; } -int CPlatformNetworkManagerStub::GetPlayerCount() -{ - return m_pIQNet->GetPlayerCount(); +bool CPlatformNetworkManagerStub::AddLocalPlayerByUserIndex(int userIndex) { + NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); + return (m_pIQNet->AddLocalPlayerByUserIndex(userIndex) == S_OK); } -bool CPlatformNetworkManagerStub::ShouldMessageForFullSession() -{ - return false; +bool CPlatformNetworkManagerStub::RemoveLocalPlayerByUserIndex(int userIndex) { + return true; } -int CPlatformNetworkManagerStub::GetOnlinePlayerCount() -{ - return 1; +bool CPlatformNetworkManagerStub::IsInStatsEnabledSession() { return true; } + +bool CPlatformNetworkManagerStub::SessionHasSpace( + unsigned int spaceRequired /*= 1*/) { + return true; } -int CPlatformNetworkManagerStub::GetLocalPlayerMask(int playerIndex) -{ - return 1 << playerIndex; +void CPlatformNetworkManagerStub::SendInviteGUI(int quadrant) {} + +bool CPlatformNetworkManagerStub::IsAddingPlayer() { return false; } + +bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) { + if (m_bLeavingGame) return true; + + m_bLeavingGame = true; + + // If we are the host wait for the game server to end + if (m_pIQNet->IsHost() && g_NetworkManager.ServerStoppedValid()) { + m_pIQNet->EndGame(); + g_NetworkManager.ServerStoppedWait(); + g_NetworkManager.ServerStoppedDestroy(); + } + return true; } -bool CPlatformNetworkManagerStub::AddLocalPlayerByUserIndex( int userIndex ) -{ - NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); - return ( m_pIQNet->AddLocalPlayerByUserIndex(userIndex) == S_OK ); +bool CPlatformNetworkManagerStub::_LeaveGame(bool bMigrateHost, + bool bLeaveRoom) { + return true; } -bool CPlatformNetworkManagerStub::RemoveLocalPlayerByUserIndex( int userIndex ) -{ - return true; +void CPlatformNetworkManagerStub::HostGame( + int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, + unsigned char privateSlots /*= 0*/) { + // #ifdef _XBOX + // 4J Stu - We probably did this earlier as well, but just to be sure! + SetLocalGame(!bOnlineGame); + SetPrivateGame(bIsPrivate); + SystemFlagReset(); + + // Make sure that the Primary Pad is in by default + localUsersMask |= GetLocalPlayerMask(g_NetworkManager.GetPrimaryPad()); + + m_bLeavingGame = false; + + m_pIQNet->HostGame(); + + _HostGame(localUsersMask, publicSlots, privateSlots); + // #endif } -bool CPlatformNetworkManagerStub::IsInStatsEnabledSession() -{ - return true; +void CPlatformNetworkManagerStub::_HostGame( + int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, + unsigned char privateSlots /*= 0*/) {} + +bool CPlatformNetworkManagerStub::_StartGame() { return true; } + +int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo* searchResult, + int localUsersMask, + int primaryUserIndex) { + return CGameNetworkManager::JOINGAME_SUCCESS; } -bool CPlatformNetworkManagerStub::SessionHasSpace(unsigned int spaceRequired /*= 1*/) -{ - return true; +bool CPlatformNetworkManagerStub::SetLocalGame(bool isLocal) { + m_bIsOfflineGame = isLocal; + + return true; } -void CPlatformNetworkManagerStub::SendInviteGUI(int quadrant) -{ +void CPlatformNetworkManagerStub::SetPrivateGame(bool isPrivate) { + app.DebugPrintf("Setting as private game: %s\n", isPrivate ? "yes" : "no"); + m_bIsPrivateGame = isPrivate; } -bool CPlatformNetworkManagerStub::IsAddingPlayer() -{ - return false; +void CPlatformNetworkManagerStub::RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + playerChangedCallback[iPad] = callback; + playerChangedCallbackParam[iPad] = callbackParam; } -bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) -{ - if( m_bLeavingGame ) return true; - - m_bLeavingGame = true; - - // If we are the host wait for the game server to end - if(m_pIQNet->IsHost() && g_NetworkManager.ServerStoppedValid()) - { - m_pIQNet->EndGame(); - g_NetworkManager.ServerStoppedWait(); - g_NetworkManager.ServerStoppedDestroy(); - } - return true; +void CPlatformNetworkManagerStub::UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + if (playerChangedCallbackParam[iPad] == callbackParam) { + playerChangedCallback[iPad] = NULL; + playerChangedCallbackParam[iPad] = NULL; + } } -bool CPlatformNetworkManagerStub::_LeaveGame(bool bMigrateHost, bool bLeaveRoom) -{ - return true; +void CPlatformNetworkManagerStub::HandleSignInChange() { return; } + +bool CPlatformNetworkManagerStub::_RunNetworkGame() { return true; } + +void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving /*= NULL*/) { + // DWORD playerCount = m_pIQNet->GetPlayerCount(); + // + // if( this->m_bLeavingGame ) + // return; + // + // if( GetHostPlayer() == NULL ) + // return; + // + // for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) + // { + // if( i < playerCount ) + // { + // INetworkPlayer *pNetworkPlayer = GetPlayerByIndex(i); + // + // // We can call this from NotifyPlayerLeaving but at that + // point the player is still considered in the session if( pNetworkPlayer != + // pNetworkPlayerLeaving ) + // { + // m_hostGameSessionData.players[i] = + // ((NetworkPlayerXbox *)pNetworkPlayer)->GetUID(); + // + // char *temp; + // temp = (char *)wstringtofilename( + // pNetworkPlayer->GetOnlineName() ); + // memcpy(m_hostGameSessionData.szPlayers[i],temp,XUSER_NAME_SIZE); + // } + // else + // { + // m_hostGameSessionData.players[i] = NULL; + // memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); + // } + // } + // else + // { + // m_hostGameSessionData.players[i] = NULL; + // memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); + // } + // } + // + // m_hostGameSessionData.hostPlayerUID = ((NetworkPlayerXbox + // *)GetHostPlayer())->GetQNetPlayer()->GetXuid(); + // m_hostGameSessionData.m_uiGameHostSettings = + // app.GetGameHostOption(eGameHostOption_All); } -void CPlatformNetworkManagerStub::HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) -{ -// #ifdef _XBOX - // 4J Stu - We probably did this earlier as well, but just to be sure! - SetLocalGame( !bOnlineGame ); - SetPrivateGame( bIsPrivate ); - SystemFlagReset(); +int CPlatformNetworkManagerStub::RemovePlayerOnSocketClosedThreadProc( + void* lpParam) { + INetworkPlayer* pNetworkPlayer = (INetworkPlayer*)lpParam; - // Make sure that the Primary Pad is in by default - localUsersMask |= GetLocalPlayerMask( g_NetworkManager.GetPrimaryPad() ); + Socket* socket = pNetworkPlayer->GetSocket(); - m_bLeavingGame = false; + if (socket != NULL) { + // printf("Waiting for socket closed event\n"); + socket->m_socketClosedEvent->WaitForSignal(INFINITE); - m_pIQNet->HostGame(); + // printf("Socket closed event has fired\n"); + // 4J Stu - Clear our reference to this socket + pNetworkPlayer->SetSocket(NULL); + delete socket; + } - _HostGame( localUsersMask, publicSlots, privateSlots ); -//#endif + return g_pPlatformNetworkManager->RemoveLocalPlayer(pNetworkPlayer); } -void CPlatformNetworkManagerStub::_HostGame(int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) -{ +bool CPlatformNetworkManagerStub::RemoveLocalPlayer( + INetworkPlayer* pNetworkPlayer) { + return true; } -bool CPlatformNetworkManagerStub::_StartGame() -{ - return true; +CPlatformNetworkManagerStub::PlayerFlags::PlayerFlags( + INetworkPlayer* pNetworkPlayer, unsigned int count) { + // 4J Stu - Don't assert, just make it a multiple of 8! This count is + // calculated from a load of separate values, and makes tweaking + // world/render sizes a pain if we hit an assert here + count = (count + 8 - 1) & ~(8 - 1); + // assert( ( count % 8 ) == 0 ); + this->m_pNetworkPlayer = pNetworkPlayer; + this->flags = new unsigned char[count / 8]; + memset(this->flags, 0, count / 8); + this->count = count; +} +CPlatformNetworkManagerStub::PlayerFlags::~PlayerFlags() { delete[] flags; } + +// Add a player to the per system flag storage - if we've already got a player +// from that system, copy its flags over +void CPlatformNetworkManagerStub::SystemFlagAddPlayer( + INetworkPlayer* pNetworkPlayer) { + PlayerFlags* newPlayerFlags = + new PlayerFlags(pNetworkPlayer, m_flagIndexSize); + // If any of our existing players are on the same system, then copy over + // flags from that one + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer)) { + memcpy(newPlayerFlags->flags, m_playerFlags[i]->flags, + m_playerFlags[i]->count / 8); + break; + } + } + m_playerFlags.push_back(newPlayerFlags); } -int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex) -{ - return CGameNetworkManager::JOINGAME_SUCCESS; +// Remove a player from the per system flag storage - just maintains the +// m_playerFlags vector without any gaps in it +void CPlatformNetworkManagerStub::SystemFlagRemovePlayer( + INetworkPlayer* pNetworkPlayer) { + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer) { + delete m_playerFlags[i]; + m_playerFlags[i] = m_playerFlags.back(); + m_playerFlags.pop_back(); + return; + } + } } -bool CPlatformNetworkManagerStub::SetLocalGame(bool isLocal) -{ - m_bIsOfflineGame = isLocal; - - return true; +void CPlatformNetworkManagerStub::SystemFlagReset() { + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + delete m_playerFlags[i]; + } + m_playerFlags.clear(); } -void CPlatformNetworkManagerStub::SetPrivateGame(bool isPrivate) -{ - app.DebugPrintf("Setting as private game: %s\n", isPrivate ? "yes" : "no" ); - m_bIsPrivateGame = isPrivate; +// Set a per system flag - this is done by setting the flag on every player that +// shares that system +void CPlatformNetworkManagerStub::SystemFlagSet(INetworkPlayer* pNetworkPlayer, + int index) { + if ((index < 0) || (index >= m_flagIndexSize)) return; + if (pNetworkPlayer == NULL) return; + + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer)) { + m_playerFlags[i]->flags[index / 8] |= (128 >> (index % 8)); + } + } } -void CPlatformNetworkManagerStub::RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - playerChangedCallback[iPad] = callback; - playerChangedCallbackParam[iPad] = callbackParam; +// Get value of a per system flag - can be read from the flags of the passed in +// player as anything else sent to that system should also have been duplicated +// here +bool CPlatformNetworkManagerStub::SystemFlagGet(INetworkPlayer* pNetworkPlayer, + int index) { + if ((index < 0) || (index >= m_flagIndexSize)) return false; + if (pNetworkPlayer == NULL) { + return false; + } + + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer) { + return ((m_playerFlags[i]->flags[index / 8] & + (128 >> (index % 8))) != 0); + } + } + return false; } -void CPlatformNetworkManagerStub::UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - if(playerChangedCallbackParam[iPad] == callbackParam) - { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; - } +std::wstring CPlatformNetworkManagerStub::GatherStats() { return L""; } + +std::wstring CPlatformNetworkManagerStub::GatherRTTStats() { + std::wstring stats(L"Rtt: "); + + wchar_t stat[32]; + + for (unsigned int i = 0; i < GetPlayerCount(); ++i) { + IQNetPlayer* pQNetPlayer = + ((NetworkPlayerXbox*)GetPlayerByIndex(i))->GetQNetPlayer(); + + if (!pQNetPlayer->IsLocal()) { + ZeroMemory(stat, 32 * sizeof(WCHAR)); + swprintf(stat, 32, L"%d: %d/", i, pQNetPlayer->GetCurrentRtt()); + stats.append(stat); + } + } + return stats; } -void CPlatformNetworkManagerStub::HandleSignInChange() -{ - return; +void CPlatformNetworkManagerStub::TickSearch() {} + +void CPlatformNetworkManagerStub::SearchForGames() {} + +int CPlatformNetworkManagerStub::SearchForGamesThreadProc(void* lpParameter) { + return 0; } -bool CPlatformNetworkManagerStub::_RunNetworkGame() -{ - return true; +void CPlatformNetworkManagerStub::SetSearchResultsReady(int resultCount) { + m_bSearchResultsReady = true; + m_searchResultsCount[m_lastSearchPad] = resultCount; } -void CPlatformNetworkManagerStub::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) -{ -// DWORD playerCount = m_pIQNet->GetPlayerCount(); -// -// if( this->m_bLeavingGame ) -// return; -// -// if( GetHostPlayer() == NULL ) -// return; -// -// for(unsigned int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; ++i) -// { -// if( i < playerCount ) -// { -// INetworkPlayer *pNetworkPlayer = GetPlayerByIndex(i); -// -// // We can call this from NotifyPlayerLeaving but at that point the player is still considered in the session -// if( pNetworkPlayer != pNetworkPlayerLeaving ) -// { -// m_hostGameSessionData.players[i] = ((NetworkPlayerXbox *)pNetworkPlayer)->GetUID(); -// -// char *temp; -// temp = (char *)wstringtofilename( pNetworkPlayer->GetOnlineName() ); -// memcpy(m_hostGameSessionData.szPlayers[i],temp,XUSER_NAME_SIZE); -// } -// else -// { -// m_hostGameSessionData.players[i] = NULL; -// memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); -// } -// } -// else -// { -// m_hostGameSessionData.players[i] = NULL; -// memset(m_hostGameSessionData.szPlayers[i],0,XUSER_NAME_SIZE); -// } -// } -// -// m_hostGameSessionData.hostPlayerUID = ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetXuid(); -// m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); +std::vector* CPlatformNetworkManagerStub::GetSessionList( + int iPad, int localPlayers, bool partyOnly) { + std::vector* filteredList = + new std::vector(); + ; + return filteredList; } -int CPlatformNetworkManagerStub::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) -{ - INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; - - Socket *socket = pNetworkPlayer->GetSocket(); - - if( socket != NULL ) - { - //printf("Waiting for socket closed event\n"); - socket->m_socketClosedEvent->WaitForSignal(INFINITE); - - //printf("Socket closed event has fired\n"); - // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); - delete socket; - } - - return g_pPlatformNetworkManager->RemoveLocalPlayer( pNetworkPlayer ); +bool CPlatformNetworkManagerStub::GetGameSessionInfo( + int iPad, SessionID sessionId, FriendSessionInfo* foundSessionInfo) { + return false; } -bool CPlatformNetworkManagerStub::RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ) -{ - return true; +void CPlatformNetworkManagerStub::SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam) { + m_SessionsUpdatedCallback = SessionsUpdatedCallback; + m_pSearchParam = pSearchParam; } -CPlatformNetworkManagerStub::PlayerFlags::PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count) -{ - // 4J Stu - Don't assert, just make it a multiple of 8! This count is calculated from a load of separate values, - // and makes tweaking world/render sizes a pain if we hit an assert here - count = (count + 8 - 1) & ~(8 - 1); - //assert( ( count % 8 ) == 0 ); - this->m_pNetworkPlayer = pNetworkPlayer; - this->flags = new unsigned char [ count / 8 ]; - memset( this->flags, 0, count / 8 ); - this->count = count; -} -CPlatformNetworkManagerStub::PlayerFlags::~PlayerFlags() -{ - delete [] flags; +void CPlatformNetworkManagerStub::GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), void* pParam) { + FriendSessionUpdatedFn(true, pParam); } -// Add a player to the per system flag storage - if we've already got a player from that system, copy its flags over -void CPlatformNetworkManagerStub::SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer) -{ - PlayerFlags *newPlayerFlags = new PlayerFlags( pNetworkPlayer, m_flagIndexSize); - // If any of our existing players are on the same system, then copy over flags from that one - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) - { - memcpy( newPlayerFlags->flags, m_playerFlags[i]->flags, m_playerFlags[i]->count / 8 ); - break; - } - } - m_playerFlags.push_back(newPlayerFlags); +void CPlatformNetworkManagerStub::ForceFriendsSessionRefresh() { + app.DebugPrintf("Resetting friends session search data\n"); + + for (unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) { + m_searchResultsCount[i] = 0; + m_lastSearchStartTime[i] = 0; + delete m_pSearchResults[i]; + m_pSearchResults[i] = NULL; + } } -// Remove a player from the per system flag storage - just maintains the m_playerFlags vector without any gaps in it -void CPlatformNetworkManagerStub::SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer) -{ - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) - { - delete m_playerFlags[i]; - m_playerFlags[i] = m_playerFlags.back(); - m_playerFlags.pop_back(); - return; - } - } +INetworkPlayer* CPlatformNetworkManagerStub::addNetworkPlayer( + IQNetPlayer* pQNetPlayer) { + NetworkPlayerXbox* pNetworkPlayer = new NetworkPlayerXbox(pQNetPlayer); + pQNetPlayer->SetCustomDataValue((ULONG_PTR)pNetworkPlayer); + currentNetworkPlayers.push_back(pNetworkPlayer); + return pNetworkPlayer; } -void CPlatformNetworkManagerStub::SystemFlagReset() -{ - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - delete m_playerFlags[i]; - } - m_playerFlags.clear(); +void CPlatformNetworkManagerStub::removeNetworkPlayer( + IQNetPlayer* pQNetPlayer) { + INetworkPlayer* pNetworkPlayer = getNetworkPlayer(pQNetPlayer); + for (AUTO_VAR(it, currentNetworkPlayers.begin()); + it != currentNetworkPlayers.end(); it++) { + if (*it == pNetworkPlayer) { + currentNetworkPlayers.erase(it); + return; + } + } } -// Set a per system flag - this is done by setting the flag on every player that shares that system -void CPlatformNetworkManagerStub::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) -{ - if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; - - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) - { - m_playerFlags[i]->flags[ index / 8 ] |= ( 128 >> ( index % 8 ) ); - } - } +INetworkPlayer* CPlatformNetworkManagerStub::getNetworkPlayer( + IQNetPlayer* pQNetPlayer) { + return pQNetPlayer ? (INetworkPlayer*)(pQNetPlayer->GetCustomDataValue()) + : NULL; } -// Get value of a per system flag - can be read from the flags of the passed in player as anything else sent to that -// system should also have been duplicated here -bool CPlatformNetworkManagerStub::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) -{ - if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) - { - return false; - } - - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) - { - return ( ( m_playerFlags[i]->flags[ index / 8 ] & ( 128 >> ( index % 8 ) ) ) != 0 ); - } - } - return false; +INetworkPlayer* CPlatformNetworkManagerStub::GetLocalPlayerByUserIndex( + int userIndex) { + return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); } -std::wstring CPlatformNetworkManagerStub::GatherStats() -{ - return L""; +INetworkPlayer* CPlatformNetworkManagerStub::GetPlayerByIndex(int playerIndex) { + return getNetworkPlayer(m_pIQNet->GetPlayerByIndex(playerIndex)); } -std::wstring CPlatformNetworkManagerStub::GatherRTTStats() -{ - std::wstring stats(L"Rtt: "); - - wchar_t stat[32]; - - for(unsigned int i = 0; i < GetPlayerCount(); ++i) - { - IQNetPlayer *pQNetPlayer = ((NetworkPlayerXbox *)GetPlayerByIndex( i ))->GetQNetPlayer(); - - if(!pQNetPlayer->IsLocal()) - { - ZeroMemory(stat,32*sizeof(WCHAR)); - swprintf(stat, 32, L"%d: %d/", i, pQNetPlayer->GetCurrentRtt() ); - stats.append(stat); - } - } - return stats; +INetworkPlayer* CPlatformNetworkManagerStub::GetPlayerByXuid(PlayerUID xuid) { + return getNetworkPlayer(m_pIQNet->GetPlayerByXuid(xuid)); } -void CPlatformNetworkManagerStub::TickSearch() -{ +INetworkPlayer* CPlatformNetworkManagerStub::GetPlayerBySmallId( + unsigned char smallId) { + return getNetworkPlayer(m_pIQNet->GetPlayerBySmallId(smallId)); } -void CPlatformNetworkManagerStub::SearchForGames() -{ +INetworkPlayer* CPlatformNetworkManagerStub::GetHostPlayer() { + return getNetworkPlayer(m_pIQNet->GetHostPlayer()); } -int CPlatformNetworkManagerStub::SearchForGamesThreadProc( void* lpParameter ) -{ - return 0; +bool CPlatformNetworkManagerStub::IsHost() { + return m_pIQNet->IsHost() && !m_bHostChanged; } -void CPlatformNetworkManagerStub::SetSearchResultsReady(int resultCount) -{ - m_bSearchResultsReady = true; - m_searchResultsCount[m_lastSearchPad] = resultCount; +bool CPlatformNetworkManagerStub::JoinGameFromInviteInfo( + int userIndex, int userMask, const INVITE_INFO* pInviteInfo) { + return (m_pIQNet->JoinGameFromInviteInfo(userIndex, userMask, + pInviteInfo) == S_OK); } -std::vector *CPlatformNetworkManagerStub::GetSessionList(int iPad, int localPlayers, bool partyOnly) -{ - std::vector *filteredList = new std::vector();; - return filteredList; +void CPlatformNetworkManagerStub::SetSessionTexturePackParentId(int id) { + m_hostGameSessionData.texturePackParentId = id; } -bool CPlatformNetworkManagerStub::GetGameSessionInfo(int iPad, SessionID sessionId, FriendSessionInfo *foundSessionInfo) -{ - return false; +void CPlatformNetworkManagerStub::SetSessionSubTexturePackId(int id) { + m_hostGameSessionData.subTexturePackId = id; } -void CPlatformNetworkManagerStub::SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ) -{ - m_SessionsUpdatedCallback = SessionsUpdatedCallback; m_pSearchParam = pSearchParam; +void CPlatformNetworkManagerStub::Notify(int ID, ULONG_PTR Param) {} + +bool CPlatformNetworkManagerStub::IsInSession() { + return m_pIQNet->GetState() != QNET_STATE_IDLE; } -void CPlatformNetworkManagerStub::GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) -{ - FriendSessionUpdatedFn(true, pParam); +bool CPlatformNetworkManagerStub::IsInGameplay() { + return m_pIQNet->GetState() == QNET_STATE_GAME_PLAY; } -void CPlatformNetworkManagerStub::ForceFriendsSessionRefresh() -{ - app.DebugPrintf("Resetting friends session search data\n"); - - for(unsigned int i = 0; i < XUSER_MAX_COUNT; ++i) - { - m_searchResultsCount[i] = 0; - m_lastSearchStartTime[i] = 0; - delete m_pSearchResults[i]; - m_pSearchResults[i] = NULL; - } -} - -INetworkPlayer *CPlatformNetworkManagerStub::addNetworkPlayer(IQNetPlayer *pQNetPlayer) -{ - NetworkPlayerXbox *pNetworkPlayer = new NetworkPlayerXbox(pQNetPlayer); - pQNetPlayer->SetCustomDataValue((ULONG_PTR)pNetworkPlayer); - currentNetworkPlayers.push_back( pNetworkPlayer ); - return pNetworkPlayer; -} - -void CPlatformNetworkManagerStub::removeNetworkPlayer(IQNetPlayer *pQNetPlayer) -{ - INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pQNetPlayer); - for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) - { - if( *it == pNetworkPlayer ) - { - currentNetworkPlayers.erase(it); - return; - } - } -} - -INetworkPlayer *CPlatformNetworkManagerStub::getNetworkPlayer(IQNetPlayer *pQNetPlayer) -{ - return pQNetPlayer ? (INetworkPlayer *)(pQNetPlayer->GetCustomDataValue()) : NULL; -} - - -INetworkPlayer *CPlatformNetworkManagerStub::GetLocalPlayerByUserIndex(int userIndex ) -{ - return getNetworkPlayer(m_pIQNet->GetLocalPlayerByUserIndex(userIndex)); -} - -INetworkPlayer *CPlatformNetworkManagerStub::GetPlayerByIndex(int playerIndex) -{ - return getNetworkPlayer(m_pIQNet->GetPlayerByIndex(playerIndex)); -} - -INetworkPlayer * CPlatformNetworkManagerStub::GetPlayerByXuid(PlayerUID xuid) -{ - return getNetworkPlayer( m_pIQNet->GetPlayerByXuid(xuid)) ; -} - -INetworkPlayer * CPlatformNetworkManagerStub::GetPlayerBySmallId(unsigned char smallId) -{ - return getNetworkPlayer(m_pIQNet->GetPlayerBySmallId(smallId)); -} - -INetworkPlayer *CPlatformNetworkManagerStub::GetHostPlayer() -{ - return getNetworkPlayer(m_pIQNet->GetHostPlayer()); -} - -bool CPlatformNetworkManagerStub::IsHost() -{ - return m_pIQNet->IsHost() && !m_bHostChanged; -} - -bool CPlatformNetworkManagerStub::JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo) -{ - return ( m_pIQNet->JoinGameFromInviteInfo( userIndex, userMask, pInviteInfo ) == S_OK); -} - -void CPlatformNetworkManagerStub::SetSessionTexturePackParentId( int id ) -{ - m_hostGameSessionData.texturePackParentId = id; -} - -void CPlatformNetworkManagerStub::SetSessionSubTexturePackId( int id ) -{ - m_hostGameSessionData.subTexturePackId = id; -} - -void CPlatformNetworkManagerStub::Notify(int ID, ULONG_PTR Param) -{ -} - -bool CPlatformNetworkManagerStub::IsInSession() -{ - return m_pIQNet->GetState() != QNET_STATE_IDLE; -} - -bool CPlatformNetworkManagerStub::IsInGameplay() -{ - return m_pIQNet->GetState() == QNET_STATE_GAME_PLAY; -} - -bool CPlatformNetworkManagerStub::IsReadyToPlayOrIdle() -{ - return true; -} +bool CPlatformNetworkManagerStub::IsReadyToPlayOrIdle() { return true; } diff --git a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.h b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.h index 19a5a938c..1a64cba27 100644 --- a/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.h +++ b/Minecraft.Client/Platform/Common/Network/PlatformNetworkManagerStub.h @@ -1,170 +1,201 @@ #pragma once -//using namespace std; +// using namespace std; #include #include "../../Minecraft.World/Util/C4JThread.h" #include "NetworkPlayerInterface.h" #include "PlatformNetworkManagerInterface.h" #include "SessionInfo.h" -class CPlatformNetworkManagerStub : public CPlatformNetworkManager -{ - friend class CGameNetworkManager; +class CPlatformNetworkManagerStub : public CPlatformNetworkManager { + friend class CGameNetworkManager; + public: - virtual bool Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize); - virtual void Terminate(); - virtual int GetJoiningReadyPercentage(); - virtual int CorrectErrorIDS(int IDS); + virtual bool Initialise(CGameNetworkManager* pGameNetworkManager, + int flagIndexSize); + virtual void Terminate(); + virtual int GetJoiningReadyPercentage(); + virtual int CorrectErrorIDS(int IDS); - virtual void DoWork(); - virtual int GetPlayerCount(); - virtual int GetOnlinePlayerCount(); - virtual int GetLocalPlayerMask(int playerIndex); - virtual bool AddLocalPlayerByUserIndex( int userIndex ); - virtual bool RemoveLocalPlayerByUserIndex( int userIndex ); - virtual INetworkPlayer *GetLocalPlayerByUserIndex( int userIndex ); - virtual INetworkPlayer *GetPlayerByIndex(int playerIndex); - virtual INetworkPlayer * GetPlayerByXuid(PlayerUID xuid); - virtual INetworkPlayer * GetPlayerBySmallId(unsigned char smallId); - virtual bool ShouldMessageForFullSession(); + virtual void DoWork(); + virtual int GetPlayerCount(); + virtual int GetOnlinePlayerCount(); + virtual int GetLocalPlayerMask(int playerIndex); + virtual bool AddLocalPlayerByUserIndex(int userIndex); + virtual bool RemoveLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetPlayerByIndex(int playerIndex); + virtual INetworkPlayer* GetPlayerByXuid(PlayerUID xuid); + virtual INetworkPlayer* GetPlayerBySmallId(unsigned char smallId); + virtual bool ShouldMessageForFullSession(); - virtual INetworkPlayer *GetHostPlayer(); - virtual bool IsHost(); - virtual bool JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo); - virtual bool LeaveGame(bool bMigrateHost); + virtual INetworkPlayer* GetHostPlayer(); + virtual bool IsHost(); + virtual bool JoinGameFromInviteInfo(int userIndex, int userMask, + const INVITE_INFO* pInviteInfo); + virtual bool LeaveGame(bool bMigrateHost); - virtual bool IsInSession(); - virtual bool IsInGameplay(); - virtual bool IsReadyToPlayOrIdle(); - virtual bool IsInStatsEnabledSession(); - virtual bool SessionHasSpace(unsigned int spaceRequired = 1); - virtual void SendInviteGUI(int quadrant); - virtual bool IsAddingPlayer(); + virtual bool IsInSession(); + virtual bool IsInGameplay(); + virtual bool IsReadyToPlayOrIdle(); + virtual bool IsInStatsEnabledSession(); + virtual bool SessionHasSpace(unsigned int spaceRequired = 1); + virtual void SendInviteGUI(int quadrant); + virtual bool IsAddingPlayer(); - virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); - virtual int JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex ); - virtual bool SetLocalGame(bool isLocal); - virtual bool IsLocalGame() { return m_bIsOfflineGame; } - virtual void SetPrivateGame(bool isPrivate); - virtual bool IsPrivateGame() { return m_bIsPrivateGame; } - virtual bool IsLeavingGame() { return m_bLeavingGame; } - virtual void ResetLeavingGame() { m_bLeavingGame = false; } + virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0); + virtual int JoinGame(FriendSessionInfo* searchResult, int localUsersMask, + int primaryUserIndex); + virtual bool SetLocalGame(bool isLocal); + virtual bool IsLocalGame() { return m_bIsOfflineGame; } + virtual void SetPrivateGame(bool isPrivate); + virtual bool IsPrivateGame() { return m_bIsPrivateGame; } + virtual bool IsLeavingGame() { return m_bLeavingGame; } + virtual void ResetLeavingGame() { m_bLeavingGame = false; } - virtual void RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); - virtual void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); + virtual void RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); + virtual void UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); - virtual void HandleSignInChange(); + virtual void HandleSignInChange(); - virtual bool _RunNetworkGame(); - -private: - bool isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer); - virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); - virtual void _HostGame(int dwUsersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); - virtual bool _StartGame(); - - IQNet * m_pIQNet; // pointer to QNet interface - - HANDLE m_notificationListener; - - std::vector m_machineQNetPrimaryPlayers; // collection of players that we deem to be the main one for that system - - bool m_bLeavingGame; - bool m_bLeaveGameOnTick; - bool m_migrateHostOnLeave; - bool m_bHostChanged; - - bool m_bIsOfflineGame; - bool m_bIsPrivateGame; - int m_flagIndexSize; - - // This is only maintained by the host, and is not valid on client machines - GameSessionData m_hostGameSessionData; - CGameNetworkManager *m_pGameNetworkManager; -public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual bool _RunNetworkGame(); private: - // TODO 4J Stu - Do we need to be able to have more than one of these? - void (*playerChangedCallback[XUSER_MAX_COUNT])(void *callbackParam, INetworkPlayer *pPlayer, bool leaving); - void *playerChangedCallbackParam[XUSER_MAX_COUNT]; + bool isSystemPrimaryPlayer(IQNetPlayer* pQNetPlayer); + virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); + virtual void _HostGame( + int dwUsersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0); + virtual bool _StartGame(); - static int RemovePlayerOnSocketClosedThreadProc( void* lpParam ); - virtual bool RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ); + IQNet* m_pIQNet; // pointer to QNet interface - // Things for handling per-system flags - class PlayerFlags - { - public: - INetworkPlayer *m_pNetworkPlayer; - unsigned char *flags; - unsigned int count; - PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count); - ~PlayerFlags(); - }; - std::vector m_playerFlags; - void SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer); - void SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer); - void SystemFlagReset(); -public: - virtual void SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index); - virtual bool SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index); + HANDLE m_notificationListener; - // For telemetry -private: - float m_lastPlayerEventTimeStart; + std::vector + m_machineQNetPrimaryPlayers; // collection of players that we deem to + // be the main one for that system + + bool m_bLeavingGame; + bool m_bLeaveGameOnTick; + bool m_migrateHostOnLeave; + bool m_bHostChanged; + + bool m_bIsOfflineGame; + bool m_bIsPrivateGame; + int m_flagIndexSize; + + // This is only maintained by the host, and is not valid on client machines + GameSessionData m_hostGameSessionData; + CGameNetworkManager* m_pGameNetworkManager; public: - std::wstring GatherStats(); - std::wstring GatherRTTStats(); - -private: - std::vector friendsSessions[XUSER_MAX_COUNT]; - int m_searchResultsCount[XUSER_MAX_COUNT]; - int m_lastSearchStartTime[XUSER_MAX_COUNT]; - - // The results that will be filled in with the current search - XSESSION_SEARCHRESULT_HEADER *m_pSearchResults[XUSER_MAX_COUNT]; - XNQOS *m_pQoSResult[XUSER_MAX_COUNT]; - - // The results from the previous search, which are currently displayed in the game - XSESSION_SEARCHRESULT_HEADER *m_pCurrentSearchResults[XUSER_MAX_COUNT]; - XNQOS *m_pCurrentQoSResult[XUSER_MAX_COUNT]; - int m_currentSearchResultsCount[XUSER_MAX_COUNT]; - - int m_lastSearchPad; - bool m_bSearchResultsReady; - bool m_bSearchPending; - void *m_pSearchParam; - void (*m_SessionsUpdatedCallback)(void *pParam); - - C4JThread* m_SearchingThread; - - void TickSearch(); - void SearchForGames(); - static int SearchForGamesThreadProc( void* lpParameter ); - - void SetSearchResultsReady(int resultCount = 0); - - std::vectorcurrentNetworkPlayers; - INetworkPlayer *addNetworkPlayer(IQNetPlayer *pQNetPlayer); - void removeNetworkPlayer(IQNetPlayer *pQNetPlayer); - static INetworkPlayer *getNetworkPlayer(IQNetPlayer *pQNetPlayer); - - virtual void SetSessionTexturePackParentId( int id ); - virtual void SetSessionSubTexturePackId( int id ); - virtual void Notify(int ID, ULONG_PTR Param); - -public: - virtual std::vector *GetSessionList(int iPad, int localPlayers, bool partyOnly); - virtual bool GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession); - virtual void SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ); - virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ); - virtual void ForceFriendsSessionRefresh(); + virtual void UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving = NULL); private: - void NotifyPlayerJoined( IQNetPlayer *pQNetPlayer ); + // TODO 4J Stu - Do we need to be able to have more than one of these? + void (*playerChangedCallback[XUSER_MAX_COUNT])(void* callbackParam, + INetworkPlayer* pPlayer, + bool leaving); + void* playerChangedCallbackParam[XUSER_MAX_COUNT]; + + static int RemovePlayerOnSocketClosedThreadProc(void* lpParam); + virtual bool RemoveLocalPlayer(INetworkPlayer* pNetworkPlayer); + + // Things for handling per-system flags + class PlayerFlags { + public: + INetworkPlayer* m_pNetworkPlayer; + unsigned char* flags; + unsigned int count; + PlayerFlags(INetworkPlayer* pNetworkPlayer, unsigned int count); + ~PlayerFlags(); + }; + std::vector m_playerFlags; + void SystemFlagAddPlayer(INetworkPlayer* pNetworkPlayer); + void SystemFlagRemovePlayer(INetworkPlayer* pNetworkPlayer); + void SystemFlagReset(); + +public: + virtual void SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index); + virtual bool SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index); + + // For telemetry +private: + float m_lastPlayerEventTimeStart; + +public: + std::wstring GatherStats(); + std::wstring GatherRTTStats(); + +private: + std::vector friendsSessions[XUSER_MAX_COUNT]; + int m_searchResultsCount[XUSER_MAX_COUNT]; + int m_lastSearchStartTime[XUSER_MAX_COUNT]; + + // The results that will be filled in with the current search + XSESSION_SEARCHRESULT_HEADER* m_pSearchResults[XUSER_MAX_COUNT]; + XNQOS* m_pQoSResult[XUSER_MAX_COUNT]; + + // The results from the previous search, which are currently displayed in + // the game + XSESSION_SEARCHRESULT_HEADER* m_pCurrentSearchResults[XUSER_MAX_COUNT]; + XNQOS* m_pCurrentQoSResult[XUSER_MAX_COUNT]; + int m_currentSearchResultsCount[XUSER_MAX_COUNT]; + + int m_lastSearchPad; + bool m_bSearchResultsReady; + bool m_bSearchPending; + void* m_pSearchParam; + void (*m_SessionsUpdatedCallback)(void* pParam); + + C4JThread* m_SearchingThread; + + void TickSearch(); + void SearchForGames(); + static int SearchForGamesThreadProc(void* lpParameter); + + void SetSearchResultsReady(int resultCount = 0); + + std::vector currentNetworkPlayers; + INetworkPlayer* addNetworkPlayer(IQNetPlayer* pQNetPlayer); + void removeNetworkPlayer(IQNetPlayer* pQNetPlayer); + static INetworkPlayer* getNetworkPlayer(IQNetPlayer* pQNetPlayer); + + virtual void SetSessionTexturePackParentId(int id); + virtual void SetSessionSubTexturePackId(int id); + virtual void Notify(int ID, ULONG_PTR Param); + +public: + virtual std::vector* GetSessionList(int iPad, + int localPlayers, + bool partyOnly); + virtual bool GetGameSessionInfo(int iPad, SessionID sessionId, + FriendSessionInfo* foundSession); + virtual void SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam); + virtual void GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), + void* pParam); + virtual void ForceFriendsSessionRefresh(); + +private: + void NotifyPlayerJoined(IQNetPlayer* pQNetPlayer); #ifndef _XBOX - void FakeLocalPlayerJoined() { NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(0)); } + void FakeLocalPlayerJoined() { + NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(0)); + } #endif }; diff --git a/Minecraft.Client/Platform/Common/Network/SessionInfo.h b/Minecraft.Client/Platform/Common/Network/SessionInfo.h index e93b14584..0020b4978 100644 --- a/Minecraft.Client/Platform/Common/Network/SessionInfo.h +++ b/Minecraft.Client/Platform/Common/Network/SessionInfo.h @@ -4,110 +4,104 @@ #include "Sony/SQRNetworkManager.h" #endif - -// A struct that we store in the QoS data when we are hosting the session. Max size 1020 bytes. +// A struct that we store in the QoS data when we are hosting the session. Max +// size 1020 bytes. #ifdef _XBOX -typedef struct _GameSessionData -{ - unsigned short netVersion; // 2 bytes - char hostName[XUSER_NAME_SIZE]; // 16 bytes ( 16*1 ) - GameSessionUID hostPlayerUID; // 8 bytes ( 8*1 ) on xbox, 24 bytes on PS3 - GameSessionUID players[MINECRAFT_NET_MAX_PLAYERS]; // 64 bytes ( 8*8 ) on xbox, 192 ( 24*8) on PS3 - char szPlayers[MINECRAFT_NET_MAX_PLAYERS][XUSER_NAME_SIZE]; // 128 bytes ( 8*16) - unsigned int m_uiGameHostSettings; // 4 bytes - unsigned int texturePackParentId; // 4 bytes - unsigned char subTexturePackId; // 1 byte +typedef struct _GameSessionData { + unsigned short netVersion; // 2 bytes + char hostName[XUSER_NAME_SIZE]; // 16 bytes ( 16*1 ) + GameSessionUID hostPlayerUID; // 8 bytes ( 8*1 ) on xbox, 24 bytes on PS3 + GameSessionUID + players[MINECRAFT_NET_MAX_PLAYERS]; // 64 bytes ( 8*8 ) on xbox, 192 ( + // 24*8) on PS3 + char szPlayers[MINECRAFT_NET_MAX_PLAYERS] + [XUSER_NAME_SIZE]; // 128 bytes ( 8*16) + unsigned int m_uiGameHostSettings; // 4 bytes + unsigned int texturePackParentId; // 4 bytes + unsigned char subTexturePackId; // 1 byte - bool isJoinable; // 1 byte + bool isJoinable; // 1 byte - _GameSessionData() - { - netVersion = 0; - memset(hostName,0,XUSER_NAME_SIZE); - memset(players,0,MINECRAFT_NET_MAX_PLAYERS*sizeof(players[0])); - memset(szPlayers,0,MINECRAFT_NET_MAX_PLAYERS*XUSER_NAME_SIZE); - isJoinable = true; - m_uiGameHostSettings = 0; - texturePackParentId = 0; - subTexturePackId = 0; - } + _GameSessionData() { + netVersion = 0; + memset(hostName, 0, XUSER_NAME_SIZE); + memset(players, 0, MINECRAFT_NET_MAX_PLAYERS * sizeof(players[0])); + memset(szPlayers, 0, MINECRAFT_NET_MAX_PLAYERS * XUSER_NAME_SIZE); + isJoinable = true; + m_uiGameHostSettings = 0; + texturePackParentId = 0; + subTexturePackId = 0; + } } GameSessionData; #elif defined __PS3__ || defined __ORBIS__ || defined(__PSVITA__) -typedef struct _GameSessionData -{ - unsigned short netVersion; // 2 bytes - GameSessionUID hostPlayerUID; // 8 bytes ( 8*1 ) on xbox, 24 bytes on PS3 - GameSessionUID players[MINECRAFT_NET_MAX_PLAYERS]; // 64 bytes ( 8*8 ) on xbox, 192 ( 24*8) on PS3 - unsigned int m_uiGameHostSettings; // 4 bytes - unsigned int texturePackParentId; // 4 bytes - unsigned char subTexturePackId; // 1 byte +typedef struct _GameSessionData { + unsigned short netVersion; // 2 bytes + GameSessionUID hostPlayerUID; // 8 bytes ( 8*1 ) on xbox, 24 bytes on PS3 + GameSessionUID + players[MINECRAFT_NET_MAX_PLAYERS]; // 64 bytes ( 8*8 ) on xbox, 192 ( + // 24*8) on PS3 + unsigned int m_uiGameHostSettings; // 4 bytes + unsigned int texturePackParentId; // 4 bytes + unsigned char subTexturePackId; // 1 byte - bool isJoinable; // 1 byte + bool isJoinable; // 1 byte - unsigned char playerCount; // 1 byte - bool isReadyToJoin; // 1 byte + unsigned char playerCount; // 1 byte + bool isReadyToJoin; // 1 byte - _GameSessionData() - { - netVersion = 0; - memset(players,0,MINECRAFT_NET_MAX_PLAYERS*sizeof(players[0])); - isJoinable = true; - m_uiGameHostSettings = 0; - texturePackParentId = 0; - subTexturePackId = 0; - playerCount = 0; - isReadyToJoin = false; - - } + _GameSessionData() { + netVersion = 0; + memset(players, 0, MINECRAFT_NET_MAX_PLAYERS * sizeof(players[0])); + isJoinable = true; + m_uiGameHostSettings = 0; + texturePackParentId = 0; + subTexturePackId = 0; + playerCount = 0; + isReadyToJoin = false; + } } GameSessionData; #else -typedef struct _GameSessionData -{ - unsigned short netVersion; // 2 bytes - unsigned int m_uiGameHostSettings; // 4 bytes - unsigned int texturePackParentId; // 4 bytes - unsigned char subTexturePackId; // 1 byte +typedef struct _GameSessionData { + unsigned short netVersion; // 2 bytes + unsigned int m_uiGameHostSettings; // 4 bytes + unsigned int texturePackParentId; // 4 bytes + unsigned char subTexturePackId; // 1 byte - bool isReadyToJoin; // 1 byte + bool isReadyToJoin; // 1 byte - _GameSessionData() - { - netVersion = 0; - m_uiGameHostSettings = 0; - texturePackParentId = 0; - subTexturePackId = 0; - } + _GameSessionData() { + netVersion = 0; + m_uiGameHostSettings = 0; + texturePackParentId = 0; + subTexturePackId = 0; + } } GameSessionData; #endif -class FriendSessionInfo -{ +class FriendSessionInfo { public: - SessionID sessionId; + SessionID sessionId; #ifdef _XBOX - XSESSION_SEARCHRESULT searchResult; -#elif defined(__PS3__) || defined(__ORBIS__) || defined (__PSVITA__) - SQRNetworkManager::SessionSearchResult searchResult; + XSESSION_SEARCHRESULT searchResult; +#elif defined(__PS3__) || defined(__ORBIS__) || defined(__PSVITA__) + SQRNetworkManager::SessionSearchResult searchResult; #elif defined(_DURANGO) - DQRNetworkManager::SessionSearchResult searchResult; + DQRNetworkManager::SessionSearchResult searchResult; #endif - wchar_t *displayLabel; - unsigned char displayLabelLength; - unsigned char displayLabelViewableStartIndex; - GameSessionData data; - bool hasPartyMember; + wchar_t* displayLabel; + unsigned char displayLabelLength; + unsigned char displayLabelViewableStartIndex; + GameSessionData data; + bool hasPartyMember; - FriendSessionInfo() - { - displayLabel = NULL; - displayLabelLength = 0; - displayLabelViewableStartIndex = 0; - hasPartyMember = false; - } + FriendSessionInfo() { + displayLabel = NULL; + displayLabelLength = 0; + displayLabelViewableStartIndex = 0; + hasPartyMember = false; + } - ~FriendSessionInfo() - { - if(displayLabel!=NULL) - delete displayLabel; - } + ~FriendSessionInfo() { + if (displayLabel != NULL) delete displayLabel; + } }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.cpp b/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.cpp index ee589aabb..a4acdd542 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.cpp @@ -1,114 +1,80 @@ #include "../../../Minecraft.World/Platform/stdafx.h" #include "NetworkPlayerSony.h" -NetworkPlayerSony::NetworkPlayerSony(SQRNetworkPlayer *qnetPlayer) -{ - m_sqrPlayer = qnetPlayer; - m_pSocket = NULL; +NetworkPlayerSony::NetworkPlayerSony(SQRNetworkPlayer* qnetPlayer) { + m_sqrPlayer = qnetPlayer; + m_pSocket = NULL; } -unsigned char NetworkPlayerSony::GetSmallId() -{ - return m_sqrPlayer->GetSmallId(); +unsigned char NetworkPlayerSony::GetSmallId() { + return m_sqrPlayer->GetSmallId(); } -void NetworkPlayerSony::SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority) -{ - // TODO - handle priority - m_sqrPlayer->SendData( ((NetworkPlayerSony *)player)->m_sqrPlayer, pvData, dataSize ); +void NetworkPlayerSony::SendData(INetworkPlayer* player, const void* pvData, + int dataSize, bool lowPriority) { + // TODO - handle priority + m_sqrPlayer->SendData(((NetworkPlayerSony*)player)->m_sqrPlayer, pvData, + dataSize); } -bool NetworkPlayerSony::IsSameSystem(INetworkPlayer *player) -{ - return m_sqrPlayer->IsSameSystem(((NetworkPlayerSony *)player)->m_sqrPlayer); +bool NetworkPlayerSony::IsSameSystem(INetworkPlayer* player) { + return m_sqrPlayer->IsSameSystem(((NetworkPlayerSony*)player)->m_sqrPlayer); } -int NetworkPlayerSony::GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ) -{ - return 0; // TODO +int NetworkPlayerSony::GetSendQueueSizeBytes(INetworkPlayer* player, + bool lowPriority) { + return 0; // TODO } -int NetworkPlayerSony::GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ) -{ - return 0; // TODO +int NetworkPlayerSony::GetSendQueueSizeMessages(INetworkPlayer* player, + bool lowPriority) { + return 0; // TODO } -int NetworkPlayerSony::GetCurrentRtt() -{ - return 0; // TODO +int NetworkPlayerSony::GetCurrentRtt() { + return 0; // TODO } -bool NetworkPlayerSony::IsHost() -{ - return m_sqrPlayer->IsHost(); +bool NetworkPlayerSony::IsHost() { return m_sqrPlayer->IsHost(); } + +bool NetworkPlayerSony::IsGuest() { + return false; // TODO } -bool NetworkPlayerSony::IsGuest() -{ - return false; // TODO +bool NetworkPlayerSony::IsLocal() { return m_sqrPlayer->IsLocal(); } + +int NetworkPlayerSony::GetSessionIndex() { + return m_sqrPlayer->GetSessionIndex(); } -bool NetworkPlayerSony::IsLocal() -{ - return m_sqrPlayer->IsLocal(); +bool NetworkPlayerSony::IsTalking() { return m_sqrPlayer->IsTalking(); } + +bool NetworkPlayerSony::IsMutedByLocalUser(int userIndex) { + return m_sqrPlayer->IsMutedByLocalUser(userIndex); } -int NetworkPlayerSony::GetSessionIndex() -{ - return m_sqrPlayer->GetSessionIndex(); +bool NetworkPlayerSony::HasVoice() { return m_sqrPlayer->HasVoice(); } + +bool NetworkPlayerSony::HasCamera() { + return false; // TODO } -bool NetworkPlayerSony::IsTalking() -{ - return m_sqrPlayer->IsTalking(); +int NetworkPlayerSony::GetUserIndex() { + return m_sqrPlayer->GetLocalPlayerIndex(); } -bool NetworkPlayerSony::IsMutedByLocalUser(int userIndex) -{ - return m_sqrPlayer->IsMutedByLocalUser(userIndex); +void NetworkPlayerSony::SetSocket(Socket* pSocket) { m_pSocket = pSocket; } + +Socket* NetworkPlayerSony::GetSocket() { return m_pSocket; } + +const wchar_t* NetworkPlayerSony::GetOnlineName() { + return m_sqrPlayer->GetName(); } -bool NetworkPlayerSony::HasVoice() -{ - return m_sqrPlayer->HasVoice(); +std::wstring NetworkPlayerSony::GetDisplayName() { + return m_sqrPlayer->GetName(); } -bool NetworkPlayerSony::HasCamera() -{ - return false; // TODO -} +PlayerUID NetworkPlayerSony::GetUID() { return m_sqrPlayer->GetUID(); } -int NetworkPlayerSony::GetUserIndex() -{ - return m_sqrPlayer->GetLocalPlayerIndex(); -} - -void NetworkPlayerSony::SetSocket(Socket *pSocket) -{ - m_pSocket = pSocket; -} - -Socket *NetworkPlayerSony::GetSocket() -{ - return m_pSocket; -} - -const wchar_t *NetworkPlayerSony::GetOnlineName() -{ - return m_sqrPlayer->GetName(); -} - -std::wstring NetworkPlayerSony::GetDisplayName() -{ - return m_sqrPlayer->GetName(); -} - -PlayerUID NetworkPlayerSony::GetUID() -{ - return m_sqrPlayer->GetUID(); -} - -void NetworkPlayerSony::SetUID(PlayerUID UID) -{ - m_sqrPlayer->SetUID(UID); -} +void NetworkPlayerSony::SetUID(PlayerUID UID) { m_sqrPlayer->SetUID(UID); } diff --git a/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.h b/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.h index c71b343b6..4f509464e 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/NetworkPlayerSony.h @@ -3,37 +3,40 @@ #include "../NetworkPlayerInterface.h" #include "SQRNetworkPlayer.h" -// This is an implementation of the INetworkPlayer interface, for Sony platforms. It effectively wraps the SQRNetworkPlayer class in a non-platform-specific way. +// This is an implementation of the INetworkPlayer interface, for Sony +// platforms. It effectively wraps the SQRNetworkPlayer class in a +// non-platform-specific way. -class NetworkPlayerSony : public INetworkPlayer -{ +class NetworkPlayerSony : public INetworkPlayer { public: - // Common player interface - NetworkPlayerSony(SQRNetworkPlayer *sqrPlayer); - virtual unsigned char GetSmallId(); - virtual void SendData(INetworkPlayer *player, const void *pvData, int dataSize, bool lowPriority); - virtual bool IsSameSystem(INetworkPlayer *player); - virtual int GetSendQueueSizeBytes( INetworkPlayer *player, bool lowPriority ); - virtual int GetSendQueueSizeMessages( INetworkPlayer *player, bool lowPriority ); - virtual int GetCurrentRtt(); - virtual bool IsHost(); - virtual bool IsGuest(); - virtual bool IsLocal(); - virtual int GetSessionIndex(); - virtual bool IsTalking(); - virtual bool IsMutedByLocalUser(int userIndex); - virtual bool HasVoice(); - virtual bool HasCamera(); - virtual int GetUserIndex(); - virtual void SetSocket(Socket *pSocket); - virtual Socket *GetSocket(); - virtual const wchar_t *GetOnlineName(); - virtual std::wstring GetDisplayName(); - virtual PlayerUID GetUID(); + // Common player interface + NetworkPlayerSony(SQRNetworkPlayer* sqrPlayer); + virtual unsigned char GetSmallId(); + virtual void SendData(INetworkPlayer* player, const void* pvData, + int dataSize, bool lowPriority); + virtual bool IsSameSystem(INetworkPlayer* player); + virtual int GetSendQueueSizeBytes(INetworkPlayer* player, bool lowPriority); + virtual int GetSendQueueSizeMessages(INetworkPlayer* player, + bool lowPriority); + virtual int GetCurrentRtt(); + virtual bool IsHost(); + virtual bool IsGuest(); + virtual bool IsLocal(); + virtual int GetSessionIndex(); + virtual bool IsTalking(); + virtual bool IsMutedByLocalUser(int userIndex); + virtual bool HasVoice(); + virtual bool HasCamera(); + virtual int GetUserIndex(); + virtual void SetSocket(Socket* pSocket); + virtual Socket* GetSocket(); + virtual const wchar_t* GetOnlineName(); + virtual std::wstring GetDisplayName(); + virtual PlayerUID GetUID(); - void SetUID(PlayerUID UID); + void SetUID(PlayerUID UID); private: - SQRNetworkPlayer *m_sqrPlayer; - Socket *m_pSocket; + SQRNetworkPlayer* m_sqrPlayer; + Socket* m_pSocket; }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.cpp b/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.cpp index abb1116fb..be6075080 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.cpp @@ -5,210 +5,178 @@ #include "NetworkPlayerSony.h" #include "../GameNetworkManager.h" -CPlatformNetworkManagerSony *g_pPlatformNetworkManager; +CPlatformNetworkManagerSony* g_pPlatformNetworkManager; -bool CPlatformNetworkManagerSony::IsLocalGame() -{ - return m_bIsOfflineGame; -} -bool CPlatformNetworkManagerSony::IsPrivateGame() -{ - return m_bIsPrivateGame; -} -bool CPlatformNetworkManagerSony::IsLeavingGame() -{ - return m_bLeavingGame; -} -void CPlatformNetworkManagerSony::ResetLeavingGame() -{ - m_bLeavingGame = false; -} +bool CPlatformNetworkManagerSony::IsLocalGame() { return m_bIsOfflineGame; } +bool CPlatformNetworkManagerSony::IsPrivateGame() { return m_bIsPrivateGame; } +bool CPlatformNetworkManagerSony::IsLeavingGame() { return m_bLeavingGame; } +void CPlatformNetworkManagerSony::ResetLeavingGame() { m_bLeavingGame = false; } - -void CPlatformNetworkManagerSony::HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull) -{ - static const char * c_apszStateNames[] = - { - "SNM_STATE_INITIALISING", - "SNM_STATE_INITIALISE_FAILED", - "SNM_STATE_IDLE", - "SNM_STATE_HOSTING", - "SNM_STATE_JOINING", - "SNM_STATE_STARTING", - "SNM_STATE_PLAYING", - "SNM_STATE_LEAVING", - "SNM_STATE_ENDING", +void CPlatformNetworkManagerSony::HandleStateChange( + SQRNetworkManager::eSQRNetworkManagerState oldState, + SQRNetworkManager::eSQRNetworkManagerState newState, + bool idleReasonIsSessionFull) { + static const char* c_apszStateNames[] = { + "SNM_STATE_INITIALISING", "SNM_STATE_INITIALISE_FAILED", + "SNM_STATE_IDLE", "SNM_STATE_HOSTING", + "SNM_STATE_JOINING", "SNM_STATE_STARTING", + "SNM_STATE_PLAYING", "SNM_STATE_LEAVING", + "SNM_STATE_ENDING", }; - app.DebugPrintf( "Network State: %s ==> %s\n", - c_apszStateNames[ oldState ], - c_apszStateNames[ newState ] ); + app.DebugPrintf("Network State: %s ==> %s\n", c_apszStateNames[oldState], + c_apszStateNames[newState]); - if( newState == SQRNetworkManager::SNM_STATE_HOSTING ) - { - m_bLeavingGame = false; - m_bLeaveGameOnTick = false; - m_bHostChanged = false; - g_NetworkManager.StateChange_AnyToHosting(); - } - else if( newState == SQRNetworkManager::SNM_STATE_JOINING ) - { - // 4J Stu - We may be accepting an invite from the DLC menu, so hide the icon + if (newState == SQRNetworkManager::SNM_STATE_HOSTING) { + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + g_NetworkManager.StateChange_AnyToHosting(); + } else if (newState == SQRNetworkManager::SNM_STATE_JOINING) { + // 4J Stu - We may be accepting an invite from the DLC menu, so hide the + // icon #ifdef __ORBIS__ - sceNpCommerceHidePsStoreIcon(); + sceNpCommerceHidePsStoreIcon(); #elif defined __PSVITA__ - sceNpCommerce2HidePsStoreIcon(); + sceNpCommerce2HidePsStoreIcon(); #endif - m_bLeavingGame = false; - m_bLeaveGameOnTick = false; - m_bHostChanged = false; - g_NetworkManager.StateChange_AnyToJoining(); - } - else if( newState == SQRNetworkManager::SNM_STATE_IDLE && oldState == SQRNetworkManager::SNM_STATE_JOINING ) - { - if( idleReasonIsSessionFull ) - { - g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_SERVER_FULL); - } - else - { - g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_NONSPECIFIC); - } - } - else if( newState == SQRNetworkManager::SNM_STATE_IDLE && oldState == SQRNetworkManager::SNM_STATE_HOSTING ) - { - m_bLeavingGame = true; - } - else if( newState == SQRNetworkManager::SNM_STATE_STARTING ) - { - m_lastPlayerEventTimeStart = app.getAppTime(); - - g_NetworkManager.StateChange_AnyToStarting(); - } - // Fix for #93148 - TCR 001: BAS Game Stability: Title will crash for the multiplayer client if host of the game will exit during the clients loading to created world. - // 4J Stu - If the client joins just as the host is exiting, then they can skip to leaving without passing through ending - else if( newState == SQRNetworkManager::SNM_STATE_ENDING ) - { - g_NetworkManager.StateChange_AnyToEnding( oldState == SQRNetworkManager::SNM_STATE_PLAYING ); - - // 4J-PB - Only the host can leave here - the clients will hang if m_bLeavingGame is set to true here - if( m_pSQRNet->IsHost() ) - { - m_bLeavingGame = true; - } - } - - if( newState == SQRNetworkManager::SNM_STATE_IDLE ) - { - // On PS3, sometimes we're getting a SNM_STATE_ENDING transition to SNM_STATE_IDLE on joining, because the server context being deleted sets the state away from SNM_STATE_JOINING before we detect - // the cause for the disconnection. This means we don't pick up on the joining->idle transition. Set disconnection reason here too for this case. - if( idleReasonIsSessionFull ) - { - app.SetDisconnectReason( DisconnectPacket::eDisconnect_ServerFull ); - } - g_NetworkManager.StateChange_AnyToIdle(); - } -} - -void CPlatformNetworkManagerSony::HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize) -{ - if(m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_ENDING) - { - return; - } - - if( playerTo->IsHost() ) - { - // If we are the host we care who this came from - //app.DebugPrintf( "Pushing data into host read queue for user \"%ls\"\n", pPlayerFrom->GetGamertag()); - // Push this data into the read queue for the player that sent it - INetworkPlayer *pPlayerFrom = getNetworkPlayer(playerFrom); - Socket *socket = pPlayerFrom->GetSocket(); - - if(socket != NULL) - socket->pushDataToQueue(data, dataSize, false); - } - else - { - // If we are not the host the message must have come from the host, so we care more about who it is addressed to - INetworkPlayer *pPlayerTo = getNetworkPlayer(playerTo); - Socket *socket = pPlayerTo->GetSocket(); - //app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", apPlayersTo[dwPlayer]->GetGamertag()); - if(socket != NULL) - socket->pushDataToQueue(data, dataSize); - } -} - -void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * pSQRPlayer) -{ - const char * pszDescription; - - // 4J Stu - We create a fake socket for every where that we need an INBOUND queue of game data. Outbound - // is all handled by QNet so we don't need that. Therefore each client player has one, and the host has one - // for each client player. - bool createFakeSocket = false; - bool localPlayer = false; - - NetworkPlayerSony *networkPlayer = (NetworkPlayerSony *)addNetworkPlayer(pSQRPlayer); - - if( pSQRPlayer->IsLocal() ) - { - localPlayer = true; - if( pSQRPlayer->IsHost() ) - { - pszDescription = "local host"; - // 4J Stu - No socket for the localhost as it uses a special loopback queue - - m_machineSQRPrimaryPlayers.push_back( pSQRPlayer ); + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + g_NetworkManager.StateChange_AnyToJoining(); + } else if (newState == SQRNetworkManager::SNM_STATE_IDLE && + oldState == SQRNetworkManager::SNM_STATE_JOINING) { + if (idleReasonIsSessionFull) { + g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_SERVER_FULL); + } else { + g_NetworkManager.StateChange_JoiningToIdle(JOIN_FAILED_NONSPECIFIC); } - else - { + } else if (newState == SQRNetworkManager::SNM_STATE_IDLE && + oldState == SQRNetworkManager::SNM_STATE_HOSTING) { + m_bLeavingGame = true; + } else if (newState == SQRNetworkManager::SNM_STATE_STARTING) { + m_lastPlayerEventTimeStart = app.getAppTime(); + + g_NetworkManager.StateChange_AnyToStarting(); + } + // Fix for #93148 - TCR 001: BAS Game Stability: Title will crash for the + // multiplayer client if host of the game will exit during the clients + // loading to created world. 4J Stu - If the client joins just as the host + // is exiting, then they can skip to leaving without passing through ending + else if (newState == SQRNetworkManager::SNM_STATE_ENDING) { + g_NetworkManager.StateChange_AnyToEnding( + oldState == SQRNetworkManager::SNM_STATE_PLAYING); + + // 4J-PB - Only the host can leave here - the clients will hang if + // m_bLeavingGame is set to true here + if (m_pSQRNet->IsHost()) { + m_bLeavingGame = true; + } + } + + if (newState == SQRNetworkManager::SNM_STATE_IDLE) { + // On PS3, sometimes we're getting a SNM_STATE_ENDING transition to + // SNM_STATE_IDLE on joining, because the server context being deleted + // sets the state away from SNM_STATE_JOINING before we detect the cause + // for the disconnection. This means we don't pick up on the + // joining->idle transition. Set disconnection reason here too for this + // case. + if (idleReasonIsSessionFull) { + app.SetDisconnectReason(DisconnectPacket::eDisconnect_ServerFull); + } + g_NetworkManager.StateChange_AnyToIdle(); + } +} + +void CPlatformNetworkManagerSony::HandleDataReceived( + SQRNetworkPlayer* playerFrom, SQRNetworkPlayer* playerTo, + unsigned char* data, unsigned int dataSize) { + if (m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_ENDING) { + return; + } + + if (playerTo->IsHost()) { + // If we are the host we care who this came from + // app.DebugPrintf( "Pushing data into host read queue for user + // \"%ls\"\n", pPlayerFrom->GetGamertag()); + // Push this data into the read queue for the player that sent it + INetworkPlayer* pPlayerFrom = getNetworkPlayer(playerFrom); + Socket* socket = pPlayerFrom->GetSocket(); + + if (socket != NULL) socket->pushDataToQueue(data, dataSize, false); + } else { + // If we are not the host the message must have come from the host, so + // we care more about who it is addressed to + INetworkPlayer* pPlayerTo = getNetworkPlayer(playerTo); + Socket* socket = pPlayerTo->GetSocket(); + // app.DebugPrintf( "Pushing data into read queue for user \"%ls\"\n", + // apPlayersTo[dwPlayer]->GetGamertag()); + if (socket != NULL) socket->pushDataToQueue(data, dataSize); + } +} + +void CPlatformNetworkManagerSony::HandlePlayerJoined( + SQRNetworkPlayer* pSQRPlayer) { + const char* pszDescription; + + // 4J Stu - We create a fake socket for every where that we need an INBOUND + // queue of game data. Outbound is all handled by QNet so we don't need + // that. Therefore each client player has one, and the host has one for each + // client player. + bool createFakeSocket = false; + bool localPlayer = false; + + NetworkPlayerSony* networkPlayer = + (NetworkPlayerSony*)addNetworkPlayer(pSQRPlayer); + + if (pSQRPlayer->IsLocal()) { + localPlayer = true; + if (pSQRPlayer->IsHost()) { + pszDescription = "local host"; + // 4J Stu - No socket for the localhost as it uses a special + // loopback queue + + m_machineSQRPrimaryPlayers.push_back(pSQRPlayer); + } else { pszDescription = "local"; - // We need an inbound queue on all local players to receive data from the host - createFakeSocket = true; + // We need an inbound queue on all local players to receive data + // from the host + createFakeSocket = true; } - } - else - { - if( pSQRPlayer->IsHost() ) - { + } else { + if (pSQRPlayer->IsHost()) { pszDescription = "remote host"; - } - else - { + } else { pszDescription = "remote"; - // If we are the host, then create a fake socket for every remote player - if( m_pSQRNet->IsHost() ) - { - createFakeSocket = true; - } + // If we are the host, then create a fake socket for every remote + // player + if (m_pSQRNet->IsHost()) { + createFakeSocket = true; + } } - if( m_pSQRNet->IsHost() && !m_bHostChanged ) - { - // Do we already have a primary player for this system? - bool systemHasPrimaryPlayer = false; - for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) - { - SQRNetworkPlayer *pQNetPrimaryPlayer = *it; - if( pSQRPlayer->IsSameSystem(pQNetPrimaryPlayer) ) - { - systemHasPrimaryPlayer = true; - break; - } - } - if( !systemHasPrimaryPlayer ) - m_machineSQRPrimaryPlayers.push_back( pSQRPlayer ); - } + if (m_pSQRNet->IsHost() && !m_bHostChanged) { + // Do we already have a primary player for this system? + bool systemHasPrimaryPlayer = false; + for (AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); + it < m_machineSQRPrimaryPlayers.end(); ++it) { + SQRNetworkPlayer* pQNetPrimaryPlayer = *it; + if (pSQRPlayer->IsSameSystem(pQNetPrimaryPlayer)) { + systemHasPrimaryPlayer = true; + break; + } + } + if (!systemHasPrimaryPlayer) + m_machineSQRPrimaryPlayers.push_back(pSQRPlayer); + } + } + g_NetworkManager.PlayerJoining(networkPlayer); + + if (createFakeSocket == true && !m_bHostChanged) { + g_NetworkManager.CreateSocket(networkPlayer, localPlayer); } - g_NetworkManager.PlayerJoining( networkPlayer ); - - if( createFakeSocket == true && !m_bHostChanged ) - { - g_NetworkManager.CreateSocket( networkPlayer, localPlayer ); - } #if 0 app.DebugPrintf( "Player 0x%p \"%ls\" joined; %s; voice %i; camera %i.\n", @@ -219,332 +187,311 @@ void CPlatformNetworkManagerSony::HandlePlayerJoined(SQRNetworkPlayer * (int) pSQRPlayer->HasCamera() ); #endif + if (m_pSQRNet->IsHost()) { + // 4J-PB - only the host should do this + g_NetworkManager.UpdateAndSetGameSessionData(); + SystemFlagAddPlayer(networkPlayer); + } - if( m_pSQRNet->IsHost() ) - { - // 4J-PB - only the host should do this - g_NetworkManager.UpdateAndSetGameSessionData(); - SystemFlagAddPlayer( networkPlayer ); - } - - for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(playerChangedCallback[idx] != NULL) - playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, false ); - } + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (playerChangedCallback[idx] != NULL) + playerChangedCallback[idx](playerChangedCallbackParam[idx], + networkPlayer, false); + } - if(true) // TODO m_pSQRNet->GetState() == QNET_STATE_GAME_PLAY) - { - int localPlayerCount = 0; - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; - } + if (true) // TODO m_pSQRNet->GetState() == QNET_STATE_GAME_PLAY) + { + int localPlayerCount = 0; + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL) + ++localPlayerCount; + } - float appTime = app.getAppTime(); + float appTime = app.getAppTime(); - // Only record stats for the primary player here - m_lastPlayerEventTimeStart = appTime; - } + // Only record stats for the primary player here + m_lastPlayerEventTimeStart = appTime; + } } -void CPlatformNetworkManagerSony::HandlePlayerLeaving(SQRNetworkPlayer *pSQRPlayer) -{ - //__debugbreak(); +void CPlatformNetworkManagerSony::HandlePlayerLeaving( + SQRNetworkPlayer* pSQRPlayer) { + //__debugbreak(); - app.DebugPrintf( "Player 0x%p leaving.\n", - pSQRPlayer ); + app.DebugPrintf("Player 0x%p leaving.\n", pSQRPlayer); - INetworkPlayer *networkPlayer = getNetworkPlayer(pSQRPlayer); + INetworkPlayer* networkPlayer = getNetworkPlayer(pSQRPlayer); - if( networkPlayer ) - { - // Get our wrapper object associated with this player. - Socket *socket = networkPlayer->GetSocket(); - if( socket != NULL ) - { - // If we are in game then remove this player from the game as well. - // We may get here either from the player requesting to exit the game, - // in which case we they will already have left the game server, or from a disconnection - // where we then have to remove them from the game server - if( m_pSQRNet->IsHost() && !m_bHostChanged ) - { - g_NetworkManager.CloseConnection(networkPlayer); - } + if (networkPlayer) { + // Get our wrapper object associated with this player. + Socket* socket = networkPlayer->GetSocket(); + if (socket != NULL) { + // If we are in game then remove this player from the game as well. + // We may get here either from the player requesting to exit the + // game, in which case we they will already have left the game + // server, or from a disconnection where we then have to remove them + // from the game server + if (m_pSQRNet->IsHost() && !m_bHostChanged) { + g_NetworkManager.CloseConnection(networkPlayer); + } - // Free the wrapper object memory. - // TODO 4J Stu - We may still be using this at the point that the player leaves the session. - // We need this as long as the game server still needs to communicate with the player - //delete socket; + // Free the wrapper object memory. + // TODO 4J Stu - We may still be using this at the point that the + // player leaves the session. We need this as long as the game + // server still needs to communicate with the player + // delete socket; - networkPlayer->SetSocket( NULL ); - } + networkPlayer->SetSocket(NULL); + } - if( m_pSQRNet->IsHost() && !m_bHostChanged ) - { - if( isSystemPrimaryPlayer(pSQRPlayer) ) - { - SQRNetworkPlayer *pNewSQRPrimaryPlayer = NULL; - for(unsigned int i = 0; i < m_pSQRNet->GetPlayerCount(); ++i ) - { - SQRNetworkPlayer *pSQRPlayer2 = m_pSQRNet->GetPlayerByIndex( i ); + if (m_pSQRNet->IsHost() && !m_bHostChanged) { + if (isSystemPrimaryPlayer(pSQRPlayer)) { + SQRNetworkPlayer* pNewSQRPrimaryPlayer = NULL; + for (unsigned int i = 0; i < m_pSQRNet->GetPlayerCount(); ++i) { + SQRNetworkPlayer* pSQRPlayer2 = + m_pSQRNet->GetPlayerByIndex(i); - if ( pSQRPlayer2 != NULL && pSQRPlayer2 != pSQRPlayer && pSQRPlayer2->IsSameSystem( pSQRPlayer ) ) - { - pNewSQRPrimaryPlayer = pSQRPlayer2; - break; - } - } - AUTO_VAR(it, find( m_machineSQRPrimaryPlayers.begin(), m_machineSQRPrimaryPlayers.end(), pSQRPlayer)); - if( it != m_machineSQRPrimaryPlayers.end() ) - { - m_machineSQRPrimaryPlayers.erase( it ); - } + if (pSQRPlayer2 != NULL && pSQRPlayer2 != pSQRPlayer && + pSQRPlayer2->IsSameSystem(pSQRPlayer)) { + pNewSQRPrimaryPlayer = pSQRPlayer2; + break; + } + } + AUTO_VAR(it, + find(m_machineSQRPrimaryPlayers.begin(), + m_machineSQRPrimaryPlayers.end(), pSQRPlayer)); + if (it != m_machineSQRPrimaryPlayers.end()) { + m_machineSQRPrimaryPlayers.erase(it); + } - if( pNewSQRPrimaryPlayer != NULL ) - m_machineSQRPrimaryPlayers.push_back( pNewSQRPrimaryPlayer ); - } + if (pNewSQRPrimaryPlayer != NULL) + m_machineSQRPrimaryPlayers.push_back(pNewSQRPrimaryPlayer); + } - g_NetworkManager.UpdateAndSetGameSessionData( networkPlayer ); - SystemFlagRemovePlayer( networkPlayer ); + g_NetworkManager.UpdateAndSetGameSessionData(networkPlayer); + SystemFlagRemovePlayer(networkPlayer); + } - } + g_NetworkManager.PlayerLeaving(networkPlayer); - g_NetworkManager.PlayerLeaving( networkPlayer ); - - for( int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if(playerChangedCallback[idx] != NULL) - playerChangedCallback[idx]( playerChangedCallbackParam[idx], networkPlayer, true ); - } + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (playerChangedCallback[idx] != NULL) + playerChangedCallback[idx](playerChangedCallbackParam[idx], + networkPlayer, true); + } - if(m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING) - { - int localPlayerCount = 0; - for(unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) - { - if( m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL ) ++localPlayerCount; - } + if (m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING) { + int localPlayerCount = 0; + for (unsigned int idx = 0; idx < XUSER_MAX_COUNT; ++idx) { + if (m_pSQRNet->GetLocalPlayerByUserIndex(idx) != NULL) + ++localPlayerCount; + } - float appTime = app.getAppTime(); - m_lastPlayerEventTimeStart = appTime; - } + float appTime = app.getAppTime(); + m_lastPlayerEventTimeStart = appTime; + } - removeNetworkPlayer(pSQRPlayer); - } + removeNetworkPlayer(pSQRPlayer); + } } -// Update our external data to match the current internal player slots, and resync back out (host only) -void CPlatformNetworkManagerSony::HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers) -{ - m_hostGameSessionData.playerCount = 0; - for(int i = 0; i < SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT; i++ ) - { - if( aPlayers[i] ) - { - m_hostGameSessionData.players[i] = aPlayers[i]->GetUID(); - m_hostGameSessionData.playerCount++; - } - else - { - memset(&m_hostGameSessionData.players[i],0,sizeof(m_hostGameSessionData.players[i])); - } - } - m_pSQRNet->UpdateExternalRoomData(); +// Update our external data to match the current internal player slots, and +// resync back out (host only) +void CPlatformNetworkManagerSony::HandleResyncPlayerRequest( + SQRNetworkPlayer** aPlayers) { + m_hostGameSessionData.playerCount = 0; + for (int i = 0; i < SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT; i++) { + if (aPlayers[i]) { + m_hostGameSessionData.players[i] = aPlayers[i]->GetUID(); + m_hostGameSessionData.playerCount++; + } else { + memset(&m_hostGameSessionData.players[i], 0, + sizeof(m_hostGameSessionData.players[i])); + } + } + m_pSQRNet->UpdateExternalRoomData(); } -void CPlatformNetworkManagerSony::HandleAddLocalPlayerFailed(int idx) -{ - g_NetworkManager.AddLocalPlayerFailed(idx); +void CPlatformNetworkManagerSony::HandleAddLocalPlayerFailed(int idx) { + g_NetworkManager.AddLocalPlayerFailed(idx); } -void CPlatformNetworkManagerSony::HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut) -{ - g_NetworkManager.HandleDisconnect(bLostRoomOnly,bPSNSignOut); +void CPlatformNetworkManagerSony::HandleDisconnect(bool bLostRoomOnly, + bool bPSNSignOut) { + g_NetworkManager.HandleDisconnect(bLostRoomOnly, bPSNSignOut); } -void CPlatformNetworkManagerSony::HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo) -{ - g_NetworkManager.GameInviteReceived( userIndex, pInviteInfo ); +void CPlatformNetworkManagerSony::HandleInviteReceived( + int userIndex, const SQRNetworkManager::PresenceSyncInfo* pInviteInfo) { + g_NetworkManager.GameInviteReceived(userIndex, pInviteInfo); } -extern SQRNetworkManager *testSQRNetworkManager; +extern SQRNetworkManager* testSQRNetworkManager; -bool CPlatformNetworkManagerSony::Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize) -{ - // Create a sony network manager, and go online +bool CPlatformNetworkManagerSony::Initialise( + CGameNetworkManager* pGameNetworkManager, int flagIndexSize) { + // Create a sony network manager, and go online #ifdef __ORBIS__ - m_pSQRNet = new SQRNetworkManager_Orbis(this); - m_pSQRNet->Initialise(); -#elif defined __PS3__ - m_pSQRNet = new SQRNetworkManager_PS3(this); - m_pSQRNet->Initialise(); -#else // __PSVITA__ - // m_pSQRNet = new SQRNetworkManager_Vita(this); - m_bUsingAdhocMode = false; - m_pSQRNet_Vita_Adhoc = new SQRNetworkManager_AdHoc_Vita(this); - m_pSQRNet_Vita = new SQRNetworkManager_Vita(this); + m_pSQRNet = new SQRNetworkManager_Orbis(this); + m_pSQRNet->Initialise(); +#elif defined __PS3__ + m_pSQRNet = new SQRNetworkManager_PS3(this); + m_pSQRNet->Initialise(); +#else // __PSVITA__ + // m_pSQRNet = new SQRNetworkManager_Vita(this); + m_bUsingAdhocMode = false; + m_pSQRNet_Vita_Adhoc = new SQRNetworkManager_AdHoc_Vita(this); + m_pSQRNet_Vita = new SQRNetworkManager_Vita(this); - m_pSQRNet = m_pSQRNet_Vita; + m_pSQRNet = m_pSQRNet_Vita; - // 4J-PB - seems we can't initialise both adhoc and psn comms - from Rohan - "having adhoc matching and matching2 library initialised together results in undesired behaviour", but probably having other parts initialised also is 'undesirable' + // 4J-PB - seems we can't initialise both adhoc and psn comms - from Rohan - + // "having adhoc matching and matching2 library initialised together results + // in undesired behaviour", but probably having other parts initialised also + // is 'undesirable' - m_pSQRNet_Vita->Initialise(); - - if(ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) - { - // we're signed into the PSN, but we won't be online yet, force a sign-in online here - m_pSQRNet_Vita->AttemptPSNSignIn(NULL, NULL); - } + m_pSQRNet_Vita->Initialise(); + if (ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad())) { + // we're signed into the PSN, but we won't be online yet, force a + // sign-in online here + m_pSQRNet_Vita->AttemptPSNSignIn(NULL, NULL); + } #endif - m_pGameNetworkManager = pGameNetworkManager; - m_flagIndexSize = flagIndexSize; - g_pPlatformNetworkManager = this; - for( int i = 0; i < XUSER_MAX_COUNT; i++ ) - { - playerChangedCallback[ i ] = NULL; - } - - m_bLeavingGame = false; - m_bLeaveGameOnTick = false; - m_bHostChanged = false; - m_bLeaveRoomWhenLeavingGame = true; + m_pGameNetworkManager = pGameNetworkManager; + m_flagIndexSize = flagIndexSize; + g_pPlatformNetworkManager = this; + for (int i = 0; i < XUSER_MAX_COUNT; i++) { + playerChangedCallback[i] = NULL; + } - m_bSearchPending = false; + m_bLeavingGame = false; + m_bLeaveGameOnTick = false; + m_bHostChanged = false; + m_bLeaveRoomWhenLeavingGame = true; - m_bIsOfflineGame = false; - m_pSearchParam = nullptr; - m_SessionsUpdatedCallback = nullptr; + m_bSearchPending = false; - m_searchResultsCount = 0; - m_pSearchResults = NULL; - - m_lastSearchStartTime = 0; + m_bIsOfflineGame = false; + m_pSearchParam = nullptr; + m_SessionsUpdatedCallback = nullptr; + + m_searchResultsCount = 0; + m_pSearchResults = NULL; + + m_lastSearchStartTime = 0; // Success! return true; } -void CPlatformNetworkManagerSony::Terminate() -{ - m_pSQRNet->Terminate(); +void CPlatformNetworkManagerSony::Terminate() { m_pSQRNet->Terminate(); } + +int CPlatformNetworkManagerSony::GetJoiningReadyPercentage() { + return m_pSQRNet->GetJoiningReadyPercentage(); } -int CPlatformNetworkManagerSony::GetJoiningReadyPercentage() -{ - return m_pSQRNet->GetJoiningReadyPercentage(); -} +int CPlatformNetworkManagerSony::CorrectErrorIDS(int IDS) { + // Attempts to remap the following messages to provide something that PS3 + // TCRs are happier with + // + // IDS_CONNECTION_LOST - "Connection lost" + // IDS_CONNECTION_FAILED - "Connection failed" + // IDS_CONNECTION_LOST_LIVE - "Connection to "PSN" was + //lost. Exiting to the main menu." + // IDS_CONNECTION_LOST_LIVE_NO_EXIT - "Connection to "PSN" was lost." + // IDS_CONNECTION_LOST_SERVER - "Connection to the server + // was lost. Exiting to the main menu." + // + // Map to: + // + // IDS_ERROR_NETWORK - "A network error + // has occurred" IDS_ERROR_NETWORK_TITLE - "Network + // Error" IDS_ERROR_NETWORK_EXIT - "A network error + // has occurred. Exiting to Main Menu." IDS_ERROR_PSN_SIGN_OUT + // - You have been signed out from the "PSN". IDS_ERROR_PSN_SIGN_OUT_EXIT + // - You have been signed out from the "PSN". Exiting to Main Menu -int CPlatformNetworkManagerSony::CorrectErrorIDS(int IDS) -{ - // Attempts to remap the following messages to provide something that PS3 TCRs are happier with - // - // IDS_CONNECTION_LOST - "Connection lost" - // IDS_CONNECTION_FAILED - "Connection failed" - // IDS_CONNECTION_LOST_LIVE - "Connection to "PSN" was lost. Exiting to the main menu." - // IDS_CONNECTION_LOST_LIVE_NO_EXIT - "Connection to "PSN" was lost." - // IDS_CONNECTION_LOST_SERVER - "Connection to the server was lost. Exiting to the main menu." - // - // Map to: - // - // IDS_ERROR_NETWORK - "A network error has occurred" - // IDS_ERROR_NETWORK_TITLE - "Network Error" - // IDS_ERROR_NETWORK_EXIT - "A network error has occurred. Exiting to Main Menu." - // IDS_ERROR_PSN_SIGN_OUT - You have been signed out from the "PSN". - // IDS_ERROR_PSN_SIGN_OUT_EXIT - You have been signed out from the "PSN". Exiting to Main Menu - - // Determine if we'd prefer to present errors as a signing out issue, rather than a network issue, based on whether we have a network connection at all or not - bool preferSignoutError = false; - int state; + // Determine if we'd prefer to present errors as a signing out issue, rather + // than a network issue, based on whether we have a network connection at + // all or not + bool preferSignoutError = false; + int state; #ifdef __PS3__ - int ret = cellNetCtlGetState( &state ); - int IPObtainedState = CELL_NET_CTL_STATE_IPObtained; + int ret = cellNetCtlGetState(&state); + int IPObtainedState = CELL_NET_CTL_STATE_IPObtained; #elif defined __ORBIS__ - int ret = sceNetCtlGetState( &state ); - int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; + int ret = sceNetCtlGetState(&state); + int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; #elif defined __PSVITA__ - int ret = sceNetCtlInetGetState( &state ); - int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; + int ret = sceNetCtlInetGetState(&state); + int IPObtainedState = SCE_NET_CTL_STATE_IPOBTAINED; #endif - if( ret == 0 ) - { - if( state == IPObtainedState ) - { - preferSignoutError = true; - } - } + if (ret == 0) { + if (state == IPObtainedState) { + preferSignoutError = true; + } + } #ifdef __PSVITA__ - // If we're in ad-hoc mode this problem definitely wasn't PSN related - if (usingAdhocMode()) preferSignoutError = false; + // If we're in ad-hoc mode this problem definitely wasn't PSN related + if (usingAdhocMode()) preferSignoutError = false; #endif - // If we're the host we haven't lost connection to the server - if (IDS == IDS_CONNECTION_LOST_SERVER && g_NetworkManager.IsHost()) - { - IDS = IDS_CONNECTION_LOST_LIVE; - } + // If we're the host we haven't lost connection to the server + if (IDS == IDS_CONNECTION_LOST_SERVER && g_NetworkManager.IsHost()) { + IDS = IDS_CONNECTION_LOST_LIVE; + } - switch(IDS) - { - case IDS_CONNECTION_LOST: - case IDS_CONNECTION_FAILED: - return IDS_ERROR_NETWORK_TITLE; - case IDS_CONNECTION_LOST_LIVE: - if( preferSignoutError ) - { - return IDS_ERROR_PSN_SIGN_OUT_EXIT; - } - else - { - return IDS_ERROR_NETWORK_EXIT; - } - case IDS_CONNECTION_LOST_LIVE_NO_EXIT: - if( preferSignoutError ) - { - return IDS_ERROR_PSN_SIGN_OUT; - } - else - { - return IDS_ERROR_NETWORK_TITLE; - } - break; + switch (IDS) { + case IDS_CONNECTION_LOST: + case IDS_CONNECTION_FAILED: + return IDS_ERROR_NETWORK_TITLE; + case IDS_CONNECTION_LOST_LIVE: + if (preferSignoutError) { + return IDS_ERROR_PSN_SIGN_OUT_EXIT; + } else { + return IDS_ERROR_NETWORK_EXIT; + } + case IDS_CONNECTION_LOST_LIVE_NO_EXIT: + if (preferSignoutError) { + return IDS_ERROR_PSN_SIGN_OUT; + } else { + return IDS_ERROR_NETWORK_TITLE; + } + break; #ifdef __PSVITA__ - case IDS_CONNECTION_LOST_SERVER: - if(preferSignoutError) - { - if(ProfileManager.IsSignedInPSN(ProfileManager.GetPrimaryPad()) == false) - return IDS_ERROR_PSN_SIGN_OUT_EXIT; - } + case IDS_CONNECTION_LOST_SERVER: + if (preferSignoutError) { + if (ProfileManager.IsSignedInPSN( + ProfileManager.GetPrimaryPad()) == false) + return IDS_ERROR_PSN_SIGN_OUT_EXIT; + } #endif - default: - return IDS; - } - - + default: + return IDS; + } } -bool CPlatformNetworkManagerSony::isSystemPrimaryPlayer(SQRNetworkPlayer *pSQRPlayer) -{ - bool playerIsSystemPrimary = false; - for(AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); it < m_machineSQRPrimaryPlayers.end(); ++it) - { - SQRNetworkPlayer *pSQRPrimaryPlayer = *it; - if( pSQRPrimaryPlayer == pSQRPlayer ) - { - playerIsSystemPrimary = true; - break; - } - } - return playerIsSystemPrimary; +bool CPlatformNetworkManagerSony::isSystemPrimaryPlayer( + SQRNetworkPlayer* pSQRPlayer) { + bool playerIsSystemPrimary = false; + for (AUTO_VAR(it, m_machineSQRPrimaryPlayers.begin()); + it < m_machineSQRPrimaryPlayers.end(); ++it) { + SQRNetworkPlayer* pSQRPrimaryPlayer = *it; + if (pSQRPrimaryPlayer == pSQRPlayer) { + playerIsSystemPrimary = true; + break; + } + } + return playerIsSystemPrimary; } -// We call this twice a frame, either side of the render call so is a good place to "tick" things -void CPlatformNetworkManagerSony::DoWork() -{ +// We call this twice a frame, either side of the render call so is a good place +// to "tick" things +void CPlatformNetworkManagerSony::DoWork() { #if 0 DWORD dwNotifyId; ULONG_PTR ulpNotifyParam; @@ -583,70 +530,63 @@ void CPlatformNetworkManagerSony::DoWork() m_pIQNet->DoWork(); #else - TickSearch(); + TickSearch(); - if( m_bLeaveGameOnTick ) - { - m_pSQRNet->LeaveRoom(m_bLeaveRoomWhenLeavingGame); - m_bLeaveGameOnTick = false; - } + if (m_bLeaveGameOnTick) { + m_pSQRNet->LeaveRoom(m_bLeaveRoomWhenLeavingGame); + m_bLeaveGameOnTick = false; + } - m_pSQRNet->Tick(); + m_pSQRNet->Tick(); #endif } -int CPlatformNetworkManagerSony::GetPlayerCount() -{ - return m_pSQRNet->GetPlayerCount(); +int CPlatformNetworkManagerSony::GetPlayerCount() { + return m_pSQRNet->GetPlayerCount(); } -bool CPlatformNetworkManagerSony::ShouldMessageForFullSession() -{ - return false; +bool CPlatformNetworkManagerSony::ShouldMessageForFullSession() { + return false; } -int CPlatformNetworkManagerSony::GetOnlinePlayerCount() -{ - return m_pSQRNet->GetOnlinePlayerCount(); +int CPlatformNetworkManagerSony::GetOnlinePlayerCount() { + return m_pSQRNet->GetOnlinePlayerCount(); } -int CPlatformNetworkManagerSony::GetLocalPlayerMask(int playerIndex) -{ - return 1 << playerIndex; +int CPlatformNetworkManagerSony::GetLocalPlayerMask(int playerIndex) { + return 1 << playerIndex; } -bool CPlatformNetworkManagerSony::AddLocalPlayerByUserIndex( int userIndex ) -{ - return m_pSQRNet->AddLocalPlayerByUserIndex(userIndex); +bool CPlatformNetworkManagerSony::AddLocalPlayerByUserIndex(int userIndex) { + return m_pSQRNet->AddLocalPlayerByUserIndex(userIndex); } -bool CPlatformNetworkManagerSony::RemoveLocalPlayerByUserIndex( int userIndex ) -{ - SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(userIndex); - INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); +bool CPlatformNetworkManagerSony::RemoveLocalPlayerByUserIndex(int userIndex) { + SQRNetworkPlayer* pSQRPlayer = + m_pSQRNet->GetLocalPlayerByUserIndex(userIndex); + INetworkPlayer* pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - if(pNetworkPlayer != NULL) - { - Socket *socket = pNetworkPlayer->GetSocket(); + if (pNetworkPlayer != NULL) { + Socket* socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) - { - // We can't remove the player from qnet until we have stopped using it to communicate - C4JThread* thread = new C4JThread(&CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc, pNetworkPlayer, "RemovePlayerOnSocketClosed"); - thread->SetProcessor( CPU_CORE_REMOVE_PLAYER ); - thread->Run(); - } - else - { - // Safe to remove the player straight away - return m_pSQRNet->RemoveLocalPlayerByUserIndex(userIndex); - } - } - return true; + if (socket != NULL) { + // We can't remove the player from qnet until we have stopped using + // it to communicate + C4JThread* thread = + new C4JThread(&CPlatformNetworkManagerSony:: + RemovePlayerOnSocketClosedThreadProc, + pNetworkPlayer, "RemovePlayerOnSocketClosed"); + thread->SetProcessor(CPU_CORE_REMOVE_PLAYER); + thread->Run(); + } else { + // Safe to remove the player straight away + return m_pSQRNet->RemoveLocalPlayerByUserIndex(userIndex); + } + } + return true; } -bool CPlatformNetworkManagerSony::IsInStatsEnabledSession() -{ +bool CPlatformNetworkManagerSony::IsInStatsEnabledSession() { #if 0 DWORD dataSize = sizeof(QNET_LIVE_STATS_MODE); QNET_LIVE_STATS_MODE statsMode; @@ -656,12 +596,12 @@ bool CPlatformNetworkManagerSony::IsInStatsEnabledSession() bool statsEnabled = statsMode == QNET_LIVE_STATS_MODE_ENABLED; return m_pIQNet->GetState() != QNET_STATE_IDLE && statsEnabled; #endif - return true; + return true; } -bool CPlatformNetworkManagerSony::SessionHasSpace(unsigned int spaceRequired /*= 1*/) -{ - return m_pSQRNet->SessionHasSpace(spaceRequired); +bool CPlatformNetworkManagerSony::SessionHasSpace( + unsigned int spaceRequired /*= 1*/) { + return m_pSQRNet->SessionHasSpace(spaceRequired); #if 0 // This function is used while a session is running, so all players trying to join // should use public slots, @@ -680,118 +620,120 @@ bool CPlatformNetworkManagerSony::SessionHasSpace(unsigned int spaceRequired /*= return spaceLeft >= spaceRequired; #else - return true; + return true; #endif } -void CPlatformNetworkManagerSony::SendInviteGUI(int quadrant) -{ - m_pSQRNet->SendInviteGUI(); +void CPlatformNetworkManagerSony::SendInviteGUI(int quadrant) { + m_pSQRNet->SendInviteGUI(); } -bool CPlatformNetworkManagerSony::IsAddingPlayer() -{ - return false; +bool CPlatformNetworkManagerSony::IsAddingPlayer() { return false; } + +bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) { + if (m_bLeavingGame) return true; + + m_bLeavingGame = true; + + // If we are a client, wait for all client connections to close + // TODO Possibly need to do multiple objects depending on how split screen + // online works + SQRNetworkPlayer* pSQRPlayer = + m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); + INetworkPlayer* pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + + if (pNetworkPlayer != NULL) { + Socket* socket = pNetworkPlayer->GetSocket(); + + if (socket != NULL) { + // printf("Waiting for socket closed event\n"); + socket->m_socketClosedEvent->WaitForSignal(INFINITE); + + // The session might be gone once the socket releases + if (IsInSession()) { + // printf("Socket closed event has fired\n"); + // 4J Stu - Clear our reference to this socket + pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex( + g_NetworkManager.GetPrimaryPad()); + pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + pNetworkPlayer->SetSocket(NULL); + } + delete socket; + } else { + // printf("Socket is already NULL\n"); + } + } + + // If we are the host wait for the game server to end + if (m_pSQRNet->IsHost() && g_NetworkManager.ServerStoppedValid()) { + m_pSQRNet->EndGame(); + g_NetworkManager.ServerStoppedWait(); + g_NetworkManager.ServerStoppedDestroy(); + } + + return _LeaveGame(bMigrateHost, true); } -bool CPlatformNetworkManagerSony::LeaveGame(bool bMigrateHost) -{ - if( m_bLeavingGame ) return true; +bool CPlatformNetworkManagerSony::_LeaveGame(bool bMigrateHost, + bool bLeaveRoom) { + // 4J Stu - Fix for #10490 - TCR 001 BAS Game Stability: When a party of + // four players leave a world to join another world without saving the title + // will crash. Changed this to make it threadsafe + m_bLeavingGame = + true; // Added for Sony platforms but unsure why the 360 doesn't need + // it - without this, the leaving triggered by this causes the + // game to respond by leaving again when it transitions to the + // SNM_STATE_ENDING state + m_bLeaveRoomWhenLeavingGame = bLeaveRoom; + m_bLeaveGameOnTick = true; + m_migrateHostOnLeave = bMigrateHost; - m_bLeavingGame = true; - - // If we are a client, wait for all client connections to close - // TODO Possibly need to do multiple objects depending on how split screen online works - SQRNetworkPlayer *pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); - INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - - if(pNetworkPlayer != NULL) - { - Socket *socket = pNetworkPlayer->GetSocket(); - - if( socket != NULL ) - { - //printf("Waiting for socket closed event\n"); - socket->m_socketClosedEvent->WaitForSignal(INFINITE); - - // The session might be gone once the socket releases - if( IsInSession() ) - { - //printf("Socket closed event has fired\n"); - // 4J Stu - Clear our reference to this socket - pSQRPlayer = m_pSQRNet->GetLocalPlayerByUserIndex(g_NetworkManager.GetPrimaryPad()); - pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - pNetworkPlayer->SetSocket( NULL ); - } - delete socket; - } - else - { - //printf("Socket is already NULL\n"); - } - } - - // If we are the host wait for the game server to end - if(m_pSQRNet->IsHost() && g_NetworkManager.ServerStoppedValid()) - { - m_pSQRNet->EndGame(); - g_NetworkManager.ServerStoppedWait(); - g_NetworkManager.ServerStoppedDestroy(); - } - - return _LeaveGame(bMigrateHost, true); + return true; } -bool CPlatformNetworkManagerSony::_LeaveGame(bool bMigrateHost, bool bLeaveRoom) -{ - // 4J Stu - Fix for #10490 - TCR 001 BAS Game Stability: When a party of four players leave a world to join another world without saving the title will crash. - // Changed this to make it threadsafe - m_bLeavingGame = true; // Added for Sony platforms but unsure why the 360 doesn't need it - without this, the leaving triggered by this causes the game to respond by leaving again when it transitions to the SNM_STATE_ENDING state - m_bLeaveRoomWhenLeavingGame = bLeaveRoom; - m_bLeaveGameOnTick = true; - m_migrateHostOnLeave = bMigrateHost; +void CPlatformNetworkManagerSony::HostGame( + int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, + unsigned char privateSlots /*= 0*/) { + // #ifdef _XBOX + // 4J Stu - We probably did this earlier as well, but just to be sure! + SetLocalGame(!bOnlineGame); + SetPrivateGame(bIsPrivate); + SystemFlagReset(); - return true; + // Make sure that the Primary Pad is in by default + localUsersMask |= GetLocalPlayerMask(g_NetworkManager.GetPrimaryPad()); + + _HostGame(localUsersMask, publicSlots, privateSlots); + // #endif } -void CPlatformNetworkManagerSony::HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) -{ -// #ifdef _XBOX - // 4J Stu - We probably did this earlier as well, but just to be sure! - SetLocalGame( !bOnlineGame ); - SetPrivateGame( bIsPrivate ); - SystemFlagReset(); +void CPlatformNetworkManagerSony::_HostGame( + int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, + unsigned char privateSlots /*= 0*/) { + // Start hosting a new game - // Make sure that the Primary Pad is in by default - localUsersMask |= GetLocalPlayerMask( g_NetworkManager.GetPrimaryPad() ); + memset(&m_hostGameSessionData, 0, sizeof(m_hostGameSessionData)); + m_hostGameSessionData.netVersion = MINECRAFT_NET_VERSION; + m_hostGameSessionData.isJoinable = !IsPrivateGame(); + m_hostGameSessionData.isReadyToJoin = false; + m_hostGameSessionData.playerCount = 0; + m_hostGameSessionData.m_uiGameHostSettings = + app.GetGameHostOption(eGameHostOption_All); + for (int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++) { + if (usersMask & (1 << i)) { + m_hostGameSessionData.playerCount++; + } + } - _HostGame( localUsersMask, publicSlots, privateSlots ); -//#endif + m_pSQRNet->CreateAndJoinRoom( + g_NetworkManager.GetPrimaryPad(), usersMask, &m_hostGameSessionData, + sizeof(m_hostGameSessionData), + IsLocalGame()); // Should be using: g_NetworkManager.GetLockedProfile() + // but that isn't being set currently } -void CPlatformNetworkManagerSony::_HostGame(int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) -{ - // Start hosting a new game - - memset(&m_hostGameSessionData,0,sizeof(m_hostGameSessionData)); - m_hostGameSessionData.netVersion = MINECRAFT_NET_VERSION; - m_hostGameSessionData.isJoinable = !IsPrivateGame(); - m_hostGameSessionData.isReadyToJoin = false; - m_hostGameSessionData.playerCount = 0; - m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); - for( int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++ ) - { - if( usersMask & ( 1 << i ) ) - { - m_hostGameSessionData.playerCount++; - } - } - - m_pSQRNet->CreateAndJoinRoom(g_NetworkManager.GetPrimaryPad(),usersMask, &m_hostGameSessionData, sizeof(m_hostGameSessionData), IsLocalGame()); // Should be using: g_NetworkManager.GetLockedProfile() but that isn't being set currently -} - -bool CPlatformNetworkManagerSony::_StartGame() -{ +bool CPlatformNetworkManagerSony::_StartGame() { #if 0 // Set the options that now allow players to join this game BOOL enableJip = TRUE; // Must always be true othewise nobody can join the game while in the PLAY state @@ -803,41 +745,35 @@ bool CPlatformNetworkManagerSony::_StartGame() return ( m_pIQNet->StartGame() == S_OK ); #else - m_pSQRNet->StartGame(); - return true; + m_pSQRNet->StartGame(); + return true; #endif } -int CPlatformNetworkManagerSony::JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex) -{ - int joinPlayerCount = 0; - for( int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++ ) - { - if( localUsersMask & ( 1 << i ) ) - { - joinPlayerCount++; - } - } - GameSessionData *gameSession = (GameSessionData *)(&searchResult->data); - if( ( gameSession->playerCount + joinPlayerCount ) > SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT ) - { - return CGameNetworkManager::JOINGAME_FAIL_SERVER_FULL; - } +int CPlatformNetworkManagerSony::JoinGame(FriendSessionInfo* searchResult, + int localUsersMask, + int primaryUserIndex) { + int joinPlayerCount = 0; + for (int i = 0; i < SQRNetworkManager::MAX_LOCAL_PLAYER_COUNT; i++) { + if (localUsersMask & (1 << i)) { + joinPlayerCount++; + } + } + GameSessionData* gameSession = (GameSessionData*)(&searchResult->data); + if ((gameSession->playerCount + joinPlayerCount) > + SQRNetworkManager::MAX_ONLINE_PLAYER_COUNT) { + return CGameNetworkManager::JOINGAME_FAIL_SERVER_FULL; + } - if( m_pSQRNet->JoinRoom(&searchResult->searchResult, localUsersMask) ) - { - return CGameNetworkManager::JOINGAME_SUCCESS; - } - else - { - return CGameNetworkManager::JOINGAME_FAIL_GENERAL; - } + if (m_pSQRNet->JoinRoom(&searchResult->searchResult, localUsersMask)) { + return CGameNetworkManager::JOINGAME_SUCCESS; + } else { + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } } -bool CPlatformNetworkManagerSony::SetLocalGame(bool isLocal) -{ - if( m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_IDLE) - { +bool CPlatformNetworkManagerSony::SetLocalGame(bool isLocal) { + if (m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_IDLE) { #if 0 QNET_SESSIONTYPE sessionType = isLocal ? QNET_SESSIONTYPE_LOCAL : QNET_SESSIONTYPE_LIVE_STANDARD; m_pIQNet->SetOpt(QNET_OPTION_TYPE_SESSIONTYPE, &sessionType , sizeof QNET_SESSIONTYPE); @@ -854,45 +790,45 @@ bool CPlatformNetworkManagerSony::SetLocalGame(bool isLocal) m_pIQNet->SetOpt(QNET_OPTION_LIVE_PRESENCE_MODE, &presenceMode , sizeof QNET_LIVE_PRESENCE_MODE); #endif - m_bIsOfflineGame = isLocal; - app.DebugPrintf("Setting as local game: %s\n", isLocal ? "yes" : "no" ); - } - else - { - app.DebugPrintf("Tried to change session type while not in idle or offline state\n"); - } + m_bIsOfflineGame = isLocal; + app.DebugPrintf("Setting as local game: %s\n", isLocal ? "yes" : "no"); + } else { + app.DebugPrintf( + "Tried to change session type while not in idle or offline " + "state\n"); + } - return true; + return true; } -void CPlatformNetworkManagerSony::SetPrivateGame(bool isPrivate) -{ - app.DebugPrintf("Setting as private game: %s\n", isPrivate ? "yes" : "no" ); - m_bIsPrivateGame = isPrivate; +void CPlatformNetworkManagerSony::SetPrivateGame(bool isPrivate) { + app.DebugPrintf("Setting as private game: %s\n", isPrivate ? "yes" : "no"); + m_bIsPrivateGame = isPrivate; } -void CPlatformNetworkManagerSony::RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - playerChangedCallback[iPad] = callback; - playerChangedCallbackParam[iPad] = callbackParam; +void CPlatformNetworkManagerSony::RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + playerChangedCallback[iPad] = callback; + playerChangedCallbackParam[iPad] = callbackParam; } -void CPlatformNetworkManagerSony::UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam) -{ - if(playerChangedCallbackParam[iPad] == callbackParam) - { - playerChangedCallback[iPad] = NULL; - playerChangedCallbackParam[iPad] = NULL; - } +void CPlatformNetworkManagerSony::UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam) { + if (playerChangedCallbackParam[iPad] == callbackParam) { + playerChangedCallback[iPad] = NULL; + playerChangedCallbackParam[iPad] = NULL; + } } -void CPlatformNetworkManagerSony::HandleSignInChange() -{ - return; -} +void CPlatformNetworkManagerSony::HandleSignInChange() { return; } -bool CPlatformNetworkManagerSony::_RunNetworkGame() -{ +bool CPlatformNetworkManagerSony::_RunNetworkGame() { #if 0 // We delay actually starting the session so that we know the game server is running by the time the clients try to join // This does result in a host advantage @@ -907,175 +843,168 @@ bool CPlatformNetworkManagerSony::_RunNetworkGame() BOOL enablePres = !IsPrivateGame() && !IsLocalGame(); m_pIQNet->SetOpt( QNET_OPTION_PRESENCE_JOIN_MODE, &enablePres, sizeof BOOL ); #endif - if( IsHost() ) - { - m_pSQRNet->StartGame(); - m_hostGameSessionData.isReadyToJoin = true; - m_pSQRNet->UpdateExternalRoomData(); - m_pSQRNet->SetPresenceDataStartHostingGame(); - } + if (IsHost()) { + m_pSQRNet->StartGame(); + m_hostGameSessionData.isReadyToJoin = true; + m_pSQRNet->UpdateExternalRoomData(); + m_pSQRNet->SetPresenceDataStartHostingGame(); + } - return true; + return true; } -// Note that this does less than the xbox equivalent as we have HandleResyncPlayerRequest that is called by the underlying SQRNetworkManager when players are added/removed etc., so this -// call is only used to update the game host settings & then do the final push out of the data. -void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving /*= NULL*/) -{ - if( this->m_bLeavingGame ) - return; +// Note that this does less than the xbox equivalent as we have +// HandleResyncPlayerRequest that is called by the underlying SQRNetworkManager +// when players are added/removed etc., so this call is only used to update the +// game host settings & then do the final push out of the data. +void CPlatformNetworkManagerSony::UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving /*= NULL*/) { + if (this->m_bLeavingGame) return; - m_hostGameSessionData.hostPlayerUID = GetHostPlayer()->GetUID(); + m_hostGameSessionData.hostPlayerUID = GetHostPlayer()->GetUID(); #ifdef __PSVITA__ - if(usingAdhocMode()) - { - m_hostGameSessionData.hostPlayerUID.setForAdhoc(); - } -#endif + if (usingAdhocMode()) { + m_hostGameSessionData.hostPlayerUID.setForAdhoc(); + } +#endif - m_hostGameSessionData.m_uiGameHostSettings = app.GetGameHostOption(eGameHostOption_All); + m_hostGameSessionData.m_uiGameHostSettings = + app.GetGameHostOption(eGameHostOption_All); - // If this is called With a pNetworkPlayerLeaving, then the call has ultimately started within SQRNetworkManager::RemoveRemotePlayersAndSync, so we don't need to sync each change - // as that function does a sync at the end of all changes. - if( pNetworkPlayerLeaving == NULL ) - { - m_pSQRNet->UpdateExternalRoomData(); - } + // If this is called With a pNetworkPlayerLeaving, then the call has + // ultimately started within SQRNetworkManager::RemoveRemotePlayersAndSync, + // so we don't need to sync each change as that function does a sync at the + // end of all changes. + if (pNetworkPlayerLeaving == NULL) { + m_pSQRNet->UpdateExternalRoomData(); + } } -int CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc( void* lpParam ) -{ - INetworkPlayer *pNetworkPlayer = (INetworkPlayer *)lpParam; +int CPlatformNetworkManagerSony::RemovePlayerOnSocketClosedThreadProc( + void* lpParam) { + INetworkPlayer* pNetworkPlayer = (INetworkPlayer*)lpParam; - Socket *socket = pNetworkPlayer->GetSocket(); + Socket* socket = pNetworkPlayer->GetSocket(); - if( socket != NULL ) - { - //printf("Waiting for socket closed event\n"); - socket->m_socketClosedEvent->WaitForSignal(INFINITE); + if (socket != NULL) { + // printf("Waiting for socket closed event\n"); + socket->m_socketClosedEvent->WaitForSignal(INFINITE); - //printf("Socket closed event has fired\n"); - // 4J Stu - Clear our reference to this socket - pNetworkPlayer->SetSocket( NULL ); - delete socket; - } + // printf("Socket closed event has fired\n"); + // 4J Stu - Clear our reference to this socket + pNetworkPlayer->SetSocket(NULL); + delete socket; + } - return g_pPlatformNetworkManager->RemoveLocalPlayer( pNetworkPlayer ); + return g_pPlatformNetworkManager->RemoveLocalPlayer(pNetworkPlayer); } -bool CPlatformNetworkManagerSony::RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ) -{ - if( pNetworkPlayer->IsLocal() ) - { - return m_pSQRNet->RemoveLocalPlayerByUserIndex( pNetworkPlayer->GetUserIndex() ); - } +bool CPlatformNetworkManagerSony::RemoveLocalPlayer( + INetworkPlayer* pNetworkPlayer) { + if (pNetworkPlayer->IsLocal()) { + return m_pSQRNet->RemoveLocalPlayerByUserIndex( + pNetworkPlayer->GetUserIndex()); + } - return true; + return true; } -CPlatformNetworkManagerSony::PlayerFlags::PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count) -{ - // 4J Stu - Don't assert, just make it a multiple of 8! This count is calculated from a load of separate values, - // and makes tweaking world/render sizes a pain if we hit an assert here - count = (count + 8 - 1) & ~(8 - 1); - //assert( ( count % 8 ) == 0 ); - this->m_pNetworkPlayer = pNetworkPlayer; - this->flags = new unsigned char [ count / 8 ]; - memset( this->flags, 0, count / 8 ); - this->count = count; +CPlatformNetworkManagerSony::PlayerFlags::PlayerFlags( + INetworkPlayer* pNetworkPlayer, unsigned int count) { + // 4J Stu - Don't assert, just make it a multiple of 8! This count is + // calculated from a load of separate values, and makes tweaking + // world/render sizes a pain if we hit an assert here + count = (count + 8 - 1) & ~(8 - 1); + // assert( ( count % 8 ) == 0 ); + this->m_pNetworkPlayer = pNetworkPlayer; + this->flags = new unsigned char[count / 8]; + memset(this->flags, 0, count / 8); + this->count = count; } -CPlatformNetworkManagerSony::PlayerFlags::~PlayerFlags() -{ - delete [] flags; +CPlatformNetworkManagerSony::PlayerFlags::~PlayerFlags() { delete[] flags; } + +// Add a player to the per system flag storage - if we've already got a player +// from that system, copy its flags over +void CPlatformNetworkManagerSony::SystemFlagAddPlayer( + INetworkPlayer* pNetworkPlayer) { + PlayerFlags* newPlayerFlags = + new PlayerFlags(pNetworkPlayer, m_flagIndexSize); + // If any of our existing players are on the same system, then copy over + // flags from that one + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer)) { + memcpy(newPlayerFlags->flags, m_playerFlags[i]->flags, + m_playerFlags[i]->count / 8); + break; + } + } + m_playerFlags.push_back(newPlayerFlags); } -// Add a player to the per system flag storage - if we've already got a player from that system, copy its flags over -void CPlatformNetworkManagerSony::SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer) -{ - PlayerFlags *newPlayerFlags = new PlayerFlags( pNetworkPlayer, m_flagIndexSize); - // If any of our existing players are on the same system, then copy over flags from that one - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) - { - memcpy( newPlayerFlags->flags, m_playerFlags[i]->flags, m_playerFlags[i]->count / 8 ); - break; - } - } - m_playerFlags.push_back(newPlayerFlags); +// Remove a player from the per system flag storage - just maintains the +// m_playerFlags vector without any gaps in it +void CPlatformNetworkManagerSony::SystemFlagRemovePlayer( + INetworkPlayer* pNetworkPlayer) { + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer) { + delete m_playerFlags[i]; + m_playerFlags[i] = m_playerFlags.back(); + m_playerFlags.pop_back(); + return; + } + } } -// Remove a player from the per system flag storage - just maintains the m_playerFlags vector without any gaps in it -void CPlatformNetworkManagerSony::SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer) -{ - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) - { - delete m_playerFlags[i]; - m_playerFlags[i] = m_playerFlags.back(); - m_playerFlags.pop_back(); - return; - } - } +void CPlatformNetworkManagerSony::SystemFlagReset() { + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + delete m_playerFlags[i]; + } + m_playerFlags.clear(); } -void CPlatformNetworkManagerSony::SystemFlagReset() -{ - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - delete m_playerFlags[i]; - } - m_playerFlags.clear(); +// Set a per system flag - this is done by setting the flag on every player that +// shares that system +void CPlatformNetworkManagerSony::SystemFlagSet(INetworkPlayer* pNetworkPlayer, + int index) { + if ((index < 0) || (index >= m_flagIndexSize)) return; + if (pNetworkPlayer == NULL) return; + + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer)) { + m_playerFlags[i]->flags[index / 8] |= (128 >> (index % 8)); + } + } } -// Set a per system flag - this is done by setting the flag on every player that shares that system -void CPlatformNetworkManagerSony::SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index) -{ - if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return; - if( pNetworkPlayer == NULL ) return; +// Get value of a per system flag - can be read from the flags of the passed in +// player as anything else sent to that system should also have been duplicated +// here +bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer* pNetworkPlayer, + int index) { + if ((index < 0) || (index >= m_flagIndexSize)) return false; + if (pNetworkPlayer == NULL) { + return false; + } - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( pNetworkPlayer->IsSameSystem(m_playerFlags[i]->m_pNetworkPlayer) ) - { - m_playerFlags[i]->flags[ index / 8 ] |= ( 128 >> ( index % 8 ) ); - } - } + for (unsigned int i = 0; i < m_playerFlags.size(); i++) { + if (m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer) { + return ((m_playerFlags[i]->flags[index / 8] & + (128 >> (index % 8))) != 0); + } + } + return false; } -// Get value of a per system flag - can be read from the flags of the passed in player as anything else sent to that -// system should also have been duplicated here -bool CPlatformNetworkManagerSony::SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index) -{ - if( ( index < 0 ) || ( index >= m_flagIndexSize ) ) return false; - if( pNetworkPlayer == NULL ) - { - return false; - } - - for( unsigned int i = 0; i < m_playerFlags.size(); i++ ) - { - if( m_playerFlags[i]->m_pNetworkPlayer == pNetworkPlayer ) - { - return ( ( m_playerFlags[i]->flags[ index / 8 ] & ( 128 >> ( index % 8 ) ) ) != 0 ); - } - } - return false; -} - -std::wstring CPlatformNetworkManagerSony::GatherStats() -{ +std::wstring CPlatformNetworkManagerSony::GatherStats() { #if 0 return L"Queue messages: " + _toString(((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_MESSAGES ) ) + L" Queue bytes: " + _toString( ((NetworkPlayerXbox *)GetHostPlayer())->GetQNetPlayer()->GetSendQueueSize( NULL, QNET_GETSENDQUEUESIZE_BYTES ) ); #else - return L""; + return L""; #endif } -std::wstring CPlatformNetworkManagerSony::GatherRTTStats() -{ +std::wstring CPlatformNetworkManagerSony::GatherRTTStats() { #if 0 std::wstring stats(L"Rtt: "); @@ -1094,88 +1023,84 @@ std::wstring CPlatformNetworkManagerSony::GatherRTTStats() } return stats; #else - return L""; + return L""; #endif } -void CPlatformNetworkManagerSony::TickSearch() -{ - if( m_bSearchPending ) - { - if( !m_pSQRNet->FriendRoomManagerIsBusy() ) - { - m_searchResultsCount = m_pSQRNet->FriendRoomManagerGetCount(); - delete m_pSearchResults; - m_pSearchResults = new SQRNetworkManager::SessionSearchResult[m_searchResultsCount]; +void CPlatformNetworkManagerSony::TickSearch() { + if (m_bSearchPending) { + if (!m_pSQRNet->FriendRoomManagerIsBusy()) { + m_searchResultsCount = m_pSQRNet->FriendRoomManagerGetCount(); + delete m_pSearchResults; + m_pSearchResults = new SQRNetworkManager::SessionSearchResult + [m_searchResultsCount]; - for( int i = 0; i < m_searchResultsCount; i++ ) - { - m_pSQRNet->FriendRoomManagerGetRoomInfo(i, &m_pSearchResults[i] ); - } - m_bSearchPending = false; + for (int i = 0; i < m_searchResultsCount; i++) { + m_pSQRNet->FriendRoomManagerGetRoomInfo(i, + &m_pSearchResults[i]); + } + m_bSearchPending = false; - if( m_SessionsUpdatedCallback != NULL ) m_SessionsUpdatedCallback(m_pSearchParam); - } - } - else - { - if( !m_pSQRNet->FriendRoomManagerIsBusy() ) - { - // Don't start searches unless we have registered a callback - int searchDelay = MINECRAFT_PS3ROOM_SEARCH_DELAY_MILLISECONDS; + if (m_SessionsUpdatedCallback != NULL) + m_SessionsUpdatedCallback(m_pSearchParam); + } + } else { + if (!m_pSQRNet->FriendRoomManagerIsBusy()) { + // Don't start searches unless we have registered a callback + int searchDelay = MINECRAFT_PS3ROOM_SEARCH_DELAY_MILLISECONDS; #ifdef __PSVITA__ - // in adhoc mode we can keep searching, as the friend list is populated in callbacks - // 4J Stu - Every second seems a bit much as it makes the friend list flash every time it updates. Changed this to 5 seconds. - if( usingAdhocMode()) - searchDelay = 5000; + // in adhoc mode we can keep searching, as the friend list is + // populated in callbacks 4J Stu - Every second seems a bit much as + // it makes the friend list flash every time it updates. Changed + // this to 5 seconds. + if (usingAdhocMode()) searchDelay = 5000; #endif - if( m_SessionsUpdatedCallback != NULL && (m_lastSearchStartTime + searchDelay) < GetTickCount() ) - { - if( m_pSQRNet->FriendRoomManagerSearch() ) - { - m_bSearchPending = true; - m_lastSearchStartTime = GetTickCount(); - } - } - } - } + if (m_SessionsUpdatedCallback != NULL && + (m_lastSearchStartTime + searchDelay) < GetTickCount()) { + if (m_pSQRNet->FriendRoomManagerSearch()) { + m_bSearchPending = true; + m_lastSearchStartTime = GetTickCount(); + } + } + } + } } -std::vector *CPlatformNetworkManagerSony::GetSessionList(int iPad, int localPlayers, bool partyOnly) -{ - std::vector *filteredList = new std::vector(); - for( int i = 0; i < m_searchResultsCount; i++ ) - { - if( m_pSearchResults[i].m_extData ) - { - FriendSessionInfo *newInfo = new FriendSessionInfo(); - newInfo->displayLabel = new wchar_t[17]; - ZeroMemory(newInfo->displayLabel, sizeof(wchar_t)*17); - // TODO - this mbstowcs shouldn't encounter any non-ascii characters, but I imagine we'll want to actually use the online name here which is UTF-8 - mbstowcs(newInfo->displayLabel, m_pSearchResults[i].m_NpId.handle.data, 17); - newInfo->displayLabelLength = strlen(m_pSearchResults[i].m_NpId.handle.data); - newInfo->hasPartyMember = false; - newInfo->searchResult = m_pSearchResults[i]; - newInfo->sessionId = m_pSearchResults[i].m_sessionId; - memcpy(&newInfo->data, m_pSearchResults[i].m_extData, sizeof(GameSessionData)); - if( ( newInfo->data.isReadyToJoin ) && - ( newInfo->data.isJoinable ) && - ( newInfo->data.netVersion == MINECRAFT_NET_VERSION ) ) - { - filteredList->push_back(newInfo); - } - else - { - delete newInfo; - } - } - } +std::vector* CPlatformNetworkManagerSony::GetSessionList( + int iPad, int localPlayers, bool partyOnly) { + std::vector* filteredList = + new std::vector(); + for (int i = 0; i < m_searchResultsCount; i++) { + if (m_pSearchResults[i].m_extData) { + FriendSessionInfo* newInfo = new FriendSessionInfo(); + newInfo->displayLabel = new wchar_t[17]; + ZeroMemory(newInfo->displayLabel, sizeof(wchar_t) * 17); + // TODO - this mbstowcs shouldn't encounter any non-ascii + // characters, but I imagine we'll want to actually use the online + // name here which is UTF-8 + mbstowcs(newInfo->displayLabel, + m_pSearchResults[i].m_NpId.handle.data, 17); + newInfo->displayLabelLength = + strlen(m_pSearchResults[i].m_NpId.handle.data); + newInfo->hasPartyMember = false; + newInfo->searchResult = m_pSearchResults[i]; + newInfo->sessionId = m_pSearchResults[i].m_sessionId; + memcpy(&newInfo->data, m_pSearchResults[i].m_extData, + sizeof(GameSessionData)); + if ((newInfo->data.isReadyToJoin) && (newInfo->data.isJoinable) && + (newInfo->data.netVersion == MINECRAFT_NET_VERSION)) { + filteredList->push_back(newInfo); + } else { + delete newInfo; + } + } + } - return filteredList; + return filteredList; } -bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID sessionId, FriendSessionInfo *foundSessionInfo) -{ +bool CPlatformNetworkManagerSony::GetGameSessionInfo( + int iPad, SessionID sessionId, FriendSessionInfo* foundSessionInfo) { #if 0 HRESULT hr = E_FAIL; @@ -1250,213 +1175,194 @@ bool CPlatformNetworkManagerSony::GetGameSessionInfo(int iPad, SessionID session return ( hr == S_OK ); #else - return false; + return false; #endif } -void CPlatformNetworkManagerSony::SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ) -{ - m_SessionsUpdatedCallback = SessionsUpdatedCallback; m_pSearchParam = pSearchParam; +void CPlatformNetworkManagerSony::SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam) { + m_SessionsUpdatedCallback = SessionsUpdatedCallback; + m_pSearchParam = pSearchParam; } -void CPlatformNetworkManagerSony::GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) -{ - m_pSQRNet->GetExtDataForRoom( foundSession->sessionId.m_RoomId, &foundSession->data, FriendSessionUpdatedFn, pParam); +void CPlatformNetworkManagerSony::GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), void* pParam) { + m_pSQRNet->GetExtDataForRoom(foundSession->sessionId.m_RoomId, + &foundSession->data, FriendSessionUpdatedFn, + pParam); } -void CPlatformNetworkManagerSony::ForceFriendsSessionRefresh() -{ - app.DebugPrintf("Resetting friends session search data\n"); - m_lastSearchStartTime = 0; - m_searchResultsCount = 0; - delete m_pSearchResults; - m_pSearchResults = NULL; +void CPlatformNetworkManagerSony::ForceFriendsSessionRefresh() { + app.DebugPrintf("Resetting friends session search data\n"); + m_lastSearchStartTime = 0; + m_searchResultsCount = 0; + delete m_pSearchResults; + m_pSearchResults = NULL; } -INetworkPlayer *CPlatformNetworkManagerSony::addNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) -{ - NetworkPlayerSony *pNetworkPlayer = new NetworkPlayerSony(pSQRPlayer); - pSQRPlayer->SetCustomDataValue((ULONG_PTR)pNetworkPlayer); - currentNetworkPlayers.push_back( pNetworkPlayer ); - return pNetworkPlayer; +INetworkPlayer* CPlatformNetworkManagerSony::addNetworkPlayer( + SQRNetworkPlayer* pSQRPlayer) { + NetworkPlayerSony* pNetworkPlayer = new NetworkPlayerSony(pSQRPlayer); + pSQRPlayer->SetCustomDataValue((ULONG_PTR)pNetworkPlayer); + currentNetworkPlayers.push_back(pNetworkPlayer); + return pNetworkPlayer; } -void CPlatformNetworkManagerSony::removeNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) -{ - INetworkPlayer *pNetworkPlayer = getNetworkPlayer(pSQRPlayer); - for( AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++ ) - { - if( *it == pNetworkPlayer ) - { - currentNetworkPlayers.erase(it); - return; - } - } +void CPlatformNetworkManagerSony::removeNetworkPlayer( + SQRNetworkPlayer* pSQRPlayer) { + INetworkPlayer* pNetworkPlayer = getNetworkPlayer(pSQRPlayer); + for (AUTO_VAR(it, currentNetworkPlayers.begin()); + it != currentNetworkPlayers.end(); it++) { + if (*it == pNetworkPlayer) { + currentNetworkPlayers.erase(it); + return; + } + } } -INetworkPlayer *CPlatformNetworkManagerSony::getNetworkPlayer(SQRNetworkPlayer *pSQRPlayer) -{ - return pSQRPlayer ? (INetworkPlayer *)(pSQRPlayer->GetCustomDataValue()) : NULL; +INetworkPlayer* CPlatformNetworkManagerSony::getNetworkPlayer( + SQRNetworkPlayer* pSQRPlayer) { + return pSQRPlayer ? (INetworkPlayer*)(pSQRPlayer->GetCustomDataValue()) + : NULL; } - -INetworkPlayer *CPlatformNetworkManagerSony::GetLocalPlayerByUserIndex(int userIndex ) -{ - return getNetworkPlayer(m_pSQRNet->GetLocalPlayerByUserIndex(userIndex)); +INetworkPlayer* CPlatformNetworkManagerSony::GetLocalPlayerByUserIndex( + int userIndex) { + return getNetworkPlayer(m_pSQRNet->GetLocalPlayerByUserIndex(userIndex)); } -INetworkPlayer *CPlatformNetworkManagerSony::GetPlayerByIndex(int playerIndex) -{ - return getNetworkPlayer(m_pSQRNet->GetPlayerByIndex(playerIndex)); +INetworkPlayer* CPlatformNetworkManagerSony::GetPlayerByIndex(int playerIndex) { + return getNetworkPlayer(m_pSQRNet->GetPlayerByIndex(playerIndex)); } -INetworkPlayer * CPlatformNetworkManagerSony::GetPlayerByXuid(PlayerUID xuid) -{ - return getNetworkPlayer(m_pSQRNet->GetPlayerByXuid(xuid)); +INetworkPlayer* CPlatformNetworkManagerSony::GetPlayerByXuid(PlayerUID xuid) { + return getNetworkPlayer(m_pSQRNet->GetPlayerByXuid(xuid)); } -INetworkPlayer * CPlatformNetworkManagerSony::GetPlayerBySmallId(unsigned char smallId) -{ - return getNetworkPlayer(m_pSQRNet->GetPlayerBySmallId(smallId)); +INetworkPlayer* CPlatformNetworkManagerSony::GetPlayerBySmallId( + unsigned char smallId) { + return getNetworkPlayer(m_pSQRNet->GetPlayerBySmallId(smallId)); } -INetworkPlayer *CPlatformNetworkManagerSony::GetHostPlayer() -{ - return getNetworkPlayer(m_pSQRNet->GetHostPlayer()); +INetworkPlayer* CPlatformNetworkManagerSony::GetHostPlayer() { + return getNetworkPlayer(m_pSQRNet->GetHostPlayer()); } -bool CPlatformNetworkManagerSony::IsHost() -{ - return m_pSQRNet->IsHost() && !m_bHostChanged; +bool CPlatformNetworkManagerSony::IsHost() { + return m_pSQRNet->IsHost() && !m_bHostChanged; } -bool CPlatformNetworkManagerSony::JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo) -{ - return m_pSQRNet->JoinRoom( pInviteInfo->m_RoomId, pInviteInfo->m_ServerId, userMask, pInviteInfo ); +bool CPlatformNetworkManagerSony::JoinGameFromInviteInfo( + int userIndex, int userMask, const INVITE_INFO* pInviteInfo) { + return m_pSQRNet->JoinRoom(pInviteInfo->m_RoomId, pInviteInfo->m_ServerId, + userMask, pInviteInfo); } -void CPlatformNetworkManagerSony::SetSessionTexturePackParentId( int id ) -{ - m_hostGameSessionData.texturePackParentId = id; +void CPlatformNetworkManagerSony::SetSessionTexturePackParentId(int id) { + m_hostGameSessionData.texturePackParentId = id; } -void CPlatformNetworkManagerSony::SetSessionSubTexturePackId( int id ) -{ - m_hostGameSessionData.subTexturePackId = id; +void CPlatformNetworkManagerSony::SetSessionSubTexturePackId(int id) { + m_hostGameSessionData.subTexturePackId = id; } -void CPlatformNetworkManagerSony::Notify(int ID, ULONG_PTR Param) -{ +void CPlatformNetworkManagerSony::Notify(int ID, ULONG_PTR Param) { #if 0 m_pSQRNet->Notify( ID, Param ); #endif } -bool CPlatformNetworkManagerSony::IsInSession() -{ - return m_pSQRNet->IsInSession(); +bool CPlatformNetworkManagerSony::IsInSession() { + return m_pSQRNet->IsInSession(); } -bool CPlatformNetworkManagerSony::IsInGameplay() -{ - return m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING; +bool CPlatformNetworkManagerSony::IsInGameplay() { + return m_pSQRNet->GetState() == SQRNetworkManager::SNM_STATE_PLAYING; } -bool CPlatformNetworkManagerSony::IsReadyToPlayOrIdle() -{ - return m_pSQRNet->IsReadyToPlayOrIdle(); +bool CPlatformNetworkManagerSony::IsReadyToPlayOrIdle() { + return m_pSQRNet->IsReadyToPlayOrIdle(); } -void CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData(SQRNetworkManager::PresenceSyncInfo *presence, void *pExtData, SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId) -{ - GameSessionData *gsd = (GameSessionData *)pExtData; +void CPlatformNetworkManagerSony::SetSQRPresenceInfoFromExtData( + SQRNetworkManager::PresenceSyncInfo* presence, void* pExtData, + SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId) { + GameSessionData* gsd = (GameSessionData*)pExtData; - memcpy(&presence->hostPlayerUID, &gsd->hostPlayerUID, sizeof(GameSessionUID) ); - presence->m_RoomId = roomId; - presence->m_ServerId = serverId; - presence->texturePackParentId = gsd->texturePackParentId; - presence->subTexturePackId = gsd->subTexturePackId; - presence->netVersion = gsd->netVersion; - presence->inviteOnly = !gsd->isJoinable; + memcpy(&presence->hostPlayerUID, &gsd->hostPlayerUID, + sizeof(GameSessionUID)); + presence->m_RoomId = roomId; + presence->m_ServerId = serverId; + presence->texturePackParentId = gsd->texturePackParentId; + presence->subTexturePackId = gsd->subTexturePackId; + presence->netVersion = gsd->netVersion; + presence->inviteOnly = !gsd->isJoinable; } -void CPlatformNetworkManagerSony::MallocAndSetExtDataFromSQRPresenceInfo(void **pExtData, SQRNetworkManager::PresenceSyncInfo *presence) -{ - GameSessionData *gsd = (GameSessionData *)malloc(sizeof(GameSessionData)); - memset(gsd, 0, sizeof(GameSessionData)); - if( presence->netVersion != 0 ) - { - memcpy(&gsd->hostPlayerUID, &presence->hostPlayerUID, sizeof(GameSessionUID) ); - gsd->texturePackParentId = presence->texturePackParentId; - gsd->subTexturePackId = presence->subTexturePackId; - gsd->netVersion = presence->netVersion; - gsd->isJoinable = !presence->inviteOnly; - gsd->isReadyToJoin = true; - } - *pExtData = gsd; +void CPlatformNetworkManagerSony::MallocAndSetExtDataFromSQRPresenceInfo( + void** pExtData, SQRNetworkManager::PresenceSyncInfo* presence) { + GameSessionData* gsd = (GameSessionData*)malloc(sizeof(GameSessionData)); + memset(gsd, 0, sizeof(GameSessionData)); + if (presence->netVersion != 0) { + memcpy(&gsd->hostPlayerUID, &presence->hostPlayerUID, + sizeof(GameSessionUID)); + gsd->texturePackParentId = presence->texturePackParentId; + gsd->subTexturePackId = presence->subTexturePackId; + gsd->netVersion = presence->netVersion; + gsd->isJoinable = !presence->inviteOnly; + gsd->isReadyToJoin = true; + } + *pExtData = gsd; } #ifdef __PSVITA__ -bool CPlatformNetworkManagerSony::setAdhocMode( bool bAdhoc ) -{ - if(m_bUsingAdhocMode != bAdhoc) - { - m_bUsingAdhocMode = bAdhoc; - if(m_bUsingAdhocMode) - { - // uninit the PSN, and init adhoc - if(m_pSQRNet_Vita->IsInitialised()) - { - m_pSQRNet_Vita->UnInitialise(); - } +bool CPlatformNetworkManagerSony::setAdhocMode(bool bAdhoc) { + if (m_bUsingAdhocMode != bAdhoc) { + m_bUsingAdhocMode = bAdhoc; + if (m_bUsingAdhocMode) { + // uninit the PSN, and init adhoc + if (m_pSQRNet_Vita->IsInitialised()) { + m_pSQRNet_Vita->UnInitialise(); + } - if(m_pSQRNet_Vita_Adhoc->IsInitialised()==false) - { - m_pSQRNet_Vita_Adhoc->Initialise(); - } + if (m_pSQRNet_Vita_Adhoc->IsInitialised() == false) { + m_pSQRNet_Vita_Adhoc->Initialise(); + } - m_pSQRNet = m_pSQRNet_Vita_Adhoc; - } - else - { - if(m_pSQRNet_Vita_Adhoc->IsInitialised()) - { - int ret = sceNetCtlAdhocDisconnect(); - // uninit the adhoc, and init psn - m_pSQRNet_Vita_Adhoc->UnInitialise(); - } + m_pSQRNet = m_pSQRNet_Vita_Adhoc; + } else { + if (m_pSQRNet_Vita_Adhoc->IsInitialised()) { + int ret = sceNetCtlAdhocDisconnect(); + // uninit the adhoc, and init psn + m_pSQRNet_Vita_Adhoc->UnInitialise(); + } - if(m_pSQRNet_Vita->IsInitialised()==false) - { - m_pSQRNet_Vita->Initialise(); - } + if (m_pSQRNet_Vita->IsInitialised() == false) { + m_pSQRNet_Vita->Initialise(); + } - m_pSQRNet = m_pSQRNet_Vita; - } - } + m_pSQRNet = m_pSQRNet_Vita; + } + } - return true; + return true; } -void CPlatformNetworkManagerSony::startAdhocMatching( ) -{ - assert(m_pSQRNet == m_pSQRNet_Vita_Adhoc); - ((SQRNetworkManager_AdHoc_Vita*)m_pSQRNet_Vita_Adhoc)->startMatching(); +void CPlatformNetworkManagerSony::startAdhocMatching() { + assert(m_pSQRNet == m_pSQRNet_Vita_Adhoc); + ((SQRNetworkManager_AdHoc_Vita*)m_pSQRNet_Vita_Adhoc)->startMatching(); } -bool CPlatformNetworkManagerSony::checkValidInviteData(const INVITE_INFO* pInviteInfo) -{ - if(((SQRNetworkManager_Vita*)m_pSQRNet_Vita)->GetHostUID() == pInviteInfo->hostPlayerUID) - { - // we're trying to join a game we're already in, so we just ignore this - return false; - } - else - { - return true; - } +bool CPlatformNetworkManagerSony::checkValidInviteData( + const INVITE_INFO* pInviteInfo) { + if (((SQRNetworkManager_Vita*)m_pSQRNet_Vita)->GetHostUID() == + pInviteInfo->hostPlayerUID) { + // we're trying to join a game we're already in, so we just ignore this + return false; + } else { + return true; + } } - - -#endif // __PSVITA__ +#endif // __PSVITA__ diff --git a/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.h b/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.h index a244c3190..ea959d6f5 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/PlatformNetworkManagerSony.h @@ -1,5 +1,5 @@ #pragma once -//using namespace std; +// using namespace std; #include #include "../../../Minecraft.World/Util/C4JThread.h" #include "../NetworkPlayerInterface.h" @@ -10,178 +10,220 @@ // This is how often we allow a search for new games #define MINECRAFT_PS3ROOM_SEARCH_DELAY_MILLISECONDS 30000 -// This is the Sony platform specific implementation of CPlatformNetworkManager. It is implemented using SQRNetworkManager/SQRNetworkPlayer. There shouldn't be any general game code in here, -// this class is for providing a bridge between the common game-side network implementation, and the lowest level platform specific libraries. +// This is the Sony platform specific implementation of CPlatformNetworkManager. +// It is implemented using SQRNetworkManager/SQRNetworkPlayer. There shouldn't +// be any general game code in here, this class is for providing a bridge +// between the common game-side network implementation, and the lowest level +// platform specific libraries. + +class CPlatformNetworkManagerSony : public CPlatformNetworkManager, + ISQRNetworkManagerListener { + friend class CGameNetworkManager; -class CPlatformNetworkManagerSony : public CPlatformNetworkManager, ISQRNetworkManagerListener -{ - friend class CGameNetworkManager; public: - virtual bool Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize); - virtual void Terminate(); - virtual int GetJoiningReadyPercentage(); - virtual int CorrectErrorIDS(int IDS); + virtual bool Initialise(CGameNetworkManager* pGameNetworkManager, + int flagIndexSize); + virtual void Terminate(); + virtual int GetJoiningReadyPercentage(); + virtual int CorrectErrorIDS(int IDS); - virtual void DoWork(); - virtual int GetPlayerCount(); - virtual int GetOnlinePlayerCount(); - virtual int GetLocalPlayerMask(int playerIndex); - virtual bool AddLocalPlayerByUserIndex( int userIndex ); - virtual bool RemoveLocalPlayerByUserIndex( int userIndex ); - virtual INetworkPlayer *GetLocalPlayerByUserIndex( int userIndex ); - virtual INetworkPlayer *GetPlayerByIndex(int playerIndex); - virtual INetworkPlayer * GetPlayerByXuid(PlayerUID xuid); - virtual INetworkPlayer * GetPlayerBySmallId(unsigned char smallId); - virtual bool ShouldMessageForFullSession(); + virtual void DoWork(); + virtual int GetPlayerCount(); + virtual int GetOnlinePlayerCount(); + virtual int GetLocalPlayerMask(int playerIndex); + virtual bool AddLocalPlayerByUserIndex(int userIndex); + virtual bool RemoveLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetLocalPlayerByUserIndex(int userIndex); + virtual INetworkPlayer* GetPlayerByIndex(int playerIndex); + virtual INetworkPlayer* GetPlayerByXuid(PlayerUID xuid); + virtual INetworkPlayer* GetPlayerBySmallId(unsigned char smallId); + virtual bool ShouldMessageForFullSession(); - virtual INetworkPlayer *GetHostPlayer(); - virtual bool IsHost(); - virtual bool JoinGameFromInviteInfo( int userIndex, int userMask, const INVITE_INFO *pInviteInfo); - virtual bool LeaveGame(bool bMigrateHost); + virtual INetworkPlayer* GetHostPlayer(); + virtual bool IsHost(); + virtual bool JoinGameFromInviteInfo(int userIndex, int userMask, + const INVITE_INFO* pInviteInfo); + virtual bool LeaveGame(bool bMigrateHost); - virtual bool IsInSession(); - virtual bool IsInGameplay(); - virtual bool IsReadyToPlayOrIdle(); - virtual bool IsInStatsEnabledSession(); - virtual bool SessionHasSpace(unsigned int spaceRequired = 1); + virtual bool IsInSession(); + virtual bool IsInGameplay(); + virtual bool IsReadyToPlayOrIdle(); + virtual bool IsInStatsEnabledSession(); + virtual bool SessionHasSpace(unsigned int spaceRequired = 1); - virtual void SendInviteGUI(int quadrant); - virtual bool IsAddingPlayer(); + virtual void SendInviteGUI(int quadrant); + virtual bool IsAddingPlayer(); - virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); - virtual int JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex ); - virtual bool SetLocalGame(bool isLocal); - virtual bool IsLocalGame(); - virtual void SetPrivateGame(bool isPrivate); - virtual bool IsPrivateGame(); - virtual bool IsLeavingGame(); - virtual void ResetLeavingGame(); + virtual void HostGame(int localUsersMask, bool bOnlineGame, bool bIsPrivate, + unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0); + virtual int JoinGame(FriendSessionInfo* searchResult, int localUsersMask, + int primaryUserIndex); + virtual bool SetLocalGame(bool isLocal); + virtual bool IsLocalGame(); + virtual void SetPrivateGame(bool isPrivate); + virtual bool IsPrivateGame(); + virtual bool IsLeavingGame(); + virtual void ResetLeavingGame(); - virtual void RegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); - virtual void UnRegisterPlayerChangedCallback(int iPad, void (*callback)(void *callbackParam, INetworkPlayer *pPlayer, bool leaving), void *callbackParam); + virtual void RegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); + virtual void UnRegisterPlayerChangedCallback( + int iPad, + void (*callback)(void* callbackParam, INetworkPlayer* pPlayer, + bool leaving), + void* callbackParam); - virtual void HandleSignInChange(); + virtual void HandleSignInChange(); - virtual bool _RunNetworkGame(); + virtual bool _RunNetworkGame(); #ifdef __PSVITA__ - bool usingAdhocMode() { return m_bUsingAdhocMode; } - bool setAdhocMode(bool bAdhoc); - void startAdhocMatching(); - bool checkValidInviteData(const INVITE_INFO* pInviteInfo); + bool usingAdhocMode() { return m_bUsingAdhocMode; } + bool setAdhocMode(bool bAdhoc); + void startAdhocMatching(); + bool checkValidInviteData(const INVITE_INFO* pInviteInfo); #endif - + private: - bool isSystemPrimaryPlayer(SQRNetworkPlayer *pQNetPlayer); - virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); - virtual void _HostGame(int dwUsersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, unsigned char privateSlots = 0); - virtual bool _StartGame(); + bool isSystemPrimaryPlayer(SQRNetworkPlayer* pQNetPlayer); + virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom); + virtual void _HostGame( + int dwUsersMask, unsigned char publicSlots = MINECRAFT_NET_MAX_PLAYERS, + unsigned char privateSlots = 0); + virtual bool _StartGame(); #ifdef __PSVITA__ - bool m_bUsingAdhocMode; - SQRNetworkManager_Vita* m_pSQRNet_Vita; - SQRNetworkManager_AdHoc_Vita* m_pSQRNet_Vita_Adhoc; + bool m_bUsingAdhocMode; + SQRNetworkManager_Vita* m_pSQRNet_Vita; + SQRNetworkManager_AdHoc_Vita* m_pSQRNet_Vita_Adhoc; #endif - SQRNetworkManager * m_pSQRNet; // pointer to SQRNetworkManager interface + SQRNetworkManager* m_pSQRNet; // pointer to SQRNetworkManager interface - HANDLE m_notificationListener; + HANDLE m_notificationListener; - std::vector m_machineSQRPrimaryPlayers; // collection of players that we deem to be the main one for that system + std::vector + m_machineSQRPrimaryPlayers; // collection of players that we deem to be + // the main one for that system - bool m_bLeavingGame; - bool m_bLeaveGameOnTick; - bool m_migrateHostOnLeave; - bool m_bHostChanged; - bool m_bLeaveRoomWhenLeavingGame; + bool m_bLeavingGame; + bool m_bLeaveGameOnTick; + bool m_migrateHostOnLeave; + bool m_bHostChanged; + bool m_bLeaveRoomWhenLeavingGame; - bool m_bIsOfflineGame; - bool m_bIsPrivateGame; - int m_flagIndexSize; + bool m_bIsOfflineGame; + bool m_bIsPrivateGame; + int m_flagIndexSize; + + // This is only maintained by the host, and is not valid on client machines + GameSessionData m_hostGameSessionData; + CGameNetworkManager* m_pGameNetworkManager; - // This is only maintained by the host, and is not valid on client machines - GameSessionData m_hostGameSessionData; - CGameNetworkManager *m_pGameNetworkManager; public: - virtual void UpdateAndSetGameSessionData(INetworkPlayer *pNetworkPlayerLeaving = NULL); + virtual void UpdateAndSetGameSessionData( + INetworkPlayer* pNetworkPlayerLeaving = NULL); private: - // TODO 4J Stu - Do we need to be able to have more than one of these? - void (*playerChangedCallback[XUSER_MAX_COUNT])(void *callbackParam, INetworkPlayer *pPlayer, bool leaving); - void *playerChangedCallbackParam[XUSER_MAX_COUNT]; + // TODO 4J Stu - Do we need to be able to have more than one of these? + void (*playerChangedCallback[XUSER_MAX_COUNT])(void* callbackParam, + INetworkPlayer* pPlayer, + bool leaving); + void* playerChangedCallbackParam[XUSER_MAX_COUNT]; - static int RemovePlayerOnSocketClosedThreadProc( void* lpParam ); - virtual bool RemoveLocalPlayer( INetworkPlayer *pNetworkPlayer ); + static int RemovePlayerOnSocketClosedThreadProc(void* lpParam); + virtual bool RemoveLocalPlayer(INetworkPlayer* pNetworkPlayer); + + // Things for handling per-system flags + class PlayerFlags { + public: + INetworkPlayer* m_pNetworkPlayer; + unsigned char* flags; + unsigned int count; + PlayerFlags(INetworkPlayer* pNetworkPlayer, unsigned int count); + ~PlayerFlags(); + }; + std::vector m_playerFlags; + void SystemFlagAddPlayer(INetworkPlayer* pNetworkPlayer); + void SystemFlagRemovePlayer(INetworkPlayer* pNetworkPlayer); + void SystemFlagReset(); - // Things for handling per-system flags - class PlayerFlags - { - public: - INetworkPlayer *m_pNetworkPlayer; - unsigned char *flags; - unsigned int count; - PlayerFlags(INetworkPlayer *pNetworkPlayer, unsigned int count); - ~PlayerFlags(); - }; - std::vector m_playerFlags; - void SystemFlagAddPlayer(INetworkPlayer *pNetworkPlayer); - void SystemFlagRemovePlayer(INetworkPlayer *pNetworkPlayer); - void SystemFlagReset(); public: - virtual void SystemFlagSet(INetworkPlayer *pNetworkPlayer, int index); - virtual bool SystemFlagGet(INetworkPlayer *pNetworkPlayer, int index); + virtual void SystemFlagSet(INetworkPlayer* pNetworkPlayer, int index); + virtual bool SystemFlagGet(INetworkPlayer* pNetworkPlayer, int index); - // For telemetry + // For telemetry private: - float m_lastPlayerEventTimeStart; + float m_lastPlayerEventTimeStart; public: - std::wstring GatherStats(); - std::wstring GatherRTTStats(); + std::wstring GatherStats(); + std::wstring GatherRTTStats(); -private: - std::vector friendsSessions; - - int m_lastSearchStartTime; +private: + std::vector friendsSessions; - // The results that will be filled in with the current search - int m_searchResultsCount; - SQRNetworkManager::SessionSearchResult *m_pSearchResults; + int m_lastSearchStartTime; - int m_lastSearchPad; - bool m_bSearchPending; - void *m_pSearchParam; - void (*m_SessionsUpdatedCallback)(void *pParam); + // The results that will be filled in with the current search + int m_searchResultsCount; + SQRNetworkManager::SessionSearchResult* m_pSearchResults; - C4JThread* m_SearchingThread; + int m_lastSearchPad; + bool m_bSearchPending; + void* m_pSearchParam; + void (*m_SessionsUpdatedCallback)(void* pParam); - void TickSearch(); + C4JThread* m_SearchingThread; - std::vectorcurrentNetworkPlayers; - INetworkPlayer *addNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); - void removeNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); - static INetworkPlayer *getNetworkPlayer(SQRNetworkPlayer *pSQRPlayer); + void TickSearch(); - virtual void SetSessionTexturePackParentId( int id ); - virtual void SetSessionSubTexturePackId( int id ); - virtual void Notify(int ID, ULONG_PTR Param); + std::vector currentNetworkPlayers; + INetworkPlayer* addNetworkPlayer(SQRNetworkPlayer* pSQRPlayer); + void removeNetworkPlayer(SQRNetworkPlayer* pSQRPlayer); + static INetworkPlayer* getNetworkPlayer(SQRNetworkPlayer* pSQRPlayer); + + virtual void SetSessionTexturePackParentId(int id); + virtual void SetSessionSubTexturePackId(int id); + virtual void Notify(int ID, ULONG_PTR Param); public: - virtual std::vector *GetSessionList(int iPad, int localPlayers, bool partyOnly); - virtual bool GetGameSessionInfo(int iPad, SessionID sessionId,FriendSessionInfo *foundSession); - virtual void SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(void *pParam), void *pSearchParam ); - virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ); - virtual void ForceFriendsSessionRefresh(); + virtual std::vector* GetSessionList(int iPad, + int localPlayers, + bool partyOnly); + virtual bool GetGameSessionInfo(int iPad, SessionID sessionId, + FriendSessionInfo* foundSession); + virtual void SetSessionsUpdatedCallback( + void (*SessionsUpdatedCallback)(void* pParam), void* pSearchParam); + virtual void GetFullFriendSessionInfo( + FriendSessionInfo* foundSession, + void (*FriendSessionUpdatedFn)(bool success, void* pParam), + void* pParam); + virtual void ForceFriendsSessionRefresh(); - // ... and the new ones that have been converted to ISQRNetworkManagerListener - virtual void HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize); - virtual void HandlePlayerJoined(SQRNetworkPlayer *player); - virtual void HandlePlayerLeaving(SQRNetworkPlayer *player); - virtual void HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull); - virtual void HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers); - virtual void HandleAddLocalPlayerFailed(int idx); - virtual void HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut=false); - virtual void HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo); + // ... and the new ones that have been converted to + // ISQRNetworkManagerListener + virtual void HandleDataReceived(SQRNetworkPlayer* playerFrom, + SQRNetworkPlayer* playerTo, + unsigned char* data, unsigned int dataSize); + virtual void HandlePlayerJoined(SQRNetworkPlayer* player); + virtual void HandlePlayerLeaving(SQRNetworkPlayer* player); + virtual void HandleStateChange( + SQRNetworkManager::eSQRNetworkManagerState oldState, + SQRNetworkManager::eSQRNetworkManagerState newState, + bool idleReasonIsSessionFull); + virtual void HandleResyncPlayerRequest(SQRNetworkPlayer** aPlayers); + virtual void HandleAddLocalPlayerFailed(int idx); + virtual void HandleDisconnect(bool bLostRoomOnly, bool bPSNSignOut = false); + virtual void HandleInviteReceived( + int userIndex, const SQRNetworkManager::PresenceSyncInfo* pInviteInfo); - static void SetSQRPresenceInfoFromExtData(SQRNetworkManager::PresenceSyncInfo *presence, void *pExtData, SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId); - static void MallocAndSetExtDataFromSQRPresenceInfo(void **pExtData, SQRNetworkManager::PresenceSyncInfo *presence); + static void SetSQRPresenceInfoFromExtData( + SQRNetworkManager::PresenceSyncInfo* presence, void* pExtData, + SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId); + static void MallocAndSetExtDataFromSQRPresenceInfo( + void** pExtData, SQRNetworkManager::PresenceSyncInfo* presence); }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.cpp b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.cpp index 56c007077..dd67952d4 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.cpp @@ -4,7 +4,6 @@ bool SQRNetworkManager::s_safeToRespondToGameBootInvite = false; -void SQRNetworkManager::SafeToRespondToGameBootInvite() -{ - s_safeToRespondToGameBootInvite = true; +void SQRNetworkManager::SafeToRespondToGameBootInvite() { + s_safeToRespondToGameBootInvite = true; } diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.h b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.h index c93368d8b..58c5e4bfe 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkManager.h @@ -17,297 +17,324 @@ class ISQRNetworkManagerListener; class SonyVoiceChat; class C4JThread; -// This is the lowest level manager for providing network functionality on Sony platforms. This manages various network activities including the players within a gaming session. -// The game shouldn't directly use this class, it is here to provide functionality required by PlatformNetworkManagerSony. +// This is the lowest level manager for providing network functionality on Sony +// platforms. This manages various network activities including the players +// within a gaming session. The game shouldn't directly use this class, it is +// here to provide functionality required by PlatformNetworkManagerSony. -class SQRNetworkManager -{ +class SQRNetworkManager { public: - static const int MAX_LOCAL_PLAYER_COUNT = XUSER_MAX_COUNT; - static const int MAX_ONLINE_PLAYER_COUNT = MINECRAFT_NET_MAX_PLAYERS; + static const int MAX_LOCAL_PLAYER_COUNT = XUSER_MAX_COUNT; + static const int MAX_ONLINE_PLAYER_COUNT = MINECRAFT_NET_MAX_PLAYERS; + + static const int NP_POOL_SIZE = 128 * 1024; - static const int NP_POOL_SIZE = 128 * 1024; protected: - friend class SQRNetworkPlayer; - friend class SonyVoiceChat; + friend class SQRNetworkPlayer; + friend class SonyVoiceChat; - - static const int MAX_FRIENDS = 100; + static const int MAX_FRIENDS = 100; #ifdef __PS3__ - static const int RUDP_THREAD_PRIORITY = 999; -#else // __ORBIS_ - static const int RUDP_THREAD_PRIORITY = 500; + static const int RUDP_THREAD_PRIORITY = 999; +#else // __ORBIS_ + static const int RUDP_THREAD_PRIORITY = 500; #endif - static const int RUDP_THREAD_STACK_SIZE = 32878; - static const int MAX_SIMULTANEOUS_INVITES = 10; - + static const int RUDP_THREAD_STACK_SIZE = 32878; + static const int MAX_SIMULTANEOUS_INVITES = 10; - // This class stores everything about a player that must be synchronised between machines. This syncing is carried out - // by the Matching2 lib by using internal room binary data (ie data that is only visible to current members of a room) - class PlayerSyncData - { - public: - PlayerUID m_UID; // Assigned by the associated player->GetUID() - SceNpMatching2RoomMemberId m_roomMemberId; // Assigned by Matching2 lib, we can use to indicate which machine this player belongs to (note - 16 bits) - unsigned char m_smallId; // Assigned by SQRNetworkManager, to attach a permanent id to this player (until we have to wrap round), to match a similar concept in qnet - unsigned char m_localIdx : 4; // Which local player (by controller index) this represents - unsigned char m_playerCount : 4; - }; + // This class stores everything about a player that must be synchronised + // between machines. This syncing is carried out by the Matching2 lib by + // using internal room binary data (ie data that is only visible to current + // members of a room) + class PlayerSyncData { + public: + PlayerUID m_UID; // Assigned by the associated player->GetUID() + SceNpMatching2RoomMemberId + m_roomMemberId; // Assigned by Matching2 lib, we can use to + // indicate which machine this player belongs to + // (note - 16 bits) + unsigned char + m_smallId; // Assigned by SQRNetworkManager, to attach a permanent + // id to this player (until we have to wrap round), to + // match a similar concept in qnet + unsigned char m_localIdx + : 4; // Which local player (by controller index) this represents + unsigned char m_playerCount : 4; + }; - class RoomSyncData - { - public: - PlayerSyncData players[MAX_ONLINE_PLAYER_COUNT]; - void setPlayerCount(int c) { players[0].m_playerCount = c;} - int getPlayerCount() { return players[0].m_playerCount;} - }; + class RoomSyncData { + public: + PlayerSyncData players[MAX_ONLINE_PLAYER_COUNT]; + void setPlayerCount(int c) { players[0].m_playerCount = c; } + int getPlayerCount() { return players[0].m_playerCount; } + }; public: - class PresenceSyncInfo - { - public: - GameSessionUID hostPlayerUID; - SceNpMatching2RoomId m_RoomId; - SceNpMatching2ServerId m_ServerId; - unsigned int texturePackParentId; - unsigned short netVersion; - unsigned char subTexturePackId; - bool inviteOnly; - }; + class PresenceSyncInfo { + public: + GameSessionUID hostPlayerUID; + SceNpMatching2RoomId m_RoomId; + SceNpMatching2ServerId m_ServerId; + unsigned int texturePackParentId; + unsigned short netVersion; + unsigned char subTexturePackId; + bool inviteOnly; + }; + // Externally exposed state. All internal states are mapped to one of these + // broader states. + typedef enum { + SNM_STATE_INITIALISING, + SNM_STATE_INITIALISE_FAILED, + SNM_STATE_IDLE, - // Externally exposed state. All internal states are mapped to one of these broader states. - typedef enum - { - SNM_STATE_INITIALISING, - SNM_STATE_INITIALISE_FAILED, - SNM_STATE_IDLE, + SNM_STATE_HOSTING, + SNM_STATE_JOINING, - SNM_STATE_HOSTING, - SNM_STATE_JOINING, + SNM_STATE_STARTING, + SNM_STATE_PLAYING, - SNM_STATE_STARTING, - SNM_STATE_PLAYING, + SNM_STATE_LEAVING, + SNM_STATE_ENDING, + } eSQRNetworkManagerState; - SNM_STATE_LEAVING, - SNM_STATE_ENDING, - } eSQRNetworkManagerState; + struct SessionID { + SceNpMatching2RoomId m_RoomId; + SceNpMatching2ServerId m_ServerId; + }; - struct SessionID - { - SceNpMatching2RoomId m_RoomId; - SceNpMatching2ServerId m_ServerId; - }; - - struct SessionSearchResult - { - SceNpId m_NpId; - SessionID m_sessionId; - void *m_extData; + struct SessionSearchResult { + SceNpId m_NpId; + SessionID m_sessionId; + void* m_extData; #ifdef __PSVITA__ - SceNetInAddr m_netAddr; + SceNetInAddr m_netAddr; #endif - }; + }; protected: + // On initialisation, state should transition from + // SNM_INT_STATE_UNINITIALISED -> SNM_INT_STATE_SIGNING_IN -> + // SNM_INT_STATE_SIGNED_IN -> SNM_INT_STATE_STARTING_CONTEXT -> + // SNM_INT_STATE_IDLE. Error indicated if we transition at any point to + // SNM_INT_STATE_INITIALISE_FAILED. - // On initialisation, state should transition from SNM_INT_STATE_UNINITIALISED -> SNM_INT_STATE_SIGNING_IN -> SNM_INT_STATE_SIGNED_IN -> SNM_INT_STATE_STARTING_CONTEXT -> SNM_INT_STATE_IDLE. - // Error indicated if we transition at any point to SNM_INT_STATE_INITIALISE_FAILED. + // NOTE: If anything changes in here, then the mapping from internal -> + // external state needs to be updated (m_INTtoEXTStateMappings, defined in + // the cpp file) + typedef enum { + SNM_INT_STATE_UNINITIALISED, + SNM_INT_STATE_SIGNING_IN, + SNM_INT_STATE_STARTING_CONTEXT, + SNM_INT_STATE_INITIALISE_FAILED, - // NOTE: If anything changes in here, then the mapping from internal -> external state needs to be updated (m_INTtoEXTStateMappings, defined in the cpp file) - typedef enum - { - SNM_INT_STATE_UNINITIALISED, - SNM_INT_STATE_SIGNING_IN, - SNM_INT_STATE_STARTING_CONTEXT, - SNM_INT_STATE_INITIALISE_FAILED, + SNM_INT_STATE_IDLE, + SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT, - SNM_INT_STATE_IDLE, - SNM_INT_STATE_IDLE_RECREATING_MATCHING_CONTEXT, + SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT, + SNM_INT_STATE_HOSTING_SEARCHING_FOR_SERVER, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_SERVER_ERROR, + SNM_INT_STATE_HOSTING_SERVER_FOUND, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_CREATING_CONTEXT, + SNM_INT_STATE_HOSTING_SERVER_SEARCH_FAILED, - SNM_INT_STATE_HOSTING_STARTING_MATCHING_CONTEXT, - SNM_INT_STATE_HOSTING_SEARCHING_FOR_SERVER, - SNM_INT_STATE_HOSTING_SERVER_SEARCH_SERVER_ERROR, - SNM_INT_STATE_HOSTING_SERVER_FOUND, - SNM_INT_STATE_HOSTING_SERVER_SEARCH_CREATING_CONTEXT, - SNM_INT_STATE_HOSTING_SERVER_SEARCH_FAILED, + SNM_INT_STATE_HOSTING_CREATE_ROOM_SEARCHING_FOR_WORLD, + SNM_INT_STATE_HOSTING_CREATE_ROOM_WORLD_FOUND, + SNM_INT_STATE_HOSTING_CREATE_ROOM_CREATING_ROOM, + SNM_INT_STATE_HOSTING_CREATE_ROOM_SUCCESS, + SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED, + SNM_INT_STATE_HOSTING_CREATE_ROOM_RESTART_MATCHING_CONTEXT, + SNM_INT_STATE_HOSTING_WAITING_TO_PLAY, - SNM_INT_STATE_HOSTING_CREATE_ROOM_SEARCHING_FOR_WORLD, - SNM_INT_STATE_HOSTING_CREATE_ROOM_WORLD_FOUND, - SNM_INT_STATE_HOSTING_CREATE_ROOM_CREATING_ROOM, - SNM_INT_STATE_HOSTING_CREATE_ROOM_SUCCESS, - SNM_INT_STATE_HOSTING_CREATE_ROOM_FAILED, - SNM_INT_STATE_HOSTING_CREATE_ROOM_RESTART_MATCHING_CONTEXT, - SNM_INT_STATE_HOSTING_WAITING_TO_PLAY, + SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT, + SNM_INT_STATE_JOINING_SEARCHING_FOR_SERVER, + SNM_INT_STATE_JOINING_SERVER_SEARCH_SERVER_ERROR, + SNM_INT_STATE_JOINING_SERVER_FOUND, + SNM_INT_STATE_JOINING_SERVER_SEARCH_CREATING_CONTEXT, + SNM_INT_STATE_JOINING_SERVER_SEARCH_FAILED, - SNM_INT_STATE_JOINING_STARTING_MATCHING_CONTEXT, - SNM_INT_STATE_JOINING_SEARCHING_FOR_SERVER, - SNM_INT_STATE_JOINING_SERVER_SEARCH_SERVER_ERROR, - SNM_INT_STATE_JOINING_SERVER_FOUND, - SNM_INT_STATE_JOINING_SERVER_SEARCH_CREATING_CONTEXT, - SNM_INT_STATE_JOINING_SERVER_SEARCH_FAILED, + SNM_INT_STATE_JOINING_JOIN_ROOM, + SNM_INT_STATE_JOINING_JOIN_ROOM_FAILED, - SNM_INT_STATE_JOINING_JOIN_ROOM, - SNM_INT_STATE_JOINING_JOIN_ROOM_FAILED, + SNM_INT_STATE_JOINING_WAITING_FOR_LOCAL_PLAYERS, - SNM_INT_STATE_JOINING_WAITING_FOR_LOCAL_PLAYERS, + SNM_INT_STATE_SERVER_DELETING_CONTEXT, - SNM_INT_STATE_SERVER_DELETING_CONTEXT, + SNM_INT_STATE_STARTING, + SNM_INT_STATE_PLAYING, - SNM_INT_STATE_STARTING, - SNM_INT_STATE_PLAYING, + SNM_INT_STATE_LEAVING, + SNM_INT_STATE_LEAVING_FAILED, - SNM_INT_STATE_LEAVING, - SNM_INT_STATE_LEAVING_FAILED, + SNM_INT_STATE_ENDING, - SNM_INT_STATE_ENDING, + SNM_INT_STATE_COUNT - SNM_INT_STATE_COUNT - - } eSQRNetworkManagerInternalState; + } eSQRNetworkManagerInternalState; - typedef enum - { - SNM_FORCE_ERROR_NP2_INIT, - SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK, - SNM_FORCE_ERROR_NET_CTL_INIT, - SNM_FORCE_ERROR_RUDP_INIT, - SNM_FORCE_ERROR_NET_START_DIALOG, - SNM_FORCE_ERROR_MATCHING2_INIT, - SNM_FORCE_ERROR_REGISTER_NP_CALLBACK, - SNM_FORCE_ERROR_GET_NPID, - SNM_FORCE_ERROR_CREATE_MATCHING_CONTEXT, - SNM_FORCE_ERROR_REGISTER_CALLBACKS, - SNM_FORCE_ERROR_CONTEXT_START_ASYNC, - SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA, - SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY_COUNT, - SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY, - SNM_FORCE_ERROR_GET_USER_INFO_LIST, - SNM_FORCE_ERROR_LEAVE_ROOM, - SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL, - SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2, - SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT, - SNM_FORCE_ERROR_CREATE_JOIN_ROOM, - SNM_FORCE_ERROR_GET_SERVER_INFO, - SNM_FORCE_ERROR_DELETE_SERVER_CONTEXT, - SNM_FORCE_ERROR_SETSOCKOPT_0, - SNM_FORCE_ERROR_SETSOCKOPT_1, - SNM_FORCE_ERROR_SETSOCKOPT_2, - SNM_FORCE_ERROR_SOCK_BIND, - SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT, - SNM_FORCE_ERROR_RUDP_BIND, - SNM_FORCE_ERROR_RUDP_INIT2, - SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA, - SNM_FORCE_ERROR_GET_SERVER_INFO_DATA, - SNM_FORCE_ERROR_GET_WORLD_INFO_DATA, - SNM_FORCE_ERROR_GET_CREATE_JOIN_ROOM_DATA, - SNM_FORCE_ERROR_GET_USER_INFO_LIST_DATA, - SNM_FORCE_ERROR_GET_JOIN_ROOM_DATA, - SNM_FORCE_ERROR_GET_ROOM_MEMBER_DATA_INTERNAL, - SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA2, - SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT_CALLBACK, - SNM_FORCE_ERROR_SET_ROOM_DATA_CALLBACK, - SNM_FORCE_ERROR_UPDATED_ROOM_DATA, - SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL1, - SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL2, - SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL3, - SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL4, - SNM_FORCE_ERROR_GET_WORLD_INFO_LIST, - SNM_FORCE_ERROR_JOIN_ROOM, + typedef enum { + SNM_FORCE_ERROR_NP2_INIT, + SNM_FORCE_ERROR_NET_INITIALIZE_NETWORK, + SNM_FORCE_ERROR_NET_CTL_INIT, + SNM_FORCE_ERROR_RUDP_INIT, + SNM_FORCE_ERROR_NET_START_DIALOG, + SNM_FORCE_ERROR_MATCHING2_INIT, + SNM_FORCE_ERROR_REGISTER_NP_CALLBACK, + SNM_FORCE_ERROR_GET_NPID, + SNM_FORCE_ERROR_CREATE_MATCHING_CONTEXT, + SNM_FORCE_ERROR_REGISTER_CALLBACKS, + SNM_FORCE_ERROR_CONTEXT_START_ASYNC, + SNM_FORCE_ERROR_SET_EXTERNAL_ROOM_DATA, + SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY_COUNT, + SNM_FORCE_ERROR_GET_FRIEND_LIST_ENTRY, + SNM_FORCE_ERROR_GET_USER_INFO_LIST, + SNM_FORCE_ERROR_LEAVE_ROOM, + SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL, + SNM_FORCE_ERROR_SET_ROOM_MEMBER_DATA_INTERNAL2, + SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT, + SNM_FORCE_ERROR_CREATE_JOIN_ROOM, + SNM_FORCE_ERROR_GET_SERVER_INFO, + SNM_FORCE_ERROR_DELETE_SERVER_CONTEXT, + SNM_FORCE_ERROR_SETSOCKOPT_0, + SNM_FORCE_ERROR_SETSOCKOPT_1, + SNM_FORCE_ERROR_SETSOCKOPT_2, + SNM_FORCE_ERROR_SOCK_BIND, + SNM_FORCE_ERROR_CREATE_RUDP_CONTEXT, + SNM_FORCE_ERROR_RUDP_BIND, + SNM_FORCE_ERROR_RUDP_INIT2, + SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA, + SNM_FORCE_ERROR_GET_SERVER_INFO_DATA, + SNM_FORCE_ERROR_GET_WORLD_INFO_DATA, + SNM_FORCE_ERROR_GET_CREATE_JOIN_ROOM_DATA, + SNM_FORCE_ERROR_GET_USER_INFO_LIST_DATA, + SNM_FORCE_ERROR_GET_JOIN_ROOM_DATA, + SNM_FORCE_ERROR_GET_ROOM_MEMBER_DATA_INTERNAL, + SNM_FORCE_ERROR_GET_ROOM_EXTERNAL_DATA2, + SNM_FORCE_ERROR_CREATE_SERVER_CONTEXT_CALLBACK, + SNM_FORCE_ERROR_SET_ROOM_DATA_CALLBACK, + SNM_FORCE_ERROR_UPDATED_ROOM_DATA, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL1, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL2, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL3, + SNM_FORCE_ERROR_UPDATED_ROOM_MEMBER_DATA_INTERNAL4, + SNM_FORCE_ERROR_GET_WORLD_INFO_LIST, + SNM_FORCE_ERROR_JOIN_ROOM, - SNM_FORCE_ERROR_COUNT, - } eSQRForceError; + SNM_FORCE_ERROR_COUNT, + } eSQRForceError; + class StateChangeInfo { + public: + eSQRNetworkManagerState m_oldState; + eSQRNetworkManagerState m_newState; + bool m_idleReasonIsSessionFull; + StateChangeInfo(eSQRNetworkManagerState oldState, + eSQRNetworkManagerState newState, + bool idleReasonIsSessionFull) + : m_oldState(oldState), + m_newState(newState), + m_idleReasonIsSessionFull(idleReasonIsSessionFull) {} + }; - class StateChangeInfo - { - public: - eSQRNetworkManagerState m_oldState; - eSQRNetworkManagerState m_newState; - bool m_idleReasonIsSessionFull; - StateChangeInfo(eSQRNetworkManagerState oldState, eSQRNetworkManagerState newState,bool idleReasonIsSessionFull) : m_oldState(oldState), m_newState(newState), m_idleReasonIsSessionFull(idleReasonIsSessionFull) {} - }; + std::queue m_stateChangeQueue; + CRITICAL_SECTION m_csStateChangeQueue; + CRITICAL_SECTION m_csMatching; - std::queue m_stateChangeQueue; - CRITICAL_SECTION m_csStateChangeQueue; - CRITICAL_SECTION m_csMatching; + typedef enum { + SNM_FRIEND_SEARCH_STATE_IDLE, // Idle - search result will be valid + // (although it may not have any entries) + SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT, // Getting count of + // friends in friend list + SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO, // Getting presence/NpId + // info for each friend + } eSQRNetworkManagerFriendSearchState; - typedef enum - { - SNM_FRIEND_SEARCH_STATE_IDLE, // Idle - search result will be valid (although it may not have any entries) - SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_COUNT, // Getting count of friends in friend list - SNM_FRIEND_SEARCH_STATE_GETTING_FRIEND_INFO, // Getting presence/NpId info for each friend - } eSQRNetworkManagerFriendSearchState; + typedef void (*ServerContextValidCallback)(SQRNetworkManager* manager); - typedef void (*ServerContextValidCallback)(SQRNetworkManager *manager); - - static bool s_safeToRespondToGameBootInvite; + static bool s_safeToRespondToGameBootInvite; public: - - // General - virtual void Tick() = 0; - virtual void Initialise() = 0; + // General + virtual void Tick() = 0; + virtual void Initialise() = 0; #ifdef __PSVITA__ - virtual void UnInitialise() = 0; // to switch from PSN to Adhoc - virtual bool IsInitialised() = 0; + virtual void UnInitialise() = 0; // to switch from PSN to Adhoc + virtual bool IsInitialised() = 0; #endif - virtual void Terminate() = 0; - virtual eSQRNetworkManagerState GetState() = 0; - virtual bool IsHost() = 0; - virtual bool IsReadyToPlayOrIdle() = 0; - virtual bool IsInSession() = 0; + virtual void Terminate() = 0; + virtual eSQRNetworkManagerState GetState() = 0; + virtual bool IsHost() = 0; + virtual bool IsReadyToPlayOrIdle() = 0; + virtual bool IsInSession() = 0; - // Session management - virtual void CreateAndJoinRoom(int hostIndex, int localPlayerMask, void *extData, int extDataSize, bool offline) = 0; - virtual void UpdateExternalRoomData() = 0; - virtual bool FriendRoomManagerIsBusy() = 0; - virtual bool FriendRoomManagerSearch() = 0; - virtual bool FriendRoomManagerSearch2() = 0; - virtual int FriendRoomManagerGetCount() = 0; - virtual void FriendRoomManagerGetRoomInfo(int idx, SessionSearchResult *searchResult) = 0; - virtual bool JoinRoom(SessionSearchResult *searchResult, int localPlayerMask) = 0; - virtual bool JoinRoom(SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId, int localPlayerMask, const SQRNetworkManager::PresenceSyncInfo *presence) = 0; - virtual void StartGame() = 0; - virtual void LeaveRoom(bool bActuallyLeaveRoom) = 0; - virtual void EndGame() = 0; - virtual bool SessionHasSpace(int spaceRequired) = 0; - virtual bool AddLocalPlayerByUserIndex(int idx) = 0; - virtual bool RemoveLocalPlayerByUserIndex(int idx) = 0; - virtual void SendInviteGUI() = 0; + // Session management + virtual void CreateAndJoinRoom(int hostIndex, int localPlayerMask, + void* extData, int extDataSize, + bool offline) = 0; + virtual void UpdateExternalRoomData() = 0; + virtual bool FriendRoomManagerIsBusy() = 0; + virtual bool FriendRoomManagerSearch() = 0; + virtual bool FriendRoomManagerSearch2() = 0; + virtual int FriendRoomManagerGetCount() = 0; + virtual void FriendRoomManagerGetRoomInfo( + int idx, SessionSearchResult* searchResult) = 0; + virtual bool JoinRoom(SessionSearchResult* searchResult, + int localPlayerMask) = 0; + virtual bool JoinRoom( + SceNpMatching2RoomId roomId, SceNpMatching2ServerId serverId, + int localPlayerMask, + const SQRNetworkManager::PresenceSyncInfo* presence) = 0; + virtual void StartGame() = 0; + virtual void LeaveRoom(bool bActuallyLeaveRoom) = 0; + virtual void EndGame() = 0; + virtual bool SessionHasSpace(int spaceRequired) = 0; + virtual bool AddLocalPlayerByUserIndex(int idx) = 0; + virtual bool RemoveLocalPlayerByUserIndex(int idx) = 0; + virtual void SendInviteGUI() = 0; - virtual void GetExtDataForRoom( SceNpMatching2RoomId roomId, void *extData, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) = 0; + virtual void GetExtDataForRoom(SceNpMatching2RoomId roomId, void* extData, + void (*FriendSessionUpdatedFn)(bool success, + void* pParam), + void* pParam) = 0; - // Player retrieval - virtual int GetPlayerCount() = 0; - virtual int GetOnlinePlayerCount() = 0; - virtual SQRNetworkPlayer *GetPlayerByIndex(int idx) = 0; - virtual SQRNetworkPlayer *GetPlayerBySmallId(int idx) = 0; - virtual SQRNetworkPlayer *GetPlayerByXuid(PlayerUID xuid) = 0; - virtual SQRNetworkPlayer *GetLocalPlayerByUserIndex(int idx) = 0; - virtual SQRNetworkPlayer *GetHostPlayer() = 0; + // Player retrieval + virtual int GetPlayerCount() = 0; + virtual int GetOnlinePlayerCount() = 0; + virtual SQRNetworkPlayer* GetPlayerByIndex(int idx) = 0; + virtual SQRNetworkPlayer* GetPlayerBySmallId(int idx) = 0; + virtual SQRNetworkPlayer* GetPlayerByXuid(PlayerUID xuid) = 0; + virtual SQRNetworkPlayer* GetLocalPlayerByUserIndex(int idx) = 0; + virtual SQRNetworkPlayer* GetHostPlayer() = 0; - virtual void SetPresenceDataStartHostingGame() = 0; - virtual int GetJoiningReadyPercentage() = 0; + virtual void SetPresenceDataStartHostingGame() = 0; + virtual int GetJoiningReadyPercentage() = 0; - virtual void LocalDataSend(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, const void *data, unsigned int dataSize) = 0; - virtual int GetSessionIndex(SQRNetworkPlayer *player) = 0; - - static void SafeToRespondToGameBootInvite(); + virtual void LocalDataSend(SQRNetworkPlayer* playerFrom, + SQRNetworkPlayer* playerTo, const void* data, + unsigned int dataSize) = 0; + virtual int GetSessionIndex(SQRNetworkPlayer* player) = 0; + static void SafeToRespondToGameBootInvite(); }; - // Class defining interface to be implemented for class that handles callbacks -class ISQRNetworkManagerListener -{ +class ISQRNetworkManagerListener { public: - virtual void HandleDataReceived(SQRNetworkPlayer *playerFrom, SQRNetworkPlayer *playerTo, unsigned char *data, unsigned int dataSize) = 0; - virtual void HandlePlayerJoined(SQRNetworkPlayer *player) = 0; - virtual void HandlePlayerLeaving(SQRNetworkPlayer *player) = 0; - virtual void HandleStateChange(SQRNetworkManager::eSQRNetworkManagerState oldState, SQRNetworkManager::eSQRNetworkManagerState newState, bool idleReasonIsSessionFull) = 0; - virtual void HandleResyncPlayerRequest(SQRNetworkPlayer **aPlayers) = 0; - virtual void HandleAddLocalPlayerFailed(int idx) = 0; - virtual void HandleDisconnect(bool bLostRoomOnly,bool bPSNSignOut=false) = 0; - virtual void HandleInviteReceived( int userIndex, const SQRNetworkManager::PresenceSyncInfo *pInviteInfo) = 0; + virtual void HandleDataReceived(SQRNetworkPlayer* playerFrom, + SQRNetworkPlayer* playerTo, + unsigned char* data, + unsigned int dataSize) = 0; + virtual void HandlePlayerJoined(SQRNetworkPlayer* player) = 0; + virtual void HandlePlayerLeaving(SQRNetworkPlayer* player) = 0; + virtual void HandleStateChange( + SQRNetworkManager::eSQRNetworkManagerState oldState, + SQRNetworkManager::eSQRNetworkManagerState newState, + bool idleReasonIsSessionFull) = 0; + virtual void HandleResyncPlayerRequest(SQRNetworkPlayer** aPlayers) = 0; + virtual void HandleAddLocalPlayerFailed(int idx) = 0; + virtual void HandleDisconnect(bool bLostRoomOnly, + bool bPSNSignOut = false) = 0; + virtual void HandleInviteReceived( + int userIndex, + const SQRNetworkManager::PresenceSyncInfo* pInviteInfo) = 0; }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.cpp b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.cpp index 365e3e654..f0c86bbbf 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.cpp @@ -9,391 +9,360 @@ #include #include "../../../../Platform/Orbis/Network/SonyVoiceChat_Orbis.h" -#else // __PSVITA__ +#else // __PSVITA__ #include #include #include "../../../../Platform/PSVita/Network/SonyVoiceChat_Vita.h" #endif - static const bool sc_verbose = false; -int SQRNetworkPlayer::GetSmallId() -{ - return m_ISD.m_smallId; +int SQRNetworkPlayer::GetSmallId() { return m_ISD.m_smallId; } + +wchar_t* SQRNetworkPlayer::GetName() { return m_name; } + +bool SQRNetworkPlayer::IsRemote() { return !IsLocal(); } + +bool SQRNetworkPlayer::IsHost() { return (m_type == SNP_TYPE_HOST); } + +bool SQRNetworkPlayer::IsLocal() { + // m_host determines whether this *machine* is hosting the game, not this + // player (which is determined by m_type) + if (m_host) { + // If we are the hosting machine, then both the host & local players are + // local to this machine + return (m_type == SNP_TYPE_HOST) || (m_type == SNP_TYPE_LOCAL); + } else { + // Not hosting, just local players are actually physically local + return (m_type == SNP_TYPE_LOCAL); + } } -wchar_t *SQRNetworkPlayer::GetName() -{ - return m_name; +int SQRNetworkPlayer::GetLocalPlayerIndex() { return m_localPlayerIdx; } + +bool SQRNetworkPlayer::IsSameSystem(SQRNetworkPlayer* other) { + return (m_roomMemberId == other->m_roomMemberId); } -bool SQRNetworkPlayer::IsRemote() -{ - return !IsLocal(); +uintptr_t SQRNetworkPlayer::GetCustomDataValue() { return m_customData; } + +void SQRNetworkPlayer::SetCustomDataValue(uintptr_t data) { + m_customData = data; } -bool SQRNetworkPlayer::IsHost() -{ - return (m_type == SNP_TYPE_HOST); -} - -bool SQRNetworkPlayer::IsLocal() -{ - // m_host determines whether this *machine* is hosting the game, not this player (which is determined by m_type) - if( m_host ) - { - // If we are the hosting machine, then both the host & local players are local to this machine - return (m_type == SNP_TYPE_HOST) || (m_type == SNP_TYPE_LOCAL); - } - else - { - // Not hosting, just local players are actually physically local - return (m_type == SNP_TYPE_LOCAL) ; - } -} - -int SQRNetworkPlayer::GetLocalPlayerIndex() -{ - return m_localPlayerIdx; -} - -bool SQRNetworkPlayer::IsSameSystem(SQRNetworkPlayer *other) -{ - return (m_roomMemberId == other->m_roomMemberId); -} - -uintptr_t SQRNetworkPlayer::GetCustomDataValue() -{ - return m_customData; -} - -void SQRNetworkPlayer::SetCustomDataValue(uintptr_t data) -{ - m_customData = data; -} - -SQRNetworkPlayer::SQRNetworkPlayer(SQRNetworkManager *manager, eSQRNetworkPlayerType playerType, bool onHost, SceNpMatching2RoomMemberId roomMemberId, int localPlayerIdx, int rudpCtx, PlayerUID *pUID) -{ - m_roomMemberId = roomMemberId; - m_localPlayerIdx = localPlayerIdx; - m_rudpCtx = rudpCtx; - m_flags = 0; - m_type = playerType; - m_host = onHost; - m_manager = manager; - m_customData = 0; - if( pUID ) - { - memcpy(&m_ISD.m_UID,pUID,sizeof(PlayerUID)); +SQRNetworkPlayer::SQRNetworkPlayer(SQRNetworkManager* manager, + eSQRNetworkPlayerType playerType, + bool onHost, + SceNpMatching2RoomMemberId roomMemberId, + int localPlayerIdx, int rudpCtx, + PlayerUID* pUID) { + m_roomMemberId = roomMemberId; + m_localPlayerIdx = localPlayerIdx; + m_rudpCtx = rudpCtx; + m_flags = 0; + m_type = playerType; + m_host = onHost; + m_manager = manager; + m_customData = 0; + if (pUID) { + memcpy(&m_ISD.m_UID, pUID, sizeof(PlayerUID)); #ifdef __PSVITA__ - if(CGameNetworkManager::usingAdhocMode() && pUID->getOnlineID()[0] == 0) - { - assert(localPlayerIdx == 0); - // player doesn't have an online UID, set it from the player name - m_ISD.m_UID.setForAdhoc(); - } -#endif // __PSVITA__ - } - else - { - memset(&m_ISD.m_UID,0,sizeof(PlayerUID)); - } - SetNameFromUID(); - InitializeCriticalSection(&m_csQueue); + if (CGameNetworkManager::usingAdhocMode() && + pUID->getOnlineID()[0] == 0) { + assert(localPlayerIdx == 0); + // player doesn't have an online UID, set it from the player name + m_ISD.m_UID.setForAdhoc(); + } +#endif // __PSVITA__ + } else { + memset(&m_ISD.m_UID, 0, sizeof(PlayerUID)); + } + SetNameFromUID(); + InitializeCriticalSection(&m_csQueue); #ifdef __ORBIS__ - if(IsLocal()) - { - SonyVoiceChat_Orbis::initLocalPlayer(m_localPlayerIdx); - } + if (IsLocal()) { + SonyVoiceChat_Orbis::initLocalPlayer(m_localPlayerIdx); + } #endif - } -SQRNetworkPlayer::~SQRNetworkPlayer() -{ +SQRNetworkPlayer::~SQRNetworkPlayer() { #ifdef __ORBIS__ - SQRNetworkManager_Orbis* pMan = (SQRNetworkManager_Orbis*)m_manager; + SQRNetworkManager_Orbis* pMan = (SQRNetworkManager_Orbis*)m_manager; // pMan->removePlayerFromVoiceChat(this); // m_roomMemberId = -1; #endif - DeleteCriticalSection(&m_csQueue); + DeleteCriticalSection(&m_csQueue); } -bool SQRNetworkPlayer::IsReady() -{ - return ( ( m_flags & SNP_FLAG_READY_MASK ) == SNP_FLAG_READY_MASK ); -} - -PlayerUID SQRNetworkPlayer::GetUID() -{ - return m_ISD.m_UID; +bool SQRNetworkPlayer::IsReady() { + return ((m_flags & SNP_FLAG_READY_MASK) == SNP_FLAG_READY_MASK); } -void SQRNetworkPlayer::SetUID(PlayerUID UID) -{ - m_ISD.m_UID = UID; - SetNameFromUID(); +PlayerUID SQRNetworkPlayer::GetUID() { return m_ISD.m_UID; } + +void SQRNetworkPlayer::SetUID(PlayerUID UID) { + m_ISD.m_UID = UID; + SetNameFromUID(); } -bool SQRNetworkPlayer::HasConnectionAndSmallId() -{ - const int reqFlags = ( SNP_FLAG_CONNECTION_COMPLETE | SNP_FLAG_SMALLID_ALLOCATED ); - return (( m_flags & reqFlags) == reqFlags); +bool SQRNetworkPlayer::HasConnectionAndSmallId() { + const int reqFlags = + (SNP_FLAG_CONNECTION_COMPLETE | SNP_FLAG_SMALLID_ALLOCATED); + return ((m_flags & reqFlags) == reqFlags); } -void SQRNetworkPlayer::ConnectionComplete() -{ - m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); - app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ConnectionComplete\n"); - m_flags |= SNP_FLAG_CONNECTION_COMPLETE; +void SQRNetworkPlayer::ConnectionComplete() { + m_host ? app.DebugPrintf(sc_verbose, "host : ") + : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">> ConnectionComplete\n"); + m_flags |= SNP_FLAG_CONNECTION_COMPLETE; } -void SQRNetworkPlayer::SmallIdAllocated(unsigned char smallId) -{ - m_ISD.m_smallId = smallId; - m_flags |= SNP_FLAG_SMALLID_ALLOCATED; - m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); - app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID allocated\n"); +void SQRNetworkPlayer::SmallIdAllocated(unsigned char smallId) { + m_ISD.m_smallId = smallId; + m_flags |= SNP_FLAG_SMALLID_ALLOCATED; + m_host ? app.DebugPrintf(sc_verbose, "host : ") + : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">> Small ID allocated\n"); + // If this is a non-network sort of player then flag now as having its small + // id confirmed + if ((m_type == SNP_TYPE_HOST) || (m_host && (m_type == SNP_TYPE_LOCAL)) || + (!m_host && (m_type == SNP_TYPE_REMOTE))) { + m_host ? app.DebugPrintf(sc_verbose, "host : ") + : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">>>>>> Small ID confirmed\n"); - // If this is a non-network sort of player then flag now as having its small id confirmed - if( ( m_type == SNP_TYPE_HOST ) || - ( m_host && ( m_type == SNP_TYPE_LOCAL ) ) || - ( !m_host && ( m_type == SNP_TYPE_REMOTE ) ) ) - { - m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); - app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); - - m_flags |= SNP_FLAG_SMALLID_CONFIRMED; - } + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; + } } -void SQRNetworkPlayer::InitialDataReceived(SQRNetworkPlayer::InitSendData *ISD) -{ - assert(m_ISD.m_smallId == ISD->m_smallId); - memcpy(&m_ISD, ISD, sizeof(InitSendData) ); +void SQRNetworkPlayer::InitialDataReceived( + SQRNetworkPlayer::InitSendData* ISD) { + assert(m_ISD.m_smallId == ISD->m_smallId); + memcpy(&m_ISD, ISD, sizeof(InitSendData)); #ifdef __PSVITA__ - SetNameFromUID(); + SetNameFromUID(); #endif - m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); - app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); - m_flags |= SNP_FLAG_SMALLID_CONFIRMED; + m_host ? app.DebugPrintf(sc_verbose, "host : ") + : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">> Small ID confirmed\n"); + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; } -bool SQRNetworkPlayer::HasSmallIdConfirmed() -{ - return ( m_flags & SNP_FLAG_SMALLID_CONFIRMED ); +bool SQRNetworkPlayer::HasSmallIdConfirmed() { + return (m_flags & SNP_FLAG_SMALLID_CONFIRMED); } -// To confirm to the host that we are ready, send a single byte with our small id. -void SQRNetworkPlayer::ConfirmReady() -{ +// To confirm to the host that we are ready, send a single byte with our small +// id. +void SQRNetworkPlayer::ConfirmReady() { #ifdef __PS3__ - int ret = cellRudpWrite( m_rudpCtx, &m_ISD, sizeof(InitSendData), CELL_RUDP_MSG_LATENCY_CRITICAL ); -#else //__ORBIS__ - int ret = sceRudpWrite( m_rudpCtx, &m_ISD, sizeof(InitSendData), SCE_RUDP_MSG_LATENCY_CRITICAL ); + int ret = cellRudpWrite(m_rudpCtx, &m_ISD, sizeof(InitSendData), + CELL_RUDP_MSG_LATENCY_CRITICAL); +#else //__ORBIS__ + int ret = sceRudpWrite(m_rudpCtx, &m_ISD, sizeof(InitSendData), + SCE_RUDP_MSG_LATENCY_CRITICAL); #endif - // TODO - error handling here? - assert ( ret == sizeof(InitSendData) ); - // Final flag for a local player on the client, as we are now safe to send data on to the host - m_host ? app.DebugPrintf(sc_verbose, "host : ") : app.DebugPrintf(sc_verbose, "client:"); - app.DebugPrintf(sc_verbose, ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Small ID confirmed\n"); - m_flags |= SNP_FLAG_SMALLID_CONFIRMED; + // TODO - error handling here? + assert(ret == sizeof(InitSendData)); + // Final flag for a local player on the client, as we are now safe to send + // data on to the host + m_host ? app.DebugPrintf(sc_verbose, "host : ") + : app.DebugPrintf(sc_verbose, "client:"); + app.DebugPrintf(sc_verbose, + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + ">> Small ID confirmed\n"); + m_flags |= SNP_FLAG_SMALLID_CONFIRMED; } -// Attempt to send data, of any size, from this player to that specified by pPlayerTarget. This may not be possible depending on the two players, due to -// our star shaped network connectivity. Data may be any size, and is copied so on returning from this method it does not need to be preserved. -void SQRNetworkPlayer::SendData( SQRNetworkPlayer *pPlayerTarget, const void *data, unsigned int dataSize ) -{ - // Our network is connected as a star. If we are the host, then we can send to any remote player. If we're a client, we can send only to the host. - // The host can also send to other local players, but this doesn't need to go through Rudp. - if( m_host ) - { - if( ( m_type == SNP_TYPE_HOST ) && ( pPlayerTarget->m_type == SNP_TYPE_LOCAL ) ) - { - // Special internal communication from host to local player - m_manager->LocalDataSend( this, pPlayerTarget, data, dataSize ); - } - else if( ( m_type == SNP_TYPE_LOCAL ) && ( pPlayerTarget->m_type == SNP_TYPE_HOST ) ) - { - // Special internal communication from local player to host - m_manager->LocalDataSend( this, pPlayerTarget, data, dataSize ); - } - else if( ( m_type == SNP_TYPE_HOST ) && ( pPlayerTarget->m_type == SNP_TYPE_REMOTE ) ) - { - // Rudp communication from host to remote player - handled by remote player instance - pPlayerTarget->SendInternal(data,dataSize); - } - else - { - // Can't do any other types of communications - assert(false); - } - } - else - { - if( ( m_type == SNP_TYPE_LOCAL ) && ( pPlayerTarget->m_type == SNP_TYPE_HOST ) ) - { - // Rudp communication from client to host - handled by this player instace - SendInternal(data, dataSize); - } - else - { - // Can't do any other types of communications - assert(false); - } - } +// Attempt to send data, of any size, from this player to that specified by +// pPlayerTarget. This may not be possible depending on the two players, due to +// our star shaped network connectivity. Data may be any size, and is copied so +// on returning from this method it does not need to be preserved. +void SQRNetworkPlayer::SendData(SQRNetworkPlayer* pPlayerTarget, + const void* data, unsigned int dataSize) { + // Our network is connected as a star. If we are the host, then we can send + // to any remote player. If we're a client, we can send only to the host. + // The host can also send to other local players, but this doesn't need to + // go through Rudp. + if (m_host) { + if ((m_type == SNP_TYPE_HOST) && + (pPlayerTarget->m_type == SNP_TYPE_LOCAL)) { + // Special internal communication from host to local player + m_manager->LocalDataSend(this, pPlayerTarget, data, dataSize); + } else if ((m_type == SNP_TYPE_LOCAL) && + (pPlayerTarget->m_type == SNP_TYPE_HOST)) { + // Special internal communication from local player to host + m_manager->LocalDataSend(this, pPlayerTarget, data, dataSize); + } else if ((m_type == SNP_TYPE_HOST) && + (pPlayerTarget->m_type == SNP_TYPE_REMOTE)) { + // Rudp communication from host to remote player - handled by remote + // player instance + pPlayerTarget->SendInternal(data, dataSize); + } else { + // Can't do any other types of communications + assert(false); + } + } else { + if ((m_type == SNP_TYPE_LOCAL) && + (pPlayerTarget->m_type == SNP_TYPE_HOST)) { + // Rudp communication from client to host - handled by this player + // instace + SendInternal(data, dataSize); + } else { + // Can't do any other types of communications + assert(false); + } + } } -// Internal send function - to simplify the number of mechanisms we have for sending data, this method just adds the data to be send to the player's internal queue, -// and then calls SendMoreInternal. This method can take any size of data, which it will split up into payload size chunks before sending. All input data is copied -// into internal buffers. -void SQRNetworkPlayer::SendInternal(const void *data, unsigned int dataSize) -{ - EnterCriticalSection(&m_csQueue); +// Internal send function - to simplify the number of mechanisms we have for +// sending data, this method just adds the data to be send to the player's +// internal queue, and then calls SendMoreInternal. This method can take any +// size of data, which it will split up into payload size chunks before sending. +// All input data is copied into internal buffers. +void SQRNetworkPlayer::SendInternal(const void* data, unsigned int dataSize) { + EnterCriticalSection(&m_csQueue); - QueuedSendBlock sendBlock; + QueuedSendBlock sendBlock; - unsigned char *dataCurrent = (unsigned char *)data; - unsigned int dataRemaining = dataSize; + unsigned char* dataCurrent = (unsigned char*)data; + unsigned int dataRemaining = dataSize; - while( dataRemaining ) - { - int dataSize = dataRemaining; - if( dataSize > SNP_MAX_PAYLOAD ) dataSize = SNP_MAX_PAYLOAD; - sendBlock.start = new unsigned char [dataSize]; - sendBlock.end = sendBlock.start + dataSize; - sendBlock.current = sendBlock.start; - memcpy( sendBlock.start, dataCurrent, dataSize); - m_sendQueue.push(sendBlock); - dataRemaining -= dataSize; - dataCurrent += dataSize; - } + while (dataRemaining) { + int dataSize = dataRemaining; + if (dataSize > SNP_MAX_PAYLOAD) dataSize = SNP_MAX_PAYLOAD; + sendBlock.start = new unsigned char[dataSize]; + sendBlock.end = sendBlock.start + dataSize; + sendBlock.current = sendBlock.start; + memcpy(sendBlock.start, dataCurrent, dataSize); + m_sendQueue.push(sendBlock); + dataRemaining -= dataSize; + dataCurrent += dataSize; + } - // Now try and send as much as we can - SendMoreInternal(); + // Now try and send as much as we can + SendMoreInternal(); - LeaveCriticalSection(&m_csQueue); + LeaveCriticalSection(&m_csQueue); } - - - -// Internal send function. This attempts to send as many elements in the queue as possible until the write function tells us that we can't send any more. This way, -// we are guaranteed that if there *is* anything more in the queue left to send, we'll get a CELL_RUDP_CONTEXT_EVENT_WRITABLE event when whatever we've managed to -// send here is complete, and can continue on. -void SQRNetworkPlayer::SendMoreInternal() -{ - EnterCriticalSection(&m_csQueue); - bool keepSending; - do - { - keepSending = false; - if( m_sendQueue.size() > 0) - { - // Attempt to send the full data in the first element in our queue - unsigned char *data= m_sendQueue.front().current; - int dataSize = m_sendQueue.front().end - m_sendQueue.front().current; +// Internal send function. This attempts to send as many elements in the queue +// as possible until the write function tells us that we can't send any more. +// This way, we are guaranteed that if there *is* anything more in the queue +// left to send, we'll get a CELL_RUDP_CONTEXT_EVENT_WRITABLE event when +// whatever we've managed to send here is complete, and can continue on. +void SQRNetworkPlayer::SendMoreInternal() { + EnterCriticalSection(&m_csQueue); + bool keepSending; + do { + keepSending = false; + if (m_sendQueue.size() > 0) { + // Attempt to send the full data in the first element in our queue + unsigned char* data = m_sendQueue.front().current; + int dataSize = + m_sendQueue.front().end - m_sendQueue.front().current; #ifdef __PS3__ - int ret = cellRudpWrite( m_rudpCtx, data, dataSize, 0);//CELL_RUDP_MSG_LATENCY_CRITICAL ); - int wouldBlockFlag = CELL_RUDP_ERROR_WOULDBLOCK; + int ret = cellRudpWrite(m_rudpCtx, data, dataSize, + 0); // CELL_RUDP_MSG_LATENCY_CRITICAL ); + int wouldBlockFlag = CELL_RUDP_ERROR_WOULDBLOCK; -#else // __ORBIS__ - int ret = sceRudpWrite( m_rudpCtx, data, dataSize, 0);//CELL_RUDP_MSG_LATENCY_CRITICAL ); - int wouldBlockFlag = SCE_RUDP_ERROR_WOULDBLOCK; +#else // __ORBIS__ + int ret = sceRudpWrite(m_rudpCtx, data, dataSize, + 0); // CELL_RUDP_MSG_LATENCY_CRITICAL ); + int wouldBlockFlag = SCE_RUDP_ERROR_WOULDBLOCK; #endif - if( ret == dataSize ) - { - // Fully sent, remove from queue - will loop in the while loop to see if there's anything else in the queue we could send - delete [] m_sendQueue.front().start; - m_sendQueue.pop(); - if( m_sendQueue.size() ) - { - keepSending = true; - } - } - else if( ( ret >= 0 ) || ( ret == wouldBlockFlag ) ) - { - - - // Things left to send - adjust this element in the queue - int remainingBytes; - if( ret >= 0 ) - { - // Only ret bytes sent so far - remainingBytes = dataSize - ret; - assert(remainingBytes > 0 ); - } - else - { - // Is CELL_RUDP_ERROR_WOULDBLOCK, nothing has yet been sent - remainingBytes = dataSize; - } - m_sendQueue.front().current = m_sendQueue.front().end - remainingBytes; - } - } - } while (keepSending); - LeaveCriticalSection(&m_csQueue); + if (ret == dataSize) { + // Fully sent, remove from queue - will loop in the while loop + // to see if there's anything else in the queue we could send + delete[] m_sendQueue.front().start; + m_sendQueue.pop(); + if (m_sendQueue.size()) { + keepSending = true; + } + } else if ((ret >= 0) || (ret == wouldBlockFlag)) { + // Things left to send - adjust this element in the queue + int remainingBytes; + if (ret >= 0) { + // Only ret bytes sent so far + remainingBytes = dataSize - ret; + assert(remainingBytes > 0); + } else { + // Is CELL_RUDP_ERROR_WOULDBLOCK, nothing has yet been sent + remainingBytes = dataSize; + } + m_sendQueue.front().current = + m_sendQueue.front().end - remainingBytes; + } + } + } while (keepSending); + LeaveCriticalSection(&m_csQueue); } -void SQRNetworkPlayer::SetNameFromUID() -{ - mbstowcs(m_name, m_ISD.m_UID.getOnlineID(), 16); - m_name[16] = 0; -#ifdef __PS3__ // only 1 player on vita, and they have to be online (or adhoc), and with PS4 all local players need to be signed in - // Not an online player? Add a suffix with the controller ID on - if( m_ISD.m_UID.isSignedIntoPSN() == 0) - { - int pos = wcslen(m_name); - swprintf(&m_name[pos], 5, L" (%d)", m_ISD.m_UID.getQuadrant() + 1 ); - } +void SQRNetworkPlayer::SetNameFromUID() { + mbstowcs(m_name, m_ISD.m_UID.getOnlineID(), 16); + m_name[16] = 0; +#ifdef __PS3__ // only 1 player on vita, and they have to be online (or adhoc), + // and with PS4 all local players need to be signed in + // Not an online player? Add a suffix with the controller ID on + if (m_ISD.m_UID.isSignedIntoPSN() == 0) { + int pos = wcslen(m_name); + swprintf(&m_name[pos], 5, L" (%d)", m_ISD.m_UID.getQuadrant() + 1); + } #endif } -void SQRNetworkPlayer::SetName(char *name) -{ - mbstowcs(m_name, name, 20); - m_name[20] = 0; +void SQRNetworkPlayer::SetName(char* name) { + mbstowcs(m_name, name, 20); + m_name[20] = 0; } -int SQRNetworkPlayer::GetSessionIndex() -{ - return m_manager->GetSessionIndex(this); +int SQRNetworkPlayer::GetSessionIndex() { + return m_manager->GetSessionIndex(this); } -bool SQRNetworkPlayer::HasVoice() -{ +bool SQRNetworkPlayer::HasVoice() { #ifdef __ORBIS__ - return SonyVoiceChat_Orbis::hasMicConnected(this); + return SonyVoiceChat_Orbis::hasMicConnected(this); #elif defined __PSVITA__ - return SonyVoiceChat_Vita::hasMicConnected(this); + return SonyVoiceChat_Vita::hasMicConnected(this); #else - return SonyVoiceChat::hasMicConnected(&m_roomMemberId); + return SonyVoiceChat::hasMicConnected(&m_roomMemberId); #endif } -bool SQRNetworkPlayer::IsTalking() -{ +bool SQRNetworkPlayer::IsTalking() { #ifdef __ORBIS__ - return SonyVoiceChat_Orbis::isTalking(this); + return SonyVoiceChat_Orbis::isTalking(this); #elif defined __PSVITA__ - return SonyVoiceChat_Vita::isTalking(this); + return SonyVoiceChat_Vita::isTalking(this); #else - return SonyVoiceChat::isTalking(&m_roomMemberId); + return SonyVoiceChat::isTalking(&m_roomMemberId); #endif } -bool SQRNetworkPlayer::IsMutedByLocalUser(int userIndex) -{ +bool SQRNetworkPlayer::IsMutedByLocalUser(int userIndex) { #ifdef __ORBIS__ -// assert(0); // this is never called, so isn't implemented in the PS4 voice stuff at the moment - return false; + // assert(0); // this is never called, so isn't implemented in the PS4 + // voice stuff at the moment + return false; #elif defined __PSVITA__ - return false;// this is never called, so isn't implemented in the Vita voice stuff at the moment + return false; // this is never called, so isn't implemented in the Vita + // voice stuff at the moment #else - SQRNetworkManager_PS3* pMan = (SQRNetworkManager_PS3*)m_manager; - return SonyVoiceChat::isMutedPlayer(pMan->m_roomSyncData.players[userIndex].m_roomMemberId); + SQRNetworkManager_PS3* pMan = (SQRNetworkManager_PS3*)m_manager; + return SonyVoiceChat::isMutedPlayer( + pMan->m_roomSyncData.players[userIndex].m_roomMemberId); #endif } diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.h b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.h index 0cd56e8d6..8610e4417 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/SQRNetworkPlayer.h @@ -2,102 +2,139 @@ #include "SQRNetworkManager.h" #include -// This is the lowest level class for handling the concept of a player on Sony platforms. This is managed by SQRNetworkManager. The game shouldn't directly communicate -// with this class, as it is wrapped by NetworkPlayerSony which is an implementation of a platform-independent interface INetworkPlayer. +// This is the lowest level class for handling the concept of a player on Sony +// platforms. This is managed by SQRNetworkManager. The game shouldn't directly +// communicate with this class, as it is wrapped by NetworkPlayerSony which is +// an implementation of a platform-independent interface INetworkPlayer. -class SQRNetworkPlayer -{ +class SQRNetworkPlayer { #ifdef __ORBIS__ - friend class SQRNetworkManager_Orbis; - friend class SonyVoiceChat_Orbis; + friend class SQRNetworkManager_Orbis; + friend class SonyVoiceChat_Orbis; #elif defined __PS3__ - friend class SQRNetworkManager_PS3; -#else // __PSVITA__ - friend class SQRNetworkManager_Vita; - friend class SQRNetworkManager_AdHoc_Vita; - friend class SonyVoiceChat_Vita; + friend class SQRNetworkManager_PS3; +#else // __PSVITA__ + friend class SQRNetworkManager_Vita; + friend class SQRNetworkManager_AdHoc_Vita; + friend class SonyVoiceChat_Vita; #endif - friend class SQRNetworkManager; - friend class NetworkPlayerSony; - friend class CPlatformNetworkManagerSony; + friend class SQRNetworkManager; + friend class NetworkPlayerSony; + friend class CPlatformNetworkManagerSony; - int GetSmallId(); - wchar_t *GetName(); - bool IsRemote(); - bool IsHost(); - bool IsLocal(); - int GetLocalPlayerIndex(); - bool IsSameSystem(SQRNetworkPlayer *other); - uintptr_t GetCustomDataValue(); - void SetCustomDataValue(uintptr_t data); - bool HasVoice(); - bool IsTalking(); - bool IsMutedByLocalUser(int userIndex); + int GetSmallId(); + wchar_t* GetName(); + bool IsRemote(); + bool IsHost(); + bool IsLocal(); + int GetLocalPlayerIndex(); + bool IsSameSystem(SQRNetworkPlayer* other); + uintptr_t GetCustomDataValue(); + void SetCustomDataValue(uintptr_t data); + bool HasVoice(); + bool IsTalking(); + bool IsMutedByLocalUser(int userIndex); - static const int SNP_FLAG_CONNECTION_COMPLETE = 1; // This player has a fully connected Rudp or other local link established (to a remote player if this is on the host, to the host if this is a client) - or isn't expected to have one - static const int SNP_FLAG_SMALLID_ALLOCATED = 2; // This player has a small id allocated - static const int SNP_FLAG_SMALLID_CONFIRMED = 4; // This player's small id has been confirmed as received by the client (only relevant for players using network communications, others set at the same time as allocating) - static const int SNP_FLAG_READY_MASK = 7; // Mask indicated all bits which must be set in the flags for this player to be considered "ready" + static const int SNP_FLAG_CONNECTION_COMPLETE = + 1; // This player has a fully connected Rudp or other local link + // established (to a remote player if this is on the host, to the + // host if this is a client) - or isn't expected to have one + static const int SNP_FLAG_SMALLID_ALLOCATED = + 2; // This player has a small id allocated + static const int SNP_FLAG_SMALLID_CONFIRMED = + 4; // This player's small id has been confirmed as received by the + // client (only relevant for players using network communications, + // others set at the same time as allocating) + static const int SNP_FLAG_READY_MASK = + 7; // Mask indicated all bits which must be set in the flags for this + // player to be considered "ready" - static const int SNP_MAX_PAYLOAD = 1346; // This is the default RUDP payload size - if we want to change this we'll need to use cellRudpSetOption to set something else & adjust segment size + static const int SNP_MAX_PAYLOAD = + 1346; // This is the default RUDP payload size - if we want to change + // this we'll need to use cellRudpSetOption to set something else + // & adjust segment size - typedef enum - { - SNP_TYPE_HOST, // This player represents the host - SNP_TYPE_LOCAL, // On host - this player is a local player that needs communicated with specially not using rudp. On clients - this is a local player, where m_rudpCtx is the context used to communicate from this player to/from the host - SNP_TYPE_REMOTE, // On host - this player's m_rupdCtx can be used to communicate from between the host and this player. On clients - this is a remote player that cannot be communicated with - } eSQRNetworkPlayerType; + typedef enum { + SNP_TYPE_HOST, // This player represents the host + SNP_TYPE_LOCAL, // On host - this player is a local player that needs + // communicated with specially not using rudp. On + // clients - this is a local player, where m_rudpCtx is + // the context used to communicate from this player + // to/from the host + SNP_TYPE_REMOTE, // On host - this player's m_rupdCtx can be used to + // communicate from between the host and this player. + // On clients - this is a remote player that cannot be + // communicated with + } eSQRNetworkPlayerType; - class QueuedSendBlock - { - public: - unsigned char *start; - unsigned char *end; - unsigned char *current; - }; + class QueuedSendBlock { + public: + unsigned char* start; + unsigned char* end; + unsigned char* current; + }; - class InitSendData - { - public: - unsigned char m_smallId; // Id to uniquely and permanently identify this player between machines - assigned by the server - PlayerUID m_UID; - }; + class InitSendData { + public: + unsigned char + m_smallId; // Id to uniquely and permanently identify this player + // between machines - assigned by the server + PlayerUID m_UID; + }; - SQRNetworkPlayer(SQRNetworkManager *manager, eSQRNetworkPlayerType playerType, bool onHost, SceNpMatching2RoomMemberId roomMemberId, int localPlayerIdx, int rudpCtx, PlayerUID *pUID); - ~SQRNetworkPlayer(); + SQRNetworkPlayer(SQRNetworkManager* manager, + eSQRNetworkPlayerType playerType, bool onHost, + SceNpMatching2RoomMemberId roomMemberId, + int localPlayerIdx, int rudpCtx, PlayerUID* pUID); + ~SQRNetworkPlayer(); - PlayerUID GetUID(); - void SetUID(PlayerUID UID); - bool HasConnectionAndSmallId(); - bool IsReady(); - void ConnectionComplete(); - void SmallIdAllocated(unsigned char smallId); - void InitialDataReceived(InitSendData *ISD); // Only for remote players as viewed from the host, this is set when the host has received confirmation that the client has received the small id for this player, ie it is now safe to send data to - bool HasSmallIdConfirmed(); + PlayerUID GetUID(); + void SetUID(PlayerUID UID); + bool HasConnectionAndSmallId(); + bool IsReady(); + void ConnectionComplete(); + void SmallIdAllocated(unsigned char smallId); + void InitialDataReceived( + InitSendData* + ISD); // Only for remote players as viewed from the host, this is + // set when the host has received confirmation that the + // client has received the small id for this player, ie it is + // now safe to send data to + bool HasSmallIdConfirmed(); - void SendData( SQRNetworkPlayer *pPlayerTarget, const void *data, unsigned int dataSize ); + void SendData(SQRNetworkPlayer* pPlayerTarget, const void* data, + unsigned int dataSize); - void ConfirmReady(); - void SendInternal(const void *data, unsigned int dataSize); - void SendMoreInternal(); + void ConfirmReady(); + void SendInternal(const void* data, unsigned int dataSize); + void SendMoreInternal(); #ifdef __PSVITA__ - void SendInternal_VitaAdhoc(const void *data, unsigned int dataSize, EAdhocDataTag tag = e_dataTag_Normal); - void SendMoreInternal_VitaAdhoc(); + void SendInternal_VitaAdhoc(const void* data, unsigned int dataSize, + EAdhocDataTag tag = e_dataTag_Normal); + void SendMoreInternal_VitaAdhoc(); #endif - void SetNameFromUID(); - void SetName(char *name); - int GetSessionIndex(); + void SetNameFromUID(); + void SetName(char* name); + int GetSessionIndex(); - eSQRNetworkPlayerType m_type; // The player type - bool m_host; // Whether this actual player class is stored on a host (not whether it represents the host, or a player on the host machine) - int m_flags; // Flags reflecting current state of this player - int m_rudpCtx; // Rudp context that can be used to communicate between this player & the host (see comments for eSQRNetworkPlayerType above) - int m_localPlayerIdx; // Index of this player on the machine to which it belongs - SceNpMatching2RoomMemberId m_roomMemberId; // The room member id, effectively a per machine id - InitSendData m_ISD; // Player UID & ID that get sent together to the host when connection is established - SQRNetworkManager *m_manager; // Pointer back to the manager that is managing this player - wchar_t m_name[21]; - uintptr_t m_customData; - CRITICAL_SECTION m_csQueue; - std::queue m_sendQueue; + eSQRNetworkPlayerType m_type; // The player type + bool m_host; // Whether this actual player class is stored on a host (not + // whether it represents the host, or a player on the host + // machine) + int m_flags; // Flags reflecting current state of this player + int m_rudpCtx; // Rudp context that can be used to communicate between this + // player & the host (see comments for eSQRNetworkPlayerType + // above) + int m_localPlayerIdx; // Index of this player on the machine to which it + // belongs + SceNpMatching2RoomMemberId + m_roomMemberId; // The room member id, effectively a per machine id + InitSendData m_ISD; // Player UID & ID that get sent together to the host + // when connection is established + SQRNetworkManager* + m_manager; // Pointer back to the manager that is managing this player + wchar_t m_name[21]; + uintptr_t m_customData; + CRITICAL_SECTION m_csQueue; + std::queue m_sendQueue; }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.cpp b/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.cpp index 1beafa953..3ce5ec6e0 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.cpp @@ -4,1488 +4,1410 @@ #include "../../../../Platform/PS3/PS3Extras/ShutdownManager.h" #include +bool SonyCommerce::m_bCommerceInitialised = false; +SceNpCommerce2SessionInfo SonyCommerce::m_sessionInfo; +SonyCommerce::State SonyCommerce::m_state = e_state_noSession; +int SonyCommerce::m_errorCode = 0; +void* SonyCommerce::m_callbackParam = NULL; -bool SonyCommerce::m_bCommerceInitialised = false; -SceNpCommerce2SessionInfo SonyCommerce::m_sessionInfo; -SonyCommerce::State SonyCommerce::m_state = e_state_noSession; -int SonyCommerce::m_errorCode = 0; -void* SonyCommerce::m_callbackParam = NULL; +void* SonyCommerce::m_receiveBuffer = NULL; +SonyCommerce::Event SonyCommerce::m_event; +std::queue SonyCommerce::m_messageQueue; +std::vector* SonyCommerce::m_pProductInfoList = NULL; +SonyCommerce::ProductInfoDetailed* SonyCommerce::m_pProductInfoDetailed = NULL; +SonyCommerce::ProductInfo* SonyCommerce::m_pProductInfo = NULL; -void* SonyCommerce::m_receiveBuffer = NULL; -SonyCommerce::Event SonyCommerce::m_event; -std::queue SonyCommerce::m_messageQueue; -std::vector* SonyCommerce::m_pProductInfoList = NULL; -SonyCommerce::ProductInfoDetailed* SonyCommerce::m_pProductInfoDetailed = NULL; -SonyCommerce::ProductInfo* SonyCommerce::m_pProductInfo = NULL; +SonyCommerce::CategoryInfo* SonyCommerce::m_pCategoryInfo = NULL; +const char* SonyCommerce::m_pProductID = NULL; +char* SonyCommerce::m_pCategoryID = NULL; +SonyCommerce::CheckoutInputParams SonyCommerce::m_checkoutInputParams; +SonyCommerce::DownloadListInputParams SonyCommerce::m_downloadInputParams; -SonyCommerce::CategoryInfo* SonyCommerce::m_pCategoryInfo = NULL; -const char* SonyCommerce::m_pProductID = NULL; -char* SonyCommerce::m_pCategoryID = NULL; -SonyCommerce::CheckoutInputParams SonyCommerce::m_checkoutInputParams; -SonyCommerce::DownloadListInputParams SonyCommerce::m_downloadInputParams; +SonyCommerce::CallbackFunc SonyCommerce::m_callbackFunc = NULL; +sys_memory_container_t SonyCommerce::m_memContainer = + SYS_MEMORY_CONTAINER_ID_INVALID; +bool SonyCommerce::m_bUpgradingTrial = false; -SonyCommerce::CallbackFunc SonyCommerce::m_callbackFunc = NULL; -sys_memory_container_t SonyCommerce::m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; -bool SonyCommerce::m_bUpgradingTrial = false; +SonyCommerce::CallbackFunc SonyCommerce::m_trialUpgradeCallbackFunc; +void* SonyCommerce::m_trialUpgradeCallbackParam; -SonyCommerce::CallbackFunc SonyCommerce::m_trialUpgradeCallbackFunc; -void* SonyCommerce::m_trialUpgradeCallbackParam; +CRITICAL_SECTION SonyCommerce::m_queueLock; -CRITICAL_SECTION SonyCommerce::m_queueLock; - - - -uint32_t SonyCommerce::m_contextId=0; ///< The npcommerce2 context ID -bool SonyCommerce::m_contextCreated=false; ///< npcommerce2 context ID created? -SonyCommerce::Phase SonyCommerce::m_currentPhase = e_phase_stopped; ///< Current commerce2 util -char SonyCommerce::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; - -C4JThread* SonyCommerce::m_tickThread = NULL; -bool SonyCommerce::m_bLicenseChecked=false; // Check the trial/full license for the game +uint32_t SonyCommerce::m_contextId = 0; ///< The npcommerce2 context ID +bool SonyCommerce::m_contextCreated = + false; ///< npcommerce2 context ID created? +SonyCommerce::Phase SonyCommerce::m_currentPhase = + e_phase_stopped; ///< Current commerce2 util +char SonyCommerce::m_commercebuffer[SCE_NP_COMMERCE2_RECV_BUF_SIZE]; +C4JThread* SonyCommerce::m_tickThread = NULL; +bool SonyCommerce::m_bLicenseChecked = + false; // Check the trial/full license for the game SonyCommerce::ProductInfoDetailed s_trialUpgradeProductInfoDetailed; -void SonyCommerce::Delete() -{ - m_pProductInfoList=NULL; - m_pProductInfoDetailed=NULL; - m_pProductInfo=NULL; - m_pCategoryInfo = NULL; - m_pProductID = NULL; - m_pCategoryID = NULL; +void SonyCommerce::Delete() { + m_pProductInfoList = NULL; + m_pProductInfoDetailed = NULL; + m_pProductInfo = NULL; + m_pCategoryInfo = NULL; + m_pProductID = NULL; + m_pCategoryID = NULL; } -void SonyCommerce::Init() -{ - int ret; +void SonyCommerce::Init() { + int ret; - assert(m_state == e_state_noSession); - if(!m_bCommerceInitialised) - { - ret = sceNpCommerce2Init(); - if (ret < 0) - { - app.DebugPrintf(4,"sceNpCommerce2Init failed (0x%x)\n", ret); - return; - } - else - { - m_bCommerceInitialised = true; - } - m_pCategoryID=(char *)malloc(sizeof(char) * 100); - InitializeCriticalSection(&m_queueLock); - } - - return ; + assert(m_state == e_state_noSession); + if (!m_bCommerceInitialised) { + ret = sceNpCommerce2Init(); + if (ret < 0) { + app.DebugPrintf(4, "sceNpCommerce2Init failed (0x%x)\n", ret); + return; + } else { + m_bCommerceInitialised = true; + } + m_pCategoryID = (char*)malloc(sizeof(char) * 100); + InitializeCriticalSection(&m_queueLock); + } + return; } - - -void SonyCommerce::CheckForTrialUpgradeKey_Callback(void* param, bool bFullVersion) -{ - ProfileManager.SetFullVersion(bFullVersion); - if(ProfileManager.IsFullVersion()) - { - StorageManager.SetSaveDisabled(false); - ConsoleUIController::handleUnlockFullVersionCallback(); - // licence has been checked, so we're ok to install the trophies now - ProfileManager.InitialiseTrophies( SQRNetworkManager_PS3::GetSceNpCommsId(), - SQRNetworkManager_PS3::GetSceNpCommsSig()); - - } - m_bLicenseChecked=true; +void SonyCommerce::CheckForTrialUpgradeKey_Callback(void* param, + bool bFullVersion) { + ProfileManager.SetFullVersion(bFullVersion); + if (ProfileManager.IsFullVersion()) { + StorageManager.SetSaveDisabled(false); + ConsoleUIController::handleUnlockFullVersionCallback(); + // licence has been checked, so we're ok to install the trophies now + ProfileManager.InitialiseTrophies( + SQRNetworkManager_PS3::GetSceNpCommsId(), + SQRNetworkManager_PS3::GetSceNpCommsSig()); + } + m_bLicenseChecked = true; } -bool SonyCommerce::LicenseChecked() -{ - return m_bLicenseChecked; +bool SonyCommerce::LicenseChecked() { return m_bLicenseChecked; } + +void SonyCommerce::CheckForTrialUpgradeKey() { + StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, + NULL); } -void SonyCommerce::CheckForTrialUpgradeKey() -{ - StorageManager.CheckForTrialUpgradeKey(CheckForTrialUpgradeKey_Callback, NULL); +int SonyCommerce::Shutdown() { + int ret = 0; + if (m_contextCreated) { + ret = sceNpCommerce2DestroyCtx(m_contextId); + if (ret != 0) { + return ret; + } + + m_contextId = 0; + m_contextCreated = false; + } + + ret = sceNpCommerce2Term(); + m_bCommerceInitialised = false; + if (ret != 0) { + return ret; + } + delete m_pCategoryID; + DeleteCriticalSection(&m_queueLock); + + return ret; } -int SonyCommerce::Shutdown() -{ - int ret=0; - if (m_contextCreated) - { - ret = sceNpCommerce2DestroyCtx(m_contextId); - if (ret != 0) - { - return ret; - } +int SonyCommerce::TickLoop(void* lpParam) { + ShutdownManager::HasStarted(ShutdownManager::eCommerceThread); + while ((m_currentPhase != e_phase_stopped) && + ShutdownManager::ShouldRun(ShutdownManager::eCommerceThread)) { + processEvent(); + processMessage(); + Sleep(16); // sleep for a frame + } - m_contextId = 0; - m_contextCreated = false; - } + ShutdownManager::HasFinished(ShutdownManager::eCommerceThread); - ret = sceNpCommerce2Term(); - m_bCommerceInitialised = false; - if (ret != 0) - { - return ret; - } - delete m_pCategoryID; - DeleteCriticalSection(&m_queueLock); - - return ret; + return 0; } +int SonyCommerce::getProductList(std::vector* productList, + char* categoryId) { + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + SceNpCommerce2GetCategoryContentsResult result; + SceNpCommerce2CategoryInfo categoryInfo; + SceNpCommerce2ContentInfo contentInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + ProductInfo tempInfo; + std::vector tempProductVec; + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + setError(ret); + return ret; + } + } -int SonyCommerce::TickLoop(void* lpParam) -{ - ShutdownManager::HasStarted(ShutdownManager::eCommerceThread); - while( (m_currentPhase != e_phase_stopped) && ShutdownManager::ShouldRun(ShutdownManager::eCommerceThread) ) - { - processEvent(); - processMessage(); - Sleep(16); // sleep for a frame - } + // Create request ID + ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); + if (ret < 0) { + setError(ret); + return ret; + } - ShutdownManager::HasFinished(ShutdownManager::eCommerceThread); + // Obtain category content data + ret = sceNpCommerce2GetCategoryContentsStart( + requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + setError(ret); + return ret; + } - return 0; -} + ret = sceNpCommerce2GetCategoryContentsGetResult( + requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + setError(ret); + return ret; + } -int SonyCommerce::getProductList(std::vector* productList, char *categoryId) -{ - int ret = 0; - uint32_t requestId; - size_t bufSize = sizeof(m_commercebuffer); - size_t fillSize = 0; - SceNpCommerce2GetCategoryContentsResult result; - SceNpCommerce2CategoryInfo categoryInfo; - SceNpCommerce2ContentInfo contentInfo; - SceNpCommerce2GameProductInfo productInfo; - SceNpCommerce2GameSkuInfo skuInfo; - ProductInfo tempInfo; - std::vector tempProductVec; + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) { + setError(ret); + return ret; + } - if (!m_contextCreated) - { - ret = createContext(); - if (ret < 0) - { - setError(ret); - return ret; - } - } + // We have the initial category content data, + // now to take out the category content information. + ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, + fillSize); + if (ret < 0) { + setError(ret); + return ret; + } - // Create request ID - ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); - if (ret < 0) - { - setError(ret); - return ret; - } + // Get the category information + ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } - // Obtain category content data - ret = sceNpCommerce2GetCategoryContentsStart(requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); - if (ret < 0) - { - sceNpCommerce2DestroyReq(requestId); - setError(ret); - return ret; - } + if (categoryInfo.countOfProduct == 0) { + // There is no DLC + return 0; + } - ret = sceNpCommerce2GetCategoryContentsGetResult(requestId, m_commercebuffer, bufSize, &fillSize); - if (ret < 0) - { - sceNpCommerce2DestroyReq(requestId); - setError(ret); - return ret; - } + // Reserve some space + tempProductVec.reserve(categoryInfo.countOfProduct); - ret = sceNpCommerce2DestroyReq(requestId); - if (ret < 0) - { - setError(ret); - return ret; - } + // For each product, obtain information + for (int i = 0; i < result.rangeOfContents.count; i++) { + ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } - // We have the initial category content data, - // now to take out the category content information. - ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, fillSize); - if (ret < 0) - { - setError(ret); - return ret; - } + // Only process if it is a product + if (contentInfo.contentType == SCE_NP_COMMERCE2_CONTENT_TYPE_PRODUCT) { + // reset tempInfo + memset(&tempInfo, 0x0, sizeof(tempInfo)); - // Get the category information - ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - setError(ret); - return ret; - } + // Get product info + ret = sceNpCommerce2GetGameProductInfoFromContentInfo(&contentInfo, + &productInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } - if(categoryInfo.countOfProduct==0) - { - // There is no DLC - return 0; - } + // populate our temp struct - // Reserve some space - tempProductVec.reserve(categoryInfo.countOfProduct); - - // For each product, obtain information - for (int i = 0; i < result.rangeOfContents.count; i++) - { - ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - setError(ret); - return ret; - } - - // Only process if it is a product - if (contentInfo.contentType == SCE_NP_COMMERCE2_CONTENT_TYPE_PRODUCT) - { - - // reset tempInfo - memset(&tempInfo, 0x0, sizeof(tempInfo)); - - // Get product info - ret = sceNpCommerce2GetGameProductInfoFromContentInfo(&contentInfo, &productInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - setError(ret); - return ret; - } - - // populate our temp struct - - strncpy(tempInfo.productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); - strncpy(tempInfo.productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); - strncpy(tempInfo.shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); - if(tempInfo.longDescription[0]!=0) - { - strncpy(tempInfo.longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); - } - else - { + strncpy(tempInfo.productId, productInfo.productId, + SCE_NP_COMMERCE2_PRODUCT_ID_LEN); + strncpy(tempInfo.productName, productInfo.productName, + SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); + strncpy(tempInfo.shortDescription, + productInfo.productShortDescription, + SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + if (tempInfo.longDescription[0] != 0) { + strncpy(tempInfo.longDescription, + productInfo.productLongDescription, + SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); + } else { #ifdef _DEBUG - strcpy(tempInfo.longDescription,"Missing long description"); + strcpy(tempInfo.longDescription, "Missing long description"); #endif - } - strncpy(tempInfo.spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); - strncpy(tempInfo.imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); - tempInfo.releaseDate = productInfo.releaseDate; + } + strncpy(tempInfo.spName, productInfo.spName, + SCE_NP_COMMERCE2_SP_NAME_LEN); + strncpy(tempInfo.imageUrl, productInfo.imageUrl, + SCE_NP_COMMERCE2_URL_LEN); + tempInfo.releaseDate = productInfo.releaseDate; - if (productInfo.countOfSku == 1) - { - // Get SKU info - ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - setError(ret); - return ret; - } - tempInfo.purchasabilityFlag = skuInfo.purchasabilityFlag; + if (productInfo.countOfSku == 1) { + // Get SKU info + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo( + &productInfo, 0, &skuInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + tempInfo.purchasabilityFlag = skuInfo.purchasabilityFlag; - // Take out the price. Nicely formatted - // but also keep the price as a value in case it's 0 - we need to show "free" for that - tempInfo.ui32Price= skuInfo.price; - ret = sceNpCommerce2GetPrice(m_contextId, tempInfo.price, sizeof(tempInfo.price), skuInfo.price); - - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - setError(ret); - return ret; - } - } - tempProductVec.push_back(tempInfo); - } - } + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need + // to show "free" for that + tempInfo.ui32Price = skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, tempInfo.price, + sizeof(tempInfo.price), + skuInfo.price); - // Set our result - *productList = tempProductVec; + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + setError(ret); + return ret; + } + } + tempProductVec.push_back(tempInfo); + } + } - // Destroy the category contents result - ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); - if (ret < 0) - { - return ret; - } + // Set our result + *productList = tempProductVec; - return ret; + // Destroy the category contents result + ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); + if (ret < 0) { + return ret; + } + + return ret; } -int SonyCommerce::getCategoryInfo(CategoryInfo *pInfo, char *categoryId) -{ - int ret = 0; - uint32_t requestId; - size_t bufSize = sizeof(m_commercebuffer); - size_t fillSize = 0; - SceNpCommerce2GetCategoryContentsResult result; - SceNpCommerce2CategoryInfo categoryInfo; - SceNpCommerce2ContentInfo contentInfo; - //CategoryInfo tempCatInfo; - CategoryInfoSub tempSubCatInfo; +int SonyCommerce::getCategoryInfo(CategoryInfo* pInfo, char* categoryId) { + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + SceNpCommerce2GetCategoryContentsResult result; + SceNpCommerce2CategoryInfo categoryInfo; + SceNpCommerce2ContentInfo contentInfo; + // CategoryInfo + // tempCatInfo; + CategoryInfoSub tempSubCatInfo; - if (!m_contextCreated) - { - ret = createContext(); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } - } + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + } - // Create request ID - ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + // Create request ID + ret = sceNpCommerce2GetCategoryContentsCreateReq(m_contextId, &requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Obtain category content data - if (categoryId) - { - ret = sceNpCommerce2GetCategoryContentsStart(requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); - } - else - { - ret = sceNpCommerce2GetCategoryContentsStart(requestId,categoryId, - 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); - } - if (ret < 0) - { - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + // Obtain category content data + if (categoryId) { + ret = sceNpCommerce2GetCategoryContentsStart( + requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + } else { + ret = sceNpCommerce2GetCategoryContentsStart( + requestId, categoryId, 0, SCE_NP_COMMERCE2_GETCAT_MAX_COUNT); + } + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetCategoryContentsGetResult(requestId, m_commercebuffer, bufSize, &fillSize); - if (ret < 0) - { - if(ret==SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE) - { - app.DebugPrintf(4,"\n--- SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE ---\n\n"); - } - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2GetCategoryContentsGetResult( + requestId, m_commercebuffer, bufSize, &fillSize); + if (ret < 0) { + if (ret == SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE) { + app.DebugPrintf( + 4, "\n--- SCE_NP_COMMERCE2_ERROR_SERVER_MAINTENANCE ---\n\n"); + } + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2DestroyReq(requestId); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // We have the initial category content data, - // now to take out the category content information. - ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, fillSize); - if (ret < 0) { - m_errorCode = ret; - return ret; - } + // We have the initial category content data, + // now to take out the category content information. + ret = sceNpCommerce2InitGetCategoryContentsResult(&result, m_commercebuffer, + fillSize); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Get the category information - ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); - if (ret < 0) { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - m_errorCode = ret; - return ret; - } + // Get the category information + ret = sceNpCommerce2GetCategoryInfo(&result, &categoryInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } - strcpy(pInfo->current.categoryId, categoryInfo.categoryId); - strcpy(pInfo->current.categoryName, categoryInfo.categoryName); - strcpy(pInfo->current.categoryDescription, categoryInfo.categoryDescription); - strcpy(pInfo->current.imageUrl, categoryInfo.imageUrl); - pInfo->countOfProducts = categoryInfo.countOfProduct; - pInfo->countOfSubCategories = categoryInfo.countOfSubCategory; + strcpy(pInfo->current.categoryId, categoryInfo.categoryId); + strcpy(pInfo->current.categoryName, categoryInfo.categoryName); + strcpy(pInfo->current.categoryDescription, + categoryInfo.categoryDescription); + strcpy(pInfo->current.imageUrl, categoryInfo.imageUrl); + pInfo->countOfProducts = categoryInfo.countOfProduct; + pInfo->countOfSubCategories = categoryInfo.countOfSubCategory; - if (categoryInfo.countOfSubCategory > 0) - { - // For each sub category, obtain information - for (int i = 0; i < result.rangeOfContents.count; i++) - { + if (categoryInfo.countOfSubCategory > 0) { + // For each sub category, obtain information + for (int i = 0; i < result.rangeOfContents.count; i++) { + ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetContentInfo(&result, i, &contentInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - m_errorCode = ret; - return ret; - } + // Only process if it is a category + if (contentInfo.contentType == + SCE_NP_COMMERCE2_CONTENT_TYPE_CATEGORY) { + ret = sceNpCommerce2GetCategoryInfoFromContentInfo( + &contentInfo, &categoryInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetCategoryContentsResult(&result); + m_errorCode = ret; + return ret; + } - // Only process if it is a category - if (contentInfo.contentType == SCE_NP_COMMERCE2_CONTENT_TYPE_CATEGORY) - { + strcpy(tempSubCatInfo.categoryId, categoryInfo.categoryId); + strcpy(tempSubCatInfo.categoryName, categoryInfo.categoryName); + strcpy(tempSubCatInfo.categoryDescription, + categoryInfo.categoryDescription); + strcpy(tempSubCatInfo.imageUrl, categoryInfo.imageUrl); - ret = sceNpCommerce2GetCategoryInfoFromContentInfo(&contentInfo, &categoryInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetCategoryContentsResult(&result); - m_errorCode = ret; - return ret; - } + // Add to the list + pInfo->subCategories.push_back(tempSubCatInfo); + } + } + } - strcpy(tempSubCatInfo.categoryId, categoryInfo.categoryId); - strcpy(tempSubCatInfo.categoryName, categoryInfo.categoryName); - strcpy(tempSubCatInfo.categoryDescription, categoryInfo.categoryDescription); - strcpy(tempSubCatInfo.imageUrl, categoryInfo.imageUrl); + // Set our result + //*info = tempCatInfo; - // Add to the list - pInfo->subCategories.push_back(tempSubCatInfo); - } - } - } + // Destroy the category contents result + ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); + if (ret < 0) { + return ret; + } - // Set our result - //*info = tempCatInfo; - - // Destroy the category contents result - ret = sceNpCommerce2DestroyGetCategoryContentsResult(&result); - if (ret < 0) { - return ret; - } - - return ret; + return ret; } +int SonyCommerce::getDetailedProductInfo(ProductInfoDetailed* pInfo, + const char* productId, + char* categoryId) { + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + std::list ratingDescList; + SceNpCommerce2GetProductInfoResult result; + SceNpCommerce2ContentRatingInfo ratingInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + // ProductInfoDetailed + // tempInfo; -int SonyCommerce::getDetailedProductInfo(ProductInfoDetailed *pInfo, const char *productId, char *categoryId) -{ - int ret = 0; - uint32_t requestId; - size_t bufSize = sizeof(m_commercebuffer); - size_t fillSize = 0; - std::list ratingDescList; - SceNpCommerce2GetProductInfoResult result; - SceNpCommerce2ContentRatingInfo ratingInfo; - SceNpCommerce2GameProductInfo productInfo; - SceNpCommerce2GameSkuInfo skuInfo; - //ProductInfoDetailed tempInfo; + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + } - if (!m_contextCreated) { - ret = createContext(); - if (ret < 0) { - m_errorCode = ret; - return ret; - } - } + // Obtain product data + ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Obtain product data - ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); - if (ret < 0) { - m_errorCode = ret; - return ret; - } + if (categoryId && categoryId[0] != 0) { + ret = + sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } else { + ret = sceNpCommerce2GetProductInfoStart(requestId, NULL, productId); + } + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - if (categoryId && categoryId[0] != 0) { - ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); - } else { - ret = sceNpCommerce2GetProductInfoStart(requestId, NULL, productId); - } - if (ret < 0) { - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, + bufSize, &fillSize); + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, bufSize, &fillSize); - if (ret < 0) { - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2DestroyReq(requestId); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + // Take Out Game Product Information + ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, + fillSize); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Take Out Game Product Information - ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, fillSize); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } + // Get rating info + ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, + &ratingInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } - // Get rating info - ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, &ratingInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } + for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; + index++) { + SceNpCommerce2ContentRatingDescriptor desc; + sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); + ratingDescList.push_back(desc); + } - for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; index++) - { - SceNpCommerce2ContentRatingDescriptor desc; - sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); - ratingDescList.push_back(desc); - } + // populate our temp struct + pInfo->ratingDescriptors = ratingDescList; + strncpy(pInfo->productId, productInfo.productId, + SCE_NP_COMMERCE2_PRODUCT_ID_LEN); + strncpy(pInfo->productName, productInfo.productName, + SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); + strncpy(pInfo->shortDescription, productInfo.productShortDescription, + SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + strncpy(pInfo->longDescription, productInfo.productLongDescription, + SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); + strncpy(pInfo->legalDescription, productInfo.legalDescription, + SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); + strncpy(pInfo->spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); + strncpy(pInfo->imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + pInfo->releaseDate = productInfo.releaseDate; + strncpy(pInfo->ratingSystemId, ratingInfo.ratingSystemId, + SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); + strncpy(pInfo->ratingImageUrl, ratingInfo.imageUrl, + SCE_NP_COMMERCE2_URL_LEN); - // populate our temp struct - pInfo->ratingDescriptors = ratingDescList; - strncpy(pInfo->productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); - strncpy(pInfo->productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); - strncpy(pInfo->shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); - strncpy(pInfo->longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); - strncpy(pInfo->legalDescription, productInfo.legalDescription, SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); - strncpy(pInfo->spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); - strncpy(pInfo->imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); - pInfo->releaseDate = productInfo.releaseDate; - strncpy(pInfo->ratingSystemId, ratingInfo.ratingSystemId, SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); - strncpy(pInfo->ratingImageUrl, ratingInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + // Get SKU info + if (productInfo.countOfSku == 1) { + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, + &skuInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + strncpy(pInfo->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); + pInfo->purchasabilityFlag = skuInfo.purchasabilityFlag; - // Get SKU info - if (productInfo.countOfSku == 1) - { - ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } - strncpy(pInfo->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); - pInfo->purchasabilityFlag = skuInfo.purchasabilityFlag; + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need to show + // "free" for that + pInfo->ui32Price = skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, pInfo->price, + sizeof(pInfo->price), skuInfo.price); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + } - // Take out the price. Nicely formatted - // but also keep the price as a value in case it's 0 - we need to show "free" for that - pInfo->ui32Price= skuInfo.price; - ret = sceNpCommerce2GetPrice(m_contextId, pInfo->price, sizeof(pInfo->price), skuInfo.price); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } - } + // Set our result + //*info = tempInfo; - // Set our result - //*info = tempInfo; + ret = sceNpCommerce2DestroyGetProductInfoResult(&result); + if (ret < 0) { + return ret; + } - ret = sceNpCommerce2DestroyGetProductInfoResult(&result); - if (ret < 0) - { - return ret; - } - - return ret; + return ret; } +int SonyCommerce::addDetailedProductInfo(ProductInfo* info, + const char* productId, + char* categoryId) { + int ret = 0; + uint32_t requestId; + size_t bufSize = sizeof(m_commercebuffer); + size_t fillSize = 0; + std::list ratingDescList; + SceNpCommerce2GetProductInfoResult result; + SceNpCommerce2ContentRatingInfo ratingInfo; + SceNpCommerce2GameProductInfo productInfo; + SceNpCommerce2GameSkuInfo skuInfo; + // ProductInfoDetailed + // tempInfo; -int SonyCommerce::addDetailedProductInfo(ProductInfo *info, const char *productId, char *categoryId) -{ - int ret = 0; - uint32_t requestId; - size_t bufSize = sizeof(m_commercebuffer); - size_t fillSize = 0; - std::list ratingDescList; - SceNpCommerce2GetProductInfoResult result; - SceNpCommerce2ContentRatingInfo ratingInfo; - SceNpCommerce2GameProductInfo productInfo; - SceNpCommerce2GameSkuInfo skuInfo; - //ProductInfoDetailed tempInfo; + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + m_errorCode = ret; + return ret; + } + } - if (!m_contextCreated) - { - ret = createContext(); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } - } + // Obtain product data + ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Obtain product data - ret = sceNpCommerce2GetProductInfoCreateReq(m_contextId, &requestId); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + if (categoryId && categoryId[0] != 0) { + ret = + sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } else { + ret = + sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); + } + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - if (categoryId && categoryId[0] != 0) - { - ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); - } - else - { - ret = sceNpCommerce2GetProductInfoStart(requestId, categoryId, productId); - } - if (ret < 0) { - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, + bufSize, &fillSize); + if (ret < 0) { + sceNpCommerce2DestroyReq(requestId); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetProductInfoGetResult(requestId, m_commercebuffer, bufSize, &fillSize); - if (ret < 0) - { - sceNpCommerce2DestroyReq(requestId); - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2DestroyReq(requestId); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2DestroyReq(requestId); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + // Take Out Game Product Information + ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, + fillSize); + if (ret < 0) { + m_errorCode = ret; + return ret; + } - // Take Out Game Product Information - ret = sceNpCommerce2InitGetProductInfoResult(&result, m_commercebuffer, fillSize); - if (ret < 0) - { - m_errorCode = ret; - return ret; - } + ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } - ret = sceNpCommerce2GetGameProductInfo(&result, &productInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } + // Get rating info + ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, + &ratingInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } - // Get rating info - ret = sceNpCommerce2GetContentRatingInfoFromGameProductInfo(&productInfo, &ratingInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } + for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; + index++) { + SceNpCommerce2ContentRatingDescriptor desc; + sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); + ratingDescList.push_back(desc); + } - for (int index = 0; index < ratingInfo.countOfContentRatingDescriptor; index++) - { - SceNpCommerce2ContentRatingDescriptor desc; - sceNpCommerce2GetContentRatingDescriptor(&ratingInfo, index, &desc); - ratingDescList.push_back(desc); - } + // populate our temp struct + // tempInfo.ratingDescriptors = ratingDescList; + // strncpy(tempInfo.productId, productInfo.productId, + // SCE_NP_COMMERCE2_PRODUCT_ID_LEN); strncpy(tempInfo.productName, + // productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); + // strncpy(tempInfo.shortDescription, productInfo.productShortDescription, + // SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); + strncpy(info->longDescription, productInfo.productLongDescription, + SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); + // strncpy(tempInfo.legalDescription, productInfo.legalDescription, + // SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); strncpy(tempInfo.spName, + // productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); + // strncpy(tempInfo.imageUrl, productInfo.imageUrl, + // SCE_NP_COMMERCE2_URL_LEN); tempInfo.releaseDate = + // productInfo.releaseDate; strncpy(tempInfo.ratingSystemId, + // ratingInfo.ratingSystemId, SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); + // strncpy(tempInfo.ratingImageUrl, ratingInfo.imageUrl, + // SCE_NP_COMMERCE2_URL_LEN); - // populate our temp struct -// tempInfo.ratingDescriptors = ratingDescList; -// strncpy(tempInfo.productId, productInfo.productId, SCE_NP_COMMERCE2_PRODUCT_ID_LEN); -// strncpy(tempInfo.productName, productInfo.productName, SCE_NP_COMMERCE2_PRODUCT_NAME_LEN); -// strncpy(tempInfo.shortDescription, productInfo.productShortDescription, SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN); - strncpy(info->longDescription, productInfo.productLongDescription, SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN); -// strncpy(tempInfo.legalDescription, productInfo.legalDescription, SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN); -// strncpy(tempInfo.spName, productInfo.spName, SCE_NP_COMMERCE2_SP_NAME_LEN); -// strncpy(tempInfo.imageUrl, productInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); -// tempInfo.releaseDate = productInfo.releaseDate; -// strncpy(tempInfo.ratingSystemId, ratingInfo.ratingSystemId, SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN); -// strncpy(tempInfo.ratingImageUrl, ratingInfo.imageUrl, SCE_NP_COMMERCE2_URL_LEN); + // Get SKU info + if (productInfo.countOfSku == 1) { + ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, + &skuInfo); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + strncpy(info->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); + info->purchasabilityFlag = skuInfo.purchasabilityFlag; + info->annotation = skuInfo.annotation; - // Get SKU info - if (productInfo.countOfSku == 1) - { - ret = sceNpCommerce2GetGameSkuInfoFromGameProductInfo(&productInfo, 0, &skuInfo); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } - strncpy(info->skuId, skuInfo.skuId, SCE_NP_COMMERCE2_SKU_ID_LEN); - info->purchasabilityFlag = skuInfo.purchasabilityFlag; - info->annotation = skuInfo.annotation; + // Take out the price. Nicely formatted + // but also keep the price as a value in case it's 0 - we need to show + // "free" for that + info->ui32Price = skuInfo.price; + ret = sceNpCommerce2GetPrice(m_contextId, info->price, + sizeof(info->price), skuInfo.price); + if (ret < 0) { + sceNpCommerce2DestroyGetProductInfoResult(&result); + m_errorCode = ret; + return ret; + } + } else { + // 4J-PB - more than one sku id! We have to be able to use the sku id + // returned for a product, so there is not supposed to be more than 1 + app.DebugPrintf("MORE THAN 1 SKU ID FOR %s\n", info->productName); + } - // Take out the price. Nicely formatted - // but also keep the price as a value in case it's 0 - we need to show "free" for that - info->ui32Price= skuInfo.price; - ret = sceNpCommerce2GetPrice(m_contextId, info->price, sizeof(info->price), skuInfo.price); - if (ret < 0) - { - sceNpCommerce2DestroyGetProductInfoResult(&result); - m_errorCode = ret; - return ret; - } - } - else - { - // 4J-PB - more than one sku id! We have to be able to use the sku id returned for a product, so there is not supposed to be more than 1 - app.DebugPrintf("MORE THAN 1 SKU ID FOR %s\n",info->productName); - } + // Set our result + //*info = tempInfo; - // Set our result - //*info = tempInfo; + ret = sceNpCommerce2DestroyGetProductInfoResult(&result); + if (ret < 0) { + return ret; + } - ret = sceNpCommerce2DestroyGetProductInfoResult(&result); - if (ret < 0) - { - return ret; - } - - return ret; + return ret; } +int SonyCommerce::checkout(CheckoutInputParams& params) { + int ret = 0; + const char* skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; + std::list::iterator iter = params.skuIds.begin(); + std::list::iterator iterEnd = params.skuIds.end(); -int SonyCommerce::checkout(CheckoutInputParams ¶ms) -{ - int ret = 0; - const char *skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; - std::list::iterator iter = params.skuIds.begin(); - std::list::iterator iterEnd = params.skuIds.end(); + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + return ret; + } + } - if (!m_contextCreated) { - ret = createContext(); - if (ret < 0) { - return ret; - } - } + for (int i = 0; i < params.skuIds.size(); i++) { + skuIdsTemp[i] = (const char*)(*iter); + iter++; + } - for (int i = 0; i < params.skuIds.size(); i++) { - skuIdsTemp[i] = (const char *)(*iter); - iter++; - } + ret = sceNpCommerce2DoCheckoutStartAsync( + m_contextId, skuIdsTemp, params.skuIds.size(), *params.memContainer); + if (ret < 0) { + return ret; + } - ret = sceNpCommerce2DoCheckoutStartAsync(m_contextId, skuIdsTemp, params.skuIds.size(), *params.memContainer); - if (ret < 0) { - return ret; - } - - return CELL_OK; + return CELL_OK; } +int SonyCommerce::downloadList(DownloadListInputParams& params) { + int ret = 0; + const char* skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; + std::list::iterator iter = params.skuIds.begin(); + std::list::iterator iterEnd = params.skuIds.end(); -int SonyCommerce::downloadList(DownloadListInputParams ¶ms) -{ - int ret = 0; - const char *skuIdsTemp[SCE_NP_COMMERCE2_SKU_CHECKOUT_MAX]; - std::list::iterator iter = params.skuIds.begin(); - std::list::iterator iterEnd = params.skuIds.end(); + if (!m_contextCreated) { + ret = createContext(); + if (ret < 0) { + return ret; + } + } - if (!m_contextCreated) { - ret = createContext(); - if (ret < 0) { - return ret; - } - } + for (int i = 0; i < params.skuIds.size(); i++) { + skuIdsTemp[i] = (const char*)(*iter); + iter++; + } + ret = sceNpCommerce2DoDlListStartAsync( + m_contextId, app.GetCommerceCategory(), skuIdsTemp, + params.skuIds.size(), *params.memContainer); + if (ret < 0) { + return ret; + } - for (int i = 0; i < params.skuIds.size(); i++) { - skuIdsTemp[i] = (const char *)(*iter); - iter++; - } - ret = sceNpCommerce2DoDlListStartAsync(m_contextId, app.GetCommerceCategory(), skuIdsTemp, params.skuIds.size(), *params.memContainer); - if (ret < 0) { - return ret; - } - - return CELL_OK; + return CELL_OK; } -void SonyCommerce::UpgradeTrialCallback2(void* lpParam,int err) -{ - app.DebugPrintf(4,"SonyCommerce_UpgradeTrialCallback2 : err : 0x%08x\n", err); - SonyCommerce::CheckForTrialUpgradeKey(); - if(err != CELL_OK) - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, uiIDA,1,ProfileManager.GetPrimaryPad()); - } - m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); +void SonyCommerce::UpgradeTrialCallback2(void* lpParam, int err) { + app.DebugPrintf(4, "SonyCommerce_UpgradeTrialCallback2 : err : 0x%08x\n", + err); + SonyCommerce::CheckForTrialUpgradeKey(); + if (err != CELL_OK) { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + C4JStorage::EMessageResult result = + ui.RequestMessageBox(IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, + uiIDA, 1, ProfileManager.GetPrimaryPad()); + } + m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); } -void SonyCommerce::UpgradeTrialCallback1(void* lpParam,int err) -{ - - app.DebugPrintf(4,"SonyCommerce_UpgradeTrialCallback1 : err : 0x%08x\n", err); - if(err == CELL_OK) - { - const char* skuID = s_trialUpgradeProductInfoDetailed.skuId; - if(s_trialUpgradeProductInfoDetailed.purchasabilityFlag == SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF) - { - app.DebugPrintf(4,"UpgradeTrialCallback1 - DownloadAlreadyPurchased\n"); - SonyCommerce::DownloadAlreadyPurchased( UpgradeTrialCallback2, NULL, skuID); - } - else - { - app.DebugPrintf(4,"UpgradeTrialCallback1 - Checkout\n"); - SonyCommerce::Checkout( UpgradeTrialCallback2, NULL, skuID); - } - } - else - { - unsigned int uiIDA[1]; - uiIDA[0]=IDS_CONFIRM_OK; - C4JStorage::EMessageResult result = ui.RequestMessageBox( IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, uiIDA,1,ProfileManager.GetPrimaryPad()); - m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); - } +void SonyCommerce::UpgradeTrialCallback1(void* lpParam, int err) { + app.DebugPrintf(4, "SonyCommerce_UpgradeTrialCallback1 : err : 0x%08x\n", + err); + if (err == CELL_OK) { + const char* skuID = s_trialUpgradeProductInfoDetailed.skuId; + if (s_trialUpgradeProductInfoDetailed.purchasabilityFlag == + SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_OFF) { + app.DebugPrintf( + 4, "UpgradeTrialCallback1 - DownloadAlreadyPurchased\n"); + SonyCommerce::DownloadAlreadyPurchased(UpgradeTrialCallback2, NULL, + skuID); + } else { + app.DebugPrintf(4, "UpgradeTrialCallback1 - Checkout\n"); + SonyCommerce::Checkout(UpgradeTrialCallback2, NULL, skuID); + } + } else { + unsigned int uiIDA[1]; + uiIDA[0] = IDS_CONFIRM_OK; + C4JStorage::EMessageResult result = + ui.RequestMessageBox(IDS_PRO_UNLOCKGAME_TITLE, IDS_NO_DLCOFFERS, + uiIDA, 1, ProfileManager.GetPrimaryPad()); + m_trialUpgradeCallbackFunc(m_trialUpgradeCallbackParam, m_errorCode); + } } - - // global func, so we can call from the profile lib -void SonyCommerce_UpgradeTrial() -{ - // we're now calling the app function here, which manages pending requests - app.UpgradeTrial(); +void SonyCommerce_UpgradeTrial() { + // we're now calling the app function here, which manages pending requests + app.UpgradeTrial(); } -void SonyCommerce::UpgradeTrial(CallbackFunc cb, void* lpParam) -{ - m_trialUpgradeCallbackFunc = cb; - m_trialUpgradeCallbackParam = lpParam; - -// static char szTrialUpgradeSkuID[64]; -// sprintf(szTrialUpgradeSkuID, "%s-TRIALUPGRADE0001", app.GetCommerceCategory());//, szSKUSuffix); - GetDetailedProductInfo(UpgradeTrialCallback1, NULL, &s_trialUpgradeProductInfoDetailed, app.GetUpgradeKey(), app.GetCommerceCategory()); +void SonyCommerce::UpgradeTrial(CallbackFunc cb, void* lpParam) { + m_trialUpgradeCallbackFunc = cb; + m_trialUpgradeCallbackParam = lpParam; + + // static char szTrialUpgradeSkuID[64]; + // sprintf(szTrialUpgradeSkuID, "%s-TRIALUPGRADE0001", + // app.GetCommerceCategory());//, szSKUSuffix); + GetDetailedProductInfo(UpgradeTrialCallback1, NULL, + &s_trialUpgradeProductInfoDetailed, + app.GetUpgradeKey(), app.GetCommerceCategory()); } +int SonyCommerce::createContext() { + SceNpId npId; + int ret = sceNpManagerGetNpId(&npId); + if (ret < 0) { + app.DebugPrintf(4, "createContext sceNpManagerGetNpId problem\n"); + return ret; + } -int SonyCommerce::createContext() -{ - SceNpId npId; - int ret = sceNpManagerGetNpId(&npId); - if(ret < 0) - { - app.DebugPrintf(4,"createContext sceNpManagerGetNpId problem\n"); - return ret; - } + if (m_contextCreated) { + ret = sceNpCommerce2DestroyCtx(m_contextId); + if (ret < 0) { + app.DebugPrintf(4, + "createContext sceNpCommerce2DestroyCtx problem\n"); + return ret; + } + } - if (m_contextCreated) { - ret = sceNpCommerce2DestroyCtx(m_contextId); - if (ret < 0) - { - app.DebugPrintf(4,"createContext sceNpCommerce2DestroyCtx problem\n"); - return ret; - } - } + // Create commerce2 context + ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, + commerce2Handler, NULL, &m_contextId); + if (ret < 0) { + app.DebugPrintf(4, "createContext sceNpCommerce2CreateCtx problem\n"); + return ret; + } - // Create commerce2 context - ret = sceNpCommerce2CreateCtx(SCE_NP_COMMERCE2_VERSION, &npId, commerce2Handler, NULL, &m_contextId); - if (ret < 0) - { - app.DebugPrintf(4,"createContext sceNpCommerce2CreateCtx problem\n"); - return ret; - } + m_contextCreated = true; - m_contextCreated = true; - - return CELL_OK; + return CELL_OK; } -int SonyCommerce::createSession() -{ - int ret = createContext(); - if (ret < 0) { - return ret; - } +int SonyCommerce::createSession() { + int ret = createContext(); + if (ret < 0) { + return ret; + } - m_currentPhase = e_phase_creatingSessionPhase; - ret = sceNpCommerce2CreateSessionStart(m_contextId); - if (ret < 0) { - return ret; - } - return ret; + m_currentPhase = e_phase_creatingSessionPhase; + ret = sceNpCommerce2CreateSessionStart(m_contextId); + if (ret < 0) { + return ret; + } + return ret; } +void SonyCommerce::commerce2Handler(uint32_t contextId, uint32_t subjectId, + int event, int errorCode, void* arg) { + // Event reply; + // reply.service = Toolkit::NP::commerce; + // + EnterCriticalSection(&m_queueLock); -void SonyCommerce::commerce2Handler(uint32_t contextId, uint32_t subjectId, int event, int errorCode, void *arg) -{ -// Event reply; -// reply.service = Toolkit::NP::commerce; -// - EnterCriticalSection(&m_queueLock); + switch (event) { + case SCE_NP_COMMERCE2_EVENT_REQUEST_ERROR: { + m_messageQueue.push(e_message_commerceEnd); + m_errorCode = errorCode; + break; + } + case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_DONE: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceSessionCreated; + break; + } + case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_ABORT: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceSessionAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_STARTED: { + m_currentPhase = e_phase_checkoutPhase; + m_event = e_event_commerceCheckoutStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_SUCCESS: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceCheckoutSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_BACK: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceCheckoutAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_FINISHED: { + m_event = e_event_commerceCheckoutFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_STARTED: { + m_currentPhase = e_phase_downloadListPhase; + m_event = e_event_commerceDownloadListStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_SUCCESS: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceDownloadListSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_FINISHED: { + m_event = e_event_commerceDownloadListFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_STARTED: + m_currentPhase = e_phase_productBrowsePhase; + m_event = e_event_commerceProductBrowseStarted; + break; + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_SUCCESS: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceProductBrowseSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_BACK: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceProductBrowseAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_FINISHED: { + m_event = e_event_commerceProductBrowseFinished; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_OPENED: + break; + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_STARTED: { + m_currentPhase = e_phase_voucherRedeemPhase; + m_event = e_event_commerceVoucherInputStarted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_SUCCESS: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceVoucherInputSuccess; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_BACK: { + m_messageQueue.push(e_message_commerceEnd); + m_event = e_event_commerceVoucherInputAborted; + break; + } + case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_FINISHED: { + m_event = e_event_commerceVoucherInputFinished; + break; + } + default: + break; + }; - switch (event) { - case SCE_NP_COMMERCE2_EVENT_REQUEST_ERROR: - { - m_messageQueue.push(e_message_commerceEnd); - m_errorCode = errorCode; - break; - } - case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_DONE: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceSessionCreated; - break; - } - case SCE_NP_COMMERCE2_EVENT_CREATE_SESSION_ABORT: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceSessionAborted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_STARTED: - { - m_currentPhase = e_phase_checkoutPhase; - m_event = e_event_commerceCheckoutStarted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_SUCCESS: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceCheckoutSuccess; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_BACK: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceCheckoutAborted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_CHECKOUT_FINISHED: - { - m_event = e_event_commerceCheckoutFinished; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_STARTED: - { - m_currentPhase = e_phase_downloadListPhase; - m_event = e_event_commerceDownloadListStarted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_SUCCESS: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceDownloadListSuccess; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_DL_LIST_FINISHED: - { - m_event = e_event_commerceDownloadListFinished; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_STARTED: - m_currentPhase = e_phase_productBrowsePhase; - m_event = e_event_commerceProductBrowseStarted; - break; - case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_SUCCESS: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceProductBrowseSuccess; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_BACK: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceProductBrowseAborted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_FINISHED: - { - m_event = e_event_commerceProductBrowseFinished; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PROD_BROWSE_OPENED: - break; - case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_STARTED: - { - m_currentPhase = e_phase_voucherRedeemPhase; - m_event = e_event_commerceVoucherInputStarted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_SUCCESS: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceVoucherInputSuccess; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_BACK: - { - m_messageQueue.push(e_message_commerceEnd); - m_event = e_event_commerceVoucherInputAborted; - break; - } - case SCE_NP_COMMERCE2_EVENT_DO_PRODUCT_CODE_FINISHED: - { - m_event = e_event_commerceVoucherInputFinished; - break; - } - default: - break; - }; - - LeaveCriticalSection(&m_queueLock); + LeaveCriticalSection(&m_queueLock); } +void SonyCommerce::processMessage() { + EnterCriticalSection(&m_queueLock); + int ret; + if (m_messageQueue.empty()) { + LeaveCriticalSection(&m_queueLock); + return; + } + Message msg = m_messageQueue.front(); + m_messageQueue.pop(); + switch (msg) { + case e_message_commerceCreateSession: + ret = createSession(); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; -void SonyCommerce::processMessage() -{ - EnterCriticalSection(&m_queueLock); - int ret; - if(m_messageQueue.empty()) - { - LeaveCriticalSection(&m_queueLock); - return; - } - Message msg = m_messageQueue.front(); - m_messageQueue.pop(); + case e_message_commerceGetCategoryInfo: { + ret = getCategoryInfo(m_pCategoryInfo, m_pCategoryID); + if (ret < 0) { + m_event = e_event_commerceError; + app.DebugPrintf( + 4, "ERROR - e_event_commerceGotCategoryInfo - %s\n", + m_pCategoryID); + m_errorCode = ret; + } else { + m_event = e_event_commerceGotCategoryInfo; + app.DebugPrintf(4, "e_event_commerceGotCategoryInfo - %s\n", + m_pCategoryID); + } + break; + } - switch (msg) - { + case e_message_commerceGetProductList: { + ret = getProductList(m_pProductInfoList, m_pCategoryID); + if (ret < 0) { + m_event = e_event_commerceError; + } else { + m_event = e_event_commerceGotProductList; + app.DebugPrintf(4, "e_event_commerceGotProductList - %s\n", + m_pCategoryID); + } + break; + } - case e_message_commerceCreateSession: - ret = createSession(); - if (ret < 0) - { - m_event = e_event_commerceError; - m_errorCode = ret; - } - break; + case e_message_commerceGetDetailedProductInfo: { + ret = getDetailedProductInfo(m_pProductInfoDetailed, m_pProductID, + m_pCategoryID); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } else { + m_event = e_event_commerceGotDetailedProductInfo; + app.DebugPrintf(4, + "e_event_commerceGotDetailedProductInfo - %s\n", + m_pCategoryID); + } + break; + } + case e_message_commerceAddDetailedProductInfo: { + ret = addDetailedProductInfo(m_pProductInfo, m_pProductID, + m_pCategoryID); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } else { + m_event = e_event_commerceAddedDetailedProductInfo; + } + break; + } - case e_message_commerceGetCategoryInfo: - { - ret = getCategoryInfo(m_pCategoryInfo, m_pCategoryID); - if (ret < 0) - { - m_event = e_event_commerceError; - app.DebugPrintf(4,"ERROR - e_event_commerceGotCategoryInfo - %s\n",m_pCategoryID); - m_errorCode = ret; - } - else - { - m_event = e_event_commerceGotCategoryInfo; - app.DebugPrintf(4,"e_event_commerceGotCategoryInfo - %s\n",m_pCategoryID); - } - break; - } + // + // case e_message_commerceStoreProductBrowse: + // { + // ret = productBrowse(*(ProductBrowseParams + // *)msg.inputArgs); if (ret < 0) { m_event = e_event_commerceError; + // m_errorCode = ret; + // } + // _TOOLKIT_NP_DEL (ProductBrowseParams + // *)msg.inputArgs; break; + // } + // + // case e_message_commerceUpgradeTrial: + // { + // ret = upgradeTrial(); + // if (ret < 0) { + // m_event = e_event_commerceError; + // m_errorCode = ret; + // } + // break; + // } + // + // case e_message_commerceRedeemVoucher: + // { + // ret = voucherCodeInput(*(VoucherInputParams + // *)msg.inputArgs); if (ret < 0) { m_event = e_event_commerceError; + // m_errorCode = ret; + // } + // _TOOLKIT_NP_DEL (VoucherInputParams + // *)msg.inputArgs; break; + // } + // + // case e_message_commerceGetEntitlementList: + // { + // Job > + // tmpJob(static_cast > + // *>(msg.output)); + // + // int state = 0; + // int ret = sceNpManagerGetStatus(&state); + // + // // We don't want to process this if we are + // offline if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { + // m_event = e_event_commerceError; + // reply.returnCode = + // SCE_TOOLKIT_NP_OFFLINE; tmpJob.setError(SCE_TOOLKIT_NP_OFFLINE); + // } else { + // getEntitlementList(&tmpJob); + // } + // break; + // } + // + // case e_message_commerceConsumeEntitlement: + // { + // int state = 0; + // int ret = sceNpManagerGetStatus(&state); + // + // // We don't want to process this if we are + // offline if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { + // m_event = e_event_commerceError; + // reply.returnCode = + // SCE_TOOLKIT_NP_OFFLINE; } else { + // + // ret = + // consumeEntitlement(*(EntitlementToConsume *)msg.inputArgs); if + // (ret < 0) { m_event = e_event_commerceError; m_errorCode = ret; + // } else { + // m_event = + // e_event_commerceConsumedEntitlement; + // } + // } + // _TOOLKIT_NP_DEL (EntitlementToConsume + // *)msg.inputArgs; + // + // break; + // } + // + case e_message_commerceCheckout: { + ret = checkout(m_checkoutInputParams); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; + } - case e_message_commerceGetProductList: - { - ret = getProductList(m_pProductInfoList, m_pCategoryID); - if (ret < 0) - { - m_event = e_event_commerceError; - } - else - { - m_event = e_event_commerceGotProductList; - app.DebugPrintf(4,"e_event_commerceGotProductList - %s\n",m_pCategoryID); - } - break; - } + case e_message_commerceDownloadList: { + ret = downloadList(m_downloadInputParams); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + break; + } - case e_message_commerceGetDetailedProductInfo: - { - ret = getDetailedProductInfo(m_pProductInfoDetailed, m_pProductID, m_pCategoryID); - if (ret < 0) - { - m_event = e_event_commerceError; - m_errorCode = ret; - } - else - { - m_event = e_event_commerceGotDetailedProductInfo; - app.DebugPrintf(4,"e_event_commerceGotDetailedProductInfo - %s\n",m_pCategoryID); - } - break; - } - case e_message_commerceAddDetailedProductInfo: - { - ret = addDetailedProductInfo(m_pProductInfo, m_pProductID, m_pCategoryID); - if (ret < 0) - { - m_event = e_event_commerceError; - m_errorCode = ret; - } - else - { - m_event = e_event_commerceAddedDetailedProductInfo; - } - break; - } + case e_message_commerceEnd: + app.DebugPrintf("XXX - e_message_commerceEnd!\n"); + ret = commerceEnd(); + if (ret < 0) { + m_event = e_event_commerceError; + m_errorCode = ret; + } + // 4J-PB - we don't seem to handle the error code here + else if (m_errorCode != 0) { + m_event = e_event_commerceError; + } + break; -// -// case e_message_commerceStoreProductBrowse: -// { -// ret = productBrowse(*(ProductBrowseParams *)msg.inputArgs); -// if (ret < 0) { -// m_event = e_event_commerceError; -// m_errorCode = ret; -// } -// _TOOLKIT_NP_DEL (ProductBrowseParams *)msg.inputArgs; -// break; -// } -// -// case e_message_commerceUpgradeTrial: -// { -// ret = upgradeTrial(); -// if (ret < 0) { -// m_event = e_event_commerceError; -// m_errorCode = ret; -// } -// break; -// } -// -// case e_message_commerceRedeemVoucher: -// { -// ret = voucherCodeInput(*(VoucherInputParams *)msg.inputArgs); -// if (ret < 0) { -// m_event = e_event_commerceError; -// m_errorCode = ret; -// } -// _TOOLKIT_NP_DEL (VoucherInputParams *)msg.inputArgs; -// break; -// } -// -// case e_message_commerceGetEntitlementList: -// { -// Job > tmpJob(static_cast > *>(msg.output)); -// -// int state = 0; -// int ret = sceNpManagerGetStatus(&state); -// -// // We don't want to process this if we are offline -// if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { -// m_event = e_event_commerceError; -// reply.returnCode = SCE_TOOLKIT_NP_OFFLINE; -// tmpJob.setError(SCE_TOOLKIT_NP_OFFLINE); -// } else { -// getEntitlementList(&tmpJob); -// } -// break; -// } -// -// case e_message_commerceConsumeEntitlement: -// { -// int state = 0; -// int ret = sceNpManagerGetStatus(&state); -// -// // We don't want to process this if we are offline -// if (ret < 0 || state != SCE_NP_MANAGER_STATUS_ONLINE) { -// m_event = e_event_commerceError; -// reply.returnCode = SCE_TOOLKIT_NP_OFFLINE; -// } else { -// -// ret = consumeEntitlement(*(EntitlementToConsume *)msg.inputArgs); -// if (ret < 0) { -// m_event = e_event_commerceError; -// m_errorCode = ret; -// } else { -// m_event = e_event_commerceConsumedEntitlement; -// } -// } -// _TOOLKIT_NP_DEL (EntitlementToConsume *)msg.inputArgs; -// -// break; -// } -// - case e_message_commerceCheckout: - { - ret = checkout(m_checkoutInputParams); - if (ret < 0) { - m_event = e_event_commerceError; - m_errorCode = ret; - } - break; - } + default: + break; + } - case e_message_commerceDownloadList: - { - ret = downloadList(m_downloadInputParams); - if (ret < 0) { - m_event = e_event_commerceError; - m_errorCode = ret; - } - break; - } - - case e_message_commerceEnd: - app.DebugPrintf("XXX - e_message_commerceEnd!\n"); - ret = commerceEnd(); - if (ret < 0) - { - m_event = e_event_commerceError; - m_errorCode = ret; - } - // 4J-PB - we don't seem to handle the error code here - else if(m_errorCode!=0) - { - m_event = e_event_commerceError; - } - break; - - default: - break; - } - - LeaveCriticalSection(&m_queueLock); + LeaveCriticalSection(&m_queueLock); } +void SonyCommerce::processEvent() { + int ret = 0; -void SonyCommerce::processEvent() -{ - int ret = 0; + switch (m_event) { + case e_event_none: + break; + case e_event_commerceSessionCreated: + app.DebugPrintf(4, "Commerce Session Created.\n"); + runCallback(); + break; + case e_event_commerceSessionAborted: + app.DebugPrintf(4, "Commerce Session aborted.\n"); + runCallback(); + break; + case e_event_commerceGotProductList: + app.DebugPrintf(4, "Got product list.\n"); + runCallback(); + break; + case e_event_commerceGotCategoryInfo: + app.DebugPrintf(4, "Got category info\n"); + runCallback(); + break; + case e_event_commerceGotDetailedProductInfo: + app.DebugPrintf(4, "Got detailed product info.\n"); + runCallback(); + break; + case e_event_commerceAddedDetailedProductInfo: + app.DebugPrintf(4, "Added detailed product info.\n"); + runCallback(); + break; + case e_event_commerceProductBrowseStarted: + break; + case e_event_commerceProductBrowseSuccess: + break; + case e_event_commerceProductBrowseAborted: + break; + case e_event_commerceProductBrowseFinished: + assert(0); + // ret = sys_memory_container_destroy(s_memContainer); + // if (ret < 0) { + // printf("Failed to destroy memory container"); + // } + // s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + break; + case e_event_commerceVoucherInputStarted: + break; + case e_event_commerceVoucherInputSuccess: + break; + case e_event_commerceVoucherInputAborted: + break; + case e_event_commerceVoucherInputFinished: + assert(0); + // ret = sys_memory_container_destroy(s_memContainer); + // if (ret < 0) { + // printf("Failed to destroy memory container"); + // } + // s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + break; + case e_event_commerceGotEntitlementList: + break; + case e_event_commerceConsumedEntitlement: + break; + case e_event_commerceCheckoutStarted: + app.DebugPrintf(4, "Checkout Started\n"); + break; + case e_event_commerceCheckoutSuccess: + app.DebugPrintf(4, "Checkout succeeded: 0x%x\n", m_errorCode); + // clear the DLC installed and check again + app.ClearDLCInstalled(); + ui.HandleDLCInstalled(0); + break; + case e_event_commerceCheckoutAborted: + app.DebugPrintf(4, "Checkout aborted: 0x%x\n", m_errorCode); + break; + case e_event_commerceCheckoutFinished: + app.DebugPrintf(4, "Checkout Finished: 0x%x\n", m_errorCode); + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4, "Failed to destroy memory container"); + } - switch (m_event) - { - case e_event_none: - break; - case e_event_commerceSessionCreated: - app.DebugPrintf(4,"Commerce Session Created.\n"); - runCallback(); - break; - case e_event_commerceSessionAborted: - app.DebugPrintf(4,"Commerce Session aborted.\n"); - runCallback(); - break; - case e_event_commerceGotProductList: - app.DebugPrintf(4,"Got product list.\n"); - runCallback(); - break; - case e_event_commerceGotCategoryInfo: - app.DebugPrintf(4,"Got category info\n"); - runCallback(); - break; - case e_event_commerceGotDetailedProductInfo: - app.DebugPrintf(4,"Got detailed product info.\n"); - runCallback(); - break; - case e_event_commerceAddedDetailedProductInfo: - app.DebugPrintf(4,"Added detailed product info.\n"); - runCallback(); - break; - case e_event_commerceProductBrowseStarted: - break; - case e_event_commerceProductBrowseSuccess: - break; - case e_event_commerceProductBrowseAborted: - break; - case e_event_commerceProductBrowseFinished: - assert(0); -// ret = sys_memory_container_destroy(s_memContainer); -// if (ret < 0) { -// printf("Failed to destroy memory container"); -// } -// s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; - break; - case e_event_commerceVoucherInputStarted: - break; - case e_event_commerceVoucherInputSuccess: - break; - case e_event_commerceVoucherInputAborted: - break; - case e_event_commerceVoucherInputFinished: - assert(0); -// ret = sys_memory_container_destroy(s_memContainer); -// if (ret < 0) { -// printf("Failed to destroy memory container"); -// } -// s_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; - break; - case e_event_commerceGotEntitlementList: - break; - case e_event_commerceConsumedEntitlement: - break; - case e_event_commerceCheckoutStarted: - app.DebugPrintf(4,"Checkout Started\n"); - break; - case e_event_commerceCheckoutSuccess: - app.DebugPrintf(4,"Checkout succeeded: 0x%x\n", m_errorCode); - // clear the DLC installed and check again - app.ClearDLCInstalled(); - ui.HandleDLCInstalled(0); - break; - case e_event_commerceCheckoutAborted: - app.DebugPrintf(4,"Checkout aborted: 0x%x\n", m_errorCode); - break; - case e_event_commerceCheckoutFinished: - app.DebugPrintf(4,"Checkout Finished: 0x%x\n", m_errorCode); - ret = sys_memory_container_destroy(m_memContainer); - if (ret < 0) { - app.DebugPrintf(4,"Failed to destroy memory container"); - } + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + // 4J-PB - if there's been an error - like dlc already purchased, + // the runcallback has already happened, and will crash this time + if (m_callbackFunc != NULL) { + runCallback(); + } + break; + case e_event_commerceDownloadListStarted: + app.DebugPrintf(4, "Download List Started\n"); + break; + case e_event_commerceDownloadListSuccess: + app.DebugPrintf(4, "Download succeeded: 0x%x\n", m_errorCode); + break; + case e_event_commerceDownloadListFinished: + app.DebugPrintf(4, "Download Finished: 0x%x\n", m_errorCode); + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4, "Failed to destroy memory container"); + } - m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; - // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) - { - runCallback(); - } - break; - case e_event_commerceDownloadListStarted: - app.DebugPrintf(4,"Download List Started\n"); - break; - case e_event_commerceDownloadListSuccess: - app.DebugPrintf(4,"Download succeeded: 0x%x\n", m_errorCode); - break; - case e_event_commerceDownloadListFinished: - app.DebugPrintf(4,"Download Finished: 0x%x\n", m_errorCode); - ret = sys_memory_container_destroy(m_memContainer); - if (ret < 0) { - app.DebugPrintf(4,"Failed to destroy memory container"); - } + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + // 4J-PB - if there's been an error - like dlc already purchased, + // the runcallback has already happened, and will crash this time + if (m_callbackFunc != NULL) { + runCallback(); + } + break; + case e_event_commerceError: + app.DebugPrintf(4, "Commerce Error 0x%x\n", m_errorCode); - m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; - // 4J-PB - if there's been an error - like dlc already purchased, the runcallback has already happened, and will crash this time - if(m_callbackFunc!=NULL) - { - runCallback(); - } - break; - case e_event_commerceError: - app.DebugPrintf(4,"Commerce Error 0x%x\n", m_errorCode); + if (m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) { + ret = sys_memory_container_destroy(m_memContainer); + if (ret < 0) { + app.DebugPrintf(4, "Failed to destroy memory container"); + } - if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) - { - ret = sys_memory_container_destroy(m_memContainer); - if (ret < 0) { - app.DebugPrintf(4,"Failed to destroy memory container"); - } + m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; + } - m_memContainer = SYS_MEMORY_CONTAINER_ID_INVALID; - } - - runCallback(); - break; - default: - break; - } - m_event = e_event_none; + runCallback(); + break; + default: + break; + } + m_event = e_event_none; } +int SonyCommerce::commerceEnd() { + int ret = 0; -int SonyCommerce::commerceEnd() -{ - int ret = 0; + if (m_currentPhase == e_phase_voucherRedeemPhase) + ret = sceNpCommerce2DoProductCodeFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_productBrowsePhase) + ret = sceNpCommerce2DoProductBrowseFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_creatingSessionPhase) + ret = sceNpCommerce2CreateSessionFinish(m_contextId, &m_sessionInfo); + else if (m_currentPhase == e_phase_checkoutPhase) + ret = sceNpCommerce2DoCheckoutFinishAsync(m_contextId); + else if (m_currentPhase == e_phase_downloadListPhase) + ret = sceNpCommerce2DoDlListFinishAsync(m_contextId); - if (m_currentPhase == e_phase_voucherRedeemPhase) - ret = sceNpCommerce2DoProductCodeFinishAsync(m_contextId); - else if (m_currentPhase == e_phase_productBrowsePhase) - ret = sceNpCommerce2DoProductBrowseFinishAsync(m_contextId); - else if (m_currentPhase == e_phase_creatingSessionPhase) - ret = sceNpCommerce2CreateSessionFinish(m_contextId, &m_sessionInfo); - else if (m_currentPhase == e_phase_checkoutPhase) - ret = sceNpCommerce2DoCheckoutFinishAsync(m_contextId); - else if (m_currentPhase == e_phase_downloadListPhase) - ret = sceNpCommerce2DoDlListFinishAsync(m_contextId); - - m_currentPhase = e_phase_idle; + m_currentPhase = e_phase_idle; - return ret; + return ret; } -void SonyCommerce::CreateSession( CallbackFunc cb, void* lpParam ) -{ - Init(); - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - m_messageQueue.push(e_message_commerceCreateSession); - if(m_tickThread == NULL) - m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce tick"); - if(m_tickThread->isRunning() == false) - { - m_currentPhase = e_phase_idle; - m_tickThread->Run(); - } - LeaveCriticalSection(&m_queueLock); +void SonyCommerce::CreateSession(CallbackFunc cb, void* lpParam) { + Init(); + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + m_messageQueue.push(e_message_commerceCreateSession); + if (m_tickThread == NULL) + m_tickThread = new C4JThread(TickLoop, NULL, "SonyCommerce tick"); + if (m_tickThread->isRunning() == false) { + m_currentPhase = e_phase_idle; + m_tickThread->Run(); + } + LeaveCriticalSection(&m_queueLock); } -void SonyCommerce::CloseSession() -{ - assert(m_currentPhase == e_phase_idle); - m_currentPhase = e_phase_stopped; - Shutdown(); +void SonyCommerce::CloseSession() { + assert(m_currentPhase == e_phase_idle); + m_currentPhase = e_phase_stopped; + Shutdown(); } -void SonyCommerce::GetProductList( CallbackFunc cb, void* lpParam, std::vector* productList, const char *categoryId) -{ - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - m_pProductInfoList = productList; - strcpy(m_pCategoryID,categoryId); - m_messageQueue.push(e_message_commerceGetProductList); - LeaveCriticalSection(&m_queueLock); +void SonyCommerce::GetProductList(CallbackFunc cb, void* lpParam, + std::vector* productList, + const char* categoryId) { + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + m_pProductInfoList = productList; + strcpy(m_pCategoryID, categoryId); + m_messageQueue.push(e_message_commerceGetProductList); + LeaveCriticalSection(&m_queueLock); } -void SonyCommerce::GetDetailedProductInfo( CallbackFunc cb, void* lpParam, ProductInfoDetailed* productInfo, const char *productId, const char *categoryId ) -{ - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - m_pProductInfoDetailed = productInfo; - m_pProductID = productId; - strcpy(m_pCategoryID,categoryId); - m_messageQueue.push(e_message_commerceGetDetailedProductInfo); - LeaveCriticalSection(&m_queueLock); +void SonyCommerce::GetDetailedProductInfo(CallbackFunc cb, void* lpParam, + ProductInfoDetailed* productInfo, + const char* productId, + const char* categoryId) { + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + m_pProductInfoDetailed = productInfo; + m_pProductID = productId; + strcpy(m_pCategoryID, categoryId); + m_messageQueue.push(e_message_commerceGetDetailedProductInfo); + LeaveCriticalSection(&m_queueLock); } // 4J-PB - fill out the long description and the price for the product -void SonyCommerce::AddDetailedProductInfo( CallbackFunc cb, void* lpParam, ProductInfo* productInfo, const char *productId, const char *categoryId ) -{ - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - m_pProductInfo = productInfo; - m_pProductID = productId; - strcpy(m_pCategoryID,categoryId); - m_messageQueue.push(e_message_commerceAddDetailedProductInfo); - LeaveCriticalSection(&m_queueLock); +void SonyCommerce::AddDetailedProductInfo(CallbackFunc cb, void* lpParam, + ProductInfo* productInfo, + const char* productId, + const char* categoryId) { + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + m_pProductInfo = productInfo; + m_pProductID = productId; + strcpy(m_pCategoryID, categoryId); + m_messageQueue.push(e_message_commerceAddDetailedProductInfo); + LeaveCriticalSection(&m_queueLock); } -void SonyCommerce::GetCategoryInfo( CallbackFunc cb, void* lpParam, CategoryInfo *info, const char *categoryId ) -{ - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - m_pCategoryInfo = info; - strcpy(m_pCategoryID,categoryId); - m_messageQueue.push(e_message_commerceGetCategoryInfo); - LeaveCriticalSection(&m_queueLock); +void SonyCommerce::GetCategoryInfo(CallbackFunc cb, void* lpParam, + CategoryInfo* info, const char* categoryId) { + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + m_pCategoryInfo = info; + strcpy(m_pCategoryID, categoryId); + m_messageQueue.push(e_message_commerceGetCategoryInfo); + LeaveCriticalSection(&m_queueLock); } -void SonyCommerce::Checkout( CallbackFunc cb, void* lpParam, const char* skuID ) -{ - if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) - { - return; - } - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - int ret = sys_memory_container_create(&m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); - if (ret < 0) - { - app.DebugPrintf(4,"sys_memory_container_create() failed. ret = 0x%x\n", ret); - } +void SonyCommerce::Checkout(CallbackFunc cb, void* lpParam, const char* skuID) { + if (m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) { + return; + } + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + int ret = sys_memory_container_create( + &m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); + if (ret < 0) { + app.DebugPrintf(4, "sys_memory_container_create() failed. ret = 0x%x\n", + ret); + } - m_checkoutInputParams.memContainer = &m_memContainer; - m_checkoutInputParams.skuIds.clear(); - m_checkoutInputParams.skuIds.push_back(skuID); - m_messageQueue.push(e_message_commerceCheckout); - LeaveCriticalSection(&m_queueLock); + m_checkoutInputParams.memContainer = &m_memContainer; + m_checkoutInputParams.skuIds.clear(); + m_checkoutInputParams.skuIds.push_back(skuID); + m_messageQueue.push(e_message_commerceCheckout); + LeaveCriticalSection(&m_queueLock); } -void SonyCommerce::DownloadAlreadyPurchased( CallbackFunc cb, void* lpParam, const char* skuID ) -{ - if(m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) - return; - EnterCriticalSection(&m_queueLock); - setCallback(cb,lpParam); - int ret = sys_memory_container_create(&m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); - if (ret < 0) - { - app.DebugPrintf(4,"sys_memory_container_create() failed. ret = 0x%x\n", ret); - } +void SonyCommerce::DownloadAlreadyPurchased(CallbackFunc cb, void* lpParam, + const char* skuID) { + if (m_memContainer != SYS_MEMORY_CONTAINER_ID_INVALID) return; + EnterCriticalSection(&m_queueLock); + setCallback(cb, lpParam); + int ret = sys_memory_container_create( + &m_memContainer, SCE_NP_COMMERCE2_DO_CHECKOUT_MEMORY_CONTAINER_SIZE); + if (ret < 0) { + app.DebugPrintf(4, "sys_memory_container_create() failed. ret = 0x%x\n", + ret); + } - m_downloadInputParams.memContainer = &m_memContainer; - m_downloadInputParams.skuIds.clear(); - m_downloadInputParams.skuIds.push_back(skuID); - m_messageQueue.push(e_message_commerceDownloadList); - LeaveCriticalSection(&m_queueLock); + m_downloadInputParams.memContainer = &m_memContainer; + m_downloadInputParams.skuIds.clear(); + m_downloadInputParams.skuIds.push_back(skuID); + m_messageQueue.push(e_message_commerceDownloadList); + LeaveCriticalSection(&m_queueLock); } - - diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.h b/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.h index 8b0e2e4dd..fa92357e4 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyCommerce.h @@ -10,164 +10,257 @@ #elif defined __PSVITA__ #include #include -#else // __ORBIS__ +#else // __ORBIS__ -#define SCE_NP_COMMERCE2_CATEGORY_ID_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_ID_LEN ///< The size of the category ID. -#define SCE_NP_COMMERCE2_PRODUCT_ID_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_ID_LEN ///< The size of the product ID. -#define SCE_NP_COMMERCE2_CATEGORY_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_NAME_LEN ///< The size of the category name. -#define SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_CATEGORY_DESCRIPTION_LEN ///< The size of the category description. -#define SCE_NP_COMMERCE2_URL_LEN SCE_TOOLKIT_NP_COMMERCE_URL_LEN ///< The size of the URL. -#define SCE_NP_COMMERCE2_PRODUCT_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_NAME_LEN ///< The size of the product name. -#define SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_SHORT_DESCRIPTION_LEN ///< The size of the product short description. -#define SCE_NP_COMMERCE2_SP_NAME_LEN SCE_TOOLKIT_NP_COMMERCE_SP_NAME_LEN ///< The size of the licensee (publisher) name. -#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN ///< The size of currency code. -#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN -#define SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN SCE_TOOLKIT_NP_COMMERCE_CURRENCY_SYMBOL_LEN ///< The size of currency symbol. -#define SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN SCE_TOOLKIT_NP_COMMERCE_THOUSAND_SEPARATOR_LEN ///< The size of the character separating every 3 digits of the price. -#define SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN SCE_TOOLKIT_NP_COMMERCE_DECIMAL_LETTER_LEN ///< The size of the character indicating the decimal point in the price. -#define SCE_NP_COMMERCE2_SKU_ID_LEN SCE_TOOLKIT_NP_COMMERCE_SKU_ID_LEN ///< The size of the SKU ID. -#define SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LONG_DESCRIPTION_LEN ///< The size of the product long description. -#define SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LEGAL_DESCRIPTION_LEN ///< The size of the product legal description. -#define SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN SCE_TOOLKIT_NP_COMMERCE_RATING_SYSTEM_ID_LEN ///< The size of the rating system ID. -#define SCE_NP_ENTITLEMENT_ID_SIZE SCE_TOOLKIT_NP_COMMERCE_ENTITLEMENT_ID_LEN ///< The size of entitlement ID. +#define SCE_NP_COMMERCE2_CATEGORY_ID_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CATEGORY_ID_LEN ///< The size of the category ID. +#define SCE_NP_COMMERCE2_PRODUCT_ID_LEN \ + SCE_TOOLKIT_NP_COMMERCE_PRODUCT_ID_LEN ///< The size of the product ID. +#define SCE_NP_COMMERCE2_CATEGORY_NAME_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CATEGORY_NAME_LEN ///< The size of the category + ///< name. +#define SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CATEGORY_DESCRIPTION_LEN ///< The size of the + ///< category description. +#define SCE_NP_COMMERCE2_URL_LEN \ + SCE_TOOLKIT_NP_COMMERCE_URL_LEN ///< The size of the URL. +#define SCE_NP_COMMERCE2_PRODUCT_NAME_LEN \ + SCE_TOOLKIT_NP_COMMERCE_PRODUCT_NAME_LEN ///< The size of the product name. +#define SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN \ + SCE_TOOLKIT_NP_COMMERCE_PRODUCT_SHORT_DESCRIPTION_LEN ///< The size of the + ///< product short + ///< description. +#define SCE_NP_COMMERCE2_SP_NAME_LEN \ + SCE_TOOLKIT_NP_COMMERCE_SP_NAME_LEN ///< The size of the licensee + ///< (publisher) name. +#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN ///< The size of currency code. +#define SCE_NP_COMMERCE2_CURRENCY_CODE_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CURRENCY_CODE_LEN +#define SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN \ + SCE_TOOLKIT_NP_COMMERCE_CURRENCY_SYMBOL_LEN ///< The size of currency + ///< symbol. +#define SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN \ + SCE_TOOLKIT_NP_COMMERCE_THOUSAND_SEPARATOR_LEN ///< The size of the + ///< character separating + ///< every 3 digits of the + ///< price. +#define SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN \ + SCE_TOOLKIT_NP_COMMERCE_DECIMAL_LETTER_LEN ///< The size of the character + ///< indicating the decimal + ///< point in the price. +#define SCE_NP_COMMERCE2_SKU_ID_LEN \ + SCE_TOOLKIT_NP_COMMERCE_SKU_ID_LEN ///< The size of the SKU ID. +#define SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN \ + SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LONG_DESCRIPTION_LEN ///< The size of the + ///< product long + ///< description. +#define SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN \ + SCE_TOOLKIT_NP_COMMERCE_PRODUCT_LEGAL_DESCRIPTION_LEN ///< The size of the + ///< product legal + ///< description. +#define SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN \ + SCE_TOOLKIT_NP_COMMERCE_RATING_SYSTEM_ID_LEN ///< The size of the rating + ///< system ID. +#define SCE_NP_ENTITLEMENT_ID_SIZE \ + SCE_TOOLKIT_NP_COMMERCE_ENTITLEMENT_ID_LEN ///< The size of entitlement ID. #endif #ifndef __PSVITA__ -#define SCE_TOOLKIT_NP_SKU_PRICE_LEN (SCE_NP_COMMERCE2_CURRENCY_CODE_LEN \ - + SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN \ - + SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN \ - + SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN) ///< The maximum length of a price in characters. +#define SCE_TOOLKIT_NP_SKU_PRICE_LEN \ + (SCE_NP_COMMERCE2_CURRENCY_CODE_LEN + \ + SCE_NP_COMMERCE2_CURRENCY_SYMBOL_LEN + \ + SCE_NP_COMMERCE2_THOUSAND_SEPARATOR_LEN + \ + SCE_NP_COMMERCE2_DECIMAL_LETTER_LEN) ///< The maximum length of a price in + ///< characters. #endif -class SonyCommerce -{ - +class SonyCommerce { public: - typedef void (*CallbackFunc)(void* lpParam, int error_code); + typedef void (*CallbackFunc)(void* lpParam, int error_code); + /// @brief + /// Contains information about a subcategory on the PlayStation(R)Store. + /// + /// Contains information about a subcategory on the PlayStation(R)Store. + typedef struct CategoryInfoSub { + char categoryId[SCE_NP_COMMERCE2_CATEGORY_ID_LEN]; ///< The ID of the + ///< subcategory. + char + categoryName[SCE_NP_COMMERCE2_CATEGORY_NAME_LEN]; ///< The name of + ///< the + ///< subcategory. + char categoryDescription + [SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN]; ///< The detailed + ///< description of + ///< the subcategory. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The image URL of the + ///< subcategory. + } CategoryInfoSub; - /// @brief - /// Contains information about a subcategory on the PlayStation(R)Store. - /// - /// Contains information about a subcategory on the PlayStation(R)Store. - typedef struct CategoryInfoSub - { - char categoryId[SCE_NP_COMMERCE2_CATEGORY_ID_LEN]; ///< The ID of the subcategory. - char categoryName[SCE_NP_COMMERCE2_CATEGORY_NAME_LEN]; ///< The name of the subcategory. - char categoryDescription[SCE_NP_COMMERCE2_CATEGORY_DESCRIPTION_LEN]; ///< The detailed description of the subcategory. - char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The image URL of the subcategory. - } - CategoryInfoSub; + /// @brief + /// Current category information + /// + /// This structure contains information about a category on the + /// PlayStation(R)Store + typedef struct CategoryInfo { + CategoryInfoSub current; ///< The currently selected subcategory. + std::list + subCategories; ///< Information about the subcategories in this + ///< category. + uint32_t countOfProducts; ///< The number of products in the category. + uint32_t countOfSubCategories; ///< The number of subcategories. + } CategoryInfo; - /// @brief - /// Current category information - /// - /// This structure contains information about a category on the PlayStation(R)Store - typedef struct CategoryInfo - { - CategoryInfoSub current; ///< The currently selected subcategory. - std::list subCategories; ///< Information about the subcategories in this category. - uint32_t countOfProducts; ///< The number of products in the category. - uint32_t countOfSubCategories; ///< The number of subcategories. - } - CategoryInfo; - - /// Contains information about a product in the PlayStation(R)Store. - typedef struct ProductInfo - { - uint32_t purchasabilityFlag; ///< A flag that indicates whether the product can be purchased (SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX). - uint32_t annotation; // SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CANNOT_PURCHASE_AGAIN or SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CAN_PURCHASE_AGAIN - uint32_t ui32Price; - char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. - char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of the product. - char shortDescription[SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short description of the product. - char longDescription[SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long description of the product. - char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID - char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider name. - char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. - char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the product. This is formatted to include the currency code. - char padding[6]; ///< Padding. + /// Contains information about a product in the PlayStation(R)Store. + typedef struct ProductInfo { + uint32_t + purchasabilityFlag; ///< A flag that indicates whether the product + ///< can be purchased + ///< (SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX). + uint32_t + annotation; // SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CANNOT_PURCHASE_AGAIN + // or + // SCE_NP_COMMERCE2_SKU_ANN_PURCHASED_CAN_PURCHASE_AGAIN + uint32_t ui32Price; + char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. + char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of + ///< the product. + char shortDescription + [SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short + ///< description + ///< of the + ///< product. + char longDescription + [SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long + ///< description + ///< of the + ///< product. + char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID + char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider + ///< name. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. + char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the + ///< product. This is + ///< formatted to include the + ///< currency code. + char padding[6]; ///< Padding. #ifdef __PS3__ - CellRtcTick releaseDate; ///< The product release date. + CellRtcTick releaseDate; ///< The product release date. #else - SceRtcTick releaseDate; + SceRtcTick releaseDate; #endif - } - ProductInfo; + } ProductInfo; - /// @brief - /// Contains detailed information about a product on the PlayStation(R)Store. - /// - /// Contains detailed information about a product on the PlayStation(R)Store. - typedef struct ProductInfoDetailed - { - uint32_t purchasabilityFlag; ///< A flag that indicates whether the product can be purchased (SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX). - uint32_t ui32Price; - char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID - char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. - char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of the product. - char shortDescription[SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short description of the product. - char longDescription[SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long description of the product. - char legalDescription[SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN]; ///< The legal description for the product. - char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider name. - char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. - char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the product. This is formatted to include the currency code. - char ratingSystemId[SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN]; ///< The ID of the rating system (for example: PEGI, ESRB). - char ratingImageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The URL of the rating icon. - char padding[2]; ///< Padding. + /// @brief + /// Contains detailed information about a product on the + /// PlayStation(R)Store. + /// + /// Contains detailed information about a product on the + /// PlayStation(R)Store. + typedef struct ProductInfoDetailed { + uint32_t + purchasabilityFlag; ///< A flag that indicates whether the product + ///< can be purchased + ///< (SCE_NP_COMMERCE2_SKU_PURCHASABILITY_FLAG_XXX). + uint32_t ui32Price; + char skuId[SCE_NP_COMMERCE2_SKU_ID_LEN]; ///< The SKU ID + char productId[SCE_NP_COMMERCE2_PRODUCT_ID_LEN]; ///< The product ID. + char productName[SCE_NP_COMMERCE2_PRODUCT_NAME_LEN]; ///< The name of + ///< the product. + char shortDescription + [SCE_NP_COMMERCE2_PRODUCT_SHORT_DESCRIPTION_LEN]; ///< A short + ///< description + ///< of the + ///< product. + char longDescription + [SCE_NP_COMMERCE2_PRODUCT_LONG_DESCRIPTION_LEN]; ///< A long + ///< description + ///< of the + ///< product. + char legalDescription + [SCE_NP_COMMERCE2_PRODUCT_LEGAL_DESCRIPTION_LEN]; ///< The legal + ///< description + ///< for the + ///< product. + char spName[SCE_NP_COMMERCE2_SP_NAME_LEN]; ///< The service provider + ///< name. + char imageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The product image URL. + char price[SCE_TOOLKIT_NP_SKU_PRICE_LEN]; ///< The price of the + ///< product. This is + ///< formatted to include the + ///< currency code. + char ratingSystemId + [SCE_NP_COMMERCE2_RATING_SYSTEM_ID_LEN]; ///< The ID of the rating + ///< system (for example: + ///< PEGI, ESRB). + char ratingImageUrl[SCE_NP_COMMERCE2_URL_LEN]; ///< The URL of the + ///< rating icon. + char padding[2]; ///< Padding. #ifdef __PS3__ - std::list ratingDescriptors; ///< The list of rating descriptors. - CellRtcTick releaseDate; ///< The product release date. -#else - SceRtcTick releaseDate; ///< The product release date. + std::list + ratingDescriptors; ///< The list of rating descriptors. + CellRtcTick releaseDate; ///< The product release date. +#else + SceRtcTick releaseDate; ///< The product release date. #endif - } - ProductInfoDetailed; + } ProductInfoDetailed; - /// @brief - /// Checkout parameters - /// - /// This structure contains list of SKUs to checkout to and a memory container - typedef struct CheckoutInputParams - { - std::list skuIds; ///< List of SKU IDs + /// @brief + /// Checkout parameters + /// + /// This structure contains list of SKUs to checkout to and a memory + /// container + typedef struct CheckoutInputParams { + std::list skuIds; ///< List of SKU IDs #ifdef __PS3__ - sys_memory_container_t *memContainer; ///< Memory container for checkout overlay + sys_memory_container_t* + memContainer; ///< Memory container for checkout overlay #endif - } - CheckoutInputParams; + } CheckoutInputParams; - /// @brief - /// Contains download list parameters. - /// - /// Contains download list parameters. - typedef struct DownloadListInputParams - { - std::list skuIds; ///< The list of SKU IDs + /// @brief + /// Contains download list parameters. + /// + /// Contains download list parameters. + typedef struct DownloadListInputParams { + std::list skuIds; ///< The list of SKU IDs #ifdef __PS3__ - sys_memory_container_t *memContainer; ///< A memory container for checkout overlay. + sys_memory_container_t* + memContainer; ///< A memory container for checkout overlay. #endif - const char* categoryID; - } - DownloadListInputParams; - + const char* categoryID; + } DownloadListInputParams; public: - virtual void CreateSession(CallbackFunc cb, void* lpParam) = 0; - virtual void CloseSession() = 0; + virtual void CreateSession(CallbackFunc cb, void* lpParam) = 0; + virtual void CloseSession() = 0; - virtual void GetCategoryInfo(CallbackFunc cb, void* lpParam, CategoryInfo *info, const char *categoryId) = 0; - virtual void GetProductList(CallbackFunc cb, void* lpParam, std::vector* productList, const char *categoryId) = 0; - virtual void GetDetailedProductInfo(CallbackFunc cb, void* lpParam, ProductInfoDetailed* productInfoDetailed, const char *productId, const char *categoryId) = 0; - virtual void AddDetailedProductInfo( CallbackFunc cb, void* lpParam, ProductInfo* productInfo, const char *productId, const char *categoryId ) = 0; - virtual void Checkout(CallbackFunc cb, void* lpParam, const char* skuID) = 0; - virtual void DownloadAlreadyPurchased(CallbackFunc cb, void* lpParam, const char* skuID) = 0; -#if defined(__ORBIS__) || defined( __PSVITA__) - virtual void Checkout_Game(CallbackFunc cb, void* lpParam, const char* skuID) = 0; - virtual void DownloadAlreadyPurchased_Game(CallbackFunc cb, void* lpParam, const char* skuID) = 0; + virtual void GetCategoryInfo(CallbackFunc cb, void* lpParam, + CategoryInfo* info, + const char* categoryId) = 0; + virtual void GetProductList(CallbackFunc cb, void* lpParam, + std::vector* productList, + const char* categoryId) = 0; + virtual void GetDetailedProductInfo( + CallbackFunc cb, void* lpParam, + ProductInfoDetailed* productInfoDetailed, const char* productId, + const char* categoryId) = 0; + virtual void AddDetailedProductInfo(CallbackFunc cb, void* lpParam, + ProductInfo* productInfo, + const char* productId, + const char* categoryId) = 0; + virtual void Checkout(CallbackFunc cb, void* lpParam, + const char* skuID) = 0; + virtual void DownloadAlreadyPurchased(CallbackFunc cb, void* lpParam, + const char* skuID) = 0; +#if defined(__ORBIS__) || defined(__PSVITA__) + virtual void Checkout_Game(CallbackFunc cb, void* lpParam, + const char* skuID) = 0; + virtual void DownloadAlreadyPurchased_Game(CallbackFunc cb, void* lpParam, + const char* skuID) = 0; #endif - virtual void UpgradeTrial(CallbackFunc cb, void* lpParam) = 0; - virtual void CheckForTrialUpgradeKey() = 0; - virtual bool LicenseChecked() = 0; - + virtual void UpgradeTrial(CallbackFunc cb, void* lpParam) = 0; + virtual void CheckForTrialUpgradeKey() = 0; + virtual bool LicenseChecked() = 0; }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.cpp b/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.cpp index 9b745a274..78a9a0d3c 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.cpp @@ -1,7 +1,6 @@ #include "../../../Minecraft.World/Platform/stdafx.h" #include "SonyHttp.h" - #ifdef __PS3__ #include "../../../../Platform/PS3/Network/SonyHttp_PS3.h" SonyHttp_PS3 g_SonyHttp; @@ -16,19 +15,11 @@ SonyHttp_Vita g_SonyHttp; #endif +bool SonyHttp::init() { return g_SonyHttp.init(); } +void SonyHttp::shutdown() { g_SonyHttp.shutdown(); } -bool SonyHttp::init() -{ - return g_SonyHttp.init(); -} - -void SonyHttp::shutdown() -{ - g_SonyHttp.shutdown(); -} - -bool SonyHttp::getDataFromURL(const char* szURL, void** ppOutData, int* pDataSize) -{ - return g_SonyHttp.getDataFromURL(szURL, ppOutData, pDataSize); +bool SonyHttp::getDataFromURL(const char* szURL, void** ppOutData, + int* pDataSize) { + return g_SonyHttp.getDataFromURL(szURL, ppOutData, pDataSize); } diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.h b/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.h index 3fa526b0c..e3595bc0c 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyHttp.h @@ -1,11 +1,9 @@ #pragma once - - -class SonyHttp -{ +class SonyHttp { public: - static bool init(); - static void shutdown(); - static bool getDataFromURL(const char* szURL, void** ppOutData, int* pDataSize); + static bool init(); + static void shutdown(); + static bool getDataFromURL(const char* szURL, void** ppOutData, + int* pDataSize); }; \ No newline at end of file diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.cpp b/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.cpp index db885e5ea..132c17034 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.cpp +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.cpp @@ -3,7 +3,6 @@ #include "../../../Minecraft.World/Platform/stdafx.h" #include "SonyRemoteStorage.h" - static const char sc_remoteSaveFilename[] = "/minecraft_save/gamedata.rs"; #ifdef __PSVITA__ static const char sc_localSaveFilename[] = "CloudSave_Vita.bin"; @@ -18,323 +17,278 @@ static const char sc_localSaveFullPath[] = "/app0/CloudSave_Orbis.bin"; static SceRemoteStorageStatus statParams; - - - -// void remoteStorageGetCallback(void* lpParam, SonyRemoteStorage::Status s, int error_code) +// void remoteStorageGetCallback(void* lpParam, SonyRemoteStorage::Status s, int +// error_code) // { // app.DebugPrintf("remoteStorageGetCallback err : 0x%08x\n"); // } -// -// void remoteStorageCallback(void* lpParam, SonyRemoteStorage::Status s, int error_code) +// +// void remoteStorageCallback(void* lpParam, SonyRemoteStorage::Status s, int +// error_code) // { // app.DebugPrintf("remoteStorageCallback err : 0x%08x\n"); -// -// app.getRemoteStorage()->getRemoteFileInfo(&statParams, remoteStorageGetInfoCallback, NULL); +// +// app.getRemoteStorage()->getRemoteFileInfo(&statParams, +// remoteStorageGetInfoCallback, NULL); // } - - - - - - - -void getSaveInfoReturnCallback(void* lpParam, SonyRemoteStorage::Status s, int error_code) -{ - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; - app.DebugPrintf("remoteStorageGetInfoCallback err : 0x%08x\n", error_code); - if(error_code == 0) - { - for(int i=0;im_getInfoStatus = SonyRemoteStorage::e_infoFound; - pRemoteStorage->m_remoteFileInfo = &statParams.data[i]; - } - } - } - if(pRemoteStorage->m_getInfoStatus != SonyRemoteStorage::e_infoFound) - pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; +void getSaveInfoReturnCallback(void* lpParam, SonyRemoteStorage::Status s, + int error_code) { + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + app.DebugPrintf("remoteStorageGetInfoCallback err : 0x%08x\n", error_code); + if (error_code == 0) { + for (int i = 0; i < statParams.numFiles; i++) { + if (strcmp(statParams.data[i].fileName, sc_remoteSaveFilename) == + 0) { + // found the file we need in the cloud + pRemoteStorage->m_getInfoStatus = + SonyRemoteStorage::e_infoFound; + pRemoteStorage->m_remoteFileInfo = &statParams.data[i]; + } + } + } + if (pRemoteStorage->m_getInfoStatus != SonyRemoteStorage::e_infoFound) + pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; } - - - - - -static void getSaveInfoInitCallback(void* lpParam, SonyRemoteStorage::Status s, int error_code) -{ - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; - if(error_code != 0) - { - app.DebugPrintf("getSaveInfoInitCallback err : 0x%08x\n", error_code); - pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; - } - else - { - app.DebugPrintf("getSaveInfoInitCallback calling getRemoteFileInfo\n"); - app.getRemoteStorage()->getRemoteFileInfo(&statParams, getSaveInfoReturnCallback, pRemoteStorage); - } +static void getSaveInfoInitCallback(void* lpParam, SonyRemoteStorage::Status s, + int error_code) { + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + if (error_code != 0) { + app.DebugPrintf("getSaveInfoInitCallback err : 0x%08x\n", error_code); + pRemoteStorage->m_getInfoStatus = SonyRemoteStorage::e_noInfoFound; + } else { + app.DebugPrintf("getSaveInfoInitCallback calling getRemoteFileInfo\n"); + app.getRemoteStorage()->getRemoteFileInfo( + &statParams, getSaveInfoReturnCallback, pRemoteStorage); + } } -void SonyRemoteStorage::getSaveInfo() -{ - if(m_getInfoStatus == e_gettingInfo) - { - app.DebugPrintf("SonyRemoteStorage::getSaveInfo already running!!!\n"); - return; - } +void SonyRemoteStorage::getSaveInfo() { + if (m_getInfoStatus == e_gettingInfo) { + app.DebugPrintf("SonyRemoteStorage::getSaveInfo already running!!!\n"); + return; + } - m_getInfoStatus = e_gettingInfo; - if(!ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) - { - m_getInfoStatus = e_noInfoFound; - return; - } - app.DebugPrintf("SonyRemoteStorage::getSaveInfo calling init\n"); + m_getInfoStatus = e_gettingInfo; + if (!ProfileManager.IsSignedInLive(ProfileManager.GetPrimaryPad())) { + m_getInfoStatus = e_noInfoFound; + return; + } + app.DebugPrintf("SonyRemoteStorage::getSaveInfo calling init\n"); - bool bOK = init(getSaveInfoInitCallback, this); - if(!bOK) - m_getInfoStatus = e_noInfoFound; + bool bOK = init(getSaveInfoInitCallback, this); + if (!bOK) m_getInfoStatus = e_noInfoFound; } -bool SonyRemoteStorage::getSaveData( const char* localDirname, CallbackFunc cb, void* lpParam ) -{ - m_startTime = System::currentTimeMillis(); - m_dataProgress = 0; - return getData(sc_remoteSaveFilename, localDirname, cb, lpParam); +bool SonyRemoteStorage::getSaveData(const char* localDirname, CallbackFunc cb, + void* lpParam) { + m_startTime = System::currentTimeMillis(); + m_dataProgress = 0; + return getData(sc_remoteSaveFilename, localDirname, cb, lpParam); } - -static void setSaveDataInitCallback(void* lpParam, SonyRemoteStorage::Status s, int error_code) -{ - SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; - if(error_code != 0) - { - app.DebugPrintf("setSaveDataInitCallback err : 0x%08x\n", error_code); - pRemoteStorage->m_setDataStatus = SonyRemoteStorage::e_settingDataFailed; - if(pRemoteStorage->m_initCallbackFunc) - pRemoteStorage->m_initCallbackFunc(pRemoteStorage->m_initCallbackParam, s, error_code); - } - else - { - app.getRemoteStorage()->setData(pRemoteStorage->m_setSaveDataInfo, pRemoteStorage->m_initCallbackFunc, pRemoteStorage->m_initCallbackParam); - } - +static void setSaveDataInitCallback(void* lpParam, SonyRemoteStorage::Status s, + int error_code) { + SonyRemoteStorage* pRemoteStorage = (SonyRemoteStorage*)lpParam; + if (error_code != 0) { + app.DebugPrintf("setSaveDataInitCallback err : 0x%08x\n", error_code); + pRemoteStorage->m_setDataStatus = + SonyRemoteStorage::e_settingDataFailed; + if (pRemoteStorage->m_initCallbackFunc) + pRemoteStorage->m_initCallbackFunc( + pRemoteStorage->m_initCallbackParam, s, error_code); + } else { + app.getRemoteStorage()->setData(pRemoteStorage->m_setSaveDataInfo, + pRemoteStorage->m_initCallbackFunc, + pRemoteStorage->m_initCallbackParam); + } } -bool SonyRemoteStorage::setSaveData(PSAVE_INFO info, CallbackFunc cb, void* lpParam) -{ - m_setSaveDataInfo = info; - m_setDataStatus = e_settingData; - m_initCallbackFunc = cb; - m_initCallbackParam = lpParam; - m_dataProgress = 0; - bool bOK = init(setSaveDataInitCallback, this); - if(!bOK) - m_setDataStatus = e_settingDataFailed; +bool SonyRemoteStorage::setSaveData(PSAVE_INFO info, CallbackFunc cb, + void* lpParam) { + m_setSaveDataInfo = info; + m_setDataStatus = e_settingData; + m_initCallbackFunc = cb; + m_initCallbackParam = lpParam; + m_dataProgress = 0; + bool bOK = init(setSaveDataInitCallback, this); + if (!bOK) m_setDataStatus = e_settingDataFailed; - return bOK; + return bOK; } -const char* SonyRemoteStorage::getLocalFilename() -{ - return sc_localSaveFullPath; +const char* SonyRemoteStorage::getLocalFilename() { + return sc_localSaveFullPath; } -const char* SonyRemoteStorage::getSaveNameUTF8() -{ - if(m_getInfoStatus != e_infoFound) - return NULL; - DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; - return pDescData->m_saveNameUTF8; +const char* SonyRemoteStorage::getSaveNameUTF8() { + if (m_getInfoStatus != e_infoFound) return NULL; + DescriptionData* pDescData = + (DescriptionData*)m_remoteFileInfo->fileDescription; + return pDescData->m_saveNameUTF8; } -ESavePlatform SonyRemoteStorage::getSavePlatform() -{ - if(m_getInfoStatus != e_infoFound) - return SAVE_FILE_PLATFORM_NONE; - DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; - return (ESavePlatform)MAKE_FOURCC(pDescData->m_platform[0], pDescData->m_platform[1], pDescData->m_platform[2], pDescData->m_platform[3]); - +ESavePlatform SonyRemoteStorage::getSavePlatform() { + if (m_getInfoStatus != e_infoFound) return SAVE_FILE_PLATFORM_NONE; + DescriptionData* pDescData = + (DescriptionData*)m_remoteFileInfo->fileDescription; + return (ESavePlatform)MAKE_FOURCC( + pDescData->m_platform[0], pDescData->m_platform[1], + pDescData->m_platform[2], pDescData->m_platform[3]); } -__int64 SonyRemoteStorage::getSaveSeed() -{ - if(m_getInfoStatus != e_infoFound) - return 0; - DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; +__int64 SonyRemoteStorage::getSaveSeed() { + if (m_getInfoStatus != e_infoFound) return 0; + DescriptionData* pDescData = + (DescriptionData*)m_remoteFileInfo->fileDescription; - char seedString[17]; - ZeroMemory(seedString,17); - memcpy(seedString, pDescData->m_seed,16); + char seedString[17]; + ZeroMemory(seedString, 17); + memcpy(seedString, pDescData->m_seed, 16); - __uint64 seed = 0; - std::stringstream ss; - ss << seedString; - ss >> std::hex >> seed; - return seed; + __uint64 seed = 0; + std::stringstream ss; + ss << seedString; + ss >> std::hex >> seed; + return seed; } -unsigned int SonyRemoteStorage::getSaveHostOptions() -{ - if(m_getInfoStatus != e_infoFound) - return 0; - DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; +unsigned int SonyRemoteStorage::getSaveHostOptions() { + if (m_getInfoStatus != e_infoFound) return 0; + DescriptionData* pDescData = + (DescriptionData*)m_remoteFileInfo->fileDescription; - char optionsString[9]; - ZeroMemory(optionsString,9); - memcpy(optionsString, pDescData->m_hostOptions,8); + char optionsString[9]; + ZeroMemory(optionsString, 9); + memcpy(optionsString, pDescData->m_hostOptions, 8); - unsigned int uiHostOptions = 0; - std::stringstream ss; - ss << optionsString; - ss >> std::hex >> uiHostOptions; - return uiHostOptions; + unsigned int uiHostOptions = 0; + std::stringstream ss; + ss << optionsString; + ss >> std::hex >> uiHostOptions; + return uiHostOptions; } -unsigned int SonyRemoteStorage::getSaveTexturePack() -{ - if(m_getInfoStatus != e_infoFound) - return 0; - DescriptionData* pDescData = (DescriptionData*)m_remoteFileInfo->fileDescription; +unsigned int SonyRemoteStorage::getSaveTexturePack() { + if (m_getInfoStatus != e_infoFound) return 0; + DescriptionData* pDescData = + (DescriptionData*)m_remoteFileInfo->fileDescription; - char textureString[9]; - ZeroMemory(textureString,9); - memcpy(textureString, pDescData->m_texturePack,8); + char textureString[9]; + ZeroMemory(textureString, 9); + memcpy(textureString, pDescData->m_texturePack, 8); - unsigned int uiTexturePack = 0; - std::stringstream ss; - ss << textureString; - ss >> std::hex >> uiTexturePack; - return uiTexturePack; + unsigned int uiTexturePack = 0; + std::stringstream ss; + ss << textureString; + ss >> std::hex >> uiTexturePack; + return uiTexturePack; } -const char* SonyRemoteStorage::getRemoteSaveFilename() -{ - return sc_remoteSaveFilename; +const char* SonyRemoteStorage::getRemoteSaveFilename() { + return sc_remoteSaveFilename; } -int SonyRemoteStorage::getSaveFilesize() -{ - if(m_getInfoStatus == e_infoFound) - { - return m_remoteFileInfo->fileSize; - } - return 0; +int SonyRemoteStorage::getSaveFilesize() { + if (m_getInfoStatus == e_infoFound) { + return m_remoteFileInfo->fileSize; + } + return 0; } +bool SonyRemoteStorage::setData(PSAVE_INFO info, CallbackFunc cb, + void* lpParam) { + m_setDataSaveInfo = info; + m_callbackFunc = cb; + m_callbackParam = lpParam; + m_status = e_setDataInProgress; -bool SonyRemoteStorage::setData( PSAVE_INFO info, CallbackFunc cb, void* lpParam ) -{ - m_setDataSaveInfo = info; - m_callbackFunc = cb; - m_callbackParam = lpParam; - m_status = e_setDataInProgress; - - C4JStorage::ESaveGameState eLoadStatus=StorageManager.LoadSaveDataThumbnail(info,&LoadSaveDataThumbnailReturned,this); - return true; + C4JStorage::ESaveGameState eLoadStatus = + StorageManager.LoadSaveDataThumbnail( + info, &LoadSaveDataThumbnailReturned, this); + return true; } -int SonyRemoteStorage::LoadSaveDataThumbnailReturned(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes) -{ - SonyRemoteStorage *pClass= (SonyRemoteStorage *)lpParam; +int SonyRemoteStorage::LoadSaveDataThumbnailReturned( + void* lpParam, std::uint8_t* thumbnailData, unsigned int thumbnailBytes) { + SonyRemoteStorage* pClass = (SonyRemoteStorage*)lpParam; - if(pClass->m_bAborting) - { - pClass->runCallback(); - return 0; - } + if (pClass->m_bAborting) { + pClass->runCallback(); + return 0; + } - app.DebugPrintf("Received data for a thumbnail\n"); + app.DebugPrintf("Received data for a thumbnail\n"); - if(thumbnailData && thumbnailBytes) - { - pClass->m_thumbnailData = thumbnailData; - pClass->m_thumbnailDataSize = thumbnailBytes; - } - else - { - app.DebugPrintf("Thumbnail data is NULL, or has size 0\n"); - pClass->m_thumbnailData = NULL; - pClass->m_thumbnailDataSize = 0; - } + if (thumbnailData && thumbnailBytes) { + pClass->m_thumbnailData = thumbnailData; + pClass->m_thumbnailDataSize = thumbnailBytes; + } else { + app.DebugPrintf("Thumbnail data is NULL, or has size 0\n"); + pClass->m_thumbnailData = NULL; + pClass->m_thumbnailDataSize = 0; + } - if(pClass->m_SetDataThread != NULL) - delete pClass->m_SetDataThread; + if (pClass->m_SetDataThread != NULL) delete pClass->m_SetDataThread; - pClass->m_SetDataThread = new C4JThread(setDataThread, pClass, "setDataThread"); - pClass->m_SetDataThread->Run(); + pClass->m_SetDataThread = + new C4JThread(setDataThread, pClass, "setDataThread"); + pClass->m_SetDataThread->Run(); - return 0; + return 0; } -int SonyRemoteStorage::setDataThread(void* lpParam) -{ - SonyRemoteStorage* pClass = (SonyRemoteStorage*)lpParam; - pClass->m_startTime = System::currentTimeMillis(); - pClass->setDataInternal(); - return 0; +int SonyRemoteStorage::setDataThread(void* lpParam) { + SonyRemoteStorage* pClass = (SonyRemoteStorage*)lpParam; + pClass->m_startTime = System::currentTimeMillis(); + pClass->setDataInternal(); + return 0; } -bool SonyRemoteStorage::saveIsAvailable() -{ - if(m_getInfoStatus != e_infoFound) - return false; +bool SonyRemoteStorage::saveIsAvailable() { + if (m_getInfoStatus != e_infoFound) return false; #ifdef __PS3__ - return (getSavePlatform() == SAVE_FILE_PLATFORM_PSVITA); + return (getSavePlatform() == SAVE_FILE_PLATFORM_PSVITA); #elif defined __PSVITA__ - return (getSavePlatform() == SAVE_FILE_PLATFORM_PS3); -#else // __ORBIS__ - return true; + return (getSavePlatform() == SAVE_FILE_PLATFORM_PS3); +#else // __ORBIS__ + return true; #endif } -int SonyRemoteStorage::getDataProgress() -{ - __int64 time = System::currentTimeMillis(); - int elapsedSecs = (time - m_startTime) / 1000; - int progVal = m_dataProgress + (elapsedSecs/3); - if(progVal > 95) - { - return m_dataProgress; - } - return progVal; +int SonyRemoteStorage::getDataProgress() { + __int64 time = System::currentTimeMillis(); + int elapsedSecs = (time - m_startTime) / 1000; + int progVal = m_dataProgress + (elapsedSecs / 3); + if (progVal > 95) { + return m_dataProgress; + } + return progVal; } - -bool SonyRemoteStorage::shutdown() -{ - if(m_bInitialised) - { - int ret = sceRemoteStorageTerm(); - if(ret >= 0) - { - app.DebugPrintf("Term request done \n"); - m_bInitialised = false; - free(m_memPoolBuffer); - m_memPoolBuffer = NULL; - return true; - } - else - { - app.DebugPrintf("Error in Term request: 0x%x \n", ret); - return false; - } - } - return true; +bool SonyRemoteStorage::shutdown() { + if (m_bInitialised) { + int ret = sceRemoteStorageTerm(); + if (ret >= 0) { + app.DebugPrintf("Term request done \n"); + m_bInitialised = false; + free(m_memPoolBuffer); + m_memPoolBuffer = NULL; + return true; + } else { + app.DebugPrintf("Error in Term request: 0x%x \n", ret); + return false; + } + } + return true; } - -void SonyRemoteStorage::waitForStorageManagerIdle() -{ - C4JStorage::ESaveGameState storageState = StorageManager.GetSaveState(); - while(storageState != C4JStorage::ESaveGame_Idle) - { - Sleep(10); -// app.DebugPrintf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>> storageState = %d\n", storageState); - storageState = StorageManager.GetSaveState(); - } +void SonyRemoteStorage::waitForStorageManagerIdle() { + C4JStorage::ESaveGameState storageState = StorageManager.GetSaveState(); + while (storageState != C4JStorage::ESaveGame_Idle) { + Sleep(10); + // app.DebugPrintf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + // >>>>> storageState = %d\n", storageState); + storageState = StorageManager.GetSaveState(); + } } diff --git a/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.h b/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.h index dccb52949..e35e58719 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/SonyRemoteStorage.h @@ -1,121 +1,114 @@ -#pragma once - +#pragma once #include "sceRemoteStorage/header/sceRemoteStorage.h" #include -class SonyRemoteStorage -{ +class SonyRemoteStorage { public: - enum Status - { - e_idle, - e_accountLinked, - e_error, - e_signInRequired, - e_compressInProgress, - e_setDataInProgress, - e_setDataSucceeded, - e_getDataInProgress, - e_getDataSucceeded, - e_getStatusInProgress, - e_getStatusSucceeded - }; - typedef void (*CallbackFunc)(void* lpParam, Status s, int error_code); + enum Status { + e_idle, + e_accountLinked, + e_error, + e_signInRequired, + e_compressInProgress, + e_setDataInProgress, + e_setDataSucceeded, + e_getDataInProgress, + e_getDataSucceeded, + e_getStatusInProgress, + e_getStatusSucceeded + }; + typedef void (*CallbackFunc)(void* lpParam, Status s, int error_code); - enum GetInfoStatus - { - e_gettingInfo, - e_infoFound, - e_noInfoFound - }; - GetInfoStatus m_getInfoStatus; + enum GetInfoStatus { e_gettingInfo, e_infoFound, e_noInfoFound }; + GetInfoStatus m_getInfoStatus; - enum SetDataStatus - { - e_settingData, - e_settingDataFailed, - e_settingDataSucceeded - }; - SetDataStatus m_setDataStatus; + enum SetDataStatus { + e_settingData, + e_settingDataFailed, + e_settingDataSucceeded + }; + SetDataStatus m_setDataStatus; - PSAVE_INFO m_setSaveDataInfo; - SceRemoteStorageData* m_remoteFileInfo; + PSAVE_INFO m_setSaveDataInfo; + SceRemoteStorageData* m_remoteFileInfo; - class DescriptionData - { - // this stuff is read from a JSON query, so it all has to be text based, max 256 bytes - public: - char m_platform[4]; - char m_seed[16]; // 8 bytes as hex - char m_hostOptions[8]; // 4 bytes as hex - char m_texturePack[8]; // 4 bytes as hex - char m_saveNameUTF8[128]; - }; + class DescriptionData { + // this stuff is read from a JSON query, so it all has to be text based, + // max 256 bytes + public: + char m_platform[4]; + char m_seed[16]; // 8 bytes as hex + char m_hostOptions[8]; // 4 bytes as hex + char m_texturePack[8]; // 4 bytes as hex + char m_saveNameUTF8[128]; + }; - CallbackFunc m_callbackFunc; - void* m_callbackParam; + CallbackFunc m_callbackFunc; + void* m_callbackParam; + CallbackFunc m_initCallbackFunc; + void* m_initCallbackParam; - CallbackFunc m_initCallbackFunc; - void* m_initCallbackParam; + void getSaveInfo(); + bool waitingForSaveInfo() { return (m_getInfoStatus == e_gettingInfo); } + bool saveIsAvailable(); - void getSaveInfo(); - bool waitingForSaveInfo() { return (m_getInfoStatus == e_gettingInfo); } - bool saveIsAvailable(); + int getSaveFilesize(); + bool getSaveData(const char* localDirname, CallbackFunc cb, void* lpParam); - int getSaveFilesize(); - bool getSaveData(const char* localDirname, CallbackFunc cb, void* lpParam); + bool setSaveData(PSAVE_INFO info, CallbackFunc cb, void* lpParam); + bool waitingForSetData() { return (m_setDataStatus == e_settingData); } - bool setSaveData(PSAVE_INFO info, CallbackFunc cb, void* lpParam); - bool waitingForSetData() { return (m_setDataStatus == e_settingData); } + const char* getLocalFilename(); + const char* getSaveNameUTF8(); + ESavePlatform getSavePlatform(); + __int64 getSaveSeed(); + unsigned int getSaveHostOptions(); + unsigned int getSaveTexturePack(); - const char* getLocalFilename(); - const char* getSaveNameUTF8(); - ESavePlatform getSavePlatform(); - __int64 getSaveSeed(); - unsigned int getSaveHostOptions(); - unsigned int getSaveTexturePack(); + void SetServiceID(char* pchServiceID) { m_pchServiceID = pchServiceID; } - void SetServiceID(char *pchServiceID) { m_pchServiceID=pchServiceID; } + virtual bool init(CallbackFunc cb, void* lpParam) = 0; + virtual bool getRemoteFileInfo(SceRemoteStorageStatus* pInfo, + CallbackFunc cb, void* lpParam) = 0; + virtual bool getData(const char* remotePath, const char* localPath, + CallbackFunc cb, void* lpParam) = 0; + virtual void abort() = 0; + virtual bool shutdown(); + virtual bool setDataInternal() = 0; + virtual void runCallback() = 0; - virtual bool init(CallbackFunc cb, void* lpParam) = 0; - virtual bool getRemoteFileInfo(SceRemoteStorageStatus* pInfo, CallbackFunc cb, void* lpParam) = 0; - virtual bool getData(const char* remotePath, const char* localPath, CallbackFunc cb, void* lpParam) = 0; - virtual void abort() = 0; - virtual bool shutdown(); - virtual bool setDataInternal() = 0; - virtual void runCallback() = 0; + Status getStatus() { return m_status; } + int getDataProgress(); + void waitForStorageManagerIdle(); + bool setData(PSAVE_INFO info, CallbackFunc cb, void* lpParam); + static int LoadSaveDataThumbnailReturned(void* lpParam, + std::uint8_t* thumbnailData, + unsigned int thumbnailBytes); + static int setDataThread(void* lpParam); - Status getStatus() { return m_status; } - int getDataProgress(); - void waitForStorageManagerIdle(); - - - - bool setData( PSAVE_INFO info, CallbackFunc cb, void* lpParam ); - static int LoadSaveDataThumbnailReturned(void *lpParam,std::uint8_t *thumbnailData,unsigned int thumbnailBytes); - static int setDataThread(void* lpParam); - - SonyRemoteStorage() : m_memPoolBuffer(NULL), m_bInitialised(false),m_getInfoStatus(e_noInfoFound) {} + SonyRemoteStorage() + : m_memPoolBuffer(NULL), + m_bInitialised(false), + m_getInfoStatus(e_noInfoFound) {} protected: - const char* getRemoteSaveFilename(); - bool m_bInitialised; - void* m_memPoolBuffer; - Status m_status; - int m_dataProgress; - char *m_pchServiceID; + const char* getRemoteSaveFilename(); + bool m_bInitialised; + void* m_memPoolBuffer; + Status m_status; + int m_dataProgress; + char* m_pchServiceID; - std::uint8_t *m_thumbnailData; - unsigned int m_thumbnailDataSize; - C4JThread* m_SetDataThread; - PSAVE_INFO m_setDataSaveInfo; - __int64 m_startTime; - - bool m_bAborting; - bool m_bTransferStarted; + std::uint8_t* m_thumbnailData; + unsigned int m_thumbnailDataSize; + C4JThread* m_SetDataThread; + PSAVE_INFO m_setDataSaveInfo; + __int64 m_startTime; + bool m_bAborting; + bool m_bTransferStarted; }; diff --git a/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h b/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h index de70398d7..c07809b9d 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorage.h @@ -7,131 +7,212 @@ /// @brief /// Initialises the RemoteStorage library. /// -/// Initialises the RemoteStorage library, creates a session on the server and starts the Thread to process requests. -/// This method must be executed to start the RemoteStorage library or none of its functionality will be available. -/// This method will block while it initializes its thread and will return an error if it is -/// unable to do so. The session will be created on the thread once this is created and it won't be a blocking operation. +/// Initialises the RemoteStorage library, creates a session on the server and +/// starts the Thread to process requests. This method must be executed to start +/// the RemoteStorage library or none of its functionality will be available. +/// This method will block while it initializes its thread and will return an +/// error if it is unable to do so. The session will be created on the thread +/// once this is created and it won't be a blocking operation. /// -/// It is important to note that HTTP, SSL and NET libraries are not being initialised by the library and should be initialised outside of it. +/// It is important to note that HTTP, SSL and NET libraries are not being +/// initialised by the library and should be initialised outside of it. /// -/// @param params The structure of type <>SceRemoteStorageInitParams that contains necessary information to start the library. +/// @param params The structure of type +/// <>SceRemoteStorageInitParams that contains necessary information to +/// start the library. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. -/// @retval SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT At least one of the arguments passed in the input structure is not valid. -/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. -/// @retval USER_ACCOUNT_LINKED This event will be sent to the event callback when the session is created and linked to PSN on the server -/// @retval PSN_SIGN_IN_REQUIRED This event will be sent to the event callback when the session is created but not linked to PSN on the server. -/// This will only happen on the PC version and requires to call sceRemoteStorageOpenWebBrowser() function. -/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT At least one of +/// the arguments passed in the input structure is not valid. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no +/// enough memory on the library to perform an allocation. +/// @retval USER_ACCOUNT_LINKED +/// This event will be sent to the event callback when the session is created +/// and linked to PSN on the server +/// @retval PSN_SIGN_IN_REQUIRED +/// This event will be sent to the event callback when the session is created +/// but not linked to PSN on the server. +/// This +///will only happen on the PC version and requires to call +///sceRemoteStorageOpenWebBrowser() function. +/// @retval ERROR_OCCURRED +/// This event will be sent to the event callback when an error has occurred in +/// the thread. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageInit(const SceRemoteStorageInitParams & params); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageInit(const SceRemoteStorageInitParams& params); /// @brief /// Terminates the RemoteStorage library. /// -/// Terminates the RemoteStorage library and deletes the thread that process requests. -/// This method must be executed to terminate the RemoteStorage library to prevent leaks in memory and resources. -/// This method will abort any other pending requests and terminate the library. It won't wait for requests to finish. -/// This method is synchronous and does not make use of the callback to inform the user of success termination. It is executed on the calling thread. +/// Terminates the RemoteStorage library and deletes the thread that process +/// requests. This method must be executed to terminate the RemoteStorage +/// library to prevent leaks in memory and resources. This method will abort any +/// other pending requests and terminate the library. It won't wait for requests +/// to finish. This method is synchronous and does not make use of the callback +/// to inform the user of success termination. It is executed on the calling +/// thread. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successful. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successful. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. /// -/// @note System errors may be returned. Design your code so it does expect other errors. +/// @note System errors may be returned. Design your code so it does expect +/// other errors. int32_t sceRemoteStorageTerm(); /// @brief /// Aborts a request sent to the RemoteStorage library. /// -/// Aborts a request being processed or pending to be processed by the RemoteStorage library. -/// This method is synchronous and does not make use of the callback to inform the user of success termination. It is executed on the calling thread. +/// Aborts a request being processed or pending to be processed by the +/// RemoteStorage library. This method is synchronous and does not make use of +/// the callback to inform the user of success termination. It is executed on +/// the calling thread. /// -/// @param param A structure containing the request Id to be aborted. -/// This request Id is provided by other functions (get/setData, getStatus and OpenWebBrowser) so they can be referenced. +/// @param param A structure containing the request Id to be aborted. +/// This request Id is provided by other +///functions (get/setData, getStatus and OpenWebBrowser) so they can be +///referenced. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successful. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. -/// @retval SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND The request Id sent is not found. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successful. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND The request Id +/// sent is not found. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageAbort(const SceRemoteStorageAbortReqParams & params); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageAbort(const SceRemoteStorageAbortReqParams& params); /// @brief /// Opens the default web browser to sign in to PSN on PC. /// -/// Opens the default web browser to sign in to PSN on PC. This function does not have any functionality on other platforms. -/// This method does make use of the callback to inform the user of success termination. This function has priority over other functions on the thread (as getData(), getStatus() -/// and setData()) and it will be executed as soon as the thread finishes processing a pending request. +/// Opens the default web browser to sign in to PSN on PC. This function does +/// not have any functionality on other platforms. This method does make use of +/// the callback to inform the user of success termination. This function has +/// priority over other functions on the thread (as getData(), getStatus() and +/// setData()) and it will be executed as soon as the thread finishes processing +/// a pending request. /// -/// @param param The structure containing extra parameters to be passed in. This structure does only exist for future expansions. +/// @param param The structure containing extra parameters to be +/// passed in. This structure does only exist for future expansions. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. -/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. -/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no +/// enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED +/// This event will be sent to the event callback when an error has occurred in +/// the thread. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageOpenWebBrowser(const SceRemoteStorageWebBrowserReqParams & params); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageOpenWebBrowser( + const SceRemoteStorageWebBrowserReqParams& params); /// @brief /// Gives details for all files of a user. /// -/// Gives details for all files of a user. It provides generic information (remaining bandwidth per day, HDD space per user, number of files) as well as -/// specific file information (number of bytes, file name, file description, MD5 checksum, timestamp and file visibility). File data is not provided. -/// This method does make use of the callback to inform the user of success termination. The SceRemoteStorageStatus pointer must be pointer a to a valid -/// location in memory until the callback is called as the output information will be stored in such location. +/// Gives details for all files of a user. It provides generic information +/// (remaining bandwidth per day, HDD space per user, number of files) as well +/// as specific file information (number of bytes, file name, file description, +/// MD5 checksum, timestamp and file visibility). File data is not provided. +/// This method does make use of the callback to inform the user of success +/// termination. The SceRemoteStorageStatus pointer must be pointer a to a valid +/// location in memory until the callback is called as the output information +/// will be stored in such location. /// -/// @param params The structure containing extra parameters to be passed in. This structure does only exist for future expansions. -/// @param status The structure where the output information will be stored. The memory location being pointed must be valid until the callback gets called. +/// @param params The structure containing extra parameters to be +/// passed in. This structure does only exist for future expansions. +/// @param status The structure where the output information will +/// be stored. The memory location being pointed must be valid until the +/// callback gets called. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. -/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. -/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no +/// enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED +/// This event will be sent to the event callback when an error has occurred in +/// the thread. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageGetStatus(const SceRemoteStorageStatusReqParams & params, SceRemoteStorageStatus * status); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageGetStatus(const SceRemoteStorageStatusReqParams& params, + SceRemoteStorageStatus* status); /// @brief /// Gets section of data from a file specified. /// -/// Gets section of data from a file specified. The amount of data requested can be of any size. To request this information the name of file, the number of bytes and -/// the byte to start reading along with a buffer to store such data must be provided. -/// Metadata information of the file, as description or visibility, will be provided only in the case the first amount of bytes for the file are requested (offset = 0). -/// This method does make use of the callback to inform the user of success termination. The SceRemoteStorageData pointer must be a pointer to a valid -/// location in memory until the callback is called as the output information will be stored in such location. +/// Gets section of data from a file specified. The amount of data requested can +/// be of any size. To request this information the name of file, the number of +/// bytes and the byte to start reading along with a buffer to store such data +/// must be provided. Metadata information of the file, as description or +/// visibility, will be provided only in the case the first amount of bytes for +/// the file are requested (offset = 0). This method does make use of the +/// callback to inform the user of success termination. The SceRemoteStorageData +/// pointer must be a pointer to a valid location in memory until the callback +/// is called as the output information will be stored in such location. /// -/// @param params The structure containing the file name to read, the start byte to start reading and the amount of bytes to read. -/// @param status The structure where the output information will be stored. The memory location being pointed must be valid until the callback gets called. +/// @param params The structure containing the file name to read, +/// the start byte to start reading and the amount of bytes to read. +/// @param status The structure where the output information will +/// be stored. The memory location being pointed must be valid until the +/// callback gets called. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. -/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. -/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no +/// enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED +/// This event will be sent to the event callback when an error has occurred in +/// the thread. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageGetData(const SceRemoteStorageGetDataReqParams & params, SceRemoteStorageData * data); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageGetData(const SceRemoteStorageGetDataReqParams& params, + SceRemoteStorageData* data); /// @brief /// Sets chunk of data to a file specified. /// -/// Sets chunk of data to a file specified. The amount of data sent must be of, at least, 5 Megabytes per chunk excepts -/// in the case of the last chunk of the file (or the only one if that is the case) as it can be smaller. -/// The information provided regarding the chunk as the chunk number, total number of chunks, data buffer and its size should be provided in every call. -/// The information provided regarding the file as its name, description and visibility should be provided in the last chunk only (this is, when -/// chunk number = number of chunks). -/// This method does make use of the callback to inform the user of success termination. The data attribute of the SceRemoteStorageSetDataReqParams pointer -/// must be a pointer to a valid location in memory until the callback is called as the buffer won't be copied internally. +/// Sets chunk of data to a file specified. The amount of data sent must be of, +/// at least, 5 Megabytes per chunk excepts in the case of the last chunk of the +/// file (or the only one if that is the case) as it can be smaller. The +/// information provided regarding the chunk as the chunk number, total number +/// of chunks, data buffer and its size should be provided in every call. The +/// information provided regarding the file as its name, description and +/// visibility should be provided in the last chunk only (this is, when chunk +/// number = number of chunks). This method does make use of the callback to +/// inform the user of success termination. The data attribute of the +/// SceRemoteStorageSetDataReqParams pointer must be a pointer to a valid +/// location in memory until the callback is called as the buffer won't be +/// copied internally. /// /// @param data The structure containing the chunk information. /// -/// @retval SCE_REMOTE_STORAGE_SUCCESS The operation was successfully registered on the thread. -/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The RemoteStorage library was not initialised. -/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no enough memory on the library to perform an allocation. -/// @retval ERROR_OCCURRED This event will be sent to the event callback when an error has occurred in the thread. +/// @retval SCE_REMOTE_STORAGE_SUCCESS +/// The operation was successfully registered on the thread. +/// @retval SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED The +/// RemoteStorage library was not initialised. +/// @retval SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE There is no +/// enough memory on the library to perform an allocation. +/// @retval ERROR_OCCURRED +/// This event will be sent to the event callback when an error has occurred in +/// the thread. /// -/// @note System errors may be returned. Design your code so it does expect other errors. -int32_t sceRemoteStorageSetData(const SceRemoteStorageSetDataReqParams & data); +/// @note System errors may be returned. Design your code so it does expect +/// other errors. +int32_t sceRemoteStorageSetData(const SceRemoteStorageSetDataReqParams& data); #endif \ No newline at end of file diff --git a/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h b/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h index 3e6e517f5..692942f11 100644 --- a/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h +++ b/Minecraft.Client/Platform/Common/Network/Sony/sceRemoteStorage/header/sceRemoteStorageDefines.h @@ -15,153 +15,201 @@ #include // Macros -#define SCE_REMOTE_STORAGE_MAX_FILES 16 -#define SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN 64 -#define SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN 64 -#define SCE_REMOTE_STORAGE_PLATFORM_NAME_MAX_LEN 16 -#define SCE_REMOTE_STORAGE_MD5_STRING_LENGTH 33 -#define SCE_REMOTE_STORAGE_RFC2822_LENGTH 32 -#define SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN 256 -#define SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN 256 -#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE 16 -#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE 13 -#define SCE_REMOTE_STORAGE_AUTH_CODE_MAX_LEN 128 +#define SCE_REMOTE_STORAGE_MAX_FILES 16 +#define SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN 64 +#define SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN 64 +#define SCE_REMOTE_STORAGE_PLATFORM_NAME_MAX_LEN 16 +#define SCE_REMOTE_STORAGE_MD5_STRING_LENGTH 33 +#define SCE_REMOTE_STORAGE_RFC2822_LENGTH 32 +#define SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN 256 +#define SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN 256 +#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE 16 +#define SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE 13 +#define SCE_REMOTE_STORAGE_AUTH_CODE_MAX_LEN 128 // Return values -#define SCE_REMOTE_STORAGE_SUCCESS 0 +#define SCE_REMOTE_STORAGE_SUCCESS 0 // Error codes -#define SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT 0x80001001 -#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_CREATE_THREAD 0x80001002 -#define SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED 0x80001003 -#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_WEB_BROWSER 0x80001004 -#define SCE_REMOTE_STORAGE_ERROR_PSN_ACCOUNT_NOT_LINKED 0x80001005 -#define SCE_REMOTE_STORAGE_ERROR_COULD_NOT_CREATE_SESSION 0x80001006 -#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE 0x80001007 -#define SCE_REMOTE_STORAGE_ERROR_SESSION_DOES_NOT_EXIST 0x80001008 -#define SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND 0x80001009 -#define SCE_REMOTE_STORAGE_ERROR_MAX_NUMBER_FILES_REACHED 0x8000100A -#define SCE_REMOTE_STORAGE_ERROR_NO_MORE_SYNCS 0x8000100B -#define SCE_REMOTE_STORAGE_ERROR_ALREADY_INITIALISED 0x8000100C -#define SCE_REMOTE_STORAGE_ERROR_INVALID_UPLOADID 0x8000100D -#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_FILE 0x8000100E -#define SCE_REMOTE_STORAGE_ERROR_CLOUD_DATA_CORRUPTED 0x8000100F -#define SCE_REMOTE_STORAGE_ERROR_INVALID_CHAR_IN_FILE_NAME 0x80001010 -#define SCE_REMOTE_STORAGE_ERROR_INVALID_JSON_RESPONSE 0x80001011 -#define SCE_REMOTE_STORAGE_ERROR_REQUEST_ABORTED 0x80001012 -#define SCE_REMOTE_STORAGE_ERROR_SERVER_ERROR 0x80002000 // Server errors can be between 0x80002064 to 0x800022BB both included +#define SCE_REMOTE_STORAGE_ERROR_INVALID_ARGUMENT 0x80001001 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_CREATE_THREAD 0x80001002 +#define SCE_REMOTE_STORAGE_ERROR_NOT_INITIALISED 0x80001003 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_WEB_BROWSER 0x80001004 +#define SCE_REMOTE_STORAGE_ERROR_PSN_ACCOUNT_NOT_LINKED 0x80001005 +#define SCE_REMOTE_STORAGE_ERROR_COULD_NOT_CREATE_SESSION 0x80001006 +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_ALLOCATE 0x80001007 +#define SCE_REMOTE_STORAGE_ERROR_SESSION_DOES_NOT_EXIST 0x80001008 +#define SCE_REMOTE_STORAGE_ERROR_REQ_ID_NOT_FOUND 0x80001009 +#define SCE_REMOTE_STORAGE_ERROR_MAX_NUMBER_FILES_REACHED 0x8000100A +#define SCE_REMOTE_STORAGE_ERROR_NO_MORE_SYNCS 0x8000100B +#define SCE_REMOTE_STORAGE_ERROR_ALREADY_INITIALISED 0x8000100C +#define SCE_REMOTE_STORAGE_ERROR_INVALID_UPLOADID 0x8000100D +#define SCE_REMOTE_STORAGE_ERROR_FAILED_TO_OPEN_FILE 0x8000100E +#define SCE_REMOTE_STORAGE_ERROR_CLOUD_DATA_CORRUPTED 0x8000100F +#define SCE_REMOTE_STORAGE_ERROR_INVALID_CHAR_IN_FILE_NAME 0x80001010 +#define SCE_REMOTE_STORAGE_ERROR_INVALID_JSON_RESPONSE 0x80001011 +#define SCE_REMOTE_STORAGE_ERROR_REQUEST_ABORTED 0x80001012 +#define SCE_REMOTE_STORAGE_ERROR_SERVER_ERROR \ + 0x80002000 // Server errors can be between 0x80002064 to 0x800022BB both + // included - -typedef enum SceRemoteStorageDataVisibility -{ - PRIVATE = 0, // Only data owner can read and write data - PUBLIC_READ_ONLY, // Everyone can read this data. Owner can write to it - PUBLIC_READ_WRITE // Everyone can read and write data +typedef enum SceRemoteStorageDataVisibility { + PRIVATE = 0, // Only data owner can read and write data + PUBLIC_READ_ONLY, // Everyone can read this data. Owner can write to it + PUBLIC_READ_WRITE // Everyone can read and write data } SceRemoteStorageDataVisibility; -typedef enum SceRemoteStorageEvent -{ - USER_ACCOUNT_LINKED = 0, // User's account has been linked with PSN - PSN_SIGN_IN_REQUIRED, // User's PSN sign-in through web browser is required - WEB_BROWSER_RESULT, // Result of sceRemoteStorageOpenWebBrowser(). Please check retCode - GET_DATA_RESULT, // Result of sceRemoteStorageGetData(). Please check retCode - GET_DATA_PROGRESS, // Progress of sceRemoteStorageGetData() completion as a percentage. Please check retCode - SET_DATA_RESULT, // Result of sceRemoteStorageSetData(). Please check retCode - SET_DATA_PROGRESS, // Progress of sceRemoteStorageSetData() completion as a percentage. Please check retCode - GET_STATUS_RESULT, // Result of sceRemoteStorageGetStatus(). Please check retCode - ERROR_OCCURRED // A generic error has occurred. Please check retCode +typedef enum SceRemoteStorageEvent { + USER_ACCOUNT_LINKED = 0, // User's account has been linked with PSN + PSN_SIGN_IN_REQUIRED, // User's PSN sign-in through web browser is required + WEB_BROWSER_RESULT, // Result of sceRemoteStorageOpenWebBrowser(). Please + // check retCode + GET_DATA_RESULT, // Result of sceRemoteStorageGetData(). Please check + // retCode + GET_DATA_PROGRESS, // Progress of sceRemoteStorageGetData() completion as a + // percentage. Please check retCode + SET_DATA_RESULT, // Result of sceRemoteStorageSetData(). Please check + // retCode + SET_DATA_PROGRESS, // Progress of sceRemoteStorageSetData() completion as a + // percentage. Please check retCode + GET_STATUS_RESULT, // Result of sceRemoteStorageGetStatus(). Please check + // retCode + ERROR_OCCURRED // A generic error has occurred. Please check retCode } SceRemoteStorageEvent; -typedef enum SceRemoteStorageEnvironment -{ - DEVELOPMENT = 0, - PRODUCTION -}SceRemoteStorageEnvironment; +typedef enum SceRemoteStorageEnvironment { + DEVELOPMENT = 0, + PRODUCTION +} SceRemoteStorageEnvironment; -typedef void (*sceRemoteStorageCallback)(const SceRemoteStorageEvent event, int32_t retCode, void * userData); +typedef void (*sceRemoteStorageCallback)(const SceRemoteStorageEvent event, + int32_t retCode, void* userData); -typedef struct SceRemoteStorageInitParamsThread -{ - int32_t threadAffinity; // Thread affinity - int32_t threadPriority; // Priority that the thread runs out +typedef struct SceRemoteStorageInitParamsThread { + int32_t threadAffinity; // Thread affinity + int32_t threadPriority; // Priority that the thread runs out } SceRemoteStorageInitParamsThread; -typedef struct SceRemoteStorageInitParamsPool -{ - void * memPoolBuffer; // Memory pool used by sceRemoteStorage library - size_t memPoolSize; // Size of memPoolBuffer +typedef struct SceRemoteStorageInitParamsPool { + void* memPoolBuffer; // Memory pool used by sceRemoteStorage library + size_t memPoolSize; // Size of memPoolBuffer } SceRemoteStorageInitParamsPool; -typedef struct SceRemoteStorageInitTimeout -{ - uint32_t resolveMs; //Timeout for DNS resolution in milliseconds. Defaults to 30 seconds - uint32_t connectMs; //Timeout for first connection between client and server. Defaults to 30 seconds - uint32_t sendMs; //Timeout to send request to server. Defaults to 120 seconds - uint32_t receiveMs; //Timeout to receive information from server. Defaults to 120 seconds - - SceRemoteStorageInitTimeout() : resolveMs(30 * 1000), connectMs(30 * 1000), sendMs(120 * 1000), receiveMs(120 * 1000) {} -}SceRemoteStorageInitTimeout; +typedef struct SceRemoteStorageInitTimeout { + uint32_t resolveMs; // Timeout for DNS resolution in milliseconds. Defaults + // to 30 seconds + uint32_t connectMs; // Timeout for first connection between client and + // server. Defaults to 30 seconds + uint32_t + sendMs; // Timeout to send request to server. Defaults to 120 seconds + uint32_t receiveMs; // Timeout to receive information from server. Defaults + // to 120 seconds -typedef struct SceRemoteStorageInitParams -{ - sceRemoteStorageCallback callback; // Event callback - void * userData; // Application defined data for callback - int32_t httpContextId; // PS4 only: Http context ID that was returned from sceHttpInit() - int32_t userId; // PS4 only: Current user, see SceUserServiceUserId - void * psnTicket; // PS3 only: The PSN ticket used to authenticate the user - size_t psnTicketSize; // PS3 only: The size of the PSN ticket in bytes - char clientId[SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN]; // This represents your application on PSN, used to sign PSN user in for your title - SceRemoteStorageInitTimeout timeout; // Timeout for network transactions - SceRemoteStorageInitParamsPool pool; // Memory pool parameters - SceRemoteStorageInitParamsThread thread; // Thread creation parameters - SceRemoteStorageEnvironment environment; // Only used on non-PlayStation platforms: PSN Environment used by the library + SceRemoteStorageInitTimeout() + : resolveMs(30 * 1000), + connectMs(30 * 1000), + sendMs(120 * 1000), + receiveMs(120 * 1000) {} +} SceRemoteStorageInitTimeout; + +typedef struct SceRemoteStorageInitParams { + sceRemoteStorageCallback callback; // Event callback + void* userData; // Application defined data for callback + int32_t httpContextId; // PS4 only: Http context ID that was returned from + // sceHttpInit() + int32_t userId; // PS4 only: Current user, see SceUserServiceUserId + void* psnTicket; // PS3 only: The PSN ticket used to authenticate the user + size_t psnTicketSize; // PS3 only: The size of the PSN ticket in bytes + char clientId[SCE_REMOTE_STORAGE_CLIENT_ID_MAX_LEN]; // This represents + // your application on + // PSN, used to sign + // PSN user in for + // your title + SceRemoteStorageInitTimeout timeout; // Timeout for network transactions + SceRemoteStorageInitParamsPool pool; // Memory pool parameters + SceRemoteStorageInitParamsThread thread; // Thread creation parameters + SceRemoteStorageEnvironment + environment; // Only used on non-PlayStation platforms: PSN Environment + // used by the library } SceRemoteStorageInitParams; -typedef struct SceRemoteStorageGetDataReqParams -{ - char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server - char pathLocation[SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD - char secureFileId[SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID used for save data encryption - char ps3DataFilename[SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of data file in save data - uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX - SceAppUtilSaveDataDataSlot psVitaSaveDataSlot; // PS Vita only. Save data slot information +typedef struct SceRemoteStorageGetDataReqParams { + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on + // remote storage + // server + char pathLocation + [SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD + char secureFileId + [SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID + // used for save + // data encryption + char ps3DataFilename + [SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of + // data file in save + // data + uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX + SceAppUtilSaveDataDataSlot + psVitaSaveDataSlot; // PS Vita only. Save data slot information } SceRemoteStorageGetDataReqParams; -typedef struct SceRemoteStorageSetDataReqParams -{ - char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server - char fileDescription[SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file on remote storage server - char pathLocation[SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD - char secureFileId[SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID used for save data encryption - char ps3DataFilename[SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of data file in save data - uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX - SceRemoteStorageDataVisibility visibility; // Visibility of data +typedef struct SceRemoteStorageSetDataReqParams { + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on + // remote storage + // server + char fileDescription + [SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file + // on remote storage + // server + char pathLocation + [SCE_REMOTE_STORAGE_DATA_LOCATION_MAX_LEN]; // File location on the HDD + char secureFileId + [SCE_REMOTE_STORAGE_PS3_SAVEDATA_SECUREFILEID_SIZE]; // PS3 only. ID + // used for save + // data encryption + char ps3DataFilename + [SCE_REMOTE_STORAGE_PS3_SAVEDATA_FILENAME_SIZE]; // PS3 only. Name of + // data file in save + // data + uint32_t ps3FileType; // PS3 only. Type of file, CELL_SAVEDATA_FILETYPE_XXX + SceRemoteStorageDataVisibility visibility; // Visibility of data } SceRemoteStorageSetDataReqParams; -typedef struct SceRemoteStorageData -{ - char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on remote storage server - char fileDescription[SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file on remote storage server - size_t fileSize; // Size of file in bytes - char md5Checksum[SCE_REMOTE_STORAGE_MD5_STRING_LENGTH]; // File MD5 checksum - char timeStamp[SCE_REMOTE_STORAGE_RFC2822_LENGTH]; // Time that data was written on the server. Format is RFC2822 - SceRemoteStorageDataVisibility visibility; // Visibility of data +typedef struct SceRemoteStorageData { + char fileName[SCE_REMOTE_STORAGE_DATA_NAME_MAX_LEN]; // Name of file on + // remote storage + // server + char fileDescription + [SCE_REMOTE_STORAGE_DATA_DESCRIPTION_MAX_LEN]; // Description of file + // on remote storage + // server + size_t fileSize; // Size of file in bytes + char + md5Checksum[SCE_REMOTE_STORAGE_MD5_STRING_LENGTH]; // File MD5 checksum + char + timeStamp[SCE_REMOTE_STORAGE_RFC2822_LENGTH]; // Time that data was + // written on the server. + // Format is RFC2822 + SceRemoteStorageDataVisibility visibility; // Visibility of data } SceRemoteStorageData; -typedef struct SceRemoteStorageWebBrowserReqParams { } SceRemoteStorageWebBrowseReqParams; +typedef struct SceRemoteStorageWebBrowserReqParams { +} SceRemoteStorageWebBrowseReqParams; -typedef struct SceRemoteStorageStatusReqParams { } SceRemoteStorageStatusReqParams; +typedef struct SceRemoteStorageStatusReqParams { +} SceRemoteStorageStatusReqParams; -typedef struct SceRemoteStorageAbortReqParams -{ - uint32_t requestId; // The request Id to be aborted +typedef struct SceRemoteStorageAbortReqParams { + uint32_t requestId; // The request Id to be aborted } SceRemoteStorageAbortReqParams; -typedef struct SceRemoteStorageStatus -{ - uint32_t numFiles; // Number of files user has on remote storage server - SceRemoteStorageData data[SCE_REMOTE_STORAGE_MAX_FILES]; // Details about data if available. Data buffer will not be retrieved - uint64_t remainingSyncs; // Remaining syncs. the user has for upload/download +typedef struct SceRemoteStorageStatus { + uint32_t numFiles; // Number of files user has on remote storage server + SceRemoteStorageData + data[SCE_REMOTE_STORAGE_MAX_FILES]; // Details about data if available. + // Data buffer will not be + // retrieved + uint64_t + remainingSyncs; // Remaining syncs. the user has for upload/download } SceRemoteStorageStatus; #endif