feat: move Lua scripts to Script/lua and add binary UE bundle packing

This commit is contained in:
szy73711 committed 2026-11-29 00:18:13 +08:00
1 parent 256a60ac80
commit ebce41f347
41 files changed
+1545 -57

No files matched your search

+1 -1
View File
@@ -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
+2 -2
View File
@@ -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");
};
+1 -1
View File
@@ -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
@@ -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()
+1 -1
View File
@@ -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)
@@ -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<ULuaBundleAsset> 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<ULuaScriptSettings>()->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 <ProjectDir>/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<ULuaScriptSettings>())
{
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<ULuaScriptSettings>();
if (!Settings || !Settings->LuaBundleAssetPath.IsValid())
{
UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaBundle] LuaBundleAssetPath is not configured in ULuaScriptSettings."));
return nullptr;
}
ULuaBundleAsset* Loaded = Cast<ULuaBundleAsset>(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;
}
@@ -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: <Saved>/HotUpdate/Script/ (or PersistentDownloadDir on mobile)
* 2. Default project script directory: <Content>/Script/
* 2. Development (WITH_EDITOR, unless -UseLuaBundle is passed): external <ProjectDir>/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 (<ProjectDir>/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<uint8>& Data, FString& FullFilePath);
static bool TryLoadLuaFromRoot(const FString& RootDir, const FString& NormalizedModulePath, TArray<uint8>& OutData, FString& OutFullPath);
};
@@ -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<const uint8*>(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<uint32>(i));
uint8 Mask = static_cast<uint8>((State ^ (State >> 8) ^ (State >> 16) ^ (State >> 24)) & 0xFFu);
if (KeyLen > 0)
{
Mask ^= KeyBytes[(i + EntryIndex) % KeyLen];
}
Data[i] ^= Mask;
}
}
bool FLuaBundleArchive::Build(
const TArray<FLuaBundleSourceItem>& SourceItems,
TArray<uint8>& OutArchiveBytes,
bool bEncrypt,
const FString& EncryptionKey,
uint32 EncryptionSalt)
{
OutArchiveBytes.Reset();
// Sort deterministically by normalized lowercase path so builds are reproducible
TArray<FLuaBundleSourceItem> 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<FLuaBundleEntry> Entries;
Entries.Reserve(SortedItems.Num());
TArray<uint8> PayloadBytes;
int64 TotalPayloadSize = 0;
for (const FLuaBundleSourceItem& Item : SortedItems)
{
TotalPayloadSize += Item.PlaintextBytes.Num();
}
PayloadBytes.Reserve(static_cast<int32>(TotalPayloadSize));
for (int32 Index = 0; Index < SortedItems.Num(); ++Index)
{
const FLuaBundleSourceItem& Item = SortedItems[Index];
FLuaBundleEntry Entry;
Entry.CanonicalPath = Item.RelativePath;
Entry.EntryIndex = static_cast<uint32>(Index);
Entry.DataOffset = static_cast<uint32>(PayloadBytes.Num());
Entry.DataSize = static_cast<uint32>(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<uint32>(bEncrypt ? ELuaBundleFlags::Encrypted : ELuaBundleFlags::None);
uint32 HeaderSalt = EncryptionSalt;
uint32 EntryCount = static_cast<uint32>(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<const uint8> ArchiveBytes, const FString& EncryptionKey)
{
Reset();
if (ArchiveBytes.Num() < static_cast<int32>(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<int32>(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<FString, FLuaBundleEntry>& Pair : EntriesByLowerPath)
{
const FLuaBundleEntry& Entry = Pair.Value;
const int64 EndOffset = PayloadBaseOffset + static_cast<int64>(Entry.DataOffset) + static_cast<int64>(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<ELuaBundleFlags>(HeaderFlags);
EncryptionSalt = HeaderSalt;
CachedEncryptionKey = EncryptionKey;
bParsed = true;
return true;
}
bool FLuaBundleArchive::ExtractEntry(
const FLuaBundleEntry& Entry,
TArrayView<const uint8> ArchiveBytes,
TArray<uint8>& OutPlaintextData,
FString& OutChunkName) const
{
const int64 StartOffset = PayloadBaseOffset + static_cast<int64>(Entry.DataOffset);
const int64 EndOffset = StartOffset + static_cast<int64>(Entry.DataSize);
if (StartOffset < 0 || EndOffset > ArchiveBytes.Num())
{
return false;
}
OutPlaintextData.SetNumUninitialized(static_cast<int32>(Entry.DataSize));
if (Entry.DataSize > 0)
{
FMemory::Memcpy(OutPlaintextData.GetData(), ArchiveBytes.GetData() + StartOffset, Entry.DataSize);
if (IsEncrypted())
{
ApplyCipherInPlace(
OutPlaintextData.GetData(),
static_cast<int32>(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<const uint8> ArchiveBytes,
TArray<uint8>& 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;
}
@@ -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<uint8> 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<FLuaBundleSourceItem>& SourceItems,
TArray<uint8>& OutArchiveBytes,
bool bEncrypt,
const FString& EncryptionKey,
uint32 EncryptionSalt = 0);
/** Parses header and index table from an existing binary archive buffer. */
bool Parse(TArrayView<const uint8> 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 "<Module>.lua" first, then "<Module>/init.lua".
*/
bool ReadScript(
const FString& NormalizedModulePath,
TArrayView<const uint8> ArchiveBytes,
TArray<uint8>& 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<const uint8> ArchiveBytes,
TArray<uint8>& OutPlaintextData,
FString& OutChunkName) const;
bool bParsed = false;
uint32 FormatVersion = 0;
ELuaBundleFlags Flags = ELuaBundleFlags::None;
uint32 EncryptionSalt = 0;
int64 PayloadBaseOffset = 0;
FString CachedEncryptionKey;
TMap<FString, FLuaBundleEntry> EntriesByLowerPath;
};
@@ -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<ULuaScriptSettings>();
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<uint8>& OutData, FString& OutChunkName) const
{
FScopeLock Lock(&IndexMutex);
if (!EnsureIndexParsed())
{
return false;
}
return ParsedArchive.ReadScript(NormalizedModulePath, ArchiveBytes, OutData, OutChunkName);
}
@@ -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 <ProjectDir>/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<uint8> ArchiveBytes;
/** Looks up and decrypts a Lua script module from the packaged archive. */
bool FindScript(const FString& NormalizedModulePath, TArray<uint8>& 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;
};
@@ -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);
}
@@ -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 (<ProjectDir>/<ExternalScriptRelativePath>). */
FString GetExternalScriptRootFullPath() const;
virtual FName GetCategoryName() const override { return TEXT("Game"); }
};
@@ -15,6 +15,7 @@ public class UnrealLuaDemo : ModuleRules
"Core",
"CoreUObject",
"Engine",
"DeveloperSettings",
"InputCore",
"EnhancedInput",
"UMG",
+1
View File
@@ -11,5 +11,6 @@ public class UnrealLuaDemoEditorTarget : TargetRules
DefaultBuildSettings = BuildSettingsVersion.V7;
IncludeOrderVersion = EngineIncludeOrderVersion.Unreal5_8;
ExtraModuleNames.Add("UnrealLuaDemo");
ExtraModuleNames.Add("UnrealLuaDemoEditor");
}
}
@@ -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<FString> 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<FString, FLuaBundleSourceItem>& InOutItemsByLowerPath,
bool bAllowOverwrite)
{
if (!FPaths::DirectoryExists(RootDir))
{
return;
}
FString NormalizedRoot = FPaths::ConvertRelativePathToFull(RootDir);
FPaths::NormalizeDirectoryName(NormalizedRoot);
if (!NormalizedRoot.EndsWith(TEXT("/")))
{
NormalizedRoot += TEXT("/");
}
TArray<FString> 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<uint8> 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<FLuaBundleSourceItem>& OutItems, FString& OutError)
{
OutItems.Reset();
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
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<FString, FLuaBundleSourceItem> ItemsByLowerPath;
// 1. Collect project scripts from <ProjectDir>/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<IPlugin> 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<FString, FLuaBundleSourceItem>& Pair : ItemsByLowerPath)
{
OutItems.Add(MoveTemp(Pair.Value));
}
return true;
}
bool FLuaBundlePacker::PackToDefaultAsset(FLuaBundlePackResult& OutResult, TOptional<bool> bEncryptOverride)
{
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
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<bool> bEncryptOverride)
{
OutResult = FLuaBundlePackResult{};
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
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<FLuaBundleSourceItem> SourceItems;
if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage))
{
return false;
}
const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle);
TArray<uint8> 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<ULuaBundleAsset>(Package, *AssetName);
const bool bNewlyCreated = (BundleAsset == nullptr);
if (!BundleAsset)
{
BundleAsset = NewObject<ULuaBundleAsset>(Package, *AssetName, RF_Public | RF_Standalone);
}
BundleAsset->FormatVersion = static_cast<int32>(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<bool> bEncryptOverride)
{
OutResult = FLuaBundlePackResult{};
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
if (!Settings)
{
OutResult.ErrorMessage = TEXT("ULuaScriptSettings CDO is unavailable.");
return false;
}
TArray<FLuaBundleSourceItem> SourceItems;
if (!CollectLuaSources(SourceItems, OutResult.ErrorMessage))
{
return false;
}
const bool bEncrypt = bEncryptOverride.Get(Settings->bEncryptBundle);
TArray<uint8> 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;
}
@@ -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<FLuaBundleSourceItem>& OutItems, FString& OutError);
/** Packs external Lua scripts into the default ULuaBundleAsset configured in ULuaScriptSettings. */
static bool PackToDefaultAsset(FLuaBundlePackResult& OutResult, TOptional<bool> 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<bool> 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<bool> bEncryptOverride = {});
private:
static void CollectDirectoryLuaFiles(
const FString& RootDir,
TMap<FString, FLuaBundleSourceItem>& InOutItemsByLowerPath,
bool bAllowOverwrite);
};
@@ -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<bool> 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<ULuaScriptSettings>();
ULuaBundleAsset* LoadedAsset = Settings ? Cast<ULuaBundleAsset>(Settings->LuaBundleAssetPath.TryLoad()) : nullptr;
if (!LoadedAsset)
{
UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[PackLuaBundleCommandlet] Verify failed: could not load bundle asset."));
return 1;
}
TArray<FLuaBundleSourceItem> 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<uint8> 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;
}
@@ -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 <Project.uproject> -run=PackLuaBundle [-NoEncrypt] [-OutputFile=<path>] [-Verify]
*/
UCLASS()
class UNREALLUADEMOEDITOR_API UPackLuaBundleCommandlet : public UCommandlet
{
GENERATED_BODY()
public:
UPackLuaBundleCommandlet();
virtual int32 Main(const FString& Params) override;
};
@@ -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"
});
}
}
@@ -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<const ITargetPlatform*> InTargetPlatforms,
TArray<FName>& InOutPackagesToCook,
TArray<FName>& InOutPackagesToNeverCook)
{
const ULuaScriptSettings* Settings = GetDefault<ULuaScriptSettings>();
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);
@@ -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<const ITargetPlatform*> InTargetPlatforms,
TArray<FName>& InOutPackagesToCook,
TArray<FName>& InOutPackagesToNeverCook);
void RegisterMenus();
FDelegateHandle ModifyCookHandle;
IConsoleObject* PackBundleCmd = nullptr;
};