game-village-politics-backend/docs/architecture.md

193 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Architecture
## Repos and runtime
| Repo | Stack | Local URL |
|---|---|---|
| `game-village-politics-backend` | Laravel 13, PHP 8.4 (`blaxsoftware/laravel:laravel13-php8.4`), MySQL, Redis, Pest, Sanctum, blax-software/laravel-websockets | `server-village.localhost.at`, `ws-server-village.localhost.at` |
| `game-village-politics-frontend` | Nuxt 4, TypeScript, `@blax-software/networking`, `@blax-software/i18n` | `village.localhost.at` |
Docker Compose and Traefik labels follow learn-atc. The `app` container runs nginx and php-fpm, plus supervisor programs for the queue worker, the scheduler, the WS server, and `game:events`.
The frontend builds with `ssr: false` for every target. It is a game behind a login, so SSR buys nothing. One static build then serves both the web and a later Steam wrapper (Electron or Tauri). This is a deliberate deviation from learn-atc, which uses SSR on the web.
## Transport and auth
- Accounts are email + password, with no verification for now. Steam login comes later as a second provider.
- HTTP `POST /api/auth/register|login` returns a Sanctum bearer token. The client stores it and passes it as `getAuthToken` to the WS client. The same flow works inside a Steam wrapper, where cookies across origins would not.
- Everything else runs over WS through native controllers (`<prefix>.<method>`), for example `village.show`, `village.build`, `village.demolish`, `village.cancel`, and `village.staff`.
- Push goes to the owner's sockets with `ws_whisper('village:updated', …)` after the engine processes an event. The client then refetches or patches its state.
## Backend layers
```
app/Game/ pure rules: no Eloquent, no now(), fully unit tested
WorldConfig.php defaults from config/game/* merged with worlds.config
Economy/Production.php rates per resource from buildings, staffing, base trickle
Economy/Population.php food budget, capacity, villagers, worker assignment
Economy/Settle.php stored + rate × elapsed, storage caps, food zero-crossing
Buildings/BuildingRules.php cost, time, workers, output, space, points per level
Buildings/BuildQueue.php builders, next unblocked order
Map/Continent.php K-names of the 100 × 100 continents
Travel/TravelTime.php
Combat/CombatResolver.php
Combat/LootCalculator.php
ConfigLint.php proves the config has no locks (see "No locks")
app/Actions/ use cases: transaction + lockForUpdate + calls into app/Game
app/Engine/ game_events processing and handlers per event type
app/Websocket/Controllers/ thin: validate, authorize, call an Action, return a Resource
app/Models/ Eloquent
```
## Economy
### Resources
There are four resources: wood, clay, iron, and food. Every village gets a base trickle of wood, clay, and iron (`economy.base_production`, for example 5/h each). That trickle ignores staffing. Buildings add to it. Food comes from farms only. Storage caps all four resources.
Rates are constant between events. Any change to a rate settles the village first: it writes the current amounts and `resources_at = now`, then applies the change. Changes to rates include a build finishing, a worker change, levy, troops arriving or leaving, and a food delivery expiring.
### Population
- **Capacity** is a food budget in food/h: `nominal farm output + 24h average of food delivered to this village`. Nominal means the output at full staffing, which avoids a loop between farms, workers, and capacity (see "No locks"). Capacity is TW-like and instant: no growth timer.
- **Upkeep**: every villager eats `upkeep.villager` (for example 1 food/h), and soldiers eat per unit type (for example spear 1, heavy cav 4, noble 10). Foreign support stationed in the village counts against the host's budget.
- **Villagers** fill instantly up to whatever budget soldiers and stationed support leave free. Villagers are the workforce.
- **Training a soldier** turns one villager into that unit and costs resources. The soldier's upkeep takes from the budget, so villagers shrink to match, the same as TW farm space.
- **Levy**: the player can draft workers as militia for a fixed time (world config). Their buildings run understaffed meanwhile, and the militia return to work automatically when the time ends.
### Workers and staffing
- Each building level needs `workers` (config). Villagers are assigned to buildings automatically, highest `priority` first, then evenly. The player sets the priority per building instance.
- Output at staffing ratio `r = staffed / required` is `e^(k·(r−1))`, with `k` from world config (`staffing.k`, default 2.3). Full staffing gives 100% and an empty building gives about 10%, so output never reaches zero.
- Staffing scales resource production, and the HQ's staffing scales build speed.
### Builders
Each village has `builders` (default 2, +1 at the HQ levels listed in world config, for example 10 and 20). All orders share one queue. A free builder takes the first order that is not blocked by an order still running, for example a second upgrade of the same building instance. Build time is scaled by the HQ's level and staffing.
### Starvation
When upkeep exceeds income, food stock drains. The engine computes the exact moment the stock reaches 0 and schedules an event there. At that point a grace timer starts (`starvation.grace`, default 24h). If the village is still in deficit when it runs out, units desert in hourly waves until upkeep fits the budget. The order is foreign support first, then own soldiers from the highest upkeep down, then villagers that are not working on farms. Farm workers never desert. The timer resets as soon as income covers upkeep again.
## Village space
- Each village has a building space budget. The world config sets the default (`village.space`, 50). The village row stores its own `space`, so terrain or specials can change it per village later.
- Each building type takes a fixed `space` from config, for example HQ 9, barracks 6, resource buildings 4, and hiding place 1. The level changes only the look, never the space. A building fits when the space of all buildings plus new buildings still in the queue, plus its own, stays within the budget. The space is reserved when the order is queued.
- There are no tiles and no stored positions. The client draws the village as a low-poly isometric diorama and lays the buildings out itself (HQ in the centre, the rest around it), so where a building stands is presentation, not game state.
- Levels start at 0. Level 0 is a real, primitive state: the HQ is a tent, storage is open ground, and the farm is gatherers. A new instance is built at level 0.
- Multiple instances per type are allowed. `max_per_village` limits types that must stay unique (HQ, rally point, wall). `instance_cost_factor` makes the n-th instance of a type more expensive, so many cheap copies don't beat upgrading.
- Demolishing goes through the build queue. It lowers an instance by one level and refunds `demolish_refund` × that level's cost (default 0.5). Below level 0 the instance is removed and its space is freed.
- The wall takes 0 space: it surrounds the village.
- Each building level is worth `points` (config); a village's points are their sum, kept on the row when an order finishes and shown on the map.
A new village starts with HQ 0, storage 0, and farm 0, plus starting resources from world config.
## No locks
A village may fail through war or bad play, but it must never get stuck. Every lock below has a way out in the rules, and each one marked "lint" is proven by `ConfigLint`, which runs as a Pest test against the default config and every world's overrides.
| Lock | Rule that prevents it |
|---|---|
| No villagers, no food | Farm 0 (gatherers) has nominal output > 0, so capacity is never 0. Villagers fill instantly. Wood, clay, and iron trickle regardless of staffing. |
| Farm, workers, and capacity feeding each other | Capacity uses nominal farm output, not actual output. Farms are staffed before every other building. Lint: each farm level's worker upkeep < its output. |
| Next upgrade costs more than storage holds | Lint: for every building and level, the cost fits the storage cap reachable without that building, and storage's own next level fits its current cap. |
| Building space full | Demolishing is always allowed, costs nothing, and refunds. Core buildings (HQ, one storage, one farm) cannot go below level 0. Lint: the start buildings fit the space, and every type fits next to them. |
| Queue blocked | A free builder skips blocked orders. Every order can be cancelled with a refund. |
| Building requirements | Lint: the requirement graph has no cycles, and every building and level is reachable from the start village. |
| Starvation spiral | Deserters leave in the order foreign support, soldiers, non-farm villagers. Farm workers stay, so food income can't collapse. |
| Foreign support eats the host | The host can send any support home at any time. Foreign support deserts first. |
| Levy never returns | Militia return automatically on a timer. |
| All merchants killed | Merchants are trained at the market like units, so dead merchants can always be replaced. |
| Player loses every village | The player can restart on the same world with a fresh village. |
## Config
`config/game/world.php`, `economy.php`, `buildings.php`, `units.php`, and `combat.php` hold the defaults. `worlds.config` (JSON) overrides any key, the way Die Stämme world settings do: speed, unit speed, morale, night bonus, beginner protection, map size, builders, refund rate, building space, staffing k, starvation grace, noble rules, and so on. `WorldConfig` merges the two and is the only reader.
A building entry looks like this (numbers start TW-like):
```php
'timber_camp' => [
'space' => 4,
'max_per_village' => null,
'max_level' => 30,
'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25],
'build_time' => ['base' => 900, 'factor' => 1.2], // seconds at world speed 1
'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163],
'requires' => ['headquarters' => 1],
],
```
## Data model
| Table | Columns |
|---|---|
| `worlds` | name, slug, config json, started_at, ends_at null |
| `players` | user_id, world_id, name, points. unique(user_id, world_id) |
| `villages` | world_id, player_id null (null = barbarian), name, x, y, space, wood/clay/iron/food decimal(14,4), resources_at datetime(3), villagers, levy_until null, starving_since null, loyalty, loyalty_at, points. unique(world_id, x, y) |
| `buildings` | village_id, type, level, priority (workers are derived on every read) |
| `build_orders` | village_id, building_id null (null = new instance), type, action (build/upgrade/demolish), target_level, cost json, builder null, starts_at null, finishes_at null. Queue order is id order |
| `unit_stacks` | village_id (where they stand), home_village_id (owner), unit, count. unique(village_id, home_village_id, unit) |
| `recruit_orders` | village_id, building_id, unit, count, done, seconds_per_unit, starts_at, finishes_at, game_event_id |
| `food_deliveries` | village_id, amount, delivered_at. Feeds the 24h import average; each row's expiry is an event |
| `movements` | world_id, player_id, type (attack/support/return/trade), mode, origin_id, target_id, units json, merchants, cargo json, catapult_target, rng_seed, sent_at, arrives_at, visible_at, destroyed_at null |
| `tribes`, `tribe_members`, `tribe_relations` | name, tag; player_id, role; tribe_id, other_tribe_id, state (ally/nap/enemy). Arrives in M6 |
| `reports` | player_id, type, payload json, read_at |
| `game_events` | world_id, type, subject_type, subject_id, fire_at datetime(3), processed_at null, attempts. index(processed_at, fire_at) |
## Event engine
Delayed queue jobs give no global order and can fire late or get lost. When an attack and a wall upgrade on the same village fall in the same second, the order decides the result. So:
1. Every timed effect writes a `game_events` row: `type`, `subject`, `fire_at` (datetime(3)), and `processed_at`.
2. The `game:events` worker loops. It takes due rows in `(fire_at, id)` order, locks the subject village, runs the handler, and sets `processed_at`, all in one transaction. When nothing is due, it sleeps until the next `fire_at`, at most 1 s.
3. Every read or action on a village first runs `CatchUp::village($id, now)`, which processes that village's due events inline. A lagging worker therefore never shows stale state, and tests need no worker at all.
Handlers are idempotent per event row: the transaction plus `processed_at` guards against double execution.
## Map
The map is square (`map.size`, default 1000 × 1000) and split into TW-style continents of 100 × 100 for orientation (K55). New players spawn on a ring that moves outward from the center as the world fills. Barbarian villages fill the gaps, grow slowly (world config), and a village whose player has been inactive for too long turns barbarian.
`map.view {world_id, x, y, w, h}` returns the villages in a `w × h` window (at most `map.max_view` per side) centred on `x|y`, kept inside the map; without a centre it opens on the player's first village. Each village comes with its coordinates, continent, name, points, owner (null for barbarians) and whether it is the player's own. The client draws it like the Die Stämme map: a top-down field grid with coordinate rulers and continent lines.
So far (M2 in progress) players spawn on rings of every second field around the centre, and `SeedBarbarians` scatters `map.barbarians.count` barbarian villages with random low building levels within `radius` of the centre, once per world, keeping the inner spawn area free.
## Movements and encounters
Every group on the map is a `movement`: an attack, support, return, or trade caravan (merchants, optionally with an escort). It moves in a straight line at constant speed, so its position at time t is a linear interpolation between origin and target.
### Travel modes
Each movement has a mode, defined in `config/game/movement.php`:
| Mode | Speed | Visibility radius |
|---|---|---|
| sneaky | much slower | 0 (undetectable) |
| cautious | slower | small |
| normal | 1.0 | normal |
| fast | faster | large |
| fighting march | much faster | very large |
The visibility radius decides two things:
- **Warning time**: a target village sees an incoming movement once it is within `visibility radius + village detection radius`. The engine computes that moment and schedules it as an event. A watchtower raises the village's detection radius. A sneaky movement shows up only when it arrives.
- **Encounters**: another group can only engage a movement that comes within that movement's visibility radius.
### Encounters
- When a movement is sent, `EncounterFinder` (a pure function) computes its closest approach to every active movement in its bounding box. If two groups meet within range, an `encounter` event is scheduled at that exact time.
- A soldier group engages every hostile army or caravan it meets. Groups on a return trip never engage, but they can be engaged. Friendly groups (own, tribe, allies) pass each other.
- An encounter is a field battle: `CombatResolver` without wall or morale. The losing group dies. The winners carry on along their original path and schedule, so later encounters don't need recalculating, and the handler skips encounters whose group no longer exists.
- A caught caravan's escort fights first. If the escort loses, the merchants die and the winners take cargo up to their carry capacity. The rest is lost.
- Barbarian ambushes: a caravan has a small chance per hour of being ambushed, depending on its mode (sneaky never). The roll uses a seeded RNG per movement, so tests are deterministic.
### Diplomacy
Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states between them. Until then, every other player is hostile. Hostility is checked at encounter time, not at send time.
## Combat
Combat uses the TW model. Attack strength is split into infantry, cavalry, and archer. Defense is weighted by the attacker's composition. Then the wall bonus applies, plus morale and luck (±25%, from world config). Losses follow `(weaker / stronger)^1.5`. Rams lower the wall before the fight, catapults hit a building after it. All of this lives in `CombatResolver` as a pure function and is tested with fixed luck.