# RaceSim — the rules of a turf race
The whole of the game's logic, with nothing drawn and nothing scheduled. Every
other piece of the game reads it:
- `RaceDirector.component` steps it every frame and places the horses from it.
- `HorseRaceUI.module` draws the standings, clock and times it produces.
- `Racecourse.sceneModule` and `scenes/main.scene/build.luau` mirror its
`TRACK` numbers so the horses are always on the turf they model.
## The oval
```lua
RaceSim.TRACK = { A = 92, B = 56, WIDTH = 22, RAIL_OUT = 12.4, RAIL_IN = 11.6, SAMPLES = 720 }
```
An ellipse in the XZ plane. Distance is measured in **metres run from the
finish line**, and the finish line sits at `t = 0` — the point of least
curvature, world `(92, 0, 0)` — so the home straight runs along **Z** and the
stands stand outside it at **+X**. A model on the track faces **+Z**.
```lua
RaceSim.pose(distance, lane) -> x, z, yaw, nx, nz
```
`lane` is `-1` (inner) through `1` (outer); `yaw` turns a +Z-facing model down
the track; `nx, nz` is the outward normal, which is how the broadcast camera
finds the outside of the rail. `RaceSim.LENGTH` is the oval's circumference in
metres (about 472).
## The field
`RaceSim.FIELD` is the eight horses: `number`, `name`, coat `body`, `silk` and
`cap` colours, a preferred `style`, and the three hidden parameters
`speed` / `stamina` / `guts` (0–100). Horse 1 is the player's, `ヒカリノサクラ`.
`RaceSim.STYLES` are the four 作戦 — `nige` 逃げ, `senko` 先行, `sashi` 差し,
`oikomi` 追込 — with `STYLE_NAME` and `STYLE_NOTE` for the screen.
## One race
```lua
local race = RaceSim.newRace(plan, career) -- plan overrides horse 1's style
local events = RaceSim.step(race, dt) -- { kind = "lead"|"final"|"drain"|"finish", ... }
local rows = RaceSim.standings(race) -- place, number, name, colour, gap, finished, time
```
`step` is where the race is decided:
- **Pace** — each style keeps its own multiplier through 序盤 / 中盤 / 終盤
(`PACE`, ×0.92 to ×1.09 of the horse's own top speed). Front runners go early,
差し and 追込 keep something for the last stretch.
- **Stamina** — drains with `(v/16)^3`, so a horse that runs faster empties it
sooner; a full tank lasts `38 + 0.62 × stamina` seconds at racing speed. Below
14% the horse fades toward ×0.78 — that is 失速, and it happens in the last
200 m to the horses that were asked too much too early.
- **根性** — every rival within 5 m adds up to ×1.03, scaled by `guts/100` and by
how late the race is, so horses that are level in the straight fight each other
harder than horses alone.
`RaceSim.FINAL` is the last 200 m. `RaceSim.formatTime` writes `m:ss.cc`,
`RaceSim.prize` pays a placing in 万円, `RaceSim.colourOf` / `nameOf` look a
horse up by number.
## Changing the track
Change `A`, `B` and `WIDTH` here and change the same three numbers in
`Racecourse.sceneModule` (it cannot `require` this module — a scene module
compiles in its own environment) and the scene's start gate follows. Everything
else — distances, pace, finish times — works in metres and needs no edit.
# HorseRaceUI
The three ターフヴィクトリー screens — **start**, **in-play HUD**, **result** — as
plain `ui.registerScreen`-ready widget trees. `RaceDirector` is the only caller:
it registers `HorseRaceUI.SCREEN` once and calls `ui.updateScreen(SCREEN, tree)`
whenever its state changes.
The module holds no engine state and no scene code. Each builder is a pure
`state -> widget tree` function, so a tree can also be built from a test with a
hand-written state.
```lua
local HorseRaceUI = require("HorseRaceUI")
ui.registerScreen(HorseRaceUI.SCREEN, HorseRaceUI.buildStart(state), HorseRaceUI.LAYER)
ui.showScreen(HorseRaceUI.SCREEN)
ui.updateScreen(HorseRaceUI.SCREEN, HorseRaceUI.buildHud(state)) -- on state change
```
## API
| Member | What it is |
|--------|------------|
| `HorseRaceUI.SCREEN` | `"horserace"` — the screen name the director registers under |
| `HorseRaceUI.LAYER` | `40` — the layer the director registers it on |
| `HorseRaceUI.buildStart(state)` | title lockup, horse-data card, the four 作戦 cards, START RACE |
| `HorseRaceUI.buildHud(state)` | rank strip, race clock, camera buttons, stamina, commentary, PLAYER tag |
| `HorseRaceUI.buildResult(state)` | gold heading, winning time, eight ranked rows, prize, career, run-again |
Each returns `{ type, style, props, children }` sized to fill the viewport, with
`position = "absolute"` where the reference places a block. Everything lays out
from percentages and flex, so it follows the canvas (`ui.canvas()`) without
relayout code.
## Callback ids
The ids are strings on a node's `props`, delivered to
`RaceDirector:onCallback(id, data)`:
| id | who emits it |
|----|--------------|
| `plan:nige` `plan:senko` `plan:sashi` `plan:oikomi` | the four 作戦 cards on the start screen |
| `start` | the crimson START RACE / レースを開始する button |
| `cam:broadcast` `cam:chase` `cam:overhead` | the 固定 / 追従 / 俯瞰 buttons on the HUD |
| `again` | the もう一度レースする button on the result screen |
## State it reads
`buildStart` reads `plan` (which card is lit) and `result.career` (the career
line, when a previous race left one). `buildHud` reads `rows`, `clock`,
`camera`, `commentary`, `stamina`, `marker`, and `phase` / `countdown` for the
gates-hold numeral. `buildResult` reads `result` and tolerates it being `nil`
(the panel then draws its empty state with the run-again button live).
`result`: `{ rows, winTime, prize, career = { runs, wins, earnings, best }, won }`.
`rows`: eight `{ place, number, name, colour, gap, time, isPlayer }`, leader
first. `marker`: `{ x, y, on }` in screen pixels — the PLAYER tag is placed at
it and disappears when `on` is false.
## Look
Deep-navy translucent panels (`#0d1b2e` family) over the live scene, thin gold
rules (`#c9a227`), cream text (`#f4ead7`), crimson (`#b31528`) as the single
accent: the selected 作戦, the active camera mode, the winner's row and every
primary button. Gold headings and the START RACE lockup are serif (`tinos`);
numerals — the clock, placings and times — are condensed (`anton`); body text
and Japanese are `arimo`. Japanese glyphs fall back to the engine's CJK face.
The galloping-horse silhouettes, the crown, the camera triangles and the
PLAYER tag's triangle are inline `svg` nodes painted in `currentColor`.
# RaceAudio
Every sound the race makes, behind one interface. `RaceDirector` calls it; no
one else needs to know how the mix is wired.
The module owns no geometry. On the first call it spawns its own temporary,
internal audio entities under a `RaceAudioRig` root and attaches an `Audio`
component to each — four looping beds and six one-shots — then finds them by
name ever after, so a second `setup()` rebuilds rather than duplicates and a
scene reload costs one rebuild. Every function is safe to call before `setup`,
and none of them throws: a clip that will not resolve leaves that one voice
silent and is reported, never raised.
## What it exports
| Function | What it does |
|---|---|
| `setup()` | Idempotent. Builds the ten voices once, then settles the mix into whichever state the race is in: the menu bed when nothing runs, the race beds when one does. Every volume it owns is re-asserted, so a second call also undoes drift. |
| `startRace()` | The gates open — the claxon and its crowd roar, hooves away, the race bed under them, the start-screen theme out of the way, and the grandstand swelling. |
| `stop()` | The race is over — race bed, hooves and the caller go quiet, the crowd settles to its between-races level, and the menu bed comes back under the result screen. |
| `setCrowd(level)` | `0..1` excitement, mapped onto the grandstand bed's volume. Recorded even before `setup`, applied as soon as the bed is alive. |
| `sting(kind)` | `"win"` or `"lose"` — the result sting. Any other value is a quiet no-op. |
| `say(text)` | Plays the race-caller reading of a commentary line, if one exists for that text. Otherwise silent. The same line will not retrigger within 2.5 s. |
## Which clip plays where
All clips live in `/zero/source/audio/` and were generated for this game.
| Clip | Used for | Mix |
|---|---|---|
| `race_day_theme` | Start screen and result screen — golden-hour fanfare, strings and brass, 54 s loop | `music` channel, 0.55 |
| `race_bed` | The field running — string ostinato under taiko, 60 s loop | `music` channel, 0.52 |
| `start_gate_claxon` | The gates opening — bell over a crowd roar, 2.5 s one-shot | `sfx`, 0.9 |
| `crowd_bed` | The packed grandstand, 8 s loop, always under everything | `ambient`, 0.10 → 0.72 with `setCrowd` |
| `hooves_turf` | The pack passing — hoofbeats on turf, 4 s loop, races only | `sfx`, 0.5 |
| `sting_win` | First place — brass flourish and a cheer, 4 s | `sfx`, 0.9 |
| `sting_lose` | Anything else — muted trombone and a sigh, 3 s | `sfx`, 0.9 |
| `lines/line_start` · `lines/line_final` · `lines/line_hold` | Race-caller commentary — 「各馬スタートしました!」, 「最後の直線、外から1番が伸びてくる!」, 「そのまま押し切る!」 | `sfx`, 0.9 |
All four looping beds read `seamless` on `clipRef:loopSeam()`, so none of them
ticks at the wrap.
`say` matches a commentary line exactly first, then falls back to a keyword
(`スタートしました`, `最後の直線`, `押し切`) so the director's dynamic lines — the
leader's number, the finishing call — borrow the nearest reading instead of
going silent.
## Adding a line
Drop the clip under `audio/lines/`, resolve it in the `REF` table from its
literal identity, add a voice to `VOICES`, list it in `LINES`, and point the
commentary text at it in `SPEECH`.
One entity per spoken line, on purpose: a voice whose clip is swapped
mid-flight loses the source it was playing, so lines never share one.
Identities are written as literals: a computed `asset.resolve` records nothing
in the world's reference table, so the clip would not travel with the world.