docs: Initialize comprehensive project documentation
Migrates existing GDD and engine design notes from HacknPlan into a new Obsidian vault. This establishes a centralized, version-controlled knowledge base covering engine architecture, game constraints, design decisions, and open questions.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- assets
|
||||
---
|
||||
|
||||
# Assets
|
||||
|
||||
## Handles, not shared pointers
|
||||
|
||||
- Every asset is referenced by a typed `Handle<T>` (index plus generation), **not** `Ref<T>` / `shared_ptr`.
|
||||
- Ownership stays with the `AssetManager`, so it's always clear when an asset is freed.
|
||||
- **Hot reload** swaps the resource behind a handle, and every holder sees the new version automatically.
|
||||
|
||||
## Asset types
|
||||
|
||||
| Type | Source | Loader |
|
||||
|---|---|---|
|
||||
| `Texture` | PNG, JPG | SDL_image → GPU upload |
|
||||
| `Model` | glTF 2.0 (`.glb`/`.gltf`) | cgltf or fastgltf (TBD) |
|
||||
| `AnimationClip` | glTF node animations | same as Model |
|
||||
| `Material` | parameters + textures | glTF material or script data |
|
||||
| `Shader` / `Pipeline` | SPIR-V built from `Assets/Shaders` | see [[Rendering#Shaders]] |
|
||||
| `Font` | TTF | SDL_ttf |
|
||||
| `Sound`, `Music` | WAV, OGG | SDL_mixer |
|
||||
| Script modules | see [[Scripting]] | script backend |
|
||||
|
||||
## Paths
|
||||
|
||||
- Assets resolve relative to `SDL_GetBasePath()/Assets`, which matches the existing post-build copy step.
|
||||
- Saves and settings go to `SDL_GetPrefPath()`.
|
||||
|
||||
## Hot reload (debug builds only)
|
||||
|
||||
- Poll file modification times about twice a second; reload textures, models, shaders, sounds and scripts.
|
||||
- Failed reloads keep the previous version and report the error in the debug UI.
|
||||
|
||||
## Definition databases
|
||||
|
||||
- `DefinitionDB<T>` maps a `StringId` to a definition (`CardDef`, `TowerDef`, `EnemyDef`, …).
|
||||
- Definitions are filled by the script loader (see [[Scripting]]).
|
||||
- Instances store only the ID, so reloaded definitions take effect immediately.
|
||||
|
||||
> [!question] Open
|
||||
> glTF loader choice: cgltf (a single C header, simple) or fastgltf (C++20, faster, needs simdjson). Check nixpkgs availability under the same-version rule. See [[Open Questions]].
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- audio
|
||||
---
|
||||
|
||||
# Audio
|
||||
|
||||
Built on SDL_mixer 3.
|
||||
|
||||
- **Buses:** master, music, sfx, ui. Each has its own volume, saved with settings.
|
||||
- **Voice limiting:** a per-sound maximum of concurrent voices plus a minimum retrigger interval, so twenty towers firing in the same tick don't produce twenty overlapping sounds.
|
||||
- **Pause behaviour:** gameplay sounds follow `SimClock` (paused during planning); UI sounds and music don't.
|
||||
- **Spatialisation:** simple pan and distance attenuation from the camera focus point is enough for a top-down tower defense. Full 3D audio isn't needed.
|
||||
- Sounds and music are `Handle<T>` assets (see [[Assets]]).
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- roadmap
|
||||
---
|
||||
|
||||
# Build Order
|
||||
|
||||
- [ ] **1. Skeleton:** split CMake into `siege_engine` and `siege_deck`; write `Application`, `FrameClock`, `SimClock` and the main loop. `--frames N` keeps working. See [[Main Loop and Time]].
|
||||
- [ ] **2. RenderDevice:** SDL_GPU device and swapchain, the GLSL → SPIR-V build step, clear the screen, ImGui on `imgui_impl_sdlgpu3`. See [[Rendering]].
|
||||
- [ ] **3. Renderer2D:** sprite batch, text, debug overlay.
|
||||
- [ ] **4. SceneRenderer3D:** glTF loading, instanced static meshes, camera, a ground-plane picking ray to a tile.
|
||||
- [ ] **5. Scenes and ECS:** `SceneStack`, `World`, interpolated entities walking a hardcoded lane. See [[Scenes and ECS]].
|
||||
- [ ] **6. Scripting spike:** the same three test items in Lua/Luau and AngelScript, then pick one. See [[Scripting#Decision spike]].
|
||||
- [ ] **7. Content loading:** `DefinitionDB`, one tower and one enemy defined in script. **This completes the vertical slice.**
|
||||
- [ ] **8. Card-hand UI:** input actions, tweens, drag and drop.
|
||||
- [ ] **9. Rigid animation:** glTF node clips plus procedural aim and recoil. See [[Rigid-Part Animation]].
|
||||
- [ ] **10. Polish:** audio, hot reload, debug panels.
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- tooling
|
||||
---
|
||||
|
||||
# Debug and Tooling
|
||||
|
||||
## ImGui layer
|
||||
Debug only; the game UI is built separately on `Renderer2D`. Subsystems register panels:
|
||||
|
||||
- Entity inspector (components per entity)
|
||||
- Simulation controls: pause, single-step, speed
|
||||
- Script console and script error list (see [[Scripting]])
|
||||
- Asset list with hot-reload status (see [[Assets]])
|
||||
- Frame timings and draw and instance counts (see [[Rendering]])
|
||||
- RNG stream states (see [[Randomness]])
|
||||
|
||||
## Logging
|
||||
spdlog with per-subsystem loggers (`engine`, `render`, `script`, `game`) and levels adjustable at runtime.
|
||||
|
||||
## Profiling
|
||||
Scoped CPU timers feed the timings panel. Tracy can be added later if needed.
|
||||
|
||||
## Headless and smoke runs
|
||||
- `--frames N` renders N frames and exits (already supported).
|
||||
- Later: a headless mode with no window that runs the simulation only, for `siege_tests`.
|
||||
@@ -0,0 +1,84 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- architecture
|
||||
---
|
||||
|
||||
# Engine Overview
|
||||
|
||||
## Scope
|
||||
|
||||
The **engine** is game-agnostic. It knows nothing about cards, towers, lanes or waves. It provides:
|
||||
|
||||
- the main loop and time model
|
||||
- windowing and platform services
|
||||
- input, rendering, assets and audio
|
||||
- a script host
|
||||
- scenes and an ECS world
|
||||
- RNG
|
||||
- debug tooling
|
||||
|
||||
The **game** layer defines everything specific to the tower defense deck-builder.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Main[Main.cpp] --> Game
|
||||
Game[Game layer<br/>cards · deck · towers · enemies · lanes · waves · run map] --> Engine
|
||||
Scripts[Content scripts<br/>Assets/Scripts] -. bound via .-> Game
|
||||
Engine[siege_engine<br/>loop · render · assets · audio · input · script host · scenes · ECS] --> Libs
|
||||
Libs[SDL3 · SDL_GPU · SDL_image · SDL_ttf · SDL_mixer · glm · EnTT · ImGui · spdlog]
|
||||
```
|
||||
|
||||
> [!important] Dependency rule
|
||||
> `Engine/` must never include anything from `Game/`. The CMake target split enforces this.
|
||||
|
||||
## Source layout
|
||||
|
||||
```
|
||||
Source/
|
||||
Engine/ static lib `siege_engine`
|
||||
Core/ Log, Assert, Result (std::expected), Id/Handle, StringId
|
||||
Platform/ Window, SDL init, paths (base/pref), file watcher
|
||||
Time/ FrameClock, SimClock, Timer, Tween
|
||||
Input/ InputState, ActionMap
|
||||
Render/ RenderDevice, SceneRenderer3D, Renderer2D, Camera, text
|
||||
Animation/ rigid node clips, animator
|
||||
Assets/ AssetManager, Handle<T>, loaders, hot reload
|
||||
Audio/ AudioSystem (buses, voice limiting)
|
||||
Script/ ScriptHost / backend (language TBD)
|
||||
Scene/ Scene, SceneStack
|
||||
Ecs/ World (entt::registry wrapper), common components
|
||||
Random/ Rng, RngStreams
|
||||
Debug/ ImGui layer, panel registry, script console, profiling
|
||||
Application.h/.cpp
|
||||
Game/ everything specific to siege-deck
|
||||
Main.cpp a few lines: build AppConfig, run the game
|
||||
```
|
||||
|
||||
## CMake targets
|
||||
|
||||
| Target | Kind | Links |
|
||||
|---|---|---|
|
||||
| `siege_engine` | static lib | SDL3 family, glm, EnTT, ImGui, spdlog, script runtime |
|
||||
| `siege_deck` | executable | `siege_engine` + `Game/` |
|
||||
| `siege_tests` (later) | executable | engine + game logic, headless |
|
||||
|
||||
## Principles
|
||||
|
||||
1. **No singletons.** `Application` owns every subsystem and passes an `EngineContext&` to scenes. That keeps code testable and allows a headless run (the existing `--frames N` flag).
|
||||
2. **Handles over shared ownership.** Assets are `Handle<T>` (index plus generation), not `Ref<T>`. See [[Assets]].
|
||||
3. **Instances reference definitions by ID.** A live tower stores a `DefId`, never a copy of its definition, so hot-reloaded content takes effect immediately.
|
||||
4. **Scripts on events, C++ per tick.** See [[Scripting]].
|
||||
5. **Single-threaded by design.** Asynchronous asset loading can come later behind the same API.
|
||||
6. **Recoverable errors are values; fatal ones are exceptions.** Loaders return `std::expected`: a broken asset or script logs an error and falls back, it doesn't crash. Startup failures and broken invariants throw from constructors and are caught once in `main`. See [[Decision Log#Error handling split]].
|
||||
|
||||
## Subsystems
|
||||
- [[Main Loop and Time]]
|
||||
- [[Scenes and ECS]]
|
||||
- [[Rendering]] and [[Rigid-Part Animation]]
|
||||
- [[Assets]]
|
||||
- [[Scripting]]
|
||||
- [[Randomness]]
|
||||
- [[Input]]
|
||||
- [[Audio]]
|
||||
- [[Debug and Tooling]]
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- input
|
||||
---
|
||||
|
||||
# Input
|
||||
|
||||
- **`InputState`:** per frame, it tracks keys (pressed, held, released), the mouse position and buttons, wheel and drag deltas. It's rebuilt from SDL events in `PumpSdlEvents`.
|
||||
- **`ActionMap`:** maps keys and buttons to named actions (`Cancel`, `EndTurn`, `SpeedUp`, `RotateCamera`, …). Rebindable and saved with settings.
|
||||
- **ImGui gating:** when ImGui wants the mouse or keyboard, game input sees nothing.
|
||||
- **Picking helpers:** screen → ray → ground plane. See [[Rendering#Picking]]. Converting a hit to a tile is game code.
|
||||
- **Card drag and drop and hover** are game UI built on `InputState` plus tweens ([[Main Loop and Time#Timers and tweens]]).
|
||||
|
||||
Input runs on `FrameClock`, so it works during the paused planning phase.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- time
|
||||
---
|
||||
|
||||
# Main Loop and Time
|
||||
|
||||
The simulation runs on a **fixed timestep**, and rendering, UI and tweens run at a **variable rate**. This directly supports the phased game (see [[Game Constraints]]).
|
||||
|
||||
## The loop
|
||||
|
||||
```cpp
|
||||
while (running) {
|
||||
frameClock.Tick(); // real dt, clamped to 0.25 s
|
||||
input.BeginFrame(); PumpSdlEvents(); // ImGui sees events first and may capture them
|
||||
|
||||
scenes.Update(frameClock.Dt()); // UI, tweens, card hand, camera: real time
|
||||
|
||||
simClock.Accumulate(frameClock.Dt() * simClock.Speed());
|
||||
int steps = 0;
|
||||
while (simClock.ConsumeStep() && steps++ < kMaxStepsPerFrame) // spiral-of-death guard
|
||||
scenes.FixedUpdate(kSimDt); // 1/60 s: movement, targeting, projectiles, damage
|
||||
|
||||
renderer.BeginFrame();
|
||||
scenes.Render(renderer, simClock.Alpha()); // interpolate between the previous and current transform
|
||||
debugUi.Render();
|
||||
renderer.EndFrame();
|
||||
}
|
||||
```
|
||||
|
||||
## Two clocks
|
||||
|
||||
| Clock | Drives | Pausable | Scaled by game speed |
|
||||
|---|---|---|---|
|
||||
| `FrameClock` | UI, card hand, menus, camera, UI tweens | no | no |
|
||||
| `SimClock` | combat simulation, gameplay tweens | **yes** (speed 0 = planning phase) | **yes** |
|
||||
|
||||
The planning phase is simply `simClock.SetSpeed(0)`. Cards still animate and hover because they run on `FrameClock`.
|
||||
|
||||
## Game speed
|
||||
|
||||
At 1×, 2× or 3× the loop runs **more fixed steps per frame, never bigger ones**. A 3× frame runs three 1/60 s steps, not one 1/20 s step, so fast projectiles can't skip past enemies at high speed.
|
||||
|
||||
`kMaxStepsPerFrame` caps the catch-up work after a stall (window drag, breakpoint). The simulation slows down rather than freezing the frame.
|
||||
|
||||
## Interpolation
|
||||
|
||||
- A `PrevTransform` component is copied from `Transform3D` before each fixed step.
|
||||
- Rendering blends the two with `SimClock::Alpha()`, so motion stays smooth on high-refresh monitors while the simulation runs at 60 Hz.
|
||||
- Entities that teleport (spawns, snaps) reset `PrevTransform` to avoid a one-frame smear.
|
||||
|
||||
## Timers and tweens
|
||||
|
||||
- `Timer` and `TweenSystem` let you choose which clock they run on.
|
||||
- Tweens are engine-level because a deck-builder's feel is mostly tweens: fanning the hand, drawing, cards flying to targets, damage popups.
|
||||
|
||||
Related: [[Scenes and ECS]], [[Rigid-Part Animation]]
|
||||
@@ -0,0 +1,31 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- rng
|
||||
---
|
||||
|
||||
# Randomness
|
||||
|
||||
Goal: **the same seed gives the same run** (map, rewards, deck shuffles) on Linux and Windows. Combat does not need to replay exactly. See [[Game Constraints]].
|
||||
|
||||
## Rng
|
||||
|
||||
- Our own PCG32 (or xoshiro) generator, **plus our own range and float mapping**.
|
||||
- **Never use `std::uniform_int_distribution` or `std::uniform_real_distribution`.** Their output is implementation-defined, so libstdc++ and MSVC produce different values from the same seed. Using them would silently break seed reproducibility across platforms.
|
||||
|
||||
## RngStreams
|
||||
|
||||
Independent named streams are derived from the run seed:
|
||||
|
||||
| Stream | Used for |
|
||||
|---|---|
|
||||
| `map` | run map generation |
|
||||
| `shuffle` | deck shuffles, draws |
|
||||
| `rewards` | card, relic and gold rewards |
|
||||
| `events` | map events, shops |
|
||||
| `combat` | crits, procs, random targets |
|
||||
|
||||
Because the streams are independent, extra combat randomness can't shift which rewards a seed gives.
|
||||
|
||||
- Stream states are saved with the run.
|
||||
- Scripts get RNG only through bound stream accessors; the language's own random function is removed in the sandbox (see [[Scripting]]).
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- rendering
|
||||
---
|
||||
|
||||
# Rendering
|
||||
|
||||
The target is **rigid-part 3D** on **SDL_GPU**, with a 2D overlay for the card hand and HUD. See [[Decision Log#Rigid-part 3D on SDL_GPU]].
|
||||
|
||||
## Layers
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Scene[Scene::Render] --> S3D[SceneRenderer3D]
|
||||
Scene --> R2D[Renderer2D]
|
||||
S3D --> Dev[RenderDevice]
|
||||
R2D --> Dev
|
||||
Dev --> GPU[SDL_GPU → Vulkan / D3D12 / Metal]
|
||||
```
|
||||
|
||||
### RenderDevice
|
||||
A thin wrapper over SDL_GPU: buffers, textures, samplers, pipelines, command buffers, upload staging and per-frame uniform data. Nothing outside `Render/` calls SDL_GPU directly.
|
||||
|
||||
### SceneRenderer3D
|
||||
- **Instanced meshes are required.** The render queue batches by (pipeline, material, mesh) and draws instances.
|
||||
- Lighting: one directional sun with a single shadow map, plus a few point lights.
|
||||
- Materials: PBR-lite or toon (art direction open, see [[Open Questions]]).
|
||||
- Opaque objects are sorted by pipeline and material; transparent objects back to front.
|
||||
|
||||
### Renderer2D
|
||||
- A command-and-sort-key sprite batch: `DrawSprite`, `DrawQuad`, `DrawText`, `DrawLine`.
|
||||
- Used for the card hand, HUD, menus, health bars, range indicators and damage numbers.
|
||||
- Draws after the 3D pass in screen space.
|
||||
|
||||
## Shaders
|
||||
|
||||
SDL_GPU consumes **precompiled bytecode per backend**.
|
||||
|
||||
1. Write GLSL or HLSL in `Assets/Shaders`.
|
||||
2. Compile to SPIR-V at build time with `glslang`.
|
||||
3. Use the **Vulkan backend on both Linux and Windows**.
|
||||
4. Add SDL_shadercross (for DXIL and MSL) only if D3D12 or macOS becomes a target.
|
||||
|
||||
Shaders are hot-reloadable in debug builds (see [[Assets]]).
|
||||
|
||||
## Text and ImGui
|
||||
|
||||
- Text: SDL_ttf 3's GPU text engine (`TTF_CreateGPUTextEngine`), with cached text objects for numbers that change constantly.
|
||||
- ImGui: the `imgui_impl_sdlgpu3` backend.
|
||||
|
||||
## Camera
|
||||
|
||||
- A **fixed-pitch perspective** camera (about 50°) with limited zoom and optional 90° rotation steps. No free orbit: a tower defense must stay readable.
|
||||
- The alternative, an orthographic isometric camera, is noted in [[Open Questions]].
|
||||
|
||||
## Picking
|
||||
|
||||
- **Tiles:** cast a ray from the mouse onto the ground plane (y = 0) and convert the hit to a tile. No physics engine.
|
||||
- **Enemies** (for targeted cards): a ray test against bounding spheres.
|
||||
- **World-space UI** (health bars, range circles): project world positions to the screen and draw them with `Renderer2D`.
|
||||
|
||||
Related: [[Rigid-Part Animation]], [[Assets]]
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- animation
|
||||
---
|
||||
|
||||
# Rigid-Part Animation
|
||||
|
||||
Models are **hierarchies of separate rigid meshes**, with no skinning and no bones. See [[Decision Log#Rigid-part 3D on SDL_GPU]].
|
||||
|
||||
## Two sources of motion
|
||||
|
||||
1. **Authored clips.** glTF supports node (translation, rotation, scale) animation without any skinning. Artists animate parts in Blender (a turret yawing, a barrel recoiling, legs swinging) and export glTF.
|
||||
- The engine samples keyframes for each node, walks the node hierarchy and draws each part as an instance.
|
||||
2. **Procedural overrides.** C++ systems write to named parts *after* the clip is applied, for example turret aim toward the target, hit recoil, idle bob and death tumble.
|
||||
|
||||
## Data
|
||||
|
||||
```cpp
|
||||
struct Model { // asset, see Assets
|
||||
Vector<ModelNode> nodes; // parent index, local bind TRS, optional mesh + material
|
||||
Map<StringId, UInt16> nodeByName;
|
||||
Vector<Handle<AnimationClip>> clips;
|
||||
};
|
||||
|
||||
struct Animator { // component
|
||||
Handle<AnimationClip> clip; float time; float speed; bool loop;
|
||||
Vector<glm::mat4> nodeWorld; // recomputed each frame
|
||||
};
|
||||
```
|
||||
|
||||
## Per-frame order
|
||||
|
||||
1. Advance clip time (on `SimClock` for gameplay entities, so it pauses and speeds up with the simulation).
|
||||
2. Sample clip → local TRS per node.
|
||||
3. Apply procedural overrides by node name.
|
||||
4. Compute world matrices down the hierarchy.
|
||||
5. Push one instance per mesh-bearing node to the [[Rendering]] queue.
|
||||
|
||||
## Later
|
||||
|
||||
- **Vertex animation textures:** if we need thousands of animated enemies.
|
||||
- **Skeletal skinning:** only for a few bosses or heroes, as a separate milestone.
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- ecs
|
||||
---
|
||||
|
||||
# Scenes and ECS
|
||||
|
||||
## Scene stack
|
||||
|
||||
- `SceneStack` supports **push, pop and replace**.
|
||||
- Each scene declares `blocksUpdate` and `blocksRender`.
|
||||
- A pause menu or card-reward overlay on top of Combat blocks Combat's update but not its render.
|
||||
- Scene callbacks: `OnEnter`, `OnExit`, `Update(dt)`, `FixedUpdate(dt)`, `Render(renderer, alpha)`.
|
||||
- Scenes receive an `EngineContext&`; nothing is global.
|
||||
|
||||
Game-side scenes (examples, not engine code): MainMenu, RunMap, Combat, Shop, Reward.
|
||||
|
||||
## World (ECS)
|
||||
|
||||
- **One `World` (an `entt::registry` wrapper) per scene.** Leaving a combat throws its whole world away, which is simpler than cleaning up individual entities.
|
||||
- **Run state is not ECS data.** Deck, relics, gold and map are plain C++ owned by the game and persist across scenes.
|
||||
|
||||
### Engine components
|
||||
|
||||
| Component | Purpose |
|
||||
|---|---|
|
||||
| `Transform3D` | vec3 position, quat rotation, vec3 scale (render space) |
|
||||
| `PrevTransform` | for interpolation, see [[Main Loop and Time]] |
|
||||
| `MeshRenderer` | model and material handles |
|
||||
| `Animator` | rigid clip playback, see [[Rigid-Part Animation]] |
|
||||
| `Tweened` | active tweens on this entity |
|
||||
|
||||
Gameplay components (`Health`, `Tower`, `LaneFollower`, `Targeting`, `StatusEffects`, …) live in `Game/`.
|
||||
|
||||
> [!note] Sim position vs render transform
|
||||
> Gameplay systems write a 2D ground-plane position. A sync step turns it into the `Transform3D` render transform (adding height, facing and bobbing). The simulation never reads `Transform3D`.
|
||||
|
||||
## Events
|
||||
|
||||
- A **queued bus** wraps `entt::dispatcher` and flushes at the end of each fixed step.
|
||||
- Deck-builders stack triggers ("when an enemy dies, draw 1"). Queueing gives a defined resolution order and stops handlers from mutating the world while a system is iterating it.
|
||||
- The engine provides the bus; the game defines the event types and the trigger and effect resolution.
|
||||
|
||||
Related: [[Scripting]] (hooks fire from events)
|
||||
@@ -0,0 +1,103 @@
|
||||
---
|
||||
tags:
|
||||
- engine
|
||||
- scripting
|
||||
status: undecided
|
||||
candidates:
|
||||
- Lua 5.4 / Luau
|
||||
- AngelScript
|
||||
---
|
||||
|
||||
# Scripting
|
||||
|
||||
> [!warning] Language not chosen yet
|
||||
> The shortlist is **Lua (5.4 or Luau)** and **AngelScript**. Keep the boundary language-agnostic until a spike settles it. Don't add a script runtime to CMake before then.
|
||||
|
||||
## The core rule
|
||||
|
||||
**Scripts run on events, never per entity per tick.**
|
||||
|
||||
- **Scripted hooks:** card play, tower placed, hit, kill, wave start, turn start, relic triggers.
|
||||
- **Stays in C++:** movement, targeting scans, projectile integration and damage application.
|
||||
|
||||
Towers are *configured* by scripts (targeting mode, attack stats, an `on_hit` hook) and *executed* by C++ systems.
|
||||
|
||||
## Language-agnostic boundary
|
||||
|
||||
1. **Definitions are C++ structs.** A loader's only job is to fill them in. The rest of the engine never sees a script value.
|
||||
```cpp
|
||||
struct CardDef {
|
||||
StringId id; int cost; TargetSpec target;
|
||||
ScriptHook onPlay; // opaque: a Lua function ref or an asIScriptFunction*
|
||||
};
|
||||
```
|
||||
2. **The game API is defined once in C++** (`PlayContext::DamageArea`, `ApplyStatusArea`, `Draw`, …). Each backend binds the same surface; only the binding code is language-specific.
|
||||
3. **One small backend interface:**
|
||||
```cpp
|
||||
class IScriptBackend {
|
||||
public:
|
||||
virtual ~IScriptBackend() = default;
|
||||
virtual Result<void> LoadModule(const Path& file) = 0; // fills DefinitionDBs
|
||||
virtual void Invoke(ScriptHook hook, PlayContext& ctx, const Tile& tile) = 0;
|
||||
virtual void Reload(const Path& file) = 0;
|
||||
};
|
||||
```
|
||||
Once a language is picked, collapse this into a concrete class. A permanent two-language abstraction isn't worth keeping.
|
||||
|
||||
## Host responsibilities (either language)
|
||||
|
||||
- Sandbox: no file or OS access; randomness only through engine RNG streams (see [[Randomness]]).
|
||||
- Module loading from `Assets/Scripts`.
|
||||
- Errors are caught, logged and shown in the debug UI. A broken script never crashes the game.
|
||||
- Hot reload refills the `DefinitionDB`s (see [[Assets#Definition databases]]).
|
||||
|
||||
## Candidates
|
||||
|
||||
### Lua 5.4 / Luau
|
||||
Lua tables are the data format, so data and behaviour live in one file.
|
||||
```lua
|
||||
--!strict (Luau only)
|
||||
local fireball: Card = {
|
||||
id = "fireball", cost = 2, target = Target.tile(1),
|
||||
on_play = function(ctx: PlayContext, tile: Tile)
|
||||
ctx:damage_area(tile, 1, 12, "fire")
|
||||
ctx:apply_status_area(tile, 1, "burn", 3)
|
||||
end,
|
||||
}
|
||||
return fireball
|
||||
```
|
||||
- **Lua 5.4:** tiny and well known; sol2 bindings; dynamic typing.
|
||||
- **Luau:** gradual static types, a type checker and language server, a built-in sandbox, faster than 5.4. Its C API is close to Lua 5.1's, and sol2 would need adapting. It ships its own CMake build.
|
||||
|
||||
### AngelScript
|
||||
C++-like syntax with static types. C++ functions are registered directly with native calling conventions, so there's very little glue.
|
||||
```cpp
|
||||
class Fireball : ICard {
|
||||
string id() const { return "fireball"; }
|
||||
int cost() const { return 2; }
|
||||
void onPlay(PlayContext@ ctx, const Tile &in tile) {
|
||||
ctx.damageArea(tile, 1, 12, DamageType::Fire);
|
||||
ctx.applyStatusArea(tile, 1, "burn", 3);
|
||||
}
|
||||
}
|
||||
```
|
||||
```cpp
|
||||
engine->RegisterObjectMethod("PlayContext",
|
||||
"void damageArea(const Tile &in, int, int, DamageType)",
|
||||
asMETHOD(PlayContext, DamageArea), asCALL_THISCALL);
|
||||
```
|
||||
- There's no table literal, so pure stat blocks (enemy HP, wave lists) need TOML or JSON, or have to be written as classes.
|
||||
|
||||
## Decision spike
|
||||
|
||||
Implement the same three things in each candidate:
|
||||
|
||||
1. **Fireball card:** a targeted area effect.
|
||||
2. **"When an enemy dies, draw 1" relic:** event subscription.
|
||||
3. **Tower `on_hit` hook:** called at high frequency during a wave.
|
||||
|
||||
Compare authoring ergonomics, lines of binding code, hot-reload behaviour and error messages.
|
||||
|
||||
## Considered and dropped
|
||||
- **C#:** hosting CoreCLR, maintaining an interop layer, reload through `AssemblyLoadContext` and shipping the runtime cost too much for event-only hooks. It would only make sense as the *main game language*, which isn't the goal. See [[Decision Log]].
|
||||
- **Wren, Squirrel, QuickJS/TypeScript, pocketpy, Daslang, WebAssembly, C++ hot-reload DLLs:** reviewed and not shortlisted.
|
||||
Reference in New Issue
Block a user