Skip to content

Algorithms, data structures and storage

Entity-Component-System storage

The engine models every game object (ship, missile, Bydo, explosion) as an entity: an id with components (Transform, Velocity, Sprite, Collider, Health, NetworkId; in place: ecs/components.hpp, plain data shared by client and server) processed by systems (in place: ecs::ISystem, ecs::Scheduler). Systems run in the order the game registers them, once per fixed step: the order (inputs, movement, collisions, damage, cleanup) is written in one place and is the same on every tick, which keeps the server deterministic.

Approach Iteration Add/remove component Fit
Inheritance tree (GameObject → Ship...) Virtual call per object, scattered memory Impossible at runtime Rigid: a "missile that is also a power-up" needs a new class
Archetype ECS (EnTT groups, flecs, Unity DOTS) Fastest: entities with the same components stored together Moves the entity between tables Most complex to write correctly
Sparse-set ECS (chosen, in place: ecs::SparseSet, ecs::Registry) Fast: each component type is a packed array O(1) add and remove Simple enough to write, test and explain, fast enough for thousands of entities

Sparse set: a dense array holds the components contiguously and a sparse array maps an entity index to its position in the dense array. Removal swaps the last element into the hole, so the dense array stays packed and iteration touches only live data. Iterating entities that own several components walks the smallest pool and checks the others in O(1) (in place: ecs::View; walkthrough in ECS design).

Entity ids (in place: ecs::Entity) are 32 bits: a 24-bit index (up to 16 million entities) and an 8-bit generation. Destroyed indices go to a free list (in place: ecs::EntityAllocator) and come back with a new generation, so a stale id held by a system is detected instead of silently pointing to another entity. The free list is first in, first out: an index is reused only after all the other free ones, which delays the wrap of its 8-bit generation.

Collision detection

Approach Cost per frame Fit
Brute force, every pair O(n²) Fine below a hundred entities, too slow with missile spam
Quadtree O(n log n), rebuilds as things move Good for uneven densities; more code and allocations
Uniform grid (chosen, in place: ecs::CollisionGrid) ≈ O(n) The play area is a fixed rectangle with objects of similar sizes: a fixed grid is the simplest structure with near-linear cost

The grid is the broad phase (candidate pairs); an axis-aligned bounding box test with layer masks is the narrow phase (in place: ecs::find_contacts; enemies ignore enemies, missiles hit only their targets). Masks are tested before boxes, as they cost one AND. Tests compare both phases with brute force on random scenes. The grid reports each pair once without a hash set: two boxes are paired only in the first cell they share (the top-left one of the cells both cover), so the cost stays linear and nothing is allocated once the cells have grown.

Time and simulation

  • Fixed time step with an accumulator (in place: core::FixedTimestep, core::MainLoop): the simulation advances in steps of exactly 1/60 s whatever the frame rate, so movement, cooldowns and spawns never depend on CPU speed (a subject requirement) and the server and clients compute the same thing. A frame longer than 250 ms is capped, so a stall slows the game down instead of triggering hundreds of catch-up steps. Rendering interpolates between steps with the remaining fraction (alpha); without a renderer, the server sleeps until the next step is due.
  • Seeded pseudo-random generator on the server (planned): enemy spawns use a seeded PRNG, so a game can be replayed and tested deterministically.

Concurrency

  • Lock-free SPSC ring buffers (in place: core::SpscQueue) between the network thread and the game thread: one producer, one consumer, a fixed-size array and two atomic indices. No locks, no allocation on the hot path, and the producer never waits on the consumer.
  • Typed event bus (in place: core::EventBus): systems publish events (shmup::ShotFired, ecs::Explosion, ecs::LifeLost) that other subsystems subscribe to, so audio (audio::EventSounds) or visual effects react without gameplay code knowing them (Mediator/Observer pattern, as the subject suggests). Dispatch is immediate and keyed by std::type_index; it runs on the game thread only, so it needs no lock.

Storage

Data Format Why Alternatives
Client and server settings (ports, window size, key bindings, volumes, accessibility options) JSON with nlohmann-json (in place: core::Config, dotted paths, comments allowed, the library stays private to core) Human-readable, editable by hand, nested structures, one header-only library INI (too flat for bindings), YAML (heavier parser, whitespace pitfalls), TOML (good, but one more dependency)
Enemy waves and levels JSON data files (planned) Game designers add waves without recompiling Lua scripts (more power, more integration work), binary formats (not editable)
Sprites and sounds PNG and WAV/OGG files loaded at runtime (planned) Standard formats, editable with any tool Embedding assets in the binary (rebuild for every change)
Live game state In memory only (server) A game lasts minutes; nothing has to survive a restart A database would add latency and failure modes for no benefit

Reliability and constraints (planned)

  • Settings files are written to a temporary file and renamed over the old one, so a crash while saving never leaves a half-written file; unknown or invalid values fall back to defaults instead of aborting.
  • Data files are validated when loaded (types, ranges, required fields) and rejected with a clear log message, never trusted blindly, the same way network input is.
  • Persistent data that would need concurrent access and history (accounts, match history) would move to an embedded database such as SQLite, which adds transactions and crash safety without a server process. The scores and bans of Part 2 do not need it (below).

Scores and bans (Part 2)

The R-Type server keeps two things across its restarts: the best scores, shown in the lobby, and the banned addresses of its admin console.

Data Choice Why Alternatives
Best scores One JSON file of the 10 best, scores.json (in progress: Scoreboard, Aegis2D-Dev/project-rtype#95) 10 small records, one writer (the network thread), read once at start: a file the size of a few hundred bytes, readable and fixable by hand SQLite (transactions and queries for a table of 10 rows: a dependency for nothing), a binary file (not editable, needs its own versioning), memory only (lost at each restart: the ticket asks for the opposite)
Banned addresses One JSON file of addresses, checked at the login (planned: #311) Few entries, written only when an admin bans; a ban is a fact about an address, not a relation to query Firewall rules (iptables, Windows Firewall: stronger, but outside the game and different on each OS), SQLite (same as above), memory only (a restart would lift every ban)

Reliability and constraints

  • Atomic writes: each change writes the whole file to <file>.tmp, which then replaces the old one (core::Config::save(), in place). A crash while writing leaves the old file, never half of each; there is no lock, as one thread writes.
  • Bounded size: the board keeps its 10 best scores and drops the rest, so the file never grows, whatever the number of games. A ban list grows only by admin commands.
  • Validated on read, never trusted: a name breaking the rules of a login, a score that is not a number, a missing array... The file is then reported in the log and the server starts with an empty board, replaced at the next score: a corrupted file is never fatal, nor silently half-read.
  • Written rarely: the board is written only when a score enters it, at the end of a game, not at every point scored; the cost is a few hundred bytes per game.
  • Where: the file is in the folder the server runs from, or where --scores says, so the operator chooses its disk and its backups; .gitignore keeps a run from a clone out of git.