Files
DedicatedServerCourse/Source/FPSTemplate/Private/Game/ShooterGameMode.cpp

296 lines
12 KiB
C++
Raw Normal View History

2026-02-24 22:39:26 -05:00
// Fill out your copyright notice in the Description page of Project Settings.
#include "Game/ShooterGameMode.h"
#include "DSP/BufferDiagnostics.h"
2026-02-24 22:39:26 -05:00
#include "UObject/ConstructorHelpers.h"
#include "Kismet/GameplayStatics.h"
#if WITH_GAMELIFT
#include "GameLiftServerSDKModels.h"
#endif
#include "GenericPlatform/GenericPlatformOutputDevices.h"
#include "Misc/TypeContainer.h"
DEFINE_LOG_CATEGORY(LogShooterGameMode)
AShooterGameMode::AShooterGameMode()
{
UE_LOG(LogShooterGameMode, Log, TEXT("Initializing ShooterGameMode..."));
}
void AShooterGameMode::BeginPlay()
{
Super::BeginPlay();
#if WITH_GAMELIFT
InitGameLift();
#endif
}
#if WITH_GAMELIFT
// ReSharper disable once CppMemberFunctionMayBeConst - cannot be const due to FCommandLine::Get() and UE_LOG with non-const log category
bool AShooterGameMode::SetParametersFromCommandLine(FServerParameters& OutServerParameters,
FProcessParameters& OutProcessParameters)
2026-02-24 22:39:26 -05:00
{
bool bCriticalFault = false;
FString CommandLine = FCommandLine::Get();
UE_LOG(LogShooterGameMode, Log, TEXT(">>> Command Line: %s"), *CommandLine);
// Checks if param exists (returns bool)
// AuthToken returned from the "aws gamelift get-compute-auth-token" API. Note this will expire and require a new call to the API after 15 minutes.
bCriticalFault |= ValidateServerParameters(CommandLine, TEXT("authtoken"),OutServerParameters.m_authToken);
2026-02-24 22:39:26 -05:00
// The Host/compute-name of the GameLift Anywhere instance
bCriticalFault |= ValidateServerParameters(CommandLine, TEXT("hostid"),OutServerParameters.m_hostId);
2026-02-24 22:39:26 -05:00
// The AnywhereFleet ID.
bCriticalFault |= ValidateServerParameters(CommandLine, TEXT("fleetid"),OutServerParameters.m_fleetId);
2026-02-24 22:39:26 -05:00
// The WebSocket URL (GameLiftServiceSdkEndpoint)
bCriticalFault |= ValidateServerParameters(CommandLine, TEXT("websocketurl"),OutServerParameters.m_webSocketUrl);
2026-02-24 22:39:26 -05:00
// The port being used, uses UE system default if not entered as a switch
OutProcessParameters.port = FURL::UrlConfig.DefaultPort;
FParse::Value(*CommandLine, TEXT("port="), OutProcessParameters.port);
LogServerSummary(OutServerParameters,OutProcessParameters);
return bCriticalFault;
}
void AShooterGameMode::LogServerParameters(const FServerParameters& InServerParameters)
2026-02-24 22:39:26 -05:00
{
// Log Server Parameters
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_YELLOW);
UE_LOG(LogShooterGameMode, Log, TEXT(">>>> WebSocket URL: %s"), *InServerParameters.m_webSocketUrl);
UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Fleet ID: %s"), *InServerParameters.m_fleetId);
UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Process ID: %s"), *InServerParameters.m_processId);
UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Host ID (Compute Name): %s"), *InServerParameters.m_hostId);
UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Auth Token: %s"), *InServerParameters.m_authToken);
2026-02-24 22:39:26 -05:00
// UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Aws Region: %s"), *ServerParameters.m_awsRegion);
// UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Access Key: %s"), *ServerParameters.m_accessKey);
// UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Secret Key: %s"), *ServerParameters.m_secretKey);
// UE_LOG(LogShooterGameMode, Log, TEXT(">>>> Session Token: %s"), *ServerParameters.m_sessionToken);
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
void AShooterGameMode::SetProcessIdOnServerParameters(FServerParameters& OutServerParameters)
{
// The PID of the running process
#if PLATFORM_WINDOWS
OutServerParameters.m_processId = FString::Printf(TEXT("%d"), GetCurrentProcessId());
#else
OutServerParameters.m_processId = FString::Printf(TEXT("%d"), FGenericPlatformProcess::GetCurrentProcessId());
2026-02-24 22:39:26 -05:00
#endif
}
2026-02-24 22:39:26 -05:00
bool AShooterGameMode::ValidateServerParameters(const FString& CommandLine, const FString& ParameterName,
FString& OutValue, const bool bCritical)
2026-02-24 22:39:26 -05:00
{
if (!FParse::Value(*CommandLine, *FString::Printf(TEXT("%s="), *ParameterName), OutValue))
2026-02-24 22:39:26 -05:00
{
UE_LOG(LogShooterGameMode, Warning, TEXT("-%s not found"), *ParameterName);
return bCritical;
2026-02-24 22:39:26 -05:00
}
return false;
2026-02-24 22:39:26 -05:00
}
void AShooterGameMode::LogServerSummary(const FServerParameters& InServerParameters,
const FProcessParameters& InProcessParameters)
2026-02-24 22:39:26 -05:00
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_YELLOW);
UE_LOG(LogShooterGameMode, Log, TEXT("=== SERVER STARTUP SUMMARY ==="));
UE_LOG(LogShooterGameMode, Log, TEXT("Port: %d"), InProcessParameters.port);
2026-02-24 22:39:26 -05:00
// Inline validation of ServerParams
bool bAllValid = !InServerParameters.m_authToken.IsEmpty() &&
!InServerParameters.m_hostId.IsEmpty() &&
!InServerParameters.m_fleetId.IsEmpty() &&
!InServerParameters.m_webSocketUrl.IsEmpty();
2026-02-24 22:39:26 -05:00
UE_LOG(LogShooterGameMode, Log, TEXT("All Anywhere params: %s"),
bAllValid ? TEXT("VALID ✓") : TEXT("MISSING ❌"));
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
2026-02-24 22:39:26 -05:00
void AShooterGameMode::BindGameLiftCallbackFunctions(FProcessParameters& ProcessParameters, FGameLiftServerSDKModule& GameLiftSdkModule)
{
2026-02-24 22:39:26 -05:00
// Implement callback function onStartGameSession
// GameLift sends a game session activation request to the game server
// and passes a game session object with game properties and other settings.
// Here is where a game server takes action based on the game session object.
// When the game server is ready to receive incoming player connections,
// it invokes the server SDK call ActivateGameSession().
ProcessParameters.OnStartGameSession.BindLambda([this, &GameLiftSdkModule](Aws::GameLift::Server::Model::GameSession InGameSession)
2026-02-24 22:39:26 -05:00
{
FString GameSessionId = FString(InGameSession.GetGameSessionId());
UE_LOG(LogShooterGameMode, Log, TEXT("GameSession Initializing: %s"), *GameSessionId);
FGameLiftGenericOutcome ActivateGameSessionOutcome = GameLiftSdkModule.ActivateGameSession();
if (ActivateGameSessionOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, Log, TEXT("Activate GameSession successful"));
}
else
{
const FGameLiftError& Error = ActivateGameSessionOutcome.GetError();
UE_LOG(LogShooterGameMode, Error, TEXT("ActivateGameSession() failed. Error: %s"), Error.m_errorMessage.IsEmpty() ? TEXT("Unknown Error") : *Error.m_errorMessage);
FPlatformMisc::RequestExit(true);
}
});
2026-02-24 22:39:26 -05:00
ProcessParameters.OnTerminate.BindLambda([this, &GameLiftSdkModule]()
2026-02-24 22:39:26 -05:00
{
FGameLiftGenericOutcome ProcessEndingOutcome = GameLiftSdkModule.ProcessEnding();
FGameLiftGenericOutcome DestroyOutcome = GameLiftSdkModule.Destroy();
if (ProcessEndingOutcome.IsSuccess() && DestroyOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, Log, TEXT("Server process ending successfully"));
FPlatformMisc::RequestExit(false);
}
else
{
if (!ProcessEndingOutcome.IsSuccess())
{
const FGameLiftError& Error = ProcessEndingOutcome.GetError();
UE_LOG(LogShooterGameMode, Error, TEXT("ProcessEnding() failed. Error: %s"), Error.m_errorMessage.IsEmpty() ? TEXT("Unknown Error") : *Error.m_errorMessage);
}
if (!DestroyOutcome.IsSuccess())
{
const FGameLiftError& Error = DestroyOutcome.GetError();
UE_LOG(LogShooterGameMode, Error, TEXT("Destroy() failed. Error: %s"), Error.m_errorMessage.IsEmpty() ? TEXT("Unknown error") : *Error.m_errorMessage);
}
FPlatformMisc::RequestExit(true);
}
});
2026-02-24 22:39:26 -05:00
ProcessParameters.OnHealthCheck.BindLambda([=]()
2026-02-24 22:39:26 -05:00
{
return true;
});
2026-02-24 22:39:26 -05:00
// Here, the game server tells GameLift where to find game session Log files.
// At the end of a game session, GameLift uploads everything in the specified
// location and stores it in the cloud for access later.
TArray<FString> LogFiles;
FString LogDirectory =FPaths::ProjectSavedDir() / TEXT("Logs");
FString LogFile = LogDirectory / TEXT("GameLiftServer.log");
LogFiles.Add(LogFile);
UE_LOG(LogShooterGameMode, Log, TEXT("Before Adding Log Files"));
ProcessParameters.logParameters = LogFiles;
}
void AShooterGameMode::InitiateProcessReady(FProcessParameters& ProcessParameters, FGameLiftServerSDKModule& GameLiftSdkModule)
{
2026-02-24 22:39:26 -05:00
// The game server calls ProcessReady() to tell Amazon GameLift Servers it's ready to host game sessions.
UE_LOG(LogShooterGameMode, Log, TEXT("Calling Process Ready..."));
FGameLiftGenericOutcome ProcessReadyOutcome = GameLiftSdkModule.ProcessReady(ProcessParameters);
2026-02-24 22:39:26 -05:00
if (ProcessReadyOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_GREEN);
UE_LOG(LogShooterGameMode, Log, TEXT("Process Ready!"));
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
else
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_RED);
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: Process Ready Failed!"));
FGameLiftError ProcessReadyError = ProcessReadyOutcome.GetError();
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: %s"), *ProcessReadyError.m_errorMessage);
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
UE_LOG(LogShooterGameMode, Log, TEXT("InitGameLift completed!"));
}
bool AShooterGameMode::InitiateConnectionWithGameLiftAgent(FServerParameters& ServerParameters, FGameLiftServerSDKModule& GameLiftSdkModule)
{
// InitSDK will establish a local connection with GameLift's agent to enable further communication
2026-02-24 22:39:26 -05:00
FGameLiftGenericOutcome InitSdkOutcome = GameLiftSdkModule.InitSDK(ServerParameters);
if (InitSdkOutcome.IsSuccess())
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_GREEN);
UE_LOG(LogShooterGameMode, Log, TEXT("GameLift Init SDK Succeeded"));
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
}
else
{
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_RED);
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: InitSDK failed : ("));
FGameLiftError GameLiftError = InitSdkOutcome.GetError();
UE_LOG(LogShooterGameMode, Log, TEXT("ERROR: %s"), *GameLiftError.m_errorMessage);
UE_LOG(LogShooterGameMode, SetColor, TEXT("%s"), COLOR_NONE);
return true;
}
return false;
}
2026-02-24 22:39:26 -05:00
#endif
void AShooterGameMode::InitGameLift()
{
#if WITH_GAMELIFT
UE_LOG(LogShooterGameMode, Log, TEXT("Calling InitGameLift"));
2026-02-24 22:39:26 -05:00
FServerParameters ServerParameters;
FProcessParameters ProcessParameters;
// Getting the module first.
FGameLiftServerSDKModule& GameLiftSdkModule = FModuleManager::LoadModuleChecked<FGameLiftServerSDKModule>(FName("GameLiftServerSDK"));
// Define the server parameters for a GameLift Anywhere fleet. These are not needed for a GameLift managed EC2 fleet.
bool bIsAnywhereActive = false;
if (FParse::Param(FCommandLine::Get(), TEXT("-glAnywhere")))
{
bIsAnywhereActive = true;
}
if (bIsAnywhereActive)
{
UE_LOG(LogShooterGameMode, Log, TEXT("Configuring server parameters for Anywhere..."));
if (SetParametersFromCommandLine(ServerParameters, ProcessParameters))
{
UE_LOG(LogShooterGameMode, Error, TEXT("Critical Error, shutting server down..."));
FPlatformMisc::RequestExit(true);
return;
}
SetProcessIdOnServerParameters(ServerParameters);
if (ServerParameters.m_processId.IsEmpty())
{
UE_LOG(LogShooterGameMode, Warning, TEXT("ProcessId is empty"));
FPlatformMisc::RequestExit(true);
return;
}
LogServerParameters(ServerParameters);
UE_LOG(LogShooterGameMode, Log, TEXT("Initializing the GameLift Server..."));
BindGameLiftCallbackFunctions(ProcessParameters, GameLiftSdkModule);
}
else
{
// Using EC2
UE_LOG(LogShooterGameMode, Log, TEXT("Using Gamelift EC2 Managed Fleet"));
// EC2: Bind Callbacks (populates logParameters automatically)
BindGameLiftCallbackFunctions(ProcessParameters, GameLiftSdkModule);
// EC2: Empty ServerParameters = GameLift agent provies all config
UE_LOG(LogShooterGameMode, Log, TEXT("Initializing EC2 GameLift Server..."));
}
if (InitiateConnectionWithGameLiftAgent(ServerParameters, GameLiftSdkModule)) return;
InitiateProcessReady(ProcessParameters, GameLiftSdkModule);
#endif
}