Files

228 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AGENTS.md — Seele Engine
Guidance for AI agents (and humans) working in this repository. Read this first, then
`README.md` and `OPTIMIZATIONS.md` for deeper design detail.
## What this is
**Seele** is a general-purpose 3D game/render engine. C++ (C++23), **Vulkan** as the primary
graphics backend (a Metal backend exists; the `Graphics` API is designed so other backends
like OpenGL could be added). It is a proof-of-concept engine but is built to be extensible.
- **Engine** — shared library, the core (`src/Engine`).
- **Editor** — executable, the content/inspector tool (`src/Editor`).
- **AssetViewer** — executable (`src/AssetViewer`).
- **Benchmark** — executable (`src/Benchmark`).
- **SeeleUnitTests** — GTest executable (`tests/`).
> Note: an earlier design used a coroutine-based Job system (`Job`/`MainJob`/`Event` and
> templated `RenderPass<T>`). It was dropped (MSVC memory-leak issues + forcing everything
> async). The shipped job system is a plain `ThreadPool` (`src/Engine/ThreadPool.{h,cpp}`,
> `getThreadPool()`). Do not assume the coroutine API is present.
## Repo layout
```
src/
Engine/ # the engine shared library (one CMake target: Engine)
Graphics/ # graphics API abstraction + Vulkan + Metal + RenderPass impls
Vulkan/ # Vulkan backend (Graphics.h is the abstract base in Graphics/)
Metal/ # Metal backend
RenderPass/ # concrete render passes (BasePass, DepthCulling, LightCulling,
# Shadow, RayTracing, ToneMapping, UI, Visibility, Fluid, ...)
CBT/ # command buffer tracking
Containers/ # custom containers (Array, StaticArray, Map, List, Set, Tree, ...)
Math/ # math (glm-backed typedefs: Vector, Vector3→Vector, Matrix4, etc.)
Asset/ # asset registry, loaders (mesh, texture, font, material, env, SVG, level)
Material/ # material / BRDF system (Slang-generated)
Actor/ # Entity + concrete actors (mesh, light, camera) — EnTT-based
Component/ # components (Transform, Mesh, Camera, lights, colliders, ...)
Scene/ # scene, event manager, light environment
System/ # per-frame systems: SystemGraph, ComponentSystem, updaters (mesh,
# light, fluid, camera), executor
Physics/ # physics: BVH, collision system, physics system
Serialization/ # ArchiveBuffer + Serialization.h
UI/ # custom UI framework (Element, FlexLayout, Style)
Window/ # WindowManager, View (GameView, etc.)
Platform/ # per-OS: Linux/, Mac/, Windows/ (GameInterface)
Editor/ # Editor executable (main.cpp, Asset/ importers, Window/ views)
AssetViewer/ # AssetViewer executable
Benchmark/ # Benchmark executable
tests/
Engine/ # GTest suite, mirrored under Engine/<Subsystem>/
res/
shaders/ # Slang shader sources (.slang)
fonts/ textures/ cmake/
cmake/ # SuperBuild.cmake, EngineConfig.cmake.in
external/ # submodules: vcpkg, CRCpp, metal-cpp (do not edit)
```
## Building
Standard CMake, **C++23**. Deps come from **vcpkg** (manifest mode, `vcpkg.json`) plus the
`external/` submodules. Prereq on Linux: the X11 dev libs for GLFW
(`libx11-dev libxrandr-dev libxinerama-dev libxcursor-dev libxi-dev`).
```bash
# one-time: pull dependencies (vcpkg submodule + everything)
git submodule update --init --recursive
# configure + build (use a preset)
cmake --preset debug
cmake --build --preset debug --config Debug
```
Presets (`CMakePresets.json`): `debug`, `release`, `debug-asan`, `release-asan`,
`debug-mac` (Xcode). Binary dir is the in-tree `build/` (gitignored). The vcpkg toolchain
is hard-wired in the top-level `CMakeLists.txt`
(`CMAKE_TOOLCHAIN_FILE=${EXTERNAL_ROOT}/vcpkg/scripts/buildsystems/vcpkg.cmake`).
- The engine is a **SHARED** lib (`add_library(Engine SHARED)`) — all four binaries link it.
- `Editor` is compiled with `EDITOR=1` and includes `src/Editor` + the Stb includes.
- On non-Apple, the `slang-glslang` **plugin** is a MODULE library and is **copied** next to
the `Engine` binary at post-build (do not try to link it). On Windows the runtime DLLs are
likewise copied next to `Editor`.
- Windows defines `USE_EXTENSIONS` and adds `WIN32`; MSVC builds with `/W4`, GCC/Clang with
`-Wall -Wextra -Wno-error -pedantic`. Warnings are **not** fatal, but keep the build clean.
- There is **no CI** and no `test` preset. Run tests manually (below).
`OPTIMIZATIONS.md` is a scratch list of optimization ideas (LTO, PGO, attributes, copy-avoidance
guidelines) — it is reference material, not a build requirement.
## Testing
GTest. `tests/` builds a single `SeeleUnitTests` binary and registers with CTest via
`gtest_discover_tests`. Tests are organized to mirror the engine tree
(`tests/Engine/Containers/Array.cpp`, `tests/Engine/Math/Vector.cpp`,
`tests/Engine/System/ComponentSystem.cpp`, `tests/Engine/Serialization/ArchiveBuffer.cpp`,
`tests/Engine/ThreadPool.cpp`, `tests/Engine/UI/...`, `tests/Engine/Graphics/...`).
- Every test file includes `tests/Engine/EngineTest.h` (which pulls in `<gtest/gtest.h>` +
`MinimalEngine.h` + `using namespace Seele;`).
- Add a new test: create `tests/Engine/<Subsystem>/Foo.cpp` and **add it to that
subdirectory's `tests/Engine/<Subsystem>/CMakeLists.txt`** (the subdirs `add_subdirectory`
into `tests/Engine/CMakeLists.txt`). Forgetting the CMake registration is the #1 way a new
test silently never compiles or runs.
- Run: `cd build && ctest --test-dir . -R <TestNamePattern> --output-on-failure` (or run the
`SeeleUnitTests` binary directly). Use a `debug`/`debug-asan` preset for test development.
## Core architecture (read before touching Graphics/RenderPass)
The invariants that are **actual in the code**:
- **`Gfx::Graphics`** (`src/Engine/Graphics/Graphics.h`) is the abstract backend interface.
`Vulkan::Graphics` (`Graphics/Vulkan/Graphics.h`) and `Metal::Graphics` (`Graphics/Metal/`)
implement it. All GPU work goes through this interface; render passes must not touch
Vulkan or Metal handles directly. `ENABLE_VALIDATION` is defined in `Graphics.h`.
- **Window → View → RenderPass.** A `WindowManager` owns `Graphics` + `Window`s; each
`Window` holds `View`s (a viewport; e.g. `Editor::InspectorView`, `GameView`). Rendering of
all viewports in a window is synchronized, but per-`View` logic runs on its own thread.
The thread handshake is the lock-protected `commitUpdate()` (logic side) → `prepareRender()`
(render side); a `View` pushes a concrete `RenderPassDataType` packet to each pass it uses.
- **Render passes** are plain (non-template) `RenderPass` subclasses in
`src/Engine/Graphics/RenderPass/` (`beginFrame`/`render`/`endFrame`/`publishOutputs`/
`createRenderPass`). All passes share one `PRenderGraphResources` object; a pass
**publishes** the GPU outputs it produces (`publishOutputs()`) and other passes **consume**
them by name — so pass *init order does not matter*. If you add a pass that produces or
consumes shared resources, you must wire both the publish and the consume.
- **Descriptor sets** for pass-shared data (camera, lights, view params) are managed per
render pass; because Vulkan pipeline layouts cannot have empty set indices, each pass has a
static `modifyRenderPassMacros` that `#define`s the correct descriptor-set indices for shared
layouts. Keep that in sync if you add/remove descriptor sets.
- **`getGlobals()`** (`MinimalEngine.h`) is the global feature/flags struct (e.g.
`useRayTracing`, `useDepthCulling`, `running`, …). It controls which passes run. Treat it as
global mutable state — do not add per-frame logic to it.
### Entities / scenes / systems (EnTT)
- `Actor`/`Entity` (`src/Engine/Actor/`) wrap an **EnTT** entity ID + a `PScene`. Components
live in `src/Engine/Component/`; attach via `scene->attachComponent<C>(...)` /
`entity.accessComponent<C>()`.
- Per-frame update is driven by `SystemGraph` / `ComponentSystem` in `src/Engine/System/`.
A `Component` can declare dependencies on other components (the `Dependencies` /
`has_dependencies` / `REQUIRE_COMPONENT` mechanism in `Component.h`). The concrete updaters
(`MeshUpdater`, `LightGather`, `FluidUpdater`, `CameraUpdater`, …) are the per-frame work
and must be registered in the system graph.
### Materials (Slang-generated)
- A material is a JSON doc: a `profile` (BRDF, e.g. `BlinnPhong`), typed `params` (HLSL
types + defaults), and a `code` section with one string-array per BRDF output. On load,
the engine generates the descriptor layout and compiles a Slang `IMaterial` type (see
`src/Engine/Material/`, `Graphics/slang-compile.cpp`).
Shared Slang lives in `res/shaders/*.slang`; per-material pipeline variants are generated
from a render pass's base `.slang` via `#define`s. **If you change the set of BRDF outputs
or a shared Slang input, the generated material code and the `prepare()`/`get*` accessors
must stay consistent** — they are produced from the JSON profile, not hand-written.
## Code conventions (match the surrounding code)
- **C++23.** The build sets `CMAKE_CXX_STANDARD 23`; C++20/23 features are in active use
(concepts, `std::span`, designated initializers, `<=>` spaceship, `[[unlikely]]`, etc.).
- **Formatting: `.clang-format`** — `BasedOnStyle: LLVM`, `IndentWidth: 4`, `ColumnLimit: 140`,
left-aligned pointers (`P*`, not `P *`), 2-space class-member indent in practice (see
`Graphics.h`/`RenderPass.h`). Headers use `#pragma once`. Keep to it; do not reformat
untouched code.
- **Namespaces.** Engine code lives in `namespace Seele`; the graphics backend in
`namespace Seele::Gfx` (Vulkan impl in `Seele::Vulkan`, Metal in `Seele::Metal`).
- **Types.**
- Fixed-width scalars come from `EngineTypes.h`: `uint8/16/32/64`, `int8/16/32/64`.
Prefer these over `std::uint32_t` for consistency with the codebase.
- Math types are **glm typedefs** in `Math/Math.h`/`Vector.h`/`Matrix.h`: `Vector` is
`glm::vec3`, `Vector2`/`Vector4`/`UVector`(`uvec3`)/`IVector`/`Quaternion`
(`glm::quat`)/`Matrix4`, etc. Use these, not raw `glm::vec*`. `Math.h` re-exports glm.
- `Matrix` types: `Matrix4` etc. — `Matrix.h`.
- **Smart pointers / ownership** (the most important idiom — defined in `MinimalEngine.h`):
- `DEFINE_REF(ClassName)` at the end of a class's header typedefs `P<Name>`, `UP<Name>`,
`O<Name>`. `DECLARE_REF(ClassName)` is the same but only forward-declares (for
headers that need the typedefs but not the class). `DECLARE_NAME_REF(nmsp, Name)`
is the namespaced variant (used heavily in `Gfx`, e.g. `DECLARE_NAME_REF(Gfx, Viewport)`).
- **`P<T>`** = `RefPtr<T>` — a *non-owning* strong reference (shared, `dynamic_cast`
`cast()`, `<=>`-comparable). Use as the default "have a reference" type (members,
parameters, return of non-owning lookups).
- **`O<T>`** = `OwningPtr<T>` — the *owning* pointer (move-only, deletes on scope exit,
implicitly converts to `P<T>`). Use it for the **result of factories/creators** —
e.g. `Graphics::createWindow(...) -> OWindow`, `createTexture2D(...) -> OTexture2D`.
A factory returns `O<T>`; anything storing it should keep it as `P<T>` (or pass the
`O<T>` into a `P<T>` conversion).
- **`UP<T>`** = `UniquePtr<T>` — move-only, deletes on scope exit.
- You will rarely `new` explicitly: `P<Foo> p = new Foo();` is the pattern used in
`main.cpp` / tests because `RefPtr` has a raw-pointer constructor. For factories,
return `O<T>`.
- Do **not** introduce `std::shared_ptr`/`std::unique_ptr` for engine objects — use the
`P/O/UP` types.
- **Containers:** use the engine's own in `Containers/` (`Array<T>` = heap `std::vector`-like
with `add`/`resize`/`remove`/`removeAt`/`find`/`clear`; `StaticArray<T,N>`; `Map`, `List`,
`Set`, `Tree`, `Pair`). There is a `MemoryResource` (pool) too. Prefer these over
`std::vector`/`std::map` for engine data (they are what serialization etc. integrate with).
- **Errors / asserts:** `assert()` from `<assert.h>` (see `MinimalEngine.h`). `fmt`
(`fmt::format`) is used for string building (linked via vcpkg); `nlohmann_json` for JSON
(see `Serialization.h`). There is no exception-based error API to follow — match local style.
- **Per-subsystem `CMakeLists.txt`** only calls `target_sources(Engine PRIVATE ... .cpp)` and
`target_sources(Engine PUBLIC FILE_SET HEADERS FILES ... .h)`. When you add a `.cpp`,
add it to the `PRIVATE` list of the **nearest** `CMakeLists.txt`; when you add a public
header, add it to `FILE_SET HEADERS` too (or it won't install/export and other targets
can't find it).
## Workflow & gotchas
- **No CI, no `test` preset.** Nothing runs the test suite for you. Configure a `debug`/
`debug-asan` preset, build, then `cd build && ctest --test-dir . --output-on-failure`.
- **`src/Editor/main.cpp` hard-codes `/home/dynamitos/...` paths** (lines 26–27). The Editor
will not run on any other machine without editing those two lines to your checkout path.
The `if (true)` branch is the live one; the else-branch (cmake `ExportProject.cmake`
export flow) is dead code that only worked with the original author's paths.
- **Coroutines are not in the code.** An earlier design described a coroutine `Job`/`MainJob`
/`Event` system and templated `RenderPass<T>`; none of it is implemented (MSVC memory leaks
+ forcing everything async). The real job system is `ThreadPool`
(`src/Engine/ThreadPool.{h,cpp}`, `getThreadPool()`).
- **Render passes must not touch backend handles.** All GPU work goes through `Gfx::Graphics`.
Adding a pass that produces or consumes a shared `RenderGraphResources` resource requires
wiring **both** the `publishOutputs()` side and the consume-by-name side, and keeping the
`modifyRenderPassMacros` descriptor-set index `#define`s in sync.
- **New `.cpp`/`.h` files must be registered in CMake** — both the nearest `CMakeLists.txt`
(`target_sources ... PRIVATE` for `.cpp`, `FILE_SET HEADERS` for public headers) and, for
tests, the test subdirectory's `CMakeLists.txt`. An unregistered file silently never
compiles.