forked from Dynamitos/Seele
Merge pull request 'docs: add per-subsystem deep-dives + cross-repo orientation (for coding agents)' (#1) from coding-agent/Seele:docs/engine-orientation into master
Reviewed-on: Dynamitos/Seele#1 Reviewed-by: Dynamitos <[email protected]>
This commit is contained in:
commit
499407d366
17 files changed
+1698
No files matched your search
+135
@@ -0,0 +1,135 @@
|
||||
# Seele — Engine Documentation (for coding agents)
|
||||
|
||||
> **Start here if you are a coding agent (or a human new to the repo) and need to
|
||||
> navigate the Seele engine and the MeshShadingDemo test harness.** This `docs/`
|
||||
> tree is the *per-subsystem navigation layer*. It complements — it does **not**
|
||||
> replace — the engine-root [`AGENTS.md`](../AGENTS.md), which is the
|
||||
> map + the hard rules. Read that first; use this tree to drill into a specific
|
||||
> area.
|
||||
|
||||
---
|
||||
|
||||
## 0. What this repository is (30-second orientation)
|
||||
|
||||
- **`Seele`** is a C++ game engine. It lives in this submodule
|
||||
(`external/Seele` inside the parent monorepo). It has a **Vulkan** and **Metal**
|
||||
backend, an ECS (entt-based), a render graph, a Slang-based material/shader
|
||||
system, a Jolt-based physics layer, a full **flexbox UI**, and an **asset
|
||||
pipeline**. ~320 source files under `src/Engine/`.
|
||||
- **`MeshShadingDemo`** is a *test game* built against Seele. It is **not** the
|
||||
product; it is the integration harness. The engine is the product. The demo
|
||||
shows how a real consumer composes a game (scene, systems, materials,
|
||||
render-graph overrides) against the engine.
|
||||
- The **engine↔demo boundary** is a strict ABI: the engine's per-OS
|
||||
`GameInterface` `dlopen`/`LoadLibrary`-loads the demo's shared library and
|
||||
resolves exactly two C symbols (`createInstance` / `destroyInstance`). See
|
||||
[`cross-repo.md`](cross-repo.md) for the full contract.
|
||||
|
||||
**The single best first read is [`../AGENTS.md`](../AGENTS.md)** (engine root):
|
||||
the memory model, the `update`/GPU phase split, the Jolt ground rules, the
|
||||
culling note, and a subsystem map. Everything below is the per-subsystem drill-
|
||||
down it points into.
|
||||
|
||||
---
|
||||
|
||||
## 1. The cross-repo contract (read before touching either repo)
|
||||
|
||||
📄 [`cross-repo.md`](cross-repo.md) — **the orientation doc for working across
|
||||
both repos.** It covers:
|
||||
|
||||
1. The repo relationship (engine = submodule, demo = harness).
|
||||
2. **The engine↔demo ABI** — the two-C-symbol contract (`createInstance` /
|
||||
`destroyInstance`), how the per-OS `GameInterface` loads the demo's shared
|
||||
lib, and the **shader-copy-on-reload** gotcha.
|
||||
3. **The demo-side `ComponentSystem<...>` pattern** (the only pattern you need
|
||||
for per-frame demo logic), with the canonical `FlyCamSystem` example.
|
||||
4. **The CMake contract** — in-tree `add_subdirectory` (what the demo does) vs.
|
||||
the engine's out-of-tree `install(EXPORT)` / `FILE_SET HEADERS` path.
|
||||
5. A **practical "where do I look" task map** and the three invariants that
|
||||
save hours.
|
||||
|
||||
> **Rule of thumb:** engine changes go *in the submodule* (commit inside
|
||||
> `external/Seele`, then re-record the submodule pointer in the parent). The
|
||||
> demo never edits engine code.
|
||||
|
||||
---
|
||||
|
||||
## 2. Per-subsystem deep dives
|
||||
|
||||
Each doc follows the same shape: **key types & where they live** (a per-type
|
||||
table mapping each public type to its defining header), **data flow /
|
||||
lifecycle**, **where to look** (file:line pointers), and **gotchas & sharp
|
||||
edges**. Links below are to the real files.
|
||||
|
||||
### Core engine
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Scene / ECS / Components / Actors** | [scene-ecs](subsystems/scene-ecs-components-actors.md) | The entt registry, `Actor`, `Component` model, how the demo composes a scene in `setupScene`. The foundation everything else builds on. |
|
||||
| **Component Systems & the Update Loop** | [systems](subsystems/systems-update-loop.md) | `System`, `SystemGraph`, `ComponentSystem`, the per-frame tick order, the CPU/GPU phase split. |
|
||||
| **Game Interface & Frame Loop** | [game-interface](subsystems/game-interface.md) | `Game` (abstract), `GameView`, the render/update protocol (`beginUpdate`/`update`/`commitUpdate`/`prepareRender`/`render`), the frame loop. |
|
||||
| **Window & view layer** | [window](subsystems/window.md) | `Window`, `WindowManager`, `View`, `GameView` — the OS window, the render/update protocol, the frame loop wiring. |
|
||||
|
||||
### Graphics (GPU)
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Graphics Abstract Backend** | [graphics-backend](subsystems/graphics-abstract-backend.md) | `Gfx::Graphics` — the backend-agnostic API (buffers, textures, pipelines, descriptors, render passes). The layer you write against. |
|
||||
| **Render Graph & Render Passes** | [render-graph](subsystems/render-graph-and-passes.md) | The auto-invalidated render graph, render passes, dependencies, **meshlet layout**, and the **ray-tracing** paths. |
|
||||
| **GPU Resources** | [graphics-resources](subsystems/graphics-resources.md) | Buffers, textures, shaders, pipelines, descriptor sets in the abstract layer — and how they map to the backends. |
|
||||
| **Vulkan Backend** | [vulkan](subsystems/vulkan-backend.md) | `Vulkan::Graphics` — the concrete Vulkan implementation, its gotchas, and the RT path. |
|
||||
| **Metal Backend** | [metal](subsystems/metal-backend.md) | `Metal::Graphics` — the concrete Metal implementation, its gotchas, and the RT path. |
|
||||
| **Materials & Shader Graphs** | [materials](subsystems/materials-shader-graphs.md) | `ShaderExpression` — the Slang-based material/shader-graph system, parameter binding, and how the demo overrides the render graph. |
|
||||
|
||||
### Simulation & content
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Physics (Jolt)** | [physics](subsystems/physics.md) | The Jolt wrapper, `PhysicsSystem`, `CollisionSystem`, BVH broadphase, witness-based narrowphase. |
|
||||
| **UI (flexbox)** | [ui](subsystems/ui.md) | The full flexbox layout engine (two-phase measure/place), the element tree, widgets, theming/styles, the `UIRender` quad pipeline. A separate render path from the 3D scene. |
|
||||
| **Asset Pipeline** | [assets](subsystems/asset-pipeline.md) | `AssetManager`, loaders, storage — how assets are loaded, cached, and streamed. |
|
||||
|
||||
### Platform & core
|
||||
|
||||
| Area | Doc | What it covers |
|
||||
|---|---|---|
|
||||
| **Platform / OS abstraction** | [platform](subsystems/platform.md) | Per-OS `GameInterface` (Windows/Linux/Mac), dynamic library loading (`dlopen`/`LoadLibrary`/`NSCreateObject`), input enums, and the **shader-copy-on-reload** mechanism. This is where the engine↔demo boundary is physically enforced. |
|
||||
| **Core Utilities** | [core-utils](subsystems/core-utilities.md) | Math, containers, log, time, memory, reflection, **serialization** — the cross-cutting utilities every other subsystem uses. |
|
||||
|
||||
---
|
||||
|
||||
## 3. How to use this tree (agent workflow)
|
||||
|
||||
1. **Orient** — read [`../AGENTS.md`](../AGENTS.md) (rules) + [`cross-repo.md`](cross-repo.md)
|
||||
(the contract). Ten minutes, saves hours.
|
||||
2. **Locate** — use the table above (or `cross-repo.md` §5's task map) to find
|
||||
the subsystem doc for your task.
|
||||
3. **Navigate** — the subsystem doc's **key-types table** tells you *which
|
||||
header* defines each type; **where-to-look** gives file:line pointers into
|
||||
the actual source. Go to the source — this tree is a *map*, not the
|
||||
source of truth for implementation detail.
|
||||
4. **Respect the rules** — the memory model (`DEFINE_REF`/`DECLARE_REF`,
|
||||
`RefPtr`/`OwningPtr`/`UniquePtr`), the CPU/GPU phase split, and the Jolt
|
||||
ground rules from `AGENTS.md` apply everywhere. When a doc and `AGENTS.md`
|
||||
disagree, `AGENTS.md` wins.
|
||||
|
||||
**If a subsystem doc is missing or wrong** (the engine moves fast), update it
|
||||
here — the format is simple and consistent (key types → data flow → where to
|
||||
look → gotchas). Keep `AGENTS.md` for cross-cutting *rules* and this tree for
|
||||
*per-subsystem navigation*.
|
||||
|
||||
---
|
||||
|
||||
## 4. Pointers to the rest of the repo
|
||||
|
||||
- [`../AGENTS.md`](../AGENTS.md) — **the rules + map** (start here).
|
||||
- [`../README.md`](../README.md) — the human-facing engine README (build
|
||||
instructions, features).
|
||||
- [`../OPTIMIZATIONS.md`](../OPTIMIZATIONS.md) — the optimization notes
|
||||
(meshlet/culling strategy).
|
||||
- [`../Culling.md`](../Culling.md) — the culling design note (referenced by
|
||||
the render-graph and physics docs).
|
||||
- [`../CMakeLists.txt`](../CMakeLists.txt) — the engine build (install/export
|
||||
path; see `cross-repo.md` §4.2).
|
||||
- `src/Engine/` — the source tree, ~320 files, ~20 subsystems (the per-subsystem
|
||||
docs above map onto it directory-by-directory).
|
||||
@@ -0,0 +1,348 @@
|
||||
# Seele × MeshShadingDemo — Cross-Repository Orientation
|
||||
|
||||
> **Read this first** if you are an agent working in the *MeshShadingDemo* test
|
||||
> repository and need to reach into the **Seele engine** at `external/Seele`, or
|
||||
> vice-versa. This is the "how does the test game plug into the engine" doc.
|
||||
> For engine-internal navigation (per-subsystem deep dives) see
|
||||
> [`docs/README.md`](README.md) and [`AGENTS.md`](../AGENTS.md).
|
||||
|
||||
The **MeshShadingDemo** repo is *not* a standalone app. It is a **test game /
|
||||
integration harness** built *against* the Seele engine. It exists to exercise the
|
||||
engine (mesh shading, lighting, culling, the render pipeline) with real content.
|
||||
The engine itself lives in the `external/Seele` **git submodule** and is the only
|
||||
place engine code should be modified.
|
||||
|
||||
---
|
||||
|
||||
## 1. Repository relationship (the two repos)
|
||||
|
||||
| | **Seele (the engine)** | **MeshShadingDemo (the test game)** |
|
||||
|---|---|---|
|
||||
| Role | Game engine (C++23, Vulkan/Metal) | Test / integration harness |
|
||||
| Location | `external/Seele/` (git submodule → `Dynamitos/Seele`) | repo root |
|
||||
| Default branch | `master` | `main` |
|
||||
| Build target | `Engine` (SHARED lib) + `Editor`, `Benchmark`, `AssetViewer`, tests | `MeshShadingDemo` (SHARED lib, a **plugin DLL**) |
|
||||
| Where you change | engine code, render passes, materials, components | scene content, demo actors, demo systems, camera rigs |
|
||||
|
||||
**The rule that keeps the two from bleeding together:**
|
||||
|
||||
- To change *engine* behaviour (rendering, components, systems, assets) → edit
|
||||
files under `external/Seele/`. That is a **separate repository**; a commit
|
||||
there must be made *inside the submodule* and then the parent repo must
|
||||
re-record the new submodule pointer.
|
||||
- To change the *demo* (which meshes, lights, camera moves, what the test
|
||||
asserts) → edit files in the demo repo (`src/`, `res/`, `CMakeLists.txt`).
|
||||
These files never touch the engine.
|
||||
|
||||
Both repos are consumed by the same CMake build: the demo's top-level
|
||||
`CMakeLists.txt` does `add_subdirectory(external/Seele)` and links the engine's
|
||||
`Engine` target. There is one build tree, two source trees, two git identities.
|
||||
|
||||
---
|
||||
|
||||
## 2. The plugin contract: how a "game" plugs into the engine
|
||||
|
||||
The engine is backend-agnostic about *games*. A "game" is just a **shared
|
||||
library that exports two C symbols** and provides a `Seele::Game` subclass. The
|
||||
engine (or any host) loads the DLL, calls `createInstance()`, and the engine
|
||||
drives the game. This is the *entire* contract — it is deliberately tiny.
|
||||
|
||||
### 2.1 The engine side (`Seele::Game`)
|
||||
|
||||
`src/Engine/Game.h` (12 lines total — the whole interface):
|
||||
|
||||
```cpp
|
||||
namespace Seele {
|
||||
class Game {
|
||||
public:
|
||||
Game() {}
|
||||
virtual ~Game() {}
|
||||
virtual void setupScene(PScene scene, PSystemGraph graph) = 0; // the only hook
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
That single pure-virtual, `setupScene(PScene, PSystemGraph)`, is the **only**
|
||||
entry point the engine gives a game. The engine hands you:
|
||||
|
||||
- a **`PScene`** — the scene to populate (entities, components, actors), and
|
||||
- a **`PSystemGraph`** — the per-frame system graph to register your update
|
||||
systems into.
|
||||
|
||||
You do *not* own the main loop, the window, the render loop, or the
|
||||
`Graphics` instance. The engine (specifically the `WindowManager` + `GameView`)
|
||||
owns all of that. Your job in `setupScene` is to **declare content and
|
||||
per-frame work**; the engine runs the frame loop and calls your systems.
|
||||
|
||||
> This is why there is no "main" in a Seele game and no `app.run()` call — the
|
||||
> host (the editor, a benchmark harness, or the game's own `main.cpp`) is what
|
||||
> owns `WindowManager` and pumps frames.
|
||||
|
||||
### 2.2 The demo side (what MeshShadingDemo actually ships)
|
||||
|
||||
`src/MeshShadingDemoGame.h` + `.cpp` implement the contract:
|
||||
|
||||
- `class MeshShadingDemoGame : public Game` with the override
|
||||
`setupScene(PScene, PSystemGraph)`.
|
||||
- `extern "C" MESHSHADINGDEMO_API Game* createInstance();` — constructs and
|
||||
returns the game (host calls this to load the plugin).
|
||||
- `extern "C" MESHSHADINGDEMO_API void destroyInstance(Game* game);` — the
|
||||
matching teardown (host calls this to unload it).
|
||||
|
||||
`MESHSHADINGDEMO_API` is the DLL export macro in `src/Define.h`
|
||||
(`__declspec(dllexport)` when building the DLL, `dllimport` otherwise, empty on
|
||||
non-Windows). `Define.h` also does `using namespace Seele;` so demo code can
|
||||
write `Scene`, `Component::Camera`, etc. without the namespace.
|
||||
|
||||
**When you add demo content, the flow is:**
|
||||
|
||||
1. In `setupScene`, create actors via the engine factories
|
||||
(`scene->createActor<...>()` / `O<...Actor>`) — e.g. `OStaticMeshActor`,
|
||||
`ODirectionalLightActor`, `OPointLightActor`, `OFlyCam`, `OPathFollowCam`.
|
||||
2. Attach components (`scene->attachComponent<Component::Mesh>(...)`,
|
||||
`.Transform`, `.Camera`, etc.) to those actors.
|
||||
3. Register any **demo-specific per-frame systems** with
|
||||
`graph->addSystem<OYourSystem>(...)`. See §3.
|
||||
4. Load assets through the engine's `AssetRegistry`
|
||||
(`assetRegistry->findMesh<...>(path)`, `findMaterial`, `findTexture`) — the
|
||||
demo never parses asset files itself; the engine's importers (§ in the
|
||||
asset docs) do that.
|
||||
|
||||
The demo's `MeshShadingDemoGame::setupScene` is the canonical example of all
|
||||
four steps; it is the single best "how a game is composed" reference in the
|
||||
whole monorepo. **Read it before touching demo code.**
|
||||
|
||||
---
|
||||
|
||||
## 3. The demo-side system pattern (per-frame logic lives here)
|
||||
|
||||
The demo is not just a scene — it carries its **own per-frame systems** (camera
|
||||
rigs). These are *demo* `System`s: they live in the demo repo, are registered
|
||||
into the engine's `SystemGraph` from `setupScene`, and operate on **demo
|
||||
components** (`Component::Path`, `Component::PathFollow`, plus the engine's own
|
||||
`Camera`/`Transform`/`KeyboardInput`). This is the "game logic" half of the
|
||||
cross-repo contract.
|
||||
|
||||
### 3.1 The `ComponentSystem<...>` pattern (the only pattern you need)
|
||||
|
||||
The demo's systems all derive from the engine's **`System::ComponentSystem`**
|
||||
(`src/Engine/System/ComponentSystem.h` in the engine). A `ComponentSystem<...>`
|
||||
is a `System` whose `update` is invoked **per entity that carries every one of
|
||||
the template parameter components**. The engine's ECS (entt) does the entity
|
||||
selection for you; you just write the per-entity body.
|
||||
|
||||
**The canonical example** (`src/System/FlyCamSystem.h` in the demo):
|
||||
|
||||
```cpp
|
||||
class FlyCamSystem : public System::ComponentSystem<
|
||||
Component::KeyboardInput, // <- entity must have all of these
|
||||
Component::Camera,
|
||||
Component::Transform,
|
||||
Component::PointLight>
|
||||
{
|
||||
public:
|
||||
FlyCamSystem(PScene scene);
|
||||
virtual ~FlyCamSystem();
|
||||
// one call per matching entity, with the components passed in already:
|
||||
virtual void update(Seele::Component::KeyboardInput& input,
|
||||
Seele::Component::Camera& camera,
|
||||
Seele::Component::Transform& transform,
|
||||
Seele::Component::PointLight& pointLight) override;
|
||||
private:
|
||||
float lastMouseX; // per-system state (NOT per-entity — see gotchas)
|
||||
float lastMouseY;
|
||||
};
|
||||
DEFINE_REF(FlyCamSystem)
|
||||
```
|
||||
|
||||
Key facts about this pattern:
|
||||
|
||||
- **Template params = the entity query.** Add/remove a component in the
|
||||
`ComponentSystem<...>` list and the set of entities your `update` runs on
|
||||
changes. This is how the "I want to run on every fly-cam entity" selection is
|
||||
expressed — there is no manual query writing.
|
||||
- **The `update` signature mirrors the template list, in order.** The engine
|
||||
binds each of your `update`'s parameters to the corresponding component on
|
||||
the matched entity. Get the order or the type wrong and it won't compile.
|
||||
- **`DEFINE_REF(YourSystem)`** is required at the bottom — the demo's systems
|
||||
are `RefPtr`/`OwningPtr`-managed like engine systems.
|
||||
- **Constructor takes a `PScene`** — you get the scene for creating/attaching
|
||||
things; you do *not* own the graph.
|
||||
|
||||
### 3.2 The two demo systems that exist (and the rig they serve)
|
||||
|
||||
The demo ships **two** systems, both camera rigs (`src/System/`):
|
||||
|
||||
| System | Components (the query) | What it does |
|
||||
|---|---|---|
|
||||
| `FlyCamSystem` | `KeyboardInput`, `Camera`, `Transform`, `PointLight` | WASD/mouse fly camera; drives a `PointLight` (the "light follows the cam" test rig). |
|
||||
| `SplineCamSystem` | `Camera`, `Transform`, `Path`, `PathFollow` | moves a `Camera` along a demo `Path` (a control-point spline) via `PathFollow` progress — the cinematic path camera. |
|
||||
|
||||
The **path machinery is demo-side**: `Component::Path` (`src/Component/Path.h`)
|
||||
holds a control-point spline; `Component::PathFollow` holds a progress
|
||||
parameter; `SplineCamSystem` samples the spline and writes the camera
|
||||
`Transform`. The engine has no knowledge of "spline cameras" — that's demo
|
||||
logic built on the engine's generic `Transform`/`Camera` components.
|
||||
|
||||
### 3.3 The demo's actors (the "game objects")
|
||||
|
||||
Demo content actors live in `src/Actor/` (`FlyCam`, `PathFollowCam`). The
|
||||
`FlyCam`/`PathFollowCam` *actors* are thin wrappers that *attach* the relevant
|
||||
components; the actual per-frame behavior is in the systems above. The
|
||||
`setupScene` in `src/MeshShadingDemoGame.cpp` is where actors are created and
|
||||
components attached. **When you add a new camera rig or content type, the
|
||||
pattern is exactly what the two existing ones do:** an actor that attaches
|
||||
components + a `ComponentSystem` that reads them.
|
||||
|
||||
### 3.4 Gotchas (demo systems)
|
||||
|
||||
- **Per-system state vs per-entity state.** A `ComponentSystem` `update` runs
|
||||
*per entity*. Any member field on the system (like `FlyCamSystem::lastMouseX`)
|
||||
is **shared across every matched entity** — it is per-*system*, not
|
||||
per-*entity*. If you need per-entity state, put it in a **component**, not in
|
||||
a system field. This is the most common demo-system bug (stale state leaking
|
||||
between entities that happen to match the same query).
|
||||
- **Do not add GPU work in `update`.** Same rule as the engine: `update` is the
|
||||
CPU tick; anything that touches the render graph / GPU belongs in the
|
||||
engine's render-side systems (or you're in the wrong layer). Demo systems
|
||||
only write transforms and component state.
|
||||
- **`ComponentSystem` order = binding order.** The template list order and the
|
||||
`update` parameter order must line up 1:1. The compiler is your friend here.
|
||||
- **Demo components** like `Path`/`PathFollow` are plain data structs stored
|
||||
*by value* in the entt registry — no `REF` needed. (See
|
||||
[scene-ecs-components-actors.md](subsystems/scene-ecs-components-actors.md)
|
||||
for the component model.)
|
||||
|
||||
---
|
||||
|
||||
## 4. The CMake contract (how the two builds are stitched)
|
||||
|
||||
There are **two ways** to consume the engine, and the demo uses the first:
|
||||
|
||||
### 4.1 In-tree (what the demo actually does)
|
||||
|
||||
The demo's top-level `CMakeLists.txt` (`main/CMakeLists.txt` in the demo repo)
|
||||
does:
|
||||
|
||||
```cmake
|
||||
set(CMAKE_TOOLCHAIN_FILE .../external/Seele/external/vcpkg/scripts/buildsystems/vcpkg.cmake)
|
||||
project(MeshShadingDemo)
|
||||
add_subdirectory(external/Seele) # <- builds the Engine target in-tree
|
||||
|
||||
add_library(MeshShadingDemo SHARED "")
|
||||
target_link_libraries(MeshShadingDemo PUBLIC Engine) # <- link the engine
|
||||
target_compile_definitions(MeshShadingDemo PRIVATE BUILD_DLL) # -> __declspec(dllexport)
|
||||
add_subdirectory(src/)
|
||||
```
|
||||
|
||||
Key facts:
|
||||
|
||||
- **One build tree, two source trees, two git identities.** `add_subdirectory`
|
||||
compiles the *entire engine* as part of the demo's build. There is no separate
|
||||
engine install step in this flow.
|
||||
- **`BUILD_DLL` is the demo's export switch.** It is a *demo* compile definition
|
||||
(see `src/Define.h`): it flips `MESHSHADINGDEMO_API` to `__declspec(dllexport)`,
|
||||
which is what makes `createInstance`/`destroyInstance` visible to the engine's
|
||||
`GameInterface` `GetProcAddress`/`dlsym`. **If a symbol isn't exported, the
|
||||
engine's loader can't see it** — this is the most common "game won't load" bug.
|
||||
- **vcpkg is the single dependency provider** for *both* repos (the toolchain
|
||||
file is pointed at `external/Seele/external/vcpkg`). The engine's `find_package`
|
||||
calls (Vulkan, EnTT, assimp, slang, etc.) all resolve through it. You do not
|
||||
manage dependencies per-repo.
|
||||
- **Outputs are written to the demo's `bin/`** (`CMAKE_BINARY_DIR` is set to
|
||||
`main/bin` in the demo's CMake). The demo's `.so`/`.dll` and the engine's
|
||||
`Engine` shared lib both land there; the engine's `GameInterface` is given a
|
||||
path to that `.so`.
|
||||
|
||||
### 4.2 Out-of-tree (the engine's install/export path)
|
||||
|
||||
The engine *also* ships a proper install/export so it can be consumed as a
|
||||
**package** (not used by this demo, but it's how a real consumer would link
|
||||
against a prebuilt engine). In `external/Seele/CMakeLists.txt`:
|
||||
|
||||
```cmake
|
||||
install(TARGETS AssetViewer Editor Engine crcpp metal
|
||||
EXPORT EngineTargets
|
||||
FILE_SET HEADERS
|
||||
DESTINATION include/Seele)
|
||||
|
||||
export(EXPORT EngineTargets
|
||||
FILE "${CMAKE_BINARY_DIR}/EngineTargets.cmake"
|
||||
NAMESPACE Seele::)
|
||||
|
||||
configure_package_config_file(cmake/EngineConfig.cmake.in "SeeleConfig.cmake" ...)
|
||||
install(EXPORT EngineTargets FILE EngineTargets.cmake ...)
|
||||
```
|
||||
|
||||
- `FILE_SET HEADERS` (CMake ≥ 3.23) is what installs the public headers under
|
||||
`include/Seele` — this is the "clean install" story.
|
||||
- The `Seele::` namespace prefix means an out-of-tree consumer would
|
||||
`find_package(Seele)` and link `Seele::Engine`.
|
||||
- **This demo does NOT use this path.** It builds the engine in-tree. If you
|
||||
ever need a "link against a prebuilt Seele" flow, *this* is the export to
|
||||
consume — but today, in this repo, `add_subdirectory` is the only path.
|
||||
|
||||
### 4.3 Gotchas (CMake)
|
||||
|
||||
- **Two CMake versions matter.** The demo's CMake is `3.7...3.23` (range) and
|
||||
the engine's `FILE_SET HEADERS` needs `≥3.23`. If you downgrade your CMake
|
||||
below 3.23, the *install* path breaks (the in-tree build may still work).
|
||||
- **Don't `find_package(Seele)` in the demo** — it isn't installed; it's
|
||||
`add_subdirectory`'d. Conversely, don't `add_subdirectory` the demo *into* the
|
||||
engine (wrong direction).
|
||||
- **`BUILD_DLL` is demo-side, not engine-side.** The engine never defines it. If
|
||||
you move the demo's `CMakeLists` or restructure, the `target_compile_definitions
|
||||
(BUILD_DLL)` must travel with the demo library target or exports vanish.
|
||||
- **vcpkg toolchain file is a single global switch.** Changing vcpkg manifests or
|
||||
the toolchain affects *both* repos at once.
|
||||
|
||||
---
|
||||
|
||||
## 5. Practical "where do I look" map
|
||||
|
||||
A quick index by task. For full detail, each link is a per-subsystem deep dive.
|
||||
|
||||
| You want to… | Start at |
|
||||
|---|---|
|
||||
| Compose a scene (actors + components) in the demo | `main/src/MeshShadingDemoGame.cpp` (`setupScene`) + [scene-ecs](subsystems/scene-ecs-components-actors.md) |
|
||||
| Add a new demo per-frame system (camera, etc.) | `main/src/System/FlyCamSystem.{h,cpp}` as the template + §3 above |
|
||||
| Add a new component (engine or demo) | [scene-ecs](subsystems/scene-ecs-components-actors.md) (component model) + `src/Engine/Component/` |
|
||||
| Add a new render pass / change a shader | [render-graph](subsystems/render-graph-and-passes.md) + [graphics-backend](subsystems/graphics-abstract-backend.md) + `src/Engine/Rendering/` |
|
||||
| Add/modify a material or shader graph | [materials](subsystems/materials-shader-graphs.md) + `src/Engine/Materials/` (slang) |
|
||||
| Add a mesh / change meshlet layout | [render-graph](subsystems/render-graph-and-passes.md) (meshlet layout + render pipeline) + `src/Engine/Rendering/` + the `Culling.md` note in the engine root |
|
||||
| Work on ray tracing | [render-graph](subsystems/render-graph-and-passes.md) + [graphics-backend](subsystems/graphics-abstract-backend.md) + the RT sections in [vulkan](subsystems/vulkan-backend.md) / [metal](subsystems/metal-backend.md) |
|
||||
| Add UI (HUD, menus, panels) | [ui](subsystems/ui.md) + `src/Engine/UI/` (flexbox, theming, the font INVARAIT) |
|
||||
| Add physics (rigid bodies, collisions) | [physics](subsystems/physics.md) + `AGENTS.md` § "Physics (Jolt)" |
|
||||
| Touch the window / frame loop / input | [window](subsystems/window.md) + `src/Engine/Window/` |
|
||||
| Fix "game won't load" / cross-repo symbol issues | [platform](subsystems/platform.md) + `src/Engine/Platform/<OS>/GameInterface.cpp` + §2 (the two-symbol contract) |
|
||||
| Load/create/serialize assets | [assets](subsystems/asset-pipeline.md) + [core-utils](subsystems/core-utilities.md) (serialization) + `src/Engine/Asset/` |
|
||||
| Vulkan backend specifics | [vulkan](subsystems/vulkan-backend.md) + `src/Engine/Graphics/Vulkan/` |
|
||||
| Metal backend specifics | [metal](subsystems/metal-backend.md) + `src/Engine/Graphics/Metal/` |
|
||||
| Understand the frame (what runs when) | [systems](subsystems/systems-update-loop.md) + [window](subsystems/window.md) (the render/update protocol) |
|
||||
| The engine↔demo ABI (the two C symbols) | §2 above + [game-interface](subsystems/game-interface.md) + [platform](subsystems/platform.md) |
|
||||
|
||||
### 5.1 The three invariants that save hours
|
||||
|
||||
1. **Engine changes go in the submodule.** Edit `external/Seele/...`, commit
|
||||
*inside the submodule*, then re-record the submodule pointer in the parent.
|
||||
Never edit engine files from the demo repo's perspective.
|
||||
2. **`update` is CPU; `prepare`/`render`/`commitUpdate` are GPU.** Put work in
|
||||
the right phase of the [render/update protocol](subsystems/window.md) or you
|
||||
will get tearing, stale resources, or the render graph's auto-invalidation
|
||||
fighting you.
|
||||
3. **The ABI is exactly two C symbols** (`createInstance`/`destroyInstance`).
|
||||
Everything else crosses the boundary as virtual methods on `Game`. Don't add
|
||||
a third export; route new functionality through `Game`'s virtuals.
|
||||
|
||||
### 5.2 The two "read these first" documents
|
||||
|
||||
- **`AGENTS.md`** (engine root) — the map + the rules (memory model, the
|
||||
`update`/GPU split, the Jolt ground rules, the culling note). **It is the
|
||||
single best first read.** This `docs/` tree is the *per-subsystem* layer that
|
||||
it points you into.
|
||||
- **`src/MeshShadingDemoGame.cpp`** (demo) — the one file that shows the whole
|
||||
"how a game is composed" flow against the real engine. Read it before writing
|
||||
demo code.
|
||||
|
||||
**That is the whole orientation.** Every other detail is a per-subsystem doc,
|
||||
linked from the table above.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Asset Pipeline (AssetManager / Loaders / Storage)
|
||||
|
||||
> Asset loading, saving, the registry, the storage backends, the editor-side importers, and the asset viewer.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `AssetManager` | `git grep` in `src/` |
|
||||
| `Asset` | `src/Engine/Asset/Asset.h` |
|
||||
| `AssetLoader<T>` | `git grep` in `src/` |
|
||||
| `AssetLoaderBase` | `git grep` in `src/` |
|
||||
| `AssetLoaderManager` | `git grep` in `src/` |
|
||||
| `AssetSaveData` | `git grep` in `src/` |
|
||||
| `AssetSaveContext` | `git grep` in `src/` |
|
||||
| `AssetView` | `git grep` in `src/` |
|
||||
| `Asset` | `src/Engine/Asset/Asset.h` |
|
||||
| `MeshAsset` | `src/Engine/Asset/MeshAsset.h` |
|
||||
| `MaterialAsset` | `src/Engine/Asset/MaterialAsset.h` |
|
||||
| `MaterialInstanceAsset` | `src/Engine/Asset/MaterialInstanceAsset.h` |
|
||||
| `SkyboxAsset` | `git grep` in `src/` |
|
||||
| `FluidGridAsset` | `git grep` in `src/` |
|
||||
| `TerrainTileAsset` | `git grep` in `src/` |
|
||||
| `WaterTileAsset` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
AssetManager (src/Engine/Asset/AssetManager.h + .cpp, 1.7KB header + 10.3KB impl) is the central asset registry. It maps asset names/paths to Asset objects. API: load(name) (checks cache, if missing calls the appropriate AssetLoader<T> to load from disk), get(name) (cached lookup), unload(name) (removes from cache, calls Asset::unload()), reload(name) (forces re-load from disk). AssetLoaderManager (AssetLoaderManager.h + .cpp, 589B + 472B) is a name->loader map: each AssetLoader<T> registers itself by file extension. AssetLoader<T> (AssetLoader.h, 1.1KB) is a template base with load(context, name) -> T and virtual load implementation. AssetLoaderBase (AssetLoaderBase.h + .cpp, 869B + 3.1KB) is the non-template base that handles the common load/unload lifecycle. Asset (Asset.h, 1.2KB) is the abstract base for all loadable assets: has a name, a path, a reference count, and virtual load/unload. Concrete asset types: MeshAsset (Asset/MeshAsset.h + .cpp, 580B + 5.4KB — loads mesh data from disk into a Gfx::Mesh + VertexData), MaterialAsset (791B + 1.2KB), MaterialInstanceAsset (791B + 1KB), SkyboxAsset (SkyboxAsset.h + .cpp, 813B + 2.3KB — loads cubemap textures), FluidGridAsset (1KB + 1.6KB — loads fluid simulation grid data), TerrainTileAsset (819B + 1.5KB), WaterTileAsset (815B + 1.5KB). AssetSaveData (AssetSaveData.h + .cpp, 798B + 3.1KB) and AssetSaveContext (AssetSaveContext.h + .cpp, 825B + 3.1KB) are the SAVE side: AssetSaveData holds the data to be written, AssetSaveContext tracks the save state. AssetView (AssetView.h + .cpp, 1.2KB + 6.5KB) is a read-only view over an asset (for the editor's asset browser). The AssetLoader<T> template pattern: each concrete loader (e.g. MeshAssetLoader) is registered with the AssetLoaderManager at startup (static initializer or explicit registration call). The loader's load() method reads the file from disk (using std::filesystem or a custom file abstraction) and deserializes it into the asset object. The editor (src/Editor/) has its own set of asset loaders (MaterialLoader, etc.) that are registered in the editor context. The AssetViewer (src/AssetViewer/main.cpp, 7KB) is a standalone CLI tool that uses the AssetManager to browse and inspect assets without running the full engine.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Asset/AssetManager.h + .cpp` | central registry, 10.3KB impl |
|
||||
| `src/Engine/Asset/Asset.h` | abstract asset base |
|
||||
| `src/Engine/Asset/AssetLoader.h` | template base |
|
||||
| `src/Engine/Asset/AssetLoaderBase.h + .cpp` | non-template lifecycle base |
|
||||
| `src/Engine/Asset/AssetLoaderManager.h + .cpp` | loader registry |
|
||||
| `src/Engine/Asset/AssetSaveData.h + .cpp` | save data |
|
||||
| `src/Engine/Asset/AssetSaveContext.h + .cpp` | save context |
|
||||
| `src/Engine/Asset/AssetView.h + .cpp` | read-only asset view, 6.5KB impl |
|
||||
| `src/Engine/Asset/MeshAsset.h + .cpp` | mesh asset, 5.4KB impl |
|
||||
| `src/Engine/Asset/MaterialAsset.h + .cpp` | material asset |
|
||||
| `src/Engine/Asset/SkyboxAsset.h + .cpp` | skybox/cubemap asset, 2.3KB impl |
|
||||
| `src/Engine/Asset/FluidGridAsset.h + .cpp` | fluid grid asset |
|
||||
| `src/Engine/Asset/TerrainTileAsset.h + .cpp` | terrain tile asset |
|
||||
| `src/Engine/Asset/WaterTileAsset.h + .cpp` | water tile asset |
|
||||
| `src/Editor/Asset/MaterialLoader.h + .cpp` | editor material loader, 9.5KB impl |
|
||||
| `src/AssetViewer/main.cpp` | standalone asset browser |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- AssetLoader<T> uses a template + registration pattern. Each concrete loader MUST be explicitly registered with the AssetLoaderManager (or via a static initializer). If you add a new asset type but forget to register its loader, AssetManager::load() will fail with 'no loader for extension' at runtime.
|
||||
- The asset file format is NOT documented in a schema file. Each asset type has its own serialization code in its .cpp file (e.g. MeshAsset.cpp uses Seele::Serialization to read/write). If you need to author assets by hand, you must reverse-engineer the format from the load code.
|
||||
- AssetManager::load() is NOT thread-safe — it uses a single cache map with no locking. All asset loading must happen on the main thread (or be guarded by external synchronization). The editor loads assets on the main thread; the game DLL should do the same.
|
||||
- AssetView (6.5KB impl) is the editor's read-only interface over assets. It is used by the AssetViewer tool and the editor's asset browser. It does NOT mutate the asset — all modifications go through the asset's own API (or the editor's specific loader).
|
||||
- The AssetSaveData/AssetSaveContext pair is the save path. AssetSaveContext tracks the save state (which assets are dirty, which are being saved). The actual file writing is done by each asset's save() method (called through the save context). If an asset's save() throws, the context marks the save as failed and rolls back (check AssetSaveContext.cpp for the rollback logic).
|
||||
- MeshAsset loading (5.4KB impl) reads mesh data from disk and constructs a Gfx::Mesh + VertexData. The VertexData then self-registers into the global VertexData::getList(). If you load a MeshAsset multiple times, you get MULTIPLE VertexData registrations (each load creates a new VertexData). The AssetManager cache prevents re-loading the same asset, but if you unload and reload, the old VertexData remains in the global list (check VertexData.cpp for whether it unregisters on destruction).
|
||||
- The AssetViewer (main.cpp, 7KB) is a standalone executable that links against the engine's AssetManager. It does NOT require a window or GPU — it can run headless. It is useful for validating asset files without running the full engine.
|
||||
- The editor's MaterialLoader (9.5KB impl) is a CUSTOM loader that does NOT go through the standard AssetLoader<T> template — it has its own loading logic. This is because material assets have a complex node graph (ShaderExpression) that requires special deserialization. If you modify the material asset format, you must update BOTH the engine's MaterialAsset.cpp AND the editor's MaterialLoader.cpp.
|
||||
- Asset files are stored on disk in a project-specific directory (configured by the game's GameInterface or the editor's project settings). The AssetManager does NOT hardcode a path — the base path is provided at initialization. If the path is wrong, all loads will fail silently (return nullptr or throw).
|
||||
- There is no asset hot-reload in the engine. To reload an asset, you must call AssetManager::unload() + AssetManager::load(). The editor may have a file-watcher that triggers this automatically (check the editor's source), but the engine itself has no file-watching capability.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,88 @@
|
||||
# Core Utilities (Math, Containers, Log, Time, Memory, Reflection, Serialization)
|
||||
|
||||
> The engine's foundation: math, containers, logging, time, memory, the reflection/serialization system, and dynamic loading.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Log` | `git grep` in `src/` |
|
||||
| `Log/Info` | `git grep` in `src/` |
|
||||
| `Log/Warning` | `git grep` in `src/` |
|
||||
| `Log/Error` | `git grep` in `src/` |
|
||||
| `Log/Debug` | `git grep` in `src/` |
|
||||
| `Seele::Math (Vec2/3/4, Mat3/4, Quat, Transform, BBox, Ray, Plane)` | `git grep` in `src/` |
|
||||
| `Array<T>` | `git grep` in `src/` |
|
||||
| `Stack<T>` | `git grep` in `src/` |
|
||||
| `HashMap` | `git grep` in `src/` |
|
||||
| `HashSet` | `git grep` in `src/` |
|
||||
| `HashMapStringKey` | `git grep` in `src/` |
|
||||
| `HashMapPtrKey` | `git grep` in `src/` |
|
||||
| `StringMap` | `git grep` in `src/` |
|
||||
| `StringHashMap` | `git grep` in `src/` |
|
||||
| `StringHashMapPtrKey` | `git grep` in `src/` |
|
||||
| `PtrHashMap` | `git grep` in `src/` |
|
||||
| `PtrMap` | `git grep` in `src/` |
|
||||
| `StringToPtrHashMap` | `git grep` in `src/` |
|
||||
| `StringToPtrMap` | `git grep` in `src/` |
|
||||
| `Optional<T>` | `git grep` in `src/` |
|
||||
| `Result<T, E>` | `git grep` in `src/` |
|
||||
| `String/ConstString` | `git grep` in `src/` |
|
||||
| `GameTime` | `git grep` in `src/` |
|
||||
| `Time` | `git grep` in `src/` |
|
||||
| `Memory (malloc/free wrappers)` | `git grep` in `src/` |
|
||||
| `Platform (OS abstraction)` | `git grep` in `src/` |
|
||||
| `Reflection (struct member registry)` | `git grep` in `src/` |
|
||||
| `Serialization (Archive/ArchiveBuffer/ArchiveJson)` | `git grep` in `src/` |
|
||||
| `JobSystem (thread pool)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Log (src/Engine/Core/Log.h + Log.cpp, 1.8KB + 1.1KB) provides Log::info/warning/error/debug static methods that format a message with source location (file:line via __FILE__/__LINE__) and write to stdout + a log file (Log.cpp opens a log file in the working directory). There are also macros (LOG_INFO, LOG_WARNING, etc.) that wrap these. Math (src/Engine/Core/Math/) is a SIMD-friendly math library: Vec2/Vec3/Vec4 (float/double/int variants), Mat3/Mat4 (float/double), Quat, Transform (position/rotation/scale), BBox (axis-aligned bounding box with intersection tests), Ray (origin+direction, BBox intersection), Plane (normal+distance, point classification), Sphere. All are header-only inline functions with SIMD intrinsics (SSE/AVX where available). The math library is used pervasively: Transform (Component/Transform.h) uses Math::Mat4 for the world matrix, BBox is used for frustum culling in RenderPass::computePlane, Ray is used for ray queries. Containers (src/Engine/Containers/) wrap std:: containers with engine conventions: Array<T> (dynamic array with growth strategy, 5.6KB), Stack<T> (5.3KB), HashMap (open-addressing, 8.6KB), HashSet (10.7KB), HashMapStringKey/HashMapPtrKey (key-type specializations), StringMap/StringHashMap/StringHashMapPtrKey (string-keyed), PtrHashMap/PtrMap (pointer-keyed), StringToPtrHashMap/StringToPtrMap (string->pointer maps), Optional<T> (2.4KB, std::optional-like), Result<T,E> (2.7KB, tagged union for success/failure). The hash functions in HashMap/HashSet use a FNV-1a or similar non-cryptographic hash. String (src/Engine/Core/String/String.h + .cpp, 6.9KB + 16.9KB) is a custom string class (NOT std::string) with UTF-8 storage, format(), split(), find(), replace(), and interning (ConstString is an interned string reference — used for type names and asset names). ConstString (ConstString.h, 770B) is a non-owning reference to an interned string — it is implicitly convertible from string literals and std::string. GameTime (GameTime.h + .cpp, 812B + 945B) and Time (Time.h + .cpp, 730B + 1.2KB) provide high-resolution timing (std::chrono::high_resolution_clock wrappers). GameTime is the frame timer used by GameView. Memory (Memory.h + .cpp, 1.2KB + 2.8KB) wraps malloc/free/new/delete with allocation tracking (total allocated, peak, allocation count) and optional leak detection. Platform (Platform.h + .cpp, 1.4KB + 1.7KB) is the OS abstraction: file I/O (read/write/delete/mkdir), path manipulation (join, normalize, getExtension), command-line argument parsing, environment variable access, process ID. Reflection (Reflection.h + .cpp, 2.8KB + 3.4KB) provides a struct member registry — each serializable struct registers its members (name, offset, type) at compile time (via a macro or static initializer). This is used by the Serialization system to generically read/write struct fields by name. Serialization (src/Engine/Serialization/Serialization.h + .cpp, 5.1KB + 23.3KB) provides the Archive abstract class (read/write primitives: int/float/string/struct-by-reflection) + ArchiveBuffer (binary buffer archive, 1.3KB header + 13.6KB impl) + ArchiveJson (JSON archive, 2.2KB header + 11.6KB impl). ArchiveJson uses a JSON parser (likely nlohmann/json or a custom one — check the includes). The Archive class uses the Reflection registry to iterate struct members and serialize/deserialize them generically. JobSystem (JobSystem.h + .cpp, 801B + 963B) is a minimal thread pool for parallel work. It is used by the Executor (System/Executor.h) and potentially by the asset loader for parallel loading.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Core/Log.h + .cpp` | logging |
|
||||
| `src/Engine/Core/Math/ (all math types: Vec.h, Mat.h, Quat.h, Transform.h, BBox.h, Ray.h, Plane.h, Sphere.h, etc.)` | |
|
||||
| `src/Engine/Containers/Array.h + .cpp` | |
|
||||
| `src/Engine/Containers/HashMap.h + .cpp` | open-addressing hash map |
|
||||
| `src/Engine/Containers/HashSet.h + .cpp` | |
|
||||
| `src/Engine/Containers/Optional.h + .cpp` | |
|
||||
| `src/Engine/Containers/Result.h + .cpp` | |
|
||||
| `src/Engine/Core/String/String.h + .cpp` | custom string, 16.9KB impl |
|
||||
| `src/Engine/Core/String/ConstString.h` | interned string reference |
|
||||
| `src/Engine/Core/GameTime.h + .cpp` | frame timer |
|
||||
| `src/Engine/Core/Time.h + .cpp` | high-res clock wrapper |
|
||||
| `src/Engine/Core/Memory.h + .cpp` | allocation tracking |
|
||||
| `src/Engine/Core/Platform.h + .cpp` | OS abstraction: file I/O, paths, args |
|
||||
| `src/Engine/Core/Reflection.h + .cpp` | struct member registry |
|
||||
| `src/Engine/Serialization/Serialization.h + .cpp` | Archive base + reflection-driven serialization, 23.3KB impl |
|
||||
| `src/Engine/Serialization/ArchiveBuffer.h + .cpp` | binary archive, 13.6KB impl |
|
||||
| `src/Engine/Serialization/ArchiveJson.h + .cpp` | JSON archive, 11.6KB impl |
|
||||
| `src/Engine/Job/JobSystem.h + .cpp` | thread pool |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The custom String class is NOT std::string — it has a different API (no std::string interop). If you pass a std::string to a function expecting Seele::String, you must construct a String from it (String has a std::string constructor). The reverse (String -> std::string) is via String::c_str() + String::length().
|
||||
- ConstString is an INTERNED string reference — it is cheap to copy (pointer + hash) but the underlying string must outlive the ConstString. ConstStrings are used for type names in the Reflection system and for asset names in the AssetManager. Do NOT create a ConstString from a temporary string literal that will be destroyed.
|
||||
- The Reflection system requires explicit member registration — each serializable struct must call DEFINE_REFLECTION(TypeName) or equivalent macro at file scope. If you add a new field to a struct but forget to add it to the reflection registration, the field will be SILENTLY SKIPPED during serialization (no error, no warning). This is the most common source of data corruption bugs in this engine.
|
||||
- ArchiveJson (JSON serialization) and ArchiveBuffer (binary serialization) are interchangeable — any struct can be serialized to either format. The Archive base class dispatches to the concrete archive at runtime. If you mix the two (read a binary file with ArchiveJson), you will get garbage data with no error (check the type tags in the serialization format).
|
||||
- The Math library is HEADER-ONLY — all functions are inline. There is no separate .cpp file for most math types. If you get linker errors for math functions, check that you included the correct header (e.g. Math/Vec3.h for Vec3, not Math.h).
|
||||
- The Array<T> container has a GROWTH STRATEGY — it does not use std::vector's doubling strategy. The growth factor is configurable (check Array.h). If you resize an Array to a very large size, the growth strategy may cause multiple reallocations. For predictable performance, reserve() in advance.
|
||||
- The HashMap/HashSet use OPEN-ADDRESSING with a specific probe sequence (linear or quadratic — check the header). The load factor is capped (typically 0.7) — if you exceed the cap, the map rehashes. Rehashing is O(n) and can cause frame hitches if it happens during a frame update. Pre-size the map if you know the expected size.
|
||||
- Platform.h provides file I/O — it is the ONLY way to do file I/O in the engine. Do NOT use std::ifstream/std::ofstream directly (the Platform layer may use a different I/O strategy, e.g. memory-mapped files on some platforms). The AssetManager uses Platform for all file access.
|
||||
- JobSystem (thread pool) is minimal (963B impl) — it has a fixed thread count (from GraphicsInitializer or a default) and a simple task queue. It is NOT a work-stealing scheduler. If you submit more work than the pool can handle, the excess is queued and processed in order. There is no priority, no cancellation, no async result (no std::future equivalent).
|
||||
- The Memory tracking (Memory.h) is ON by default in debug builds — it tracks every allocation (total, peak, count) and can report leaks at shutdown. In release builds, the tracking is compiled out (check the #ifdef in Memory.h). If you see performance issues, the memory tracking overhead in debug builds may be significant (each allocation has a tracking call).
|
||||
- GameTime (frame timer) uses std::chrono::high_resolution_clock. On some platforms (Windows), high_resolution_clock has a 1ms granularity by default — the engine may use QueryPerformanceCounter directly for better resolution (check GameTime.cpp). If you see frame timing jitter, the clock resolution may be the cause.
|
||||
- The Log system writes to BOTH stdout and a log file (Log.cpp opens the log file in the current working directory at first log call). The log file is NOT rotated — it grows without bound. For long-running applications, you may need to implement log rotation externally (or modify Log.cpp to add rotation).
|
||||
- The String class has a format() method (printf-style) — use it for log messages. Do NOT use std::format or snprintf directly (the String::format is the engine's convention and may have platform-specific behavior).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,46 @@
|
||||
# Game Interface & Frame Loop (GameView / GameInterface)
|
||||
|
||||
> How the engine hosts a game DLL: the GameInterface contract, the GameView frame loop, window/graphics setup, and the reload path.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `GameInterface` | `src/Engine/Platform/Linux/GameInterface.h` |
|
||||
| `GameView` | `src/Engine/Window/GameView.h` |
|
||||
| `Game` | `src/Engine/Game.h` |
|
||||
| `GameInterface (abstract)` | `git grep` in `src/` |
|
||||
| `Game (abstract game base)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
GameInterface (src/Engine/Interface/GameInterface.h + .cpp, 1.3KB header + 1.2KB impl) is the abstract contract between the engine and the game. It defines the virtual methods that a game DLL must implement: setupScene(PScene, PSystemGraph) (called once when the game is loaded — the game populates the scene with entities/components and may add custom systems to the system graph), updateScene() (called every frame before the built-in systems run — the game can do custom per-frame work), and potentially other hooks (check the full header). Game (src/Engine/Interface/Game.h, 634B) is the abstract game base class (DEFINE_REF(Game) -> PGame) — it is the type that the game DLL exports. GameView (src/Engine/Window/GameView.h + .cpp, 1.7KB header + 5.4KB impl) is the ENGINE-SIDE host that: (1) creates the Gfx::Graphics backend (Vulkan::Graphics or Metal::Graphics — the selection is done by the embedding app, NOT by GameView; GameView receives a PGraphics), (2) creates a Scene, (3) loads the game DLL (via a dynamic library loader — check GameView.cpp for the dlopen/LoadLibrary call), (4) calls game->setupScene(scene, systemGraph) to let the game populate the scene, (5) runs the frame loop: GameView::update() (compute deltaTime, reset VertexData, run systemGraph->run(dt), scene->update(dt), re-create VertexData descriptors, lightEnv->commit()) and GameView::render() (find main camera, call renderGraph.render(cam, transform), call rayTracingGraph.render(cam, transform) if RT enabled). The main entry point is src/Main.cpp (9.4KB) — it parses command-line arguments (window size, graphics backend, project path), creates the Graphics backend, creates a GameView, creates the GameInterface (loads the game DLL), and enters the main loop. The game DLL is a separate compilation unit that links against the engine's exported symbols (the engine exports a C or C++ ABI for the game to link against). The game DLL exports a factory function (check the Interface/ headers for the exact export name) that returns a PGame.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Interface/GameInterface.h + .cpp` | game<->engine contract |
|
||||
| `src/Engine/Interface/Game.h` | abstract game base |
|
||||
| `src/Engine/Window/GameView.h + .cpp` | engine-side host: frame loop, game loading, render wiring |
|
||||
| `src/Main.cpp` | main entry point, 9.4KB — backend selection, GameView creation, main loop |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The graphics backend is NOT selected by GameView or the game DLL — it is selected by the EMBEDDING APP (Main.cpp or a custom launcher). Main.cpp parses a command-line argument to choose between Vulkan and Metal. If you want to change the backend, you modify Main.cpp (or write your own launcher that constructs the appropriate backend and passes it to GameView).
|
||||
- The game DLL is loaded at RUNTIME via dlopen (Linux) or LoadLibrary (Windows). The DLL path is either a command-line argument or a hardcoded path (check Main.cpp / GameView.cpp). If the DLL is missing, the engine will fail at startup with a clear error message. If the DLL exports the wrong symbol name, the dlsym/GetProcAddress will fail — check the exact export name in the Interface/ headers.
|
||||
- GameView::render() finds the main camera by iterating ALL Camera+Transform entities and checking the mainCamera boolean. If the game forgets to set mainCamera=true on its camera, the render will use a default-constructed (identity) camera and you will see a broken view with no error message. This is a common game-side bug.
|
||||
- The system graph is REBUILT on every reloadGame() call — the game's setupScene is called again. If the game's setupScene is not idempotent (e.g. it adds duplicate entities), the scene will accumulate duplicates on reload. The game must clean up its entities before re-populating (or the engine must clear the scene before calling setupScene — check GameView.cpp reloadGame() for whether it clears the scene first).
|
||||
- GameView::update() calls VertexData::getList() to iterate ALL registered VertexData instances and reset their mesh data. This is a GLOBAL side-channel — if you create a VertexData outside the ECS (e.g. in a system that doesn't own it), it will still be in the global list and will be reset every frame. If you need per-vertex-data update logic, hook into the VertexData's own update callback (check VertexData.h for a callback mechanism).
|
||||
- The main loop in Main.cpp is a standard while(running) { update(); render(); } loop. There is no vsync control in the engine — the vsync is controlled by the window system (Vulkan::Window or Metal::Window). If you see frame rate issues, check the swapchain configuration in the backend's Window implementation.
|
||||
- GameInterface is the CONTRACT, not the implementation. The engine does NOT contain a default game — it is a pure interface. The game DLL provides all game logic. If you are building a new game, you must implement the GameInterface contract in a separate DLL.
|
||||
- The scene is created by GameView (not by the game). The game receives the scene as a parameter to setupScene() and populates it. The game CANNOT create a new scene — it must use the one provided by the engine. If the game tries to create its own Scene, it will have a different entt::registry and the engine's render pipeline will not see the game's entities.
|
||||
- The frame timing (updateTime) is computed in GameView::update() using std::chrono. It is the ACTUAL wall-clock delta between frames, not a fixed timestep. If the frame takes longer than expected (e.g. due to Slang compilation), updateTime will be large and the simulation will take a large step. There is no clamping of deltaTime in the engine — the game is responsible for clamping if it wants stable simulation (check the game's system implementations).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,57 @@
|
||||
# Graphics Abstract Backend (Gfx::Graphics)
|
||||
|
||||
> The abstract GPU backend interface that all backends implement, and the factory methods every GPU resource is created through.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Gfx::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Gfx::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Gfx::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Gfx::ShaderCompiler` | `git grep` in `src/` |
|
||||
| `Gfx::GraphicsPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::ComputePipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::Texture2D/3D/Cube` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorLayout` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineLayout` | `git grep` in `src/` |
|
||||
| `Gfx::VertexInput` | `git grep` in `src/` |
|
||||
| `Gfx::OcclusionQuery` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineStatisticsQuery` | `git grep` in `src/` |
|
||||
| `Gfx::TimestampQuery` | `git grep` in `src/` |
|
||||
| `Gfx::BottomLevelAS` | `git grep` in `src/` |
|
||||
| `Gfx::TopLevelAS` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Gfx::Graphics (src/Engine/Graphics/Graphics.h, lines 45-132) is the abstract backend. Backends: Vulkan::Graphics (src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp, 51KB) and Metal::Graphics (src/Engine/Graphics/Metal/Graphics.h + Graphics.mm). All resources are created through virtual factory methods: createWindow, createViewport, createRenderPass(RenderTargetLayout, dependencies, area, name, viewMasks, correlationMasks), beginRenderPass/endRenderPass, waitDeviceIdle, executeCommands(ORenderCommand/OComputeCommand), createTexture2D/2DArray/3D/Cube, createUniformBuffer, createShaderBuffer, createVertexBuffer, createIndexBuffer, createRenderCommand, createComputeCommand, beginShaderCompilation + createVertexShader/FragmentShader/ComputeShader/MeshShader/TaskShader, createGraphicsPipeline(LegacyPipelineCreateInfo or MeshPipelineCreateInfo), createRayTracingPipeline(RayTracingPipelineCreateInfo), createComputePipeline, createSampler, createDescriptorLayout, createPipelineLayout, createVertexInput, createOcclusionQuery, createPipelineStatisticsQuery, createTimestampQuery, beginDebugRegion/endDebugRegion, resolveTexture, copyTexture, copyBuffer, createBottomLevelAccelerationStructure/createTopLevelAccelerationStructure/buildBottomLevelAccelerationStructures, createRayGenShader/AnyHitShader/ClosestHitShader/MissShader/IntersectionShader/CallableShader. Capability gates: supportMeshShading() (meshShadingEnabled flag) and supportRayTracing() (rayTracingEnabled flag). Protected members: QueueFamilyMapping queueMapping, OShaderCompiler shaderCompiler. DEFINE_REF(Graphics) generates PGraphics/UPGraphics/OGraphics typedefs from MinimalEngine.h macros (RefPtr/UniquePtr/OwningPtr). The ShaderCompiler class lives in Shader.h line 178 (not a separate file).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Graphics.h` | abstract interface, 133 lines |
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp` | Vulkan impl, ~52KB |
|
||||
| `src/Engine/Graphics/Metal/Graphics.h + Graphics.mm` | Metal impl |
|
||||
| `src/Engine/Graphics/Shader.h` | ShaderCompiler at line 178; Vertex/Fragment/Compute/Task/MeshShader classes above |
|
||||
| `src/Engine/Graphics/Pipeline.h` | pipeline create structs: LegacyPipelineCreateInfo, MeshPipelineCreateInfo, ComputePipelineCreateInfo |
|
||||
| `src/Engine/Graphics/Initializer.h` | GraphicsInitializer, WindowCreateInfo, ViewportCreateInfo, all resource create-info structs |
|
||||
| `src/Engine/MinimalEngine.h` | RefPtr/UniquePtr/OwningPtr, DEFINE_REF/DECLARE_REF/DECLARE_NAME_REF macros |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ShaderCompiler is declared in Graphics/Shader.h (line 178), NOT in a separate ShaderCompiler.h file.
|
||||
- createGraphics() factory does NOT exist in the codebase — backends are constructed directly (Vulkan::Graphics / Metal::Graphics) by the embedding app.
|
||||
- Graphics.h has #define ENABLE_VALIDATION at line 7 — Vulkan validation layers are active in every build.
|
||||
- OwningPtr (O-prefix) is the owning handle; RefPtr (P-prefix) is a non-owning shared reference. You cannot assign an OwningPtr to a RefPtr (deleted operator=).
|
||||
- Both LegacyPipelineCreateInfo and MeshPipelineCreateInfo exist — mesh shading uses the second. MeshPipelineCreateInfo is only usable when supportMeshShading() is true.
|
||||
- QueueFamilyMapping is a protected member set by the backend; the abstract interface exposes it read-only via getFamilyMapping().
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,87 @@
|
||||
# GPU Resources (Buffers, Textures, Shaders, Pipelines, Descriptors)
|
||||
|
||||
> GPU resource types, VertexData self-registration, the descriptor/parameter layer, and the shader compilation flow.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Gfx::Buffer (abstract)` | `git grep` in `src/` |
|
||||
| `Gfx::ShaderBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::UniformBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::VertexBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::IndexBuffer` | `git grep` in `src/` |
|
||||
| `Gfx::Texture` | `src/Engine/Graphics/Metal/Texture.h` |
|
||||
| `Gfx::Texture2D` | `git grep` in `src/` |
|
||||
| `Gfx::Texture2DArray` | `git grep` in `src/` |
|
||||
| `Gfx::Texture3D` | `git grep` in `src/` |
|
||||
| `Gfx::TextureCube` | `git grep` in `src/` |
|
||||
| `Gfx::TextureView` | `git grep` in `src/` |
|
||||
| `Gfx::Sampler` | `git grep` in `src/` |
|
||||
| `Gfx::Shader (abstract)` | `git grep` in `src/` |
|
||||
| `Gfx::VertexShader` | `git grep` in `src/` |
|
||||
| `Gfx::FragmentShader` | `git grep` in `src/` |
|
||||
| `Gfx::ComputeShader` | `git grep` in `src/` |
|
||||
| `Gfx::TaskShader` | `git grep` in `src/` |
|
||||
| `Gfx::MeshShader` | `git grep` in `src/` |
|
||||
| `Gfx::ShaderCompiler` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorLayout` | `git grep` in `src/` |
|
||||
| `Gfx::DescriptorSet` | `git grep` in `src/` |
|
||||
| `Gfx::PipelineLayout` | `git grep` in `src/` |
|
||||
| `Gfx::GraphicsPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::ComputePipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Gfx::RenderTarget` | `src/Engine/Graphics/RenderTarget.h` |
|
||||
| `Gfx::RenderTargetAttachment` | `git grep` in `src/` |
|
||||
| `Gfx::VertexInput` | `git grep` in `src/` |
|
||||
| `Gfx::RenderCommand` | `git grep` in `src/` |
|
||||
| `Gfx::ComputeCommand` | `git grep` in `src/` |
|
||||
| `Gfx::Meshlet` | `src/Engine/Graphics/Meshlet.h` |
|
||||
| `Gfx::Mesh` | `src/Engine/Component/Mesh.h` |
|
||||
| `VertexData` | `src/Engine/Graphics/VertexData.h` |
|
||||
| `StaticMeshVertexData` | `src/Engine/Graphics/StaticMeshVertexData.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
All GPU resources are created through Gfx::Graphics factory methods (see Gfx Abstract Backend). Resource classes are thin wrappers around backend handles: Buffer.h (abstract base, 3.7KB) -> ShaderBuffer/UniformBuffer/VertexBuffer/IndexBuffer (each with a createInfo struct in Initializer.h). Texture.h (7KB) defines Texture base + Texture2D/2DArray/3D/Cube + TextureView + Sampler. Each has a TextureCreateInfo / SamplerCreateInfo in Initializer.h. Shader.h (5.9KB) defines Shader base (with ShaderStage enum) + VertexShader/FragmentShader/ComputeShader/TaskShader/MeshShader + ShaderCompiler (line 178). Shader compilation is two-phase: Graphics::beginShaderCompilation(ShaderCompilationInfo) then createXxxShader(ShaderCreateInfo) — the ShaderCompiler (held as OShaderCompiler member of Graphics) does the actual Slang->SPIR-V/Metal translation (see slang-compile.h/.cpp, 9KB). Descriptor.h (4.4KB) defines DescriptorLayout (with DescriptorBinding struct: binding index, stage flags, resource type), DescriptorSet (binds resources to a layout), PipelineLayout (composes descriptor layouts + push constant ranges). RenderTarget.h (4.7KB) defines RenderTarget (wraps Gfx::ORenderPass + framebuffers), RenderTargetAttachment (texture + load/store op + initial layout + final layout), SubPassDependency. Pipeline.h (904B) defines LegacyPipelineCreateInfo (vertex/fragment shader stages, vertex input state, render pass, multisample state, depth/stencil state, blend state, rasterization state) and MeshPipelineCreateInfo (task/mesh/fragment shaders, vertex output state, same fixed-function state). ComputePipelineCreateInfo and RayTracingPipelineCreateInfo are also here. Meshlet.h (442B) + Meshlet.cpp (6.2KB) define the meshlet data structure (submesh with bounding sphere, transform, index range) used by the GPU culling pipeline. Mesh.h (895B) + Mesh.cpp (1.5KB) define the GPU mesh asset (vertex buffer + index buffer + meshlets). VertexData (6.5KB header + 27.5KB impl) is the CPU-side mesh data object that owns the source vertex/index arrays, builds meshlets (Meshlet.cpp), and uploads to GPU (createDescriptors()). StaticMeshVertexData (2.3KB header + 7.9KB impl) is the concrete implementation for static meshes. VertexData has a STATIC global registry (getList()) that GameView::update() iterates. Slang shaders are compiled by slang-compile.cpp (9KB) which invokes the Slang compiler frontend and produces SPIR-V (Vulkan) or Metal SL (Metal). The ShaderCompiler class in Shader.h orchestrates this.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Buffer.h + .cpp` | abstract buffer base + create-info structs |
|
||||
| `src/Engine/Graphics/Texture.h + .cpp` | texture hierarchy, 7KB header |
|
||||
| `src/Engine/Graphics/Shader.h` | Shader base + all shader types + ShaderCompiler at line 178 |
|
||||
| `src/Engine/Graphics/Shader.cpp` | 7.3KB — shader compilation orchestration |
|
||||
| `src/Engine/Graphics/slang-compile.h + .cpp` | Slang frontend invocation, 9KB |
|
||||
| `src/Engine/Graphics/Descriptor.h + .cpp` | descriptor layout/set/pipeline layout |
|
||||
| `src/Engine/Graphics/Pipeline.h + .cpp` | pipeline create-info structs |
|
||||
| `src/Engine/Graphics/RenderTarget.h + .cpp` | render target + attachments + subpass dependencies |
|
||||
| `src/Engine/Graphics/Command.h + .cpp` | RenderCommand/ComputeCommand — command buffer wrappers |
|
||||
| `src/Engine/Graphics/Meshlet.h + .cpp` | meshlet data structure for GPU culling |
|
||||
| `src/Engine/Graphics/Mesh.h + .cpp` | GPU mesh asset |
|
||||
| `src/Engine/Graphics/VertexData.h + .cpp` | CPU mesh data, meshlet builder, GPU upload — 27.5KB impl |
|
||||
| `src/Engine/Graphics/StaticMeshVertexData.h + .cpp` | static mesh implementation |
|
||||
| `src/Engine/Graphics/Initializer.h` | ALL create-info structs: GraphicsInitializer, WindowCreateInfo, ViewportCreateInfo, TextureCreateInfo, BufferCreateInfo, ShaderCreateInfo, PipelineCreateInfo variants, SamplerCreateInfo, etc. — 8.5KB |
|
||||
| `src/Engine/Graphics/Enums.h` | 81KB — all Vulkan/Metal enums, flags, and mapping tables |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- VertexData is NOT an entt component — it is a standalone object that self-registers into a static global list. GameView::update() calls VertexData::getList() to iterate all registered instances. If you create a VertexData and never add it to a scene entity, it still appears in the global list.
|
||||
- StaticMeshVertexData is the only concrete VertexData implementation in the codebase. There is no 'dynamic mesh' or 'animated mesh' VertexData variant.
|
||||
- The Slang compiler is invoked at RUNTIME via slang-compile.cpp — shaders are NOT pre-compiled at build time. This means first-frame startup time includes Slang compilation. The PipelineCache (Vulkan/PipelineCache.cpp, 36.8KB / Metal/PipelineCache.mm, 12.8KB) caches compiled pipeline binaries to disk to avoid re-compilation on subsequent launches.
|
||||
- DescriptorSet and DescriptorLayout are GPU resources — they are created via Graphics::createDescriptorLayout / the backend. You cannot create them directly; you must go through the Graphics factory.
|
||||
- The MeshPipelineCreateInfo (for mesh shading) is a SEPARATE struct from LegacyPipelineCreateInfo. Graphics::createGraphicsPipeline has two overloads — one takes each. Passing the wrong one is a compile error (no implicit conversion).
|
||||
- ShaderCompiler is a member of Graphics (OShaderCompiler shaderCompiler) and is accessed via Graphics::getShaderCompiler(). It is NOT a standalone service — it dies when the Graphics instance is destroyed.
|
||||
- RenderTargetAttachment holds a Gfx::PTexture (the actual texture) + load/store ops + initial/final layouts. The RenderTarget class wraps the GPU render pass + framebuffers. createRenderPass on Graphics takes a RenderTargetLayout (array of attachments) + SubPassDependency array + render area + optional viewMasks/correlationMasks (for multi-view/SPIRV workarounds).
|
||||
- Buffer.h defines the abstract Buffer base with a BufferUsageFlags enum. ShaderBuffer is for generic GPU-usable buffers (uniform/vertex/index data). UniformBuffer is specifically for uniform buffers (has a dedicated createUniformBuffer factory). VertexBuffer and IndexBuffer are for vertex/index data (have dedicated factories).
|
||||
- The 81KB Enums.h file contains ALL Vulkan enums + Metal enum mappings. It is auto-generated or hand-maintained. Modifying it is fragile.
|
||||
- PipelineCache (Vulkan) serializes VkPipelineCacheData to disk. Metal's PipelineCache.mm uses MTLBinaryArchive. Both are keyed by a hash of the pipeline create-info + shader code.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,48 @@
|
||||
# Materials & Shader Graphs (ShaderExpression)
|
||||
|
||||
> The node-graph material system that emits Slang at runtime: Material, MaterialInstance, ShaderExpression, and the shader compiler entry.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Material` | `src/Engine/Material/Material.h` |
|
||||
| `MaterialInstance` | `src/Engine/Material/MaterialInstance.h` |
|
||||
| `ShaderExpression` | `src/Engine/Material/ShaderExpression.h` |
|
||||
| `MaterialAsset` | `src/Engine/Asset/MaterialAsset.h` |
|
||||
| `MaterialInstanceAsset` | `src/Engine/Asset/MaterialInstanceAsset.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Material (src/Engine/Material/Material.h + Material.cpp, 2.4KB header + 7.7KB impl) is the runtime material object (DEFINE_REF(Material) -> PMaterial). It owns a ShaderExpression (the compiled shader graph) + a Map of texture parameter bindings + scalar/vec/matrix parameter values. Material::update() (or equivalent) re-evaluates the ShaderExpression when parameters change and rebuilds the Slang source string. MaterialInstance (MaterialInstance.h + .cpp, 1.5KB + 2.6KB) is a per-entity or per-asset material variant that references a base Material (PMaterial) and overrides specific parameters (texture swaps, scalar overrides). MaterialInstanceAsset (Asset/MaterialInstanceAsset.h + .cpp, 791B + 1KB) is the loadable asset wrapper. MaterialAsset (Asset/MaterialAsset.h + .cpp, 805B + 1.2KB) is the loadable asset for the base material — it loads the material definition from disk (JSON or binary) and constructs the Material + ShaderExpression. ShaderExpression (src/Engine/Material/ShaderExpression.h + .cpp, 12.6KB header + 14KB impl) is the node-graph representation of a material shader: it is a directed acyclic graph of shader nodes (math ops, texture samples, parameter reads, branching, loops) that is compiled to Slang source code. The ShaderExpression::compile() (or equivalent) walks the node graph and emits Slang source, which is then handed to the ShaderCompiler (via Graphics::beginShaderCompilation) for GPU compilation. The node types are defined in ShaderExpression.h (12.6KB — large header with all node structs). The material system is the HIGHEST-LEVEL abstraction in the engine: game code creates MaterialAsset (loaded from disk) -> Material (runtime) -> MaterialInstance (per-entity override) -> ShaderExpression (node graph) -> Slang source -> ShaderCompiler -> GPU shader. The AssetViewer tool (src/AssetViewer/main.cpp, 7KB) is a standalone tool that can browse/inspect assets including materials.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Material/Material.h + Material.cpp` | runtime material, 7.7KB impl |
|
||||
| `src/Engine/Material/MaterialInstance.h + .cpp` | per-entity material override |
|
||||
| `src/Engine/Material/ShaderExpression.h + .cpp` | node graph -> Slang source, 12.6KB + 14KB |
|
||||
| `src/Engine/Asset/MaterialAsset.h + .cpp` | loadable material asset |
|
||||
| `src/Engine/Asset/MaterialInstanceAsset.h + .cpp` | loadable material instance asset |
|
||||
| `src/Editor/Asset/MaterialLoader.h + .cpp` | editor-side material loader, 9.5KB impl |
|
||||
| `src/AssetViewer/main.cpp` | standalone asset browser |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ShaderExpression is the most complex single file in the material system (12.6KB header + 14KB impl). It defines ALL shader node types as C++ structs in the header. The node graph is a DAG — there is no cycle detection at compile time (a malformed graph can cause infinite recursion in the Slang emitter).
|
||||
- The material system compiles Slang at RUNTIME — every material change triggers a full Slang compilation cycle. For a project with many materials, this can cause significant stutter on first use of each material. The PipelineCache mitigates this by caching compiled pipeline binaries, but the Slang compilation itself is not cached (only the GPU pipeline binaries are).
|
||||
- MaterialInstance overrides are PARAMETER-LEVEL only — you cannot override the shader graph topology at the instance level. To use a different shader graph, you need a different Material (and therefore a different MaterialAsset).
|
||||
- The material loader in the Editor (MaterialLoader.cpp, 9.5KB) reads material definitions from a JSON or binary format on disk. The format is NOT documented in a schema file in the repository — you must reverse-engineer it from MaterialLoader.cpp or the AssetViewer.
|
||||
- MaterialAsset and MaterialInstanceAsset are separate asset types. A MaterialInstanceAsset references a MaterialAsset by name/ID. If the referenced MaterialAsset is missing or corrupted, the MaterialInstanceAsset will fail to load (check the error handling in MaterialInstanceAsset.cpp).
|
||||
- The Slang compiler (slang-compile.cpp) is a standalone C++ file that links against the Slang compiler library (libslang). The Slang library is an external dependency (not in the Seele source tree). It must be present at build time. The slang-compile.cpp file (9KB) wraps the Slang C API to compile a Slang source string into SPIR-V (Vulkan target) or MetalSL (Metal target).
|
||||
- Material::update() is called by the game code (or the MeshUpdater system) when material parameters change. If you modify a material parameter at runtime without calling update(), the GPU shader will not see the change. The ShaderExpression must be re-evaluated and the Slang re-compiled (or the parameter must be uploaded as a runtime uniform without recompilation — check Material.cpp for which approach is used).
|
||||
- There is NO 'material shader cache' at the Slang level. The PipelineCache caches GPU pipeline binaries (VkPipeline / MTLRenderPipelineState), but if the Slang source changes (because a parameter was added/removed from the graph), the cache key changes and a full recompile occurs. Changing parameter VALUES (not the graph topology) should not trigger a recompile — check Material.cpp to confirm the parameter upload path bypasses Slang compilation.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,65 @@
|
||||
# Metal Backend (Metal::Graphics)
|
||||
|
||||
> The Metal implementation: device setup, resource creation, and the feature set it lacks versus Vulkan.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Metal::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Metal::Window` | `src/Engine/Graphics/Metal/Window.h` |
|
||||
| `Metal::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Metal::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Metal::Buffer (all types)` | `git grep` in `src/` |
|
||||
| `Metal::Texture (all types)` | `git grep` in `src/` |
|
||||
| `Metal::Shader (all stages)` | `git grep` in `src/` |
|
||||
| `Metal::DescriptorLayout/DescriptorSet/PipelineLayout` | `git grep` in `src/` |
|
||||
| `Metal::GraphicsPipeline/ComputePipeline` | `git grep` in `src/` |
|
||||
| `Metal::Command (RenderCommand/ComputeCommand)` | `git grep` in `src/` |
|
||||
| `Metal::Query (Occlusion/Statistics/Timestamp)` | `git grep` in `src/` |
|
||||
| `Metal::PipelineCache` | `src/Engine/Graphics/Metal/PipelineCache.h` |
|
||||
| `Metal::Resources` | `src/Engine/Graphics/Metal/Resources.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Metal::Graphics (src/Engine/Graphics/Metal/Graphics.h + Graphics.mm, 5.8KB header + 8.3KB impl) implements Gfx::Graphics using the Metal.framework (Objective-C++). init(GraphicsInitializer) creates an MTLDevice (MTLCreateSystemDefaultDevice or from a specific identifier), an MTLCommandQueue (banded width from GraphicsInitializer), and a Metal::PipelineCache (MTLBinaryArchive-based). There is NO surface/swapchain management in Graphics.mm — that is in Window.mm (7.7KB) which creates an NSWindow (Cocoa) + CAMetalLayer + MTLView, manages the drawable pool, and handles the frame loop (drawable acquisition, command buffer commit, present). The Metal backend does NOT support ray tracing (rayTracingEnabled is always false — Metal RT is not implemented). It also does NOT support mesh shading (meshShadingEnabled is always false). All resource types mirror the Gfx::Graphics interface: Buffer.mm (8.9KB) implements MTLBuffer wrappers for all buffer types (shader/uniform/vertex/index) with MTLResourceStorageModeShared by default. Texture.mm (14.6KB) implements all MTLTexture types (2D/2DArray/3D/cube) with mipmap generation (blit encoder generateMipmaps), MTLTextureView, MTSamplerState. Shader.mm (1.9KB) creates MTLFunction objects from compiled MetalSL (the Slang compiler outputs MetalSL for the Metal target — see slang-compile.cpp target detection). Command.mm (16.5KB) implements MTLCommandBuffer + MTLRenderCommandEncoder + MTLComputeCommandEncoder wrappers: RenderCommand begins/ends render encoders, draws primitives (drawPrimitives, drawIndexedPrimitives), blits, resolves; ComputeCommand dispatches threadgroups (dispatchThreadgroups). Descriptor.mm (8.8KB) implements MTLBuffer/MTLTexture/MTLSamplerState binding into an MTLRenderPipelineState/MTLComputePipelineState (Metal has no descriptor sets — bindings are direct function arguments via the pipeline state's argument buffer, implemented here as an argument buffer + per-frame update). Pipeline.mm (906B) creates MTLRenderPipelineState (from MTLRenderPipelineDescriptor) and MTLComputePipelineState (from MTLComputePipelineDescriptor). Query.mm (2KB) implements MTLCommandBuffer counters (GPU timestamp via MTLCommandBuffer.GPUStartTime/GPUEndTime, occlusion via MTLResourceID + draw dispatch count). PipelineCache.mm (12.8KB) uses MTLBinaryArchive to cache compiled pipeline states to disk. Resources.mm (2KB) is a thin wrapper for shared Metal resource management. The Metal backend uses Objective-C++ (.mm files) throughout — all Metal API calls are Objective-C method invocations. The C++-side headers (Graphics.h, Buffer.h, Texture.h, etc.) define the C++ interface that matches Gfx::Graphics, and the .mm files implement them.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Metal/Graphics.h` | 5.8KB — Metal backend interface |
|
||||
| `src/Engine/Graphics/Metal/Graphics.mm` | 8.3KB — MTLDevice + MTLCommandQueue creation, factory methods |
|
||||
| `src/Engine/Graphics/Metal/Window.h + .mm` | Cocoa NSWindow + CAMetalLayer + MTLView, 7.7KB impl |
|
||||
| `src/Engine/Graphics/Metal/Command.h + .mm` | MTLCommandBuffer + render/compute encoders, 16.5KB impl |
|
||||
| `src/Engine/Graphics/Metal/Texture.h + .mm` | all MTLTexture types, 14.6KB impl |
|
||||
| `src/Engine/Graphics/Metal/Buffer.h + .mm` | MTLBuffer wrappers, 8.9KB impl |
|
||||
| `src/Engine/Graphics/Metal/Descriptor.h + .mm` | argument buffers for Metal pipeline binding, 8.8KB impl |
|
||||
| `src/Engine/Graphics/Metal/Pipeline.h + .mm` | MTLRenderPipelineState + MTLComputePipelineState |
|
||||
| `src/Engine/Graphics/Metal/Query.h + .mm` | GPU timestamps + occlusion counters |
|
||||
| `src/Engine/Graphics/Metal/PipelineCache.h + .mm` | MTLBinaryArchive caching, 12.8KB impl |
|
||||
| `src/Engine/Graphics/Metal/Shader.h + .mm` | MTLFunction from MetalSL |
|
||||
| `src/Engine/Graphics/Metal/Resources.h + .mm` | shared resource management |
|
||||
| `src/Engine/Graphics/Metal/Enums.h + .mm` | Metal-specific enum mappings, 32KB impl |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The Metal backend does NOT support ray tracing or mesh shading — both capability flags are hardcoded false. RayTracingPass and mesh-shading pipelines will never be used on Metal. The engine's RT path is Vulkan-only.
|
||||
- Metal has no descriptor sets or pipeline layouts in the hardware sense. Metal::Descriptor.mm implements the Gfx::DescriptorLayout/DescriptorSet interface using MTLBuffer argument buffers — the 'descriptor set' is an MTLBuffer that holds raw GPU-visible data, and the pipeline state's MTLFunction constant binding references it. This is a software abstraction over Metal's argument buffer mechanism.
|
||||
- All Metal source files are .mm (Objective-C++). You need Xcode command-line tools + the Metal.framework to build the Metal backend. The CMakeLists.txt in Metal/ configures the .mm files and links against Metal.framework + Foundation.framework.
|
||||
- The MTLDevice is created once at init() and is shared by all resources. There is no per-window device — a single MTLDevice serves all windows in the process. If the device is lost (e.g. GPU reset), the entire engine must be re-initialized.
|
||||
- MTLCommandQueue is created at init() with a banded width (from GraphicsInitializer). The command queue is long-lived and shared by all render/compute commands. Command buffers are created per-frame (or per-command) and destroyed after commit + waitCompleted. There is no command buffer pool — each MTLCommandBuffer is created fresh.
|
||||
- The Window.mm file creates an NSWindow (Cocoa) on macOS. On Linux the Metal backend is NOT available (no Metal.framework on Linux). The Metal backend is macOS-only. Linux uses the Vulkan backend. Windows can use either (the build system selects based on CMake options).
|
||||
- Mipmap generation on Metal uses MTLBlitCommandEncoder.generateMipmapsForTexture. The texture must have MTLResourceUsageBlit | MTLResourceUsageShaderRead enabled. The initial texture usage in Texture.mm is set based on the usage flags in TextureCreateInfo — if mipmap generation is requested but the usage flags are wrong, the blit will fail silently.
|
||||
- The Metal backend's command encoder lifetime is tied to the MTLCommandBuffer. All render/compute encoders must be ended before the command buffer is committed. The Command.mm implementation tracks encoder lifetime and asserts if you try to commit with an open encoder.
|
||||
- MTLBinaryArchive (PipelineCache.mm) caches compiled MTLRenderPipelineState and MTLComputePipelineState objects. The cache is keyed by a hash of the pipeline descriptor + shader function name. If the Metal driver changes (macOS update), the cache is invalidated automatically by the system (MTLBinaryArchive handles this).
|
||||
- The Metal backend's Window.mm uses MTLView (a NSView subclass that integrates Metal rendering with Cocoa). The frame callback is driven by MTLView's updateDrawable callback (called by the system when the window needs a new frame). There is no manual frame loop — the system drives rendering at the display refresh rate.
|
||||
- Metal's GPU timestamps (Query.mm) use MTLCommandBuffer.GPUStartTime/GPUEndTime (mach_time_t). Converting to nanoseconds requires converting the mach_time base (mach_timebase_info). The TimestampQuery implementation in Query.mm does this conversion. Occlusion queries use MTLCommandBuffer.dispatchThreadgroupCounts + a counter buffer (there is no hardware occlusion query on Metal).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,120 @@
|
||||
# Physics (Jolt Physics integration, collision, BVH broadphase)
|
||||
|
||||
> **Scope:** `src/Engine/Physics/` — the engine's rigid-body physics. The heavy lifting is done by
|
||||
> **Jolt Physics** (the external library in `external/JoltPhysics`, linked in `src/Engine/CMakeLists.txt`);
|
||||
> Seele provides a **thin ECS/Scene wrapper** on top: `PhysicsSystem`, `CollisionSystem`, and a
|
||||
> `BVH` broadphase. You almost never touch Jolt directly — you add components and let the systems
|
||||
> do the rest.
|
||||
|
||||
**Read `AGENTS.md` first** — it has a dedicated "Physics (Jolt)" section with the ground rules
|
||||
(this doc complements it with navigation). Jolt is a **third-party black box**: you configure it,
|
||||
you don't modify it, and you don't assume its internals.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `PhysicsSystem` | `src/Engine/Physics/PhysicsSystem.h` (impl `PhysicsSystem.cpp`, ~18 KB — the main integration) |
|
||||
| `PhysicsSystem::Body` | `src/Engine/Physics/PhysicsSystem.h:18` — Seele's mirror of a Jolt rigid body |
|
||||
| `PhysicsSystem::Contact` | `src/Engine/Physics/PhysicsSystem.h` — a collision contact |
|
||||
| `CollisionSystem` | `src/Engine/Physics/CollisionSystem.h` (impl `CollisionSystem.cpp`) |
|
||||
| `CollisionSystem::Witness` | `src/Engine/Physics/CollisionSystem.h:21` — witness-point broadphase state |
|
||||
| `BVH` | `src/Engine/Physics/BVH.h` (impl `BVH.cpp`) — the broadphase spatial structure |
|
||||
| `Component::RigidBody`, `Component::Collider`, `Component::ShapeBase`, `Box/Mesh/Sphere/Plane` | `src/Engine/Component/` (see [scene-ecs-components-actors.md](scene-ecs-components-actors.md)) |
|
||||
|
||||
`PhysicsSystem` is **embedded in `Scene`** (it is a member, not a `System` in the `SystemGraph`) —
|
||||
it is *not* a node you add to the system graph. It is driven by the scene's update tick. The
|
||||
`CollisionSystem` likewise operates on the `entt::registry`. This is a key difference from the
|
||||
"everything is a `System`" pattern — physics is *scene-owned*, not *graph-owned*.
|
||||
|
||||
## The data flow (how a body actually moves)
|
||||
|
||||
```
|
||||
Component::RigidBody + Component::Collider + Component::Transform (on an Actor's entity)
|
||||
│ (Scene collects these into PhysicsSystem bodies)
|
||||
▼
|
||||
PhysicsSystem::update(deltaTime)
|
||||
├─ readRigidBodies() # gather current Component state → Array<Body>
|
||||
├─ serializeArray(bodies, x) # pack Body[] → float[] (the Jolt API boundary)
|
||||
├─ [Jolt step] # Jolt integrates the float[] (forces, velocities, collisions)
|
||||
├─ deserializeArray(...) # unpack Jolt's result back into Body[]
|
||||
└─ write results back to Component::Transform / RigidBody (positions, velocities)
|
||||
▼
|
||||
CollisionSystem::detectCollisions() # broadphase (BVH) + narrowphase (witness points)
|
||||
└─ → Array<Collision> / Contacts (consumed by gameplay / events)
|
||||
```
|
||||
|
||||
The **`serializeArray`/`deserializeArray` pair is the Jolt API boundary** (`PhysicsSystem.h:83-87`).
|
||||
Jolt's public API works on `float*` state vectors, not C++ objects. Seele's `Body` struct is a
|
||||
*C++-side mirror* of what Jolt stores; every step it's serialized across into Jolt's float world and
|
||||
back. **If you add a new physical property, you must add it to all four**: the `Body` field,
|
||||
`serializeRB`, `deserializeRB`, and the component that feeds it — miss one and the value silently
|
||||
doesn't round-trip (Jolt integrates a stale copy).
|
||||
|
||||
## The `Body` struct (what Seele tracks per body)
|
||||
|
||||
`PhysicsSystem::Body` (`PhysicsSystem.h:18`) holds the full rigid-body state, with Jolt-aligned
|
||||
naming (so the serialization is a straight field map):
|
||||
|
||||
- `id` (the `entt::entity`), `centerOfMass`, `iBody`/`iBodyInv` (body-space inverse inertia, from
|
||||
`collider.physicsMesh.bodyInertia`), `scale`
|
||||
- state: `x` (position), `q` (orientation quat), `R` (orientation matrix), `v` (linear vel),
|
||||
`omega` (angular vel), `P` (linear momentum), `L` (angular momentum), `iInv` (world-space inverse
|
||||
inertia, recomputed in the ctor as `R * iBodyInv * Rᵀ`)
|
||||
- `force` / `torque` (inputs from `Component::RigidBody`)
|
||||
- `matrix` (the final world transform, `updateMatrix()` composes scale→rotation→translation)
|
||||
- `ptVelocity(p)` — a rigid-body point velocity helper (`v + ω × (p - x + com)`)
|
||||
|
||||
There are **two ctors**: one that takes a `RigidBody` (dynamic, momentum-carrying) and one that
|
||||
doesn't (kinematic/static, zero momentum). Both normalize the quaternion and recompute `iInv`.
|
||||
|
||||
## CollisionSystem (broadphase + narrowphase)
|
||||
|
||||
`CollisionSystem` (`CollisionSystem.h`) produces `Array<Collision>` each tick:
|
||||
|
||||
- **Broadphase** via `BVH` — a bounding-volume hierarchy over collider AABBs. `CollisionSystem`
|
||||
builds/maintains it and queries candidate pairs (broadphase = "which pairs *might* collide").
|
||||
- **Narrowphase** via **witness points** (`CollisionSystem::Witness`, `createWitness`/
|
||||
`updateWitness`/`witnessValid`): a classic GJK-style witness-point test that decides, for a
|
||||
*candidate* pair, whether the shapes actually intersect. This is the "do these two shapes
|
||||
actually collide" step.
|
||||
- `checkCollision(pair)` / `detectCollisions(&out)` are the entry points.
|
||||
|
||||
**Gotcha:** the broadphase is a *filter*, not a guarantee. A pair passing the broadphase still
|
||||
needs the narrowphase witness test. Don't treat "broadphase said they might collide" as
|
||||
"they collided."
|
||||
|
||||
## The BVH
|
||||
|
||||
`BVH` (`Physics/BVH.h` + `BVH.cpp`, ~10 KB) is a generic bounding-volume hierarchy. It's the
|
||||
spatial index the `CollisionSystem` uses for the broadphase. It's a reusable structure — if you
|
||||
need broadphase for something else (culling queries, picking), this is the building block. (For
|
||||
**rendering** culling, see the mesh culling in [meshes-and-meshlets.md](render-graph-and-passes.md) —
|
||||
that's a *different* BVH/`MeshCullingSystem` in `src/Engine/Rendering/`, do not confuse the two.)
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Physics is scene-owned, not graph-owned.** `PhysicsSystem` is a `Scene` member; you do *not*
|
||||
add it to a `SystemGraph`. Don't look for it in the graph.
|
||||
- **Adding a property = 4 places** (Body field + serialize + deserialize + component). Silent
|
||||
failure mode: value doesn't round-trip through Jolt.
|
||||
- **Jolt is a black box.** Configure via the components; don't reach into `external/JoltPhysics`
|
||||
to "fix" behavior. (The one legitimate exception is linking/version, in `src/Engine/CMakeLists.txt`.)
|
||||
- **Don't confuse the two BVHs.** `Physics/BVH` = collision broadphase. `Rendering` culling = a
|
||||
separate structure. Similar names, different subsystems, different files.
|
||||
- **`iInv` is recomputed in the `Body` ctor** from `iBody` and orientation. If you mutate
|
||||
`q`/`R` after construction, you must recompute `iInv` or the dynamics are wrong.
|
||||
- **Contacts are a transient view.** `Contact`/`Collision` are filled per tick; don't cache them
|
||||
across frames or they go stale.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a rigid body to a scene | `Component::RigidBody` + `Component::Collider` on an Actor (see scene-ecs doc) |
|
||||
| Add a new collider shape | `src/Engine/Component/` shapes (`ShapeBase` + `Box`/`Mesh`/`Sphere`/`Plane`) + `physicsMesh` (the Jolt mesh) |
|
||||
| Add a physical property that round-trips through Jolt | `PhysicsSystem::Body` + `serializeRB`/`deserializeRB` + the component |
|
||||
| Understand a "body doesn't move / wrong velocity" bug | the serialize→Jolt→deserialize path in `PhysicsSystem.cpp` |
|
||||
| Add a new collision response / query | `CollisionSystem.h` (witness) + `BVH.h` (broadphase) |
|
||||
| Jolt linking / version | `src/Engine/CMakeLists.txt` (`JOLT_PHYSICS_LIB`) |
|
||||
| Ground rules (read first) | `AGENTS.md` § "Physics (Jolt)" |
|
||||
@@ -0,0 +1,136 @@
|
||||
# Platform (OS abstraction, dynamic library loading, input enums)
|
||||
|
||||
> **Scope:** `src/Engine/Platform/` — the OS-specific layer. In Seele this is *smaller than you'd
|
||||
> expect*: the platform directory is mostly the **per-OS `GameInterface`** (which dynamically loads
|
||||
> the game's own shared library) plus the shared input enums. Heavy OS work (windows, surfaces,
|
||||
> Vulkan/Metal) lives in `Window/` and `Graphics/{Vulkan,Metal}/` respectively — this doc covers
|
||||
> the platform abstraction and, critically, **how the demo's game code actually gets loaded**.
|
||||
|
||||
This is one of the most important subsystems to understand for cross-repo work, because the
|
||||
`Platform` layer is where the **engine ↔ demo boundary is physically enforced** (dlopen /
|
||||
LoadLibrary + symbol lookup).
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `GameInterface` (Windows) | `src/Engine/Platform/Windows/GameInterface.h` (impl `.cpp`) |
|
||||
| `GameInterface` (Linux) | `src/Engine/Platform/Linux/GameInterface.h` (impl `.cpp`) |
|
||||
| `GameInterface` (macOS) | `src/Engine/Platform/Mac/GameInterface.h` (impl `.cpp`) |
|
||||
| `Game` | `src/Engine/Game.h` — the abstract class the loaded lib must instantiate |
|
||||
| Input enums: `InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` | `src/Engine/Platform/` (shared, included by `Window/View.h` input callbacks) |
|
||||
| `Window` (per-OS native surface) | `src/Engine/Window/Window.h`/`Window.cpp` (the OS window lives here, not in `Platform/`) |
|
||||
|
||||
**There is no monolithic `Platform.h`** (an older description of the codebase implied there was
|
||||
one — there isn't; `grep` for `dlopen`/`LoadLibrary` confirms all the dynamic-loading code is in the
|
||||
three `Platform/<OS>/GameInterface.cpp` files). The `Platform/` directory is the OS *abstraction for
|
||||
loading the game*, not a general OS facade.
|
||||
|
||||
## The per-OS `GameInterface` — how the demo is loaded
|
||||
|
||||
Each OS has a `GameInterface` with the same public shape:
|
||||
|
||||
```cpp
|
||||
class GameInterface {
|
||||
public:
|
||||
GameInterface(std::filesystem::path libPath); // path to the demo's .so/.dylib/.dll
|
||||
~GameInterface();
|
||||
Game* getGame(); // the live Game* (createInstance() result)
|
||||
void reload(); // (re)load the library + re-instantiate
|
||||
|
||||
private:
|
||||
// Windows: HMODULE lib; Linux: void* lib (dlopen); Mac: void* (dlopen)
|
||||
Game* (*createInstance)() = nullptr; // resolved symbol
|
||||
void (*destroyInstance)(Game*) = nullptr;
|
||||
};
|
||||
```
|
||||
|
||||
**`reload()` is the cross-repo contract in executable form.** It is *identical in logic* across all
|
||||
three OSes, only the syscalls differ:
|
||||
|
||||
| OS | Load | Resolve symbols | Unload |
|
||||
|----|------|-----------------|--------|
|
||||
| **Windows** (`Platform/Windows/GameInterface.cpp`) | `LoadLibraryA(dllPath)` | `GetProcAddress(lib, "createInstance")` / `...("destroyInstance")` | `FreeLibrary(lib)` |
|
||||
| **Linux** (`Platform/Linux/GameInterface.cpp`) | `dlopen(soPath, RTLD_NOW)` | `dlsym(lib, "createInstance")` / `...("destroyInstance")` | `dlclose(lib)` |
|
||||
| **macOS** (`Platform/Mac/GameInterface.cpp`) | `dlopen` | `dlsym` | `dlclose` |
|
||||
|
||||
The contract:
|
||||
|
||||
1. If a previous library is loaded, call `destroyInstance(game)` then unload it.
|
||||
2. Load the demo's shared library at `libPath`.
|
||||
3. Look up **exactly two** C symbols: `createInstance` and `destroyInstance` (plain `extern "C"`,
|
||||
no mangling).
|
||||
4. Call `createInstance()` → `Game*`; store it; `getGame()` returns it.
|
||||
|
||||
**The demo must export exactly these two `extern "C"` symbols** — that is the *entire* ABI. See
|
||||
[cross-repo.md](../cross-repo.md) for the demo-side half and [game-interface.md](game-interface.md)
|
||||
for the engine-side `Game` class.
|
||||
|
||||
### Gotcha: `reload()` also copies game shaders
|
||||
|
||||
The **Windows** `GameInterface::reload()` does something the other two don't (a known
|
||||
asymmetry): before loading, it **copies `<dllPath>/../res/shaders` → `./shaders/game`**
|
||||
(`std::filesystem::copy(..., copy_options::overwrite_existing)`) if that path exists. This is the
|
||||
**game-shader hot-reload** mechanism — the engine reads game shaders from `./shaders/game`, and
|
||||
`reload()` refreshes that directory so a rebuilt demo's new shaders are picked up without a full
|
||||
restart.
|
||||
|
||||
**Consequences:**
|
||||
- On Windows, "reload the game" also refreshes its shaders. On Linux/mac, it does **not** — the
|
||||
shader directory must be managed out-of-band (or you're on a platform where the copy step simply
|
||||
doesn't exist yet). **If you add cross-platform shader hot-reload, this is the place to fix the
|
||||
asymmetry.**
|
||||
- The copy target is the **CWD** (`./shaders/game`), not next to the library. CWD matters.
|
||||
- `rt`/`rt` and the engine's own shaders are separate — this only touches `shaders/game` (the
|
||||
*game's* shaders), not the engine's.
|
||||
|
||||
## Input enums (the shared platform types)
|
||||
|
||||
`InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` live in `src/Engine/Platform/` and are the
|
||||
**vocabulary of every input callback** in `Window/View.h` (`keyCallback`, `mouseButtonCallback`,
|
||||
etc.) and in `UI::System` (`key`, `mouseButton`, `scroll`). If you're adding a new input source or
|
||||
keycode, these are the enums to extend. They are the one truly shared, cross-OS piece of the
|
||||
`Platform/` layer (the `GameInterface` per-OS files are the rest).
|
||||
|
||||
## Where the OS "real" work actually lives (don't look here for it)
|
||||
|
||||
A common mistake is to look in `Platform/` for window/surface/GPU code. It's not here:
|
||||
|
||||
| Concern | Actual location |
|
||||
|---|---|
|
||||
| OS window + native surface | `src/Engine/Window/Window.{h,cpp}` (+ per-OS bits there) |
|
||||
| Vulkan | `src/Engine/Graphics/Vulkan/` |
|
||||
| Metal | `src/Engine/Graphics/Metal/` |
|
||||
| Loading the *game* (this doc) | `src/Engine/Platform/<OS>/GameInterface.cpp` |
|
||||
|
||||
The reason `Platform/` is thin: Seele pushes OS-specific code *down into the subsystem that owns
|
||||
the concern* (windowing → `Window/`, GPU → `Graphics/<Backend>/`), and keeps only the
|
||||
**game-loading** logic in `Platform/` because that is the one cross-cutting OS difference that
|
||||
belongs nowhere else.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Exactly two exported symbols** (`createInstance`, `destroyInstance`). Any other symbol the
|
||||
engine needs must be exposed *through* the `Game*` (virtual methods on `Game`), not as a new
|
||||
C symbol. Adding a third `extern "C"` export breaks the contract.
|
||||
- **Symbol names must be unmangled** (`extern "C"`). A mangled name = `dlsym`/`GetProcAddress`
|
||||
returns null = `createInstance` is null → crash on call.
|
||||
- **The shader-copy asymmetry** (Windows copies `res/shaders`→`./shaders/game` on reload; the
|
||||
others don't). Know which platform you're on before assuming "reload refreshes my shaders."
|
||||
- **`RTLD_NOW` on Linux** — all symbols are resolved at load; a missing symbol fails *at
|
||||
`dlopen`*, not at first use. Good for debugging, means a bad demo build fails loudly at load.
|
||||
- **`getGame()` lifetime** — the returned `Game*` is owned by the loaded library. When you `reload()`
|
||||
or unload, the old `Game*` is destroyed. Never hold a `Game*` across a `reload()`.
|
||||
- **CWD-sensitive** — the Windows shader copy writes to the *current working directory*, not the
|
||||
library's directory. Run from the right CWD.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Understand how the demo is loaded | `src/Engine/Platform/<OS>/GameInterface.cpp` (all three, compare) |
|
||||
| Add a new exported symbol (you probably shouldn't) | `GameInterface.cpp` + the `Game` virtuals in `src/Engine/Game.h` |
|
||||
| Fix shader hot-reload / the Windows-only copy | `Platform/Windows/GameInterface.cpp` `reload()` (the `std::filesystem::copy` block) |
|
||||
| Add a key code / input action | the enums in `src/Engine/Platform/` + `Window/View.h` callbacks + `UI/System.h` |
|
||||
| "my game lib won't load" | symbol names (unmangled?), the two exports present, the lib path, `dlopen`/`LoadLibrary` error |
|
||||
| Per-OS window/surface (not here) | `src/Engine/Window/Window.{h,cpp}` |
|
||||
@@ -0,0 +1,67 @@
|
||||
# Render Graph & Render Passes
|
||||
|
||||
> The linear RenderGraph, the per-frame begin/render/end protocol, shared string-named resources, and every render pass in the active pipeline.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `RenderGraph` | `src/Engine/Graphics/RenderPass/RenderGraph.h` |
|
||||
| `RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `RenderGraphResources` | `src/Engine/Graphics/RenderPass/RenderGraphResources.h` |
|
||||
| `CachedDepthPass` | `src/Engine/Graphics/RenderPass/CachedDepthPass.h` |
|
||||
| `DepthCullingPass` | `src/Engine/Graphics/RenderPass/DepthCullingPass.h` |
|
||||
| `VisibilityPass` | `src/Engine/Graphics/RenderPass/VisibilityPass.h` |
|
||||
| `LightCullingPass` | `src/Engine/Graphics/RenderPass/LightCullingPass.h` |
|
||||
| `ShadowPass` | `src/Engine/Graphics/RenderPass/ShadowPass.h` |
|
||||
| `BasePass` | `src/Engine/Graphics/RenderPass/BasePass.h` |
|
||||
| `ToneMappingPass` | `src/Engine/Graphics/RenderPass/ToneMappingPass.h` |
|
||||
| `RayTracingPass` | `src/Engine/Graphics/RenderPass/RayTracingPass.h` |
|
||||
| `SimulationComputePass` | `src/Engine/Graphics/RenderPass/SimulationComputePass.h` |
|
||||
| `SurfaceExtractPass` | `src/Engine/Graphics/RenderPass/SurfaceExtractPass.h` |
|
||||
| `FluidRenderPass` | `src/Engine/Graphics/RenderPass/FluidRenderPass.h` |
|
||||
| `TerrainRenderer` | `src/Engine/Graphics/RenderPass/TerrainRenderer.h` |
|
||||
| `WaterRenderer` | `src/Engine/Graphics/RenderPass/WaterRenderer.h` |
|
||||
| `UIPass` | `src/Engine/Graphics/RenderPass/UIPass.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
RenderGraph (src/Engine/Graphics/RenderPass/RenderGraph.h) is a simple linear pipeline: addPass(ORenderPass) (calls pass->setResources(res) to inject shared RenderGraphResources), setViewport, createRenderPass() (two-phase: first pass->publishOutputs() on all passes to register outputs into the shared resource map, then pass->createRenderPass() to create GPU render pass objects), render(cam, transform) (three-phase: beginFrame on all, render() on all, endFrame() on all). RenderGraphResources (RenderGraphResources.h) is a name-keyed resource registry: requestRenderTarget/requestTexture/requestBuffer/requestUniform/requestQuery/requestTimestampQuery for consumers, registerRenderPassOutput/registerTextureOutput/registerBufferOutput/registerUniformOutput/registerQueryOutput/registerTimestampQueryOutput for producers. Passes discover each other's outputs by string name (e.g. 'depthTexture', 'visibilityTexture', 'cullingBuffer', 'lightIndexList', 'lightGrid', 'shadowMaps'). RenderPass base class (RenderPass.h) holds: PRenderGraphResources resources, Gfx::PViewport viewport, Gfx::ORenderPass renderPass (GPU-side), Gfx::ODescriptorLayout viewParamsLayout, ViewParameter viewParams struct (viewMatrix, inverseViewMatrix, projectionMatrix, viewProjectionMatrix, cameraPosition_WS, cameraForward_WS, screenDimensions, invScreenDimensions, frameIndex, time). It provides updateViewParameters(cam, transform), createViewParamsSet(), and frustum culling helpers (computePlane, extract_planes_from_view_projection_matrix). A RenderPassType concept (std::derived_from<RenderPass>) is defined. GameView.cpp wires the active pipeline: CachedDepthPass -> DepthCullingPass -> VisibilityPass -> LightCullingPass -> ShadowPass -> BasePass -> ToneMappingPass. RayTracingPass is in a separate rayTracingGraph, gated by getGlobals().useRayTracing && graphics->supportRayTracing(). SimulationComputePass, SurfaceExtractPass, FluidRenderPass are commented out in both graphs (WIP).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/RenderPass/RenderGraph.h` | 45 lines, full file |
|
||||
| `src/Engine/Graphics/RenderPass/RenderPass.h + RenderPass.cpp` | base class, 77 lines header / 6.8KB impl |
|
||||
| `src/Engine/Graphics/RenderPass/RenderGraphResources.h + .cpp` | shared resource registry |
|
||||
| `src/Engine/Window/GameView.cpp` | pipeline wiring, lines 24-108 |
|
||||
| `src/Engine/Graphics/RenderPass/CachedDepthPass.h + .cpp` | depth prepass + visibility prepass |
|
||||
| `src/Engine/Graphics/RenderPass/DepthCullingPass.h + .cpp` | GPU culling: depth mip buffer, BLOCK_SIZE=32, cullingBuffer output |
|
||||
| `src/Engine/Graphics/RenderPass/VisibilityPass.h + .cpp` | visibilityTexture + cullingBuffer, compute shader |
|
||||
| `src/Engine/Graphics/RenderPass/LightCullingPass.h + .cpp` | oLightIndexList/tLightIndexList, oLightGrid/tLightGrid, frustumBuffer, double-buffered |
|
||||
| `src/Engine/Graphics/RenderPass/ShadowPass.h + .cpp` | 4 cascades, 8192x8192 shadow maps, light-space matrices |
|
||||
| `src/Engine/Graphics/RenderPass/BasePass.h + .cpp` | main 3D pass: HDR MSAA color/depth, opaque+transparent meshlets, skybox, debug rendering |
|
||||
| `src/Engine/Graphics/RenderPass/ToneMappingPass.h + .cpp` | post-processing, final output to viewport |
|
||||
| `src/Engine/Graphics/RenderPass/RayTracingPass.h + .cpp` | TLAS 'scene', rayGen/anyhit/miss shaders, radiance accumulator |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- RenderGraph is NOT a data-flow graph — it is a linear list with a two-phase setup (publishOutputs then createRenderPass) and a three-phase per-frame loop (beginFrame/render/endFrame on ALL passes before any pass runs its GPU work).
|
||||
- Passes communicate exclusively through string-named resources in RenderGraphResources. The names are hardcoded constants (e.g. DEPTHTEXTURE_NAME='depthTexture', VISIBILITY_NAME='visibilityTexture', CULLINGBUFFER_NAME='cullingBuffer', LIGHTINDEX_NAME='lightIndexList'). If you rename one, every consumer breaks silently.
|
||||
- CachedDepthPass is the FIRST pass in the graph — it does a depth prepass AND a visibility prepass (renders meshlets twice before anything else).
|
||||
- DepthCullingPass and VisibilityPass both write to 'cullingBuffer' — the culling buffer is a shared GPU buffer that DepthCullingPass creates and VisibilityPass consumes.
|
||||
- LightCullingPass uses double-buffered light grids (oLightGrid/tLightGrid, oLightIndexList/tLightIndexList) — the 'o' and 't' prefixes stand for odd/even frames.
|
||||
- BasePass.h has WaterRenderer and TerrainRenderer members commented out (lines 67-68) — water/terrain are not currently in the active render path.
|
||||
- SimulationComputePass, SurfaceExtractPass, FluidRenderPass are all commented out in GameView.cpp (lines 33-35, 41-43). The fluid simulation pipeline exists but is disabled.
|
||||
- ToneMappingPass takes only Gfx::PGraphics in its constructor (no scene) — it is the only pass that does not need scene access.
|
||||
- The 'RenderPass' name is overloaded: Gfx::RenderPass (GPU render pass object, created by Graphics::createRenderPass) vs Seele::RenderPass (the C++ base class for frame passes). They are different types in different namespaces.
|
||||
- RenderGraph::addPass takes ORenderPass (OwningPtr) — the graph owns the passes. You cannot remove a pass once added (no removePass method).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,75 @@
|
||||
# Scene / ECS / Components / Actors
|
||||
|
||||
> The entt-based ECS: entities, components, the scene update loop, actors, and the light/fluid/physics subsystems embedded in the scene.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Scene` | `src/Engine/Scene/Scene.h` |
|
||||
| `Entity` | `src/Engine/Actor/Entity.h` |
|
||||
| `Actor` | `src/Engine/Actor/Actor.h` |
|
||||
| `CameraActor` | `src/Engine/Actor/CameraActor.h` |
|
||||
| `DirectionalLightActor` | `src/Engine/Actor/DirectionalLightActor.h` |
|
||||
| `PointLightActor` | `src/Engine/Actor/PointLightActor.h` |
|
||||
| `StaticMeshActor` | `src/Engine/Actor/StaticMeshActor.h` |
|
||||
| `Component::Component` | `src/Engine/Component/Component.h` |
|
||||
| `Component::Transform` | `src/Engine/Component/Transform.h` |
|
||||
| `Component::Camera` | `src/Engine/Component/Camera.h` |
|
||||
| `Component::Mesh` | `src/Engine/Component/Mesh.h` |
|
||||
| `Component::Collider` | `src/Engine/Component/Collider.h` |
|
||||
| `Component::RigidBody` | `src/Engine/Component/RigidBody.h` |
|
||||
| `Component::DirectionalLight` | `src/Engine/Component/DirectionalLight.h` |
|
||||
| `Component::PointLight` | `src/Engine/Component/PointLight.h` |
|
||||
| `Component::Skybox` | `src/Engine/Component/Skybox.h` |
|
||||
| `Component::FluidGrid` | `src/Engine/Component/FluidGrid.h` |
|
||||
| `Component::TerrainTile` | `src/Engine/Component/TerrainTile.h` |
|
||||
| `Component::WaterTile` | `src/Engine/Component/WaterTile.h` |
|
||||
| `Component::ShapeBase` | `src/Engine/Component/ShapeBase.h` |
|
||||
| `Component::BoxCollider/MeshCollider/SphereCollider` | `src/Engine/Component/BoxCollider.h` |
|
||||
| `LightEnvironment` | `src/Engine/Scene/LightEnvironment.h` |
|
||||
| `FluidScene` | `src/Engine/Scene/FluidScene.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Scene (src/Engine/Scene/Scene.h) wraps an entt::registry (public member 'registry'). API: createEntity(), destroyEntity(entity), attachComponent<T>(entity, args...), accessComponent<T>(entity), view<Components...>(func) (C++20 constrained template requiring std::is_invocable_v), constructCallback<T>()/destroyCallback<T>() (entt on_construct/on_destroy hooks), getLightEnvironment(), getFluidScene(), getGraphics(), update(deltaTime), bakeLighting(). Private: OFluidScene fluidScene, OLightEnvironment lightEnv, PhysicsSystem physics, Array<Gfx::OTexture2D> lightMaps. Scene constructor takes Gfx::PGraphics. Components are plain structs registered with entt (Component.h defines the base Component struct). Actor (src/Engine/Actor/Actor.h) is an Entity wrapper — DEFINE_REF(Actor) gives PActor. CameraActor/DirectionalLightActor/PointLightActor/StaticMeshActor are convenience subclasses that attach their component in the constructor (CameraActor::getCameraComponent() returns Component::Camera&). CameraActor is the only actor that GameView uses to extract the active camera (GameView::render() iterates view<Camera,Transform> and picks the one with c.mainCamera==true). FluidScene (src/Engine/Scene/FluidScene.h) is a standalone fluid simulation scene (NOT in a Fluid/ directory — it lives in Scene/). LightEnvironment (Scene/LightEnvironment.h) manages baked lightmaps and commit(). PhysicsSystem (src/Engine/Physics/PhysicsSystem.h) is embedded in Scene and updated in Scene::update().
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Scene/Scene.h + Scene.cpp` | entt registry wrapper |
|
||||
| `src/Engine/Actor/Actor.h + Actor.cpp` | base actor |
|
||||
| `src/Engine/Actor/CameraActor.h + .cpp` | |
|
||||
| `src/Engine/Actor/DirectionalLightActor.h + .cpp` | attaches DirectionalLight component, registers with LightEnvironment |
|
||||
| `src/Engine/Actor/PointLightActor.h + .cpp` | |
|
||||
| `src/Engine/Actor/StaticMeshActor.h + .cpp` | |
|
||||
| `src/Engine/Component/Component.h` | base component struct |
|
||||
| `src/Engine/Component/Transform.h + .cpp` | position/rotation/scale, world matrix |
|
||||
| `src/Engine/Component/Camera.h` | mainCamera flag, fov, near/far, projection params |
|
||||
| `src/Engine/Component/Mesh.h` | references Graphics::Mesh asset |
|
||||
| `src/Engine/Component/ShapeBase.h + .cpp` | collision shape base, 8.9KB impl — shape serialization, mesh import |
|
||||
| `src/Engine/Component/FluidGrid.h` | fluid simulation grid component |
|
||||
| `src/Engine/Scene/FluidScene.h + .cpp` | standalone fluid sim scene, 11.5KB impl |
|
||||
| `src/Engine/Scene/LightEnvironment.h + .cpp` | baked lighting, lightmap commit |
|
||||
| `src/Engine/Physics/PhysicsSystem.h + .cpp` | embedded physics, 18.5KB impl |
|
||||
| `src/Engine/Physics/BVH.h + .cpp` | bounding volume hierarchy for collision |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- FluidScene is at src/Engine/Scene/FluidScene.h — there is NO Fluid/ directory. Do not look for it under Engine/Fluid/.
|
||||
- Component::Mesh, Component::Collider, Component::BoxCollider, Component::MeshCollider, Component::SphereCollider exist as files but some are EMPTY (0 bytes: BoxCollider.h, MeshCollider.h, SphereCollider.h). Only ShapeBase.cpp (8.9KB) has actual collision shape logic.
|
||||
- The entt::registry is a PUBLIC member of Scene — you can access entities directly via scene.registry without going through the accessComponent/attachComponent helpers (though the helpers are the intended API).
|
||||
- GameView::render() finds the main camera by iterating ALL Camera+Transform components and checking the mainCamera boolean flag. If no component has mainCamera=true, cam/transform remain default-constructed and the render will use an identity camera.
|
||||
- Scene has NO explicit render method — rendering is driven externally by GameView::render() which calls renderGraph.render(cam, transform) directly. Scene::update() only runs ECS systems and physics.
|
||||
- bakeLighting() on Scene bakes lightmaps into the LightEnvironment; the results are committed via lightEnv->commit() in GameView::update().
|
||||
- PhysicsSystem is a VALUE member of Scene (not a pointer) — it is constructed/destroyed with the Scene.
|
||||
- DirectionalLightActor and PointLightActor register their light with the scene's LightEnvironment in their constructor — deleting the actor does NOT unregister the light from the environment (check LightEnvironment.cpp for the actual lifecycle).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,54 @@
|
||||
# Component Systems & the Update Loop
|
||||
|
||||
> SystemGraph, SystemBase, ComponentSystem<T>, the built-in systems, and how the frame loop drives them from GameView.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `SystemBase` | `src/Engine/System/SystemBase.h` |
|
||||
| `SystemGraph` | `src/Engine/System/SystemGraph.h` |
|
||||
| `ComponentSystem<Components...>` | `git grep` in `src/` |
|
||||
| `KeyboardInput` | `src/Engine/Component/KeyboardInput.h` |
|
||||
| `FluidUpdater` | `src/Engine/System/FluidUpdater.h` |
|
||||
| `LightGather` | `src/Engine/System/LightGather.h` |
|
||||
| `MeshUpdater` | `src/Engine/System/MeshUpdater.h` |
|
||||
| `CameraUpdater` | `src/Engine/System/CameraUpdater.h` |
|
||||
| `Executor` | `src/Engine/System/Executor.h` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
SystemGraph (src/Engine/System/SystemGraph.h + .cpp, 318B + 259B) is a list of SystemBase pointers with addSystem(OSystemBase) and run(delta). SystemBase (SystemBase.h) holds a PScene scene and virtual run(double)/update(). ComponentSystem<Components...> (ComponentSystem.h) is the template base for all data-driven systems: its run(delta) calls SystemBase::run then setupView(), which iterates the entt registry over the template's component types (plus any Deps from a has_dependencies concept) and calls the virtual update(components...) / update(entity, components...) overloads. Each concrete system (FluidUpdater, LightGather, MeshUpdater, CameraUpdater, KeyboardInput) is a ComponentSystem specialization. KeyboardInput is special — it is NOT a ComponentSystem; it is a SystemBase subclass that receives raw key/mouse/scroll callbacks from GameView and translates them into entt component modifications. GameView::reloadGame() (GameView.cpp lines 96-108) rebuilds the system graph after each game reload: creates new SystemGraph, calls gameInterface.getGame()->setupScene(scene, systemGraph) (the game DLL populates the scene and may add its own systems), then adds the built-in systems: KeyboardInput, FluidUpdater, LightGather, MeshUpdater, CameraUpdater. GameView::update() (lines 54-69) runs the frame: resets all VertexData mesh data (VertexData::getList() — a global list of registered vertex data objects), runs systemGraph->run(updateTime), calls scene->update(updateTime), then re-creates GPU descriptors for all VertexData (vd->createDescriptors()), and commits the LightEnvironment. updateTime is computed from std::chrono::high_resolution_clock deltas between frames.
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/System/SystemGraph.h + SystemGraph.cpp` | |
|
||||
| `src/Engine/System/SystemBase.h` | base class, 532B |
|
||||
| `src/Engine/System/ComponentSystem.h` | template base, 1282B — full file shown above |
|
||||
| `src/Engine/System/KeyboardInput.h + .cpp` | raw input -> entt, 998B + 1442B |
|
||||
| `src/Engine/System/FluidUpdater.h + .cpp` | FluidGrid+Transform -> fluid grid update |
|
||||
| `src/Engine/System/LightGather.h + .cpp` | collects light components into LightEnvironment |
|
||||
| `src/Engine/System/MeshUpdater.h + .cpp` | updates mesh GPU data |
|
||||
| `src/Engine/System/CameraUpdater.h + .cpp` | updates camera matrices from Transform |
|
||||
| `src/Engine/System/Executor.h + .cpp` | thread pool executor, 208B + 76B — small |
|
||||
| `src/Engine/Window/GameView.cpp` | frame loop: update() lines 54-69, reloadGame() lines 96-108, render() lines 75-89 |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- ComponentSystem::setupView has a commented-out thread pool path (lines 15-22 of ComponentSystem.h) — the parallel dispatch is stubbed. All system updates run serially on the main thread.
|
||||
- KeyboardInput is NOT a ComponentSystem — it is a plain SystemBase subclass. It does not iterate the entt registry; it receives raw input callbacks from GameView and directly mutates components (e.g. calling scene->accessComponent<Transform>(entity).position += ...).
|
||||
- The system graph is DESTROYED and REBUILT on every reloadGame() call (GameView.cpp line 99: systemGraph = new SystemGraph()). The game DLL's setupScene is the hook for custom systems.
|
||||
- VertexData::getList() is a STATIC global list (VertexData.h/.cpp, 6.4KB header + 27.5KB impl). Every VertexData instance registers itself on construction. GameView::update() iterates this list to reset mesh data before the system graph runs and to re-create GPU descriptors after. This is a side-channel that bypasses the ECS — VertexData is NOT an entt component.
|
||||
- updateTime is NOT a fixed timestep — it is the measured wall-clock delta between frames (lines 55-68 of GameView.cpp). There is no fixed-timestep accumulator in the engine.
|
||||
- FluidUpdater is a ComponentSystem<FluidGrid, Transform> — it requires both components on an entity to fire. If an entity has FluidGrid but no Transform, it is silently skipped.
|
||||
- The Executor class (Executor.h/.cpp) is a tiny thread-pool wrapper (76B impl) that is NOT used by any of the built-in systems (the parallel code in ComponentSystem is commented out). It exists for the game DLL to use.
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,135 @@
|
||||
# UI (flexbox layout, element tree, theming)
|
||||
|
||||
> **Scope:** `src/Engine/UI/` — a from-scratch, dependency-free **flexbox** layout engine, an
|
||||
> element-tree widget system (Div/Button/Text/Panel), and a theme/style system. No ImGui, no
|
||||
> Dear ImGui — this is custom and it's the "app UI" (overlays, HUD, menus), not the 3D scene.
|
||||
|
||||
The UI is a **separate render path** from the 3D scene: it produces `UIRender` quads (colored
|
||||
rectangles + glyph quads) that are composited on top of the 3D frame. Layout is a real two-phase
|
||||
flexbox (measure → place), and the whole thing is driven incrementally — only dirty subtrees
|
||||
re-style/re-layout.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `UI::System` | `src/Engine/UI/System.h` (impl `System.cpp`) — the per-frame driver |
|
||||
| `UI::Element` (base widget) | `src/Engine/UI/Element.h` (impl `Element.cpp`) |
|
||||
| `UI::Div<...>`, `UI::Button<...>`, `UI::Text`, `UI::Panel` | `src/Engine/UI/Element/{Div,Button,Text,Panel}.h` |
|
||||
| `UI::FlexLayout` | `src/Engine/UI/FlexLayout.h` (impl `FlexLayout.cpp`) — the layout engine |
|
||||
| `UI::Style`, `UI::Theme`, `UI::Class<...>` | `src/Engine/UI/Style/{Style,Theme,Class,Fonts}.h` |
|
||||
| `UI::Attributes` (widget callbacks/props) | `src/Engine/UI/Attributes.h` |
|
||||
| `UIRender` (a quad to draw: color rect or glyph) | `src/Engine/UI/Element.h` / `src/Engine/Graphics/` |
|
||||
| `Display`, `Direction`, `DimensionType`, `ContentDirection` | `src/Engine/UI/Style/Style.h` (enums) |
|
||||
|
||||
`DECLARE_REF(System)` exists in `UI/System.h` — `System` is ref-countable. The element tree itself
|
||||
(`OElement`/`PElement`) is also a ref-counted tree (the `DEFINE_REF(Element)` in `Element.h`).
|
||||
|
||||
## The frame pipeline (the thing to understand first)
|
||||
|
||||
`UI::System` (`UI/System.h`) runs this, **once per frame, from the owning view, before 3D layout
|
||||
matters but as part of the render path**:
|
||||
|
||||
```
|
||||
processInput() # mouse/key/scroll events → update hover/focus state
|
||||
beginFrame(viewport) # style dirty subtrees → layout (if dirty or viewport changed) → render
|
||||
├─ styleRec(root) # walk the tree; applyStyle on elements whose style is dirty
|
||||
├─ if layoutDirty → FlexLayout::layout(viewport, root)
|
||||
└─ renderElements = render() # collect UIRender quads for the compositor
|
||||
render() → Array<UIRender> # the actual quads the view blits over the 3D frame
|
||||
```
|
||||
|
||||
**Incrementality is the core design.** The tree is built once; mutations go through element setters
|
||||
(`setText`, `setChildren`, style setters) which call `markDirty()`. Only the affected subtree
|
||||
re-styles/re-lays-out. `setTheme` forces one full re-style (`markAllDirty` + `layoutDirty`).
|
||||
`lastViewport` is cached: if the viewport didn't change and nothing is dirty, layout is **skipped
|
||||
entirely** — the UI is cheap on idle frames.
|
||||
|
||||
## The flexbox engine (`FlexLayout`)
|
||||
|
||||
`UI::FlexLayout` (`UI/FlexLayout.h`) is a **genuine two-phase flexbox**:
|
||||
|
||||
- **Phase 1 — measure** (`measure`): top-down, resolves `DimensionType::Auto` sizes against
|
||||
content (text is measured via `font->shapeText`), handles `min/max` clamps, and computes the
|
||||
main/cross sizes of every node. Text measurement is the only expensive part — it's what makes
|
||||
`Text`'s `Auto` width/height work.
|
||||
- **Phase 2 — place** (`place`/`placeFlex`): walks again, assigning final `Rect` bounds. Supports
|
||||
`Direction` (row/row-reverse/column/column-reverse), **wrap**, `justify` (content alignment along
|
||||
the main axis), `align` (cross axis), **margins**, and `ContentDirection` (start/center/end).
|
||||
- It works on an internal **flat node list** (`FlexNode`) built from the element tree — the element
|
||||
`Element` carries a `FlexNode*` back-pointer, and `FlexLayout` never touches the tree's pointer
|
||||
structure directly during layout. This is what keeps layout O(n) and cache-friendly.
|
||||
|
||||
**Gotcha:** `FlexNode`/layout state is **reused between frames** (the `FlexNode*` on each
|
||||
`Element` is stable). If you add a new widget, you must make sure it produces a valid `FlexNode`
|
||||
in `applyStyle`/measurement or layout will read stale bounds. The comment block at the top of
|
||||
`System.h` documents the frame invariants — read it before touching layout.
|
||||
|
||||
## The widget set
|
||||
|
||||
The widget vocabulary is small and **explicit** — there are no "accidental" empty widgets:
|
||||
|
||||
| Widget | Base | Notes |
|
||||
|--------|------|-------|
|
||||
| `Div<classes...>` | `Element` | container. **`Div()` is deleted** — you must name style classes (`Div<MyStyles::card>`) or you can't create one. This is intentional: it forces a style/attrs choice. |
|
||||
| `Button<classes...>` | `Div<...>` | wires `onHover`/`onHoverLeave`/`onClick`/`onScroll`/`onKey`/`onFocus`/`onBlur` callbacks in `Attributes`; key-enter fires `onClick`; hover/press state is tracked and re-marked dirty on change. |
|
||||
| `Text` | `Element` | holds a string; `setText` marks dirty; resolves a **font by name** at style time (see below); renders glyph quads from `UIRender` per glyph. |
|
||||
| `Panel<classes...>` | `Div<...>` | themed convenience: `theme.color(ColorToken::Gray900)` bg, white text, `theme.spacing(8)` padding. |
|
||||
|
||||
**Styling is template-based**: `Div<classes...>` / `Button<classes...>` / `Panel<classes...>` take
|
||||
a **variadic list of style-class types** at compile time (the `Style/Class.h` machinery). `applyStyle`
|
||||
merges: theme defaults → class styles → parent inheritance → per-instance overrides. This is the
|
||||
"CSS class" model done with C++ templates instead of strings.
|
||||
|
||||
## Fonts & text — the INVARAIT (read this)
|
||||
|
||||
The `System.h` header carries an explicit invariant (verbatim from source):
|
||||
|
||||
> **INVARAIT: fonts referenced by style classes must be imported**
|
||||
> (`AssetImporter::importFont`) **before the first `style()` call.** `Text` falls back to
|
||||
> `Theme::defaultFont` and renders **empty** (with an assert in debug) otherwise.
|
||||
|
||||
- `Text::applyStyle` resolves the font **by name** via
|
||||
`AssetRegistry::findFont("", style.fontName)` — a string literal can't be a template arg, so the
|
||||
font is a *named runtime lookup*. If the name is empty it uses `Theme::defaultFont`.
|
||||
- If the named font isn't in the `AssetRegistry` at style time, the glyphs array is left **empty**
|
||||
and the text renders as a zero-size (invisible) box — **in release you get nothing, no crash**.
|
||||
This is the #1 "my UI text doesn't show" bug. **Fix: import the font before you build the tree.**
|
||||
- Fonts are `OwningPtr<Font>` / managed by the asset system — see [assets.md](asset-pipeline.md) and
|
||||
[serialization.md](core-utilities.md) for the import path.
|
||||
|
||||
## How the UI actually gets drawn (cross-subsystem)
|
||||
|
||||
`UI::System::render()` returns `Array<UIRender>`. The **owning view** (the thing that drives
|
||||
`System::beginFrame` each frame) takes that array and blits the quads **over** the 3D render graph
|
||||
output. `UIRender` is a small struct (either a filled color rect, or a glyph: font + glyph index +
|
||||
uv + rect + color). It is *not* a separate render pass in the `RenderGraph` in the same sense as
|
||||
3D passes — it's a flat quad list the view composites. If you're looking for the "UI render pass"
|
||||
in the render graph, it's this quad list, handled at the view level.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`Div()` deleted** — always construct with a style-class template arg, or the widget won't
|
||||
compile. This is by design, not a bug.
|
||||
- **Empty text = font not imported.** No assert in release. Import fonts before first style pass.
|
||||
- **Layout state is cached and reused** — new widgets must emit a valid `FlexNode`. Stale
|
||||
`FlexNode*` = garbage bounds.
|
||||
- **`markDirty` is the only way to invalidate.** Directly mutating a `Style` field without
|
||||
`markDirty()` means the change won't be re-styled next frame. Use the setters.
|
||||
- **The UI thread is the frame thread.** All `System` methods run during the view's frame callback
|
||||
(see [window.md](window.md)). Don't call `beginFrame`/`render` from elsewhere.
|
||||
- **Templates + `classes...`** — the widget class list is a compile-time token; you can't
|
||||
"dynamically add a class" at runtime. Runtime theming goes through `setTheme` (full re-style) or
|
||||
per-instance style setters (subtree dirty), not by changing the template arg.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a new widget | `src/Engine/UI/Element/` (copy `Panel.h` as a template) + `Element.h` base |
|
||||
| Make a style class | `src/Engine/UI/Style/Class.h` (the template machinery) |
|
||||
| Change the theme (colors/spacing/fonts) | `src/Engine/UI/Style/Theme.h` + `System::setTheme` |
|
||||
| Fix "text not rendering" | confirm font imported (`AssetImporter::importFont`) before first frame; check `Text::applyStyle` `AssetRegistry::findFont` |
|
||||
| Layout bug (wrong bounds) | `src/Engine/UI/FlexLayout.cpp` (measure then place) |
|
||||
| Add an input callback to a widget | `src/Engine/UI/Attributes.h` + the widget's `onMouseEvent`/`onKeyEvent` override |
|
||||
| Understand the frame invariants | top of `src/Engine/UI/System.h` (the comment block) |
|
||||
@@ -0,0 +1,73 @@
|
||||
# Vulkan Backend (Vulkan::Graphics)
|
||||
|
||||
> The Vulkan implementation: device/queue setup, resource creation, validation, and the capability gates for mesh shading and ray tracing.
|
||||
|
||||
This is a **navigation** doc: it tells you where things live, how data actually flows, and the sharp edges — so you can orient in minutes instead of hours. It complements the repository's [AGENTS.md](../../AGENTS.md) (map + rules) and the [cross-repo guide](../cross-repo.md) (engine ↔ demo contract). Everything below is grounded in the checked-out source at commit `d3ed573`.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Vulkan::Graphics` | `src/Engine/Graphics/Graphics.h` |
|
||||
| `Vulkan::Window` | `src/Engine/Graphics/Metal/Window.h` |
|
||||
| `Vulkan::Viewport` | `src/Editor/Window/ViewportControl.h` (search) |
|
||||
| `Vulkan::RenderPass` | `src/Engine/Graphics/Metal/RenderPass.h` |
|
||||
| `Vulkan::Framebuffer` | `src/Engine/Graphics/Vulkan/Framebuffer.h` |
|
||||
| `Vulkan::Buffer` | `src/Engine/Graphics/Buffer.h` |
|
||||
| `Vulkan::ShaderBuffer/UniformBuffer/VertexBuffer/IndexBuffer` | `git grep` in `src/` |
|
||||
| `Vulkan::Texture/Texture2D/2DArray/3D/Cube/TextureView/Sampler` | `src/Engine/Graphics/Metal/Texture.h` |
|
||||
| `Vulkan::Shader (all stages)` | `git grep` in `src/` |
|
||||
| `Vulkan::DescriptorLayout/DescriptorSet/PipelineLayout` | `git grep` in `src/` |
|
||||
| `Vulkan::GraphicsPipeline/ComputePipeline/RayTracingPipeline` | `git grep` in `src/` |
|
||||
| `Vulkan::CommandBuffer (RenderCommand/ComputeCommand)` | `git grep` in `src/` |
|
||||
| `Vulkan::OcclusionQuery/PipelineStatisticsQuery/TimestampQuery` | `git grep` in `src/` |
|
||||
| `Vulkan::BottomLevelAS/TopLevelAS` | `git grep` in `src/` |
|
||||
| `Vulkan::Allocator (VMA)` | `git grep` in `src/` |
|
||||
| `Vulkan::Queue` | `src/Engine/Graphics/Vulkan/Queue.h` |
|
||||
| `Vulkan::PipelineCache` | `src/Engine/Graphics/Metal/PipelineCache.h` |
|
||||
| `Vulkan::Debug (layer)` | `git grep` in `src/` |
|
||||
|
||||
Paths above are resolved against the actual source tree (namespace ≈ directory in this codebase). A `(search)` marker means the file contains the name but may also define others — open it and grep. `git grep` is always a fallback. The full per-file map is in **Where to look** below.
|
||||
|
||||
## Data flow / lifecycle
|
||||
|
||||
Vulkan::Graphics (src/Engine/Graphics/Vulkan/Graphics.h + Graphics.cpp, 10.7KB header + 52KB impl) implements Gfx::Graphics. init(GraphicsInitializer) creates the VkInstance (with validation layers when ENABLE_VALIDATION, debug callbacks via Debug.h/.cpp), VkSurface (from the OS window handle), selects a physical device + queue families (graphics/async/transfer + optional ray tracing queue), creates VkDevice with all required extensions (VK_KHR_ray_tracing_pipeline, VK_NV_mesh_shader, VK_EXT_mesh_shader, VK_KHR_acceleration_structure, VK_KHR_deferred_host_operations, VK_EXT_vertex_input_dynamic_state, VK_EXT_tooling_info, swapchain, sync2, timeline semaphore, etc.). QueueFamilyMapping records which queue index hosts graphics/async/transfer/RT work. The VkDevice is stored alongside a Vulkan::Allocator (VMA-based memory allocator, Allocator.h + Allocator.cpp, 13KB) for all buffer/texture memory. Window.cpp (18KB) handles the OS window (X11 on Linux via GLFW or raw X11, Win32 on Windows) + VkSurface + swapchain management + frame loop (acquire next image, present). Viewport is a sub-rectangle of a Window (multiple viewports can share one window). RenderPass.cpp (12KB) creates VkRenderPass + VkFramebuffer objects (Framebuffer.h + .cpp, 3.8KB) — framebuffers are per-swapchain-image. Command.cpp (26KB) implements the command buffer pool: RenderCommand and ComputeCommand wrap VkCommandBuffer, with beginRenderPass/endRenderPass, draw/drawIndexed/drawMeshTasksNV/drawMeshTasksEXT, dispatch/dispatchBase, bindPipeline/bindDescriptorSets/bindVertexBuffers/bindIndexBuffer, beginQuery/endQuery, copyBuffer/copyImage/blendImage, buildAccelerationStructure, etc. Descriptor.cpp (20KB) implements descriptor pool + layout + set allocation. PipelineCache.cpp (37KB) loads/saves VkPipelineCacheData to disk and caches VkPipeline objects keyed by a hash. RayTracing.cpp (11KB) implements BLAS/TLAS creation + building (vkCmdBuildAccelerationStructuresKHR) and the 6 RT shader stages (raygen/anyhit/closesthit/miss/intersection/callable). Query.cpp (6.5KB) implements occlusion queries (VkQueryPool + vkGetQueryPoolResults), pipeline statistics queries (VkPipelineStatisticsQuery), and timestamp queries. Texture.cpp (27KB) implements all texture types (1D/2D/3D/cube/array) with mipmap generation (vkCmdGenerateMipmaps), sampling (VkSampler), and texture views (VkImageView). Buffer.cpp (22KB) implements all buffer types with VMA allocation + vkCmdCopyBuffer for uploads. Graphics.cpp also implements: createRenderPass (full VkRenderPass creation from RenderTargetLayout + SubPassDependency array), executeCommands (submit to VkQueue with fence), waitDeviceIdle (vkDeviceWaitIdle), resolveTexture (vkCmdBlitImage), copyTexture (vkCmdCopyImage), copyBuffer (vkCmdCopyBuffer), all RT factory methods, and the capability flags (meshShadingEnabled from VK_NV_mesh_shader/VK_EXT_mesh_shader extension presence, rayTracingEnabled from VK_KHR_ray_tracing_pipeline).
|
||||
|
||||
## Where to look
|
||||
|
||||
| Path | What's there |
|
||||
|------|--------------|
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.h` | 10.7KB — full Vulkan backend interface + members |
|
||||
| `src/Engine/Graphics/Vulkan/Graphics.cpp` | 52KB — device creation, all factory methods |
|
||||
| `src/Engine/Graphics/Vulkan/Window.h + .cpp` | OS window + swapchain, 18KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/RenderPass.h + .cpp` | VkRenderPass + framebuffer creation |
|
||||
| `src/Engine/Graphics/Vulkan/Framebuffer.h + .cpp` | VkFramebuffer wrapper |
|
||||
| `src/Engine/Graphics/Vulkan/Command.h + .cpp` | command buffer pool, 26KB impl — all draw/dispatch/AS build commands |
|
||||
| `src/Engine/Graphics/Vulkan/Descriptor.h + .cpp` | descriptor pool/layout/set, 20KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/PipelineCache.h + .cpp` | pipeline cache, 37KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/RayTracing.h + .cpp` | BLAS/TLAS + RT shaders, 11KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Query.h + .cpp` | occlusion/stats/timestamp queries |
|
||||
| `src/Engine/Graphics/Vulkan/Texture.h + .cpp` | all texture types, 27KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Buffer.h + .cpp` | all buffer types + VMA, 22KB impl |
|
||||
| `src/Engine/Graphics/Vulkan/Allocator.h + .cpp` | VMA memory allocator |
|
||||
| `src/Engine/Graphics/Vulkan/Queue.h + .cpp` | VkQueue wrapper + fence |
|
||||
| `src/Engine/Graphics/Vulkan/Debug.h + .cpp` | Vulkan validation layer callbacks |
|
||||
| `src/Engine/Graphics/Vulkan/Shader.h + .cpp` | VkShaderModule creation |
|
||||
|
||||
## Gotchas & sharp edges
|
||||
|
||||
- The Vulkan backend uses VMA (Vulkan Memory Allocator) for ALL buffer and texture memory. The Allocator wraps a VmaAllocator. You cannot free memory directly — you must go through the allocator's destroy methods. VMA must be compiled and linked (it is a sub-dependency, not in the Seele source tree).
|
||||
- Ray tracing requires VK_KHR_ray_tracing_pipeline AND a physical device that exposes VK_KHR_acceleration_structure. The capability flag rayTracingEnabled is set at init() time based on device extension availability. If RT is not supported, RayTracingPass is never added to the render graph (GameView.cpp line 39: if graphics->supportRayTracing()).
|
||||
- Mesh shading (VK_NV_mesh_shader or VK_EXT_mesh_shader) is detected at init() and sets meshShadingEnabled. If false, Graphics::createGraphicsPipeline(MeshPipelineCreateInfo) will assert/fail. The Vulkan backend must have the extension enabled in VkDeviceCreateInfo.
|
||||
- The command buffer pool in Command.cpp is a per-queue-type (graphics/async/transfer) pool of VkCommandBuffer objects. Each RenderCommand/ComputeCommand checks out a buffer, records, and checks back in. The pool is sized at init() based on the max in-flight frames. If the pool is exhausted, the backend will stall.
|
||||
- Framebuffer creation is PER SWAPCHAIN IMAGE — each VkFramebuffer in Framebuffer.cpp corresponds to one swapchain image. The RenderPass::createRenderPass method creates one framebuffer per image. If the swapchain is resized, all framebuffers are destroyed and recreated (applyArea path).
|
||||
- The Vulkan backend does NOT use the Vulkan Validation Layer in release builds — ENABLE_VALIDATION in Graphics.h (line 7) is a compile-time define that is always on in this codebase. In production you would want to #undef it or make it a build flag.
|
||||
- Queue.cpp wraps a single VkQueue + VkFence. There is ONE fence per queue. waitDeviceIdle() calls vkDeviceWaitIdle on the entire device (all queues). There is no per-queue synchronization primitive exposed through the Gfx::Graphics interface — the backend manages fences internally.
|
||||
- The debug layer (Debug.h/.cpp) installs VK_EXT_debug_utils callbacks at device creation time. All validation layer messages are routed through a single callback that forwards to stderr. There is no UI for viewing validation errors — they go to the console.
|
||||
- Texture.cpp handles mipmap generation via vkCmdGenerateMipmaps. For texture arrays and cubes, the entire array/cube is generated in one call. The texture's initial layout must be TRANSFER_DST_OPTIMAL for this to work — the Texture constructor sets the correct initial layout based on the usage flags in TextureCreateInfo.
|
||||
- The Vulkan backend's Window.cpp handles BOTH X11 (Linux) and Win32 (Windows) natively. On Linux it uses GLFW for window creation + X11 for the surface (glfwCreateWindow + glfwGetX11Window). On Windows it uses Win32 directly (CreateWindow + CreateSwapChainHcu). There is no platform abstraction layer — the #ifdef WIN32 blocks are in the source.
|
||||
- PipelineCache.cpp uses a hash of the pipeline create-info struct + shader SPIR-V bytes as the cache key. If ANY field of the create-info changes (even a padding byte), the cache miss occurs. The cache file is stored next to the executable (or in a user-specified path from GraphicsInitializer).
|
||||
|
||||
---
|
||||
|
||||
*Generated from a full read of the checked-out source at commit `d3ed573`. If a path has moved, `git grep` for the type name — the engine is small enough to find anything in seconds.*
|
||||
@@ -0,0 +1,94 @@
|
||||
# Window & view layer (Window, View, GameView, WindowManager)
|
||||
|
||||
> **Scope:** `src/Engine/Window/` (4 files), `src/Engine/View/` — the OS window + the per-frame
|
||||
> render/update protocol that the whole engine hangs off. This is the "front door" of the frame loop.
|
||||
|
||||
This is the **thinnest** layer of the engine, and the single most important thing to understand for
|
||||
getting a frame to render. Everything else (render graph, systems, UI, physics) is driven from the
|
||||
protocol defined here.
|
||||
|
||||
## Key types & where they live
|
||||
|
||||
| Type | Defined in |
|
||||
|------|------------|
|
||||
| `Window` | `src/Engine/Window/Window.h` (impl `Window.cpp`) |
|
||||
| `WindowManager` | `src/Engine/Window/WindowManager.h` |
|
||||
| `View` | `src/Engine/Window/View.h` (impl `View.cpp`) |
|
||||
| `GameView` | `src/Engine/Window/GameView.h` (impl `GameView.cpp`) — the concrete `View` that drives the render graph |
|
||||
| `WindowCreateInfo` | `src/Engine/Window/Window.h` (the `Window` ctor parameter) |
|
||||
| `Area` / `URect` | `src/Engine/Containers/` + `src/Engine/Math/` (geometry types) |
|
||||
| `InputAction`, `KeyCode`, `MouseButton`, `KeyModifier` | `src/Engine/Platform/` (input enums, see Platform doc) |
|
||||
| `Game` | `src/Engine/Game.h` — the thing `GameView` wraps |
|
||||
|
||||
## The render/update protocol — the frame contract
|
||||
|
||||
`View` (`src/Engine/Window/View.h:9`) defines the **per-frame protocol** that `Window` calls in a
|
||||
fixed order. This is the spine of the whole engine; every system's `update`/`prepare`/`render` slot
|
||||
lands on one of these callbacks:
|
||||
|
||||
| # | Callback | When | What lands here |
|
||||
|---|----------|------|-----------------|
|
||||
| 1 | `beginUpdate()` | before update | pre-frame setup (e.g. reset accumulators) |
|
||||
| 2 | `update()` | the update tick | **all `System::update` calls** (in SystemGraph topological order) |
|
||||
| 3 | `commitUpdate()` | after update | commit the updated world state (meshlets, transforms) to GPU |
|
||||
| 4 | `prepareRender()` | before render | **all `System::prepare` calls** (record command buffers, build render graph) |
|
||||
| 5 | `render()` | the render tick | **all `System::render` calls** (submit passes to the graphics backend) |
|
||||
| 6 | `applyArea(URect)` | on resize | resize swapchain / viewport |
|
||||
|
||||
Input callbacks on the same protocol (fired by the OS window, routed to `View` and on to
|
||||
`GameView` → `Game`/UI):
|
||||
|
||||
- `keyCallback(KeyCode, InputAction, uint32_t modifier)`
|
||||
- `mouseMoveCallback(double x, double y)`, `mouseButtonCallback(MouseButton, InputAction, uint32_t, ...)`
|
||||
- `scrollCallback(double, double)`, `fileCallback(int, const char** paths)` (drop/open files)
|
||||
|
||||
**The golden rule (from AGENTS.md, and it holds):** a system's `update` writes CPU-side state; a
|
||||
system's `prepare`/`render` (and `commitUpdate`) is what touches the GPU. The split between phases is
|
||||
what makes the `SystemGraph` ordering meaningful — do not move GPU work into `update`.
|
||||
|
||||
## How a frame actually flows (concrete)
|
||||
|
||||
```
|
||||
Window::render() (Window.cpp)
|
||||
└─ for each window:
|
||||
view->beginUpdate(); view->update(); view->commitUpdate();
|
||||
view->prepareRender(); view->render();
|
||||
GameView (the View impl)
|
||||
└─ update() → runs SystemGraph (topo order): each System::update(registry, scene)
|
||||
└─ commitUpdate()→ MeshUpdater / FluidUpdater commit meshlet & state changes
|
||||
└─ prepareRender()→ each System::prepare → RenderGraph records passes
|
||||
└─ render() → RenderGraph::execute → Gfx::Graphics submit (Vulkan/Metal)
|
||||
```
|
||||
|
||||
- `WindowManager` (`WindowManager.h`) owns `Array<PWindow>` and a `Gfx::PGraphics`; `addWindow`
|
||||
creates a `Window` (per-OS native surface), `render()` drives the loop, `notifyWindowClosed`
|
||||
handles teardown, `isActive()` is the "should the process keep running" check.
|
||||
- `GameView` is the `View` that a `Game` (the demo's `MeshShadingDemoGame`) produces. It owns the
|
||||
`PSystemGraph` and the `Scene`, and is the **live consumer** of the `Game` protocol
|
||||
(see the [Game interface](game-interface.md) doc and [cross-repo.md](../cross-repo.md)).
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **`applyArea` on resize is the only legal place to resize the swapchain.** Do not create new
|
||||
swapchains inside `render`/`prepareRender`; route through `applyArea` so the render graph's
|
||||
`ResourceHandle`s (which encode the old surface) are invalidated consistently. The render graph
|
||||
auto-invalidation (see [render-graph-and-passes.md](render-graph-and-passes.md)) depends on this.
|
||||
- **`View` is a friend of `Window`** (`friend class Window;` in `View.h`) — the window reaches into
|
||||
the view's internals directly. Do not assume the `View` API is the only way state changes.
|
||||
- **Input callbacks are delivered on the window thread.** If you add UI or a system that consumes
|
||||
input, it must be safe to be called from the frame callback path (i.e. during `update`), not from
|
||||
another thread.
|
||||
- **`Window` is per-OS but `View`/`GameView` are cross-OS.** The OS-specific bits (surface creation,
|
||||
event pump) are isolated in `Window`/the platform layer; the render protocol above is portable.
|
||||
When you touch a platform bug, you almost always want `Window.cpp` + the Platform layer, *not*
|
||||
`GameView`.
|
||||
|
||||
## Where to look
|
||||
|
||||
| What you're doing | Start here |
|
||||
|---|---|
|
||||
| Add a new per-frame phase / change frame order | `src/Engine/Window/View.h` (protocol) + `Window.cpp` (caller) |
|
||||
| Wire a `Game` into the render graph | `src/Engine/Window/GameView.cpp` (the live consumer) + `src/Engine/Game.h` |
|
||||
| Resize / multi-window | `src/Engine/Window/Window.h` `applyArea` + `WindowManager.h` |
|
||||
| Input (mouse/keys/scroll/files) | `src/Engine/Window/View.h` callbacks → `GameView.cpp` → `Game`/UI |
|
||||
| "Why does nothing render after my change" | confirm you didn't move GPU work into `update`; check `GameView.cpp` `prepareRender`/`render` |
|
||||
Reference in new issue
Block a user