chore: upgrade ts2lua-unreal to v0.3.1 with lowercase lib/module.lua & lib/class.lua and commit framework refactor

This commit is contained in:
szy73711 committed 2026-11-30 03:43:42 +08:00
1 parent 783dccf53d
commit 3572f2da43
206 files changed
+14442 -13186

No files matched your search

@@ -101,6 +101,11 @@ namespace
bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const char* FuncName)
{
if (ModuleName.IsEmpty())
{
return false;
}
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
if (!Env)
{
@@ -129,6 +134,11 @@ bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const
bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value)
{
if (ModuleName.IsEmpty())
{
return false;
}
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
if (!Env)
{
@@ -158,6 +168,11 @@ bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, c
bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value)
{
if (ModuleName.IsEmpty())
{
return false;
}
UnLua::FLuaEnv* Env = ResolveLuaEnv(Target);
if (!Env)
{
@@ -184,3 +199,61 @@ bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, con
lua_settop(L, Top);
return bOk;
}
bool FLuaCallbackBridge::CallResourceLoadCallback(
UObject* GameInstanceTarget,
const FString& ModuleName,
const char* FuncName,
int64 RequestId,
bool bSuccess,
UObject* LoadedObject,
const FString& ResolvedPath,
const FString& ErrorMessage)
{
if (ModuleName.IsEmpty())
{
return false;
}
UnLua::FLuaEnv* Env = ResolveLuaEnv(GameInstanceTarget);
if (!Env)
{
return false;
}
lua_State* L = Env->GetMainState();
if (!L)
{
return false;
}
const int32 Top = lua_gettop(L);
int32 ErrHandlerIdx = 0;
if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx))
{
lua_settop(L, Top);
return false;
}
UnLua::PushUObject(L, GameInstanceTarget);
lua_pushinteger(L, static_cast<lua_Integer>(RequestId));
lua_pushboolean(L, bSuccess ? 1 : 0);
if (LoadedObject)
{
UnLua::PushUObject(L, LoadedObject);
}
else
{
lua_pushnil(L);
}
const FTCHARToUTF8 PathUtf8(*ResolvedPath);
lua_pushlstring(L, PathUtf8.Get(), PathUtf8.Length());
const FTCHARToUTF8 ErrUtf8(*ErrorMessage);
lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length());
const bool bOk = (lua_pcall(L, 6, 0, ErrHandlerIdx) == LUA_OK);
lua_settop(L, Top);
return bOk;
}
+10 -1
View File
@@ -10,7 +10,7 @@ class UObject;
* 极薄 C++ -> Lua 回调分发器:
* 通过 __MODULE__.Import(ModuleName)[FuncName](Target, ...) 直接调用纯 TS/Lua 模块,
* 业务脚本无需在 Lua 中继承 UE 对象(不使用 IUnLuaInterface / UnLua.Class),
* 100% 纳入 Lib/Module.lua 与 Lib/Class.lua 的单文件热更闭环。
* 100% 纳入 lib/module.lua 与 lib/class.lua 的单文件热更闭环。
*/
class UNREALLUADEMO_API FLuaCallbackBridge
{
@@ -18,4 +18,13 @@ public:
static bool Call(UObject* Target, const FString& ModuleName, const char* FuncName);
static bool CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value);
static bool CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value);
static bool CallResourceLoadCallback(
UObject* GameInstanceTarget,
const FString& ModuleName,
const char* FuncName,
int64 RequestId,
bool bSuccess,
UObject* LoadedObject,
const FString& ResolvedPath,
const FString& ErrorMessage);
};
+2 -2
View File
@@ -7,7 +7,7 @@
#include "LuaCharacter.generated.h"
/**
* C++ 薄桥接 Character:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaCharacter。
* C++ 薄桥接 Character:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。
*/
UCLASS()
class UNREALLUADEMO_API ALuaCharacter : public ACharacter
@@ -22,5 +22,5 @@ public:
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaCharacter");
FString LuaModuleName;
};
@@ -3,17 +3,51 @@
#include "Core/LuaGameInstance.h"
#include "Core/LuaCallbackBridge.h"
#include "UnrealLuaDemo.h"
#include "Engine/World.h"
void ULuaGameInstance::Init()
{
Super::Init();
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Init() - LuaModule=%s"), *LuaModuleName);
FLuaCallbackBridge::Call(this, LuaModuleName, "OnInit");
CoreTickHandle = FTSTicker::GetCoreTicker().AddTicker(
FTickerDelegate::CreateUObject(this, &ULuaGameInstance::HandleCoreTick),
0.0f);
WorldCleanupHandle = FWorldDelegates::OnWorldCleanup.AddUObject(
this, &ULuaGameInstance::HandleWorldCleanup);
}
void ULuaGameInstance::Shutdown()
{
if (CoreTickHandle.IsValid())
{
FTSTicker::GetCoreTicker().RemoveTicker(CoreTickHandle);
CoreTickHandle.Reset();
}
if (WorldCleanupHandle.IsValid())
{
FWorldDelegates::OnWorldCleanup.Remove(WorldCleanupHandle);
WorldCleanupHandle.Reset();
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Shutdown()"));
FLuaCallbackBridge::Call(this, LuaModuleName, "OnShutdown");
Super::Shutdown();
}
bool ULuaGameInstance::HandleCoreTick(float DeltaSeconds)
{
FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds);
return true;
}
void ULuaGameInstance::HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources)
{
if (World && World->GetGameInstance() == this)
{
FLuaCallbackBridge::Call(this, LuaModuleName, "OnWorldCleanup");
}
}
+13 -2
View File
@@ -3,11 +3,15 @@
#pragma once
#include "CoreMinimal.h"
#include "Containers/Ticker.h"
#include "Engine/GameInstance.h"
#include "LuaGameInstance.generated.h"
class UWorld;
/**
* C++ 薄桥接 GameInstance:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameInstance。
* C++ 薄桥接 GameInstance:通过回调转发生命周期(OnInit / OnTick / OnWorldCleanup / OnShutdown)
* 至纯 TS/Lua 入口模块 `main`。
*/
UCLASS()
class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance
@@ -20,5 +24,12 @@ public:
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaGameInstance");
FString LuaModuleName = TEXT("main");
private:
bool HandleCoreTick(float DeltaSeconds);
void HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources);
FTSTicker::FDelegateHandle CoreTickHandle;
FDelegateHandle WorldCleanupHandle;
};
+2 -2
View File
@@ -7,7 +7,7 @@
#include "LuaGameModeBase.generated.h"
/**
* C++ 薄桥接 GameMode:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameMode。
* C++ 薄桥接 GameMode:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。
*/
UCLASS()
class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase
@@ -22,5 +22,5 @@ public:
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaGameMode");
FString LuaModuleName;
};
+458
View File
@@ -0,0 +1,458 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Core/LuaJsonLib.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonWriter.h"
#include "Policies/CondensedJsonPrintPolicy.h"
#include "lua.hpp"
namespace
{
constexpr int32 MaxJsonDepth = 64;
uint8 GJsonNullSentinel = 0;
uint8 GJsonEmptyArraySentinel = 0;
using FCondensedWriter = TJsonWriter<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>;
bool IsNullSentinel(lua_State* L, int32 Idx)
{
return lua_type(L, Idx) == LUA_TLIGHTUSERDATA && lua_touserdata(L, Idx) == &GJsonNullSentinel;
}
bool IsEmptyArraySentinel(lua_State* L, int32 Idx)
{
return lua_type(L, Idx) == LUA_TLIGHTUSERDATA && lua_touserdata(L, Idx) == &GJsonEmptyArraySentinel;
}
bool InspectTableShape(lua_State* L, int32 AbsIdx, bool& OutIsArray, int64& OutArrayLen)
{
int64 Count = 0;
int64 MaxIntKey = 0;
bool bAllPositiveIntKeys = true;
lua_pushnil(L);
while (lua_next(L, AbsIdx) != 0)
{
++Count;
if (bAllPositiveIntKeys)
{
if (lua_type(L, -2) == LUA_TNUMBER && lua_isinteger(L, -2))
{
const lua_Integer K = lua_tointeger(L, -2);
if (K > 0)
{
if (K > MaxIntKey)
{
MaxIntKey = static_cast<int64>(K);
}
}
else
{
bAllPositiveIntKeys = false;
}
}
else
{
bAllPositiveIntKeys = false;
}
}
lua_pop(L, 1);
}
OutIsArray = (Count > 0 && bAllPositiveIntKeys && MaxIntKey == Count);
OutArrayLen = OutIsArray ? Count : 0;
return true;
}
bool EncodeValue(lua_State* L, int32 Idx, const TSharedRef<FCondensedWriter>& Writer, const FString* KeyName, int32 Depth, FString& OutError)
{
if (Depth > MaxJsonDepth)
{
OutError = TEXT("JSON encode exceeded maximum recursion depth (64).");
return false;
}
const int32 AbsIdx = lua_absindex(L, Idx);
const int32 ValueType = lua_type(L, AbsIdx);
if (ValueType == LUA_TNIL || IsNullSentinel(L, AbsIdx))
{
if (KeyName) { Writer->WriteNull(*KeyName); }
else { Writer->WriteNull(); }
return true;
}
if (IsEmptyArraySentinel(L, AbsIdx))
{
if (KeyName) { Writer->WriteArrayStart(*KeyName); }
else { Writer->WriteArrayStart(); }
Writer->WriteArrayEnd();
return true;
}
switch (ValueType)
{
case LUA_TBOOLEAN:
{
const bool bVal = lua_toboolean(L, AbsIdx) != 0;
if (KeyName) { Writer->WriteValue(*KeyName, bVal); }
else { Writer->WriteValue(bVal); }
return true;
}
case LUA_TNUMBER:
{
if (lua_isinteger(L, AbsIdx))
{
const int64 IntVal = static_cast<int64>(lua_tointeger(L, AbsIdx));
if (KeyName) { Writer->WriteValue(*KeyName, IntVal); }
else { Writer->WriteValue(IntVal); }
}
else
{
const double NumVal = static_cast<double>(lua_tonumber(L, AbsIdx));
if (!FMath::IsFinite(NumVal))
{
OutError = TEXT("Cannot encode NaN or Infinity to JSON.");
return false;
}
if (KeyName) { Writer->WriteValue(*KeyName, NumVal); }
else { Writer->WriteValue(NumVal); }
}
return true;
}
case LUA_TSTRING:
{
size_t Len = 0;
const char* Str = lua_tolstring(L, AbsIdx, &Len);
const FUTF8ToTCHAR Conv(Str, static_cast<int32>(Len));
const FString ValueStr(Conv.Length(), Conv.Get());
if (KeyName) { Writer->WriteValue(*KeyName, ValueStr); }
else { Writer->WriteValue(ValueStr); }
return true;
}
case LUA_TTABLE:
{
bool bIsArray = false;
int64 ArrayLen = 0;
InspectTableShape(L, AbsIdx, bIsArray, ArrayLen);
if (bIsArray)
{
if (KeyName) { Writer->WriteArrayStart(*KeyName); }
else { Writer->WriteArrayStart(); }
for (int64 i = 1; i <= ArrayLen; ++i)
{
lua_rawgeti(L, AbsIdx, static_cast<lua_Integer>(i));
const bool bOk = EncodeValue(L, -1, Writer, nullptr, Depth + 1, OutError);
lua_pop(L, 1);
if (!bOk)
{
return false;
}
}
Writer->WriteArrayEnd();
return true;
}
else
{
if (KeyName) { Writer->WriteObjectStart(*KeyName); }
else { Writer->WriteObjectStart(); }
lua_pushnil(L);
while (lua_next(L, AbsIdx) != 0)
{
const int32 KeyType = lua_type(L, -2);
FString ChildKey;
if (KeyType == LUA_TSTRING)
{
size_t KeyLen = 0;
const char* KeyUtf8 = lua_tolstring(L, -2, &KeyLen);
const FUTF8ToTCHAR Conv(KeyUtf8, static_cast<int32>(KeyLen));
ChildKey = FString(Conv.Length(), Conv.Get());
}
else if (KeyType == LUA_TNUMBER)
{
if (lua_isinteger(L, -2))
{
ChildKey = FString::Printf(TEXT("%lld"), static_cast<long long>(lua_tointeger(L, -2)));
}
else
{
ChildKey = FString::SanitizeFloat(lua_tonumber(L, -2));
}
}
else
{
lua_pop(L, 2);
OutError = FString::Printf(TEXT("Unsupported JSON object key type: %s"), UTF8_TO_TCHAR(lua_typename(L, KeyType)));
return false;
}
const bool bOk = EncodeValue(L, -1, Writer, &ChildKey, Depth + 1, OutError);
lua_pop(L, 1);
if (!bOk)
{
lua_pop(L, 1);
return false;
}
}
Writer->WriteObjectEnd();
return true;
}
}
default:
OutError = FString::Printf(TEXT("Unsupported Lua type for JSON encode: %s"), UTF8_TO_TCHAR(lua_typename(L, ValueType)));
return false;
}
}
bool TryParseExactInt64(const FString& NumStr, int64& OutInt)
{
if (NumStr.IsEmpty())
{
return false;
}
for (int32 i = 0; i < NumStr.Len(); ++i)
{
const TCHAR Ch = NumStr[i];
if (Ch == TEXT('.') || Ch == TEXT('e') || Ch == TEXT('E'))
{
return false;
}
}
int64 Parsed = 0;
if (!LexTryParseString(Parsed, *NumStr))
{
return false;
}
// Verify exact round-trip so out-of-range integers fall back cleanly to double
const FString RoundTrip = FString::Printf(TEXT("%lld"), static_cast<long long>(Parsed));
if (RoundTrip != NumStr)
{
return false;
}
OutInt = Parsed;
return true;
}
bool DecodeNotation(lua_State* L, const TSharedRef<TJsonReader<TCHAR>>& Reader, EJsonNotation Notation, bool bKeepNull, int32 Depth, FString& OutError)
{
if (Depth > MaxJsonDepth)
{
OutError = TEXT("JSON decode exceeded maximum recursion depth (64).");
return false;
}
switch (Notation)
{
case EJsonNotation::Null:
if (bKeepNull)
{
lua_pushlightuserdata(L, &GJsonNullSentinel);
}
else
{
lua_pushnil(L);
}
return true;
case EJsonNotation::Boolean:
lua_pushboolean(L, Reader->GetValueAsBoolean() ? 1 : 0);
return true;
case EJsonNotation::Number:
{
const FString NumStr = Reader->GetValueAsNumberString();
int64 ExactInt = 0;
if (TryParseExactInt64(NumStr, ExactInt))
{
lua_pushinteger(L, static_cast<lua_Integer>(ExactInt));
}
else
{
lua_pushnumber(L, static_cast<lua_Number>(Reader->GetValueAsNumber()));
}
return true;
}
case EJsonNotation::String:
{
const FString& Val = Reader->GetValueAsString();
const FTCHARToUTF8 Utf8(*Val, Val.Len());
lua_pushlstring(L, Utf8.Get(), Utf8.Length());
return true;
}
case EJsonNotation::ArrayStart:
{
lua_newtable(L);
lua_Integer Index = 1;
EJsonNotation Next = EJsonNotation::Null;
while (Reader->ReadNext(Next))
{
if (Next == EJsonNotation::ArrayEnd)
{
return true;
}
if (Next == EJsonNotation::Error)
{
OutError = Reader->GetErrorMessage();
lua_pop(L, 1);
return false;
}
if (!DecodeNotation(L, Reader, Next, bKeepNull, Depth + 1, OutError))
{
lua_pop(L, 1);
return false;
}
lua_rawseti(L, -2, Index++);
}
OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Unexpected EOF in JSON array.") : Reader->GetErrorMessage();
lua_pop(L, 1);
return false;
}
case EJsonNotation::ObjectStart:
{
lua_newtable(L);
EJsonNotation Next = EJsonNotation::Null;
while (Reader->ReadNext(Next))
{
if (Next == EJsonNotation::ObjectEnd)
{
return true;
}
if (Next == EJsonNotation::Error)
{
OutError = Reader->GetErrorMessage();
lua_pop(L, 1);
return false;
}
const FString& Key = Reader->GetIdentifier();
const FTCHARToUTF8 KeyUtf8(*Key, Key.Len());
lua_pushlstring(L, KeyUtf8.Get(), KeyUtf8.Length());
if (!DecodeNotation(L, Reader, Next, bKeepNull, Depth + 1, OutError))
{
lua_pop(L, 2); // key + table
return false;
}
lua_rawset(L, -3);
}
OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Unexpected EOF in JSON object.") : Reader->GetErrorMessage();
lua_pop(L, 1);
return false;
}
default:
OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Invalid JSON token.") : Reader->GetErrorMessage();
return false;
}
}
int LuaJsonEncode(lua_State* L)
{
if (lua_gettop(L) < 1)
{
lua_pushnil(L);
lua_pushliteral(L, "ue_json.encode requires 1 argument");
return 2;
}
FString Output;
TSharedRef<FCondensedWriter> Writer = TJsonWriterFactory<TCHAR, TCondensedJsonPrintPolicy<TCHAR>>::Create(&Output);
FString ErrorMsg;
if (!EncodeValue(L, 1, Writer, nullptr, 0, ErrorMsg))
{
const FTCHARToUTF8 ErrUtf8(*ErrorMsg);
lua_pushnil(L);
lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length());
return 2;
}
Writer->Close();
const FTCHARToUTF8 OutUtf8(*Output, Output.Len());
lua_pushlstring(L, OutUtf8.Get(), OutUtf8.Length());
return 1;
}
int LuaJsonDecode(lua_State* L)
{
size_t Len = 0;
const char* RawUtf8 = luaL_checklstring(L, 1, &Len);
const bool bKeepNull = (lua_gettop(L) >= 2 && lua_toboolean(L, 2) != 0);
const FUTF8ToTCHAR Conv(RawUtf8, static_cast<int32>(Len));
const FString JsonText(Conv.Length(), Conv.Get());
TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(JsonText);
EJsonNotation First = EJsonNotation::Null;
if (!Reader->ReadNext(First) || First == EJsonNotation::Error)
{
const FString Err = Reader->GetErrorMessage().IsEmpty() ? TEXT("Empty or malformed JSON input.") : Reader->GetErrorMessage();
const FTCHARToUTF8 ErrUtf8(*Err);
lua_pushnil(L);
lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length());
return 2;
}
FString ErrorMsg;
if (!DecodeNotation(L, Reader, First, bKeepNull, 0, ErrorMsg))
{
const FTCHARToUTF8 ErrUtf8(*ErrorMsg);
lua_pushnil(L);
lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length());
return 2;
}
// Ensure no trailing garbage tokens after top-level value
EJsonNotation Trailing = EJsonNotation::Null;
if (Reader->ReadNext(Trailing))
{
lua_pop(L, 1);
lua_pushnil(L);
lua_pushliteral(L, "Trailing characters after top-level JSON value.");
return 2;
}
return 1;
}
int LuaOpenUeJson(lua_State* L)
{
lua_newtable(L);
lua_pushcfunction(L, &LuaJsonEncode);
lua_setfield(L, -2, "encode");
lua_pushcfunction(L, &LuaJsonDecode);
lua_setfield(L, -2, "decode");
lua_pushlightuserdata(L, &GJsonNullSentinel);
lua_setfield(L, -2, "null");
lua_pushlightuserdata(L, &GJsonEmptyArraySentinel);
lua_setfield(L, -2, "empty_array");
return 1;
}
}
void FLuaJsonLib::Register(lua_State* L)
{
if (!L)
{
return;
}
luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
lua_pushcfunction(L, &LuaOpenUeJson);
lua_setfield(L, -2, "ue_json");
lua_pop(L, 1);
}
+17
View File
@@ -0,0 +1,17 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
struct lua_State;
/**
* Registers the native UE Json streaming library (`ue_json`) into `package.preload["ue_json"]`.
* Uses UE's built-in TJsonReader/TJsonWriter directly against lua_State* with lossless Lua 5.4 int64 support.
*/
class UNREALLUADEMO_API FLuaJsonLib
{
public:
static void Register(lua_State* L);
};
@@ -2,23 +2,11 @@
#include "Core/LuaPlayerController.h"
#include "Core/LuaCallbackBridge.h"
#include "Demo/LuaDemoActor.h"
#include "UnrealLuaDemo.h"
#include "Components/InputComponent.h"
#include "Engine/World.h"
#include "EngineUtils.h"
#include "InputCoreTypes.h"
#include "InputKeyEventArgs.h"
#include "TimerManager.h"
void ALuaPlayerController::BeginPlay()
{
Super::BeginPlay();
bShowMouseCursor = false;
FInputModeGameOnly InputMode;
SetInputMode(InputMode);
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
}
@@ -27,112 +15,3 @@ void ALuaPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason)
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
Super::EndPlay(EndPlayReason);
}
void ALuaPlayerController::SetupInputComponent()
{
Super::SetupInputComponent();
if (InputComponent)
{
FInputKeyBinding& PingBinding = InputComponent->BindKey(EKeys::SpaceBar, IE_Pressed, this, &ALuaPlayerController::HandlePingKeyPressed);
PingBinding.bConsumeInput = false;
FInputKeyBinding& ReloadBinding = InputComponent->BindKey(EKeys::R, IE_Pressed, this, &ALuaPlayerController::HandleHotReloadKeyPressed);
ReloadBinding.bConsumeInput = false;
}
}
void ALuaPlayerController::HandlePingKeyPressed()
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua"));
FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoPingPressed");
}
void ALuaPlayerController::HandleHotReloadKeyPressed()
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua"));
FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoHotReloadPressed");
}
void ALuaPlayerController::DemoVerifyInteraction()
{
UWorld* World = GetWorld();
if (!World)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Scheduling simulated SpaceBar and R key presses after world ticks..."));
FTimerHandle Step1Handle;
World->GetTimerManager().SetTimer(Step1Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 1: Simulating SpaceBar Pressed/Released"));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Pressed, 1.0f));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Released, 0.0f));
}, 0.35f, false);
FTimerHandle Step2Handle;
World->GetTimerManager().SetTimer(Step2Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC)
{
return;
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 2: Simulating R Pressed/Released"));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Pressed, 1.0f));
PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Released, 0.0f));
}, 0.70f, false);
FTimerHandle Step3Handle;
World->GetTimerManager().SetTimer(Step3Handle, [WeakSelf = TWeakObjectPtr<ALuaPlayerController>(this)]()
{
ALuaPlayerController* PC = WeakSelf.Get();
if (!PC || !PC->GetWorld())
{
return;
}
ALuaDemoActor* DemoActor = nullptr;
if (TActorIterator<ALuaDemoActor> It(PC->GetWorld()); It)
{
DemoActor = *It;
}
if (!DemoActor)
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: ALuaDemoActor not found in world."));
FPlatformMisc::RequestExitWithStatus(false, 1);
return;
}
const FString StatusStr = DemoActor->GetStatusTextString();
const FRotator CubeRot = DemoActor->GetCubeLocalRotation();
const bool bHasTickRotation = !CubeRot.IsNearlyZero();
const bool bHasPing = StatusStr.Contains(TEXT("Pings: 1"));
const bool bHasReload = StatusStr.Contains(TEXT("Reloads: 1"));
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 3 Result -> CubeRot=%s | StatusText=\n%s"),
*CubeRot.ToString(), *StatusStr);
if (bHasTickRotation && bHasPing && bHasReload)
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] PASSED: Tick rotation, SpaceBar Ping, and R HotReload all verified!"));
PC->ConsoleCommand(TEXT("Quit"));
}
else
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: TickRot=%d Ping=%d Reload=%d"),
bHasTickRotation ? 1 : 0, bHasPing ? 1 : 0, bHasReload ? 1 : 0);
FPlatformMisc::RequestExitWithStatus(false, 1);
}
}, 1.15f, false);
}
@@ -7,8 +7,7 @@
#include "LuaPlayerController.generated.h"
/**
* C++ 薄桥接 PlayerController:不实现 IUnLuaInterface,通过 FLuaCallbackBridge
* 将生命周期与按键事件([Space] Ping, [R] HotReload)分发至纯 TS 模块 Game.LuaPlayerController。
* C++ 薄桥接 PlayerController:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。
*/
UCLASS()
class UNREALLUADEMO_API ALuaPlayerController : public APlayerController
@@ -18,17 +17,8 @@ class UNREALLUADEMO_API ALuaPlayerController : public APlayerController
public:
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void SetupInputComponent() override;
/** Automated self-test command (console: Demo.VerifyInteraction) that simulates Space & R and verifies Tick + Lua state. */
UFUNCTION(Exec)
void DemoVerifyInteraction();
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaPlayerController");
private:
void HandlePingKeyPressed();
void HandleHotReloadKeyPressed();
FString LuaModuleName = TEXT("game.bootstrap_player");
};
-121
View File
@@ -1,121 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Demo/LuaDemoActor.h"
#include "Core/LuaCallbackBridge.h"
#include "Components/StaticMeshComponent.h"
#include "Components/TextRenderComponent.h"
#include "Engine/StaticMesh.h"
#include "Materials/MaterialInterface.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "UObject/ConstructorHelpers.h"
ALuaDemoActor::ALuaDemoActor()
{
PrimaryActorTick.bCanEverTick = true;
SceneRoot = CreateDefaultSubobject<USceneComponent>(TEXT("SceneRoot"));
SetRootComponent(SceneRoot);
CubeMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("CubeMesh"));
CubeMesh->SetupAttachment(SceneRoot);
static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeMeshAsset(TEXT("/Engine/BasicShapes/Cube.Cube"));
if (CubeMeshAsset.Succeeded())
{
CubeMesh->SetStaticMesh(CubeMeshAsset.Object);
}
static ConstructorHelpers::FObjectFinder<UMaterialInterface> BasicMatAsset(TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial"));
if (BasicMatAsset.Succeeded())
{
CubeMesh->SetMaterial(0, BasicMatAsset.Object);
}
StatusText = CreateDefaultSubobject<UTextRenderComponent>(TEXT("StatusText"));
StatusText->SetupAttachment(SceneRoot);
StatusText->SetRelativeLocation(FVector(0.0f, 0.0f, 120.0f));
// Face -X toward PlayerStart placed at (-450, 0, 100)
StatusText->SetRelativeRotation(FRotator(0.0f, 180.0f, 0.0f));
StatusText->SetHorizontalAlignment(EHTA_Center);
StatusText->SetVerticalAlignment(EVRTA_TextCenter);
StatusText->SetWorldSize(26.0f);
StatusText->SetTextRenderColor(FColor(120, 245, 255));
StatusText->SetText(FText::FromString(TEXT("Waiting for Lua...")));
}
void ALuaDemoActor::BeginPlay()
{
InitialLocation = GetActorLocation();
if (CubeMesh)
{
CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0);
}
Super::BeginPlay();
FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay");
}
void ALuaDemoActor::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds);
}
void ALuaDemoActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast<int32>(EndPlayReason));
Super::EndPlay(EndPlayReason);
}
void ALuaDemoActor::SetStatusText(const FString& InText)
{
if (StatusText)
{
StatusText->SetText(FText::FromString(InText));
}
}
FString ALuaDemoActor::GetStatusTextString() const
{
return StatusText ? StatusText->Text.ToString() : FString();
}
void ALuaDemoActor::SetCubeColor(FLinearColor NewColor)
{
CurrentCubeColor = NewColor;
if (!CubeDynamicMaterial && CubeMesh)
{
CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0);
}
if (CubeDynamicMaterial)
{
CubeDynamicMaterial->SetVectorParameterValue(TEXT("Color"), NewColor);
}
}
void ALuaDemoActor::AddCubeLocalRotation(FRotator DeltaRotation)
{
if (CubeMesh)
{
CubeMesh->AddLocalRotation(DeltaRotation);
}
}
FRotator ALuaDemoActor::GetCubeLocalRotation() const
{
return CubeMesh ? CubeMesh->GetRelativeRotation() : FRotator::ZeroRotator;
}
void ALuaDemoActor::SetCubeVerticalOffset(float ZOffset)
{
if (CubeMesh)
{
CubeMesh->SetRelativeLocation(FVector(0.0f, 0.0f, ZOffset));
}
}
-91
View File
@@ -1,91 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "LuaDemoActor.generated.h"
class UStaticMeshComponent;
class UTextRenderComponent;
class UMaterialInstanceDynamic;
/**
* C++ 薄桥接 Demo Actor:不实现 IUnLuaInterface(不在 Lua 侧继承 UE 对象),
* 通过 FLuaCallbackBridge 将 BeginPlay / Tick / EndPlay 回调分发给纯 TS 模块 Game.LuaDemoActor,
* 以便运行时 100% 通过 __MODULE__.ReimportSafely("Game.LuaDemoActor") 单文件热更旋转速度、颜色与逻辑。
*/
UCLASS(Blueprintable)
class UNREALLUADEMO_API ALuaDemoActor : public AActor
{
GENERATED_BODY()
public:
ALuaDemoActor();
virtual void BeginPlay() override;
virtual void Tick(float DeltaSeconds) override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
/** Updates the floating 3D status text rendered above the cube. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetStatusText(const FString& InText);
/** Returns the current floating 3D status text string. */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FString GetStatusTextString() const;
/** Updates the dynamic material color of the demo cube. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetCubeColor(FLinearColor NewColor);
/** Returns the last applied dynamic material color of the demo cube. */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FLinearColor GetCubeColor() const { return CurrentCubeColor; }
/** Returns the world location captured at BeginPlay (used for smooth bobbing). */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FVector GetInitialLocation() const { return InitialLocation; }
/** Rotates only the cube mesh while keeping the floating 3D label readable. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void AddCubeLocalRotation(FRotator DeltaRotation);
/** Returns the current relative rotation of the cube mesh. */
UFUNCTION(BlueprintPure, Category = "LuaDemo")
FRotator GetCubeLocalRotation() const;
/** Sets the vertical bob offset of the cube mesh relative to the actor root. */
UFUNCTION(BlueprintCallable, Category = "LuaDemo")
void SetCubeVerticalOffset(float ZOffset);
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<USceneComponent> SceneRoot;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<UStaticMeshComponent> CubeMesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo")
TObjectPtr<UTextRenderComponent> StatusText;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float SpinSpeed = 60.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float BobAmplitude = 25.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo")
float BobFrequency = 2.0f;
protected:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua")
FString LuaModuleName = TEXT("Game.LuaDemoActor");
private:
UPROPERTY(Transient)
TObjectPtr<UMaterialInstanceDynamic> CubeDynamicMaterial;
FLinearColor CurrentCubeColor = FLinearColor::White;
FVector InitialLocation = FVector::ZeroVector;
};
@@ -1,14 +1,11 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "HotUpdate/LuaHotUpdateSubsystem.h"
#include "Demo/LuaDemoActor.h"
#include "Core/LuaJsonLib.h"
#include "LuaBundle/LuaBundleAsset.h"
#include "LuaBundle/LuaScriptSettings.h"
#include "UnrealLuaDemo.h"
#include "UnLuaDelegates.h"
#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "EngineUtils.h"
#include "HAL/FileManager.h"
#include "Misc/CommandLine.h"
#include "Misc/DateTime.h"
@@ -118,19 +115,6 @@ bool ULuaHotUpdateSubsystem::PollHotReloadTriggerFile(float DeltaTime)
*FDateTime::Now().ToString(), *Line, bOk ? TEXT("true") : TEXT("false"));
}
if (UGameInstance* GI = GetGameInstance())
{
if (UWorld* World = GI->GetWorld())
{
for (TActorIterator<ALuaDemoActor> It(World); It; ++It)
{
const FLinearColor C = It->GetCubeColor();
ResultLog += FString::Printf(TEXT("Actor=%s Color=(%.2f,%.2f,%.2f) Status=%s\n"),
*It->GetName(), C.R, C.G, C.B, *It->GetStatusTextString().Replace(TEXT("\n"), TEXT(" | ")));
}
}
}
const FString ResultPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.result"));
FFileHelper::SaveStringToFile(ResultLog, *ResultPath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM);
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[HotReloadTrigger] Processed trigger:\n%s"), *ResultLog);
@@ -178,18 +162,20 @@ void ULuaHotUpdateSubsystem::HandleLuaStateCreated(lua_State* L)
return;
}
FLuaJsonLib::Register(L);
if (UnLua::FLuaEnv* Env = UnLua::FLuaEnv::FindEnv(L))
{
const bool bOk = Env->DoString(
TEXT("if not _G.__MODULE__ then require('Lib.Module') end\nif not _G.__TS__DefineClass then require('Lib.Class') end"),
TEXT("if not _G.__MODULE__ then require('lib.module') end\nif not _G.__TS__DefineClass then require('lib.class') end"),
TEXT("InitTs2LuaModuleRuntime"));
if (!bOk)
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize Lib.Module / Lib.Class runtime."));
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize lib.module / lib.class runtime."));
}
else
{
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized Lib.Module & Lib.Class runtime."));
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized lib.module & lib.class runtime."));
}
}
}
@@ -276,11 +262,24 @@ void ULuaHotUpdateSubsystem::ReloadAllLuaModules()
return;
}
const FString ReloadAllChunk = TEXT(
"if _G.__MODULE__ then\n"
" local mods = {}\n"
" for name in pairs(_G.__MODULE__.AllLoadedModules()) do\n"
" if type(name) == 'string' then mods[#mods + 1] = name end\n"
" end\n"
" table.sort(mods)\n"
" for _, name in ipairs(mods) do\n"
" _G.__MODULE__.ReimportSafely(name)\n"
" end\n"
"end"
);
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
{
if (UnLua::FLuaEnv* Env = Pair.Value)
{
Env->DoString(TEXT("__MODULE__.Import('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll"));
Env->DoString(ReloadAllChunk, TEXT("HotReloadAll"));
}
}
}
@@ -304,7 +303,9 @@ bool ULuaHotUpdateSubsystem::ReloadLuaModule(const FString& ModuleName)
EscapedName.ReplaceInline(TEXT("\\"), TEXT("\\\\"));
EscapedName.ReplaceInline(TEXT("'"), TEXT("\\'"));
const FString Chunk = FString::Printf(TEXT("__MODULE__.Import('Framework.HotReload').ReloadModule('%s')"), *EscapedName);
const FString Chunk = FString::Printf(
TEXT("if _G.__MODULE__ and _G.__MODULE__.GetModuleByName('%s') ~= nil then assert(_G.__MODULE__.ReimportSafely('%s')) end"),
*EscapedName, *EscapedName);
bool bAnySucceeded = false;
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
@@ -0,0 +1,756 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Resource/LuaResourceSubsystem.h"
#include "Core/LuaCallbackBridge.h"
#include "UnrealLuaDemo.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Engine/Blueprint.h"
#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "HAL/FileManager.h"
#include "HAL/PlatformFileManager.h"
#include "IPlatformFilePak.h"
#include "Misc/CommandLine.h"
#include "Misc/PackageName.h"
#include "Misc/Parse.h"
#include "Misc/Paths.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonSerializer.h"
void ULuaResourceSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{
Super::Initialize(Collection);
bIsDeinitializing = false;
WorldCleanupHandle = FWorldDelegates::OnWorldCleanup.AddUObject(
this, &ULuaResourceSubsystem::HandleWorldCleanup);
if (IsPackagedResourceMode())
{
ScanAndMountExistingPatches();
}
UE_LOG(LogUnrealLuaDemo, Log,
TEXT("[LuaResourceSubsystem] Initialized (Mode=%s, PatchDir=%s, MountedPatches=%d)"),
IsPackagedResourceMode() ? TEXT("Packaged/Patch") : TEXT("Editor/PIE"),
*GetHotUpdatePakDir(),
MountedPatches.Num());
}
void ULuaResourceSubsystem::Deinitialize()
{
bIsDeinitializing = true;
if (WorldCleanupHandle.IsValid())
{
FWorldDelegates::OnWorldCleanup.Remove(WorldCleanupHandle);
WorldCleanupHandle.Reset();
}
for (FTSTicker::FDelegateHandle& Handle : PendingDeferredTickHandles)
{
if (Handle.IsValid())
{
FTSTicker::GetCoreTicker().RemoveTicker(Handle);
}
}
PendingDeferredTickHandles.Reset();
for (TPair<FSoftObjectPath, FInFlightEntry>& Pair : InFlightByPath)
{
if (Pair.Value.Handle.IsValid())
{
Pair.Value.Handle->CancelHandle();
}
}
InFlightByPath.Reset();
RequestsById.Reset();
for (TPair<FSoftObjectPath, FRetainedAssetEntry>& Pair : RetainedAssets)
{
if (Pair.Value.Handle.IsValid())
{
Pair.Value.Handle->ReleaseHandle();
}
}
RetainedAssets.Reset();
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Deinitialized."));
Super::Deinitialize();
}
ULuaResourceSubsystem* ULuaResourceSubsystem::GetFromGameInstance(UGameInstance* GameInstance)
{
return GameInstance ? GameInstance->GetSubsystem<ULuaResourceSubsystem>() : nullptr;
}
bool ULuaResourceSubsystem::IsPackagedResourceMode()
{
#if WITH_EDITOR
return FParse::Param(FCommandLine::Get(), TEXT("UsePatchPaks"));
#else
return true;
#endif
}
FString ULuaResourceSubsystem::GetHotUpdatePakDir()
{
#if PLATFORM_IOS || PLATFORM_ANDROID
return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectPersistentDownloadDir(), TEXT("HotUpdate/Paks")));
#else
return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/Paks")));
#endif
}
void ULuaResourceSubsystem::RegisterBaseAssetKey(const FString& LogicalKey, const FString& SoftPath)
{
if (!LogicalKey.IsEmpty() && !SoftPath.IsEmpty())
{
BaseCatalog.Add(LogicalKey, SoftPath);
}
}
FString ULuaResourceSubsystem::ResolveAssetPath(const FString& KeyOrPath) const
{
if (const FString* PatchPath = PatchOverlayCatalog.Find(KeyOrPath))
{
return *PatchPath;
}
if (const FString* BasePath = BaseCatalog.Find(KeyOrPath))
{
return *BasePath;
}
return KeyOrPath;
}
FSoftObjectPath ULuaResourceSubsystem::NormalizeSoftPath(const FString& RawPath, bool bIsClassLoad) const
{
FString Resolved = ResolveAssetPath(RawPath).TrimStartAndEnd();
if (Resolved.IsEmpty())
{
return FSoftObjectPath();
}
// Support passing bare package path "/Game/UI/WBP_MiniSettings" for class/object loads
if (!Resolved.Contains(TEXT(".")))
{
const FString ShortName = FPackageName::GetShortName(Resolved);
if (!ShortName.IsEmpty())
{
Resolved = bIsClassLoad
? FString::Printf(TEXT("%s.%s_C"), *Resolved, *ShortName)
: FString::Printf(TEXT("%s.%s"), *Resolved, *ShortName);
}
}
else if (bIsClassLoad && !Resolved.EndsWith(TEXT("_C")) && !Resolved.StartsWith(TEXT("/Script/")))
{
Resolved += TEXT("_C");
}
return FSoftObjectPath(Resolved);
}
bool ULuaResourceSubsystem::DoesAssetExist(const FString& KeyOrPath) const
{
const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false);
if (!SoftPath.IsValid())
{
return false;
}
const FString PackageName = SoftPath.GetLongPackageName();
if (PackageName.IsEmpty())
{
return false;
}
if (PackageName.StartsWith(TEXT("/Script/")))
{
return FindObject<UObject>(nullptr, *SoftPath.ToString()) != nullptr;
}
return FPackageName::DoesPackageExist(PackageName);
}
int64 ULuaResourceSubsystem::RequestLoadObjectAsync(const FString& KeyOrPath, int32 WorldGen)
{
return EnqueueAsyncLoad(KeyOrPath, WorldGen, /*bIsClassLoad=*/false);
}
int64 ULuaResourceSubsystem::RequestLoadClassAsync(const FString& KeyOrPath, int32 WorldGen)
{
return EnqueueAsyncLoad(KeyOrPath, WorldGen, /*bIsClassLoad=*/true);
}
int64 ULuaResourceSubsystem::EnqueueAsyncLoad(const FString& KeyOrPath, int32 WorldGen, bool bIsClassLoad)
{
const int64 RequestId = ++NextRequestId;
if (bIsDeinitializing)
{
return RequestId;
}
const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, bIsClassLoad);
FRequestRecord Record;
Record.RequestId = RequestId;
Record.SoftPath = SoftPath;
Record.WorldGen = WorldGen;
Record.bIsClassLoad = bIsClassLoad;
Record.bCancelled = false;
RequestsById.Add(RequestId, Record);
if (!SoftPath.IsValid())
{
TWeakObjectPtr<ULuaResourceSubsystem> WeakThis(this);
FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker(
FTickerDelegate::CreateLambda([WeakThis, RequestId, KeyOrPath](float)
{
if (ULuaResourceSubsystem* Self = WeakThis.Get())
{
Self->DeliverDeferredResult(
RequestId,
false,
FSoftObjectPath(),
FString::Printf(TEXT("Invalid asset path or logical key: '%s'"), *KeyOrPath));
}
return false;
}),
0.0f);
PendingDeferredTickHandles.Add(Handle);
return RequestId;
}
// 1. Fast-path cache hit if already retained
if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath))
{
if (Existing->Handle.IsValid() && Existing->Handle->HasLoadCompleted())
{
UObject* CachedObj = ExtractLoadedAsset(Existing->Handle, SoftPath, bIsClassLoad);
if (IsValid(CachedObj))
{
TWeakObjectPtr<ULuaResourceSubsystem> WeakThis(this);
FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker(
FTickerDelegate::CreateLambda([WeakThis, RequestId, SoftPath](float)
{
if (ULuaResourceSubsystem* Self = WeakThis.Get())
{
Self->DeliverDeferredResult(RequestId, true, SoftPath, FString());
}
return false;
}),
0.0f);
PendingDeferredTickHandles.Add(Handle);
return RequestId;
}
}
}
// 2. Coalesce onto an already in-flight request for the exact same FSoftObjectPath
if (FInFlightEntry* InFlight = InFlightByPath.Find(SoftPath))
{
InFlight->WaiterIds.Add(RequestId);
return RequestId;
}
// 3. Cold async load via FStreamableManager (register InFlightByPath before binding delegate to prevent sync-completion races)
FInFlightEntry NewEntry;
NewEntry.bIsClassLoad = bIsClassLoad;
NewEntry.WaiterIds.Add(RequestId);
TSharedPtr<FStreamableHandle> StreamHandle = StreamableManager.RequestAsyncLoad(
SoftPath,
FStreamableDelegate(),
FStreamableManager::AsyncLoadHighPriority,
/*bManageActiveHandle=*/false);
if (!StreamHandle.IsValid())
{
TWeakObjectPtr<ULuaResourceSubsystem> WeakThis(this);
FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker(
FTickerDelegate::CreateLambda([WeakThis, RequestId, SoftPath](float)
{
if (ULuaResourceSubsystem* Self = WeakThis.Get())
{
Self->DeliverDeferredResult(
RequestId,
false,
SoftPath,
FString::Printf(TEXT("FStreamableManager failed to start async load for '%s'"), *SoftPath.ToString()));
}
return false;
}),
0.0f);
PendingDeferredTickHandles.Add(Handle);
return RequestId;
}
NewEntry.Handle = StreamHandle;
InFlightByPath.Add(SoftPath, MoveTemp(NewEntry));
if (StreamHandle->HasLoadCompleted())
{
TWeakObjectPtr<ULuaResourceSubsystem> WeakThis(this);
FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker(
FTickerDelegate::CreateLambda([WeakThis, SoftPath](float)
{
if (ULuaResourceSubsystem* Self = WeakThis.Get())
{
Self->HandleStreamableLoadComplete(SoftPath);
}
return false;
}),
0.0f);
PendingDeferredTickHandles.Add(Handle);
}
else
{
StreamHandle->BindCompleteDelegate(
FStreamableDelegate::CreateUObject(this, &ULuaResourceSubsystem::HandleStreamableLoadComplete, SoftPath));
}
return RequestId;
}
UObject* ULuaResourceSubsystem::ExtractLoadedAsset(
const TSharedPtr<FStreamableHandle>& Handle,
const FSoftObjectPath& SoftPath,
bool bIsClassLoad) const
{
UObject* LoadedObj = Handle.IsValid() ? Handle->GetLoadedAsset() : nullptr;
if (!LoadedObj && SoftPath.IsValid())
{
LoadedObj = SoftPath.ResolveObject();
}
if (bIsClassLoad && LoadedObj)
{
if (UClass* AsClass = Cast<UClass>(LoadedObj))
{
return AsClass;
}
if (UBlueprint* AsBP = Cast<UBlueprint>(LoadedObj))
{
return AsBP->GeneratedClass;
}
return nullptr;
}
return LoadedObj;
}
void ULuaResourceSubsystem::HandleStreamableLoadComplete(FSoftObjectPath SoftPath)
{
if (bIsDeinitializing)
{
return;
}
FInFlightEntry Entry;
if (!InFlightByPath.RemoveAndCopyValue(SoftPath, Entry))
{
return;
}
TArray<FRequestRecord> ActiveWaiters;
for (int64 WaiterId : Entry.WaiterIds)
{
FRequestRecord Record;
if (RequestsById.RemoveAndCopyValue(WaiterId, Record) && !Record.bCancelled)
{
ActiveWaiters.Add(MoveTemp(Record));
}
}
if (ActiveWaiters.Num() == 0)
{
if (Entry.Handle.IsValid())
{
Entry.Handle->ReleaseHandle();
}
return;
}
UObject* LoadedObj = ExtractLoadedAsset(Entry.Handle, SoftPath, Entry.bIsClassLoad);
const bool bLoadedOk = IsValid(LoadedObj);
if (bLoadedOk)
{
FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath);
if (!Retained.Handle.IsValid())
{
Retained.Handle = Entry.Handle;
}
else if (Entry.Handle.IsValid() && Entry.Handle != Retained.Handle)
{
Entry.Handle->ReleaseHandle();
}
Retained.RefCount += ActiveWaiters.Num();
const FString ResolvedStr = SoftPath.ToString();
for (const FRequestRecord& Waiter : ActiveWaiters)
{
NotifyLuaCompletion(Waiter.RequestId, true, LoadedObj, ResolvedStr, FString());
}
}
else
{
if (Entry.Handle.IsValid())
{
Entry.Handle->ReleaseHandle();
}
const FString ResolvedStr = SoftPath.ToString();
const FString ErrMsg = FString::Printf(TEXT("Failed to load asset '%s'."), *ResolvedStr);
for (const FRequestRecord& Waiter : ActiveWaiters)
{
NotifyLuaCompletion(Waiter.RequestId, false, nullptr, ResolvedStr, ErrMsg);
}
}
}
void ULuaResourceSubsystem::DeliverDeferredResult(int64 RequestId, bool bSuccess, FSoftObjectPath SoftPath, FString ErrorMessage)
{
if (bIsDeinitializing)
{
return;
}
FRequestRecord Record;
if (!RequestsById.RemoveAndCopyValue(RequestId, Record) || Record.bCancelled)
{
return;
}
if (!bSuccess)
{
NotifyLuaCompletion(RequestId, false, nullptr, SoftPath.ToString(), ErrorMessage);
return;
}
FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath);
UObject* LoadedObj = Existing ? ExtractLoadedAsset(Existing->Handle, SoftPath, Record.bIsClassLoad) : nullptr;
if (Existing && IsValid(LoadedObj))
{
Existing->RefCount += 1;
NotifyLuaCompletion(RequestId, true, LoadedObj, SoftPath.ToString(), FString());
}
else
{
NotifyLuaCompletion(
RequestId,
false,
nullptr,
SoftPath.ToString(),
FString::Printf(TEXT("Cached asset '%s' was no longer valid at delivery time."), *SoftPath.ToString()));
}
}
void ULuaResourceSubsystem::NotifyLuaCompletion(
int64 RequestId,
bool bSuccess,
UObject* LoadedObj,
const FString& ResolvedPath,
const FString& ErrorMessage)
{
FLuaCallbackBridge::CallResourceLoadCallback(
GetGameInstance(),
LuaCallbackModule,
"OnNativeLoadComplete",
RequestId,
bSuccess,
LoadedObj,
ResolvedPath,
ErrorMessage);
}
UObject* ULuaResourceSubsystem::LoadObjectSync(const FString& KeyOrPath)
{
const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false);
if (!SoftPath.IsValid())
{
return nullptr;
}
if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath))
{
UObject* Cached = ExtractLoadedAsset(Existing->Handle, SoftPath, false);
if (IsValid(Cached))
{
Existing->RefCount += 1;
return Cached;
}
}
TSharedPtr<FStreamableHandle> Handle = StreamableManager.RequestSyncLoad(SoftPath, /*bManageActiveHandle=*/false);
UObject* Loaded = ExtractLoadedAsset(Handle, SoftPath, false);
if (!IsValid(Loaded))
{
if (Handle.IsValid())
{
Handle->ReleaseHandle();
}
return nullptr;
}
FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath);
Retained.Handle = Handle;
Retained.RefCount += 1;
return Loaded;
}
UClass* ULuaResourceSubsystem::LoadClassSync(const FString& KeyOrPath)
{
const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, true);
if (!SoftPath.IsValid())
{
return nullptr;
}
if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath))
{
if (UClass* Cached = Cast<UClass>(ExtractLoadedAsset(Existing->Handle, SoftPath, true)))
{
Existing->RefCount += 1;
return Cached;
}
}
TSharedPtr<FStreamableHandle> Handle = StreamableManager.RequestSyncLoad(SoftPath, /*bManageActiveHandle=*/false);
UClass* LoadedClass = Cast<UClass>(ExtractLoadedAsset(Handle, SoftPath, true));
if (!IsValid(LoadedClass))
{
if (Handle.IsValid())
{
Handle->ReleaseHandle();
}
return nullptr;
}
FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath);
Retained.Handle = Handle;
Retained.RefCount += 1;
return LoadedClass;
}
bool ULuaResourceSubsystem::CancelRequest(int64 RequestId)
{
FRequestRecord Record;
if (!RequestsById.RemoveAndCopyValue(RequestId, Record))
{
return false;
}
Record.bCancelled = true;
if (FInFlightEntry* InFlight = InFlightByPath.Find(Record.SoftPath))
{
InFlight->WaiterIds.Remove(RequestId);
if (InFlight->WaiterIds.Num() == 0)
{
if (InFlight->Handle.IsValid())
{
InFlight->Handle->CancelHandle();
}
InFlightByPath.Remove(Record.SoftPath);
}
}
return true;
}
int32 ULuaResourceSubsystem::CancelRequestsForWorld(int32 WorldGen)
{
TArray<int64> ToCancel;
for (const TPair<int64, FRequestRecord>& Pair : RequestsById)
{
if (Pair.Value.WorldGen == WorldGen)
{
ToCancel.Add(Pair.Key);
}
}
for (int64 RequestId : ToCancel)
{
CancelRequest(RequestId);
}
return ToCancel.Num();
}
void ULuaResourceSubsystem::ReleaseAsset(const FString& ResolvedSoftPath)
{
const FSoftObjectPath SoftPath(ResolvedSoftPath);
FRetainedAssetEntry* Retained = RetainedAssets.Find(SoftPath);
if (!Retained)
{
return;
}
Retained->RefCount -= 1;
if (Retained->RefCount <= 0)
{
if (Retained->Handle.IsValid())
{
Retained->Handle->ReleaseHandle();
}
RetainedAssets.Remove(SoftPath);
}
}
bool ULuaResourceSubsystem::PurgeCachedAsset(const FString& KeyOrPath)
{
const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false);
if (FRetainedAssetEntry* Retained = RetainedAssets.Find(SoftPath))
{
if (Retained->RefCount > 0)
{
return false;
}
if (Retained->Handle.IsValid())
{
Retained->Handle->ReleaseHandle();
}
RetainedAssets.Remove(SoftPath);
return true;
}
return false;
}
bool ULuaResourceSubsystem::MountPatchContainer(const FString& ContainerPath, int32 Priority, const FString& MountPoint)
{
if (ContainerPath.IsEmpty() || !FPaths::FileExists(ContainerPath))
{
UE_LOG(LogUnrealLuaDemo, Warning, TEXT("[LuaResourceSubsystem] MountPatchContainer: file not found '%s'."), *ContainerPath);
return false;
}
FPakPlatformFile* PakPlatform = static_cast<FPakPlatformFile*>(
FPlatformFileManager::Get().FindPlatformFile(FPakPlatformFile::GetTypeName()));
if (!PakPlatform)
{
UE_LOG(LogUnrealLuaDemo, Warning,
TEXT("[LuaResourceSubsystem] MountPatchContainer: FPakPlatformFile is inactive in current runtime (Container=%s)."),
*ContainerPath);
return false;
}
const FString EffectiveMountPoint = MountPoint.IsEmpty() ? FPaths::ProjectContentDir() : MountPoint;
if (!PakPlatform->Mount(*ContainerPath, static_cast<uint32>(FMath::Max(0, Priority)), *EffectiveMountPoint))
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaResourceSubsystem] Failed to mount patch container '%s'."), *ContainerPath);
return false;
}
FMountedPatchContainerInfo Info;
Info.ContainerPath = ContainerPath;
Info.MountPoint = EffectiveMountPoint;
Info.Priority = Priority;
MountedPatches.Add(MoveTemp(Info));
if (FModuleManager::Get().IsModuleLoaded(TEXT("AssetRegistry")))
{
IAssetRegistry& AssetRegistry = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(TEXT("AssetRegistry")).Get();
AssetRegistry.ScanPathsSynchronous({ TEXT("/Game") }, /*bForceRescan=*/false);
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Mounted patch container '%s' (priority=%d)."), *ContainerPath, Priority);
return true;
}
bool ULuaResourceSubsystem::UnmountPatchContainer(const FString& ContainerPath)
{
FPakPlatformFile* PakPlatform = static_cast<FPakPlatformFile*>(
FPlatformFileManager::Get().FindPlatformFile(FPakPlatformFile::GetTypeName()));
if (!PakPlatform)
{
return false;
}
const bool bUnmounted = PakPlatform->Unmount(*ContainerPath);
if (bUnmounted)
{
MountedPatches.RemoveAll([&ContainerPath](const FMountedPatchContainerInfo& Item)
{
return Item.ContainerPath == ContainerPath;
});
}
return bUnmounted;
}
bool ULuaResourceSubsystem::ApplyPatchManifest(const FString& ManifestJson)
{
TSharedPtr<FJsonObject> RootObj;
TSharedRef<TJsonReader<TCHAR>> Reader = TJsonReaderFactory<TCHAR>::Create(ManifestJson);
if (!FJsonSerializer::Deserialize(Reader, RootObj) || !RootObj.IsValid())
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaResourceSubsystem] ApplyPatchManifest: invalid JSON."));
return false;
}
for (const TPair<FString, TSharedPtr<FJsonValue>>& Pair : RootObj->Values)
{
FString TargetPath;
if (Pair.Value.IsValid() && Pair.Value->TryGetString(TargetPath) && !TargetPath.IsEmpty())
{
PatchOverlayCatalog.Add(Pair.Key, TargetPath);
}
}
UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Applied patch manifest (%d overlay keys)."), PatchOverlayCatalog.Num());
return true;
}
void ULuaResourceSubsystem::ClearPatchManifest()
{
PatchOverlayCatalog.Reset();
}
void ULuaResourceSubsystem::GetResourceStats(int32& OutInFlightCount, int32& OutRetainedAssetCount, int32& OutTotalRefCount) const
{
OutInFlightCount = RequestsById.Num();
OutRetainedAssetCount = RetainedAssets.Num();
int32 TotalRefs = 0;
for (const TPair<FSoftObjectPath, FRetainedAssetEntry>& Pair : RetainedAssets)
{
TotalRefs += Pair.Value.RefCount;
}
OutTotalRefCount = TotalRefs;
}
int32 ULuaResourceSubsystem::GetAssetRefCount(const FString& KeyOrPath) const
{
const FSoftObjectPath ObjPath = NormalizeSoftPath(KeyOrPath, false);
if (const FRetainedAssetEntry* Found = RetainedAssets.Find(ObjPath))
{
return Found->RefCount;
}
const FSoftObjectPath ClassPath = NormalizeSoftPath(KeyOrPath, true);
if (const FRetainedAssetEntry* FoundClass = RetainedAssets.Find(ClassPath))
{
return FoundClass->RefCount;
}
return 0;
}
void ULuaResourceSubsystem::ScanAndMountExistingPatches()
{
const FString PatchDir = GetHotUpdatePakDir();
if (!FPaths::DirectoryExists(PatchDir))
{
return;
}
TArray<FString> FoundPaks;
IFileManager::Get().FindFiles(FoundPaks, *FPaths::Combine(PatchDir, TEXT("*.pak")), /*Files=*/true, /*Directories=*/false);
FoundPaks.Sort();
int32 Priority = 100;
for (const FString& PakFile : FoundPaks)
{
MountPatchContainer(FPaths::Combine(PatchDir, PakFile), Priority++);
}
}
void ULuaResourceSubsystem::HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources)
{
// WorldGen cancellation is coordinated by TS GameInstanceContext::OnWorldCleanup -> CancelRequestsForWorld
}
@@ -0,0 +1,176 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Containers/Ticker.h"
#include "Engine/StreamableManager.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "UObject/SoftObjectPath.h"
#include "LuaResourceSubsystem.generated.h"
USTRUCT(BlueprintType)
struct UNREALLUADEMO_API FMountedPatchContainerInfo
{
GENERATED_BODY()
UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource")
FString ContainerPath;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource")
FString MountPoint;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource")
int32 Priority = 0;
};
/**
* C++ ResourceManager subsystem (per-GameInstance isolated).
*
* - Editor / PIE: directly loads loose assets under Content/ via AssetRegistry + FStreamableManager.
* - Packaged / Release (or -UsePatchPaks): loads from cooked base containers with higher-priority
* hot-update patch container mounting (PersistentDownloadDir/HotUpdate/Paks) and logical key overlay.
* - Coalesces concurrent async requests by FSoftObjectPath, supports per-caller independent cancellation,
* retains loaded UObjects via FStreamableHandle ref-counting, and delivers completions to pure TS via FLuaCallbackBridge.
*/
UCLASS()
class UNREALLUADEMO_API ULuaResourceSubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
virtual void Deinitialize() override;
/** Direct lookup from UGameInstance (works even during UGameInstance::Init before a UWorld exists). */
UFUNCTION(BlueprintPure, Category = "Lua|Resource")
static ULuaResourceSubsystem* GetFromGameInstance(UGameInstance* GameInstance);
/** True in Packaged/Release builds or when -UsePatchPaks is specified on the command line. */
UFUNCTION(BlueprintPure, Category = "Lua|Resource")
static bool IsPackagedResourceMode();
/** Returns the writable directory where future hot-update patch containers (.pak/.utoc) are stored. */
UFUNCTION(BlueprintPure, Category = "Lua|Resource")
static FString GetHotUpdatePakDir();
/** Registers a base logical key -> UE soft object/class path mapping. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
void RegisterBaseAssetKey(const FString& LogicalKey, const FString& SoftPath);
/** Resolves a logical key (PatchOverlay > BaseCatalog) or passes through a raw /Game/... path. */
UFUNCTION(BlueprintPure, Category = "Lua|Resource")
FString ResolveAssetPath(const FString& KeyOrPath) const;
/** Checks whether the resolved asset package exists in Content/ (PIE) or mounted containers (Packaged). */
UFUNCTION(BlueprintPure, Category = "Lua|Resource")
bool DoesAssetExist(const FString& KeyOrPath) const;
/** Asynchronous object load (e.g. UTexture2D). Completion invokes TS `OnNativeLoadComplete`. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
int64 RequestLoadObjectAsync(const FString& KeyOrPath, int32 WorldGen);
/** Asynchronous class load (e.g. Widget Blueprint generated class). Completion invokes TS `OnNativeLoadComplete`. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
int64 RequestLoadClassAsync(const FString& KeyOrPath, int32 WorldGen);
/** Synchronous object load (also increments retention RefCount when non-null). */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
UObject* LoadObjectSync(const FString& KeyOrPath);
/** Synchronous class load (also increments retention RefCount when non-null). */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
UClass* LoadClassSync(const FString& KeyOrPath);
/** Cancels a single caller request without aborting other coalesced callers waiting on the same asset. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
bool CancelRequest(int64 RequestId);
/** Cancels all in-flight requests belonging to a given WorldGen. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
int32 CancelRequestsForWorld(int32 WorldGen);
/** Decrements retention RefCount for a resolved soft path; releases FStreamableHandle when count hits 0. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
void ReleaseAsset(const FString& ResolvedSoftPath);
/** Releases an unused cached handle immediately if RefCount == 0 (for hot-update asset refresh). */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource")
bool PurgeCachedAsset(const FString& KeyOrPath);
// ------------------------------------------------------------------
// Hot-Update Patch Container Extension Hooks (for future patch system)
// ------------------------------------------------------------------
UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate")
bool MountPatchContainer(const FString& ContainerPath, int32 Priority = 100, const FString& MountPoint = TEXT(""));
UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate")
bool UnmountPatchContainer(const FString& ContainerPath);
/** Applies a JSON object `{ "logical_key": "/Game/..." }` into the high-priority PatchOverlayCatalog. */
UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate")
bool ApplyPatchManifest(const FString& ManifestJson);
UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate")
void ClearPatchManifest();
UFUNCTION(BlueprintPure, Category = "Lua|Resource|HotUpdate")
TArray<FMountedPatchContainerInfo> GetMountedPatchContainers() const { return MountedPatches; }
/** Diagnostics for leak verification and profiling. */
UFUNCTION(BlueprintPure, Category = "Lua|Resource|Debug")
void GetResourceStats(int32& OutInFlightCount, int32& OutRetainedAssetCount, int32& OutTotalRefCount) const;
UFUNCTION(BlueprintPure, Category = "Lua|Resource|Debug")
int32 GetAssetRefCount(const FString& KeyOrPath) const;
private:
struct FRetainedAssetEntry
{
TSharedPtr<FStreamableHandle> Handle;
int32 RefCount = 0;
};
struct FInFlightEntry
{
TSharedPtr<FStreamableHandle> Handle;
TArray<int64> WaiterIds;
bool bIsClassLoad = false;
};
struct FRequestRecord
{
int64 RequestId = 0;
FSoftObjectPath SoftPath;
int32 WorldGen = 0;
bool bIsClassLoad = false;
bool bCancelled = false;
};
int64 EnqueueAsyncLoad(const FString& KeyOrPath, int32 WorldGen, bool bIsClassLoad);
void HandleStreamableLoadComplete(FSoftObjectPath SoftPath);
void DeliverDeferredResult(int64 RequestId, bool bSuccess, FSoftObjectPath SoftPath, FString ErrorMessage);
void NotifyLuaCompletion(int64 RequestId, bool bSuccess, UObject* LoadedObj, const FString& ResolvedPath, const FString& ErrorMessage);
UObject* ExtractLoadedAsset(const TSharedPtr<FStreamableHandle>& Handle, const FSoftObjectPath& SoftPath, bool bIsClassLoad) const;
FSoftObjectPath NormalizeSoftPath(const FString& RawPath, bool bIsClassLoad) const;
void ScanAndMountExistingPatches();
void HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources);
FStreamableManager StreamableManager;
TMap<FString, FString> BaseCatalog;
TMap<FString, FString> PatchOverlayCatalog;
TArray<FMountedPatchContainerInfo> MountedPatches;
TMap<FSoftObjectPath, FRetainedAssetEntry> RetainedAssets;
TMap<FSoftObjectPath, FInFlightEntry> InFlightByPath;
TMap<int64, FRequestRecord> RequestsById;
TArray<FTSTicker::FDelegateHandle> PendingDeferredTickHandles;
int64 NextRequestId = 0;
bool bIsDeinitializing = false;
FDelegateHandle WorldCleanupHandle;
FString LuaCallbackModule = TEXT("framework.resource.resource_service");
};
@@ -0,0 +1,3 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Storage/LuaSaveGame.h"
@@ -0,0 +1,32 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/SaveGame.h"
#include "LuaSaveGame.generated.h"
/**
* UE native USaveGame byte container for dynamic Lua/TS key-value storage.
* Keeps C++ schema fixed while allowing arbitrary versioned JSON/binary payloads from TS/Lua.
*/
UCLASS()
class UNREALLUADEMO_API ULuaSaveGame : public USaveGame
{
GENERATED_BODY()
public:
static constexpr int32 CurrentContainerVersion = 1;
UPROPERTY()
int32 ContainerVersion = CurrentContainerVersion;
UPROPERTY()
FString ScopeName;
UPROPERTY()
uint32 PayloadCRC32 = 0;
UPROPERTY()
TArray<uint8> PayloadBytes;
};
@@ -0,0 +1,349 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "Storage/LuaStorageLibrary.h"
#include "UnrealLuaDemo.h"
#include "Misc/Crc.h"
#include "Misc/Paths.h"
#include "PlatformFeatures.h"
#include "SaveGameSystem.h"
namespace
{
constexpr uint32 LuaSaveMagic = 0x4C534156u; // 'LSAV'
constexpr uint32 CurrentEnvelopeVersion = 1u;
constexpr int32 EnvelopeHeaderSize = 20;
struct FLuaSaveEnvelopeHeader
{
uint32 Magic;
uint32 Version;
uint32 PayloadSize;
uint32 PayloadCRC32;
uint32 HeaderCRC32;
};
static_assert(sizeof(FLuaSaveEnvelopeHeader) == EnvelopeHeaderSize, "Unexpected header size");
bool IsValidSlotName(const FString& SlotName)
{
if (SlotName.IsEmpty() || SlotName.Len() > 128)
{
return false;
}
if (SlotName.Contains(TEXT("..")) || SlotName.Contains(TEXT("/")) || SlotName.Contains(TEXT("\\")))
{
return false;
}
for (int32 i = 0; i < SlotName.Len(); ++i)
{
const TCHAR Ch = SlotName[i];
const bool bOk = FChar::IsAlnum(Ch) || Ch == TEXT('_') || Ch == TEXT('-') || Ch == TEXT('.');
if (!bOk)
{
return false;
}
}
return true;
}
FString MakeBackupSlotName(const FString& SlotName)
{
return SlotName + TEXT(".bak");
}
FString MakeCorruptSlotName(const FString& SlotName)
{
return SlotName + TEXT(".corrupt");
}
ISaveGameSystem* GetSaveSystem()
{
return IPlatformFeaturesModule::Get().GetSaveGameSystem();
}
void EncodeEnvelope(const FString& PayloadUtf8, TArray<uint8>& OutBytes)
{
const FTCHARToUTF8 Utf8(*PayloadUtf8, PayloadUtf8.Len());
const int32 PayloadLen = Utf8.Length();
FLuaSaveEnvelopeHeader Header{};
Header.Magic = LuaSaveMagic;
Header.Version = CurrentEnvelopeVersion;
Header.PayloadSize = static_cast<uint32>(PayloadLen);
Header.PayloadCRC32 = PayloadLen > 0
? FCrc::MemCrc32(Utf8.Get(), PayloadLen)
: 0u;
Header.HeaderCRC32 = FCrc::MemCrc32(&Header, sizeof(FLuaSaveEnvelopeHeader) - sizeof(uint32));
OutBytes.SetNumUninitialized(EnvelopeHeaderSize + PayloadLen);
FMemory::Memcpy(OutBytes.GetData(), &Header, EnvelopeHeaderSize);
if (PayloadLen > 0)
{
FMemory::Memcpy(OutBytes.GetData() + EnvelopeHeaderSize, Utf8.Get(), PayloadLen);
}
}
bool DecodeAndVerifyEnvelope(
const TArray<uint8>& RawBytes,
int32& OutVersion,
FString& OutPayloadUtf8,
FString& OutError)
{
if (RawBytes.Num() < EnvelopeHeaderSize)
{
OutError = FString::Printf(TEXT("Slot too short (%d bytes)."), RawBytes.Num());
return false;
}
FLuaSaveEnvelopeHeader Header{};
FMemory::Memcpy(&Header, RawBytes.GetData(), EnvelopeHeaderSize);
if (Header.Magic != LuaSaveMagic)
{
OutError = FString::Printf(TEXT("Invalid magic 0x%08X."), Header.Magic);
return false;
}
const uint32 ExpectedHeaderCrc = FCrc::MemCrc32(&Header, sizeof(FLuaSaveEnvelopeHeader) - sizeof(uint32));
if (Header.HeaderCRC32 != ExpectedHeaderCrc)
{
OutError = TEXT("Header CRC32 mismatch.");
return false;
}
if (static_cast<int64>(EnvelopeHeaderSize) + static_cast<int64>(Header.PayloadSize) != static_cast<int64>(RawBytes.Num()))
{
OutError = FString::Printf(
TEXT("Payload length mismatch (header=%u, actual=%d)."),
Header.PayloadSize, RawBytes.Num() - EnvelopeHeaderSize);
return false;
}
const uint8* PayloadPtr = RawBytes.GetData() + EnvelopeHeaderSize;
const uint32 ComputedPayloadCrc = Header.PayloadSize > 0
? FCrc::MemCrc32(PayloadPtr, static_cast<int32>(Header.PayloadSize))
: 0u;
if (ComputedPayloadCrc != Header.PayloadCRC32)
{
OutError = FString::Printf(
TEXT("Payload CRC32 mismatch (expected=%u, actual=%u)."),
Header.PayloadCRC32, ComputedPayloadCrc);
return false;
}
OutVersion = static_cast<int32>(Header.Version);
if (Header.PayloadSize > 0)
{
const FUTF8ToTCHAR Conv(reinterpret_cast<const ANSICHAR*>(PayloadPtr), static_cast<int32>(Header.PayloadSize));
OutPayloadUtf8 = FString(Conv.Length(), Conv.Get());
}
else
{
OutPayloadUtf8.Empty();
}
return true;
}
bool TryLoadAndVerifySlot(
ISaveGameSystem* SaveSystem,
const FString& SlotName,
int32 UserIndex,
int32& OutVersion,
FString& OutPayloadUtf8,
TArray<uint8>& OutRawBytes,
FString& OutError)
{
OutRawBytes.Reset();
if (!SaveSystem || !SaveSystem->LoadGame(false, *SlotName, UserIndex, OutRawBytes))
{
OutError = FString::Printf(TEXT("ISaveGameSystem::LoadGame failed for slot '%s'."), *SlotName);
return false;
}
return DecodeAndVerifyEnvelope(OutRawBytes, OutVersion, OutPayloadUtf8, OutError);
}
}
FLuaStorageReadResult ULuaStorageLibrary::LoadSlotUtf8(const FString& SlotName, int32 UserIndex)
{
FLuaStorageReadResult Result;
if (!IsValidSlotName(SlotName))
{
Result.Status = ELuaStorageStatus::InvalidArgument;
Result.ErrorMessage = FString::Printf(TEXT("Invalid SaveGame slot name: '%s'."), *SlotName);
return Result;
}
ISaveGameSystem* SaveSystem = GetSaveSystem();
if (!SaveSystem)
{
Result.Status = ELuaStorageStatus::WriteFailed;
Result.ErrorMessage = TEXT("ISaveGameSystem is unavailable.");
return Result;
}
const bool bPrimaryExists = SaveSystem->DoesSaveGameExist(*SlotName, UserIndex);
const FString BackupSlot = MakeBackupSlotName(SlotName);
const bool bBackupExists = SaveSystem->DoesSaveGameExist(*BackupSlot, UserIndex);
if (!bPrimaryExists && !bBackupExists)
{
Result.Status = ELuaStorageStatus::NotFound;
return Result;
}
if (bPrimaryExists)
{
int32 Version = 0;
FString Payload;
TArray<uint8> RawBytes;
FString Err;
if (TryLoadAndVerifySlot(SaveSystem, SlotName, UserIndex, Version, Payload, RawBytes, Err))
{
Result.Status = ELuaStorageStatus::Ok;
Result.PayloadUtf8 = MoveTemp(Payload);
Result.ContainerVersion = Version;
Result.bRecoveredFromBackup = false;
return Result;
}
// Preserve corrupted primary bytes safely before any recovery
const FString CorruptSlot = MakeCorruptSlotName(SlotName);
if (RawBytes.Num() > 0)
{
SaveSystem->SaveGame(false, *CorruptSlot, UserIndex, RawBytes);
}
UE_LOG(LogUnrealLuaDemo, Warning,
TEXT("[LuaStorage] Primary slot '%s' corrupted (%s); preserved copy at '%s'."),
*SlotName, *Err, *CorruptSlot);
Result.ErrorMessage = Err;
}
if (bBackupExists)
{
int32 BackupVersion = 0;
FString BackupPayload;
TArray<uint8> BackupRaw;
FString BackupErr;
if (TryLoadAndVerifySlot(SaveSystem, BackupSlot, UserIndex, BackupVersion, BackupPayload, BackupRaw, BackupErr))
{
UE_LOG(LogUnrealLuaDemo, Warning,
TEXT("[LuaStorage] Recovered slot '%s' from backup '%s'."),
*SlotName, *BackupSlot);
Result.Status = ELuaStorageStatus::Ok;
Result.PayloadUtf8 = MoveTemp(BackupPayload);
Result.ContainerVersion = BackupVersion;
Result.bRecoveredFromBackup = true;
return Result;
}
if (Result.ErrorMessage.IsEmpty())
{
Result.ErrorMessage = BackupErr;
}
}
Result.Status = ELuaStorageStatus::Corrupted;
return Result;
}
ELuaStorageStatus ULuaStorageLibrary::SaveSlotUtf8(const FString& SlotName, const FString& PayloadUtf8, int32 UserIndex)
{
if (!IsValidSlotName(SlotName))
{
return ELuaStorageStatus::InvalidArgument;
}
ISaveGameSystem* SaveSystem = GetSaveSystem();
if (!SaveSystem)
{
return ELuaStorageStatus::WriteFailed;
}
// Copy valid existing primary slot to .bak before replacing
if (SaveSystem->DoesSaveGameExist(*SlotName, UserIndex))
{
int32 ExistingVersion = 0;
FString UnusedPayload;
TArray<uint8> ExistingRaw;
FString UnusedErr;
if (TryLoadAndVerifySlot(SaveSystem, SlotName, UserIndex, ExistingVersion, UnusedPayload, ExistingRaw, UnusedErr))
{
SaveSystem->SaveGame(false, *MakeBackupSlotName(SlotName), UserIndex, ExistingRaw);
}
}
TArray<uint8> Encoded;
EncodeEnvelope(PayloadUtf8, Encoded);
const bool bSaved = SaveSystem->SaveGame(false, *SlotName, UserIndex, Encoded);
return bSaved ? ELuaStorageStatus::Ok : ELuaStorageStatus::WriteFailed;
}
bool ULuaStorageLibrary::DeleteSlot(const FString& SlotName, int32 UserIndex, bool bDeleteBackups)
{
if (!IsValidSlotName(SlotName))
{
return false;
}
ISaveGameSystem* SaveSystem = GetSaveSystem();
if (!SaveSystem)
{
return false;
}
bool bRemovedAny = false;
if (SaveSystem->DoesSaveGameExist(*SlotName, UserIndex))
{
bRemovedAny |= SaveSystem->DeleteGame(false, *SlotName, UserIndex);
}
if (bDeleteBackups)
{
const FString BakSlot = MakeBackupSlotName(SlotName);
if (SaveSystem->DoesSaveGameExist(*BakSlot, UserIndex))
{
bRemovedAny |= SaveSystem->DeleteGame(false, *BakSlot, UserIndex);
}
const FString CorruptSlot = MakeCorruptSlotName(SlotName);
if (SaveSystem->DoesSaveGameExist(*CorruptSlot, UserIndex))
{
bRemovedAny |= SaveSystem->DeleteGame(false, *CorruptSlot, UserIndex);
}
}
return bRemovedAny;
}
bool ULuaStorageLibrary::DoesSlotExist(const FString& SlotName, int32 UserIndex)
{
ISaveGameSystem* SaveSystem = GetSaveSystem();
return SaveSystem && IsValidSlotName(SlotName) && SaveSystem->DoesSaveGameExist(*SlotName, UserIndex);
}
bool ULuaStorageLibrary::DoesCorruptBackupExist(const FString& SlotName, int32 UserIndex)
{
ISaveGameSystem* SaveSystem = GetSaveSystem();
return SaveSystem && IsValidSlotName(SlotName) && SaveSystem->DoesSaveGameExist(*MakeCorruptSlotName(SlotName), UserIndex);
}
FString ULuaStorageLibrary::GetSaveGamesDir()
{
return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SaveGames")));
}
bool ULuaStorageLibrary::WriteCorruptRawSlotForTest(const FString& SlotName, const FString& RawGarbage, int32 UserIndex)
{
ISaveGameSystem* SaveSystem = GetSaveSystem();
if (!SaveSystem || !IsValidSlotName(SlotName))
{
return false;
}
const FTCHARToUTF8 Utf8(*RawGarbage, RawGarbage.Len());
TArray<uint8> Bytes;
Bytes.SetNumUninitialized(Utf8.Length());
if (Utf8.Length() > 0)
{
FMemory::Memcpy(Bytes.GetData(), Utf8.Get(), Utf8.Length());
}
return SaveSystem->SaveGame(false, *SlotName, UserIndex, Bytes);
}
@@ -0,0 +1,71 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "LuaStorageLibrary.generated.h"
UENUM(BlueprintType)
enum class ELuaStorageStatus : uint8
{
Ok = 0,
NotFound = 1,
Corrupted = 2,
WriteFailed = 3,
InvalidArgument = 4
};
USTRUCT(BlueprintType)
struct UNREALLUADEMO_API FLuaStorageReadResult
{
GENERATED_BODY()
UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage")
ELuaStorageStatus Status = ELuaStorageStatus::NotFound;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage")
FString PayloadUtf8;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage")
int32 ContainerVersion = 0;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage")
bool bRecoveredFromBackup = false;
UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage")
FString ErrorMessage;
};
/**
* UE native local storage bridge backed by ISaveGameSystem / ULuaSaveGame.
* Provides CRC32 integrity checks, dual-slot (.bak) crash safety, and .corrupt preservation.
*/
UCLASS()
class UNREALLUADEMO_API ULuaStorageLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category = "Lua|Storage")
static FLuaStorageReadResult LoadSlotUtf8(const FString& SlotName, int32 UserIndex = 0);
UFUNCTION(BlueprintCallable, Category = "Lua|Storage")
static ELuaStorageStatus SaveSlotUtf8(const FString& SlotName, const FString& PayloadUtf8, int32 UserIndex = 0);
UFUNCTION(BlueprintCallable, Category = "Lua|Storage")
static bool DeleteSlot(const FString& SlotName, int32 UserIndex = 0, bool bDeleteBackups = true);
UFUNCTION(BlueprintPure, Category = "Lua|Storage")
static bool DoesSlotExist(const FString& SlotName, int32 UserIndex = 0);
UFUNCTION(BlueprintPure, Category = "Lua|Storage")
static bool DoesCorruptBackupExist(const FString& SlotName, int32 UserIndex = 0);
UFUNCTION(BlueprintPure, Category = "Lua|Storage")
static FString GetSaveGamesDir();
/** Test helper: writes malformed raw bytes directly into a SaveGame slot to verify corruption handling. */
UFUNCTION(BlueprintCallable, Category = "Lua|Storage|Test")
static bool WriteCorruptRawSlotForTest(const FString& SlotName, const FString& RawGarbage, int32 UserIndex = 0);
};
@@ -0,0 +1,113 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "UI/LuaUIEventSubsystem.h"
#include "Core/LuaCallbackBridge.h"
#include "Blueprint/UserWidget.h"
#include "Blueprint/WidgetTree.h"
#include "Components/Button.h"
#include "Engine/GameInstance.h"
void ULuaButtonClickProxy::Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId)
{
OwnerSubsystem = InOwner;
BoundButton = InButton;
BindingId = InBindingId;
if (InButton)
{
InButton->OnClicked.AddDynamic(this, &ULuaButtonClickProxy::HandleClicked);
}
}
void ULuaButtonClickProxy::Unbind()
{
if (UButton* Button = BoundButton.Get())
{
Button->OnClicked.RemoveDynamic(this, &ULuaButtonClickProxy::HandleClicked);
}
BoundButton.Reset();
OwnerSubsystem.Reset();
}
void ULuaButtonClickProxy::HandleClicked()
{
if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get())
{
Owner->DispatchButtonClicked(BindingId);
}
}
ULuaUIEventSubsystem* ULuaUIEventSubsystem::GetFromGameInstance(UGameInstance* GameInstance)
{
return GameInstance ? GameInstance->GetSubsystem<ULuaUIEventSubsystem>() : nullptr;
}
void ULuaUIEventSubsystem::Deinitialize()
{
for (TPair<int32, TObjectPtr<ULuaButtonClickProxy>>& Pair : ActiveButtonProxies)
{
if (Pair.Value)
{
Pair.Value->Unbind();
}
}
ActiveButtonProxies.Reset();
Super::Deinitialize();
}
int32 ULuaUIEventSubsystem::BindButtonClicked(UButton* Button)
{
if (!IsValid(Button))
{
return 0;
}
const int32 BindingId = ++NextBindingId;
ULuaButtonClickProxy* Proxy = NewObject<ULuaButtonClickProxy>(this);
Proxy->Init(this, Button, BindingId);
ActiveButtonProxies.Add(BindingId, Proxy);
return BindingId;
}
bool ULuaUIEventSubsystem::UnbindButtonClicked(int32 BindingId)
{
TObjectPtr<ULuaButtonClickProxy> Proxy;
if (!ActiveButtonProxies.RemoveAndCopyValue(BindingId, Proxy))
{
return false;
}
if (Proxy)
{
Proxy->Unbind();
}
return true;
}
UWidget* ULuaUIEventSubsystem::FindChildWidgetByName(UUserWidget* RootWidget, const FName& WidgetName)
{
if (!IsValid(RootWidget) || !RootWidget->WidgetTree)
{
return nullptr;
}
return RootWidget->WidgetTree->FindWidget(WidgetName);
}
bool ULuaUIEventSubsystem::SimulateButtonClick(UButton* Button)
{
if (!IsValid(Button))
{
return false;
}
Button->OnClicked.Broadcast();
return true;
}
void ULuaUIEventSubsystem::DispatchButtonClicked(int32 BindingId)
{
if (!ActiveButtonProxies.Contains(BindingId))
{
return;
}
FLuaCallbackBridge::CallInt(GetGameInstance(), LuaCallbackModule, "OnNativeButtonClicked", BindingId);
}
@@ -0,0 +1,73 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Subsystems/GameInstanceSubsystem.h"
#include "LuaUIEventSubsystem.generated.h"
class UButton;
class UUserWidget;
class ULuaUIEventSubsystem;
UCLASS()
class UNREALLUADEMO_API ULuaButtonClickProxy : public UObject
{
GENERATED_BODY()
public:
void Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId);
void Unbind();
UFUNCTION()
void HandleClicked();
private:
TWeakObjectPtr<ULuaUIEventSubsystem> OwnerSubsystem;
TWeakObjectPtr<UButton> BoundButton;
int32 BindingId = 0;
};
/**
* Per-GameInstance UMG delegate bridge for pure TS UI controllers.
* Routes UButton::OnClicked to TS `framework.ui.ui_delegate_bridge.OnNativeButtonClicked(gi, bindingId)`
* without requiring Lua UObject inheritance (@unlua), preserving 100% single-file hot-reload.
*/
UCLASS()
class UNREALLUADEMO_API ULuaUIEventSubsystem : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
virtual void Deinitialize() override;
/** Direct lookup from UGameInstance (works even during UGameInstance::Init before a UWorld exists). */
UFUNCTION(BlueprintPure, Category = "Lua|UI")
static ULuaUIEventSubsystem* GetFromGameInstance(UGameInstance* GameInstance);
UFUNCTION(BlueprintCallable, Category = "Lua|UI")
int32 BindButtonClicked(UButton* Button);
UFUNCTION(BlueprintCallable, Category = "Lua|UI")
bool UnbindButtonClicked(int32 BindingId);
UFUNCTION(BlueprintPure, Category = "Lua|UI")
int32 GetActiveBindingCount() const { return ActiveButtonProxies.Num(); }
/** Helper: finds a named UWidget inside a UUserWidget's WidgetTree (validates designer renames cleanly). */
UFUNCTION(BlueprintPure, Category = "Lua|UI")
static UWidget* FindChildWidgetByName(UUserWidget* RootWidget, const FName& WidgetName);
/** Simulates a button click for automated UE tests (invokes Button->OnClicked.Broadcast()). */
UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test")
static bool SimulateButtonClick(UButton* Button);
void DispatchButtonClicked(int32 BindingId);
private:
UPROPERTY(Transient)
TMap<int32, TObjectPtr<ULuaButtonClickProxy>> ActiveButtonProxies;
int32 NextBindingId = 0;
FString LuaCallbackModule = TEXT("framework.ui.ui_delegate_bridge");
};
+2 -1
View File
@@ -29,7 +29,8 @@ public class UnrealLuaDemo : ModuleRules
"SlateCore",
"Json",
"JsonUtilities",
"HTTP"
"HTTP",
"PakFile"
});
}
}
-44
View File
@@ -2,12 +2,7 @@
#include "UnrealLuaDemo.h"
#include "HotUpdate/LuaHotUpdateSubsystem.h"
#include "Engine/Engine.h"
#include "Engine/World.h"
#include "HAL/IConsoleManager.h"
#include "UnLua.h"
#include "LuaEnv.h"
#include "lua.hpp"
DEFINE_LOG_CATEGORY(LogUnrealLuaDemo);
@@ -39,51 +34,12 @@ void FUnrealLuaDemoModule::StartupModule()
}),
ECVF_Default);
RunTestsCmd = IConsoleManager::Get().RegisterConsoleCommand(
TEXT("Lua.RunTests"),
TEXT("Run compiled TypeScript -> UnLua runtime test suite in the current active game/PIE UWorld."),
FConsoleCommandWithWorldDelegate::CreateLambda([](UWorld* World)
{
TMap<lua_State*, UnLua::FLuaEnv*>& AllEnvs = UnLua::FLuaEnv::GetAll();
if (AllEnvs.Num() == 0)
{
UE_LOG(LogUnrealLuaDemo, Warning, TEXT("Lua.RunTests: No active UnLua environment (start PIE first)."));
return;
}
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
{
if (UnLua::FLuaEnv* Env = Pair.Value)
{
lua_State* L = Env->GetMainState();
if (L && World)
{
UnLua::PushUObject(L, World);
lua_setglobal(L, "__UE_TEST_WORLD");
}
Env->DoString(TEXT("__MODULE__.Import('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests"));
if (L)
{
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_WORLD");
}
break;
}
}
}),
ECVF_Default);
UE_LOG(LogUnrealLuaDemo, Log, TEXT("UnrealLuaDemo module started. Hot-update script dir: %s"),
*ULuaHotUpdateSubsystem::GetHotUpdateScriptDir());
}
void FUnrealLuaDemoModule::ShutdownModule()
{
if (RunTestsCmd)
{
IConsoleManager::Get().UnregisterConsoleObject(RunTestsCmd);
RunTestsCmd = nullptr;
}
if (HotReloadCmd)
{
IConsoleManager::Get().UnregisterConsoleObject(HotReloadCmd);
-1
View File
@@ -16,5 +16,4 @@ public:
private:
IConsoleObject* HotReloadCmd = nullptr;
IConsoleObject* ReloadModuleCmd = nullptr;
IConsoleObject* RunTestsCmd = nullptr;
};
@@ -0,0 +1,223 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "RunLuaFrameworkTestsCommandlet.h"
#include "UnrealLuaDemoEditor.h"
#include "Core/LuaGameInstance.h"
#include "Async/TaskGraphInterfaces.h"
#include "Containers/Ticker.h"
#include "Engine/Engine.h"
#include "Engine/World.h"
#include "GameFramework/WorldSettings.h"
#include "Tickable.h"
#include "UObject/UObjectGlobals.h"
#include "UnLua.h"
#include "UnLuaModule.h"
#include "LuaEnv.h"
#include "lua.hpp"
namespace
{
UWorld* GFrameworkTestWorld = nullptr;
int LuaFrameworkTestTick(lua_State* L)
{
const float DeltaSeconds = lua_gettop(L) >= 1 ? static_cast<float>(luaL_checknumber(L, 1)) : 0.016f;
++GFrameCounter;
if (IsAsyncLoading())
{
FPlatformProcess::Sleep(0.005f);
}
FTaskGraphInterface::Get().ProcessThreadUntilIdle(ENamedThreads::GameThread);
ProcessAsyncLoading(false, false, 0.0f);
FTSTicker::GetCoreTicker().Tick(DeltaSeconds);
FTickableGameObject::TickObjects(nullptr, LEVELTICK_All, false, DeltaSeconds);
if (GFrameworkTestWorld && IsValid(GFrameworkTestWorld))
{
GFrameworkTestWorld->Tick(LEVELTICK_All, DeltaSeconds);
}
return 0;
}
int LuaFrameworkTestCollectGarbage(lua_State* L)
{
lua_gc(L, LUA_GCCOLLECT, 0);
CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS, true);
return 0;
}
}
URunLuaFrameworkTestsCommandlet::URunLuaFrameworkTestsCommandlet()
{
IsClient = true;
IsEditor = true;
IsServer = false;
LogToConsole = true;
ShowErrorCount = true;
}
int32 URunLuaFrameworkTestsCommandlet::Main(const FString& Params)
{
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[RunLuaFrameworkTests] Starting UE 5.8 + UnLua framework test runner..."));
IUnLuaModule& UnLuaModule = IUnLuaModule::Get();
const bool bWasActive = UnLuaModule.IsActive();
if (!bWasActive)
{
UnLuaModule.SetActive(true);
}
UWorld* TestWorld = UWorld::CreateWorld(EWorldType::Game, false, TEXT("LuaFrameworkTestWorld"));
if (!TestWorld)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Failed to create UWorld."));
if (!bWasActive)
{
UnLuaModule.SetActive(false);
}
return 1;
}
ULuaGameInstance* TestGameInstance = NewObject<ULuaGameInstance>(GEngine);
TestGameInstance->AddToRoot();
FWorldContext& WorldContext = GEngine->CreateNewWorldContext(EWorldType::Game);
WorldContext.OwningGameInstance = TestGameInstance;
WorldContext.SetCurrentWorld(TestWorld);
TestWorld->SetGameInstance(TestGameInstance);
TestGameInstance->Init();
TestWorld->InitializeActorsForPlay(FURL());
if (AWorldSettings* WorldSettings = TestWorld->GetWorldSettings())
{
WorldSettings->NotifyBeginPlay();
WorldSettings->NotifyMatchStarted();
}
TestWorld->BeginPlay();
GFrameworkTestWorld = TestWorld;
int32 ExitCode = 1;
UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(TestGameInstance);
if (!Env)
{
Env = UnLuaModule.GetEnv(TestWorld);
}
if (!Env)
{
TMap<lua_State*, UnLua::FLuaEnv*>& AllEnvs = UnLua::FLuaEnv::GetAll();
for (const TPair<lua_State*, UnLua::FLuaEnv*>& Pair : AllEnvs)
{
if (Pair.Value)
{
Env = Pair.Value;
break;
}
}
}
if (!Env)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Failed to obtain UnLua FLuaEnv."));
}
else if (lua_State* L = Env->GetMainState())
{
UnLua::PushUObject(L, TestGameInstance);
lua_setglobal(L, "__UE_TEST_GAME_INSTANCE");
UnLua::PushUObject(L, TestWorld);
lua_setglobal(L, "__UE_TEST_WORLD");
lua_pushcfunction(L, &LuaFrameworkTestTick);
lua_setglobal(L, "__UE_TEST_TICK");
lua_pushcfunction(L, &LuaFrameworkTestCollectGarbage);
lua_setglobal(L, "__UE_TEST_GC");
const FString RunChunk = TEXT(
"local suite = __MODULE__.Import('tests.ue.run_ue_tests')\n"
"local runner = __MODULE__.Import('tests.harness.test_runner')\n"
"local summary = suite.RunAllUETests(_G.__UE_TEST_GAME_INSTANCE, _G.__UE_TEST_WORLD)\n"
"_G.__UE_TEST_TOTAL = summary.total or 0\n"
"_G.__UE_TEST_PASSED = summary.passed or 0\n"
"_G.__UE_TEST_FAILED = summary.failed or 0\n"
"_G.__UE_TEST_REPORT = runner.FormatReport(summary)\n"
);
const bool bExecOk = Env->DoString(RunChunk, TEXT("RunLuaFrameworkTestsCommandlet"));
lua_getglobal(L, "__UE_TEST_REPORT");
const char* ReportUtf8 = lua_tostring(L, -1);
const FString ReportText = ReportUtf8 ? UTF8_TO_TCHAR(ReportUtf8) : FString();
lua_pop(L, 1);
if (!ReportText.IsEmpty())
{
TArray<FString> Lines;
ReportText.ParseIntoArrayLines(Lines, false);
for (const FString& Line : Lines)
{
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("%s"), *Line);
}
}
lua_getglobal(L, "__UE_TEST_TOTAL");
const int32 Total = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
lua_getglobal(L, "__UE_TEST_PASSED");
const int32 Passed = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
lua_getglobal(L, "__UE_TEST_FAILED");
const int32 Failed = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_GAME_INSTANCE");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_WORLD");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_TICK");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_GC");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_REPORT");
if (!bExecOk)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Lua execution error in tests.ue.run_ue_tests."));
ExitCode = 1;
}
else if (Total <= 0 || Failed > 0)
{
UE_LOG(LogUnrealLuaDemoEditor, Error,
TEXT("[RunLuaFrameworkTests] FAILED (Total=%d, Passed=%d, Failed=%d)."),
Total, Passed, Failed);
ExitCode = 1;
}
else
{
UE_LOG(LogUnrealLuaDemoEditor, Display,
TEXT("[RunLuaFrameworkTests] PASSED (Total=%d, Passed=%d, Failed=%d)."),
Total, Passed, Failed);
ExitCode = 0;
}
}
GFrameworkTestWorld = nullptr;
TestWorld->EndPlay(EEndPlayReason::Quit);
TestGameInstance->Shutdown();
TestGameInstance->RemoveFromRoot();
GEngine->DestroyWorldContext(TestWorld);
TestWorld->DestroyWorld(false);
if (!bWasActive)
{
UnLuaModule.SetActive(false);
}
return ExitCode;
}
@@ -0,0 +1,26 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Commandlets/Commandlet.h"
#include "RunLuaFrameworkTestsCommandlet.generated.h"
/**
* Headless UE 5.8 + UnLua framework test runner commandlet.
* Boots a real ULuaGameInstance + UWorld + UnLua FLuaEnv and executes `tests.ue.run_ue_tests`.
*
* Usage:
* UnrealEditor-Cmd <Project.uproject> -run=RunLuaFrameworkTests -unattended -nop4 -nosplash -NullRHI
* (Optional: pass -UseLuaBundle to run tests directly from /Game/Generated/DA_LuaBundle)
*/
UCLASS()
class UNREALLUADEMOEDITOR_API URunLuaFrameworkTestsCommandlet : public UCommandlet
{
GENERATED_BODY()
public:
URunLuaFrameworkTestsCommandlet();
virtual int32 Main(const FString& Params) override;
};
@@ -1,172 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "RunLuaTestsCommandlet.h"
#include "UnrealLuaDemoEditor.h"
#include "Engine/Engine.h"
#include "Engine/World.h"
#include "GameFramework/WorldSettings.h"
#include "UnLua.h"
#include "UnLuaModule.h"
#include "LuaEnv.h"
#include "lua.hpp"
namespace
{
UWorld* GCurrentLuaTestWorld = nullptr;
int LuaTestWorldTick(lua_State* L)
{
const float DeltaSeconds = lua_gettop(L) >= 1 ? static_cast<float>(luaL_checknumber(L, 1)) : 0.016f;
if (GCurrentLuaTestWorld && IsValid(GCurrentLuaTestWorld))
{
// Advance GFrameCounter so FTimerManager::HasBeenTickedThisFrame() treats each call as a new engine frame.
++GFrameCounter;
GCurrentLuaTestWorld->Tick(LEVELTICK_All, DeltaSeconds);
}
return 0;
}
}
URunLuaTestsCommandlet::URunLuaTestsCommandlet()
{
IsClient = true;
IsEditor = true;
IsServer = false;
LogToConsole = true;
ShowErrorCount = true;
}
int32 URunLuaTestsCommandlet::Main(const FString& Params)
{
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[RunLuaTestsCommandlet] Starting real UE + UnLua test runner..."));
IUnLuaModule& UnLuaModule = IUnLuaModule::Get();
const bool bWasActive = UnLuaModule.IsActive();
if (!bWasActive)
{
UnLuaModule.SetActive(true);
}
UWorld* TestWorld = UWorld::CreateWorld(EWorldType::Game, false, TEXT("LuaTestWorld"));
if (!TestWorld)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to create UWorld."));
if (!bWasActive)
{
UnLuaModule.SetActive(false);
}
return 1;
}
FWorldContext& WorldContext = GEngine->CreateNewWorldContext(EWorldType::Game);
WorldContext.SetCurrentWorld(TestWorld);
TestWorld->InitializeActorsForPlay(FURL());
if (AWorldSettings* WorldSettings = TestWorld->GetWorldSettings())
{
WorldSettings->NotifyBeginPlay();
WorldSettings->NotifyMatchStarted();
}
TestWorld->BeginPlay();
GCurrentLuaTestWorld = TestWorld;
int32 ExitCode = 1;
UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(TestWorld);
if (!Env)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to obtain UnLua FLuaEnv."));
}
else
{
lua_State* L = Env->GetMainState();
if (L)
{
UnLua::PushUObject(L, TestWorld);
lua_setglobal(L, "__UE_TEST_WORLD");
lua_pushcfunction(L, &LuaTestWorldTick);
lua_setglobal(L, "__UE_TEST_TICK");
const FString RunChunk = TEXT(
"local suite = __MODULE__.Import('Tests.UE.UERuntimeSuite')\n"
"local runner = __MODULE__.Import('Tests.Harness.TestRunner')\n"
"local summary = suite.RunAllInUE(_G.__UE_TEST_WORLD)\n"
"_G.__UE_TEST_TOTAL = summary.total or 0\n"
"_G.__UE_TEST_PASSED = summary.passed or 0\n"
"_G.__UE_TEST_FAILED = summary.failed or 0\n"
"_G.__UE_TEST_REPORT = runner.FormatReport(summary)\n"
);
const bool bExecOk = Env->DoString(RunChunk, TEXT("RunLuaTestsCommandlet"));
lua_getglobal(L, "__UE_TEST_REPORT");
const char* ReportUtf8 = lua_tostring(L, -1);
const FString ReportText = ReportUtf8 ? UTF8_TO_TCHAR(ReportUtf8) : FString();
lua_pop(L, 1);
if (!ReportText.IsEmpty())
{
TArray<FString> Lines;
ReportText.ParseIntoArrayLines(Lines, false);
for (const FString& Line : Lines)
{
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("%s"), *Line);
}
}
lua_getglobal(L, "__UE_TEST_TOTAL");
const int32 Total = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
lua_getglobal(L, "__UE_TEST_PASSED");
const int32 Passed = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
lua_getglobal(L, "__UE_TEST_FAILED");
const int32 Failed = static_cast<int32>(lua_tointeger(L, -1));
lua_pop(L, 1);
// Clear test globals before teardown
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_WORLD");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_TICK");
lua_pushnil(L);
lua_setglobal(L, "__UE_TEST_REPORT");
if (!bExecOk)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Lua execution error while running Tests.UE.UERuntimeSuite."));
ExitCode = 1;
}
else if (Total <= 0 || Failed > 0)
{
UE_LOG(LogUnrealLuaDemoEditor, Error,
TEXT("[RunLuaTestsCommandlet] UE Lua tests FAILED (Total=%d, Passed=%d, Failed=%d)."),
Total, Passed, Failed);
ExitCode = 1;
}
else
{
UE_LOG(LogUnrealLuaDemoEditor, Display,
TEXT("[RunLuaTestsCommandlet] All UE Lua tests PASSED (Total=%d, Passed=%d, Failed=%d)."),
Total, Passed, Failed);
ExitCode = 0;
}
}
}
GCurrentLuaTestWorld = nullptr;
TestWorld->EndPlay(EEndPlayReason::Quit);
GEngine->DestroyWorldContext(TestWorld);
TestWorld->DestroyWorld(false);
if (!bWasActive)
{
UnLuaModule.SetActive(false);
}
return ExitCode;
}
@@ -1,26 +0,0 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Commandlets/Commandlet.h"
#include "RunLuaTestsCommandlet.generated.h"
/**
* Headless commandlet that boots a real UWorld + UnLua 2.3.6 Lua 5.4 runtime
* and executes the compiled TypeScript -> UnLua test suite (`Tests.UE.UERuntimeSuite`).
*
* Usage:
* UnrealEditor-Cmd <Project.uproject> -run=RunLuaTests -unattended -nop4 -nosplash -NullRHI
* (Optional: pass -UseLuaBundle to run tests directly from /Game/Generated/DA_LuaBundle)
*/
UCLASS()
class UNREALLUADEMOEDITOR_API URunLuaTestsCommandlet : public UCommandlet
{
GENERATED_BODY()
public:
URunLuaTestsCommandlet();
virtual int32 Main(const FString& Params) override;
};
@@ -0,0 +1,278 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#include "SetupFrameworkAssetsCommandlet.h"
#include "UnrealLuaDemoEditor.h"
#include "Core/LuaGameModeBase.h"
#include "AssetRegistry/AssetRegistryModule.h"
#include "Blueprint/WidgetTree.h"
#include "Components/Border.h"
#include "Components/Button.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "Components/Image.h"
#include "Components/TextBlock.h"
#include "Components/VerticalBox.h"
#include "Components/VerticalBoxSlot.h"
#include "Engine/Texture2D.h"
#include "Engine/World.h"
#include "GameFramework/WorldSettings.h"
#include "HAL/FileManager.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "Misc/PackageName.h"
#include "Misc/Paths.h"
#include "UObject/Package.h"
#include "UObject/SavePackage.h"
#include "WidgetBlueprint.h"
#include "WidgetBlueprintFactory.h"
namespace
{
bool SaveAssetPackage(UPackage* Package, UObject* Asset, const FString& LongPackageName)
{
if (!Package || !Asset)
{
return false;
}
const FString Extension = Asset->IsA<UWorld>()
? FPackageName::GetMapPackageExtension()
: FPackageName::GetAssetPackageExtension();
const FString Filename = FPackageName::LongPackageNameToFilename(LongPackageName, Extension);
IFileManager::Get().MakeDirectory(*FPaths::GetPath(Filename), /*Tree=*/true);
FSavePackageArgs SaveArgs;
SaveArgs.TopLevelFlags = RF_Public | RF_Standalone;
SaveArgs.Error = GError;
SaveArgs.bWarnOfLongFilename = false;
return UPackage::SavePackage(Package, Asset, *Filename, SaveArgs);
}
}
USetupFrameworkAssetsCommandlet::USetupFrameworkAssetsCommandlet()
{
IsClient = true;
IsEditor = true;
IsServer = false;
LogToConsole = true;
}
int32 USetupFrameworkAssetsCommandlet::Main(const FString& Params)
{
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupFrameworkAssets] Creating Phase-0 baseline assets..."));
if (!CreateBootstrapMap())
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/Maps/L_Bootstrap."));
return 1;
}
if (!CreateMiniSettingsTexture())
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/UI/Textures/T_MiniSettingsIcon."));
return 1;
}
if (!CreateMiniSettingsWidgetBlueprint())
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/UI/WBP_MiniSettings."));
return 1;
}
UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupFrameworkAssets] All Phase-0 baseline assets created successfully."));
return 0;
}
bool USetupFrameworkAssetsCommandlet::CreateBootstrapMap() const
{
const FString PackageName = TEXT("/Game/Maps/L_Bootstrap");
UPackage* Package = CreatePackage(*PackageName);
if (!Package)
{
return false;
}
UWorld* NewWorld = UWorld::CreateWorld(EWorldType::Inactive, false, TEXT("L_Bootstrap"), Package, true, ERHIFeatureLevel::Num);
if (!NewWorld)
{
return false;
}
NewWorld->SetFlags(RF_Public | RF_Standalone);
if (AWorldSettings* WS = NewWorld->GetWorldSettings())
{
WS->DefaultGameMode = ALuaGameModeBase::StaticClass();
}
FAssetRegistryModule::AssetCreated(NewWorld);
Package->MarkPackageDirty();
const bool bSaved = SaveAssetPackage(Package, NewWorld, PackageName);
NewWorld->DestroyWorld(false);
return bSaved;
}
bool USetupFrameworkAssetsCommandlet::CreateMiniSettingsTexture() const
{
const FString PackageName = TEXT("/Game/UI/Textures/T_MiniSettingsIcon");
const FString AssetName = TEXT("T_MiniSettingsIcon");
UPackage* Package = CreatePackage(*PackageName);
if (!Package)
{
return false;
}
constexpr int32 Size = 128;
UTexture2D* Texture = NewObject<UTexture2D>(Package, *AssetName, RF_Public | RF_Standalone);
if (!Texture)
{
return false;
}
TArray<uint8> Pixels;
Pixels.SetNumUninitialized(Size * Size * 4);
for (int32 Y = 0; Y < Size; ++Y)
{
for (int32 X = 0; X < Size; ++X)
{
const int32 Idx = (Y * Size + X) * 4;
const float Dx = (X - Size * 0.5f) / (Size * 0.5f);
const float Dy = (Y - Size * 0.5f) / (Size * 0.5f);
const float Dist = FMath::Sqrt(Dx * Dx + Dy * Dy);
const bool bRing = (Dist >= 0.45f && Dist <= 0.78f);
const bool bCore = (Dist <= 0.28f);
// BGRA8
if (bCore)
{
Pixels[Idx + 0] = 255;
Pixels[Idx + 1] = 220;
Pixels[Idx + 2] = 60;
Pixels[Idx + 3] = 255;
}
else if (bRing)
{
Pixels[Idx + 0] = 240;
Pixels[Idx + 1] = 170;
Pixels[Idx + 2] = 40;
Pixels[Idx + 3] = 255;
}
else
{
Pixels[Idx + 0] = 48;
Pixels[Idx + 1] = 36;
Pixels[Idx + 2] = 28;
Pixels[Idx + 3] = 255;
}
}
}
Texture->Source.Init(Size, Size, 1, 1, TSF_BGRA8, Pixels.GetData());
Texture->LODGroup = TEXTUREGROUP_UI;
Texture->CompressionSettings = TC_EditorIcon;
Texture->MipGenSettings = TMGS_NoMipmaps;
Texture->SRGB = true;
Texture->UpdateResource();
Texture->PostEditChange();
FAssetRegistryModule::AssetCreated(Texture);
Package->MarkPackageDirty();
return SaveAssetPackage(Package, Texture, PackageName);
}
bool USetupFrameworkAssetsCommandlet::CreateMiniSettingsWidgetBlueprint() const
{
const FString PackageName = TEXT("/Game/UI/WBP_MiniSettings");
const FString AssetName = TEXT("WBP_MiniSettings");
UPackage* Package = CreatePackage(*PackageName);
if (!Package)
{
return false;
}
UWidgetBlueprintFactory* Factory = NewObject<UWidgetBlueprintFactory>();
Factory->ParentClass = UUserWidget::StaticClass();
UWidgetBlueprint* WidgetBP = Cast<UWidgetBlueprint>(
Factory->FactoryCreateNew(UWidgetBlueprint::StaticClass(), Package, *AssetName, RF_Public | RF_Standalone, nullptr, GWarn));
if (!WidgetBP || !WidgetBP->WidgetTree)
{
return false;
}
UWidgetTree* Tree = WidgetBP->WidgetTree;
UCanvasPanel* RootCanvas = Tree->ConstructWidget<UCanvasPanel>(UCanvasPanel::StaticClass(), TEXT("RootCanvas"));
Tree->RootWidget = RootCanvas;
UBorder* PanelBorder = Tree->ConstructWidget<UBorder>(UBorder::StaticClass(), TEXT("PanelBorder"));
PanelBorder->SetBrushColor(FLinearColor(0.08f, 0.10f, 0.14f, 0.92f));
PanelBorder->SetPadding(FMargin(24.0f));
if (UCanvasPanelSlot* BorderSlot = RootCanvas->AddChildToCanvas(PanelBorder))
{
BorderSlot->SetAnchors(FAnchors(0.5f, 0.5f, 0.5f, 0.5f));
BorderSlot->SetAlignment(FVector2D(0.5f, 0.5f));
BorderSlot->SetSize(FVector2D(420.0f, 360.0f));
}
UVerticalBox* LayoutBox = Tree->ConstructWidget<UVerticalBox>(UVerticalBox::StaticClass(), TEXT("LayoutBox"));
PanelBorder->SetContent(LayoutBox);
// 1. Named Image: ImgIcon
UImage* ImgIcon = Tree->ConstructWidget<UImage>(UImage::StaticClass(), TEXT("ImgIcon"));
ImgIcon->bIsVariable = true;
ImgIcon->SetDesiredSizeOverride(FVector2D(96.0f, 96.0f));
if (UVerticalBoxSlot* IconSlot = LayoutBox->AddChildToVerticalBox(ImgIcon))
{
IconSlot->SetHorizontalAlignment(HAlign_Center);
IconSlot->SetPadding(FMargin(0.0f, 8.0f, 0.0f, 16.0f));
}
// 2. Named TextBlock: TxtStatus
UTextBlock* TxtStatus = Tree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass(), TEXT("TxtStatus"));
TxtStatus->bIsVariable = true;
TxtStatus->SetText(FText::FromString(TEXT("Mini Settings")));
if (UVerticalBoxSlot* StatusSlot = LayoutBox->AddChildToVerticalBox(TxtStatus))
{
StatusSlot->SetHorizontalAlignment(HAlign_Center);
StatusSlot->SetPadding(FMargin(0.0f, 0.0f, 0.0f, 16.0f));
}
// 3. Named Button: BtnToggle (+ TxtToggleLabel)
UButton* BtnToggle = Tree->ConstructWidget<UButton>(UButton::StaticClass(), TEXT("BtnToggle"));
BtnToggle->bIsVariable = true;
UTextBlock* TxtToggleLabel = Tree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass(), TEXT("TxtToggleLabel"));
TxtToggleLabel->bIsVariable = true;
TxtToggleLabel->SetText(FText::FromString(TEXT("Toggle Sound")));
BtnToggle->AddChild(TxtToggleLabel);
if (UVerticalBoxSlot* ToggleSlot = LayoutBox->AddChildToVerticalBox(BtnToggle))
{
ToggleSlot->SetHorizontalAlignment(HAlign_Fill);
ToggleSlot->SetPadding(FMargin(0.0f, 0.0f, 0.0f, 12.0f));
}
// 4. Named Button: BtnClose
UButton* BtnClose = Tree->ConstructWidget<UButton>(UButton::StaticClass(), TEXT("BtnClose"));
BtnClose->bIsVariable = true;
UTextBlock* TxtCloseLabel = Tree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass(), TEXT("TxtCloseLabel"));
TxtCloseLabel->SetText(FText::FromString(TEXT("Close")));
BtnClose->AddChild(TxtCloseLabel);
if (UVerticalBoxSlot* CloseSlot = LayoutBox->AddChildToVerticalBox(BtnClose))
{
CloseSlot->SetHorizontalAlignment(HAlign_Fill);
}
FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(WidgetBP);
FKismetEditorUtilities::CompileBlueprint(WidgetBP);
FAssetRegistryModule::AssetCreated(WidgetBP);
Package->MarkPackageDirty();
return SaveAssetPackage(Package, WidgetBP, PackageName);
}
@@ -0,0 +1,29 @@
// Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Commandlets/Commandlet.h"
#include "SetupFrameworkAssetsCommandlet.generated.h"
/**
* Generates deterministic Phase-0 baseline assets:
* 1. /Game/Maps/L_Bootstrap
* 2. /Game/UI/Textures/T_MiniSettingsIcon (128x128 UTexture2D)
* 3. /Game/UI/WBP_MiniSettings (UWidgetBlueprint with ImgIcon, TxtStatus, BtnToggle, TxtToggleLabel, BtnClose)
*/
UCLASS()
class UNREALLUADEMOEDITOR_API USetupFrameworkAssetsCommandlet : public UCommandlet
{
GENERATED_BODY()
public:
USetupFrameworkAssetsCommandlet();
virtual int32 Main(const FString& Params) override;
private:
bool CreateBootstrapMap() const;
bool CreateMiniSettingsTexture() const;
bool CreateMiniSettingsWidgetBlueprint() const;
};
@@ -22,11 +22,15 @@ public class UnrealLuaDemoEditor : ModuleRules
{
"UnrealEd",
"AssetRegistry",
"BlueprintGraph",
"DeveloperSettings",
"KismetCompiler",
"Projects",
"Slate",
"SlateCore",
"ToolMenus",
"UMG",
"UMGEditor",
"UnLua",
"Lua"
});