diff --git a/.gitignore b/.gitignore index 95b2c39..b12a138 100644 --- a/.gitignore +++ b/.gitignore @@ -24,8 +24,12 @@ Plugins/*/Source/**/obj/ Plugins/*/Source/**/bin/ *.ubtplugin.csproj.props -# --- UnLua Generated IntelliSense & Local HotUpdate Output --- +# --- UnLua Generated IntelliSense, TS Tooling & Local HotUpdate Output --- Content/Script/IntelliSense/ +Script/lua/IntelliSense/ +Script/ts/node_modules/ +Script/ts/dist/ +*.tsbuildinfo HotUpdateOutput/ *.luac diff --git a/Config/DefaultGame.ini b/Config/DefaultGame.ini index 6454c87..fab42f4 100644 --- a/Config/DefaultGame.ini +++ b/Config/DefaultGame.ini @@ -103,9 +103,15 @@ bSkipMovies=False +IniSectionDenylist=StorageServers +IniSectionDenylist=/Script/AndroidFileServerEditor.AndroidFileServerRuntimeSettings +DirectoriesToAlwaysCook=(Path="/NNEDenoiser") -+DirectoriesToAlwaysStageAsUFS=(Path="Script") -+DirectoriesToAlwaysStageAsUFS=(Path="../Plugins/UnLua/Content/Script") -+DirectoriesToAlwaysStageAsNonUFS=(Path="Script") ++DirectoriesToAlwaysCook=(Path="/Game/Generated") bRetainStagedDirectory=False CustomStageCopyHandler= +[/Script/UnrealLuaDemo.LuaScriptSettings] +ExternalScriptRelativePath=Script/lua +LuaBundleAssetPath=/Game/Generated/DA_LuaBundle.DA_LuaBundle +bIncludeUnLuaPluginScriptsInBundle=True +bEncryptBundle=True +BundleEncryptionKey=UnrealLuaDemo_LuaBundle_Key_v1 +bAutoPackOnCook=True + diff --git a/Content/Generated/DA_LuaBundle.uasset b/Content/Generated/DA_LuaBundle.uasset new file mode 100644 index 0000000..d2b8f86 Binary files /dev/null and b/Content/Generated/DA_LuaBundle.uasset differ diff --git a/Plugins/UnLua/Source/UnLua/Private/UnLuaFunctionLibrary.cpp b/Plugins/UnLua/Source/UnLua/Private/UnLuaFunctionLibrary.cpp index e13a5e3..a52d8ea 100644 --- a/Plugins/UnLua/Source/UnLua/Private/UnLuaFunctionLibrary.cpp +++ b/Plugins/UnLua/Source/UnLua/Private/UnLuaFunctionLibrary.cpp @@ -19,6 +19,11 @@ FString UUnLuaFunctionLibrary::GetScriptRootPath() { + const FString ExternalScriptDir = FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir(), TEXT("Script/lua/"))); + if (FPaths::DirectoryExists(ExternalScriptDir)) + { + return ExternalScriptDir; + } return FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir() + TEXT("Script/")); } diff --git a/Plugins/UnLua/Source/UnLua/Private/UnLuaLegacy.cpp b/Plugins/UnLua/Source/UnLua/Private/UnLuaLegacy.cpp index 9a2fb01..729701b 100644 --- a/Plugins/UnLua/Source/UnLua/Private/UnLuaLegacy.cpp +++ b/Plugins/UnLua/Source/UnLua/Private/UnLuaLegacy.cpp @@ -69,5 +69,5 @@ namespace UnLua } // namespace UnLua -FString GLuaSrcRelativePath = TEXT("Script/"); -FString GLuaSrcFullPath = FPaths::ConvertRelativePathToFull(FPaths::ProjectContentDir() + GLuaSrcRelativePath); +FString GLuaSrcRelativePath = TEXT("../Script/lua/"); +FString GLuaSrcFullPath = FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir(), TEXT("Script/lua/"))); diff --git a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaEditorModule.cpp b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaEditorModule.cpp index b136a0e..0686c8f 100644 --- a/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaEditorModule.cpp +++ b/Plugins/UnLua/Source/UnLuaEditor/Private/UnLuaEditorModule.cpp @@ -185,6 +185,14 @@ private: void SetupPackagingSettings() { + // When external /Script/lua is used, Lua scripts are packed into a binary UE asset + // instead of staging loose Content/Script directories. + const FString ExternalScriptDir = FPaths::Combine(FPaths::ProjectDir(), TEXT("Script/lua")); + if (FPaths::DirectoryExists(ExternalScriptDir)) + { + return; + } + auto ScriptPaths = TArray{TEXT("Script"), TEXT("../Plugins/UnLua/Content/Script")}; const auto Plugins = IPluginManager::Get().GetEnabledPlugins(); diff --git a/README.md b/README.md index bbd280d..46d2393 100644 --- a/README.md +++ b/README.md @@ -8,36 +8,47 @@ UnrealLuaDemo/ ├── Config/ # UE 项目配置(DefaultEngine / DefaultGame / DefaultInput 等) ├── Content/ -│ ├── Maps/ -│ │ └── L_LuaDemo.umap # Lua 执行与热更新验证 Demo 关卡(默认启动地图) -│ └── Script/ # Lua 脚本根目录(打包时通过 DirectoriesToAlwaysStageAsNonUFS 输出) -│ ├── Framework/ # Lua 基础框架层 -│ │ ├── Bootstrap.lua # 框架启动入口(由 LuaGameInstance 初始化) -│ │ ├── EventBus.lua # 轻量级事件总线 -│ │ ├── HotReload.lua # Lua 模块热重载协调器 -│ │ └── Log.lua # 统一日志封装 -│ └── Game/ # 游戏核心类与 Demo 对应的 Lua 绑定脚本 -│ ├── LuaGameInstance.lua -│ ├── LuaGameMode.lua -│ ├── LuaPlayerController.lua -│ ├── LuaCharacter.lua -│ └── LuaDemoActor.lua # Demo 场景中的旋转立方体与 3D 状态文本控制脚本 +│ ├── Generated/ +│ │ └── DA_LuaBundle.uasset # 打包/Cook 时自动生成的二进制 Lua 源码归档 UE 资源 +│ └── Maps/ +│ └── L_LuaDemo.umap # Lua 执行与热更新验证 Demo 关卡(默认启动地图) +├── Script/ # 外部脚本工程根目录(与 Content 同级,不作为 UE 散资源) +│ ├── lua/ # Lua 脚本目录(PIE 直接读取;打包时自动归档进 DA_LuaBundle) +│ │ ├── Framework/ # Lua 基础框架层 +│ │ │ ├── Bootstrap.lua # 框架启动入口(由 LuaGameInstance 初始化) +│ │ │ ├── EventBus.lua # 轻量级事件总线 +│ │ │ ├── HotReload.lua # Lua 模块热重载协调器 +│ │ │ └── Log.lua # 统一日志封装 +│ │ └── Game/ # 游戏核心类与 Demo 对应的 Lua 绑定脚本 +│ │ ├── LuaGameInstance.lua +│ │ ├── LuaGameMode.lua +│ │ ├── LuaPlayerController.lua +│ │ ├── LuaCharacter.lua +│ │ └── LuaDemoActor.lua # Demo 场景中的旋转立方体与 3D 状态文本控制脚本 +│ └── ts/ # TypeScript 源码目录(预留给 ts2lua,编译输出到 ../lua) ├── Plugins/ │ └── UnLua/ # Tencent UnLua 插件(已适配 UE 5.8 编译) ├── Source/ │ ├── UnrealLuaDemo.Target.cs │ ├── UnrealLuaDemoEditor.Target.cs -│ └── UnrealLuaDemo/ -│ ├── Core/ # 游戏框架 C++ 基类(实现 IUnLuaInterface) -│ │ ├── LuaGameInstance.* -│ │ ├── LuaGameModeBase.* -│ │ ├── LuaPlayerController.* -│ │ ├── LuaCharacter.* -│ │ └── LuaBlueprintLibrary.* -│ ├── Demo/ # 验证场景 Actor -│ │ └── LuaDemoActor.* -│ └── HotUpdate/ # Lua 热更新子系统 -│ └── LuaHotUpdateSubsystem.* +│ ├── UnrealLuaDemo/ +│ │ ├── Core/ # 游戏框架 C++ 基类(实现 IUnLuaInterface) +│ │ │ ├── LuaGameInstance.* +│ │ │ ├── LuaGameModeBase.* +│ │ │ ├── LuaPlayerController.* +│ │ │ ├── LuaCharacter.* +│ │ │ └── LuaBlueprintLibrary.* +│ │ ├── Demo/ # 验证场景 Actor +│ │ │ └── LuaDemoActor.* +│ │ ├── HotUpdate/ # Lua 自定义加载与热更新子系统 +│ │ │ └── LuaHotUpdateSubsystem.* +│ │ └── LuaBundle/ # 二进制 Lua 归档格式、ULuaBundleAsset 与项目设置 +│ │ ├── LuaBundleArchive.* +│ │ ├── LuaBundleAsset.* +│ │ └── LuaScriptSettings.* +│ └── UnrealLuaDemoEditor/ # 编辑器打包模块(Pre-Cook 自动打包、菜单、Commandlet) +│ ├── LuaBundlePacker.* +│ └── PackLuaBundleCommandlet.* ├── Tools/ │ └── create_demo_map.py # UE Python 关卡生成脚本(可重建 L_LuaDemo.umap) ├── .gitignore @@ -49,19 +60,22 @@ UnrealLuaDemo/ 打开 `UnrealLuaDemo.uproject` 后会自动加载默认关卡 `Content/Maps/L_LuaDemo.umap`,点击 **Play (PIE)** 即可验证: -- **自动执行验证**:场景中正前方的 `LuaDemoActor` 由 `Content/Script/Game/LuaDemoActor.lua` 驱动,会自动旋转、上下浮动,并在上方 3D 文本实时刷新 Lua 版本、运行时间、Ping 次数、热重载次数与当前颜色,同时屏幕左上角打印初始化信息。 +- **自动执行验证**:场景中正前方的 `LuaDemoActor` 由 `Script/lua/Game/LuaDemoActor.lua` 驱动,会自动旋转、上下浮动,并在上方 3D 文本实时刷新 Lua 版本、运行时间、Ping 次数、热重载次数与当前颜色,同时屏幕左上角打印初始化信息。 - **按 `Space`(空格)**:验证 `C++ 输入 -> LuaPlayerController -> EventBus -> LuaDemoActor -> C++ 材质颜色/3D 文本` 全链路,立方体切换颜色且计数 +1。 - **按 `R`**:触发全量 Lua 热重载(`HotReload.ReloadAll()`),热重载计数 +1;可先将修改后的脚本放到 `Saved/HotUpdate/Script/Game/LuaDemoActor.lua` 再按 `R` 直接验证热更新覆盖生效。 ## 核心设计 -1. **C++ 骨架 + Lua 业务分离** - - `ULuaGameInstance`、`ALuaGameModeBase`、`ALuaPlayerController`、`ALuaCharacter` 均实现 `IUnLuaInterface`,分别绑定到 `Content/Script/Game/` 下对应的 Lua 模块。 - - 底层性能敏感逻辑、引擎生命周期与热更新加载器位于 C++,玩法与业务迭代逻辑放在 Lua 层。 +1. **C++ 骨架 + 外部脚本目录分离(`Script/lua` + `Script/ts`)** + - `ULuaGameInstance`、`ALuaGameModeBase`、`ALuaPlayerController`、`ALuaCharacter` 均实现 `IUnLuaInterface`,分别绑定到 `Script/lua/Game/` 下对应的 Lua 模块。 + - `Script/lua` 与 `Content/` 同级,不作为 UE 散资源存在;同级 `Script/ts` 预留给 `ts2lua` TypeScript 源码工程。 -2. **Lua 代码热更新机制** - - `ULuaHotUpdateSubsystem` 在游戏启动时通过 `FUnLuaDelegates::CustomLoadLuaFile` 注册自定义脚本加载器。 - - 加载优先级:`Saved/HotUpdate/Script/`(热更新下载目录) → `Content/Script/`(包内默认脚本目录)。 +2. **开发期直读 + 发布期二进制 UE 资源打包** + - `ULuaHotUpdateSubsystem` 通过 `FUnLuaDelegates::CustomLoadLuaFile` 接管脚本加载: + - 优先级 1:`Saved/HotUpdate/Script/`(热更新覆盖目录,后续可扩展独立热更归档文件) + - 优先级 2(开发期 `WITH_EDITOR`,未传 `-UseLuaBundle`):直接读取外部 `/Script/lua/` + - 优先级 2(发布期 `!WITH_EDITOR`,或编辑器加 `-UseLuaBundle` 启动参数自测):从 UE 资产 `/Game/Generated/DA_LuaBundle`(`ULuaBundleAsset`)内存索引 O(1) 读取并解密 + - 打包/Cook 时通过 `FGameDelegates::GetModifyCookDelegate` 自动将 `Script/lua` 与 `Plugins/UnLua/Content/Script` 归档(支持可选轻量 XOR 加密 + CRC32 校验)生成 `/Game/Generated/DA_LuaBundle.uasset` 并加入 Cook 队列;也可通过编辑器菜单 `Tools -> Pack Lua Script Bundle`、控制台命令 `Lua.PackBundle` 或命令行 `PackLuaBundle` Commandlet 手动触发。 - 支持运行时通过 `ULuaHotUpdateSubsystem::ReloadAllLuaModules()`、`ReloadLuaModule(ModuleName)` 或控制台命令 `Lua.HotReload` / `Lua.ReloadModule ` 实时热重载 Lua 代码。 ## 开发与编译(macOS / UE 5.8) diff --git a/Content/Script/Framework/Bootstrap.lua b/Script/lua/Framework/Bootstrap.lua similarity index 100% rename from Content/Script/Framework/Bootstrap.lua rename to Script/lua/Framework/Bootstrap.lua diff --git a/Content/Script/Framework/EventBus.lua b/Script/lua/Framework/EventBus.lua similarity index 100% rename from Content/Script/Framework/EventBus.lua rename to Script/lua/Framework/EventBus.lua diff --git a/Content/Script/Framework/HotReload.lua b/Script/lua/Framework/HotReload.lua similarity index 100% rename from Content/Script/Framework/HotReload.lua rename to Script/lua/Framework/HotReload.lua diff --git a/Content/Script/Framework/Log.lua b/Script/lua/Framework/Log.lua similarity index 100% rename from Content/Script/Framework/Log.lua rename to Script/lua/Framework/Log.lua diff --git a/Content/Script/Game/LuaCharacter.lua b/Script/lua/Game/LuaCharacter.lua similarity index 100% rename from Content/Script/Game/LuaCharacter.lua rename to Script/lua/Game/LuaCharacter.lua diff --git a/Content/Script/Game/LuaDemoActor.lua b/Script/lua/Game/LuaDemoActor.lua similarity index 100% rename from Content/Script/Game/LuaDemoActor.lua rename to Script/lua/Game/LuaDemoActor.lua diff --git a/Content/Script/Game/LuaGameInstance.lua b/Script/lua/Game/LuaGameInstance.lua similarity index 100% rename from Content/Script/Game/LuaGameInstance.lua rename to Script/lua/Game/LuaGameInstance.lua diff --git a/Content/Script/Game/LuaGameMode.lua b/Script/lua/Game/LuaGameMode.lua similarity index 100% rename from Content/Script/Game/LuaGameMode.lua rename to Script/lua/Game/LuaGameMode.lua diff --git a/Content/Script/Game/LuaPlayerController.lua b/Script/lua/Game/LuaPlayerController.lua similarity index 100% rename from Content/Script/Game/LuaPlayerController.lua rename to Script/lua/Game/LuaPlayerController.lua diff --git a/Script/ts/README.md b/Script/ts/README.md new file mode 100644 index 0000000..e7a439c --- /dev/null +++ b/Script/ts/README.md @@ -0,0 +1,8 @@ +# TypeScript Scripts (`Script/ts`) + +此目录用于存放 `ts2lua`(如 TypeScriptToLua / TSTL)的 TypeScript 源代码、类型声明(`.d.ts`)与构建配置(`tsconfig.json` / `package.json`)。 + +建议配置: +- `tsconfig.json` 中的 `outDir` 指向 `../lua`(或 `../lua/Game` 等子目录,与手写 Lua 框架目录 `../lua/Framework` 隔离)。 +- 开发期在 PIE 中直接读取 `Script/lua/` 下的实时输出文件。 +- 打包发布时,先执行 `ts2lua` 编译,再由 UE Cook 流程自动将 `Script/lua/` 打包为二进制 UE 资源 `/Game/Generated/DA_LuaBundle`。 diff --git a/Source/UnrealLuaDemo/Core/LuaCharacter.h b/Source/UnrealLuaDemo/Core/LuaCharacter.h index 5a6739f..b4b456c 100644 --- a/Source/UnrealLuaDemo/Core/LuaCharacter.h +++ b/Source/UnrealLuaDemo/Core/LuaCharacter.h @@ -8,7 +8,7 @@ #include "LuaCharacter.generated.h" /** - * Base Character bound to Lua (Content/Script/Game/LuaCharacter.lua). + * Base Character bound to Lua (Script/lua/Game/LuaCharacter.lua). */ UCLASS() class UNREALLUADEMO_API ALuaCharacter : public ACharacter, public IUnLuaInterface diff --git a/Source/UnrealLuaDemo/Core/LuaGameInstance.h b/Source/UnrealLuaDemo/Core/LuaGameInstance.h index 0f64b48..06e3cad 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameInstance.h +++ b/Source/UnrealLuaDemo/Core/LuaGameInstance.h @@ -8,7 +8,7 @@ #include "LuaGameInstance.generated.h" /** - * Base GameInstance bound to Lua (Content/Script/Game/LuaGameInstance.lua). + * Base GameInstance bound to Lua (Script/lua/Game/LuaGameInstance.lua). */ UCLASS() class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance, public IUnLuaInterface @@ -22,7 +22,7 @@ public: virtual FString GetModuleName_Implementation() const override; protected: - /** Lua module name bound to this GameInstance (relative to Content/Script). */ + /** Lua module name bound to this GameInstance (relative to Script/lua). */ UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") FString LuaModuleName = TEXT("Game.LuaGameInstance"); }; diff --git a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h index bdfd97f..3e337ca 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h +++ b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h @@ -8,7 +8,7 @@ #include "LuaGameModeBase.generated.h" /** - * Base GameMode bound to Lua (Content/Script/Game/LuaGameMode.lua). + * Base GameMode bound to Lua (Script/lua/Game/LuaGameMode.lua). */ UCLASS() class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase, public IUnLuaInterface diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.h b/Source/UnrealLuaDemo/Core/LuaPlayerController.h index c559f9d..9f64c59 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.h +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.h @@ -8,7 +8,7 @@ #include "LuaPlayerController.generated.h" /** - * Base PlayerController bound to Lua (Content/Script/Game/LuaPlayerController.lua). + * Base PlayerController bound to Lua (Script/lua/Game/LuaPlayerController.lua). * Binds demo hotkeys ([Space] Ping Lua, [R] HotReload Lua) and forwards them to Lua via BlueprintImplementableEvent. */ UCLASS() diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h index 792404b..c0287d6 100644 --- a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h +++ b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h @@ -12,7 +12,7 @@ class UTextRenderComponent; class UMaterialInstanceDynamic; /** - * Interactive demo actor driven by Lua (Content/Script/Game/LuaDemoActor.lua) + * Interactive demo actor driven by Lua (Script/lua/Game/LuaDemoActor.lua) * to visually and programmatically verify UnLua binding, Tick, EventBus, and HotReload. */ UCLASS(Blueprintable) diff --git a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp index 1329f1c..724c792 100644 --- a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp +++ b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp @@ -1,11 +1,23 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "HotUpdate/LuaHotUpdateSubsystem.h" +#include "LuaBundle/LuaBundleAsset.h" +#include "LuaBundle/LuaScriptSettings.h" #include "UnrealLuaDemo.h" #include "UnLuaDelegates.h" #include "HAL/FileManager.h" +#include "Misc/CommandLine.h" #include "Misc/FileHelper.h" +#include "Misc/Parse.h" #include "Misc/Paths.h" +#include "UObject/StrongObjectPtr.h" + +namespace +{ + FCriticalSection GLuaBundleAccessMutex; + TStrongObjectPtr GCachedLuaBundleAsset; + bool GBundleLoadAttempted = false; +} void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection) { @@ -18,8 +30,22 @@ void ULuaHotUpdateSubsystem::Initialize(FSubsystemCollectionBase& Collection) IFileManager::Get().MakeDirectory(*HotUpdateDir, true); } - UE_LOG(LogUnrealLuaDemo, Log, TEXT("LuaHotUpdateSubsystem initialized. OverrideDir=%s DefaultDir=%s"), - *HotUpdateDir, *GetDefaultScriptDir()); + const bool bUseBundle = ShouldUseLuaBundle(); + if (bUseBundle) + { + ULuaBundleAsset* Bundle = GetOrLoadLuaBundleAsset(); + UE_LOG(LogUnrealLuaDemo, Log, + TEXT("LuaHotUpdateSubsystem initialized [BundleMode]. OverrideDir=%s BundleAsset=%s Loaded=%s"), + *HotUpdateDir, + *GetDefault()->LuaBundleAssetPath.ToString(), + Bundle ? TEXT("true") : TEXT("false")); + } + else + { + UE_LOG(LogUnrealLuaDemo, Log, + TEXT("LuaHotUpdateSubsystem initialized [ExternalSourceMode]. OverrideDir=%s ExternalDir=%s"), + *HotUpdateDir, *GetDefaultScriptDir()); + } } void ULuaHotUpdateSubsystem::Deinitialize() @@ -36,6 +62,25 @@ void ULuaHotUpdateSubsystem::RegisterHotUpdateLoader() void ULuaHotUpdateSubsystem::UnregisterHotUpdateLoader() { FUnLuaDelegates::CustomLoadLuaFile.Unbind(); + + FScopeLock Lock(&GLuaBundleAccessMutex); + if (UObjectInitialized() && !GExitPurge) + { + GCachedLuaBundleAsset.Reset(); + } + GBundleLoadAttempted = false; +} + +bool ULuaHotUpdateSubsystem::ShouldUseLuaBundle() +{ +#if WITH_EDITOR + // Editor / PIE / Editor-Standalone read directly from external /Script/lua by default. + // Pass -UseLuaBundle on the command line to test the packaged binary bundle inside Editor. + return FParse::Param(FCommandLine::Get(), TEXT("UseLuaBundle")); +#else + // Packaged / Release builds always read Lua scripts from the cooked ULuaBundleAsset. + return true; +#endif } FString ULuaHotUpdateSubsystem::GetHotUpdateScriptDir() @@ -49,7 +94,54 @@ FString ULuaHotUpdateSubsystem::GetHotUpdateScriptDir() FString ULuaHotUpdateSubsystem::GetDefaultScriptDir() { - return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectContentDir(), TEXT("Script"))); + if (const ULuaScriptSettings* Settings = GetDefault()) + { + return Settings->GetExternalScriptRootFullPath(); + } + return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectDir(), TEXT("Script/lua"))); +} + +void ULuaHotUpdateSubsystem::ReloadLuaBundleAsset() +{ + FScopeLock Lock(&GLuaBundleAccessMutex); + GCachedLuaBundleAsset.Reset(); + GBundleLoadAttempted = false; + GetOrLoadLuaBundleAsset(); +} + +ULuaBundleAsset* ULuaHotUpdateSubsystem::GetOrLoadLuaBundleAsset() +{ + FScopeLock Lock(&GLuaBundleAccessMutex); + + if (GCachedLuaBundleAsset.IsValid()) + { + return GCachedLuaBundleAsset.Get(); + } + + if (GBundleLoadAttempted || !UObjectInitialized()) + { + return nullptr; + } + + GBundleLoadAttempted = true; + + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings || !Settings->LuaBundleAssetPath.IsValid()) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] LuaBundleAssetPath is not configured in ULuaScriptSettings.")); + return nullptr; + } + + ULuaBundleAsset* Loaded = Cast(Settings->LuaBundleAssetPath.TryLoad()); + if (!Loaded) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Failed to load ULuaBundleAsset at '%s'. Run Lua.PackBundle or Cook first."), + *Settings->LuaBundleAssetPath.ToString()); + return nullptr; + } + + GCachedLuaBundleAsset.Reset(Loaded); + return Loaded; } void ULuaHotUpdateSubsystem::ReloadAllLuaModules() @@ -167,20 +259,38 @@ bool ULuaHotUpdateSubsystem::HandleCustomLoadLuaFile( } Normalized.ReplaceInline(TEXT("."), TEXT("/")); Normalized.ReplaceInline(TEXT("\\"), TEXT("/")); + while (Normalized.StartsWith(TEXT("/"))) + { + Normalized.RightChopInline(1); + } - // 1. Prioritize hot-update override directory + // 1. Prioritize hot-update override directory (future standalone hot-update bundle hook also plugs in here) if (TryLoadLuaFromRoot(GetHotUpdateScriptDir(), Normalized, Data, FullFilePath)) { UE_LOG(LogUnrealLuaDemo, Verbose, TEXT("[HotUpdate] Loaded Lua module '%s' from override: %s"), *RelativeFilePath, *FullFilePath); return true; } - // 2. Fallback to project Content/Script directory - if (TryLoadLuaFromRoot(GetDefaultScriptDir(), Normalized, Data, FullFilePath)) + // 2. Load from either packaged binary UE asset (Release / -UseLuaBundle) or external Script/lua directory (Editor / PIE) + if (ShouldUseLuaBundle()) { - return true; + if (ULuaBundleAsset* BundleAsset = GetOrLoadLuaBundleAsset()) + { + if (BundleAsset->FindScript(Normalized, Data, FullFilePath)) + { + UE_LOG(LogUnrealLuaDemo, Verbose, TEXT("[LuaBundle] Loaded Lua module '%s' from ULuaBundleAsset (%s)"), *RelativeFilePath, *FullFilePath); + return true; + } + } + } + else + { + if (TryLoadLuaFromRoot(GetDefaultScriptDir(), Normalized, Data, FullFilePath)) + { + return true; + } } - // 3. Return false to fall through to UnLua's default loaders (e.g. Plugins/UnLua/Content/Script) + // 3. Return false to fall through to UnLua's default loaders (e.g. Plugins/UnLua/Content/Script in PIE) return false; } diff --git a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h index 058ecdd..bd934b2 100644 --- a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h +++ b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.h @@ -7,12 +7,16 @@ #include "LuaEnv.h" #include "LuaHotUpdateSubsystem.generated.h" +class ULuaBundleAsset; + /** - * Manages Lua script hot-update resolution and runtime hot-reloading. + * Manages Lua script loading across development (external Script/lua) and release + * (packaged binary ULuaBundleAsset UE resource), as well as runtime hot-reloading. * * Script search priority: * 1. Hot-update override directory: /HotUpdate/Script/ (or PersistentDownloadDir on mobile) - * 2. Default project script directory: /Script/ + * 2. Development (WITH_EDITOR, unless -UseLuaBundle is passed): external /Script/lua/ + * Release (!WITH_EDITOR, or -UseLuaBundle): packaged UE asset ULuaBundleAsset (/Game/Generated/DA_LuaBundle) * 3. Falls through to UnLua's default filesystem/plugin loaders (e.g. Plugins/UnLua/Content/Script/) */ UCLASS() @@ -27,17 +31,25 @@ public: /** Registers the global custom Lua loader with UnLua. */ static void RegisterHotUpdateLoader(); - /** Unregisters the global custom Lua loader from UnLua. */ + /** Unregisters the global custom Lua loader from UnLua and releases cached bundle asset. */ static void UnregisterHotUpdateLoader(); + /** Returns true when Lua scripts should be loaded from the packaged binary ULuaBundleAsset instead of external Script/lua. */ + UFUNCTION(BlueprintPure, Category = "Lua|HotUpdate") + static bool ShouldUseLuaBundle(); + /** Returns the writable directory where hot-updated Lua scripts are placed. */ UFUNCTION(BlueprintPure, Category = "Lua|HotUpdate") static FString GetHotUpdateScriptDir(); - /** Returns the default packaged/project Lua script directory (Content/Script). */ + /** Returns the external project Lua script directory (/Script/lua). */ UFUNCTION(BlueprintPure, Category = "Lua|HotUpdate") static FString GetDefaultScriptDir(); + /** Clears and reloads the cached ULuaBundleAsset (useful in Editor after re-packing). */ + UFUNCTION(BlueprintCallable, Category = "Lua|HotUpdate") + static void ReloadLuaBundleAsset(); + /** Triggers UnLua hot-reload across all active Lua environments. */ UFUNCTION(BlueprintCallable, Category = "Lua|HotUpdate") static void ReloadAllLuaModules(); @@ -51,6 +63,7 @@ public: static bool ExecuteLuaString(const FString& LuaCode); private: + static ULuaBundleAsset* GetOrLoadLuaBundleAsset(); static bool HandleCustomLoadLuaFile(UnLua::FLuaEnv& Env, const FString& RelativeFilePath, TArray& Data, FString& FullFilePath); static bool TryLoadLuaFromRoot(const FString& RootDir, const FString& NormalizedModulePath, TArray& OutData, FString& OutFullPath); }; diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.cpp b/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.cpp new file mode 100644 index 0000000..aa2e643 --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.cpp @@ -0,0 +1,336 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "LuaBundle/LuaBundleArchive.h" +#include "UnrealLuaDemo.h" +#include "Misc/Crc.h" +#include "Serialization/MemoryReader.h" +#include "Serialization/MemoryWriter.h" + +namespace +{ + FORCEINLINE uint32 MixHash32(uint32 X) + { + X ^= X >> 16; + X *= 0x7feb352du; + X ^= X >> 15; + X *= 0x846ca68bu; + X ^= X >> 16; + return X; + } +} + +FString FLuaBundleArchive::NormalizeRelativePath(const FString& InPath) +{ + FString Result = InPath; + Result.ReplaceInline(TEXT("\\"), TEXT("/")); + while (Result.StartsWith(TEXT("/"))) + { + Result.RightChopInline(1); + } + return Result; +} + +void FLuaBundleArchive::ApplyCipherInPlace( + uint8* Data, + int32 Size, + const FString& EncryptionKey, + uint32 Salt, + uint32 EntryIndex) +{ + if (!Data || Size <= 0) + { + return; + } + + const FTCHARToUTF8 KeyUtf8(*EncryptionKey); + const uint8* KeyBytes = reinterpret_cast(KeyUtf8.Get()); + const int32 KeyLen = KeyUtf8.Length(); + + uint32 KeyHash = KeyLen > 0 ? FCrc::MemCrc32(KeyBytes, KeyLen) : 0xA5A55A5Au; + uint32 State = MixHash32(KeyHash ^ Salt ^ (EntryIndex * 0x9E3779B9u)); + + for (int32 i = 0; i < Size; ++i) + { + State = MixHash32(State + 0x9E3779B9u + static_cast(i)); + uint8 Mask = static_cast((State ^ (State >> 8) ^ (State >> 16) ^ (State >> 24)) & 0xFFu); + if (KeyLen > 0) + { + Mask ^= KeyBytes[(i + EntryIndex) % KeyLen]; + } + Data[i] ^= Mask; + } +} + +bool FLuaBundleArchive::Build( + const TArray& SourceItems, + TArray& OutArchiveBytes, + bool bEncrypt, + const FString& EncryptionKey, + uint32 EncryptionSalt) +{ + OutArchiveBytes.Reset(); + + // Sort deterministically by normalized lowercase path so builds are reproducible + TArray SortedItems = SourceItems; + for (FLuaBundleSourceItem& Item : SortedItems) + { + Item.RelativePath = NormalizeRelativePath(Item.RelativePath); + } + SortedItems.Sort([](const FLuaBundleSourceItem& A, const FLuaBundleSourceItem& B) + { + return A.RelativePath.Compare(B.RelativePath, ESearchCase::IgnoreCase) < 0; + }); + + // Derive a deterministic non-zero salt from content if caller passed 0 + if (bEncrypt && EncryptionSalt == 0) + { + uint32 ContentHash = 0x517CC1B7u; + for (const FLuaBundleSourceItem& Item : SortedItems) + { + ContentHash = FCrc::StrCrc32(*Item.RelativePath, ContentHash); + if (Item.PlaintextBytes.Num() > 0) + { + ContentHash = FCrc::MemCrc32(Item.PlaintextBytes.GetData(), Item.PlaintextBytes.Num(), ContentHash); + } + } + EncryptionSalt = ContentHash != 0 ? ContentHash : 0x13579BDFu; + } + + // Build payload and index entries + TArray Entries; + Entries.Reserve(SortedItems.Num()); + + TArray PayloadBytes; + int64 TotalPayloadSize = 0; + for (const FLuaBundleSourceItem& Item : SortedItems) + { + TotalPayloadSize += Item.PlaintextBytes.Num(); + } + PayloadBytes.Reserve(static_cast(TotalPayloadSize)); + + for (int32 Index = 0; Index < SortedItems.Num(); ++Index) + { + const FLuaBundleSourceItem& Item = SortedItems[Index]; + + FLuaBundleEntry Entry; + Entry.CanonicalPath = Item.RelativePath; + Entry.EntryIndex = static_cast(Index); + Entry.DataOffset = static_cast(PayloadBytes.Num()); + Entry.DataSize = static_cast(Item.PlaintextBytes.Num()); + Entry.PlaintextCrc32 = Item.PlaintextBytes.Num() > 0 + ? FCrc::MemCrc32(Item.PlaintextBytes.GetData(), Item.PlaintextBytes.Num()) + : 0u; + + if (Item.PlaintextBytes.Num() > 0) + { + const int32 WriteOffset = PayloadBytes.AddUninitialized(Item.PlaintextBytes.Num()); + FMemory::Memcpy(PayloadBytes.GetData() + WriteOffset, Item.PlaintextBytes.GetData(), Item.PlaintextBytes.Num()); + + if (bEncrypt) + { + ApplyCipherInPlace( + PayloadBytes.GetData() + WriteOffset, + Item.PlaintextBytes.Num(), + EncryptionKey, + EncryptionSalt, + Entry.EntryIndex); + } + } + + Entries.Add(MoveTemp(Entry)); + } + + // Serialize header + index + payload + FMemoryWriter Writer(OutArchiveBytes, /*bIsPersistent=*/true); + + uint32 HeaderMagic = Magic; + uint32 HeaderVersion = CurrentVersion; + uint32 HeaderFlags = static_cast(bEncrypt ? ELuaBundleFlags::Encrypted : ELuaBundleFlags::None); + uint32 HeaderSalt = EncryptionSalt; + uint32 EntryCount = static_cast(Entries.Num()); + + Writer << HeaderMagic; + Writer << HeaderVersion; + Writer << HeaderFlags; + Writer << HeaderSalt; + Writer << EntryCount; + + for (FLuaBundleEntry& Entry : Entries) + { + Writer << Entry.CanonicalPath; + Writer << Entry.DataOffset; + Writer << Entry.DataSize; + Writer << Entry.PlaintextCrc32; + } + + if (PayloadBytes.Num() > 0) + { + Writer.Serialize(PayloadBytes.GetData(), PayloadBytes.Num()); + } + + return !Writer.IsError(); +} + +void FLuaBundleArchive::Reset() +{ + bParsed = false; + FormatVersion = 0; + Flags = ELuaBundleFlags::None; + EncryptionSalt = 0; + PayloadBaseOffset = 0; + CachedEncryptionKey.Reset(); + EntriesByLowerPath.Reset(); +} + +bool FLuaBundleArchive::Parse(TArrayView ArchiveBytes, const FString& EncryptionKey) +{ + Reset(); + + if (ArchiveBytes.Num() < static_cast(sizeof(uint32) * 5)) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Archive buffer too small (%d bytes)."), ArchiveBytes.Num()); + return false; + } + + FMemoryReaderView Reader(ArchiveBytes, /*bIsPersistent=*/true); + + uint32 HeaderMagic = 0; + uint32 HeaderVersion = 0; + uint32 HeaderFlags = 0; + uint32 HeaderSalt = 0; + uint32 EntryCount = 0; + + Reader << HeaderMagic; + Reader << HeaderVersion; + Reader << HeaderFlags; + Reader << HeaderSalt; + Reader << EntryCount; + + if (Reader.IsError() || HeaderMagic != Magic) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Invalid archive magic: 0x%08X"), HeaderMagic); + return false; + } + + if (HeaderVersion != CurrentVersion) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Unsupported archive version: %u (expected %u)"), HeaderVersion, CurrentVersion); + return false; + } + + EntriesByLowerPath.Reserve(static_cast(EntryCount)); + + for (uint32 i = 0; i < EntryCount; ++i) + { + FLuaBundleEntry Entry; + Entry.EntryIndex = i; + + Reader << Entry.CanonicalPath; + Reader << Entry.DataOffset; + Reader << Entry.DataSize; + Reader << Entry.PlaintextCrc32; + + if (Reader.IsError()) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Corrupted index entry at #%u."), i); + Reset(); + return false; + } + + const FString LowerKey = NormalizeRelativePath(Entry.CanonicalPath).ToLower(); + EntriesByLowerPath.Add(LowerKey, MoveTemp(Entry)); + } + + PayloadBaseOffset = Reader.Tell(); + + // Validate all payload bounds up front + for (const TPair& Pair : EntriesByLowerPath) + { + const FLuaBundleEntry& Entry = Pair.Value; + const int64 EndOffset = PayloadBaseOffset + static_cast(Entry.DataOffset) + static_cast(Entry.DataSize); + if (EndOffset > ArchiveBytes.Num()) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] Entry '%s' exceeds archive size (%lld > %d)."), + *Entry.CanonicalPath, EndOffset, ArchiveBytes.Num()); + Reset(); + return false; + } + } + + FormatVersion = HeaderVersion; + Flags = static_cast(HeaderFlags); + EncryptionSalt = HeaderSalt; + CachedEncryptionKey = EncryptionKey; + bParsed = true; + return true; +} + +bool FLuaBundleArchive::ExtractEntry( + const FLuaBundleEntry& Entry, + TArrayView ArchiveBytes, + TArray& OutPlaintextData, + FString& OutChunkName) const +{ + const int64 StartOffset = PayloadBaseOffset + static_cast(Entry.DataOffset); + const int64 EndOffset = StartOffset + static_cast(Entry.DataSize); + if (StartOffset < 0 || EndOffset > ArchiveBytes.Num()) + { + return false; + } + + OutPlaintextData.SetNumUninitialized(static_cast(Entry.DataSize)); + if (Entry.DataSize > 0) + { + FMemory::Memcpy(OutPlaintextData.GetData(), ArchiveBytes.GetData() + StartOffset, Entry.DataSize); + + if (IsEncrypted()) + { + ApplyCipherInPlace( + OutPlaintextData.GetData(), + static_cast(Entry.DataSize), + CachedEncryptionKey, + EncryptionSalt, + Entry.EntryIndex); + } + + const uint32 ActualCrc = FCrc::MemCrc32(OutPlaintextData.GetData(), OutPlaintextData.Num()); + if (ActualCrc != Entry.PlaintextCrc32) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] CRC mismatch for '%s' (expected 0x%08X, got 0x%08X). Check encryption key."), + *Entry.CanonicalPath, Entry.PlaintextCrc32, ActualCrc); + OutPlaintextData.Reset(); + return false; + } + } + + OutChunkName = Entry.CanonicalPath; + return true; +} + +bool FLuaBundleArchive::ReadScript( + const FString& NormalizedModulePath, + TArrayView ArchiveBytes, + TArray& OutPlaintextData, + FString& OutChunkName) const +{ + if (!bParsed) + { + return false; + } + + const FString CleanModule = NormalizeRelativePath(NormalizedModulePath).ToLower(); + + const FString DirectKey = CleanModule + TEXT(".lua"); + if (const FLuaBundleEntry* Entry = EntriesByLowerPath.Find(DirectKey)) + { + return ExtractEntry(*Entry, ArchiveBytes, OutPlaintextData, OutChunkName); + } + + const FString InitKey = CleanModule + TEXT("/init.lua"); + if (const FLuaBundleEntry* Entry = EntriesByLowerPath.Find(InitKey)) + { + return ExtractEntry(*Entry, ArchiveBytes, OutPlaintextData, OutChunkName); + } + + return false; +} diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.h b/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.h new file mode 100644 index 0000000..1f0ef74 --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaBundleArchive.h @@ -0,0 +1,114 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" + +/** + * Flags stored in the binary Lua bundle header. + */ +enum class ELuaBundleFlags : uint32 +{ + None = 0, + Encrypted = 1 << 0, +}; +ENUM_CLASS_FLAGS(ELuaBundleFlags) + +/** + * Plaintext input entry used when constructing a binary Lua archive. + */ +struct UNREALLUADEMO_API FLuaBundleSourceItem +{ + /** Canonical forward-slash relative path, e.g. "Game/LuaDemoActor.lua". */ + FString RelativePath; + + /** Raw UTF-8 Lua source bytes. */ + TArray PlaintextBytes; +}; + +/** + * Parsed index record referencing a single script slice inside the archive payload. + */ +struct UNREALLUADEMO_API FLuaBundleEntry +{ + FString CanonicalPath; + uint32 EntryIndex = 0; + uint32 DataOffset = 0; + uint32 DataSize = 0; + uint32 PlaintextCrc32 = 0; +}; + +/** + * Self-contained binary Lua source archive serializer & reader. + * + * Binary layout (little-endian): + * Header: Magic ('BLUA'), Version (1), Flags, EncryptionSalt, EntryCount + * Index: EntryCount x { CanonicalPath (FString), DataOffset (uint32), DataSize (uint32), PlaintextCrc32 (uint32) } + * Payload: Concatenated script bytes (each entry independently XOR-obfuscated if Encrypted flag is set) + * + * Designed to be stored directly inside ULuaBundleAsset (cooked UE resource) and also + * reusable as a standalone file format for future hot-update downloads. + */ +class UNREALLUADEMO_API FLuaBundleArchive +{ +public: + static constexpr uint32 Magic = 0x41554C42; // 'BLUA' + static constexpr uint32 CurrentVersion = 1; + + /** Serializes sorted Lua source items into a single binary archive buffer. */ + static bool Build( + const TArray& SourceItems, + TArray& OutArchiveBytes, + bool bEncrypt, + const FString& EncryptionKey, + uint32 EncryptionSalt = 0); + + /** Parses header and index table from an existing binary archive buffer. */ + bool Parse(TArrayView ArchiveBytes, const FString& EncryptionKey); + + /** Resets parsed index state. */ + void Reset(); + + /** Returns true if an archive index is currently parsed and ready. */ + bool IsValid() const { return bParsed; } + + uint32 GetFormatVersion() const { return FormatVersion; } + bool IsEncrypted() const { return EnumHasAnyFlags(Flags, ELuaBundleFlags::Encrypted); } + int32 GetEntryCount() const { return EntriesByLowerPath.Num(); } + + /** + * Looks up a Lua module by normalized slash-separated path (without ".lua", e.g. "Game/LuaDemoActor"). + * Tries ".lua" first, then "/init.lua". + */ + bool ReadScript( + const FString& NormalizedModulePath, + TArrayView ArchiveBytes, + TArray& OutPlaintextData, + FString& OutChunkName) const; + + /** Applies symmetric lightweight XOR stream obfuscation in-place for a single entry. */ + static void ApplyCipherInPlace( + uint8* Data, + int32 Size, + const FString& EncryptionKey, + uint32 Salt, + uint32 EntryIndex); + + /** Normalizes a relative Lua path to forward slashes without leading slashes. */ + static FString NormalizeRelativePath(const FString& InPath); + +private: + bool ExtractEntry( + const FLuaBundleEntry& Entry, + TArrayView ArchiveBytes, + TArray& OutPlaintextData, + FString& OutChunkName) const; + + bool bParsed = false; + uint32 FormatVersion = 0; + ELuaBundleFlags Flags = ELuaBundleFlags::None; + uint32 EncryptionSalt = 0; + int64 PayloadBaseOffset = 0; + FString CachedEncryptionKey; + TMap EntriesByLowerPath; +}; diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.cpp b/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.cpp new file mode 100644 index 0000000..a2fccf3 --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.cpp @@ -0,0 +1,68 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "LuaBundle/LuaBundleAsset.h" +#include "LuaBundle/LuaScriptSettings.h" +#include "UnrealLuaDemo.h" + +void ULuaBundleAsset::PostLoad() +{ + Super::PostLoad(); + InvalidateCache(); +} + +void ULuaBundleAsset::InvalidateCache() +{ + FScopeLock Lock(&IndexMutex); + ParsedArchive.Reset(); + bParseAttempted = false; +} + +bool ULuaBundleAsset::EnsureIndexParsed() const +{ + if (ParsedArchive.IsValid()) + { + return true; + } + + if (bParseAttempted) + { + return false; + } + + bParseAttempted = true; + + if (ArchiveBytes.Num() == 0) + { + UE_LOG(LogUnrealLuaDemo, Warning, TEXT("[LuaBundleAsset] '%s' contains empty ArchiveBytes."), *GetPathName()); + return false; + } + + const ULuaScriptSettings* Settings = GetDefault(); + const FString Key = Settings ? Settings->BundleEncryptionKey : FString(); + + if (!ParsedArchive.Parse(ArchiveBytes, Key)) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundleAsset] Failed to parse binary archive in '%s'."), *GetPathName()); + return false; + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaBundleAsset] Parsed '%s': %d scripts, %d bytes, encrypted=%s, built=%s"), + *GetPathName(), + ParsedArchive.GetEntryCount(), + ArchiveBytes.Num(), + ParsedArchive.IsEncrypted() ? TEXT("true") : TEXT("false"), + *BuildTimestamp); + + return true; +} + +bool ULuaBundleAsset::FindScript(const FString& NormalizedModulePath, TArray& OutData, FString& OutChunkName) const +{ + FScopeLock Lock(&IndexMutex); + if (!EnsureIndexParsed()) + { + return false; + } + + return ParsedArchive.ReadScript(NormalizedModulePath, ArchiveBytes, OutData, OutChunkName); +} diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.h b/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.h new file mode 100644 index 0000000..313426e --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaBundleAsset.h @@ -0,0 +1,56 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Engine/DataAsset.h" +#include "LuaBundle/LuaBundleArchive.h" +#include "LuaBundleAsset.generated.h" + +/** + * UE DataAsset containing a single binary Lua source archive (FLuaBundleArchive). + * + * Generated automatically from /Script/lua at Cook/Package time (or via + * Lua.PackBundle / PackLuaBundleCommandlet), cooked into IoStore/Pak as a standard UE asset. + */ +UCLASS(BlueprintType) +class UNREALLUADEMO_API ULuaBundleAsset : public UDataAsset +{ + GENERATED_BODY() + +public: + /** Binary archive format version stored in ArchiveBytes. */ + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaBundle") + int32 FormatVersion = 0; + + /** Number of Lua script entries packed inside ArchiveBytes. */ + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaBundle") + int32 ScriptCount = 0; + + /** Whether script payloads inside ArchiveBytes are encrypted. */ + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaBundle") + bool bEncrypted = false; + + /** UTC timestamp recorded when this bundle was generated. */ + UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaBundle") + FString BuildTimestamp; + + /** Raw serialized FLuaBundleArchive bytes (compressed by UE IoStore/Oodle during packaging). */ + UPROPERTY() + TArray ArchiveBytes; + + /** Looks up and decrypts a Lua script module from the packaged archive. */ + bool FindScript(const FString& NormalizedModulePath, TArray& OutData, FString& OutChunkName) const; + + /** Clears the runtime parsed index cache (call after updating ArchiveBytes in Editor). */ + void InvalidateCache(); + + virtual void PostLoad() override; + +private: + bool EnsureIndexParsed() const; + + mutable FCriticalSection IndexMutex; + mutable FLuaBundleArchive ParsedArchive; + mutable bool bParseAttempted = false; +}; diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.cpp b/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.cpp new file mode 100644 index 0000000..92a9c8e --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.cpp @@ -0,0 +1,21 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "LuaBundle/LuaScriptSettings.h" +#include "Misc/Paths.h" + +ULuaScriptSettings::ULuaScriptSettings() + : ExternalScriptRelativePath(TEXT("Script/lua")) + , LuaBundleAssetPath(TEXT("/Game/Generated/DA_LuaBundle.DA_LuaBundle")) + , bIncludeUnLuaPluginScriptsInBundle(true) + , bEncryptBundle(true) + , BundleEncryptionKey(TEXT("UnrealLuaDemo_LuaBundle_Key_v1")) + , bAutoPackOnCook(true) +{ +} + +FString ULuaScriptSettings::GetExternalScriptRootFullPath() const +{ + FString FullPath = FPaths::Combine(FPaths::ProjectDir(), ExternalScriptRelativePath); + FPaths::NormalizeDirectoryName(FullPath); + return FPaths::ConvertRelativePathToFull(FullPath); +} diff --git a/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.h b/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.h new file mode 100644 index 0000000..02a5010 --- /dev/null +++ b/Source/UnrealLuaDemo/LuaBundle/LuaScriptSettings.h @@ -0,0 +1,48 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Engine/DeveloperSettings.h" +#include "LuaScriptSettings.generated.h" + +/** + * Project-level settings for external Lua script paths and packaged binary bundle generation. + */ +UCLASS(Config = Game, DefaultConfig, meta = (DisplayName = "Lua Script Settings")) +class UNREALLUADEMO_API ULuaScriptSettings : public UDeveloperSettings +{ + GENERATED_BODY() + +public: + ULuaScriptSettings(); + + /** Relative path (from project root directory) containing external Lua scripts used in Editor/PIE and packed at Cook time. */ + UPROPERTY(Config, EditAnywhere, Category = "Paths") + FString ExternalScriptRelativePath; + + /** UE DataAsset path storing the packaged binary Lua archive for cooked/release builds. */ + UPROPERTY(Config, EditAnywhere, Category = "Bundle", meta = (AllowedClasses = "/Script/UnrealLuaDemo.LuaBundleAsset")) + FSoftObjectPath LuaBundleAssetPath; + + /** Whether to include Plugins/UnLua/Content/Script files inside the packed binary bundle so release builds need zero loose Lua files. */ + UPROPERTY(Config, EditAnywhere, Category = "Bundle") + bool bIncludeUnLuaPluginScriptsInBundle; + + /** Enable lightweight XOR stream obfuscation for Lua source entries inside the binary bundle. */ + UPROPERTY(Config, EditAnywhere, Category = "Bundle") + bool bEncryptBundle; + + /** Key used to derive the lightweight XOR stream cipher when bEncryptBundle is enabled. */ + UPROPERTY(Config, EditAnywhere, Category = "Bundle", meta = (EditCondition = "bEncryptBundle")) + FString BundleEncryptionKey; + + /** Automatically rebuild and include the Lua bundle UAsset when UE starts cooking/packaging. */ + UPROPERTY(Config, EditAnywhere, Category = "Packaging") + bool bAutoPackOnCook; + + /** Resolves the absolute external Lua script root directory (/). */ + FString GetExternalScriptRootFullPath() const; + + virtual FName GetCategoryName() const override { return TEXT("Game"); } +}; diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs b/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs index 977355c..e47ed80 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs @@ -15,6 +15,7 @@ public class UnrealLuaDemo : ModuleRules "Core", "CoreUObject", "Engine", + "DeveloperSettings", "InputCore", "EnhancedInput", "UMG", diff --git a/Source/UnrealLuaDemoEditor.Target.cs b/Source/UnrealLuaDemoEditor.Target.cs index 6d62f8a..11f5917 100644 --- a/Source/UnrealLuaDemoEditor.Target.cs +++ b/Source/UnrealLuaDemoEditor.Target.cs @@ -11,5 +11,6 @@ public class UnrealLuaDemoEditorTarget : TargetRules DefaultBuildSettings = BuildSettingsVersion.V7; IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_8; ExtraModuleNames.Add("UnrealLuaDemo"); + ExtraModuleNames.Add("UnrealLuaDemoEditor"); } } diff --git a/Source/UnrealLuaDemoEditor/LuaBundlePacker.cpp b/Source/UnrealLuaDemoEditor/LuaBundlePacker.cpp new file mode 100644 index 0000000..bcca4bd --- /dev/null +++ b/Source/UnrealLuaDemoEditor/LuaBundlePacker.cpp @@ -0,0 +1,301 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "LuaBundlePacker.h" +#include "UnrealLuaDemoEditor.h" +#include "LuaBundle/LuaBundleAsset.h" +#include "LuaBundle/LuaScriptSettings.h" +#include "AssetRegistry/AssetRegistryModule.h" +#include "HAL/FileManager.h" +#include "Interfaces/IPluginManager.h" +#include "Misc/DateTime.h" +#include "Misc/FileHelper.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "UObject/Package.h" +#include "UObject/SavePackage.h" + +namespace +{ + bool ShouldSkipRelativeLuaPath(const FString& RelativePath) + { + // Skip editor-only IntelliSense stubs and hidden directories (e.g. .git) + if (RelativePath.StartsWith(TEXT("IntelliSense/"), ESearchCase::IgnoreCase) || + RelativePath.Contains(TEXT("/IntelliSense/"), ESearchCase::IgnoreCase)) + { + return true; + } + + TArray Segments; + RelativePath.ParseIntoArray(Segments, TEXT("/"), true); + for (const FString& Segment : Segments) + { + if (Segment.StartsWith(TEXT("."))) + { + return true; + } + } + + return false; + } +} + +void FLuaBundlePacker::CollectDirectoryLuaFiles( + const FString& RootDir, + TMap& InOutItemsByLowerPath, + bool bAllowOverwrite) +{ + if (!FPaths::DirectoryExists(RootDir)) + { + return; + } + + FString NormalizedRoot = FPaths::ConvertRelativePathToFull(RootDir); + FPaths::NormalizeDirectoryName(NormalizedRoot); + if (!NormalizedRoot.EndsWith(TEXT("/"))) + { + NormalizedRoot += TEXT("/"); + } + + TArray FoundFiles; + IFileManager::Get().FindFilesRecursive(FoundFiles, *NormalizedRoot, TEXT("*.lua"), /*Files=*/true, /*Directories=*/false); + FoundFiles.Sort(); + + for (const FString& FilePath : FoundFiles) + { + FString NormalizedFile = FPaths::ConvertRelativePathToFull(FilePath); + FPaths::NormalizeFilename(NormalizedFile); + + FString RelativePath = NormalizedFile; + if (!FPaths::MakePathRelativeTo(RelativePath, *NormalizedRoot)) + { + continue; + } + + RelativePath = FLuaBundleArchive::NormalizeRelativePath(RelativePath); + if (RelativePath.IsEmpty() || ShouldSkipRelativeLuaPath(RelativePath)) + { + continue; + } + + const FString LowerKey = RelativePath.ToLower(); + if (!bAllowOverwrite && InOutItemsByLowerPath.Contains(LowerKey)) + { + continue; + } + + TArray RawBytes; + if (!FFileHelper::LoadFileToArray(RawBytes, *NormalizedFile)) + { + UE_LOG(LogUnrealLuaDemoEditor, Warning, TEXT("[LuaBundlePacker] Failed to read Lua file: %s"), *NormalizedFile); + continue; + } + + // Strip UTF-8 BOM if present so runtime loading is consistent + if (RawBytes.Num() >= 3 && RawBytes[0] == 0xEF && RawBytes[1] == 0xBB && RawBytes[2] == 0xBF) + { + RawBytes.RemoveAt(0, 3); + } + + FLuaBundleSourceItem Item; + Item.RelativePath = RelativePath; + Item.PlaintextBytes = MoveTemp(RawBytes); + InOutItemsByLowerPath.Add(LowerKey, MoveTemp(Item)); + } +} + +bool FLuaBundlePacker::CollectLuaSources(TArray& OutItems, FString& OutError) +{ + OutItems.Reset(); + + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings) + { + OutError = TEXT("ULuaScriptSettings CDO is unavailable."); + return false; + } + + const FString ProjectLuaRoot = Settings->GetExternalScriptRootFullPath(); + if (!FPaths::DirectoryExists(ProjectLuaRoot)) + { + OutError = FString::Printf(TEXT("External Lua script root directory does not exist: %s"), *ProjectLuaRoot); + return false; + } + + TMap ItemsByLowerPath; + + // 1. Collect project scripts from /Script/lua (highest priority) + CollectDirectoryLuaFiles(ProjectLuaRoot, ItemsByLowerPath, /*bAllowOverwrite=*/true); + + // 2. Optionally include UnLua plugin runtime scripts (e.g. UnLua/HotReload.lua, UnLua/EnhancedInput.lua) + // without overwriting any project-provided script of the same path. + if (Settings->bIncludeUnLuaPluginScriptsInBundle) + { + if (TSharedPtr UnLuaPlugin = IPluginManager::Get().FindPlugin(TEXT("UnLua"))) + { + const FString PluginScriptRoot = FPaths::Combine(UnLuaPlugin->GetContentDir(), TEXT("Script")); + CollectDirectoryLuaFiles(PluginScriptRoot, ItemsByLowerPath, /*bAllowOverwrite=*/false); + } + } + + if (ItemsByLowerPath.Num() == 0) + { + OutError = FString::Printf(TEXT("No .lua files found under: %s"), *ProjectLuaRoot); + return false; + } + + OutItems.Reserve(ItemsByLowerPath.Num()); + for (TPair& Pair : ItemsByLowerPath) + { + OutItems.Add(MoveTemp(Pair.Value)); + } + + return true; +} + +bool FLuaBundlePacker::PackToDefaultAsset(FLuaBundlePackResult& OutResult, TOptional bEncryptOverride) +{ + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings) + { + OutResult.bSuccess = false; + OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable."); + return false; + } + + return PackToAsset(Settings->LuaBundleAssetPath, OutResult, bEncryptOverride); +} + +bool FLuaBundlePacker::PackToAsset( + const FSoftObjectPath& TargetAssetPath, + FLuaBundlePackResult& OutResult, + TOptional bEncryptOverride) +{ + OutResult = FLuaBundlePackResult{}; + + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings) + { + OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable."); + return false; + } + + const FString PackageName = TargetAssetPath.GetLongPackageName(); + const FString AssetName = TargetAssetPath.GetAssetName(); + if (PackageName.IsEmpty() || AssetName.IsEmpty()) + { + OutResult.ErrorMessage = FString::Printf(TEXT("Invalid LuaBundleAssetPath: '%s'"), *TargetAssetPath.ToString()); + return false; + } + + TArray SourceItems; + if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage)) + { + return false; + } + + const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle); + TArray ArchiveBytes; + if (!FLuaBundleArchive::Build(SourceItems, ArchiveBytes, bEncrypt, Settings->BundleEncryptionKey)) + { + OutResult.ErrorMessage = TEXT("FLuaBundleArchive::Build failed."); + return false; + } + + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + OutResult.ErrorMessage = FString::Printf(TEXT("Failed to create package '%s'."), *PackageName); + return false; + } + Package->FullyLoad(); + + ULuaBundleAsset* BundleAsset = FindObject(Package, *AssetName); + const bool bNewlyCreated = (BundleAsset == nullptr); + if (!BundleAsset) + { + BundleAsset = NewObject(Package, *AssetName, RF_Public | RF_Standalone); + } + + BundleAsset->FormatVersion = static_cast(FLuaBundleArchive::CurrentVersion); + BundleAsset->ScriptCount = SourceItems.Num(); + BundleAsset->bEncrypted = bEncrypt; + BundleAsset->BuildTimestamp = FDateTime::UtcNow().ToIso8601(); + BundleAsset->ArchiveBytes = MoveTemp(ArchiveBytes); + BundleAsset->InvalidateCache(); + BundleAsset->MarkPackageDirty(); + + if (bNewlyCreated) + { + FAssetRegistryModule::AssetCreated(BundleAsset); + } + + const FString PackageFilename = FPackageName::LongPackageNameToFilename( + PackageName, FPackageName::GetAssetPackageExtension()); + + const FString ParentDir = FPaths::GetPath(PackageFilename); + IFileManager::Get().MakeDirectory(*ParentDir, /*Tree=*/true); + + FSavePackageArgs SaveArgs; + SaveArgs.TopLevelFlags = RF_Public | RF_Standalone; + SaveArgs.Error = GError; + SaveArgs.bWarnOfLongFilename = false; + + const bool bSaved = UPackage::SavePackage(Package, BundleAsset, *PackageFilename, SaveArgs); + if (!bSaved) + { + OutResult.ErrorMessage = FString::Printf(TEXT("UPackage::SavePackage failed for '%s'."), *PackageFilename); + return false; + } + + OutResult.bSuccess = true; + OutResult.ScriptCount = BundleAsset->ScriptCount; + OutResult.ArchiveByteSize = BundleAsset->ArchiveBytes.Num(); + OutResult.bEncrypted = BundleAsset->bEncrypted; + OutResult.OutputPath = PackageFilename; + return true; +} + +bool FLuaBundlePacker::PackToStandaloneFile( + const FString& OutputFilePath, + FLuaBundlePackResult& OutResult, + TOptional bEncryptOverride) +{ + OutResult = FLuaBundlePackResult{}; + + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings) + { + OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable."); + return false; + } + + TArray SourceItems; + if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage)) + { + return false; + } + + const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle); + TArray ArchiveBytes; + if (!FLuaBundleArchive::Build(SourceItems, ArchiveBytes, bEncrypt, Settings->BundleEncryptionKey)) + { + OutResult.ErrorMessage = TEXT("FLuaBundleArchive::Build failed."); + return false; + } + + const FString FullOutputPath = FPaths::ConvertRelativePathToFull(OutputFilePath); + IFileManager::Get().MakeDirectory(*FPaths::GetPath(FullOutputPath), /*Tree=*/true); + + if (!FFileHelper::SaveArrayToFile(ArchiveBytes, *FullOutputPath)) + { + OutResult.ErrorMessage = FString::Printf(TEXT("Failed to save standalone Lua bundle to '%s'."), *FullOutputPath); + return false; + } + + OutResult.bSuccess = true; + OutResult.ScriptCount = SourceItems.Num(); + OutResult.ArchiveByteSize = ArchiveBytes.Num(); + OutResult.bEncrypted = bEncrypt; + OutResult.OutputPath = FullOutputPath; + return true; +} diff --git a/Source/UnrealLuaDemoEditor/LuaBundlePacker.h b/Source/UnrealLuaDemoEditor/LuaBundlePacker.h new file mode 100644 index 0000000..a9b7d70 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/LuaBundlePacker.h @@ -0,0 +1,43 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "LuaBundle/LuaBundleArchive.h" + +struct UNREALLUADEMOEDITOR_API FLuaBundlePackResult +{ + bool bSuccess = false; + int32 ScriptCount = 0; + int32 ArchiveByteSize = 0; + bool bEncrypted = false; + FString OutputPath; + FString ErrorMessage; +}; + +/** + * Editor-only packer that collects external Lua scripts (Script/lua and optionally + * Plugins/UnLua/Content/Script) into a single FLuaBundleArchive and writes it to either + * a UE DataAsset (ULuaBundleAsset) for cooked builds or a standalone binary file. + */ +class UNREALLUADEMOEDITOR_API FLuaBundlePacker +{ +public: + /** Collects all .lua source files according to ULuaScriptSettings. */ + static bool CollectLuaSources(TArray& OutItems, FString& OutError); + + /** Packs external Lua scripts into the default ULuaBundleAsset configured in ULuaScriptSettings. */ + static bool PackToDefaultAsset(FLuaBundlePackResult& OutResult, TOptional bEncryptOverride = {}); + + /** Packs external Lua scripts into a specific UE asset soft object path (e.g. /Game/Generated/DA_LuaBundle.DA_LuaBundle). */ + static bool PackToAsset(const FSoftObjectPath& TargetAssetPath, FLuaBundlePackResult& OutResult, TOptional bEncryptOverride = {}); + + /** Packs external Lua scripts into a standalone binary archive file (useful for CI/hot-update pipelines). */ + static bool PackToStandaloneFile(const FString& OutputFilePath, FLuaBundlePackResult& OutResult, TOptional bEncryptOverride = {}); + +private: + static void CollectDirectoryLuaFiles( + const FString& RootDir, + TMap& InOutItemsByLowerPath, + bool bAllowOverwrite); +}; diff --git a/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.cpp b/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.cpp new file mode 100644 index 0000000..1fd3d83 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.cpp @@ -0,0 +1,106 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "PackLuaBundleCommandlet.h" +#include "LuaBundlePacker.h" +#include "UnrealLuaDemoEditor.h" +#include "LuaBundle/LuaBundleAsset.h" +#include "LuaBundle/LuaScriptSettings.h" +#include "Misc/Parse.h" + +UPackLuaBundleCommandlet::UPackLuaBundleCommandlet() +{ + IsClient = false; + IsEditor = true; + IsServer = false; + LogToConsole = true; + ShowErrorCount = true; +} + +int32 UPackLuaBundleCommandlet::Main(const FString& Params) +{ + TOptional bEncryptOverride; + if (FParse::Param(*Params, TEXT("NoEncrypt"))) + { + bEncryptOverride = false; + } + else if (FParse::Param(*Params, TEXT("Encrypt"))) + { + bEncryptOverride = true; + } + + FLuaBundlePackResult AssetResult; + if (!FLuaBundlePacker::PackToDefaultAsset(AssetResult, bEncryptOverride)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] PackToDefaultAsset failed: %s"), *AssetResult.ErrorMessage); + return 1; + } + + UE_LOG(LogUnrealLuaDemoEditor, Display, + TEXT("[PackLuaBundleCommandlet] Packed %d scripts (%d bytes, encrypted=%s) -> %s"), + AssetResult.ScriptCount, + AssetResult.ArchiveByteSize, + AssetResult.bEncrypted ? TEXT("true") : TEXT("false"), + *AssetResult.OutputPath); + + FString StandaloneOutputFile; + if (FParse::Value(*Params, TEXT("OutputFile="), StandaloneOutputFile) && !StandaloneOutputFile.IsEmpty()) + { + FLuaBundlePackResult FileResult; + if (!FLuaBundlePacker::PackToStandaloneFile(StandaloneOutputFile, FileResult, bEncryptOverride)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] PackToStandaloneFile failed: %s"), *FileResult.ErrorMessage); + return 1; + } + UE_LOG(LogUnrealLuaDemoEditor, Display, + TEXT("[PackLuaBundleCommandlet] Exported standalone bundle (%d bytes) -> %s"), + FileResult.ArchiveByteSize, *FileResult.OutputPath); + } + + if (FParse::Param(*Params, TEXT("Verify"))) + { + const ULuaScriptSettings* Settings = GetDefault(); + ULuaBundleAsset* LoadedAsset = Settings ? Cast(Settings->LuaBundleAssetPath.TryLoad()) : nullptr; + if (!LoadedAsset) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] Verify failed: could not load bundle asset.")); + return 1; + } + + TArray Sources; + FString CollectError; + if (!FLuaBundlePacker::CollectLuaSources(Sources, CollectError)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] Verify failed: %s"), *CollectError); + return 1; + } + + for (const FLuaBundleSourceItem& Source : Sources) + { + FString ModulePath = Source.RelativePath; + if (ModulePath.EndsWith(TEXT(".lua"), ESearchCase::IgnoreCase)) + { + ModulePath.LeftChopInline(4); + } + + TArray ReadBackBytes; + FString ChunkName; + if (!LoadedAsset->FindScript(ModulePath, ReadBackBytes, ChunkName)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] Verify failed: missing module '%s'."), *ModulePath); + return 1; + } + + if (ReadBackBytes != Source.PlaintextBytes) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] Verify failed: content mismatch for '%s'."), *ModulePath); + return 1; + } + } + + UE_LOG(LogUnrealLuaDemoEditor, Display, + TEXT("[PackLuaBundleCommandlet] Verified all %d scripts round-trip cleanly from ULuaBundleAsset."), + Sources.Num()); + } + + return 0; +} diff --git a/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.h b/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.h new file mode 100644 index 0000000..f8feaaf --- /dev/null +++ b/Source/UnrealLuaDemoEditor/PackLuaBundleCommandlet.h @@ -0,0 +1,25 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Commandlets/Commandlet.h" +#include "PackLuaBundleCommandlet.generated.h" + +/** + * Commandlet for packing external Script/lua scripts into the binary ULuaBundleAsset UE resource + * (and optionally exporting a standalone binary archive file). + * + * Usage: + * UnrealEditor-Cmd -run=PackLuaBundle [-NoEncrypt] [-OutputFile=] [-Verify] + */ +UCLASS() +class UNREALLUADEMOEDITOR_API UPackLuaBundleCommandlet : public UCommandlet +{ + GENERATED_BODY() + +public: + UPackLuaBundleCommandlet(); + + virtual int32 Main(const FString& Params) override; +}; diff --git a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs new file mode 100644 index 0000000..eb18bb8 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs @@ -0,0 +1,32 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +using UnrealBuildTool; + +public class UnrealLuaDemoEditor : ModuleRules +{ + public UnrealLuaDemoEditor(ReadOnlyTargetRules Target) : base(Target) + { + PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; + + PublicIncludePaths.Add(ModuleDirectory); + + PublicDependencyModuleNames.AddRange(new string[] + { + "Core", + "CoreUObject", + "Engine", + "UnrealLuaDemo" + }); + + PrivateDependencyModuleNames.AddRange(new string[] + { + "UnrealEd", + "AssetRegistry", + "DeveloperSettings", + "Projects", + "Slate", + "SlateCore", + "ToolMenus" + }); + } +} diff --git a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.cpp b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.cpp new file mode 100644 index 0000000..5e1ce2c --- /dev/null +++ b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.cpp @@ -0,0 +1,135 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "UnrealLuaDemoEditor.h" +#include "LuaBundlePacker.h" +#include "LuaBundle/LuaScriptSettings.h" +#include "GameDelegates.h" +#include "HAL/IConsoleManager.h" +#include "ToolMenus.h" + +DEFINE_LOG_CATEGORY(LogUnrealLuaDemoEditor); + +#define LOCTEXT_NAMESPACE "FUnrealLuaDemoEditorModule" + +void FUnrealLuaDemoEditorModule::StartupModule() +{ + ModifyCookHandle = FGameDelegates::Get().GetModifyCookDelegate().AddRaw( + this, &FUnrealLuaDemoEditorModule::OnModifyCook); + + PackBundleCmd = IConsoleManager::Get().RegisterConsoleCommand( + TEXT("Lua.PackBundle"), + TEXT("Pack external Script/lua directory into the configured ULuaBundleAsset UE resource."), + FConsoleCommandDelegate::CreateLambda([]() + { + FLuaBundlePackResult Result; + if (FLuaBundlePacker::PackToDefaultAsset(Result)) + { + UE_LOG(LogUnrealLuaDemoEditor, Log, + TEXT("[Lua.PackBundle] Packed %d scripts (%d bytes, encrypted=%s) -> %s"), + Result.ScriptCount, + Result.ArchiveByteSize, + Result.bEncrypted ? TEXT("true") : TEXT("false"), + *Result.OutputPath); + } + else + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[Lua.PackBundle] Failed: %s"), *Result.ErrorMessage); + } + }), + ECVF_Default); + + if (!IsRunningCommandlet()) + { + UToolMenus::RegisterStartupCallback( + FSimpleMulticastDelegate::FDelegate::CreateRaw(this, &FUnrealLuaDemoEditorModule::RegisterMenus)); + } +} + +void FUnrealLuaDemoEditorModule::ShutdownModule() +{ + if (ModifyCookHandle.IsValid()) + { + FGameDelegates::Get().GetModifyCookDelegate().Remove(ModifyCookHandle); + ModifyCookHandle.Reset(); + } + + if (PackBundleCmd) + { + IConsoleManager::Get().UnregisterConsoleObject(PackBundleCmd); + PackBundleCmd = nullptr; + } + + UToolMenus::UnRegisterStartupCallback(this); + UToolMenus::UnregisterOwner(this); +} + +void FUnrealLuaDemoEditorModule::OnModifyCook( + TConstArrayView InTargetPlatforms, + TArray& InOutPackagesToCook, + TArray& InOutPackagesToNeverCook) +{ + const ULuaScriptSettings* Settings = GetDefault(); + if (!Settings || !Settings->bAutoPackOnCook) + { + return; + } + + UE_LOG(LogUnrealLuaDemoEditor, Log, TEXT("[LuaBundle] Auto-packing external Lua scripts before Cook...")); + + FLuaBundlePackResult Result; + if (!FLuaBundlePacker::PackToDefaultAsset(Result)) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[LuaBundle] Pre-Cook Lua bundle packing FAILED: %s"), *Result.ErrorMessage); + return; + } + + const FString LongPackageName = Settings->LuaBundleAssetPath.GetLongPackageName(); + if (!LongPackageName.IsEmpty()) + { + const FName PackageFName(*LongPackageName); + InOutPackagesToNeverCook.Remove(PackageFName); + InOutPackagesToCook.AddUnique(PackageFName); + + UE_LOG(LogUnrealLuaDemoEditor, Log, + TEXT("[LuaBundle] Packed %d scripts (%d bytes) and queued '%s' for cooking."), + Result.ScriptCount, Result.ArchiveByteSize, *LongPackageName); + } +} + +void FUnrealLuaDemoEditorModule::RegisterMenus() +{ + FToolMenuOwnerScoped OwnerScoped(this); + + UToolMenu* ToolsMenu = UToolMenus::Get()->ExtendMenu(TEXT("LevelEditor.MainMenu.Tools")); + if (!ToolsMenu) + { + return; + } + + FToolMenuSection& Section = ToolsMenu->FindOrAddSection(TEXT("LuaScripts")); + Section.Label = LOCTEXT("LuaScriptsSection", "Lua Scripts"); + + Section.AddMenuEntry( + TEXT("PackLuaScriptBundle"), + LOCTEXT("PackLuaBundleLabel", "Pack Lua Script Bundle"), + LOCTEXT("PackLuaBundleTooltip", "Pack external Script/lua scripts into the binary ULuaBundleAsset UE resource."), + FSlateIcon(), + FUIAction(FExecuteAction::CreateLambda([]() + { + FLuaBundlePackResult Result; + if (FLuaBundlePacker::PackToDefaultAsset(Result)) + { + UE_LOG(LogUnrealLuaDemoEditor, Log, + TEXT("[LuaBundle] Packed %d scripts (%d bytes) -> %s"), + Result.ScriptCount, Result.ArchiveByteSize, *Result.OutputPath); + } + else + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[LuaBundle] Pack failed: %s"), *Result.ErrorMessage); + } + }))); +} + +#undef LOCTEXT_NAMESPACE + +IMPLEMENT_MODULE(FUnrealLuaDemoEditorModule, UnrealLuaDemoEditor); diff --git a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.h b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.h new file mode 100644 index 0000000..063c9bc --- /dev/null +++ b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.h @@ -0,0 +1,28 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Modules/ModuleManager.h" + +class ITargetPlatform; + +DECLARE_LOG_CATEGORY_EXTERN(LogUnrealLuaDemoEditor, Log, All); + +class FUnrealLuaDemoEditorModule : public IModuleInterface +{ +public: + virtual void StartupModule() override; + virtual void ShutdownModule() override; + +private: + void OnModifyCook( + TConstArrayView InTargetPlatforms, + TArray& InOutPackagesToCook, + TArray& InOutPackagesToNeverCook); + + void RegisterMenus(); + + FDelegateHandle ModifyCookHandle; + IConsoleObject* PackBundleCmd = nullptr; +}; diff --git a/Tools/create_demo_map.py b/Tools/create_demo_map.py index 9d6bcd0..21466ba 100644 --- a/Tools/create_demo_map.py +++ b/Tools/create_demo_map.py @@ -80,7 +80,7 @@ def main(): ) player_start.set_actor_label("DemoPlayerStart") - # 6. LuaDemoActor driven by Content/Script/Game/LuaDemoActor.lua + # 6. LuaDemoActor driven by Script/lua/Game/LuaDemoActor.lua demo_actor_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaDemoActor") if demo_actor_class is None: raise RuntimeError("Could not load /Script/UnrealLuaDemo.LuaDemoActor") diff --git a/UnrealLuaDemo.uproject b/UnrealLuaDemo.uproject index 2d6607d..c022e36 100644 --- a/UnrealLuaDemo.uproject +++ b/UnrealLuaDemo.uproject @@ -8,6 +8,11 @@ "Name": "UnrealLuaDemo", "Type": "Runtime", "LoadingPhase": "Default" + }, + { + "Name": "UnrealLuaDemoEditor", + "Type": "Editor", + "LoadingPhase": "Default" } ], "Plugins": [