# Code Generation Rules: UE5 Editor Tools (MVVM Architecture)
## 1. Strict UI / Business Logic Separation
* **No UI dependencies in C++:** Business logic (Models and ViewModels) must never include GUI-related headers (`UMG`, `Slate`, `UWidget`, etc.).
* **External services isolation:** Any communication with external services (like data parsing or REST API HTTP requests) must be encapsulated within the Model. The Model updates the ViewModel, and the UI merely reflects this state.
* **Exclusive Binding:** The interface (Editor Utility Widget) must bind exclusively to properties exposed by the ViewModel. No business logic should reside in the Blueprint event graph of the interface.
## 2. ViewModels Design (C++)
* **Clean Blueprint Exposure:** Strictly use `UPROPERTY(BlueprintReadWrite, FieldNotify)` macros for state data and `UFUNCTION(BlueprintCallable)` for user actions.
* **Surgical Notification:** Only trigger change notifications (e.g., `BroadcastFieldValueChanged`) when the data has actually been modified, to avoid unnecessary and costly UI redraws in the editor.
* **Simplicity (YAGNI):** Limit inheritance depth. Do not create complex interfaces for ViewModels unless strictly justified by immediate needs.
## 3. Memory Management and Execution
* **Standard C++ vs UObject:** For pure internal logic not requiring Unreal’s reflection (string manipulation, calculations, buffers), prefer standard smart pointers (`TUniquePtr`, `TSharedPtr`) and move semantics to avoid unnecessary allocations. Reserve `UObject` for elements needing to interact with the editor or Garbage Collector.
* **Event-Driven:** Never use the `Tick` function for tool updates. All state changes must be reactive (editor delegates, network callbacks, user actions).
* **Tool Lifecycle:** Ensure subscriptions to global editor events are cleanly unregistered upon tool closure or destruction to prevent memory leaks.
## 4. Naming and Readability
* **Absolute Clarity:** No abbreviations (e.g., use `FetchTaskStatus` instead of `GetTskStat`). Every name must read clearly as technical English.
* **Unreal Conventions:** Strictly follow Epic’s naming conventions (`U` for UObject-derived classes, `F` for structs, `E` for enums, `b` for booleans).
## 5. Required Generation Workflow
* Before writing any logical implementation (`.cpp`), provide only the header files (`.h`) describing the Model and ViewModel architecture.
* Wait for my validation on the contracts (function signatures, exposed properties) before generating function bodies.
## 6. C++ Rigor and Encapsulation
* **Absolute Const-Correctness:** Strictly apply the `const` keyword. Any member function that doesn’t modify internal state must be marked `const`. Any reference parameter not modified must be `const Type&`. (In Unreal, a `BlueprintCallable` function marked `const` becomes a “Pure” node without an execution pin).
* **Strict Encapsulation (No Friend):** Using the `friend` keyword is strictly forbidden. If two classes need to share internal data, the architecture is flawed. Use clear public interfaces or rethink responsibility distribution.
* **Zero “Magic Numbers”:** No hardcoded numerical values or string literals in the middle of business logic. Use `constexpr` for internal constants and expose tweakable parameters via `UPROPERTY`.
## 7. Control Flow and Safety (Design by Contract)
* **Guard Clauses (Early Returns):** Avoid deep conditional nesting (the “Arrow” anti-pattern). Validate pre-conditions at the very beginning of the function and return/exit immediately upon failure. The “happy path” should not be indented.
* **Strict Assertions:** Aggressively validate object states. Use Unreal macros (`check()`, `ensure()`, `ensureAlwaysMsgf()`) to enforce design contracts and crash execution early upon invariant violations. Never assume a pointer is valid without testing it.
* **Clean Lambdas:** When using lambda expressions (especially for callbacks or async tasks), be explicit with captures. Global capture `[&]` or `[=]` is forbidden. Capture only what is necessary, and carefully manage the lifetime of captured objects (use weak pointers if the object might be destroyed).
## 8. Clean Code and Maintenance
* **DRY Principle (Don’t Repeat Yourself):** No code duplication is tolerated. If the same 3-line logic appears in two places, extract it into a private utility function.
* **Single Responsibility (SRP):** A class, struct, or function must have only one reason to change. If a function validates data, parses it, and then updates the UI, it must be split up.
* **Compilation Optimization:** In header files (`.h`), strictly limit `#include` directives. Systematically use forward declarations (`class UMyClass;`) when only a pointer or reference is used, to reduce global compilation time.
## 9. Traceability and Error Handling (Logging)
* **Explicit Traceability:** Never leave an error or edge case silent. Use `UE_LOG` with custom categories (`DECLARE_LOG_CATEGORY_EXTERN`) to trace important events.
* **Appropriate Log Levels:** Use `Warning` for recoverable unexpected behaviors and `Error` for critical failures. Reserve `Display` or `Log` for normal tracking.
* **Rich Context:** When an error is logged, always include context (e.g., object name, asset ID, or concerned entity) to facilitate debugging.
## 10. Data-Driven Design
* **No Hardcoding:** If logic depends on balancing values, file paths, or configurations, these must not be hardcoded in C++.
* **Asset Utilization:** Expose these configurations via `UDataAsset`, `UDataTable`, or at the very least `UPROPERTY(EditDefaultsOnly)`. The code must provide the *system*; designers must provide the *data*.
## 11. Asynchrony and Responsiveness (Non-Blocking Tools)
* **Respect the Main Thread (Game/Editor Thread):** An editor tool must never block or freeze the user interface.
* **Heavy Tasks:** If the tool must parse large external files, query a REST API (Jira, custom server), or process thousands of assets, delegate the work to asynchronous tasks (via Unreal’s `Async` framework, `TaskGraph`, or async HTTP requests).
* **Return to Main Thread:** Ensure that ViewModel updates (and thus UI updates) following an async task are always safely executed back on the Game Thread (e.g., via `AsyncTask(ENamedThreads::GameThread, [](){…})`).
## 12. Documentation and Intent (Comments)
* **The “Why”, not the “How”:** Code should be clear enough to explain *what* it does. Comments should only exist to explain *why* a technical decision was made (e.g., “Workaround for a known bug in engine version 5.3” or “Required because the third-party API expects this format”).
* **Public API Documentation:** Every function exposed in the header (`.h`) must be preceded by a comment explaining its purpose, parameters, pre-conditions, and return values.
## 13. [AI Specific] API Anti-Hallucination
* **No Inventing:** Never assume the existence of a function in the Unreal Engine C++ API. If you are not 100% certain that a function or macro exists in the requested Unreal version, do not guess it.
* **Doubt Fallback:** If you do not know how to accomplish a specific action using the Unreal API, write an explicit comment `// TODO: [Description of required action]` and ask me to provide the exact documentation or function before proceeding.
What do you think?