# game.core — the shared contract of SENGOKU TRANCE
Everything every slice of the game agrees on. The screen shape, the rules,
the three duels, the **beat clock**, the event bus, the shared state, and
the scene anchors.
```luau
local ST = require("game.core")
```
A bare dotted identity in the world root. `@world::game.core` does not
resolve.
## Exports
- `ST.VIEW` — the screen is **1080 x 1440, 3:4 portrait**, and `VIEW.band`
divides it into stage / highway / hud strips. Lay out inside your band.
- `ST.WORLD` — the metres: lane positions, the receptor plane, where the
stage is, where each duellist stands, and the fixed gameplay camera.
- `ST.RULES` — judgement windows, damage, scoring, keys, and the measured
latency constants.
- `ST.PALETTE` / `ST.LANE_COLOR` — the blacklight-ukiyo-e colours. Draw
from these so the three duels read as one game.
- `ST.STAGES` / `ST.stage(id)` — the three duels, each with a **fixed BPM**
and a psytrance section map.
- `ST.clock` — the beat clock. `songTime()`, `beat()`, `beatPhase()`,
`beatToTime(beat)`.
- `ST.bus` — `on(topic, fn) -> off`, `emit(topic, payload)`, `clear()`.
`ST.TOPICS` lists the contract topics.
- `ST.state` — the live duel numbers. The conductor writes; everyone reads.
- `ST.anchor(name)` / `ST.clearAnchor(name)` — where a slice hangs its
entities. **No slice edits the scene file.**
- `ST.provide(id, api)` / `ST.need(id)` — the slice registry.
- `ST.lerp`, `ST.clamp`, `ST.color`, `ST.accuracy`, `ST.meanOffset`,
`ST.phaseAt`, `ST.resetDuel`.
## The beat clock — measured, not assumed
The engine **does** report playback position: `audio.voice(id).positionSeconds`.
Measured on this build, over 90 consecutive frames:
| quantity | measured |
|---|---|
| distinct positions in 90 frames | 90 — it advances every frame |
| quantum | **11.6 ms** (steps are exact multiples of 11604 us) |
| frame time | **21.7 ms** — the audio clock is finer than the frame |
| lag behind a wall clock started at `:play()` | **20-23 ms**, steady |
| drift over the window | none measurable |
So the clock is **driven by the engine**, not free-running. But an 11.6 ms
quantum read on a 21.7 ms frame makes notes judder, so `ST.clock` runs a
hybrid: it free-runs on the wall clock between raw samples and re-locks to
every fresh one (nudging 18% a frame, snapping past 80 ms of error). Read
`songTime()` and never `audio.voice()` directly.
`ST.clock.tick(now)` is called once a frame by the scene entrypoint.
**A slice never calls it.**
## Latency, and what we do about it
Input is sampled once a frame, so timing resolution can never beat ±11 ms.
The windows are sized for that: KIWAMI ±45 ms, SHIN ±90 ms, KA ±140 ms.
The residual output latency is measured **from the player** by the
calibration step, which writes `ST.RULES.calibrationSeconds`; the conductor
keeps a running mean offset (`ST.meanOffset()`) so a systematic bias is
visible in data rather than guessed at.
## Notes
- The three tracks are generated **to** the BPM in `ST.STAGES`, never the
other way round. A chart is authored in **beats**; `ST.clock.beatToTime`
resolves it. That is why a chart can never disagree with its track.
- `ST.need(id)` returns nil for a slice that is not built yet. **Always
handle nil** — that is what lets the slices build in parallel.
# game.sound — the music, the mix and the clip library
Everything SENGOKU TRANCE makes a noise with. Three psytrance tracks
sequenced to the exact BPM each stage declares, the shared one-shot library
every other slice reaches for, the crowd bed, the UI kit, and the mix that
keeps them out of each other's way.
```luau
local ST = require("game.core")
local S = ST.need("game.sound") -- nil while this slice is unbuilt; handle it
```
## Exports
| call | what it does |
|---|---|
| `S.startTrack(stageId) -> boolean` | play the stage's track **and bind `ST.clock` to it**. The one call that starts a duel's music. Returns `false` when it fell back to the click track. |
| `S.stopTrack()` | stop the deck and release the clock |
| `S.deck() -> entity?` | the entity carrying the track's `Audio` component |
| `S.playing() -> boolean` | is the deck running right now |
| `S.clip(name) -> AssetRef?` | one clip from the library, or nil |
| `S.play(name, opts?)` | fire a one-shot. `opts = { volume, pitch, gap }` |
| `S.names() -> { string }` | every name the library answers to |
| `S.setBed(on)` | raise or lower the crowd, faded |
| `S.duck(seconds, amount?)` | push the music down for a moment |
| `S.mix()` | the live levels, plus the ducking multiplier |
| `S.setChannel(channel, level)` | `"music"` / `"sfx"` / `"ambient"` / `"voice"` |
`S.play` and `S.clip` take a **library name or an alias**, and an unknown
name is a quiet no-op — a slice that guesses cannot take the game down.
## The library
| group | names |
|---|---|
| judgement | `hit_kiwami` · `hit_shin` · `hit_ka` · `miss` |
| holds | `hold_begin` · `hold_end` |
| the duel | `duel_begin` · `duel_break` · `duel_win` · `duel_lose` · `combo_up` · `warn` |
| the field kit | `ui_move` · `ui_select` · `ui_back` · `ui_start` · `ui_tick` |
| the world | `taiko` · `bell` · `riser` · `impact` · `crowd_roar` · `shakuhachi` |
Aliases that resolve to one of the above: `hit` `kiwami` `shin` `ka`
`perfect` `great` `good` `kuzure` `fail` `click` `hover` `confirm` `select`
`accept` `back` `cancel` `pause` `start` `tick` `metronome` `cheer` `crowd`
`roar` `drum` `gong` `flute` `win` `lose` `begin` `combo` `danger` `sweep`
`boom`.
`ui_tick` is the metronome the **calibration card** should tap against — a
60 ms wooden click with a hard front edge.
## What answers on the bus
Nobody has to call anything. These fire on their own:
| topic | what sounds |
|---|---|
| `sfx { name, volume?, pitch? }` | that clip |
| `note.hit { judgement, combo }` | the matching judgement, plus `combo_up` every tenth |
| `note.miss` | `miss` |
| `hold.begin` / `hold.end` | the hold pair |
| `duel.begin` | `duel_begin` |
| `duel.end { outcome }` | break / win / lose, a crowd roar on a win, and the deck stops |
| `ui.command { action }` | the field kit |
| `phase.change { kind = "drop" }` | the impact |
| `story.line { seconds }` | **ducks the music to 42%** for the length of the line |
The judgement topics are answered directly as well as through `sfx`, so a
hit sounds whether or not the conductor also emits one; a repeat of the
same name inside its `gap` is dropped, so the two paths cannot flam.
## The mix
Nothing sits at the same level as anything else. Master `0.90`; a spoken
line `1.00`, the track `0.68`, the crowd `0.30`, and the field kit quietest
of all, at `0.22`–`0.30` of the sfx channel, so a menu never argues with the
music. Under a `story.line` the track drops to `42%` and walks back up over
1.6 s.
## The tracks — the BPM is the contract
The three records are **sequenced**, not generated: a bank of one-shots
stamped onto a grid derived from the bpm in `ST.STAGES`, section by section,
following the psytrance shape that table declares. That is why a chart
authored in beats and a track rendered from beats cannot disagree.
| stage | bpm | length | measured |
|---|---|---|---|
| okehazama | 142 | 96 s | mean kick offset **+3.8 ms**, sd 9.5 ms; first half +4.2 ms, second half +3.5 ms |
| nagashino | 146 | 108 s | mean **+3.8 ms**, sd 9.4 ms; halves +3.81 / +3.78 ms |
| honnoji | 150 | 120 s | mean **+3.0 ms**, sd 8.2 ms; halves +3.04 / +2.94 ms |
Measured by decoding each finished record and finding the loudest sample
within ±55 ms of every beat of the grid. The constant few milliseconds is
the kick's own attack shape — its peak sits about 4 ms behind its onset —
and the two halves agreeing to a third of a millisecond is what says the
tempo does not drift.
Each record carries a generated, wholly un-rhythmic **atmosphere** under it —
rain in the gorge, gunsmoke, the temple burning — looped seamlessly, read at
two different points for the two sides so the field is decorrelated, and
pulled down to a tenth for the drop.
## Rebuilding the bank
Everything under `/source/audio` is rendered by `bake.luau`. Run it from an
`execute`, **never** from a component or the scene entrypoint: an
`asset.create` made from either writes to the runtime store instead of
`/zero/source` and the clip does not survive a reload.
```
execute { file = "/zero/source/game/sound.module/bake.luau",
args = { what = "library",
taikoSrc = "…", fluteSrc = "…", roarSrc = "…", bedSrc = "…" } }
execute { file = "/zero/source/game/sound.module/bake.luau",
args = { what = "track", stage = "okehazama",
taikoSrc = "…", fluteSrc = "…", atmosSrc = "…" } }
```
The `*Src` arguments point at generated `.soundClip` folders and are all
optional — a synthesised voice stands in for each one, so a failed
generation never leaves the game silent. The noise is a seeded LCG, so a
re-bake is byte-identical.
## Notes
- `mount()` builds one deck, one crowd bed and a ten-slot one-shot pool
under `ST.anchor("Audio")`, and sets the four channel levels. Nothing is
synthesised at mount — the bank is on disk.
- Every clip reference is a **static literal**: a computed `asset.resolve`
on a gameplay path cannot be statically pinned and breaks when the world
is imported elsewhere.
- The crowd bed is `codec = "pcm"`, because an Opus clip loses its first
few milliseconds on decode and a bed that loops would click at the seam.
Loop *points* do nothing on this build, so the bed is authored seamless
end to end and looped by the `Audio` component's own `looping` field.
- One-shots are Opus, which keeps the whole library under a megabyte.
# game.story — staging, camera and voice
The staged beats of Sengoku Trance: the opening that establishes the place,
the beat before and after every duel, the ending, the camera work that
attends to all of it, and every spoken line in the game.
Everything it builds lives under the `Staging` scene anchor. It is the only
slice that moves the camera, and it puts the camera back on the authored
gameplay framing — `ST.resetCamera()` — every time a beat lets go, however
that beat ended.
## Playing a beat
```luau
local Story = ST.need("game.story")
Story.playOpening(function() end) -- the opening
Story.playPre("okehazama", function() end) -- tops a duel; start it in the callback
Story.playPost("okehazama", "break") -- tails a duel
Story.playEnding() -- the ending, perfect-run aware
Story.play("pre:nagashino") -- any beat by id
Story.skip() -- what the skip key does
Story.startCampaign() -- opening → three duels → ending
```
Every entry point takes an `onDone(reason)` callback, called with
`"completed"`, `"skipped"` or `"stopped"`. A beat also announces itself on
the bus, so nothing has to hold a callback to follow along:
| topic | payload | when |
|---|---|---|
| `screen.change` | `{ screen = "story" }` | a beat takes the screen |
| `story.line` | `{ speaker, who, text, voice, seconds }` | each line, as it is delivered |
| `story.done` | `{ beat, reason }` | the beat lets go |
| `screen.change` | `{ screen = <previous> }` | the screen goes back |
Anyone can ask for a beat without reaching for the module:
```luau
ST.bus.emit("story.cue", { beat = "pre", stage = "nagashino" })
ST.bus.emit("story.cue", { beat = "post", stage = "nagashino", outcome = "break" })
```
Story also listens for `duel.end` and tails the duel itself, so a duel is
topped and tailed even when nobody asks — and it answers
`ui.command { action = "start" }` by running the whole campaign, unless the
conductor publishes a `startCampaign` of its own, in which case it stands
back and only serves beats.
## The camera
A beat is one shot per line, framed on whoever is speaking: Nobunaga close,
the rival close and mirrored, the chronicle wide. The framings are
**measured by capture against the real 3:4 viewport**, not derived — a row
of paper lanterns hangs along the front of the stage at head height, so
every close shot stands above the lantern line and looks down across it.
A key light finds the speaker and eases onto them in their own colour, with
a cold rim behind so the figure keeps an edge against the back wall.
## The written form
Every spoken line is printed on a lacquer plate low on the screen, clear of
the letterbox bands, with the speaker's name and kanji over a gold hairline.
That is what makes a line survive a failed generation, a muted player and a
noisy room — the audio can go missing, the line never does.
## What it stands on
- `story.script` — the words, and who says them.
- `story.voice` — the generated audio for them, cached as `.soundClip`.
- `game.core` — `ST.WORLD` for where everything stands, `ST.PALETTE` for
colour, `ST.bus` for talking to the other slices.
# game.warlords — Nobunaga and the three men across the decks
The hero figures of SENGOKU TRANCE. Four of them, built once at scene load
and parked under `ST.anchor("Warlords")`: Oda Nobunaga, who is always on
stage, and the three rivals, one of whom stands opposite him at a time.
```luau
local W = ST.need("game.warlords")
if W then
W.setRival("nagashino") -- a stage id, or a warlord key
W.breakRival() -- the staged collapse, with its own sound
W.restoreRival() -- put him back for a retry
local r = W.report() -- what the slice believes it is showing
end
```
## Who they are, and how to tell them apart at 48 metres
Silhouette first. The gameplay camera never moves, and at that distance a
figure is a shape before it is anything else, so each of the four is a
different shape:
| figure | the shape | accent |
|---|---|---|
| **Nobunaga** | a great gold maedate flaring off a peaked namban helm, a jinbaori falling to the knee, and a set of decks he never takes his hands off | violet |
| **Yoshimoto** | a tall black court eboshi over shoulders twice the width of anybody else's, working a fan | cyan |
| **Katsuyori** | two swept horns and a sashimono standing a full body-height above his back, bringing a sword down on the beat | acid green |
| **Mitsuhide** | the narrowest figure in the game: a hood, and one straight line of naginata beside it | magenta |
They stand at **heroic scale** — about six metres on the stage deck, which
puts them inside the torii opening. That number was tuned by capture against
the real 1080x1440 viewport, not derived: a human-sized figure at 48 m is
about eighty pixels tall and reads as a smudge.
## How a figure is put together
A tree of **pivots** with geometry hung off them. The pivots are what the
dance drives; the geometry never moves on its own. That is the whole
difference between dancing and sliding.
```
WL_<key> root: world position, yaw, heroic scale
└── hips the bob and the weight shift
├── hipL / hipR → kneeL / kneeR
└── torso the lean and the counter-rotation
├── shL / shR → elL / elR arms; props hang off the elbows
├── head → helm the crown comes off in one piece
└── banner / cape lagging cloth
```
Local space: feet at `y = 0`, facing local **-Z**. That is measured, not
assumed — `Transform.lookAtQuat(0,0,0, 0,0,-10)` is the identity quaternion
on this engine, and the gameplay camera sits at -Z from the stage, so a
figure with no yaw looks straight down the highway.
Two rotation conventions the poses depend on, both measured the same way:
- a **limb** hanging along -Y swings **forward** for a positive pitch, and
stands straight up at pitch = pi;
- a **torso or head** tips **backward** for a positive pitch.
So the kick crunches forward (negative), a flinch throws the head back
(positive), and losing slumps forward.
## What it listens to
Everything comes off `ST.bus`; this slice requires nobody.
| topic | what happens |
|---|---|
| `duel.begin` | that stage's rival takes the stage, restored and upright |
| `duel.end` | a `break` outcome runs the collapse |
| `note.spawn` | the rival throws the arm on that side down the lane |
| `note.hit` | the rival flinches, harder for a better judgement; Nobunaga accents |
| `note.miss` | Nobunaga staggers |
| `meter.change` | posture and glow follow RESOLVE and COMPOSURE; zero RESOLVE breaks him |
| `phase.change` | the drop dances at 1.55x the groove, the intro at 0.55x |
| `screen.change` | keeps the right rival on stage outside a duel |
Nothing here needs the conductor to exist. With no track bound, the beat
comes from the slice's own clock at the current stage's BPM, so the figures
dance on the title screen and in an empty scene — a warlord standing still
reads as a broken game, not as a quiet moment.
## The break
RESOLVE reaching zero is the moment the duel is won, so it is **staged, not
faded**: a white flash across the rival's accent surfaces, his helmet leaves
his head on a real arc, the banner goes over, and he goes down through an
arch and a fall in 2.4 seconds. `restoreRival()` puts him back, because a
retry has to start with a man on his feet.
It has its own sound. `wl_break` is synthesised on the CPU with
`audio.encodePcm` — lacquer plates letting go, a helmet on a wooden stage,
and the body behind it — so a failed generation somewhere else can never
make a warlord break in silence. `wl_enter` is the taiko hit under a rising
breath when a rival takes the stage. Both are PCM rather than Opus: an Opus
clip loses its first ~5 ms on decode (#8873) and both of these start on the
transient. The slice also emits the `sfx` topic, so the sound slice can
answer over the top when it wants to.
## The art
`/source/art/warlords/` — nineteen materials, fifteen meshes and two sound
clips, all authored by this slice and addressed by their **folder-qualified
identity** (`art.warlords.wl_gold`, never `wl_gold`).
Every surface carries a little emissive of its own. The scene's own lighting
is near-black and the venue's rig swings between blackout and full laser;
the fiction is UV-reactive pigment under a blacklight, and the effect is
that a warlord is legible at every point in the light show rather than only
the bright half. Each figure owns **one** accent material so its glow can be
driven — beat pulse, damage dim, break flash — without touching anybody
else's surfaces.
Three mesh generators cover what the primitives cannot: a tapered box (every
armour plate and cap), a ribbon swept along an arc (crests, horns, blades)
and a hanging cloth (banners, capes, robes). All flat-shaded on purpose —
this is a woodblock print, not a render test.
`W.authorArt(true)` re-authors the whole art set in place, keeping every
guid; call it after changing a generator.
# game.hud — the authored screens
Every screen the player reads, and the flow between them.
```luau
local hud = ST.need("game.hud")
```
## What it owns
| screen | when |
|---|---|
| title | the game opens here |
| how to play + **calibration** | from the title |
| the in-duel HUD | during a duel, in the bottom band |
| the spoken-line plate | whenever anybody says anything |
| pause | ESC during a duel |
| results | when a duel ends |
| credits | after the last duel |
## Layout
The screen is **1080 x 1440 — 3:4 portrait**. Everything stacks down the tall
axis. The in-duel HUD lives entirely in `ST.VIEW.band.hud` (1210..1440) so it
never touches the highway's protected corridor; the judgement reads as a
colour bar across the top of that band plus one word inside it.
## What it listens to
`screen.change`, `duel.begin`, `duel.end`, `note.hit`, `note.miss`,
`phase.change`, `story.line`, `story.done`.
## What it publishes
`ui.command` with `action` = `start` / `retry` / `next` / `quit` /
`calibrate` / `credits` / `pause` / `resume`, and `sfx` for its own noises.
## The calibration
The card on the how-to screen runs a real synthesised metronome
(`ST.clickTrack`) at 140 BPM, binds **`ST.clock`** to it — the same clock the
conductor judges with — and reads the player's taps against it. Two kicks of
lead-in do not count; the next eight do. The mean of those taps is written
into `ST.RULES.calibrationSeconds`, which the conductor adds to every note
time before judging. A positive value means the player is consistently late
and the game moves toward them.
It refuses to run while a duel is in progress, and releases the clock when it
finishes.
## The spoken lines
Every line the story slice emits on `story.line` is printed here, whether or
not its audio generated. `{ speaker, text, seconds?, voiced? }`; the speaker
picks the plate's accent colour, and `voiced = false` marks the plate so a
missing recording is visible rather than silent.
`M.say(line)` is the direct call if a slice would rather not go through the
bus.
## The look
`ui.theme` is the palette, the type scale and the primitives; `ui.screens`
builds every tree as a pure function of state. Neither touches the engine, so
a screen can be rendered and looked at without playing the game.
# game.conductor — the rules, and the loop
The duel state machine, the judgement, the score, the two meters, and the
campaign. It owns no geometry and no anchor: everything the player *sees*
of the rules is drawn by the highway, the hud, the warlords and the venue,
off the events published here. The loop is correct when nothing is drawing
it.
## The one piece of arithmetic the whole game rests on
```
offset = songTime - (noteTime + ST.RULES.calibrationSeconds)
```
Negative early, positive late, graded against `ST.RULES.window`:
**KIWAMI ±45 ms · SHIN ±90 ms · KA ±140 ms · MISS beyond.**
Measured on this engine, through `input.simulateKeyDown` (the same key
edges a player's fingers produce, read by `input.snapshot()` inside the
conductor's own tick):
| deliberate bias | KIWAMI | SHIN | KA | MISS |
|---|---|---|---|---|
| 0 ms | 20 | 0 | 0 | 2 |
| 65 ms | 0 | 19 | 0 | 1 |
| 120 ms | 0 | 1 | 13 | 7 |
| 260 ms | 0 | 0 | 0 | 14 |
`ST.meanOffset()` over 37 consecutive clean hits read **2.0 ms**.
## The loop, per frame
`tick(dt, songTime)` runs once per engine frame — guarded on
`input.frameId()`, so one judgement pass happens whatever else calls it.
1. **spawn** every note now inside `ST.WORLD.approachSeconds` of the
receptor, as `note.spawn`;
2. **pull** notes into the judgement horizon and retire the finished ones;
3. **beats and phase** — one `beat` per beat, `phase.change` on a section
boundary;
4. **read the keys** — `keys_pressed` / `keys_released` / `keys` from
`input.snapshot()`, mapped to lanes through `ST.RULES.keys`;
5. **judge** each press against the nearest unjudged note in its lane;
6. **holds** — bank one that ran out, or one whose key came up;
7. **reap** anything nothing could still hit;
8. **publish** the meters, and test the three end conditions.
A press with no note under it is **not** punished. A rhythm game that
punishes an extra tap punishes enthusiasm.
### When a note is missed
`ST.RULES.missAfter` is 150 ms and the KA window is 140 ms — ten
milliseconds apart, less than half a frame. Input is sampled once a frame,
so a press genuinely 140 ms late is not *seen* for up to a frame more.
Reaping strictly at 150 ms therefore throws away legitimate KA hits and
misses the player for a note they hit. A note is retired only once no press
arriving this frame could still have been inside its window:
`max(missAfter, window.ka + dt)`.
## Where the music comes from
```luau
ST.need("game.sound").startTrack(stageId) -- the nice path
ST.clickTrack(bpm, seconds) -- the guaranteed one
```
The conductor asks the sound slice first, and **checks that the clock
actually got bound** — a `startTrack` that returns true without binding
`ST.clock` is treated as a failure, because an unbound clock means an
untimed duel. Failing that it synthesises a metronome at the stage's own
tempo, plays it from `ConductorDeck` under the `Fx` anchor, and binds the
clock to that. Either way the clock ends up reading a real playing voice.
In fallback the conductor also answers its own `sfx` topic with four
synthesised one-shots — a bright bell for KIWAMI, duller for SHIN and KA,
a dead thud for a miss — so a judgement is never silent while the sound
slice is still being built. Once `game.sound` answers, those go quiet.
## Beats in, seconds out
A chart is authored in beats (`game.chart`) and resolved **once**, at duel
start, with `ST.clock.beatToTime()` — after the clock has been bound, so
the conversion uses the tempo of the voice that is actually playing. Before
resolving, the conductor compares `ST.clock.bpm` against the stage's own
BPM and **refuses the duel** if they differ, naming both. A chart drifting
against its track is the bug that looks fine in every static check; this is
where it is caught.
## What it publishes
`duel.begin` · `duel.end` · `note.spawn` · `note.hit` · `note.miss` ·
`hold.begin` · `hold.end` · `meter.change` · `phase.change` · `beat` ·
`sfx` — plus three of its own: `lane.press` (a key edge, hit or not, for a
receptor to react to), `duel.cue` (a duel is wanted; the story slice's beat
goes here) and `campaign.done`.
`sfx` payloads carry `name` **and** `judgement`, so the sound slice can key
off either: `hit_kiwami`, `hit_shin`, `hit_ka`, `miss`, `break`, `fall`,
`hold`.
## What it listens to
- `ui.command` — `start` / `retry` / `next` / `quit`.
- `story.done` — a staged beat has finished; the cued duel starts.
## The flow
```
beginCampaign() -> cueDuel(stage 1) -> [story beat] -> startDuel
^ |
| duel.end <----------+
| |
+---- advance() / retry() <---- ui.command
```
`cueDuel` gives the story slice its beat first **if that slice is built**,
waits for `story.done`, and starts the duel anyway after 30 s if that never
comes — a staged beat that never finishes must not wedge the game. With no
story slice it starts immediately.
With **neither** a hud nor a story slice registered, the conductor emits
`screen.change` itself and walks the campaign on its own two seconds after
each duel, so the whole loop is provable with nothing else built. The
moment either slice registers, it stops doing both.
## Outcomes
| outcome | condition |
|---|---|
| `break` | the rival's RESOLVE reached 0 — the duel ends early, in triumph |
| `hold` | the track ended with COMPOSURE above 0 |
| `fall` | COMPOSURE reached 0 |
`duel.end` carries `outcome`, `won`, `score`, `maxCombo`, `accuracy`,
`judgeCounts`, `meanOffset`, `notesTotal` and `notesJudged`.
## Scoring
`ST.RULES.points` per judgement, times a combo multiplier that steps by
0.5 every `comboBonusEvery` (10) and caps at `comboMultiplierMax` (4.0). A
miss resets the combo and the multiplier. A hold that survives past 60% of
its length keeps the combo; anything less drops it.
## Reading the loop from outside
```luau
local c = ST.need("game.conductor")
c.status() -- everything the loop believes, as one flat table
c.upcoming(1, 8) -- the resolved note list, with judgements so far
c.lastResult() -- the duel.end payload of the duel that just ended
c.isPlaying()
```
`status()` reports the clock as well — `songTime`, `rawTime`,
`clockMaxErrorMs`, `clockResyncs` — because a timing complaint is almost
always a clock complaint, and this is where you look first.
# game.highway — the note field
The four lanes, the receptors, the note bodies, and everything that
happens to a note when it is hit, held or missed. It is the surface the
player actually reads, so its whole job is to stay legible while the venue
is at its loudest.
It is driven entirely by `ST.bus` events and by the song time the scene
entrypoint hands to `tick`. It never asks the conductor for anything and it
never touches another slice's entities. Everything it makes hangs under
`ST.anchor("Highway")`.
```luau
local ST = require("game.core")
local highway = ST.need("game.highway") -- nil until this slice mounts
```
## How a note gets on screen
The conductor publishes `note.spawn`; the highway takes a pooled body,
shows it, and moves it every frame to
```
z = (noteTime - songTime) * ST.WORLD.noteSpeed
```
from the receptor plane. Nothing else decides where a note is. A note
leaves on `note.hit`, on `note.miss`, or — as a backstop, if no judgement
ever arrives — once it is `ST.RULES.missAfter + 0.35 s` past its time.
Bodies come from a fixed pool (10 tap slots and 3 hold slots per lane) and
are only claimed once a note's approach window opens, so a chart may
publish its whole note list at `duel.begin` without allocating anything.
## Exports
- `M.mount()` / `M.tick(dt, songTime)` / `M.unmount()` — the slice contract.
- `M.laneX(lane) -> number` — where a lane actually is in world x, **in
screen order**. Lane 1 is the leftmost lane the player sees. Use this,
not `ST.WORLD.laneX` — see "Lane order" below.
- `M.corridor` — the protected volume, in world metres.
- `M.report() -> table` — live counts: notes in flight, pool pressure,
hits, misses, whether the pool has ever starved.
- `M.demo(seconds)` / `M.demoStop()` — run the note field on its own clock
with no conductor, no audio and no play mode. It publishes exactly the
bus events the conductor publishes, so it exercises the real path.
- `M.buildArt() -> boolean` — write the meshes and materials into
`/source/art/highway/`. Already done and committed; `mount` only fills
gaps.
## Bus
Subscribes to `note.spawn`, `note.hit`, `note.miss`, `hold.begin`,
`hold.end`, `duel.begin`.
Publishes `highway.corridor` once at mount, carrying `M.corridor`.
## Lane order
`ST.WORLD.laneX` is written in ascending world x. The gameplay camera looks
down +Z with +Y up, which makes world **-X** the **right** of the screen —
measured, by spawning a marker at `x = -4.5` and capturing it. Drawn
literally, `laneX[1]` therefore lands on the right and the D key would be
the rightmost lane.
The highway draws lane 1 leftmost and takes the world x values in reverse.
`M.laneX(lane)` returns the resolved position; anything that wants to put a
laser, a hand or a light over a lane should ask for it there.
## Legibility
The spec's section 4 is kept by four separate mechanisms, so no single one
failing takes readability with it:
1. **Shape.** One silhouette per lane — lane 1 a *hishi* diamond, lane 2 a
*maru* circle, lane 3 a *kikkō* hexagon, lane 4 a *masu* chamfered
square. A white strobe frame destroys colour; the outline survives it.
2. **Outline.** Every note and receptor carries a gold screen-space
outline. It is drawn whatever is behind the note, at a width that does
not shrink with distance, so a note 20 m up the highway still has a hard
contour.
3. **Ground.** The deck is near-black lacquer and the lane glow is dim, so
the contrast ratio at the receptor stays high whatever the rig does.
4. **The corridor.** `M.corridor` is the box nothing opaque or bright may
enter during play: x ±2.85, y -0.6 to 3.4, z -1.5 to 16.5. The highway
keeps its own geometry inside it too.
A hit and a miss are built to be told apart with no reading at all: a hit
**expands, rises and goes gold**; a miss **contracts, sinks and is the only
red on the highway**, and the missed note itself goes dark red and drops
through the deck.
## Notes
- The art assets in `/source/art/highway/` are generated by the code in
this module and are committed. `asset.create` called from `mount()`
during a scene load does not land, so `M.buildArt()` is the authoring
entry point; `mount` only fills gaps and never depends on the write.
- `mount()` destroys everything under the Highway anchor before rebuilding,
so a scene reload never doubles the track.
- `tintBlend` defaults to 0 and a tint does nothing until it is raised —
but raised to 1 with a white tint it *replaces* the material colour.
Geometry that should wear its material's own colour passes no tint.
# venue
The place SENGOKU TRANCE happens in. This module owns the great torii, the
raised stage and its decks, the backdrop, the crowd, the speaker stacks, the
overhead truss and its moving heads, the lasers, the haze, the lanterns, the
banners, and the beat-reactive light rig that drives all of it. Everything it
builds is parented under the `Venue` scene anchor.
It is also the slice responsible for **not drowning the note highway**. See
"The corridor" below — that is the load-bearing part of this module, not a
footnote.
## Exports
- `M.mount()` — build the venue and its rig. Called once by the scene.
- `M.tick(dt, songTime)` — drive the light show. Called once a frame.
- `M.unmount()` — tear down the emitters and drop the bus subscriptions.
- `M.setStage(stageId)` — put the venue into one of the three rooms
(`"okehazama"` / `"nagashino"` / `"honnoji"`) without waiting for a duel.
Useful for staging shots and for looking at the thing.
- `M.setPhase(kind)` — set the rig's temperament to a section of the track
(`"intro"` / `"groove"` / `"build"` / `"drop"` / `"outro"`). Also moves the
bloom, within a cap.
- `M.report()` — what the rig is right now: stage, weather, phase, and the
count of beams, crowd banks, wash lights, lanterns and emitters.
- `M.corridorReport()` — how many laser samples and how many pieces of
geometry are currently inside the note highway's protected volume. The
requirement is zero, and this is the number that says so.
## Usage
```luau
local ST = require("game.core")
local V = ST.need("game.venue")
if V then
V.setStage("honnoji")
V.setPhase("drop")
print(V.corridorReport().inside) --> 0
end
```
## What drives it
The rig reads `ST.clock.beat()` and derives the beat phase itself, so it
needs no conductor to be alive. When the clock is not bound to a deck — the
title screen, a staged beat, an agent looking at the scene in the editor —
the room keeps dancing at the current stage's own BPM rather than freezing;
a venue that only moves during a duel is a venue almost nobody sees move.
It also listens on four bus topics, all optional:
| topic | what it does |
|---|---|
| `duel.begin` | swaps the room to that duel's look and weather |
| `phase.change` | sets the rig's level and the bloom |
| `note.hit` | kicks the wash and widens the beams, harder for a KIWAMI |
| `note.miss` | a brief stumble in the rig |
## The corridor
The note highway owns a volume and a screen region, and nothing this module
draws may enter either:
- **World box** — x ±2.9 m, y −1.2 … 5.5 m, z −4 … 16.1 m (the receptor
line up to 62% of the way along the highway).
- **Screen rectangle** — the central 47% of the frame's width, from the
bottom edge up to just above the middle. The world box alone is not
enough: a beam thirty metres *behind* the highway still projects straight
down the middle of a 3:4 frame and lands on the lanes as far as the
player's eye is concerned. That was found by capture, not by reasoning.
Every laser is sampled along its length each time it is aimed. A sweep that
would put any sample in either region is refused, and the head holds its last
safe heading. `M.corridorReport()` runs the same test over the whole rig and
answers with counts.
Strobes are the moving heads' own lenses and the stage wash lights — small,
local, and capped. Nothing here writes exposure, clear colour, or a
full-screen flash, so a strobe cannot black out an incoming note. The haze,
the rain, the gunsmoke and the embers are all **additive**: they can wash a
note but they cannot hide one.
## The three rooms
| stage | weather | beams | air |
|---|---|---|---|
| OKEHAZAMA | rain, in curtains either side and behind the stage | cyan / white / violet | cold blue |
| NAGASHINO | gunsmoke walls, a stockade of stakes, muzzle flashes on the beat | acid / gold / white | ochre |
| HONNŌ-JI | the temple roof burning behind the torii, embers, a smoke column | magenta / ember / gold | ember red |
## Notes
- Art lives in `/source/art/venue/` — the `venue_glow` shader behind every
beam, the `venue_air` depth-haze post-process, and the `vn_*` materials.
- The module registers two post-process effects (`bloom`, `vignette`) if the
chain does not already carry them, and one of its own (`venue_air`). It
never removes an effect it did not add.
- Particle emitters spawn their own render entity outside the anchor tree;
`M.unmount()` destroys every one it created.