Skip to content

save game system async functions #363

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
#include "GameBaseFrameworkGameSettings.h"

#include "GameFramework/SaveGame/GBFSaveGame.h"

#include <Misc/App.h>

UGameBaseFrameworkGameSettings::UGameBaseFrameworkGameSettings()
{
SaveGameClass = UGBFSaveGame::StaticClass();
SaveGameSlotName = TEXT( "SaveGame" );
}

FName UGameBaseFrameworkGameSettings::GetCategoryName() const
{
return FApp::GetProjectName();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#include "GameFramework/SaveGame/GBFSaveGameSettings.h"

#include "GameFramework/SaveGame/GBFSaveGame.h"

UGBFSaveGameSettings::UGBFSaveGameSettings()
{
SaveGameClass = UGBFSaveGame::StaticClass();
SaveGameSlotName = TEXT( "SaveGame" );
MaxSaveFrequency = 10;
MaxSaveFrequencyDuration = 60.0f;
MaxLoadFrequency = 10;
MaxLoadFrequencyDuration = 60.0;
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,73 @@
#include "GameFramework/SaveGame/GBFSaveGameSubsystem.h"

#include "GBFTags.h"
#include "GameBaseFrameworkGameSettings.h"
#include "GameFramework/GBFWorldSettings.h"
#include "GameFramework/SaveGame/GBFSaveGame.h"
#include "GameFramework/SaveGame/GBFSaveGameSettings.h"

#include <Engine/LocalPlayer.h>
#include <Engine/World.h>
#include <Kismet/GameplayStatics.h>
#include <TimerManager.h>

DEFINE_LOG_CATEGORY_STATIC( LogGBFSaveGameSystem, Verbose, Verbose )

namespace
{
bool IsFrequencyRespected( TDeque< float > & call_times, const float current_time, const float frequency_duration, const int max_frequency )
{
while ( call_times.Num() > 0 && call_times[ 0 ] <= current_time - frequency_duration )
{
call_times.PopFirst();
}

if ( call_times.Num() >= max_frequency )
{
return false;
}

call_times.PushLast( current_time );

return true;
}
}

void UGBFSaveGameSubsystem::Initialize( FSubsystemCollectionBase & collection )
{
Super::Initialize( collection );

auto * settings = GetDefault< UGBFSaveGameSettings >();
}

void UGBFSaveGameSubsystem::NotifyPlayerAdded( ULocalPlayer * local_player )
{
if ( PrimaryPlayer == nullptr )
{
PrimaryPlayer = local_player;

Load();
Load( FGBFOnSaveGameLoaded() );
}
}

void UGBFSaveGameSubsystem::Load()
bool UGBFSaveGameSubsystem::Load( FGBFOnSaveGameLoaded on_save_game_loaded )
{
const auto current_time = GetWorld()->GetTimeSeconds();
auto * settings = GetDefault< UGBFSaveGameSettings >();

if ( !IsFrequencyRespected( LoadGameCallTimes, current_time, settings->MaxLoadFrequencyDuration, settings->MaxLoadFrequency ) )
{
UE_LOG( LogGBFSaveGameSystem, Warning, TEXT( "Too much calls to Load. Max calls : %i in %f seconds" ), settings->MaxLoadFrequency, settings->MaxLoadFrequencyDuration );
return false;
}

const auto * world = GetWorld();

const auto * world_settings = Cast< AGBFWorldSettings >( world->GetWorldSettings() );
if ( world_settings->GetGameplayTags().HasTag( GBFTag_WorldSettings_NoSaveGame ) )
{
return;
return false;
}

auto * settings = GetDefault< UGameBaseFrameworkGameSettings >();

if ( SaveGame != nullptr )
{
for ( const auto & savable_data : SaveGame->SavablesData )
Expand All @@ -38,22 +76,81 @@ void UGBFSaveGameSubsystem::Load()
}
}

SaveGame = Cast< UGBFSaveGame >( UGBFSaveGame::LoadOrCreateSaveGameForLocalPlayer( settings->SaveGameClass, PrimaryPlayer.Get(), settings->SaveGameSlotName ) );
auto callback = FOnLocalPlayerSaveGameLoadedNative::CreateLambda( [ &, delegate = MoveTemp( on_save_game_loaded ) ]( ULocalPlayerSaveGame * save_game ) {
SaveGame = Cast< UGBFSaveGame >( save_game );

for ( const auto & pending_savable : PendingSavables )
{
SaveGame->RegisterSavable( pending_savable );
}
for ( const auto & pending_savable : PendingSavables )
{
SaveGame->RegisterSavable( pending_savable );
}

PendingSavables.Reset();

PendingSavables.Reset();
delegate.ExecuteIfBound( SaveGame );
OnOperationTriggeredDelegate.Broadcast( EGBFSaveGameSubsystemOperation::Load, EGBFSaveGameSubsystemOperationEvent::Ended );
} );

OnOperationTriggeredDelegate.Broadcast( EGBFSaveGameSubsystemOperation::Load, EGBFSaveGameSubsystemOperationEvent::Started );
return UGBFSaveGame::AsyncLoadOrCreateSaveGameForLocalPlayer( settings->SaveGameClass, PrimaryPlayer.Get(), settings->SaveGameSlotName, callback );
}

void UGBFSaveGameSubsystem::Save()
bool UGBFSaveGameSubsystem::Save( FGBFOnSaveGameSaved on_save_game_saved )
{
if ( SaveGame != nullptr )
if ( SaveGame == nullptr )
{
return false;
}

if ( !ensure( PrimaryPlayer.Get() ) )
{
SaveGame->AsyncSaveGameToSlotForLocalPlayer();
return false;
}

const auto current_time = GetWorld()->GetTimeSeconds();
auto * settings = GetDefault< UGBFSaveGameSettings >();

if ( !IsFrequencyRespected( SaveGameCallTimes, current_time, settings->MaxSaveFrequencyDuration, settings->MaxSaveFrequency ) )
{
UE_LOG( LogGBFSaveGameSystem, Warning, TEXT( "Too much calls to Save. Max calls : %i in %f seconds" ), settings->MaxSaveFrequency, settings->MaxSaveFrequencyDuration );
return false;
}

const auto request_user_index = SaveGame->GetPlatformUserIndex();
const auto & request_slot_name = SaveGame->GetSaveSlotName();
if ( !ensure( request_slot_name.Len() > 0 ) )
{
return false;
}

OnOperationTriggeredDelegate.Broadcast( EGBFSaveGameSubsystemOperation::Save, EGBFSaveGameSubsystemOperationEvent::Started );

SaveGame->HandlePreSave();

auto callback = FAsyncSaveGameToSlotDelegate::CreateLambda( [ &, delegate = MoveTemp( on_save_game_saved ) ]( const FString & /*slot_name*/, const int32 /*user_index*/, bool success ) {
delegate.ExecuteIfBound( SaveGame, success );
OnOperationTriggeredDelegate.Broadcast( EGBFSaveGameSubsystemOperation::Save, EGBFSaveGameSubsystemOperationEvent::Ended );
} );

UGameplayStatics::AsyncSaveGameToSlot( SaveGame, request_slot_name, request_user_index, callback );

return true;
}

void UGBFSaveGameSubsystem::SaveNextTick( FGBFOnSaveGameSaved on_save_game_saved )
{
GetWorld()->GetTimerManager().SetTimerForNextTick( FTimerDelegate::CreateLambda( [ & ]() {
Save( on_save_game_saved );
} ) );
}

void UGBFSaveGameSubsystem::SaveWithDelay( float delay, FGBFOnSaveGameSaved on_save_game_saved )
{
FTimerHandle handle;
GetWorld()->GetTimerManager().SetTimer( handle, FTimerDelegate::CreateLambda( [ & ]() {
Save( on_save_game_saved );
} ),
delay,
false );
}

void UGBFSaveGameSubsystem::Reset()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,12 @@ class UGameBaseFrameworkGameSettings final : public UDeveloperSettingsBackedByCV
public:
UGameBaseFrameworkGameSettings();

FName GetCategoryName() const override;

UPROPERTY( BlueprintReadOnly, EditDefaultsOnly, config, Category = "UI" )
TSoftClassPtr< UCommonGameDialog > ConfirmationDialogClass;

UPROPERTY( BlueprintReadOnly, EditDefaultsOnly, config, Category = "UI" )
TSoftClassPtr< UCommonGameDialog > ErrorDialogClass;

UPROPERTY( EditDefaultsOnly, config, Category = "SaveGame" )
TSubclassOf< UGBFSaveGame > SaveGameClass;

UPROPERTY( EditDefaultsOnly, config, Category = "SaveGame" )
FString SaveGameSlotName;

UPROPERTY( BlueprintReadOnly, EditDefaultsOnly, config, Category = "Sounds" )
TSoftObjectPtr< USoundBase > BackHandlerSound;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#pragma once

#include <CoreMinimal.h>
#include <Engine/DeveloperSettings.h>

#include "GBFSaveGameSettings.generated.h"

class UGBFSaveGame;

UCLASS( config = Game, DefaultConfig, meta = ( DisplayName = "GameBaseFramework - SaveSystem" ) )
class GAMEBASEFRAMEWORK_API UGBFSaveGameSettings final : public UDeveloperSettings
{
GENERATED_BODY()

public:
UGBFSaveGameSettings();

UPROPERTY( config, EditDefaultsOnly )
TSubclassOf< UGBFSaveGame > SaveGameClass;

UPROPERTY( config, EditDefaultsOnly )
FString SaveGameSlotName;

UPROPERTY( config, EditDefaultsOnly )
int MaxSaveFrequency;

UPROPERTY( config, EditDefaultsOnly, meta = ( ForceUnits = "s" ) )
float MaxSaveFrequencyDuration;

UPROPERTY( config, EditDefaultsOnly )
int MaxLoadFrequency;

UPROPERTY( config, EditDefaultsOnly, meta = ( ForceUnits = "s" ) )
float MaxLoadFrequencyDuration;
};
Original file line number Diff line number Diff line change
@@ -1,25 +1,52 @@
#pragma once

#include "Containers/Deque.h"
#include "GBFSaveGame.h"

#include <CoreMinimal.h>
#include <Subsystems/GameInstanceSubsystem.h>

#include "GBFSaveGameSubsystem.generated.h"

UENUM( BlueprintType )
enum class EGBFSaveGameSubsystemOperation : uint8
{
Load,
Save
};

UENUM( BlueprintType )
enum class EGBFSaveGameSubsystemOperationEvent : uint8
{
Started,
Ended
};

DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams( FGBFOnOperationTriggeredDelegate, EGBFSaveGameSubsystemOperation, Operation, EGBFSaveGameSubsystemOperationEvent, Event );
DECLARE_DYNAMIC_DELEGATE_OneParam( FGBFOnSaveGameLoaded, UGBFSaveGame *, SaveGame );
DECLARE_DYNAMIC_DELEGATE_TwoParams( FGBFOnSaveGameSaved, UGBFSaveGame *, SaveGame, bool, Success );

UCLASS()
class GAMEBASEFRAMEWORK_API UGBFSaveGameSubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()

public:
void Initialize( FSubsystemCollectionBase & collection ) override;

void NotifyPlayerAdded( ULocalPlayer * local_player );

UFUNCTION( BlueprintCallable )
void Load();
bool Load( FGBFOnSaveGameLoaded on_save_game_loaded );

UFUNCTION( BlueprintCallable )
bool Save( FGBFOnSaveGameSaved on_save_game_saved );

UFUNCTION( BlueprintCallable )
void Save();
void SaveNextTick( FGBFOnSaveGameSaved on_save_game_saved );

UFUNCTION( BlueprintCallable )
void SaveWithDelay( float delay, FGBFOnSaveGameSaved on_save_game_saved );

UFUNCTION( BlueprintCallable )
void Reset();
Expand All @@ -39,7 +66,13 @@ class GAMEBASEFRAMEWORK_API UGBFSaveGameSubsystem : public UGameInstanceSubsyste
UPROPERTY()
TArray< TScriptInterface< IGBFSaveGameSystemSavableInterface > > PendingSavables;

UPROPERTY( BlueprintAssignable )
FGBFOnOperationTriggeredDelegate OnOperationTriggeredDelegate;

TWeakObjectPtr< ULocalPlayer > PrimaryPlayer;

TDeque< float > LoadGameCallTimes;
TDeque< float > SaveGameCallTimes;
};

template < typename _SAVE_GAME_CLASS_ >
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class UGBFPlatformSpecificRenderingSettings : public UPlatformSettings
TArray< int32 > MobileFrameRateLimits;
};

UCLASS( config = Game, defaultconfig, meta = ( DisplayName = "Game Base Framework - Performance Settings" ) )
UCLASS( config = Game, defaultconfig, meta = ( DisplayName = "GameBaseFramework - Performance Settings" ) )
class GAMEBASEFRAMEWORK_API UGBFPerformanceSettings : public UDeveloperSettingsBackedByCVars
{
GENERATED_BODY()
Expand Down