Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

13.5 KB
Raw Blame
#pragma once

#include "NGMP_include.h"
#include "OnlineServices_RoomsInterface.h"
#include "GameNetwork/GameInfo.h"
#include <chrono>
#include "Common/PlayerList.h"
#include "Common/Player.h"
#include "GameClient/InGameUI.h"
#include "GameLogic/VictoryConditions.h"
#include <atomic>
#include <set>

extern NGMPGame* TheNGMPGame;

struct LobbyMemberEntry : public NetworkMemberBase
{

	uint16_t preferredPort;
	// NOTE: NetworkMemberBase is not deserialized

	int side = -1;
	int color = -1;
	int team = -1;
	int startpos = -1;
	bool has_map = false;

	uint16_t m_SlotIndex = 999999;
	uint16_t m_SlotState = SlotState::SLOT_OPEN;

	std::string region;
	std::string middlewareUserID;
	int latency = 0;

	bool IsHuman() const
	{
		return user_id != -1 && m_SlotState == SlotState::SLOT_PLAYER;
	}
};

enum class ELobbyType
{
	UNKNOWN = -1,
	CustomGame = 0,
	QuickMatch = 1
};

struct LobbyEntry
{
	int64_t lobbyID = -1;

	int64_t owner = -1;
	std::string name;
	std::string map_name;
	std::string map_path;
	bool map_official = false;
	int current_players = 0;
	int max_players = 0;
	bool vanilla_teams = false;
	uint32_t starting_cash = 0;
	bool limit_superweapons = false;
	bool track_stats = false;
	bool allow_observers = false;
	uint16_t max_cam_height = 0;

	uint32_t exe_crc = 0;
	uint32_t ini_crc = 0;

	uint64_t match_id = 0;

	ELobbyType lobby_type = ELobbyType::UNKNOWN;

	int rng_seed = -1;

	bool passworded = false;
	std::string password;

	std::vector<LobbyMemberEntry> members;

	std::string region;
	int latency = 0;
};

enum class EJoinLobbyResult
{
	JoinLobbyResult_Success, // The room was joined.
	JoinLobbyResult_FullRoom,       // The room is full.
	JoinLobbyResult_BadPassword,    // An incorrect password (or none) was given for a passworded room.
	JoinLobbyResult_JoinFailed, // Generic failure.
	JoinLobbyResult_AnticheatMismatch // Anticheat mismatch
};

enum class ELobbyJoinability
{
	LobbyJoinability_Public,
	LobbyJoinability_FriendsOnly,
};

struct LobbyMemberEntry;
struct LobbyEntry;

class NGMP_OnlineServices_LobbyInterface
{
public:
	NGMP_OnlineServices_LobbyInterface();
	void StopMatchStartCountdownIfRunning();
	void SearchForLobbies(std::function<void()> onStartCallback, std::function<void(std::vector<LobbyEntry>)> onCompleteCallback);
	void DeregisterForSearchForLobbiesCallback()
	{
		m_fnCallbackSearchForLobbiesComplete = nullptr;
	}
	std::function<void(std::vector<LobbyEntry>)> m_fnCallbackSearchForLobbiesComplete = nullptr;

	std::function<void(std::string)> m_fnCallbackMatchmakingMessage = nullptr;
	void RegisterForMatchmakingMessageCallback(std::function<void(std::string)> cb)
	{
		m_fnCallbackMatchmakingMessage = cb;
	}

	void DeregisterForMatchmakingMessageCallback()
	{
		m_fnCallbackMatchmakingMessage = nullptr;
	}

	void InvokeMatchmakingMessageCallback(std::string str)
	{
		if (m_fnCallbackMatchmakingMessage != nullptr)
		{
			m_fnCallbackMatchmakingMessage(str);
		}
	}

	void InvokeMatchmakingStartGameCallback()
	{
		if (m_fnCallbackMatchmakingStartGame != nullptr)
		{
			m_fnCallbackMatchmakingStartGame();
		}
	}

	std::function<void()> m_fnCallbackMatchmakingStartGame = nullptr;
	void RegisterForMatchmakingStartGameCallback(std::function<void()> cb)
	{
		m_fnCallbackMatchmakingStartGame = cb;
	}

	void DeregisterForMatchmakingStartGameCallback()
	{
		m_fnCallbackMatchmakingStartGame = nullptr;
	}

	std::function<void()> m_fnCallbackMatchmakingMatchFound = nullptr;
	void RegisterForMatchmakingMatchFoundCallback(std::function<void()> cb)
	{
		m_fnCallbackMatchmakingMatchFound = cb;
	}

	void DeRegisterForMatchmakingMatchFoundCallback()
	{
		m_fnCallbackMatchmakingMatchFound = nullptr;
	}

	void InvokeMatchmakingMatchFoundCallback()
	{
		if (m_fnCallbackMatchmakingMatchFound != nullptr)
		{
			m_fnCallbackMatchmakingMatchFound();
		}
	}

	std::function<void()> m_fnCallbackMatchmakingRequeue = nullptr;
	void RegisterForMatchmakingRequeueCallback(std::function<void()> cb)
	{
		m_fnCallbackMatchmakingRequeue = cb;
	}

	void DeregisterForMatchmakingRequeueCallback()
	{
		m_fnCallbackMatchmakingRequeue = nullptr;
	}

	void InvokeMatchmakingRequeueCallback()
	{
		if (m_fnCallbackMatchmakingRequeue != nullptr)
		{
			m_fnCallbackMatchmakingRequeue();
		}
	}

	// timeoutMs: how long to wait for the next step; countdownMs: start countdown length, 0 while setting up, -1 if not sent
	std::function<void(int, int)> m_fnCallbackMatchmakingSetupProgress = nullptr;
	void RegisterForMatchmakingSetupProgressCallback(std::function<void(int, int)> cb)
	{
		m_fnCallbackMatchmakingSetupProgress = cb;
	}

	void DeregisterForMatchmakingSetupProgressCallback()
	{
		m_fnCallbackMatchmakingSetupProgress = nullptr;
	}

	void InvokeMatchmakingSetupProgressCallback(int timeoutMs, int countdownMs)
	{
		if (m_fnCallbackMatchmakingSetupProgress != nullptr)
		{
			m_fnCallbackMatchmakingSetupProgress(timeoutMs, countdownMs);
		}
	}
	

	// updates
	void UpdateCurrentLobby_Map(UnicodeString strMap, AsciiString strMapPath, bool bIsOfficial, int newMaxPlayers);
	void UpdateCurrentLobby_LimitSuperweapons(bool bLimitSuperweapons);
	void UpdateCurrentLobby_StartingCash(UnsignedInt startingCashValue);

	void UpdateCurrentLobby_HasMap();

	void UpdateCurrentLobby_MySide(int side, int updatedStartPos);
	void UpdateCurrentLobby_MyColor(int side);
	void UpdateCurrentLobby_MyStartPos(int side);
	void UpdateCurrentLobby_MyTeam(int side);

	// AI
	void UpdateCurrentLobby_AIColor(int slot, int color);
	void UpdateCurrentLobby_AISide(int slot, int side, int updatedStartPos);
	void UpdateCurrentLobby_AITeam(int slot, int team);
	void UpdateCurrentLobby_AIStartPos(int slot, int startpos);

	void UpdateCurrentLobbyMaxCameraHeight(uint16_t maxCameraHeight);

	void SetJoinability(ELobbyJoinability joinabilityFlag);

	void UpdateCurrentLobby_KickUser(int64_t userID, UnicodeString name);
	void UpdateCurrentLobby_SetSlotState(uint16_t slotIndex, uint16_t slotState);

	void UpdateCurrentLobby_ForceReady();

	void SetLobbyListDirty()
	{
		m_bLobbyListDirty.store(true);
	}

	void ConsumeLobbyListDirtyFlag()
	{
		m_bLobbyListDirty.store(false);
	}

	bool IsLobbyListDirty() const
	{
		return m_bLobbyListDirty.load();
	}

	UnicodeString m_PendingCreation_LobbyName;
	UnicodeString m_PendingCreation_InitialMapDisplayName;
	AsciiString m_PendingCreation_InitialMapPath;
	void CreateLobby(UnicodeString strLobbyName, UnicodeString strInitialMapName, AsciiString strInitialMapPath, bool bIsOfficial, int initialMaxSize, bool bVanillaTeamsOnly, bool bTrackStats, uint32_t startingCash, bool bPassworded, std::string strPassword, bool bAllowObservers);

	void OnJoinedOrCreatedLobby(bool bAlreadyUpdatedDetails, std::function<void(bool)> fnCallback);

	UnicodeString GetCurrentLobbyDisplayName();
	UnicodeString GetCurrentLobbyMapDisplayName();
	AsciiString GetCurrentLobbyMapPath();

	void SendChatMessageToCurrentLobby(UnicodeString& strChatMsgUnicode, bool bIsAction);
	void SendAnnouncementMessageToCurrentLobby(UnicodeString& strAnnouncementMsgUnicode, bool bShowToHost);

	void InvokeCreateLobbyCallback(bool bSuccess)
	{
		if (m_cb_CreateLobbyPendingCallback != nullptr)
		{
			m_cb_CreateLobbyPendingCallback(bSuccess);
		}
	}


	LobbyEntry& GetCurrentLobby()
	{
		return m_CurrentLobby;
	}

	const LobbyEntry& GetCurrentLobby() const
	{
		return m_CurrentLobby;
	}

	NGMPGame* GetCurrentGame()
	{
		return TheNGMPGame;
	}

	// lobby roster
	std::function<void()> m_RosterNeedsRefreshCallback = nullptr;
	mutable std::mutex m_rosterCallbackMutex;
	void RegisterForRosterNeedsRefreshCallback(std::function<void()> cb)
	{
		std::scoped_lock<std::mutex> lock(m_rosterCallbackMutex);
		m_RosterNeedsRefreshCallback = cb;
	}

	void DeregisterForRosterNeedsRefreshCallback()
	{
		std::scoped_lock<std::mutex> lock(m_rosterCallbackMutex);
		m_RosterNeedsRefreshCallback = nullptr;
	}

	// TODO_NGMP: Better support for packet callbacks
	std::function<void()> m_callbackStartGamePacket = nullptr;
	void RegisterForGameStartPacket(std::function<void()> cb)
	{
		m_callbackStartGamePacket = cb;
	}

	void DeregisterForGameStartPacket()
	{
		m_callbackStartGamePacket = nullptr;
	}

	// periodically force refresh the lobby for data accuracy
	int64_t m_lastForceRefresh = 0;

	void Tick();

	int64_t GetCurrentLobbyOwnerID()
	{
		return m_CurrentLobby.owner;
	}

	LobbyMemberEntry GetRoomMemberFromIndex(int index)
	{
		// TODO_NGMP: Optimize data structure
		if (index < m_CurrentLobby.members.size())
		{
			return m_CurrentLobby.members.at(index);
		}

		return LobbyMemberEntry();
	}

	LobbyMemberEntry GetRoomMemberFromID(int64_t userid)
	{
		for (const LobbyMemberEntry& lobbyMember : m_CurrentLobby.members)
		{
			if (lobbyMember.user_id == userid)
			{
				return lobbyMember;
			}
		}

		return LobbyMemberEntry();
	}

	std::vector<LobbyMemberEntry>& GetMembersListForCurrentRoom()
	{
		NetworkLog(ELogVerbosity::LOG_RELEASE, "[NGMP] Refreshing network room roster");
		return m_CurrentLobby.members;
	}

	void RegisterForCreateLobbyCallback(std::function<void(bool)> callback)
	{
		m_cb_CreateLobbyPendingCallback = callback;
	}

	void DeregisterForCreateLobbyCallback()
	{
		m_cb_CreateLobbyPendingCallback = nullptr;
	}

	void ApplyLocalUserPropertiesToCurrentNetworkRoom();

	void SetCurrentLobby_AcceptState(bool bAccepted)
	{

	}

	bool IsHost();

private:
	std::set<int64_t> m_setMembersBeforeUs;
	bool m_bJoinOrderKnown = false;
	void ResetJoinOrder();
	void RecordJoinOrder(const std::vector<LobbyMemberEntry>& members);

public:

	void UpdateRoomDataCache(std::function<void(bool)> fnCallback = nullptr);

	std::function<void(LobbyMemberEntry)> m_cbPlayerDoesntHaveMap = nullptr;
	void RegisterForPlayerDoesntHaveMapCallback(std::function<void(LobbyMemberEntry)> cb)
	{
		m_cbPlayerDoesntHaveMap = cb;
	}

	void DeregisterForPlayerDoesntHaveMapCallback()
	{
		m_cbPlayerDoesntHaveMap = nullptr;
	}

	std::function<void(void)> m_OnCannotConnectToLobbyCallback = nullptr;
	void RegisterForCannotConnectToLobbyCallback(std::function<void(void)> cb)
	{
			m_OnCannotConnectToLobbyCallback = cb;
	}

	void DeregisterForCannotConnectToLobbyCallback()
	{
		m_OnCannotConnectToLobbyCallback = nullptr;
	}

	// true if userID was already in the lobby when we joined, i.e. we are the later joiner of that pair
	bool JoinedAfter(int64_t userID) const
	{
		return m_bJoinOrderKnown && m_setMembersBeforeUs.contains(userID);
	}

	bool IsJoinOrderKnown() const
	{
		return m_bJoinOrderKnown;
	}

	bool IsLobbyMember(int64_t userID) const
	{
		for (const LobbyMemberEntry& member : m_CurrentLobby.members)
		{
			if (member.user_id == userID)
			{
				return true;
			}
		}
		return false;
	}

	// raised from inside the mesh's GNS callbacks, dispatched by Tick once the mesh is done with them
	bool m_bCannotConnectToLobbyPending = false;
	void QueueCannotConnectToLobby()
	{
		m_bCannotConnectToLobbyPending = true;
	}

	std::function<void(const std::string& strMessage, bool bIsAction)> m_OnRawChat = nullptr;
	std::function<void(UnicodeString strMessage, Color color)> m_OnChatCallback = nullptr;
	void RegisterForChatCallback(std::function<void(UnicodeString strMessage, Color color)> cb)
	{
		m_OnChatCallback = cb;
	}

	void DeregisterForChatCallback()
	{
		m_OnChatCallback = nullptr;
	}

	void RegisterForJoinLobbyCallback(std::function<void(EJoinLobbyResult)> cb)
	{
		m_callbackJoinedLobby = cb;
	}

	void DeregisterForJoinLobbyCallback()
	{
		m_callbackJoinedLobby = nullptr;
	}

	void ResetCachedRoomData()
	{
		m_CurrentLobby = LobbyEntry();

		std::scoped_lock<std::mutex> lock(m_rosterCallbackMutex);
		if (m_RosterNeedsRefreshCallback != nullptr)
		{
			m_RosterNeedsRefreshCallback();
		}
	}

	bool IsInLobby() const { return m_CurrentLobby.lobbyID != -1; }

	NetworkMesh* GetNetworkMeshForLobby() { return m_pLobbyMesh; }

	void JoinLobby(LobbyEntry lobby, std::string strPassword);

	void LeaveCurrentLobby();
	void ResetForMatchmakingRequeue();

	void ResetHostMigrationFlags()
	{
		m_bHostMigrated = false;
		m_bPendingHostHasLeft = false;
	}

	LobbyEntry GetLobbyFromID(int64_t lobbyID);

	std::vector<LobbyEntry> m_vecLobbies;

	bool m_bHostMigrated = false;
	bool m_bPendingHostHasLeft = false;

#if !defined(GENERALS_ONLINE_DISABLE_AUTO_ACCEPT)
	void StartAutoReadyCountdown()
	{
		m_timeStartAutoReadyCountdown = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::utc_clock::now().time_since_epoch()).count();
	}

	void ClearAutoReadyCountdown()
	{
		m_timeStartAutoReadyCountdown = -1;
	}

	bool HasAutoReadyCountdown()
	{
		return m_timeStartAutoReadyCountdown != -1;
	}
#endif

	void SetLobbyTryingToJoin(LobbyEntry lobby)
	{
		m_LobbyTryingToJoin = lobby;
	}

	void ResetLobbyTryingToJoin()
	{
		m_LobbyTryingToJoin = LobbyEntry();
	}

	LobbyEntry GetLobbyTryingToJoin()
	{
		return m_LobbyTryingToJoin;
	}

	std::string GetLobbyTurnUsername() { return m_strTURNUsername; }
	std::string GetLobbyTurnToken() { return m_strTURNToken; }

	uint64_t GetCurrentMatchID()
	{
		return m_CurrentMatchID;
	}

private:
	std::function<void(bool)> m_cb_CreateLobbyPendingCallback = nullptr;

	std::function<void(EJoinLobbyResult)> m_callbackJoinedLobby = nullptr;

	LobbyEntry m_CurrentLobby;

	std::string m_strTURNUsername = "";
	std::string m_strTURNToken = "";

	// TODO_NGMP: cleanup
	NetworkMesh* m_pLobbyMesh = nullptr;

	std::atomic_bool m_bLobbyListDirty = false;


#if !defined(GENERALS_ONLINE_DISABLE_AUTO_ACCEPT)
	int64_t m_timeStartAutoReadyCountdown = -1;
#endif

	bool m_bAttemptingToJoinLobby = false;
	// Invalidates asynchronous callbacks left behind by an abandoned lobby join.
	std::atomic<uint64_t> m_LobbyJoinGeneration = 0;
	LobbyEntry m_LobbyTryingToJoin;

	std::atomic_bool m_bSearchInProgress = false;

	bool m_bMarkedGameAsFinished = false;

	uint64_t m_CurrentMatchID = 0;
};