diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f3eb63..6124ffb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to `ts2lua-unreal` will be documented in this file. The format is based on [Semantic Versioning](https://semver.org/). +## [0.2.0] - 2026-11-29 + +### Changed +- **拆分精简 [types/unlua.d.ts](types/unlua.d.ts)**:移除所有 UE 引擎反射类声明(`UObject`/`AActor`/`UWorld`/`FVector`/`UKismetSystemLibrary` 等),仅保留 UE 反射无法自动生成的零冲突核心运行时层(`@unlua` 装饰器、`UnLua` 全局模块、`TArray`/`TMap`/`TSet`、智能指针模板别名、`FScriptDelegate`/`FMulticastScriptDelegate`/`FMulticastSparseDelegate` 以及 `UE.NewObject`/`LoadClass`/`LoadObject`),彻底避免与 UE 项目自动生成的反射 `.d.ts` 冲突。 + +### Removed +- 移除仓库内置的 `examples/` 示例工程、`examples/types/demo.d.ts` 及 `build:examples` / `watch:examples` 脚本;插件自动化测试保留在 [test/plugin.test.mjs](test/plugin.test.mjs) 中使用内存虚拟声明运行。 + ## [0.1.0] - 2026-11-29 ### Added diff --git a/README.md b/README.md index 616ad99..8d759eb 100644 --- a/README.md +++ b/README.md @@ -62,10 +62,4 @@ npm install # 构建插件并运行全部自动化测试 npm test - -# 编译示例工程(输出至 examples/out/) -npm run build:examples - -# 增量监听模式 -npm run watch:examples ``` diff --git a/docs/integration-guide.md b/docs/integration-guide.md index a9c1778..dfca416 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -34,8 +34,8 @@ YourUEProject/ ├── package.json # 声明对 ts2lua-unreal 的 Git Tag 依赖 ├── package-lock.json # 锁定精确依赖与 commit,务必提交 Git ├── tsconfig.json # 继承 ts2lua-unreal/tsconfig.base.json - ├── types/ # 本项目 UE C++/蓝图类型声明 (.d.ts) - │ └── project.d.ts + ├── types/ # 本项目自动生成的 UE 反射与蓝图类型声明 (.d.ts) + │ └── ue/ # 由 UnLua 编辑器菜单 "Generate IntelliSense & TS" 一键生成 └── src/ # 业务 TS 源码(目录结构镜像 Content/Script) ├── Framework/ └── Game/ @@ -263,7 +263,7 @@ npm install ### 5.4 `ts2lua-unreal` 仓库发版规范(维护者) 每次向外提供新版本时遵循: 1. 更新 `src/plugin/`、`types/` 或 `docs/` 并补齐 `test/plugin.test.mjs` 自动化测试; -2. 运行 `npm test && npm run build:examples` 确保全部通过; +2. 运行 `npm test` 确保全部通过; 3. 按 SemVer 更新 `package.json` 版本号与 `CHANGELOG.md`(`patch` 修 bug,`minor` 增特性/新校验,`major` 破坏性变更); 4. 提交并打 Tag 推送: ```bash diff --git a/examples/src/Framework/EventBus.ts b/examples/src/Framework/EventBus.ts deleted file mode 100644 index b306f8f..0000000 --- a/examples/src/Framework/EventBus.ts +++ /dev/null @@ -1,44 +0,0 @@ -/** @noSelfInFile */ - -interface ListenerEntry { - callback: (this: any, ...args: any[]) => void; - owner: unknown; -} - -const listeners: Record = {}; - -export function On( - eventName: string, - callback: (this: TOwner, ...args: any[]) => void, - owner: TOwner -): void { - let list = listeners[eventName]; - if (!list) { - list = []; - listeners[eventName] = list; - } - list.push({ callback, owner }); -} - -export function Emit(eventName: string, ...args: unknown[]): void { - const list = listeners[eventName]; - if (!list) return; - for (let i = 0; i < list.length; i++) { - const entry = list[i]; - entry.callback.call(entry.owner, ...args); - } -} - -export function OffAllForOwner(owner: unknown): void { - for (const [eventName, list] of pairs(listeners)) { - if (!list) continue; - for (let i = list.length - 1; i >= 0; i--) { - if (list[i].owner === owner) { - table.remove(list, i + 1); - } - } - if (list.length === 0) { - listeners[eventName] = undefined; - } - } -} diff --git a/examples/src/Framework/Log.ts b/examples/src/Framework/Log.ts deleted file mode 100644 index 2ca5dcf..0000000 --- a/examples/src/Framework/Log.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** @noSelfInFile */ - -export function Info(fmt: string, ...args: unknown[]): void { - const msg = args.length > 0 ? string.format(fmt, ...args) : fmt; - print("[INFO] " + msg); -} - -export function Warn(fmt: string, ...args: unknown[]): void { - const msg = args.length > 0 ? string.format(fmt, ...args) : fmt; - print("[WARN] " + msg); -} - -export function Error(fmt: string, ...args: unknown[]): void { - const msg = args.length > 0 ? string.format(fmt, ...args) : fmt; - print("[ERROR] " + msg); -} diff --git a/examples/src/Game/LuaDemoActor.ts b/examples/src/Game/LuaDemoActor.ts deleted file mode 100644 index f6fa55e..0000000 --- a/examples/src/Game/LuaDemoActor.ts +++ /dev/null @@ -1,140 +0,0 @@ -import * as Log from "../Framework/Log"; -import * as EventBus from "../Framework/EventBus"; - -interface DemoColorEntry { - Name: string; - R: number; - G: number; - B: number; - A: number; -} - -const DEMO_COLORS: DemoColorEntry[] = [ - { Name: "Cyan", R: 0.08, G: 0.78, B: 0.95, A: 1.0 }, - { Name: "Gold", R: 0.98, G: 0.72, B: 0.12, A: 1.0 }, - { Name: "Magenta", R: 0.92, G: 0.22, B: 0.65, A: 1.0 }, - { Name: "Lime", R: 0.25, G: 0.9, B: 0.35, A: 1.0 }, - { Name: "Orange", R: 0.98, G: 0.42, B: 0.14, A: 1.0 }, -]; - -/** @noSelf */ -function MakeLinearColor(c: DemoColorEntry): UE.FLinearColor { - return UE.FLinearColor(c.R, c.G, c.B, c.A); -} - -@unlua -export default class LuaDemoActor extends UE.ALuaDemoActor { - protected ElapsedTime!: number; - protected TextRefreshTimer!: number; - protected TickCount!: number; - protected PingCount!: number; - protected ColorIndex!: number; - protected HasLoggedTick!: boolean; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - - this.ElapsedTime = 0.0; - this.TextRefreshTimer = 0.0; - this.TickCount = 0; - this.PingCount = 0; - this.ColorIndex = 0; - this.HasLoggedTick = false; - - EventBus.On("Demo.Ping", this.OnDemoPing, this); - - this.ApplyCurrentColor(); - this.RefreshStatusText(); - - Log.Info("LuaDemoActor:ReceiveBeginPlay() bound successfully! Lua=%s", _VERSION); - - const msg = string.format( - "[UnLua Demo] LuaDemoActor active (%s) - Press [Space] to Ping", - _VERSION - ); - UE.UKismetSystemLibrary.PrintString( - this, - msg, - true, - true, - UE.FLinearColor(0.2, 1.0, 0.4, 1.0), - 8.0 - ); - } - - ReceiveTick(DeltaSeconds: number): void { - this.ElapsedTime = (this.ElapsedTime || 0.0) + DeltaSeconds; - this.TickCount = (this.TickCount || 0) + 1; - - if (!this.HasLoggedTick) { - this.HasLoggedTick = true; - Log.Info("LuaDemoActor:ReceiveTick() first tick verified (dt=%.4f)", DeltaSeconds); - } - - const yawDelta = (this.SpinSpeed || 60.0) * DeltaSeconds; - const pitchDelta = yawDelta * 0.35; - this.AddCubeLocalRotation(UE.FRotator(pitchDelta, yawDelta, 0.0)); - - const zOffset = - math.sin(this.ElapsedTime * (this.BobFrequency || 2.0)) * (this.BobAmplitude || 25.0); - this.SetCubeVerticalOffset(zOffset); - - this.TextRefreshTimer = (this.TextRefreshTimer || 0.0) + DeltaSeconds; - if (this.TextRefreshTimer >= 0.2) { - this.TextRefreshTimer = 0.0; - this.RefreshStatusText(); - } - } - - OnDemoPing(sourceName: string): void { - this.PingCount = (this.PingCount || 0) + 1; - this.ColorIndex = (this.ColorIndex + 1) % DEMO_COLORS.length; - const colorEntry = this.ApplyCurrentColor(); - this.RefreshStatusText(); - - const msg = string.format( - "[UnLua Demo] Ping #%d from %s -> Cube color: %s", - this.PingCount, - tostring(sourceName), - colorEntry.Name - ); - Log.Info(msg); - UE.UKismetSystemLibrary.PrintString( - this, - msg, - true, - true, - MakeLinearColor(colorEntry), - 3.0 - ); - } - - ApplyCurrentColor(): DemoColorEntry { - const colorEntry = DEMO_COLORS[this.ColorIndex] || DEMO_COLORS[0]; - this.SetCubeColor(MakeLinearColor(colorEntry)); - return colorEntry; - } - - RefreshStatusText(): void { - const colorEntry = DEMO_COLORS[this.ColorIndex] || DEMO_COLORS[0]; - const text = string.format( - "UnLua Active (%s)\nTime: %.1fs | Pings: %d | Color: %s", - _VERSION, - this.ElapsedTime || 0.0, - this.PingCount || 0, - colorEntry.Name - ); - this.SetStatusText(text); - } - - ReceiveEndPlay(EndPlayReason: number): void { - EventBus.OffAllForOwner(this); - Log.Info( - "LuaDemoActor:ReceiveEndPlay(ticks=%d, pings=%d, reason=%s)", - this.TickCount || 0, - this.PingCount || 0, - tostring(EndPlayReason) - ); - super.ReceiveEndPlay(EndPlayReason); - } -} diff --git a/examples/src/Game/LuaSpecialDemoActor.ts b/examples/src/Game/LuaSpecialDemoActor.ts deleted file mode 100644 index a32f83a..0000000 --- a/examples/src/Game/LuaSpecialDemoActor.ts +++ /dev/null @@ -1,17 +0,0 @@ -import * as Log from "../Framework/Log"; -import LuaDemoActor from "./LuaDemoActor"; - -@unlua -export default class LuaSpecialDemoActor extends LuaDemoActor { - private BoostMultiplier!: number; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.BoostMultiplier = 2.0; - Log.Info("LuaSpecialDemoActor initialized with boost=%.1f", this.BoostMultiplier); - } - - ReceiveTick(DeltaSeconds: number): void { - super.ReceiveTick(DeltaSeconds * this.BoostMultiplier); - } -} diff --git a/examples/tsconfig.json b/examples/tsconfig.json deleted file mode 100644 index ef5784e..0000000 --- a/examples/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "extends": "../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "out" - }, - "include": [ - "src/**/*.ts", - "types/**/*.d.ts", - "../types/**/*.d.ts" - ], - "tstl": { - "luaTarget": "5.4", - "luaLibImport": "require-minimal", - "noImplicitSelf": false, - "noHeader": true, - "sourceMapTraceback": false, - "luaPlugins": [ - { - "name": "../dist/plugin/index.js" - } - ] - } -} diff --git a/examples/types/demo.d.ts b/examples/types/demo.d.ts deleted file mode 100644 index 76978b3..0000000 --- a/examples/types/demo.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * UnrealLuaDemo 项目自定义 C++ Actor 类型声明示例 - */ -declare namespace UE { - class ALuaDemoActor extends AActor { - SpinSpeed: number; - BobFrequency: number; - BobAmplitude: number; - - AddCubeLocalRotation(DeltaRotation: FRotator): void; - SetCubeVerticalOffset(ZOffset: number): void; - SetCubeColor(Color: FLinearColor): void; - SetStatusText(Text: string): void; - static StaticClass(this: void): UClass; - } -} diff --git a/package-lock.json b/package-lock.json index 0a06159..e94c87d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ts2lua-unreal", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ts2lua-unreal", - "version": "0.1.0", + "version": "0.2.0", "dependencies": { "lua-types": "^2.14.1", "typescript": "6.0.2", diff --git a/package.json b/package.json index 6e0b58a..8ccce90 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ts2lua-unreal", - "version": "0.1.0", + "version": "0.2.0", "description": "TypeScript to Lua toolchain and compiler plugin tailored for Unreal Engine + UnLua", "main": "dist/plugin/index.js", "types": "dist/plugin/index.d.ts", @@ -32,8 +32,6 @@ "scripts": { "prepare": "npm run build:plugin", "build:plugin": "tsc -p tsconfig.plugin.json", - "build:examples": "npm run build:plugin && tstl -p examples/tsconfig.json", - "watch:examples": "tstl -p examples/tsconfig.json --watch", "test": "npm run build:plugin && node --test test/*.test.mjs" }, "dependencies": { diff --git a/test/plugin.test.mjs b/test/plugin.test.mjs index e507484..2a55318 100644 --- a/test/plugin.test.mjs +++ b/test/plugin.test.mjs @@ -13,12 +13,37 @@ const unluaTypesContent = fs.readFileSync(unluaTypesPath, "utf8"); const pluginPath = path.join(projectRoot, "dist", "plugin", "index.js"); const { UnLuaDiagnosticCode } = require(pluginPath); +const VIRTUAL_UE_REFLECTION_DTS = ` +declare namespace UE { + class UObject { + GetName(): string; + GetClass(): UClass; + IsValid(): boolean; + IsA(someBase: UClass): boolean; + static StaticClass(this: void): UClass; + } + class UClass extends UObject {} + class AActor extends UObject { + ReceiveBeginPlay(): void; + ReceiveTick(DeltaSeconds: number): void; + ReceiveEndPlay(EndPlayReason: number): void; + static StaticClass(this: void): UClass; + } + class UUserWidget extends UObject { + Construct(): void; + Destruct(): void; + static StaticClass(this: void): UClass; + } +} +`; + /** * 在内存中编译一组虚拟 TS 文件并启用 UnLua 插件。 */ function transpileWithUnLua(files) { const virtualFiles = { "unlua.d.ts": unluaTypesContent, + "ue.generated.d.ts": VIRTUAL_UE_REFLECTION_DTS, ...files, }; @@ -433,14 +458,3 @@ test("forbids multiple @unlua classes in one file, invalid @unlua args, and dire assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaMultipleClassesInFile)); assert.ok(codes.has(UnLuaDiagnosticCode.UnLuaForbiddenSuperUsage)); }); - -// ============================================================ -// 4. 端到端示例工程编译验证 -// ============================================================ - -test("examples/tsconfig.json transpiles cleanly with zero diagnostics", () => { - const exampleConfigPath = path.join(projectRoot, "examples", "tsconfig.json"); - const result = tstl.transpileProject(exampleConfigPath); - const errors = result.diagnostics.filter((d) => d.category === ts.DiagnosticCategory.Error); - assert.equal(errors.length, 0, errors.map((e) => ts.flattenDiagnosticMessageText(e.messageText, "\n")).join("\n")); -}); diff --git a/types/unlua.d.ts b/types/unlua.d.ts index 2fa92f9..ea63707 100644 --- a/types/unlua.d.ts +++ b/types/unlua.d.ts @@ -1,6 +1,13 @@ /** - * UnLua + Unreal Engine 基础编译期类型声明。 - * 实际 UE 项目可在此基础上叠加由 UnLua / UHT 自动导出的完整 UE .d.ts。 + * ts2lua-unreal + UnLua 核心运行时编译期类型声明(零冲突层)。 + * + * 本文件仅包含 UE 反射系统无法自动导出的内容: + * 1. `@unlua` 编译期装饰器 + * 2. `UnLua` 全局模块接口 + * 3. UnLua 通用容器(TArray / TMap / TSet)、智能指针/模板别名、Delegate 包装与 UE 全局加载/创建函数 + * + * 所有 UE 引擎反射类(UObject / AActor / UWorld / FVector / 项目 C++ 与蓝图类等) + * 由 UE 工程中的 UnLua Editor 命令(Generate IntelliSense & TS)自动生成并自动合并至 `UE` 命名空间。 */ /** @@ -15,6 +22,9 @@ declare function unlua(baseModuleName: string): (target: abstract new (...args: * UnLua 全局模块接口 */ declare namespace UnLua { + let PackagePath: string; + let FTextEnabled: boolean; + /** @noSelf */ function Class(superClassName?: string): any; /** @noSelf */ @@ -22,138 +32,94 @@ declare namespace UnLua { /** @noSelf */ function Unref(obj: UE.UObject): void; /** @noSelf */ - function HotReload(): void; + function HotReload(moduleNames?: string[]): void; } /** - * UE 核心反射与容器基础声明(精简基线,供插件校验与示例使用) + * UnLua 非反射泛型容器、委托与全局辅助函数(与自动生成的 UE 反射 `.d.ts` 自动合并) */ declare namespace UE { - class UObject { - GetName(): string; - GetClass(): UClass; - GetWorld(): UWorld | undefined; + type TSubclassOf = UClass; + + interface TSoftClassPtr { IsValid(): boolean; - IsA(someBase: UClass): boolean; - Initialize(Initializer?: unknown): void; + IsNull(): boolean; + IsPending(): boolean; + Reset(): void; + Set(obj: UClass | undefined): TSoftClassPtr; + GetAssetName(): string; + GetLongPackageName(): string; + Get(): UClass | undefined; + LoadSynchronous(): UClass | undefined; } - class UClass extends UObject {} - - class UWorld extends UObject { - SpawnActor( - actorClass: UClass, - transform?: FTransform, - collisionHandling?: number, - owner?: AActor, - instigator?: APawn, - moduleName?: string - ): T | undefined; + interface TSoftObjectPtr { + IsValid(): boolean; + IsNull(): boolean; + IsPending(): boolean; + Reset(): void; + Set(obj: T | undefined): TSoftObjectPtr; + GetAssetName(): string; + GetLongPackageName(): string; + Get(): T | undefined; + LoadSynchronous(): T | undefined; } - class UActorComponent extends UObject { - ReceiveBeginPlay(): void; - ReceiveTick(DeltaSeconds: number): void; - ReceiveEndPlay(EndPlayReason: number): void; + interface TWeakObjectPtr { + IsValid(): boolean; + Reset(): void; + Set(obj: T | undefined): void; + Get(): T | undefined; } - class AActor extends UObject { - ReceiveBeginPlay(): void; - ReceiveTick(DeltaSeconds: number): void; - ReceiveEndPlay(EndPlayReason: number): void; - K2_GetActorLocation(): FVector; - K2_SetActorLocation( - NewLocation: FVector, - bSweep?: boolean, - SweepHitResult?: unknown, - bTeleport?: boolean - ): boolean; - K2_DestroyActor(): void; - static StaticClass(this: void): UClass; + interface TLazyObjectPtr { + IsValid(): boolean; + Reset(): void; + Set(obj: T | undefined): void; + Get(): T | undefined; } - class APawn extends AActor { - static StaticClass(this: void): UClass; - } + type TScriptInterface = T; - class ACharacter extends APawn { - static StaticClass(this: void): UClass; - } - - class APlayerController extends AActor { - static StaticClass(this: void): UClass; - } - - class AGameModeBase extends AActor { - static StaticClass(this: void): UClass; - } - - class UGameInstance extends UObject { - ReceiveInit(): void; - ReceiveShutdown(): void; - static StaticClass(this: void): UClass; - } - - class UUserWidget extends UObject { - Construct(): void; - Destruct(): void; - Tick(MyGeometry: unknown, InDeltaTime: number): void; - static StaticClass(this: void): UClass; - } - - interface FVector { - X: number; - Y: number; - Z: number; - Add(other: FVector): FVector; - Sub(other: FVector): FVector; - Size(): number; - } - function FVector(this: void, X?: number, Y?: number, Z?: number): FVector; - - interface FRotator { - Pitch: number; - Yaw: number; - Roll: number; - } - function FRotator(this: void, Pitch?: number, Yaw?: number, Roll?: number): FRotator; - - interface FTransform { - Translation: FVector; - Rotation: unknown; - Scale3D: FVector; - } - function FTransform(this: void): FTransform; - - interface FLinearColor { - R: number; - G: number; - B: number; - A: number; - } - function FLinearColor(this: void, R?: number, G?: number, B?: number, A?: number): FLinearColor; - - interface FMulticastScriptDelegate void = () => void> { + interface FMulticastScriptDelegate void = (...args: any[]) => void> { Add(target: UObject, callback: TCallback): void; Remove(target: UObject, callback: TCallback): void; Clear(): void; Broadcast(...args: Parameters): void; + IsBound(): boolean; } - interface FScriptDelegate void = () => void> { + type FMulticastSparseDelegate void = (...args: any[]) => void> = + FMulticastScriptDelegate; + + interface FScriptDelegate any = (...args: any[]) => any> { Bind(target: UObject, callback: TCallback): void; Unbind(): void; + Execute(...args: Parameters): ReturnType; } interface TArray { Length(): number; Num(): number; Add(item: T): number; - Get(index: number): T; - Set(index: number, item: T): void; + AddUnique(item: T): number; + Find(item: T): number; + Insert(item: T, index: number): void; Remove(index: number): void; + RemoveItem(item: T): boolean; Clear(): void; + Reserve(size: number): boolean; + Resize(size: number): void; + GetData(index: number): unknown; + Get(index: number): T; + GetRef(index: number): T; + Set(index: number, item: T): void; + Swap(firstIndex: number, secondIndex: number): void; + Shuffle(): void; + LastIndex(): number; + IsValidIndex(index: number): boolean; Contains(item: T): boolean; + Append(other: TArray): void; ToTable(): T[]; } function TArray(this: void, elementType: any): TArray; @@ -162,9 +128,9 @@ declare namespace UE { Length(): number; Num(): number; Add(key: K, value: V): void; - Find(key: K): V | undefined; Remove(key: K): boolean; - Contains(key: K): boolean; + Find(key: K): V | undefined; + FindRef(key: K): V | undefined; Clear(): void; Keys(): TArray; Values(): TArray; @@ -179,29 +145,23 @@ declare namespace UE { Remove(item: T): boolean; Contains(item: T): boolean; Clear(): void; + ToArray(): TArray; ToTable(): T[]; } function TSet(this: void, elementType: any): TSet; - /** @noSelf */ - namespace UKismetSystemLibrary { - function PrintString( - WorldContextObject: UObject | undefined, - InString?: string, - bPrintToScreen?: boolean, - bPrintToLog?: boolean, - TextColor?: FLinearColor, - Duration?: number - ): void; - function IsValid(Object: UObject | undefined): boolean; - function Delay(WorldContextObject: UObject, Duration: number): void; - } - /** @noSelf */ function NewObject( outerClass: UClass, outer?: UObject, name?: string, - moduleName?: string + moduleName?: string, + initializerTable?: Record ): T; + + /** @noSelf */ + function LoadClass(classPath: string): UClass | undefined; + + /** @noSelf */ + function LoadObject(objectPath: string): T | undefined; }