From 7bea3a33fd710f5bd3fc3e818641f12f5144c528 Mon Sep 17 00:00:00 2001 From: kuwacom Date: Tue, 3 Mar 2026 03:44:36 +0900 Subject: [PATCH] add: Add MultiPlay System - Implement Windows64 LAN multiplayer (host/join, discovery, session flow) - Add command-line options for multiplayer testing: -name, -host, -target - Add multiplayer usage docs to README - Reference implementation: https://github.com/LCEMP/LCEMP --- .../Common/Network/GameNetworkManager.cpp | 9 +- .../Network/PlatformNetworkManagerInterface.h | 1 + .../Network/PlatformNetworkManagerStub.cpp | 346 ++++++- .../Network/PlatformNetworkManagerStub.h | 3 +- Minecraft.Client/Common/Network/SessionInfo.h | 26 +- .../Common/UI/UIScene_LoadOrJoinMenu.cpp | 13 +- .../Common/XUI/XUI_MultiGameJoinLoad.cpp | 18 +- Minecraft.Client/Extrax64Stubs.cpp | 170 ++- Minecraft.Client/Minecraft.Client.vcxproj | 47 +- .../Minecraft.Client.vcxproj.filters | 5 +- .../Minecraft.Client.vcxproj.user | 1 + .../Windows64/Network/WinsockNetLayer.cpp | 973 ++++++++++++++++++ .../Windows64/Network/WinsockNetLayer.h | 168 +++ Minecraft.Client/Windows64/Windows64_App.cpp | 3 +- .../Windows64/Windows64_Minecraft.cpp | 117 ++- Minecraft.World/x64headers/extraX64.h | 12 +- README.md | 29 + 17 files changed, 1857 insertions(+), 84 deletions(-) create mode 100644 Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp create mode 100644 Minecraft.Client/Windows64/Network/WinsockNetLayer.h diff --git a/Minecraft.Client/Common/Network/GameNetworkManager.cpp b/Minecraft.Client/Common/Network/GameNetworkManager.cpp index 2a80f80a5..d6ae57351 100644 --- a/Minecraft.Client/Common/Network/GameNetworkManager.cpp +++ b/Minecraft.Client/Common/Network/GameNetworkManager.cpp @@ -166,7 +166,12 @@ bool CGameNetworkManager::_RunNetworkGame(LPVOID lpParameter) return true; } } - + else + { + // Client needs QNET_STATE_GAME_PLAY so that IsInGameplay() returns true. + s_pPlatformNetworkManager->SetGamePlayState(); + } + if( g_NetworkManager.IsLeavingGame() ) return false; app.SetGameStarted(true); @@ -1396,7 +1401,7 @@ void CGameNetworkManager::CreateSocket( INetworkPlayer *pNetworkPlayer, bool loc { // 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 ) diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h index 901e59e72..31c415a75 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerInterface.h @@ -84,6 +84,7 @@ public: virtual void HandleSignInChange() = 0; virtual bool _RunNetworkGame() = 0; + virtual void SetGamePlayState() {} private: virtual bool _LeaveGame(bool bMigrateHost, bool bLeaveRoom) = 0; diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp index b6b0fe122..8e66cf3e2 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.cpp @@ -2,10 +2,63 @@ #include "..\..\..\Minecraft.World\Socket.h" #include "..\..\..\Minecraft.World\StringHelpers.h" #include "PlatformNetworkManagerStub.h" -#include "..\..\Xbox\Network\NetworkPlayerXbox.h" // TODO - stub version of this? +#include "..\..\Xbox\Network\NetworkPlayerXbox.h" +#include +#ifdef _WINDOWS64 +#include "..\..\Windows64\Network\WinsockNetLayer.h" +#include "..\..\Minecraft.h" +#include "..\..\User.h" +#endif CPlatformNetworkManagerStub *g_pPlatformNetworkManager; +#ifdef _WINDOWS64 +static void Win64_ResolveTargetServerName(const char *targetHost, wchar_t *outName, size_t outNameCount) +{ + if (outName == NULL || outNameCount == 0) + return; + + outName[0] = 0; + if (targetHost == NULL || targetHost[0] == 0) + { + wcsncpy_s(outName, outNameCount, L"Unknown", _TRUNCATE); + return; + } + + char resolvedName[256] = {0}; + addrinfo hints = {}; + addrinfo *result = NULL; + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_CANONNAME; + + if (getaddrinfo(targetHost, NULL, &hints, &result) == 0) + { + if (result != NULL && result->ai_canonname != NULL && result->ai_canonname[0] != 0) + { + strncpy_s(resolvedName, sizeof(resolvedName), result->ai_canonname, _TRUNCATE); + } + else if (result != NULL) + { + char reverseName[NI_MAXHOST] = {0}; + if (getnameinfo(result->ai_addr, (socklen_t)result->ai_addrlen, reverseName, sizeof(reverseName), NULL, 0, NI_NAMEREQD) == 0) + { + strncpy_s(resolvedName, sizeof(resolvedName), reverseName, _TRUNCATE); + } + } + freeaddrinfo(result); + } + + if (resolvedName[0] == 0) + { + strncpy_s(resolvedName, sizeof(resolvedName), targetHost, _TRUNCATE); + } + + MultiByteToWideChar(CP_ACP, 0, resolvedName, -1, outName, (int)outNameCount); + outName[outNameCount - 1] = 0; +} +#endif + void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) { @@ -114,10 +167,42 @@ void CPlatformNetworkManagerStub::NotifyPlayerJoined(IQNetPlayer *pQNetPlayer ) } } +void CPlatformNetworkManagerStub::NotifyPlayerLeaving(IQNetPlayer *pQNetPlayer) +{ + app.DebugPrintf("Player 0x%p \"%ls\" leaving.\n", pQNetPlayer, pQNetPlayer->GetGamertag()); + + INetworkPlayer *networkPlayer = getNetworkPlayer(pQNetPlayer); + if (networkPlayer == NULL) + return; + + Socket *socket = networkPlayer->GetSocket(); + if (socket != NULL) + { + if (m_pIQNet->IsHost()) + g_NetworkManager.CloseConnection(networkPlayer); + } + + if (m_pIQNet->IsHost()) + { + SystemFlagRemovePlayer(networkPlayer); + } + + g_NetworkManager.PlayerLeaving(networkPlayer); + + for (int idx = 0; idx < XUSER_MAX_COUNT; ++idx) + { + if (playerChangedCallback[idx] != NULL) + playerChangedCallback[idx](playerChangedCallbackParam[idx], networkPlayer, true); + } + + removeNetworkPlayer(pQNetPlayer); +} + bool CPlatformNetworkManagerStub::Initialise(CGameNetworkManager *pGameNetworkManager, int flagIndexSize) { m_pGameNetworkManager = pGameNetworkManager; m_flagIndexSize = flagIndexSize; + m_pIQNet = new IQNet(); g_pPlatformNetworkManager = this; for( int i = 0; i < XUSER_MAX_COUNT; i++ ) { @@ -174,6 +259,38 @@ bool CPlatformNetworkManagerStub::isSystemPrimaryPlayer(IQNetPlayer *pQNetPlayer // We call this twice a frame, either side of the render call so is a good place to "tick" things void CPlatformNetworkManagerStub::DoWork() { +#ifdef _WINDOWS64 + extern QNET_STATE _iQNetStubState; + if (_iQNetStubState == QNET_STATE_SESSION_STARTING && app.GetGameStarted()) + { + _iQNetStubState = QNET_STATE_GAME_PLAY; + if (m_pIQNet->IsHost()) + WinsockNetLayer::UpdateAdvertiseJoinable(true); + } + // Keep LAN search ticking whenever the join menu callback is active, even if QNet state + // is not idle due to prior connection attempts. + TickSearch(); + if (_iQNetStubState == QNET_STATE_GAME_PLAY && m_pIQNet->IsHost()) + { + BYTE disconnectedSmallId; + while (WinsockNetLayer::PopDisconnectedSmallId(&disconnectedSmallId)) + { + IQNetPlayer *qnetPlayer = m_pIQNet->GetPlayerBySmallId(disconnectedSmallId); + if (qnetPlayer != NULL && qnetPlayer->m_smallId == disconnectedSmallId) + { + NotifyPlayerLeaving(qnetPlayer); + qnetPlayer->m_smallId = 0; + qnetPlayer->m_isRemote = false; + qnetPlayer->m_isHostPlayer = false; + qnetPlayer->m_gamertag[0] = 0; + qnetPlayer->SetCustomDataValue(0); + WinsockNetLayer::PushFreeSmallId(disconnectedSmallId); + if (IQNet::s_playerCount > 1) + IQNet::s_playerCount--; + } + } + } +#endif } int CPlatformNetworkManagerStub::GetPlayerCount() @@ -232,13 +349,32 @@ bool CPlatformNetworkManagerStub::LeaveGame(bool bMigrateHost) m_bLeavingGame = true; - // If we are the host wait for the game server to end +#ifdef _WINDOWS64 + WinsockNetLayer::StopAdvertising(); +#endif + if(m_pIQNet->IsHost() && g_NetworkManager.ServerStoppedValid()) { m_pIQNet->EndGame(); g_NetworkManager.ServerStoppedWait(); g_NetworkManager.ServerStoppedDestroy(); } + else + { + m_pIQNet->EndGame(); + } + + for (AUTO_VAR(it, currentNetworkPlayers.begin()); it != currentNetworkPlayers.end(); it++) + delete *it; + currentNetworkPlayers.clear(); + m_machineQNetPrimaryPlayers.clear(); + SystemFlagReset(); + +#ifdef _WINDOWS64 + WinsockNetLayer::Shutdown(); + WinsockNetLayer::Initialize(); +#endif + return true; } @@ -249,21 +385,35 @@ bool CPlatformNetworkManagerStub::_LeaveGame(bool bMigrateHost, bool bLeaveRoom) 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(); +#ifdef _WINDOWS64 + IQNet::m_player[0].m_smallId = 0; + IQNet::m_player[0].m_isRemote = false; + IQNet::m_player[0].m_isHostPlayer = true; + IQNet::s_playerCount = 1; +#endif + _HostGame( localUsersMask, publicSlots, privateSlots ); -//#endif + +#ifdef _WINDOWS64 + int port = (g_Win64HostBindPort > 0) ? g_Win64HostBindPort : WIN64_NET_DEFAULT_PORT; + const char *bindIp = g_Win64HostBindSpecified ? g_Win64HostBindIP : "0.0.0.0"; + if (!WinsockNetLayer::IsActive()) + WinsockNetLayer::HostGame(bindIp, port); + + const wchar_t *hostName = IQNet::m_player[0].m_gamertag; + unsigned int settings = app.GetGameHostOption(eGameHostOption_All); + WinsockNetLayer::StartAdvertising(port, hostName, settings, 0, 0, MINECRAFT_NET_VERSION); +#endif } void CPlatformNetworkManagerStub::_HostGame(int usersMask, unsigned char publicSlots /*= MINECRAFT_NET_MAX_PLAYERS*/, unsigned char privateSlots /*= 0*/) @@ -277,7 +427,53 @@ bool CPlatformNetworkManagerStub::_StartGame() int CPlatformNetworkManagerStub::JoinGame(FriendSessionInfo *searchResult, int localUsersMask, int primaryUserIndex) { +#ifdef _WINDOWS64 + if (searchResult == NULL) + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + + const char *hostIP = searchResult->data.hostIP; + int hostPort = searchResult->data.hostPort; + + if (hostPort <= 0 || hostIP[0] == 0) + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + + m_bLeavingGame = false; + IQNet::s_isHosting = false; + m_pIQNet->ClientJoinGame(); + + IQNet::m_player[0].m_smallId = 0; + IQNet::m_player[0].m_isRemote = true; + IQNet::m_player[0].m_isHostPlayer = true; + wcsncpy_s(IQNet::m_player[0].m_gamertag, 32, searchResult->data.hostName, _TRUNCATE); + + WinsockNetLayer::StopDiscovery(); + + if (!WinsockNetLayer::JoinGame(hostIP, hostPort)) + { + app.DebugPrintf("Win64 LAN: Failed to connect to %s:%d\n", hostIP, hostPort); + WinsockNetLayer::StartDiscovery(); + return CGameNetworkManager::JOINGAME_FAIL_GENERAL; + } + + BYTE localSmallId = WinsockNetLayer::GetLocalSmallId(); + + IQNet::m_player[localSmallId].m_smallId = localSmallId; + IQNet::m_player[localSmallId].m_isRemote = false; + IQNet::m_player[localSmallId].m_isHostPlayer = false; + + Minecraft *pMinecraft = Minecraft::GetInstance(); + wcscpy_s(IQNet::m_player[localSmallId].m_gamertag, 32, pMinecraft->user->name.c_str()); + IQNet::s_playerCount = localSmallId + 1; + + NotifyPlayerJoined(&IQNet::m_player[0]); + NotifyPlayerJoined(&IQNet::m_player[localSmallId]); + + m_pGameNetworkManager->StateChange_AnyToStarting(); + return CGameNetworkManager::JOINGAME_SUCCESS; +#else + return CGameNetworkManager::JOINGAME_SUCCESS; +#endif } bool CPlatformNetworkManagerStub::SetLocalGame(bool isLocal) @@ -315,6 +511,22 @@ void CPlatformNetworkManagerStub::HandleSignInChange() bool CPlatformNetworkManagerStub::_RunNetworkGame() { +#ifdef _WINDOWS64 + extern QNET_STATE _iQNetStubState; + _iQNetStubState = QNET_STATE_GAME_PLAY; + + for (DWORD i = 0; i < IQNet::s_playerCount; i++) + { + if (IQNet::m_player[i].m_isRemote) + { + INetworkPlayer *pNetworkPlayer = getNetworkPlayer(&IQNet::m_player[i]); + if (pNetworkPlayer != NULL && pNetworkPlayer->GetSocket() != NULL) + { + Socket::addIncomingSocket(pNetworkPlayer->GetSocket()); + } + } + } +#endif return true; } @@ -503,10 +715,119 @@ wstring CPlatformNetworkManagerStub::GatherRTTStats() void CPlatformNetworkManagerStub::TickSearch() { +#ifdef _WINDOWS64 + if (m_SessionsUpdatedCallback == NULL) + return; + + if (!m_pIQNet->IsHost()) + WinsockNetLayer::StartDiscovery(); + + static DWORD lastSearchTime = 0; + DWORD now = GetTickCount(); + if (now - lastSearchTime < 2000) + return; + lastSearchTime = now; + + SearchForGames(); +#endif } void CPlatformNetworkManagerStub::SearchForGames() { +#ifdef _WINDOWS64 + std::vector lanSessions = WinsockNetLayer::GetDiscoveredSessions(); + + if (g_Win64TargetEnabled && g_Win64TargetIP[0] != 0) + { + // Manual search target: + // inject one explicit endpoint into the visible session list so players can + // attempt joining hosts outside normal broadcast discovery range. + Win64LANSession directSession; + memset(&directSession, 0, sizeof(directSession)); + strncpy_s(directSession.hostIP, sizeof(directSession.hostIP), g_Win64TargetIP, _TRUNCATE); + directSession.hostPort = g_Win64TargetPort > 0 ? g_Win64TargetPort : WIN64_NET_DEFAULT_PORT; + directSession.netVersion = MINECRAFT_NET_VERSION; + // Best-effort server metadata for the target endpoint: + // resolve canonical/reverse DNS name to show a meaningful host label. + Win64_ResolveTargetServerName(directSession.hostIP, directSession.hostName, 32); + directSession.playerCount = 0; + directSession.maxPlayers = MINECRAFT_NET_MAX_PLAYERS; + directSession.gameHostSettings = 0; + directSession.texturePackParentId = 0; + directSession.subTexturePackId = 0; + directSession.isJoinable = true; + directSession.lastSeenTick = GetTickCount(); + + bool found = false; + for (size_t i = 0; i < lanSessions.size(); i++) + { + if (strcmp(lanSessions[i].hostIP, directSession.hostIP) == 0 && + lanSessions[i].hostPort == directSession.hostPort) + { + found = true; + break; + } + } + if (!found) + { + lanSessions.push_back(directSession); + } + } + + for (size_t i = 0; i < friendsSessions[0].size(); i++) + delete friendsSessions[0][i]; + friendsSessions[0].clear(); + + for (size_t i = 0; i < lanSessions.size(); i++) + { + FriendSessionInfo *info = new FriendSessionInfo(); + // Name-tag style display for the join list: + // show host name plus transport endpoint so the player can verify the target. + wchar_t hostIpW[64]; + MultiByteToWideChar(CP_ACP, 0, lanSessions[i].hostIP, -1, hostIpW, (int)(sizeof(hostIpW) / sizeof(hostIpW[0]))); + hostIpW[(sizeof(hostIpW) / sizeof(hostIpW[0])) - 1] = 0; + + wchar_t label[128]; + bool isTargetSession = g_Win64TargetEnabled && + (strcmp(lanSessions[i].hostIP, g_Win64TargetIP) == 0) && + (lanSessions[i].hostPort == (g_Win64TargetPort > 0 ? g_Win64TargetPort : WIN64_NET_DEFAULT_PORT)); + if (isTargetSession && lanSessions[i].hostName[0] != 0) + swprintf(label, 128, L"[Target] %ls (%ls:%d)", lanSessions[i].hostName, hostIpW, lanSessions[i].hostPort); + else if (isTargetSession) + swprintf(label, 128, L"[Target] %ls:%d", hostIpW, lanSessions[i].hostPort); + else if (lanSessions[i].hostName[0] != 0) + swprintf(label, 128, L"%ls (%ls:%d)", lanSessions[i].hostName, hostIpW, lanSessions[i].hostPort); + else + swprintf(label, 128, L"%ls:%d", hostIpW, lanSessions[i].hostPort); + + size_t nameLen = wcslen(label); + info->displayLabel = new wchar_t[nameLen + 1]; + wcscpy_s(info->displayLabel, nameLen + 1, label); + info->displayLabelLength = (unsigned char)(nameLen > 255 ? 255 : nameLen); + info->displayLabelViewableStartIndex = 0; + + info->data.netVersion = lanSessions[i].netVersion; + info->data.m_uiGameHostSettings = lanSessions[i].gameHostSettings; + info->data.texturePackParentId = lanSessions[i].texturePackParentId; + info->data.subTexturePackId = lanSessions[i].subTexturePackId; + info->data.isReadyToJoin = lanSessions[i].isJoinable; + info->data.isJoinable = lanSessions[i].isJoinable; + strncpy_s(info->data.hostIP, sizeof(info->data.hostIP), lanSessions[i].hostIP, _TRUNCATE); + info->data.hostPort = lanSessions[i].hostPort; + wcsncpy_s(info->data.hostName, XUSER_NAME_SIZE, lanSessions[i].hostName, _TRUNCATE); + info->data.playerCount = lanSessions[i].playerCount; + info->data.maxPlayers = lanSessions[i].maxPlayers; + + info->sessionId = (SessionID)((unsigned __int64)inet_addr(lanSessions[i].hostIP) | ((unsigned __int64)lanSessions[i].hostPort << 32)); + + friendsSessions[0].push_back(info); + } + + m_searchResultsCount[0] = (int)friendsSessions[0].size(); + + if (m_SessionsUpdatedCallback != NULL) + m_SessionsUpdatedCallback(m_pSearchParam); +#endif } int CPlatformNetworkManagerStub::SearchForGamesThreadProc( void* lpParameter ) @@ -522,7 +843,9 @@ void CPlatformNetworkManagerStub::SetSearchResultsReady(int resultCount) vector *CPlatformNetworkManagerStub::GetSessionList(int iPad, int localPlayers, bool partyOnly) { - vector *filteredList = new vector();; + vector *filteredList = new vector(); + for (size_t i = 0; i < friendsSessions[0].size(); i++) + filteredList->push_back(friendsSessions[0][i]); return filteredList; } @@ -533,7 +856,14 @@ bool CPlatformNetworkManagerStub::GetGameSessionInfo(int iPad, SessionID session void CPlatformNetworkManagerStub::SetSessionsUpdatedCallback( void (*SessionsUpdatedCallback)(LPVOID pParam), LPVOID pSearchParam ) { - m_SessionsUpdatedCallback = SessionsUpdatedCallback; m_pSearchParam = pSearchParam; + m_SessionsUpdatedCallback = SessionsUpdatedCallback; + m_pSearchParam = pSearchParam; +#ifdef _WINDOWS64 + if (m_SessionsUpdatedCallback != NULL) + { + SearchForGames(); + } +#endif } void CPlatformNetworkManagerStub::GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ) diff --git a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h index f997dece5..919efd713 100644 --- a/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h +++ b/Minecraft.Client/Common/Network/PlatformNetworkManagerStub.h @@ -161,8 +161,9 @@ public: virtual void GetFullFriendSessionInfo( FriendSessionInfo *foundSession, void (* FriendSessionUpdatedFn)(bool success, void *pParam), void *pParam ); virtual void ForceFriendsSessionRefresh(); -private: +public: void NotifyPlayerJoined( IQNetPlayer *pQNetPlayer ); + void NotifyPlayerLeaving( IQNetPlayer *pQNetPlayer ); #ifndef _XBOX void FakeLocalPlayerJoined() { NotifyPlayerJoined(m_pIQNet->GetLocalPlayerByUserIndex(0)); } diff --git a/Minecraft.Client/Common/Network/SessionInfo.h b/Minecraft.Client/Common/Network/SessionInfo.h index 31472a19a..a267de47c 100644 --- a/Minecraft.Client/Common/Network/SessionInfo.h +++ b/Minecraft.Client/Common/Network/SessionInfo.h @@ -63,12 +63,19 @@ typedef struct _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 + unsigned short netVersion; + unsigned int m_uiGameHostSettings; + unsigned int texturePackParentId; + unsigned char subTexturePackId; - bool isReadyToJoin; // 1 byte + bool isReadyToJoin; + bool isJoinable; + + char hostIP[64]; + int hostPort; + wchar_t hostName[XUSER_NAME_SIZE]; + unsigned char playerCount; + unsigned char maxPlayers; _GameSessionData() { @@ -76,6 +83,13 @@ typedef struct _GameSessionData m_uiGameHostSettings = 0; texturePackParentId = 0; subTexturePackId = 0; + isReadyToJoin = false; + isJoinable = true; + memset(hostIP, 0, sizeof(hostIP)); + hostPort = 0; + memset(hostName, 0, sizeof(hostName)); + playerCount = 0; + maxPlayers = MINECRAFT_NET_MAX_PLAYERS; } } GameSessionData; #endif @@ -108,6 +122,6 @@ public: ~FriendSessionInfo() { if(displayLabel!=NULL) - delete displayLabel; + delete [] displayLabel; } }; diff --git a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp index 1d90da775..75b404525 100644 --- a/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp +++ b/Minecraft.Client/Common/UI/UIScene_LoadOrJoinMenu.cpp @@ -285,10 +285,9 @@ UIScene_LoadOrJoinMenu::~UIScene_LoadOrJoinMenu() if(m_currentSessions) { - for(AUTO_VAR(it, m_currentSessions->begin()); it < m_currentSessions->end(); ++it) - { - delete (*it); - } + // Session entries are owned by the platform network manager. + delete m_currentSessions; + m_currentSessions = NULL; } #if TO_BE_IMPLEMENTED @@ -300,7 +299,7 @@ UIScene_LoadOrJoinMenu::~UIScene_LoadOrJoinMenu() { for(int i = 0; i < m_iSaveDetailsCount; ++i) { - delete m_saveDetails[i].pbThumbnailData; + delete [] m_saveDetails[i].pbThumbnailData; } delete [] m_saveDetails; } @@ -595,10 +594,10 @@ void UIScene_LoadOrJoinMenu::tick() { if(m_saveDetails[i].pbThumbnailData!=NULL) { - delete m_saveDetails[i].pbThumbnailData; + delete [] m_saveDetails[i].pbThumbnailData; } } - delete m_saveDetails; + delete [] m_saveDetails; } m_saveDetails = new SaveListDetails[m_pSaveDetails->iSaveC]; diff --git a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp index 73f25da58..05eac94a4 100644 --- a/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp +++ b/Minecraft.Client/Common/XUI/XUI_MultiGameJoinLoad.cpp @@ -387,10 +387,7 @@ HRESULT CScene_MultiGameJoinLoad::OnDestroy() { g_NetworkManager.SetSessionsUpdatedCallback( NULL, NULL ); - for(AUTO_VAR(it, currentSessions.begin()); it < currentSessions.end(); ++it) - { - delete (*it); - } + currentSessions.clear(); if(m_bSaveTransferInProgress) { @@ -1145,10 +1142,6 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() if( pSelectedSession != NULL )selectedSessionId = pSelectedSession->sessionId; pSelectedSession = NULL; - for(AUTO_VAR(it, currentSessions.begin()); it < currentSessions.end(); ++it) - { - delete (*it); - } currentSessions.clear(); m_NetGamesListTimer.SetShow( FALSE ); @@ -1210,7 +1203,12 @@ void CScene_MultiGameJoinLoad::UpdateGamesList() ui.SetTooltips( DEFAULT_XUI_MENU_USER, IDS_TOOLTIPS_SELECT, IDS_TOOLTIPS_BACK, IDS_TOOLTIPS_CHANGEDEVICE, iY,-1,-1,iLB,iRB); } - currentSessions = *g_NetworkManager.GetSessionList( m_iPad, m_localPlayers, m_bShowingPartyGamesOnly ); + vector *pSessionList = g_NetworkManager.GetSessionList( m_iPad, m_localPlayers, m_bShowingPartyGamesOnly ); + if(pSessionList != NULL) + { + currentSessions = *pSessionList; + delete pSessionList; + } // Update the xui list displayed unsigned int xuiListSize = m_pGamesList->GetItemCount(); @@ -2764,4 +2762,4 @@ void CScene_MultiGameJoinLoad::SaveUploadCompleteCallback(LPVOID lpParam) app.TMSPP_SetTitleGroupID(GROUP_ID); // app.getRemoteStorage()->abort(); // pClass->m_eSaveUploadState = eSaveUpload_Idle; -} \ No newline at end of file +} diff --git a/Minecraft.Client/Extrax64Stubs.cpp b/Minecraft.Client/Extrax64Stubs.cpp index f6ad76c17..4ebd89e0b 100644 --- a/Minecraft.Client/Extrax64Stubs.cpp +++ b/Minecraft.Client/Extrax64Stubs.cpp @@ -185,28 +185,25 @@ D3DXVECTOR3::D3DXVECTOR3() {} D3DXVECTOR3::D3DXVECTOR3(float x,float y,float z) : x(x), y(y), z(z) {} D3DXVECTOR3& D3DXVECTOR3::operator += ( CONST D3DXVECTOR3& add ) { x += add.x; y += add.y; z += add.z; return *this; } -BYTE IQNetPlayer::GetSmallId() { return 0; } +#include "Windows64\Network\WinsockNetLayer.h" + +BYTE IQNetPlayer::GetSmallId() { return m_smallId; } void IQNetPlayer::SendData(IQNetPlayer *player, const void *pvData, DWORD dwDataSize, DWORD dwFlags) { - app.DebugPrintf("Sending from 0x%x to 0x%x %d bytes\n",this,player,dwDataSize); + if (WinsockNetLayer::IsActive()) + { + WinsockNetLayer::SendToSmallId(player->m_smallId, pvData, dwDataSize); + } } -bool IQNetPlayer::IsSameSystem(IQNetPlayer *player) { return true; } +bool IQNetPlayer::IsSameSystem(IQNetPlayer *player) { return (this == player) || (!m_isRemote && !player->m_isRemote); } DWORD IQNetPlayer::GetSendQueueSize( IQNetPlayer *player, DWORD dwFlags ) { return 0; } DWORD IQNetPlayer::GetCurrentRtt() { return 0; } -bool IQNetPlayer::IsHost() { return this == &IQNet::m_player[0]; } +bool IQNetPlayer::IsHost() { return m_isHostPlayer; } bool IQNetPlayer::IsGuest() { return false; } -bool IQNetPlayer::IsLocal() { return true; } -PlayerUID IQNetPlayer::GetXuid() { return INVALID_XUID; } -LPCWSTR IQNetPlayer::GetGamertag() -{ - static wchar_t tags[4][16]; - int idx = GetUserIndex(); - if(idx < 0 || idx >= 4) idx = 0; - mbstowcs(tags[idx], ProfileManager.GetGamertag(idx), 15); - tags[idx][15] = L'\0'; - return tags[idx]; -} -int IQNetPlayer::GetSessionIndex() { return 0; } +bool IQNetPlayer::IsLocal() { return !m_isRemote; } +PlayerUID IQNetPlayer::GetXuid() { return (PlayerUID)(0xe000d45248242f2e + m_smallId); } +LPCWSTR IQNetPlayer::GetGamertag() { return m_gamertag; } +int IQNetPlayer::GetSessionIndex() { return m_smallId; } bool IQNetPlayer::IsTalking() { return false; } bool IQNetPlayer::IsMutedByLocalUser(DWORD dwUserIndex) { return false; } bool IQNetPlayer::HasVoice() { return false; } @@ -219,22 +216,104 @@ ULONG_PTR IQNetPlayer::GetCustomDataValue() { return m_customData; } -IQNetPlayer IQNet::m_player[4]; +IQNetPlayer IQNet::m_player[MINECRAFT_NET_MAX_PLAYERS]; +DWORD IQNet::s_playerCount = 1; +bool IQNet::s_isHosting = true; -bool _bQNetStubGameRunning = false; +QNET_STATE _iQNetStubState = QNET_STATE_IDLE; + +void Win64_SetupRemoteQNetPlayer(IQNetPlayer *player, BYTE smallId, bool isHost, bool isLocal) +{ + player->m_smallId = smallId; + player->m_isRemote = !isLocal; + player->m_isHostPlayer = isHost; + swprintf_s(player->m_gamertag, 32, L"Player%d", smallId); + if (smallId >= IQNet::s_playerCount) + IQNet::s_playerCount = smallId + 1; +} HRESULT IQNet::AddLocalPlayerByUserIndex(DWORD dwUserIndex){ return S_OK; } IQNetPlayer *IQNet::GetHostPlayer() { return &m_player[0]; } -IQNetPlayer *IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) { return &m_player[dwUserIndex]; } -IQNetPlayer *IQNet::GetPlayerByIndex(DWORD dwPlayerIndex) { return &m_player[0]; } -IQNetPlayer *IQNet::GetPlayerBySmallId(BYTE SmallId){ return &m_player[0]; } -IQNetPlayer *IQNet::GetPlayerByXuid(PlayerUID xuid){ return &m_player[0]; } -DWORD IQNet::GetPlayerCount() { return 1; } -QNET_STATE IQNet::GetState() { return _bQNetStubGameRunning ? QNET_STATE_GAME_PLAY : QNET_STATE_IDLE; } -bool IQNet::IsHost() { return true; } +IQNetPlayer *IQNet::GetLocalPlayerByUserIndex(DWORD dwUserIndex) +{ + if (s_isHosting) + { + if (dwUserIndex < MINECRAFT_NET_MAX_PLAYERS && !m_player[dwUserIndex].m_isRemote) + return &m_player[dwUserIndex]; + return NULL; + } + if (dwUserIndex != 0) + return NULL; + for (DWORD i = 0; i < s_playerCount; i++) + { + if (!m_player[i].m_isRemote) + return &m_player[i]; + } + return NULL; +} +static bool Win64_IsActivePlayer(IQNetPlayer *p, DWORD index) +{ + if (index == 0) return true; + return (p->GetCustomDataValue() != 0); +} + +IQNetPlayer *IQNet::GetPlayerByIndex(DWORD dwPlayerIndex) +{ + DWORD found = 0; + for (DWORD i = 0; i < s_playerCount; i++) + { + if (Win64_IsActivePlayer(&m_player[i], i)) + { + if (found == dwPlayerIndex) return &m_player[i]; + found++; + } + } + return &m_player[0]; +} +IQNetPlayer *IQNet::GetPlayerBySmallId(BYTE SmallId) +{ + for (DWORD i = 0; i < s_playerCount; i++) + { + if (m_player[i].m_smallId == SmallId && Win64_IsActivePlayer(&m_player[i], i)) return &m_player[i]; + } + return NULL; +} +IQNetPlayer *IQNet::GetPlayerByXuid(PlayerUID xuid) +{ + for (DWORD i = 0; i < s_playerCount; i++) + { + if (Win64_IsActivePlayer(&m_player[i], i) && m_player[i].GetXuid() == xuid) return &m_player[i]; + } + return &m_player[0]; +} +DWORD IQNet::GetPlayerCount() +{ + DWORD count = 0; + for (DWORD i = 0; i < s_playerCount; i++) + { + if (Win64_IsActivePlayer(&m_player[i], i)) count++; + } + return count; +} +QNET_STATE IQNet::GetState() { return _iQNetStubState; } +bool IQNet::IsHost() { return s_isHosting; } HRESULT IQNet::JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, const INVITE_INFO *pInviteInfo) { return S_OK; } -void IQNet::HostGame() { _bQNetStubGameRunning = true; } -void IQNet::EndGame() { _bQNetStubGameRunning = false; } +void IQNet::HostGame() { _iQNetStubState = QNET_STATE_SESSION_STARTING; s_isHosting = true; } +void IQNet::ClientJoinGame() { _iQNetStubState = QNET_STATE_SESSION_STARTING; s_isHosting = false; } +void IQNet::EndGame() +{ + _iQNetStubState = QNET_STATE_IDLE; + s_isHosting = false; + s_playerCount = 1; + for (int i = 1; i < MINECRAFT_NET_MAX_PLAYERS; i++) + { + m_player[i].m_smallId = 0; + m_player[i].m_isRemote = false; + m_player[i].m_isHostPlayer = false; + m_player[i].m_gamertag[0] = 0; + m_player[i].SetCustomDataValue(0); + } +} DWORD MinecraftDynamicConfigurations::GetTrialTime() { return DYNAMIC_CONFIG_DEFAULT_TRIAL_TIME; } @@ -468,8 +547,23 @@ UINT C_4JProfile::DisplayOfflineProfile(int( *Func)(LPVOID,const bool, const UINT C_4JProfile::RequestConvertOfflineToGuestUI(int( *Func)(LPVOID,const bool, const int iPad),LPVOID lpParam,int iQuadrant) { return 0; } void C_4JProfile::SetPrimaryPlayerChanged(bool bVal) {} bool C_4JProfile::QuerySigninStatus(void) { return true; } -void C_4JProfile::GetXUID(int iPad, PlayerUID *pXuid,bool bOnlineXuid) {*pXuid = 0xe000d45248242f2e; } -BOOL C_4JProfile::AreXUIDSEqual(PlayerUID xuid1,PlayerUID xuid2) { return false; } +void C_4JProfile::GetXUID(int iPad, PlayerUID *pXuid,bool bOnlineXuid) +{ +#ifdef _WINDOWS64 + if (iPad != 0) + { + *pXuid = INVALID_XUID; + return; + } + if (IQNet::s_isHosting) + *pXuid = 0xe000d45248242f2e; + else + *pXuid = 0xe000d45248242f2e + WinsockNetLayer::GetLocalSmallId(); +#else + *pXuid = 0xe000d45248242f2e + iPad; +#endif +} +BOOL C_4JProfile::AreXUIDSEqual(PlayerUID xuid1,PlayerUID xuid2) { return xuid1 == xuid2; } BOOL C_4JProfile::XUIDIsGuest(PlayerUID xuid) { return false; } bool C_4JProfile::AllowedToPlayMultiplayer(int iProf) { return true; } @@ -495,22 +589,8 @@ char fakeGamerTag[32] = "PlayerName"; void SetFakeGamertag(char *name){ strcpy_s(fakeGamerTag, name); } char* C_4JProfile::GetGamertag(int iPad){ return fakeGamerTag; } #else -char* C_4JProfile::GetGamertag(int iPad) -{ - static char tags[4][16] = { "Player 1", "Player 2", "Player 3", "Player 4" }; - if(iPad >= 0 && iPad < 4) return tags[iPad]; - return tags[0]; -} -wstring C_4JProfile::GetDisplayName(int iPad) -{ - switch(iPad) - { - case 1: return L"Player 2"; - case 2: return L"Player 3"; - case 3: return L"Player 4"; - default: return L"Player 1"; - } -} +char* C_4JProfile::GetGamertag(int iPad){ extern char g_Win64Username[17]; return g_Win64Username; } +wstring C_4JProfile::GetDisplayName(int iPad){ extern wchar_t g_Win64UsernameW[17]; return g_Win64UsernameW; } #endif bool C_4JProfile::IsFullVersion() { return s_bProfileIsFullVersion; } void C_4JProfile::SetSignInChangeCallback(void ( *Func)(LPVOID, bool, unsigned int),LPVOID lpParam) {} diff --git a/Minecraft.Client/Minecraft.Client.vcxproj b/Minecraft.Client/Minecraft.Client.vcxproj index 607d158c2..34d44fed7 100644 --- a/Minecraft.Client/Minecraft.Client.vcxproj +++ b/Minecraft.Client/Minecraft.Client.vcxproj @@ -29109,6 +29109,51 @@ xcopy /q /y /i /s /e $(ProjectDir)Durango\CU $(LayoutDir)Image\Loose\CUtrue true + + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + false + false + false + false + false + false + false + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true + true true @@ -36876,4 +36921,4 @@ xcopy /q /y /i /s /e $(ProjectDir)Durango\CU $(LayoutDir)Image\Loose\CU - \ No newline at end of file + diff --git a/Minecraft.Client/Minecraft.Client.vcxproj.filters b/Minecraft.Client/Minecraft.Client.vcxproj.filters index 451dec441..9cce48ab6 100644 --- a/Minecraft.Client/Minecraft.Client.vcxproj.filters +++ b/Minecraft.Client/Minecraft.Client.vcxproj.filters @@ -4779,6 +4779,9 @@ Windows64 + + Windows64\Source Files + Durango\Source Files @@ -6017,4 +6020,4 @@ - \ No newline at end of file + diff --git a/Minecraft.Client/Minecraft.Client.vcxproj.user b/Minecraft.Client/Minecraft.Client.vcxproj.user index 10dbfa336..09a0e06ca 100644 --- a/Minecraft.Client/Minecraft.Client.vcxproj.user +++ b/Minecraft.Client/Minecraft.Client.vcxproj.user @@ -6,6 +6,7 @@ $(SolutionDir)$(Platform)\$(Configuration)\ WindowsLocalDebugger + -name Debug-Host -host 0.0.0.0:19132 $(SolutionDir)$(Platform)\$(Configuration)\ diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp new file mode 100644 index 000000000..647c4d4de --- /dev/null +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp @@ -0,0 +1,973 @@ +#include "stdafx.h" + +#ifdef _WINDOWS64 + +#include "WinsockNetLayer.h" +#include "..\..\Common\Network\PlatformNetworkManagerStub.h" +#include "..\..\..\Minecraft.World\Socket.h" + +SOCKET WinsockNetLayer::s_listenSocket = INVALID_SOCKET; +SOCKET WinsockNetLayer::s_hostConnectionSocket = INVALID_SOCKET; +HANDLE WinsockNetLayer::s_acceptThread = NULL; +HANDLE WinsockNetLayer::s_clientRecvThread = NULL; + +bool WinsockNetLayer::s_isHost = false; +bool WinsockNetLayer::s_connected = false; +bool WinsockNetLayer::s_active = false; +bool WinsockNetLayer::s_initialized = false; + +BYTE WinsockNetLayer::s_localSmallId = 0; +BYTE WinsockNetLayer::s_hostSmallId = 0; +BYTE WinsockNetLayer::s_nextSmallId = 1; + +CRITICAL_SECTION WinsockNetLayer::s_sendLock; +CRITICAL_SECTION WinsockNetLayer::s_connectionsLock; + +std::vector WinsockNetLayer::s_connections; + +SOCKET WinsockNetLayer::s_advertiseSock = INVALID_SOCKET; +HANDLE WinsockNetLayer::s_advertiseThread = NULL; +volatile bool WinsockNetLayer::s_advertising = false; +Win64LANBroadcast WinsockNetLayer::s_advertiseData = {}; +CRITICAL_SECTION WinsockNetLayer::s_advertiseLock; +int WinsockNetLayer::s_hostGamePort = WIN64_NET_DEFAULT_PORT; +HANDLE WinsockNetLayer::s_localAdvertiseMap = NULL; +Win64LocalAdvertiseState *WinsockNetLayer::s_localAdvertiseState = NULL; + +SOCKET WinsockNetLayer::s_discoverySock = INVALID_SOCKET; +HANDLE WinsockNetLayer::s_discoveryThread = NULL; +volatile bool WinsockNetLayer::s_discovering = false; +CRITICAL_SECTION WinsockNetLayer::s_discoveryLock; +std::vector WinsockNetLayer::s_discoveredSessions; + +CRITICAL_SECTION WinsockNetLayer::s_disconnectLock; +std::vector WinsockNetLayer::s_disconnectedSmallIds; + +CRITICAL_SECTION WinsockNetLayer::s_freeSmallIdLock; +std::vector WinsockNetLayer::s_freeSmallIds; + +bool g_Win64MultiplayerHost = false; +bool g_Win64HostBindSpecified = false; +int g_Win64HostBindPort = WIN64_NET_DEFAULT_PORT; +char g_Win64HostBindIP[256] = "0.0.0.0"; +bool g_Win64TargetEnabled = false; +int g_Win64TargetPort = WIN64_NET_DEFAULT_PORT; +char g_Win64TargetIP[256] = "127.0.0.1"; + +static bool TryReadLocalAdvertiseSession(Win64LANSession *outSession) +{ + // Reference-style fallback: + // If UDP discovery is not observed locally, read the host advertisement from + // a shared memory block exposed by the host process on the same machine. + if (outSession == NULL) + return false; + + HANDLE hMap = OpenFileMappingA(FILE_MAP_READ, FALSE, WIN64_LAN_LOCAL_ADVERTISE_MAP_NAMEA); + if (hMap == NULL) + return false; + + Win64LocalAdvertiseState *state = (Win64LocalAdvertiseState *)MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, sizeof(Win64LocalAdvertiseState)); + if (state == NULL) + { + CloseHandle(hMap); + return false; + } + + bool valid = false; + DWORD now = GetTickCount(); + if (state->magic == WIN64_LAN_LOCAL_ADVERTISE_MAGIC && + (now - state->tick) <= 3000 && + state->broadcast.magic == WIN64_LAN_BROADCAST_MAGIC) + { + memset(outSession, 0, sizeof(Win64LANSession)); + strncpy_s(outSession->hostIP, sizeof(outSession->hostIP), "127.0.0.1", _TRUNCATE); + outSession->hostPort = (int)state->broadcast.gamePort; + outSession->netVersion = state->broadcast.netVersion; + wcsncpy_s(outSession->hostName, 32, state->broadcast.hostName, _TRUNCATE); + outSession->playerCount = state->broadcast.playerCount; + outSession->maxPlayers = state->broadcast.maxPlayers; + outSession->gameHostSettings = state->broadcast.gameHostSettings; + outSession->texturePackParentId = state->broadcast.texturePackParentId; + outSession->subTexturePackId = state->broadcast.subTexturePackId; + outSession->isJoinable = (state->broadcast.isJoinable != 0); + outSession->lastSeenTick = now; + valid = true; + } + + UnmapViewOfFile(state); + CloseHandle(hMap); + return valid; +} + +bool WinsockNetLayer::Initialize() +{ + if (s_initialized) return true; + + WSADATA wsaData; + int result = WSAStartup(MAKEWORD(2, 2), &wsaData); + if (result != 0) + { + app.DebugPrintf("WSAStartup failed: %d\n", result); + return false; + } + + InitializeCriticalSection(&s_sendLock); + InitializeCriticalSection(&s_connectionsLock); + InitializeCriticalSection(&s_advertiseLock); + InitializeCriticalSection(&s_discoveryLock); + InitializeCriticalSection(&s_disconnectLock); + InitializeCriticalSection(&s_freeSmallIdLock); + + s_initialized = true; + + StartDiscovery(); + + return true; +} + +void WinsockNetLayer::Shutdown() +{ + StopAdvertising(); + StopDiscovery(); + + s_active = false; + s_connected = false; + + if (s_listenSocket != INVALID_SOCKET) + { + closesocket(s_listenSocket); + s_listenSocket = INVALID_SOCKET; + } + + if (s_hostConnectionSocket != INVALID_SOCKET) + { + closesocket(s_hostConnectionSocket); + s_hostConnectionSocket = INVALID_SOCKET; + } + + EnterCriticalSection(&s_connectionsLock); + for (size_t i = 0; i < s_connections.size(); i++) + { + s_connections[i].active = false; + if (s_connections[i].tcpSocket != INVALID_SOCKET) + { + closesocket(s_connections[i].tcpSocket); + } + } + s_connections.clear(); + LeaveCriticalSection(&s_connectionsLock); + + if (s_acceptThread != NULL) + { + WaitForSingleObject(s_acceptThread, 2000); + CloseHandle(s_acceptThread); + s_acceptThread = NULL; + } + + if (s_clientRecvThread != NULL) + { + WaitForSingleObject(s_clientRecvThread, 2000); + CloseHandle(s_clientRecvThread); + s_clientRecvThread = NULL; + } + + if (s_initialized) + { + DeleteCriticalSection(&s_sendLock); + DeleteCriticalSection(&s_connectionsLock); + DeleteCriticalSection(&s_advertiseLock); + DeleteCriticalSection(&s_discoveryLock); + DeleteCriticalSection(&s_disconnectLock); + s_disconnectedSmallIds.clear(); + DeleteCriticalSection(&s_freeSmallIdLock); + s_freeSmallIds.clear(); + WSACleanup(); + s_initialized = false; + } +} + +bool WinsockNetLayer::HostGame(const char *bindIp, int port) +{ + if (!s_initialized && !Initialize()) return false; + bool restartDiscoveryOnFailure = s_discovering; + // As a host we only need to advertise; keeping discovery bound in this process can + // steal packets from another local client process searching on the same machine. + StopDiscovery(); + + s_isHost = true; + s_localSmallId = 0; + s_hostSmallId = 0; + s_nextSmallId = 1; + if (port <= 0) port = WIN64_NET_DEFAULT_PORT; + s_hostGamePort = port; + + EnterCriticalSection(&s_freeSmallIdLock); + s_freeSmallIds.clear(); + LeaveCriticalSection(&s_freeSmallIdLock); + + s_listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (s_listenSocket == INVALID_SOCKET) + { + app.DebugPrintf("socket() failed: %d\n", WSAGetLastError()); + if (restartDiscoveryOnFailure) StartDiscovery(); + return false; + } + + int opt = 1; + setsockopt(s_listenSocket, SOL_SOCKET, SO_REUSEADDR, (const char *)&opt, sizeof(opt)); + + struct sockaddr_in bindAddr; + memset(&bindAddr, 0, sizeof(bindAddr)); + bindAddr.sin_family = AF_INET; + bindAddr.sin_port = htons((u_short)port); + if (bindIp != NULL && bindIp[0] != 0 && strcmp(bindIp, "0.0.0.0") != 0 && strcmp(bindIp, "*") != 0) + { + if (inet_pton(AF_INET, bindIp, &bindAddr.sin_addr) != 1) + { + app.DebugPrintf("Win64 LAN: Invalid host bind IP \"%s\"\n", bindIp); + closesocket(s_listenSocket); + s_listenSocket = INVALID_SOCKET; + if (restartDiscoveryOnFailure) StartDiscovery(); + return false; + } + } + else + { + // Default: bind to INADDR_ANY so both remote and local-loopback joins work. + bindAddr.sin_addr.s_addr = htonl(INADDR_ANY); + } + + int iResult = ::bind(s_listenSocket, (struct sockaddr *)&bindAddr, sizeof(bindAddr)); + if (iResult == SOCKET_ERROR) + { + app.DebugPrintf("bind() failed: %d\n", WSAGetLastError()); + closesocket(s_listenSocket); + s_listenSocket = INVALID_SOCKET; + if (restartDiscoveryOnFailure) StartDiscovery(); + return false; + } + + iResult = listen(s_listenSocket, SOMAXCONN); + if (iResult == SOCKET_ERROR) + { + app.DebugPrintf("listen() failed: %d\n", WSAGetLastError()); + closesocket(s_listenSocket); + s_listenSocket = INVALID_SOCKET; + if (restartDiscoveryOnFailure) StartDiscovery(); + return false; + } + + s_active = true; + s_connected = true; + + s_acceptThread = CreateThread(NULL, 0, AcceptThreadProc, NULL, 0, NULL); + + char hostBindIp[64] = "0.0.0.0"; + if (bindAddr.sin_addr.s_addr != htonl(INADDR_ANY)) + { + inet_ntop(AF_INET, &bindAddr.sin_addr, hostBindIp, sizeof(hostBindIp)); + } + app.DebugPrintf("Win64 LAN: Hosting on %s:%d\n", hostBindIp, port); + return true; +} + +bool WinsockNetLayer::JoinGame(const char *ip, int port) +{ + if (!s_initialized && !Initialize()) return false; + + s_isHost = false; + s_hostSmallId = 0; + + struct addrinfo hints = {}; + struct addrinfo *result = NULL; + + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + char portStr[16]; + sprintf_s(portStr, "%d", port); + + int iResult = getaddrinfo(ip, portStr, &hints, &result); + if (iResult != 0) + { + app.DebugPrintf("getaddrinfo failed for %s:%d - %d\n", ip, port, iResult); + return false; + } + + s_hostConnectionSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); + if (s_hostConnectionSocket == INVALID_SOCKET) + { + app.DebugPrintf("socket() failed: %d\n", WSAGetLastError()); + freeaddrinfo(result); + return false; + } + + int noDelay = 1; + setsockopt(s_hostConnectionSocket, IPPROTO_TCP, TCP_NODELAY, (const char *)&noDelay, sizeof(noDelay)); + + iResult = connect(s_hostConnectionSocket, result->ai_addr, (int)result->ai_addrlen); + freeaddrinfo(result); + if (iResult == SOCKET_ERROR) + { + app.DebugPrintf("connect() to %s:%d failed: %d\n", ip, port, WSAGetLastError()); + closesocket(s_hostConnectionSocket); + s_hostConnectionSocket = INVALID_SOCKET; + return false; + } + + BYTE assignBuf[1]; + int bytesRecv = recv(s_hostConnectionSocket, (char *)assignBuf, 1, 0); + if (bytesRecv != 1) + { + app.DebugPrintf("Failed to receive small ID assignment from host\n"); + closesocket(s_hostConnectionSocket); + s_hostConnectionSocket = INVALID_SOCKET; + return false; + } + s_localSmallId = assignBuf[0]; + + app.DebugPrintf("Win64 LAN: Connected to %s:%d, assigned smallId=%d\n", ip, port, s_localSmallId); + + s_active = true; + s_connected = true; + + s_clientRecvThread = CreateThread(NULL, 0, ClientRecvThreadProc, NULL, 0, NULL); + + return true; +} + +bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void *data, int dataSize) +{ + if (sock == INVALID_SOCKET || dataSize <= 0) return false; + + EnterCriticalSection(&s_sendLock); + + BYTE header[4]; + header[0] = (BYTE)((dataSize >> 24) & 0xFF); + header[1] = (BYTE)((dataSize >> 16) & 0xFF); + header[2] = (BYTE)((dataSize >> 8) & 0xFF); + header[3] = (BYTE)(dataSize & 0xFF); + + int totalSent = 0; + int toSend = 4; + while (totalSent < toSend) + { + int sent = send(sock, (const char *)header + totalSent, toSend - totalSent, 0); + if (sent == SOCKET_ERROR || sent == 0) + { + LeaveCriticalSection(&s_sendLock); + return false; + } + totalSent += sent; + } + + totalSent = 0; + while (totalSent < dataSize) + { + int sent = send(sock, (const char *)data + totalSent, dataSize - totalSent, 0); + if (sent == SOCKET_ERROR || sent == 0) + { + LeaveCriticalSection(&s_sendLock); + return false; + } + totalSent += sent; + } + + LeaveCriticalSection(&s_sendLock); + return true; +} + +bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void *data, int dataSize) +{ + if (!s_active) return false; + + if (s_isHost) + { + SOCKET sock = GetSocketForSmallId(targetSmallId); + if (sock == INVALID_SOCKET) return false; + return SendOnSocket(sock, data, dataSize); + } + else + { + return SendOnSocket(s_hostConnectionSocket, data, dataSize); + } +} + +SOCKET WinsockNetLayer::GetSocketForSmallId(BYTE smallId) +{ + EnterCriticalSection(&s_connectionsLock); + for (size_t i = 0; i < s_connections.size(); i++) + { + if (s_connections[i].smallId == smallId && s_connections[i].active) + { + SOCKET sock = s_connections[i].tcpSocket; + LeaveCriticalSection(&s_connectionsLock); + return sock; + } + } + LeaveCriticalSection(&s_connectionsLock); + return INVALID_SOCKET; +} + +static bool RecvExact(SOCKET sock, BYTE *buf, int len) +{ + int totalRecv = 0; + while (totalRecv < len) + { + int r = recv(sock, (char *)buf + totalRecv, len - totalRecv, 0); + if (r <= 0) return false; + totalRecv += r; + } + return true; +} + +void WinsockNetLayer::HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char *data, unsigned int dataSize) +{ + INetworkPlayer *pPlayerFrom = g_NetworkManager.GetPlayerBySmallId(fromSmallId); + INetworkPlayer *pPlayerTo = g_NetworkManager.GetPlayerBySmallId(toSmallId); + + if (pPlayerFrom == NULL || pPlayerTo == NULL) return; + + if (s_isHost) + { + ::Socket *pSocket = pPlayerFrom->GetSocket(); + if (pSocket != NULL) + pSocket->pushDataToQueue(data, dataSize, false); + } + else + { + ::Socket *pSocket = pPlayerTo->GetSocket(); + if (pSocket != NULL) + pSocket->pushDataToQueue(data, dataSize, true); + } +} + +DWORD WINAPI WinsockNetLayer::AcceptThreadProc(LPVOID param) +{ + while (s_active) + { + SOCKET clientSocket = accept(s_listenSocket, NULL, NULL); + if (clientSocket == INVALID_SOCKET) + { + if (s_active) + app.DebugPrintf("accept() failed: %d\n", WSAGetLastError()); + break; + } + + int noDelay = 1; + setsockopt(clientSocket, IPPROTO_TCP, TCP_NODELAY, (const char *)&noDelay, sizeof(noDelay)); + + extern QNET_STATE _iQNetStubState; + if (_iQNetStubState != QNET_STATE_GAME_PLAY) + { + app.DebugPrintf("Win64 LAN: Rejecting connection, game not ready\n"); + closesocket(clientSocket); + continue; + } + + BYTE assignedSmallId; + EnterCriticalSection(&s_freeSmallIdLock); + if (!s_freeSmallIds.empty()) + { + assignedSmallId = s_freeSmallIds.back(); + s_freeSmallIds.pop_back(); + } + else if (s_nextSmallId < MINECRAFT_NET_MAX_PLAYERS) + { + assignedSmallId = s_nextSmallId++; + } + else + { + LeaveCriticalSection(&s_freeSmallIdLock); + app.DebugPrintf("Win64 LAN: Server full, rejecting connection\n"); + closesocket(clientSocket); + continue; + } + LeaveCriticalSection(&s_freeSmallIdLock); + + BYTE assignBuf[1] = { assignedSmallId }; + int sent = send(clientSocket, (const char *)assignBuf, 1, 0); + if (sent != 1) + { + app.DebugPrintf("Failed to send small ID to client\n"); + closesocket(clientSocket); + continue; + } + + Win64RemoteConnection conn; + conn.tcpSocket = clientSocket; + conn.smallId = assignedSmallId; + conn.active = true; + conn.recvThread = NULL; + + EnterCriticalSection(&s_connectionsLock); + s_connections.push_back(conn); + int connIdx = (int)s_connections.size() - 1; + LeaveCriticalSection(&s_connectionsLock); + + app.DebugPrintf("Win64 LAN: Client connected, assigned smallId=%d\n", assignedSmallId); + + IQNetPlayer *qnetPlayer = &IQNet::m_player[assignedSmallId]; + + extern void Win64_SetupRemoteQNetPlayer(IQNetPlayer *player, BYTE smallId, bool isHost, bool isLocal); + Win64_SetupRemoteQNetPlayer(qnetPlayer, assignedSmallId, false, false); + + extern CPlatformNetworkManagerStub *g_pPlatformNetworkManager; + g_pPlatformNetworkManager->NotifyPlayerJoined(qnetPlayer); + + DWORD *threadParam = new DWORD; + *threadParam = connIdx; + HANDLE hThread = CreateThread(NULL, 0, RecvThreadProc, threadParam, 0, NULL); + + EnterCriticalSection(&s_connectionsLock); + if (connIdx < (int)s_connections.size()) + s_connections[connIdx].recvThread = hThread; + LeaveCriticalSection(&s_connectionsLock); + } + return 0; +} + +DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param) +{ + DWORD connIdx = *(DWORD *)param; + delete (DWORD *)param; + + EnterCriticalSection(&s_connectionsLock); + if (connIdx >= (DWORD)s_connections.size()) + { + LeaveCriticalSection(&s_connectionsLock); + return 0; + } + SOCKET sock = s_connections[connIdx].tcpSocket; + BYTE clientSmallId = s_connections[connIdx].smallId; + LeaveCriticalSection(&s_connectionsLock); + + BYTE *recvBuf = new BYTE[WIN64_NET_RECV_BUFFER_SIZE]; + + while (s_active) + { + BYTE header[4]; + if (!RecvExact(sock, header, 4)) + { + app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (header)\n", clientSmallId); + break; + } + + int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3]; + + if (packetSize <= 0 || packetSize > WIN64_NET_RECV_BUFFER_SIZE) + { + app.DebugPrintf("Win64 LAN: Invalid packet size %d from client smallId=%d\n", packetSize, clientSmallId); + break; + } + + if (!RecvExact(sock, recvBuf, packetSize)) + { + app.DebugPrintf("Win64 LAN: Client smallId=%d disconnected (body)\n", clientSmallId); + break; + } + + HandleDataReceived(clientSmallId, s_hostSmallId, recvBuf, packetSize); + } + + delete[] recvBuf; + + EnterCriticalSection(&s_connectionsLock); + for (size_t i = 0; i < s_connections.size(); i++) + { + if (s_connections[i].smallId == clientSmallId) + { + s_connections[i].active = false; + closesocket(s_connections[i].tcpSocket); + s_connections[i].tcpSocket = INVALID_SOCKET; + break; + } + } + LeaveCriticalSection(&s_connectionsLock); + + EnterCriticalSection(&s_disconnectLock); + s_disconnectedSmallIds.push_back(clientSmallId); + LeaveCriticalSection(&s_disconnectLock); + + return 0; +} + +bool WinsockNetLayer::PopDisconnectedSmallId(BYTE *outSmallId) +{ + bool found = false; + EnterCriticalSection(&s_disconnectLock); + if (!s_disconnectedSmallIds.empty()) + { + *outSmallId = s_disconnectedSmallIds.back(); + s_disconnectedSmallIds.pop_back(); + found = true; + } + LeaveCriticalSection(&s_disconnectLock); + return found; +} + +void WinsockNetLayer::PushFreeSmallId(BYTE smallId) +{ + EnterCriticalSection(&s_freeSmallIdLock); + s_freeSmallIds.push_back(smallId); + LeaveCriticalSection(&s_freeSmallIdLock); +} + +DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param) +{ + BYTE *recvBuf = new BYTE[WIN64_NET_RECV_BUFFER_SIZE]; + + while (s_active && s_hostConnectionSocket != INVALID_SOCKET) + { + BYTE header[4]; + if (!RecvExact(s_hostConnectionSocket, header, 4)) + { + app.DebugPrintf("Win64 LAN: Disconnected from host (header)\n"); + break; + } + + int packetSize = (header[0] << 24) | (header[1] << 16) | (header[2] << 8) | header[3]; + + if (packetSize <= 0 || packetSize > WIN64_NET_RECV_BUFFER_SIZE) + { + app.DebugPrintf("Win64 LAN: Invalid packet size %d from host\n", packetSize); + break; + } + + if (!RecvExact(s_hostConnectionSocket, recvBuf, packetSize)) + { + app.DebugPrintf("Win64 LAN: Disconnected from host (body)\n"); + break; + } + + HandleDataReceived(s_hostSmallId, s_localSmallId, recvBuf, packetSize); + } + + delete[] recvBuf; + + s_connected = false; + return 0; +} + +bool WinsockNetLayer::StartAdvertising(int gamePort, const wchar_t *hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer) +{ + if (s_advertising) return true; + if (!s_initialized) return false; + + EnterCriticalSection(&s_advertiseLock); + memset(&s_advertiseData, 0, sizeof(s_advertiseData)); + s_advertiseData.magic = WIN64_LAN_BROADCAST_MAGIC; + s_advertiseData.netVersion = netVer; + s_advertiseData.gamePort = (WORD)gamePort; + wcsncpy_s(s_advertiseData.hostName, 32, hostName, _TRUNCATE); + s_advertiseData.playerCount = 1; + s_advertiseData.maxPlayers = MINECRAFT_NET_MAX_PLAYERS; + s_advertiseData.gameHostSettings = gameSettings; + s_advertiseData.texturePackParentId = texPackId; + s_advertiseData.subTexturePackId = subTexId; + s_advertiseData.isJoinable = 0; + s_hostGamePort = gamePort; + LeaveCriticalSection(&s_advertiseLock); + + s_advertiseSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (s_advertiseSock == INVALID_SOCKET) + { + app.DebugPrintf("Win64 LAN: Failed to create advertise socket: %d\n", WSAGetLastError()); + return false; + } + + s_localAdvertiseMap = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Win64LocalAdvertiseState), WIN64_LAN_LOCAL_ADVERTISE_MAP_NAMEA); + if (s_localAdvertiseMap != NULL) + { + s_localAdvertiseState = (Win64LocalAdvertiseState *)MapViewOfFile(s_localAdvertiseMap, FILE_MAP_WRITE, 0, 0, sizeof(Win64LocalAdvertiseState)); + if (s_localAdvertiseState != NULL) + { + memset(s_localAdvertiseState, 0, sizeof(Win64LocalAdvertiseState)); + } + else + { + CloseHandle(s_localAdvertiseMap); + s_localAdvertiseMap = NULL; + } + } + + BOOL broadcast = TRUE; + setsockopt(s_advertiseSock, SOL_SOCKET, SO_BROADCAST, (const char *)&broadcast, sizeof(broadcast)); + + s_advertising = true; + s_advertiseThread = CreateThread(NULL, 0, AdvertiseThreadProc, NULL, 0, NULL); + + app.DebugPrintf("Win64 LAN: Started advertising on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); + return true; +} + +void WinsockNetLayer::StopAdvertising() +{ + s_advertising = false; + + if (s_advertiseSock != INVALID_SOCKET) + { + closesocket(s_advertiseSock); + s_advertiseSock = INVALID_SOCKET; + } + + if (s_advertiseThread != NULL) + { + WaitForSingleObject(s_advertiseThread, 2000); + CloseHandle(s_advertiseThread); + s_advertiseThread = NULL; + } + + if (s_localAdvertiseState != NULL) + { + memset(s_localAdvertiseState, 0, sizeof(Win64LocalAdvertiseState)); + UnmapViewOfFile(s_localAdvertiseState); + s_localAdvertiseState = NULL; + } + if (s_localAdvertiseMap != NULL) + { + CloseHandle(s_localAdvertiseMap); + s_localAdvertiseMap = NULL; + } +} + +void WinsockNetLayer::UpdateAdvertisePlayerCount(BYTE count) +{ + EnterCriticalSection(&s_advertiseLock); + s_advertiseData.playerCount = count; + LeaveCriticalSection(&s_advertiseLock); +} + +void WinsockNetLayer::UpdateAdvertiseJoinable(bool joinable) +{ + EnterCriticalSection(&s_advertiseLock); + s_advertiseData.isJoinable = joinable ? 1 : 0; + LeaveCriticalSection(&s_advertiseLock); +} + +DWORD WINAPI WinsockNetLayer::AdvertiseThreadProc(LPVOID param) +{ + struct sockaddr_in lanBroadcastAddr; + memset(&lanBroadcastAddr, 0, sizeof(lanBroadcastAddr)); + lanBroadcastAddr.sin_family = AF_INET; + lanBroadcastAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT); + lanBroadcastAddr.sin_addr.s_addr = INADDR_BROADCAST; + + struct sockaddr_in loopbackAddr; + memset(&loopbackAddr, 0, sizeof(loopbackAddr)); + loopbackAddr.sin_family = AF_INET; + loopbackAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT); + loopbackAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + + while (s_advertising) + { + EnterCriticalSection(&s_advertiseLock); + Win64LANBroadcast data = s_advertiseData; + LeaveCriticalSection(&s_advertiseLock); + + if (s_localAdvertiseState != NULL) + { + s_localAdvertiseState->magic = WIN64_LAN_LOCAL_ADVERTISE_MAGIC; + s_localAdvertiseState->tick = GetTickCount(); + s_localAdvertiseState->broadcast = data; + } + + int sentLan = sendto(s_advertiseSock, (const char *)&data, sizeof(data), 0, + (struct sockaddr *)&lanBroadcastAddr, sizeof(lanBroadcastAddr)); + int sentLoopback = sendto(s_advertiseSock, (const char *)&data, sizeof(data), 0, + (struct sockaddr *)&loopbackAddr, sizeof(loopbackAddr)); + + if ((sentLan == SOCKET_ERROR || sentLoopback == SOCKET_ERROR) && s_advertising) + { + app.DebugPrintf("Win64 LAN: Advertise sendto failed: %d (lan=%d loopback=%d)\n", WSAGetLastError(), sentLan, sentLoopback); + } + + Sleep(1000); + } + + return 0; +} + +bool WinsockNetLayer::StartDiscovery() +{ + if (s_discovering) return true; + if (!s_initialized) return false; + + s_discoverySock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (s_discoverySock == INVALID_SOCKET) + { + app.DebugPrintf("Win64 LAN: Failed to create discovery socket: %d\n", WSAGetLastError()); + return false; + } + + BOOL reuseAddr = TRUE; + setsockopt(s_discoverySock, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuseAddr, sizeof(reuseAddr)); + + struct sockaddr_in bindAddr; + memset(&bindAddr, 0, sizeof(bindAddr)); + bindAddr.sin_family = AF_INET; + bindAddr.sin_port = htons(WIN64_LAN_DISCOVERY_PORT); + bindAddr.sin_addr.s_addr = INADDR_ANY; + + if (::bind(s_discoverySock, (struct sockaddr *)&bindAddr, sizeof(bindAddr)) == SOCKET_ERROR) + { + app.DebugPrintf("Win64 LAN: Discovery bind failed: %d\n", WSAGetLastError()); + closesocket(s_discoverySock); + s_discoverySock = INVALID_SOCKET; + return false; + } + + DWORD timeout = 500; + setsockopt(s_discoverySock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout)); + + s_discovering = true; + s_discoveryThread = CreateThread(NULL, 0, DiscoveryThreadProc, NULL, 0, NULL); + + app.DebugPrintf("Win64 LAN: Listening for LAN games on UDP port %d\n", WIN64_LAN_DISCOVERY_PORT); + return true; +} + +void WinsockNetLayer::StopDiscovery() +{ + s_discovering = false; + + if (s_discoverySock != INVALID_SOCKET) + { + closesocket(s_discoverySock); + s_discoverySock = INVALID_SOCKET; + } + + if (s_discoveryThread != NULL) + { + WaitForSingleObject(s_discoveryThread, 2000); + CloseHandle(s_discoveryThread); + s_discoveryThread = NULL; + } + + EnterCriticalSection(&s_discoveryLock); + s_discoveredSessions.clear(); + LeaveCriticalSection(&s_discoveryLock); +} + +std::vector WinsockNetLayer::GetDiscoveredSessions() +{ + std::vector result; + EnterCriticalSection(&s_discoveryLock); + result = s_discoveredSessions; + LeaveCriticalSection(&s_discoveryLock); + + Win64LANSession localSession; + if (TryReadLocalAdvertiseSession(&localSession)) + { + // Merge local fallback session into the normal discovery set and de-duplicate + // by endpoint so UI only shows one row per host. + bool found = false; + for (size_t i = 0; i < result.size(); i++) + { + if (strcmp(result[i].hostIP, localSession.hostIP) == 0 && + result[i].hostPort == localSession.hostPort) + { + result[i] = localSession; + found = true; + break; + } + } + if (!found) + { + result.push_back(localSession); + } + } + + return result; +} + +DWORD WINAPI WinsockNetLayer::DiscoveryThreadProc(LPVOID param) +{ + char recvBuf[512]; + + while (s_discovering) + { + struct sockaddr_in senderAddr; + int senderLen = sizeof(senderAddr); + + int recvLen = recvfrom(s_discoverySock, recvBuf, sizeof(recvBuf), 0, + (struct sockaddr *)&senderAddr, &senderLen); + + if (recvLen == SOCKET_ERROR) + { + continue; + } + + if (recvLen < (int)sizeof(Win64LANBroadcast)) + continue; + + Win64LANBroadcast *broadcast = (Win64LANBroadcast *)recvBuf; + if (broadcast->magic != WIN64_LAN_BROADCAST_MAGIC) + continue; + + char senderIP[64]; + inet_ntop(AF_INET, &senderAddr.sin_addr, senderIP, sizeof(senderIP)); + + DWORD now = GetTickCount(); + + EnterCriticalSection(&s_discoveryLock); + + bool found = false; + for (size_t i = 0; i < s_discoveredSessions.size(); i++) + { + if (strcmp(s_discoveredSessions[i].hostIP, senderIP) == 0 && + s_discoveredSessions[i].hostPort == (int)broadcast->gamePort) + { + s_discoveredSessions[i].netVersion = broadcast->netVersion; + wcsncpy_s(s_discoveredSessions[i].hostName, 32, broadcast->hostName, _TRUNCATE); + s_discoveredSessions[i].playerCount = broadcast->playerCount; + s_discoveredSessions[i].maxPlayers = broadcast->maxPlayers; + s_discoveredSessions[i].gameHostSettings = broadcast->gameHostSettings; + s_discoveredSessions[i].texturePackParentId = broadcast->texturePackParentId; + s_discoveredSessions[i].subTexturePackId = broadcast->subTexturePackId; + s_discoveredSessions[i].isJoinable = (broadcast->isJoinable != 0); + s_discoveredSessions[i].lastSeenTick = now; + found = true; + break; + } + } + + if (!found) + { + Win64LANSession session; + memset(&session, 0, sizeof(session)); + strncpy_s(session.hostIP, sizeof(session.hostIP), senderIP, _TRUNCATE); + session.hostPort = (int)broadcast->gamePort; + session.netVersion = broadcast->netVersion; + wcsncpy_s(session.hostName, 32, broadcast->hostName, _TRUNCATE); + session.playerCount = broadcast->playerCount; + session.maxPlayers = broadcast->maxPlayers; + session.gameHostSettings = broadcast->gameHostSettings; + session.texturePackParentId = broadcast->texturePackParentId; + session.subTexturePackId = broadcast->subTexturePackId; + session.isJoinable = (broadcast->isJoinable != 0); + session.lastSeenTick = now; + s_discoveredSessions.push_back(session); + + app.DebugPrintf("Win64 LAN: Discovered game \"%ls\" at %s:%d\n", + session.hostName, session.hostIP, session.hostPort); + } + + for (size_t i = s_discoveredSessions.size(); i > 0; i--) + { + if (now - s_discoveredSessions[i - 1].lastSeenTick > 5000) + { + app.DebugPrintf("Win64 LAN: Session \"%ls\" at %s timed out\n", + s_discoveredSessions[i - 1].hostName, s_discoveredSessions[i - 1].hostIP); + s_discoveredSessions.erase(s_discoveredSessions.begin() + (i - 1)); + } + } + + LeaveCriticalSection(&s_discoveryLock); + } + + return 0; +} + +#endif diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h new file mode 100644 index 000000000..56f86ec3c --- /dev/null +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h @@ -0,0 +1,168 @@ +#pragma once + +#ifdef _WINDOWS64 + +#include +#include +#include +#include "..\..\Common\Network\NetworkPlayerInterface.h" + +#pragma comment(lib, "Ws2_32.lib") + +#define WIN64_NET_DEFAULT_PORT 25565 +#define WIN64_NET_MAX_CLIENTS 7 +#define WIN64_NET_RECV_BUFFER_SIZE 65536 +#define WIN64_LAN_DISCOVERY_PORT 25566 +#define WIN64_LAN_BROADCAST_MAGIC 0x4D434C4E +// Local process-to-process fallback for LAN discovery on the same machine. +// This avoids relying solely on UDP loopback delivery timing. +#define WIN64_LAN_LOCAL_ADVERTISE_MAGIC 0x4D434C41 +#define WIN64_LAN_LOCAL_ADVERTISE_MAP_NAMEA "Local\\MinecraftWin64LanAdvertise" + +class Socket; + +#pragma pack(push, 1) +struct Win64LANBroadcast +{ + DWORD magic; + WORD netVersion; + WORD gamePort; + wchar_t hostName[32]; + BYTE playerCount; + BYTE maxPlayers; + DWORD gameHostSettings; + DWORD texturePackParentId; + BYTE subTexturePackId; + BYTE isJoinable; +}; +#pragma pack(pop) + +struct Win64LANSession +{ + char hostIP[64]; + int hostPort; + wchar_t hostName[32]; + unsigned short netVersion; + unsigned char playerCount; + unsigned char maxPlayers; + unsigned int gameHostSettings; + unsigned int texturePackParentId; + unsigned char subTexturePackId; + bool isJoinable; + DWORD lastSeenTick; +}; + +struct Win64RemoteConnection +{ + SOCKET tcpSocket; + BYTE smallId; + HANDLE recvThread; + volatile bool active; +}; + +#pragma pack(push, 1) +struct Win64LocalAdvertiseState +{ + // Validity marker for shared-memory discovery payload. + DWORD magic; + // Last update tick written by the hosting process. + DWORD tick; + // Same payload as UDP LAN advertisement, mirrored for local readers. + Win64LANBroadcast broadcast; +}; +#pragma pack(pop) + +class WinsockNetLayer +{ +public: + static bool Initialize(); + static void Shutdown(); + + static bool HostGame(const char *bindIp, int port); + static bool JoinGame(const char *ip, int port); + + static bool SendToSmallId(BYTE targetSmallId, const void *data, int dataSize); + static bool SendOnSocket(SOCKET sock, const void *data, int dataSize); + + static bool IsHosting() { return s_isHost; } + static bool IsConnected() { return s_connected; } + static bool IsActive() { return s_active; } + + static BYTE GetLocalSmallId() { return s_localSmallId; } + static BYTE GetHostSmallId() { return s_hostSmallId; } + + static SOCKET GetSocketForSmallId(BYTE smallId); + + static void HandleDataReceived(BYTE fromSmallId, BYTE toSmallId, unsigned char *data, unsigned int dataSize); + + static bool PopDisconnectedSmallId(BYTE *outSmallId); + static void PushFreeSmallId(BYTE smallId); + + static bool StartAdvertising(int gamePort, const wchar_t *hostName, unsigned int gameSettings, unsigned int texPackId, unsigned char subTexId, unsigned short netVer); + static void StopAdvertising(); + static void UpdateAdvertisePlayerCount(BYTE count); + static void UpdateAdvertiseJoinable(bool joinable); + + static bool StartDiscovery(); + static void StopDiscovery(); + static std::vector GetDiscoveredSessions(); + + static int GetHostPort() { return s_hostGamePort; } + +private: + static DWORD WINAPI AcceptThreadProc(LPVOID param); + static DWORD WINAPI RecvThreadProc(LPVOID param); + static DWORD WINAPI ClientRecvThreadProc(LPVOID param); + static DWORD WINAPI AdvertiseThreadProc(LPVOID param); + static DWORD WINAPI DiscoveryThreadProc(LPVOID param); + + static SOCKET s_listenSocket; + static SOCKET s_hostConnectionSocket; + static HANDLE s_acceptThread; + static HANDLE s_clientRecvThread; + + static bool s_isHost; + static bool s_connected; + static bool s_active; + static bool s_initialized; + + static BYTE s_localSmallId; + static BYTE s_hostSmallId; + static BYTE s_nextSmallId; + + static CRITICAL_SECTION s_sendLock; + static CRITICAL_SECTION s_connectionsLock; + + static std::vector s_connections; + + static SOCKET s_advertiseSock; + static HANDLE s_advertiseThread; + static volatile bool s_advertising; + static Win64LANBroadcast s_advertiseData; + static CRITICAL_SECTION s_advertiseLock; + static int s_hostGamePort; + static HANDLE s_localAdvertiseMap; + static Win64LocalAdvertiseState *s_localAdvertiseState; + + static SOCKET s_discoverySock; + static HANDLE s_discoveryThread; + static volatile bool s_discovering; + static CRITICAL_SECTION s_discoveryLock; + static std::vector s_discoveredSessions; + + static CRITICAL_SECTION s_disconnectLock; + static std::vector s_disconnectedSmallIds; + + static CRITICAL_SECTION s_freeSmallIdLock; + static std::vector s_freeSmallIds; +}; + +extern bool g_Win64MultiplayerHost; +extern bool g_Win64HostBindSpecified; +extern int g_Win64HostBindPort; +extern char g_Win64HostBindIP[256]; +extern bool g_Win64TargetEnabled; +extern int g_Win64TargetPort; +extern char g_Win64TargetIP[256]; + +#endif diff --git a/Minecraft.Client/Windows64/Windows64_App.cpp b/Minecraft.Client/Windows64/Windows64_App.cpp index bba33cadc..dbc1bfc5e 100644 --- a/Minecraft.Client/Windows64/Windows64_App.cpp +++ b/Minecraft.Client/Windows64/Windows64_App.cpp @@ -57,7 +57,8 @@ void CConsoleMinecraftApp::TemporaryCreateGameStart() Minecraft *pMinecraft=Minecraft::GetInstance(); app.ReleaseSaveThumbnail(); ProfileManager.SetLockedProfile(0); - pMinecraft->user->name = L"Windows"; + extern wchar_t g_Win64UsernameW[17]; + pMinecraft->user->name = g_Win64UsernameW; app.ApplyGameSettingsChanged(0); ////////////////////////////////////////////////////////////////////////////////////////////// From CScene_MultiGameJoinLoad::OnInit diff --git a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp index c2034b8c7..552bc01ff 100644 --- a/Minecraft.Client/Windows64/Windows64_Minecraft.cpp +++ b/Minecraft.Client/Windows64/Windows64_Minecraft.cpp @@ -37,6 +37,7 @@ #include "Resource.h" #include "..\..\Minecraft.World\compression.h" #include "..\..\Minecraft.World\OldChunkStorage.h" +#include "Network\WinsockNetLayer.h" #include "Xbox/resource.h" @@ -83,11 +84,37 @@ BOOL g_bWidescreen = TRUE; int g_iScreenWidth = 1920; int g_iScreenHeight = 1080; +char g_Win64Username[17] = {0}; +wchar_t g_Win64UsernameW[17] = {0}; // Fullscreen toggle state static bool g_isFullscreen = false; static WINDOWPLACEMENT g_wpPrev = { sizeof(g_wpPrev) }; +static bool Win64_GetCmdArgValue(const char *cmdLine, const char *keyWithSpace, char *outValue, int outValueLen) +{ + if (cmdLine == NULL || keyWithSpace == NULL || outValue == NULL || outValueLen <= 0) + return false; + + const char *found = strstr(cmdLine, keyWithSpace); + if (found == NULL) + return false; + + found += strlen(keyWithSpace); + while (*found == ' ') found++; + if (*found == 0) + return false; + + int i = 0; + while (found[i] != 0 && found[i] != ' ' && i < (outValueLen - 1)) + { + outValue[i] = found[i]; + i++; + } + outValue[i] = 0; + return (i > 0); +} + void DefineActions(void) { // The app needs to define the actions required, and the possible mappings for these @@ -743,8 +770,86 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, //g_iScreenWidth = 960; //g_iScreenHeight = 544; } + + char cmdLineA[1024]; + strncpy_s(cmdLineA, sizeof(cmdLineA), lpCmdLine, _TRUNCATE); + + char *nameArg = strstr(cmdLineA, "-name "); + if (nameArg) + { + nameArg += 6; + while (*nameArg == ' ') nameArg++; + char nameBuf[17]; + int n = 0; + while (nameArg[n] && nameArg[n] != ' ' && n < 16) { nameBuf[n] = nameArg[n]; n++; } + nameBuf[n] = 0; + strncpy_s(g_Win64Username, 17, nameBuf, _TRUNCATE); + } + + char targetToken[256] = {0}; + if (Win64_GetCmdArgValue(cmdLineA, "-target ", targetToken, sizeof(targetToken))) + { + // CLI format: -target IP:PORT + // This does not auto-join; it adds one explicit endpoint candidate to discovery. + const char *ipStart = targetToken; + const char *colon = strchr(targetToken, ':'); + if (colon != NULL) + { + char ipOnly[256] = {0}; + size_t ipLen = (size_t)(colon - ipStart); + if (ipLen >= sizeof(ipOnly)) ipLen = sizeof(ipOnly) - 1; + memcpy(ipOnly, ipStart, ipLen); + ipOnly[ipLen] = 0; + + strncpy_s(g_Win64TargetIP, sizeof(g_Win64TargetIP), ipOnly, _TRUNCATE); + g_Win64TargetPort = atoi(colon + 1); + } + else + { + strncpy_s(g_Win64TargetIP, sizeof(g_Win64TargetIP), targetToken, _TRUNCATE); + } + if (g_Win64TargetPort <= 0) g_Win64TargetPort = WIN64_NET_DEFAULT_PORT; + g_Win64TargetEnabled = true; + app.DebugPrintf("Win64 LAN: Target server set to %s:%d\n", g_Win64TargetIP, g_Win64TargetPort); + } + + char hostToken[256] = {0}; + if (Win64_GetCmdArgValue(cmdLineA, "-host ", hostToken, sizeof(hostToken))) + { + // CLI format: -host IP:PORT + const char *ipStart = hostToken; + const char *colon = strchr(hostToken, ':'); + if (colon != NULL) + { + char ipOnly[256] = {0}; + size_t ipLen = (size_t)(colon - ipStart); + if (ipLen >= sizeof(ipOnly)) ipLen = sizeof(ipOnly) - 1; + memcpy(ipOnly, ipStart, ipLen); + ipOnly[ipLen] = 0; + + strncpy_s(g_Win64HostBindIP, sizeof(g_Win64HostBindIP), ipOnly, _TRUNCATE); + g_Win64HostBindPort = atoi(colon + 1); + } + else + { + strncpy_s(g_Win64HostBindIP, sizeof(g_Win64HostBindIP), hostToken, _TRUNCATE); + } + if (g_Win64HostBindPort <= 0) g_Win64HostBindPort = WIN64_NET_DEFAULT_PORT; + g_Win64HostBindSpecified = true; + app.DebugPrintf("Win64 LAN: Host bind target set to %s:%d\n", g_Win64HostBindIP, g_Win64HostBindPort); + } } + if (g_Win64Username[0] == 0) + { + DWORD sz = 17; + if (!GetUserNameA(g_Win64Username, &sz)) + strncpy_s(g_Win64Username, 17, "Player", _TRUNCATE); + g_Win64Username[16] = 0; + } + + MultiByteToWideChar(CP_ACP, 0, g_Win64Username, -1, g_Win64UsernameW, 17); + // Initialize global strings MyRegisterClass(hInstance); @@ -910,7 +1015,17 @@ int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, // ProfileManager for XN_LIVE_INVITE_ACCEPTED for QNet. g_NetworkManager.Initialise(); + for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) + { + IQNet::m_player[i].m_smallId = (BYTE)i; + IQNet::m_player[i].m_isRemote = false; + IQNet::m_player[i].m_isHostPlayer = (i == 0); + swprintf_s(IQNet::m_player[i].m_gamertag, 32, L"Player%d", i); + } + extern wchar_t g_Win64UsernameW[17]; + wcscpy_s(IQNet::m_player[0].m_gamertag, 32, g_Win64UsernameW); + WinsockNetLayer::Initialize(); // 4J-PB moved further down //app.InitGameSettings(); @@ -1538,4 +1653,4 @@ void MemPixStuff() PIXAddNamedCounter(((float)allSectsTotal)/(4096.0f),"MemSect total pages"); } -#endif \ No newline at end of file +#endif diff --git a/Minecraft.World/x64headers/extraX64.h b/Minecraft.World/x64headers/extraX64.h index d06b24207..3d95a6ed3 100644 --- a/Minecraft.World/x64headers/extraX64.h +++ b/Minecraft.World/x64headers/extraX64.h @@ -215,10 +215,17 @@ public: int GetUserIndex(); void SetCustomDataValue(ULONG_PTR ulpCustomDataValue); ULONG_PTR GetCustomDataValue(); + + BYTE m_smallId; + bool m_isRemote; + bool m_isHostPlayer; + wchar_t m_gamertag[32]; private: ULONG_PTR m_customData; }; +void Win64_SetupRemoteQNetPlayer(IQNetPlayer *player, BYTE smallId, bool isHost, bool isLocal); + const int QNET_GETSENDQUEUESIZE_SECONDARY_TYPE = 0; const int QNET_GETSENDQUEUESIZE_MESSAGES = 0; const int QNET_GETSENDQUEUESIZE_BYTES = 0; @@ -309,9 +316,12 @@ public: bool IsHost(); HRESULT JoinGameFromInviteInfo(DWORD dwUserIndex, DWORD dwUserMask, const INVITE_INFO *pInviteInfo); void HostGame(); + void ClientJoinGame(); void EndGame(); - static IQNetPlayer m_player[4]; + static IQNetPlayer m_player[MINECRAFT_NET_MAX_PLAYERS]; + static DWORD s_playerCount; + static bool s_isHosting; }; #ifdef _DURANGO diff --git a/README.md b/README.md index f32b11fc5..0a7313175 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,35 @@ This project contains the source code of Minecraft Legacy Console Edition v1.3.0 - Disabled V-Sync for better performance - Added a high-resolution timer path on Windows for smoother high-FPS gameplay timing - Device's screen resolution will be used as the game resolution instead of using a fixed resolution (1920x1080) +- Added Windows64 LAN & Target Server multiplayer (host/join via in-game Join Game menu) + +## Multiplayer (Windows64) + +The multiplayer implementation was added with reference to: + +- [LCEMP/LCEMP](https://github.com/LCEMP/LCEMP) + +### Command Line Options + +- `-name `: Set the local player name (max 16 chars) +- `-host `: Set host bind address/port when creating a game (default port: `25565`) +- `-target `: Add a direct server candidate to the Join Game list (default port: `25565`) + +### Usage Example + +Host: + +```powershell +Minecraft.Client.exe -name HostPlayer -host 0.0.0.0:25565 +``` + +Join: + +```powershell +Minecraft.Client.exe -name ClientPlayer -target 192.168.0.10:25565 +``` + +Then open **Play Game** -> **Join Game** in-game and select the discovered/target session. ## Controls (Keyboard & Mouse)