# SecondWind 1.4.8
Health, damage, death and respawn for any multiplayer game, in one component. Give players, enemies and breakable props health with one call, hurt them with another, and choose everything else with a setting: six health displays (a plain HP bar, a regenerating shield, armour, Zelda-style hearts, lives, or downed-then-revive), eight damage types with flames, sparks and numbers every player sees, eight death styles, teams and friendly fire, a kill feed in five looks, traps, and genre presets from shooter to party game, all labelled in a catalog you can filter by genre and visual style. Built on Lifeline (health, bars, numbers) and MatchFlow (countdowns, rounds), and multiplayer-safe.
## Guides
Two guides ship inside the package, so they are in your world as soon as SecondWind is installed:
- **How to add health and damage to my game** (`SecondWind.package/how-to-add-health-and-damage-to-your-game`): what the kit is, which health model to pick and when, how damage carries who caused it, its type and its team (and friendly fire), death and the respawn styles, the events a game can listen to, how it behaves in multiplayer, what to do first, and how barsKit, markersKit, weaponsKit, turretsKit, Trapline, pickupsKit, spawnerKit and aiKit fit with it.
- **Build a small arena game with health bars, hit markers and respawn** (`SecondWind.package/build-a-small-arena-game-with-health-bars-hit-markers-and-respawn`): from an empty world to a multiplayer arena with SecondWind, barsKit and markersKit: players with health and a health bar, training dummies with bars over their heads, lava, spikes and a shock pad, hit markers and damage numbers for whoever lands a hit, death and respawn, and a kill feed. Every step explains why.
Open one with the `guides` tool (`path` = the name in brackets), with `man` in the shell, or from the Docs panel.
## What's new in 1.4.8
- **`HK.base()` hands out the Lifeline SecondWind is built on.** A kit on top of SecondWind (Trapline 1.5.8 is the first) reaches spawn points and the respawn picker through it, so it depends on SecondWind alone and the stack is one line: your kit, then SecondWind, then Lifeline. Nothing else changed.
## What's new in 1.4.7
**MatchFlow brought current and the world moved to the current engine library.** SecondWind now references MatchFlow 1.4.0, the release the other kits around it use, so an install no longer lands two MatchFlow releases side by side. No code in SecondWind changed; its suite runs 108 of 108.
## What's new in 1.4.6
**Each death is heard once on every peer.** On a peer that does not own an entity, `died` and `killed` fired twice: once from the owner's announcement and once more when that peer held the entity for a moment while the owner removed it (death style `remove`), so anything counting deaths on every peer counted each one twice. A death the owner announced is now taken in quietly if this peer runs it too, and a copy of a death this peer announced itself is dropped; both hold for 3 seconds, so a later real death after a handover still fires. Two new tests (108). Found in a two-player arpgKit dungeon, where 10 kills fired 20 `died` events on the second player.
## What's new in 1.4.5
**Dependencies brought current.** Lifeline 1.0.4 and the current MatchFlow, so an install no longer carries older copies of them; no code in SecondWind changed.
## What's new in 1.4.4
**The arena guide plays again in a new world.** It now installs SecondWind and then markersKit, which brings barsKit 1.3.1 with it, instead of installing barsKit 1.4.0 directly: barsKit 1.4.0's own test suite stops a new world's Play (see Known limits). The arena was rebuilt from the guide in a new world on 1.4.3 that way: eight punches take a dummy from 120 to 0, its overhead bar reads 0/120, hit markers and numbers show, and the feed credits the puncher. The how-to guide says what was checked with each kit. No code changed: the kit is 1.4.3's, and its tests are 1.4.3's with the arena guide's install check updated.
## What's new in 1.4.3
**A fresh install plays and publishes, and its tests load the kit the way the kit does.** 1.4.0's test suite loaded the kit as `require("SecondWind")`, a name the editor's strict check refuses, so anyone who installed 1.4.0 into a new world could not press Play or publish: the editor blamed the error on their own content (#22781). 1.4.2 put those two lines back; 1.4.3 finishes the job:
- The suite now reaches the kit with `~.` (`require("~.api")`, `require("~.pool")` and the rest), exactly as every other file in the package does, and finds the files it reads from wherever the package sits, so it runs the same in this world, in a fresh world, and under `/source/deps/` when another kit brought SecondWind. It no longer names the package by its public name or by a fixed `/zero/source/...` path anywhere.
- New tests fail if any file in the package, the suite included, loads the kit by its public name or by an absolute path, if a `~.` name points at something the package doesn't hold, or if the pool stops using SecondWind's own rules (the 1.4.0 merge had rewritten its `~.logic` into a `/source/...` path, which 1.4.2 fixed).
- Checked from ZeroMind, not from a copy: a brand-new world, one install call, Play pressed twice with no errors and no edits, the first example below run as written, and the suite run twice there.
Every call, setting, event, preset, health style, damage type, death style, kill feed look and network channel works as in 1.4.0.
## What's new in 1.4.0
**Health pools for crowds.** `require("SecondWind.pool")` keeps the health of hundreds of units in one table with no component per entity, for RTS armies, swarms and tower-defence waves that one machine already simulates. It takes SecondWind's own rules: armour soak and the damage types that bypass it, the eight damage types, and team checks with friendly fire. `add`, `damage` (returns dealt, died, reason), `heal`, `kill`, `tick` for regeneration, `fraction`, `isAlive`, and `onDeath` and `onDamage` callbacks. A Vitals component costs about 0.05 ms a frame per entity; a pool costs nothing per unit until something hurts or heals it. Everything else is unchanged.
## What's new in 1.3.1
- **No long dashes left in the package.** The comment at the top of each code file used one; those are colons now. The test that checks for them now reads every file in the package, code and tests included, and names the file and line of any it finds. Only comments changed, so nothing behaves differently.
- **The showcase gallery in the Second Wind world shows the kit again.** Its saved scene held every SecondWind component at its default settings: every dummy ran plain hit points and the timed respawn, nameplates and the kill feed showed entity names such as `Model_hearts` and `Death_ragdoll`, and the title sign said v1.2.0. Rebuilding did not fix it: the build set the right values, and the saved components kept their defaults. Removing the 41 entities that carry a SecondWind component and building again created them fresh with the build's settings, and the scene was saved that way. Now each model dummy runs its own model, each death dummy dies its own way, names read "Hearts" or "Ragdoll Kai", the feed reads "Nova burned Instant Kai", and the sign shows the current version. The gallery belongs to this world, not to the package, so a world that installs SecondWind gets the values its own build gives, as before.
- **If your own scene's SecondWind components show default settings after an update** (for example a scene saved with healthKit 1.1.x, before the 1.2.0 rename, which is the likely cause here), do what fixed the gallery: delete the entities your `build.luau` gives SecondWind components to, then save `build.luau` or call `layers.active.asset:build()`. The build creates them again with your settings.
Every call, setting, event, preset and network channel works as in 1.3.0.
## What's new in 1.3.0
- **Install in one call.** `zeromind_install guid=5da0a53c-5953-4adc-80fb-f5afb02f6568` is all a new world needs. It brings Lifeline and MatchFlow with it, and SecondWind now finds them where they land, so the second install call that 1.1.3 to 1.2.0 asked for is gone. Checked in a brand-new world: one call, then the first example below pasted as written, built and played with no errors and nothing blocking a push.
- **Two guides** (see [Guides](#guides)).
- **A preset set on the Rules when it is created now applies in full.** Before, `Rules { preset = "heroShooter" }` in a build gave players the preset's numbers (150 health, a 5 s respawn) but not its model, death style, kill feed look or friendly fire, because the Rules treated its starting preset as already applied; heroShooter players got a plain health bar instead of a shield. Now the Rules applies its starting preset once, on the peer that owns it, and fills only the fields you left at their defaults, so `{ preset = "battleRoyale", friendlyFire = false }` keeps friendly fire off. Changing the preset later (`HK.applyPreset`, `HK.setRules { preset = ... }`) works as before.
- **The kill feed tells two players with the same name apart.** It used to compare names to spot a self-kill, so a player knocking out another player who had the same display name read "X died". It now compares the two entities.
- **README:** Known limits lists only issues that are still open, and the version history is one list.
Every call, setting, event, preset and network channel works as in 1.2.0. Upgrading from 1.2.0 needs no change to your code. A world that followed 1.2.0's two-call install can keep its Lifeline and MatchFlow; nothing needs removing.
## Install and use (five minutes)
1. **Install.** One call: `zeromind_install guid=5da0a53c-5953-4adc-80fb-f5afb02f6568`, or search ZeroMind for "SecondWind" and install `SecondWind.package` from the ZeroMind panel. It brings Lifeline and MatchFlow, the two kits SecondWind is built on, under `/source/deps/`, and SecondWind finds them there. There is nothing else to install. If you add kits built on SecondWind (barsKit, markersKit and the others in the guides), install SecondWind first so they use it rather than bringing a copy of their own.
2. **Set it up in your scene's `build.luau`.** A new world's main scene (or one made with the `player` scene template) builds its player in `build.luau` with a line like `local body = entity.spawn("body", { parent = prototype })`. Add these lines at the end of `content()`, after that player setup:
```lua
local HK = require("SecondWind.api")
-- World rules + on-screen HUD (kill feed, death screen, bars). Rules must be synced.
local rules = entity.spawnSynced("HealthRules")
rules.component.add(HK.RULES, { preset = "heroShooter" }) -- or leave preset empty
entity.spawn("HealthHUD").component.add(asset.resolve("SecondWind.HUD", "component"), {})
-- Players: give the PlayerPrototype's body health. Every joining player gets it.
HK.attach(body, { team = "blue" }) -- `body` from the default player setup
-- A trap: lava that burns anyone standing in it (a 3 x 1 x 3 m box on the ground).
local lava = entity.spawnSynced("Lava", { position = { 0, 0.5, 4 } })
lava.component.add(asset.resolve("SecondWind.Trap", "component"),
{ damageType = "fire", label = "Lava", amount = 15, sizeX = 3, sizeZ = 3 })
-- An orange slab on the ground, so you can see where the lava is.
local glow = entity.spawn("LavaGlow", { position = { 0, 0.05, 4 } })
glow.component.add("Model", { model = "cube", material = asset.resolve("@builtin::materials.plastic_white", "material"),
tintR = 1, tintG = 0.35, tintB = 0.05, tintBlend = 1 })
glow.localScale = { 3, 0.1, 3 }
-- A dummy standing in the edge of the lava: it burns, dies, and comes back where it stood.
local dummy = entity.spawnSynced("Dummy", { position = { 1, 0.5, 4 } })
dummy.component.add("Model", { model = "cube" })
HK.attach(dummy, { model = "hearts", deathStyle = "timed", displayName = "Dummy" })
```
3. **Press Play.** The lava is the orange slab about 4 m in front of where you start, and the dummy stands in its edge. The dummy catches fire, loses its hearts, dies, and comes back where it stood 4 seconds later, then burns again. Walk onto the slab and you catch fire too: flames, damage numbers and BURNING on screen, your shield (75, from the `heroShooter` preset) burning away first and then your health (150). Stay in and you die and come back at the spawn point after the death screen's countdown.
Hurting something from code is one call:
```lua
HK.damage(target, 20, { by = attacker, type = "fire", team = "red" })
```
Switching anything is one setting, even while the game runs:
```lua
HK.setModel(target, "shield") -- or hearts, lives, downed, armor, hitPoints
HK.setDeathStyle(target, "spectate") -- or instant, timed, wave, ragdoll, dissolve, remove, stay
HK.applyPreset("battleRoyale") -- the whole world at once
```
`HK.catalog()` lists everything below, with descriptions and labels.
## Picking from the catalog
Every entry (model, damage type, death style, feed look, preset) carries these labels:
| label | values |
|---|---|
| `kind` | `healthModel`, `damageType`, `deathStyle`, `feedLook`, `preset` |
| `family` | health models: `pool`, `counted`, `secondChance`. Damage types: `direct`, `elemental`, `world`. Death styles: `respawn`, `deathAnimation`, `outOfPlay`. Feed looks: `killFeed`. Presets: `competitive`, `adventure`, `cooperative`, `casual` |
| `genres` | a list from `shooter`, `heroShooter`, `battleRoyale`, `adventure`, `roguelike`, `rpg`, `coop`, `survival`, `platformer`, `party` |
| `hasLook` | `true` when the entry draws something of its own |
| `style` | for entries with a look: `minimal`, `scifi`, `fantasy`, `cartoon`, `pixel` (a preset takes the style of its kill feed look) |
```lua
local HK = require("SecondWind.api")
HK.find({ kind = "preset", genre = "coop" }) -- { coopRevive entry }
HK.find({ kind = "feedLook", style = { "pixel", "cartoon" } }) -- any of the listed values
HK.find({ kind = "healthModel", family = "counted" }) -- hearts, lives
HK.find({ genre = "roguelike" }) -- everything that suits a roguelike
for _, p in HK.find({ kind = "preset", genre = "battleRoyale" }) do
print(p.id, p.family, p.style, table.concat(p.genres, ", "))
end
HK.vocabulary() -- { kinds, families, genres, styles }, each word with a label and description
```
Every key is optional and takes one value or a list (any of them matches). An unknown key or kind is an error that names the valid ones, so a typo never just returns nothing. `SecondWind.catalog` also offers `C.filter(kind, query)` for one kind (a kind id like `"preset"` or a list name like `"presets"`).
## What it offers
### Health models (`model`)
| id | what it does |
|---|---|
| `hitPoints` | One health bar. |
| `shield` | A shield soaks damage first and recharges after `shieldRegenDelay` seconds without a hit. Electric damage does double to shields. |
| `armor` | An armour pool absorbs `armorAbsorb` of each physical, fire, ice, electric or explosion hit and wears down. Poison, fall and environment damage go around it. |
| `hearts` | Zelda-style hearts with half hearts (one half heart = 10 HP). Every hit costs at least half a heart and rounds up to whole half hearts. |
| `lives` | `lives` lives, each with a pool of `lifeHealth`. Emptying a pool spends a life and refills it. Losing the last life is death. |
| `downed` | A lethal hit knocks you down instead. You crawl at reduced speed and bleed out over `bleedOutTime`. A living teammate who stands within `reviveRadius` for `reviveTime` picks you up. |
### Damage types (`type`)
| id | behaviour | looks like |
|---|---|---|
| `physical` | A plain hit. | white sparks |
| `fire` | Keeps burning for a few seconds after the hit. Ice puts it out. | rising flames; burning targets trail embers |
| `poison` | Stacks up to 5. Each stack ticks every second, and a new hit refreshes them. Goes around armour. | poison bubbles; poisoned targets trail bubbles |
| `ice` | Slows the target to half speed for a few seconds. Puts out fire. | ice shards; chilled targets trail frost |
| `electric` | Chains to up to 3 nearby targets at 60% damage. Double damage to shields. | electric sparks and arcs to each chained target |
| `explosion` | Falls off with distance and knocks targets back (`HK.explode`). | an expanding explosion shell |
| `fall` | Taken automatically when landing faster than `Rules.fallSafeSpeed`. Goes around armour. | landing dust |
| `environment` | Lava, spikes, acid: the world itself (`SecondWind.Trap`). Goes around armour. | red spikes |
### Death styles (`deathStyle`)
| id | what happens |
|---|---|
| `instant` | Back at a spawn point straight away. |
| `timed` | Back at a spawn point after `respawnDelay` seconds, with a MatchFlow countdown on screen. |
| `wave` | Everyone who died comes back together on the next wave, every `Rules.waveInterval` seconds. |
| `ragdoll` | The body is flung and tumbles limp, then respawns after `respawnDelay`. |
| `dissolve` | The body sinks and dissolves into sparks, then respawns after `respawnDelay`. |
| `spectate` | Stays dead and watches a living player until the round ends (`HK.endRound()`, a MatchFlow round ending, or `Rules.autoEndRound`). |
| `remove` | Gone for good: for breakable props and one-shot enemies. |
| `stay` | Stays dead until a script calls `HK.revive`. |
### Presets (`preset`)
| id | model | death style | feed | friendly fire |
|---|---|---|---|---|
| `arcadeShooter` | hitPoints | instant | pixel | off |
| `heroShooter` | shield (150 HP + 75 shield) | timed (5 s) | scifi | off |
| `adventureHearts` | hearts (5) | dissolve | fantasy | off |
| `roguelikeLives` | lives (3 × 40 HP) | ragdoll | pixel | off |
| `coopRevive` | downed (20 s bleed-out) | wave | minimal | off |
| `battleRoyale` | armor | spectate | minimal | on |
| `partyBrawl` | hitPoints, huge knockback | ragdoll | cartoon | on |
### Kill feed looks (`feedLook`)
`minimal`, `scifi`, `fantasy`, `cartoon`, `pixel`. Rows read like "Nova burned Kai" or "Kai was killed by Lava".
## Reference
### How settings resolve
For each entity, each value is taken from the first of these that sets it:
1. The entity's own `Vitals` fields. A `model` or `deathStyle` of `auto` means "not set".
2. The entity's own `preset`.
3. For player bodies only: the world `Rules` (`playerModel`, `playerDeathStyle`, and the `preset`'s tuning).
4. For everything else: `hitPoints` and `Rules.otherDeathStyle`.
`HK.config(target)` returns the resolved result. A model switch keeps the current health fraction.
### `SecondWind.api` (`local HK = require("SecondWind.api")`)
Every target argument accepts an entity, a component or an entity id.
| call | what it does |
|---|---|
| `HK.damage(target, amount, opts?) -> ok, reason` | Hurt a target. opts: `by`, `type`, `team`, `origin {x,y,z}`, `knockback` (m/s), `crit`, `dot`, `label` ("Lava"), `ignoreInvulnerability`, `status` (false = no burn/poison/chill). |
| `HK.heal(target, amount, opts?) -> ok, reason` | Restore health. Hearts round up to half hearts. opts: `by`. |
| `HK.kill(target, opts?) -> ok, reason` | Kill outright, skipping lives and downed. opts: `by`, `type`. |
| `HK.base() -> Lifeline` | The Lifeline API SecondWind is built on (spawn points, the respawn picker, the local avatar). A kit built on SecondWind reaches Lifeline through this, so it depends on SecondWind alone. |
| `HK.revive(target, opts?) -> ok, reason` | Pick a downed target up, or respawn a dead one now. |
| `HK.explode(pos, opts?) -> count` | Explosion with falloff and knockback. opts: `radius` (5), `damage` (60), `by`, `team`, `knockback` (10), `minFalloff` (0.2). |
| `HK.attach(entity, settings?) -> Vitals` | Add Lifeline.Health and SecondWind.Vitals with these settings. Use it in a build or on a freshly spawned entity. |
| `HK.configure(target, settings) -> ok, reason` | Change any Vitals settings at runtime. |
| `HK.setModel(target, model)` / `HK.setDeathStyle(target, style)` | Switch one setting. Pass `"auto"` to follow the preset or the rules again. |
| `HK.applyPreset(name, target?)` | With no target, sets the world preset. With a target, sets that entity's own preset. |
| `HK.setRules(t) -> ok, reason` | Change world rules, e.g. `{ friendlyFire = true }`. |
| `HK.endRound()` | End the round: spectators come back. |
| `HK.state(target)` | Snapshot in the terms of its model: `health, maxHealth, fraction, shield, maxShield, armor, maxArmor, hearts, heartsLeft, lives, livesLeft, downed, bleedLeft, reviveProgress, dead, deaths, respawnIn, dyingStyle, burning, poisonStacks, chilled, model, deathStyle, preset, team, name`. |
| `HK.isAlive(target)` / `HK.isDowned(target)` | Booleans. A downed target counts as alive. |
| `HK.config(target)` | The resolved settings (model, deathStyle, preset, all tuning). |
| `HK.get(target)` / `HK.lifeline(target)` / `HK.all()` | The Vitals, the Lifeline.Health underneath, and every Vitals keyed by id. |
| `HK.rules()` / `HK.ruleValues()` | The Rules component, and its values as a table (defaults when there is no Rules entity). |
| `HK.nameOf(target)` / `HK.isPlayer(id)` / `HK.idOf(x)` | Display name, player-body test, and id normaliser. |
| `HK.on(event, fn) -> conn` | Listen to an event on this peer (`"*"` = all). `conn:Disconnect()` stops it. |
| `HK.killFeed()` | Recent kill feed entries on this peer. |
| `HK.setDamageFilter(fn?)` | `fn(vitals, amount, info) -> amount`, run on the owner after team checks. Return 0 to cancel. |
| `HK.catalog()` | Every model, damage type, death style, preset, feed look and event, plus `version` and `vocabulary`. Every entry carries its labels. |
| `HK.find(query?) -> { entry }` | Catalog entries matching labels: `kind`, `family`, `genre`, `style`, `hasLook`, `id`. Each takes one value or a list. |
| `HK.vocabulary()` | The words the labels use: kinds, families per kind, genres and styles. |
| `HK.syncReport()` | How health sync is doing on this peer: `totals` (`sent`, `asked`, `served`, `resyncs`, `snapshots`, `evtSent`, `evtBatched`), the entities this peer `owned` and the ones it `watched` (in sync, seconds off, latest snapshot). |
| `HK.VERSION`, `HK.HEALTH`, `HK.RULES`, `HK.logic` | The version string, the Vitals and Rules component assets, and the pure rules maths. |
### Events (`HK.on`)
`damaged`, `healed`, `blocked` (reason: immune, friendly, self, armor, dead), `lifeLost`, `downed`, `revived`, `died`, `killed` (a kill feed entry: `killer, killerName, victim, victimName, type, text`), `respawned`, `statusApplied`, `chained`, `exploded`, `wave`, `roundEnded`. They fire on every peer.
### `SecondWind.Vitals` component
Settings: `model`, `deathStyle`, `preset`, `team`, `displayName`, `barStyle`, `startFull`, `invulnerable`, `fallDamage`, `canRevive`.
Tuning: `maxHealth` 100, `regenRate` 0, `maxShield` 50, `shieldRegenRate` 20, `shieldRegenDelay` 3, `maxArmor` 50, `armorAbsorb` 0.66, `hearts` 3, `lives` 3, `lifeHealth` 30, `bleedOutTime` 15, `reviveTime` 3, `reviveRadius` 2, `reviveHealth` 0.3, `respawnDelay` 4, `invulnerability` 0.5 (i-frames after a hit), `knockbackScale` 1.
Read-only synced state: `armor`, `livesLeft`, `downed`, `bleedLeft`, `reviveProgress`, `reviver`, `respawnIn`, `dyingStyle`, `burning`, `poisonStacks`, `chilled`, `activeModel`, `activeStyle`, `activePreset`, `hitSeq`, `hitType`, `hitAmount` (the last hit, for its effect), `changeSeq` (bumped on every health change).
Methods: `damage(amount, opts)`, `heal(amount, opts)`, `kill(opts)`, `revive(opts)`.
It needs `Lifeline.Health` on the same entity; `awake` adds it when missing.
### `SecondWind.Rules` component (one per scene, on a synced entity)
`preset` (applied when the Rules starts, to the fields still at their defaults, and again whenever it changes), `friendlyFire` (off), `selfDamage` (on), `playerModel` (hitPoints), `playerDeathStyle` (timed), `otherDeathStyle` (timed), `feedLook` (minimal), `waveInterval` 10, `autoEndRound` (on), `matchEntity` ("Match", a MatchFlow entity whose round end ends the SecondWind round), `maxRemoteDamage` 1000, `fallSafeSpeed` 10, `fallDamagePerSpeed` 7, `allowClientConfig` (off). Read-only: `waveIn`, `waveSeq`, `roundSeq`.
### `SecondWind.HUD` component (per peer, local)
`feedLook` (`rules` follows Rules.feedLook), `showFeed`, `maxFeed` 5, `feedTime` 6, `showDeathScreen`, `showStatus`, `showDownedMarkers`, `countdownStyle` (any MatchFlow countdown style; default `bold`), `spectateSwitch` 8, `addLifelineHUD`, `autoBarStyle`. Method: `nextTarget()` switches the spectated player.
### `SecondWind.Trap` component
A box volume that hurts what enters it: `damageType`, `label`, `amount`, `mode` (`perSecond` | `onEnter`), `interval`, `sizeX/Y/Z`, `knockback`, `team`, `by`, `playersOnly`, `active`. It runs on the authority of each victim, so put it on any entity, synced or not.
### Other modules
- `SecondWind.catalog`: the data behind `HK.catalog()`.
- `SecondWind.logic`: pure maths (pools, armour and shield split, falloff, fall damage, team rule, feed text).
- `SecondWind.feed`: `render(look, entries, opts)` for your own UI.
- `SecondWind.fx`: `burst(type, pos, amount)` hit effects.
### Multiplayer
- **Authority:** each health is owned by the peer that owns its entity. A player's body belongs to that player, and synced world entities belong to the host. Only the owner changes health. All state is synced fields, so every peer sees the same health, deaths and respawns.
- **Remote calls:** `HK.damage` on a target you don't own sends a request to its owner. The owner checks that you own the attacker you named, applies team and friendly-fire rules, and caps the amount at `maxRemoteDamage`.
- **Admin calls:** `configure`, `kill`, `revive` and `endRound` from another peer are refused unless that peer owns the Rules entity or `allowClientConfig` is on.
- **Events:** effects and events run on every peer. Events for other peers leave in batches on `healthKit:evts`, at most one message every 0.05 s, in the order they were raised; `healthKit:evt` messages from 1.1.0 peers are still received. Hit effects are drawn on the next frame from a queue, and each hit is drawn once per peer however it arrives (event or synced `hitSeq`).
- **State snapshots:** the owner sends the full health state on the `healthKit:state` channel. It sends right away on every death, respawn, revive, life lost and knock-down, then again after 0.5 s and 2 s. It also sends after changes (at most once a second for players, every 3 s for others) and every 5 s regardless. Snapshots are batched, about 2 to 3 messages a second for a busy scene. A peer whose fields disagree with the last snapshot for over 0.5 s asks for a fresh one on `healthKit:resync`. All the kit's channels are registered when the kit loads; you do not call them yourself.
### Tests
The `SecondWind.secondwind` test suite has 108 tests covering every public call: catalog labels and filtering, hit effects reaching peers, fall damage around death and respawn, health sync, event batching, the README's install step and first example, the package description, the 1.2.0 rename (new names, same guid, no old requires left, channels kept), and 1.3.0's starting preset, kill feed and guides (both guides ship in the package, the arena guide's settings exist on the components it sets them on, and no long dash in any file of the package, code included), the 1.4.0 health pools, and 1.4.3's checks that every file, the suite included, loads the kit with `~.` from wherever the package sits. Run it with `tools.use("tests", "run", { suite = "secondwind" })`.
## Known limits
These are the open issues that still touch SecondWind:
- **barsKit 1.4.0 installed on its own stops a new world's Play** (#22781 again). Its test suite loads SecondWind by a long `deps.` name that does not resolve once SecondWind sits at the top of the world, and when barsKit is installed alone its looks module's long `deps.` name for Lifeline does not resolve either. This is in barsKit, not SecondWind: forced past the error, its bars read SecondWind 1.4.3 health correctly. markersKit brings barsKit 1.3.1 with it, which plays, so the arena guide installs SecondWind and then markersKit.
- **#22781: an error in an installed package's tests stops the installing world's Play** (and its publish), and the editor reports it as the world's own content. That is how 1.4.0's test suite stopped fresh installs. 1.4.3's suite passes the strict check wherever it is installed, and its own tests fail if a file loads the kit in a way that could break this again. If you change the suite in your copy, keep its requires on `~.`.
- **#19258: ZeroMind's description of SecondWind can lag one release behind** for a while after a release is pushed. The package itself, this README and `package.yaml` are current.
- **Message rate.** Lifeline, which the kit builds on and does not change, sends one `lifeline:evt` message for every hit, so the owner of many bodies taking damage at once still sends at least one message per hit. A peer with a low frame rate, such as a browser tab at 10 to 15 fps, drains those messages slowly, and everything sent after them waits behind them. The kit's own events are batched. Keep the number of bodies taking damage at the same moment modest, or only run them near players, as the showcase gallery does.
- **#20750: frame rate in a web browser.** The kit uses only cross-platform engine APIs. The first example works in a browser tab (checked with a person on 1.1.2's code: the lava set the player on fire, the bar dropped and the dummy took damage), but plays choppily there, even in that small scene. On the native engine the same scene runs at about 19 ms a frame, of which the kit's components take about 0.5 ms; most of the rest is UI drawing, the built-in character controller and rendering.
- **#20946: the web build can't be checked from an agent's engine.** 1.3.0 was checked on the native engine only. The earlier browser checks (1.1.0 to 1.1.2) were done live with a person in a browser tab.
- **#14448: two engines signed in to one account collide as one player.** Test two players with two accounts. 1.3.0's two-player check ran in one engine, with a second player body beside the real one: one player knocked the other out, the kill feed credited the right player, the respawn came 3 s later at a spawn point with full health and shield, and in 23 samples the owner's health and shield matched the synced values every other peer reads.
- **Tower freeze, seen once in a browser.** During a two-player test, a player in a web browser walked off the gallery's JUMP OFF platform and stayed hanging in the air, unable to move, until knocked out. It was not reproduced on the native engine, where the same walk falls and takes fall damage. Nothing in the kit was found to cause it: the kit only moves a player's body when it respawns.
## Version history
- **1.4.6**: `died` and `killed` are heard once per death on every peer, not twice on peers that briefly hold a dying entity; two new tests (108).
- **1.4.5**: Lifeline 1.0.4 and the current MatchFlow; no code changed.
- **1.4.4**: The arena guide installs SecondWind and then markersKit (which brings barsKit 1.3.1) instead of barsKit 1.4.0, whose own test suite stops a new world's Play; the how-to guide and Known limits say what was checked with each kit on 1.4.3. No code change.
- **1.4.3**: The test suite loads the kit with `~.` like the rest of the package and reads its files from wherever the package sits, so a fresh install plays, publishes and passes its tests (checked from ZeroMind in a new world, Play twice, the suite twice); five new tests guard every file's loads, the pool's rules and the version (106). README Known limits names only open issues; the how-to guide covers health pools; the package description and the world listing name the version.
- **1.4.2**: `SecondWind.pool` requires `~.logic` again (the 1.4.0 merge had rewritten it to a `/source/...` path, so the pool failed wherever SecondWind is installed as a dependency); the suite's catalog and pool requires restored the same way.
- **1.4.0**: `SecondWind.pool`, health for crowds with no component per entity (see What's new in 1.4.0). Four new tests (101).
- **1.3.1**: No long dashes in any file of the package, and the test for them reads the code too; the showcase gallery in the Second Wind world rebuilt so every dummy shows its own model, death style and name, and the sign the current version. No change to how the kit behaves. See [What's new in 1.3.1](#whats-new-in-131).
- **1.3.0**: One-call install; two guides in the package; a preset set on the Rules when it is created applies its model, death style, feed look and friendly fire; the kill feed tells two players with the same name apart; Known limits lists only open issues. See [What's new in 1.3.0](#whats-new-in-130).
- **1.2.0**: healthKit became **SecondWind**, with the same guid (`5da0a53c-5953-4adc-80fb-f5afb02f6568`). The require line is `local HK = require("SecondWind.api")`; the components are `SecondWind.Vitals`, `SecondWind.Rules`, `SecondWind.HUD` and `SecondWind.Trap`, the modules `SecondWind.catalog`, `SecondWind.logic`, `SecondWind.feed` and `SecondWind.fx`, and the test suite `secondwind`. Upgrading from 1.1.x: change `healthKit.` to `SecondWind.` in your `require` and `asset.resolve` lines. The network channels (`healthKit:evts`, `healthKit:state` and the rest) and the HUD's screen id `healthkit_hud` kept their names, so nothing on the wire changed. The package description became a store listing.
- **1.1.4**: The first example works as pasted: its dummy stands in the edge of the lava, on the ground, and an orange slab shows where the lava is. The world opens in the gallery again. The package description counts eight death styles and names `Vitals`.
- **1.1.3**: Step 1 became two install calls, as a workaround for an engine install problem that has since been fixed; 1.3.0 goes back to one call.
- **1.1.2**: Step 1 named Lifeline and MatchFlow as installs of their own (also a workaround, also gone in 1.3.0). Tests for the install instructions.
- **1.1.1**: Events for other peers leave in batches (one `healthKit:evts` message per 0.05 s, in order); `HK.syncReport().totals` counts `evtSent` and `evtBatched`. A lighter showcase gallery: dummies and damage stations only run near a player, and the host sends about 12 to 14 messages a second instead of about 46.
- **1.1.0**: A labelled catalog (`HK.find`, `HK.vocabulary`); hit effects drawn on every player's screen, also from the synced `hitSeq`, `hitType` and `hitAmount`; full health snapshots on every death, respawn, revive, life lost and knock-down, with resyncs; fall tracking reset on death and respawn, so a fall death no longer charges a second fall hit; gallery dummies without a `{PlayerName}` placeholder.
- **1.0.0**: First release: six health models, eight damage types, eight death styles, teams and friendly fire, a kill feed in five looks, traps and genre presets.
# MatchFlow 1.4.3
**The match loop every multiplayer game needs, as one component.** One call puts a match in your scene, and the world runs:
```
waiting for players → lobby countdown → 3-2-1-GO → round with timer → results → break → next round
```
One machine is in charge, so every player sees the same countdown, clock, round end and results at the same moment, and when that machine's player quits, the match carries on for everyone else on the same clock and scores. Eight match formats sit behind one field. Ten countdown styles with their own 3-2-1-GO sounds, four results screens, seven in-round HUD layouts, a lobby panel and a king-of-the-hill zone with five looks are each one field away, and every style carries tags so a game can list and filter them.
**matchFlowKit is this package.** matchFlowKit is the name it was first asked for. It ships as **MatchFlow** and keeps that name because other kits already install it and reach it by that name: scoreKit, spawnerKit, SecondWind, pickupsKit and others load `~MatchFlow.*`, and renaming the package would break every one of them. One package, one name; searching ZeroMind for either "MatchFlow" or "matchFlowKit" finds it.
## Guides
Two guides ship inside this package, in `MatchFlow.package/guides/`, and install with it:
- **[How to add rounds, a countdown and a scoreboard to my game](MatchFlow.package/guides/how-to-add-rounds-a-countdown-and-a-scoreboard-to-my-game)**: the how-to. Starting a match, rounds and win conditions in each format, scoring and teams, the hill zone, picking a HUD layout, countdown and results styles, and what players see when the host leaves.
- **[A best-of-three arena match with a countdown, live scores and a results screen](MatchFlow.package/guides/best-of-three-arena-match-with-countdown-live-scores-and-results-screen)**: the example. A brand-new world becomes a best-of-three match with a countdown before each round, live scores, score bars from barsKit, and a results screen and Victory or Game Over screen from menusKit. MatchFlow needs neither kit; the example adds them.
Open one with the `guides` tool by the path in its link (`MatchFlow.package/guides/<name>`). In the editor's Docs panel they are listed under MatchFlow and open by their full name, `MatchFlow.guides.<name>`.
## First example
Install the package from ZeroMind (search "MatchFlow match flow kit"). It lands at `/source/MatchFlow.package`. A brand-new world already has a scene with a ground and a player: open `scenes/main.scene/build.luau` and add these two lines at the end of its `content()` function, just before its final `end`:
```lua
local MatchFlow = require("MatchFlow.api")
MatchFlow { format = "timed", seconds = 30, minPlayers = 1 }
```
Press **Play**. A five-second "Starting in" lobby counts down, then a bold 3-2-1-GO with sound, a 30-second round timer with the scoreboard, a podium, a five-second break, and the next round. Every score is 0 until your game reports some (see "Hooking your game in"). Leave out `minPlayers = 1` and the match waits for two players, which is the default.
`MatchFlow { ... }` spawns the synced `Match` entity with a MatchFlow component set from the table, and returns the component. Every field below can go in the table, and `name` names the entity (default `Match`). From inside another package, require it as `"~MatchFlow.api"`.
**Edit it freely.** Change `30` to `45` (or any field) and save: the scene rebuilds and the match updates, on every machine, and a machine that opens the world later loads the new numbers too. Inside a scene's `content()`, `MatchFlow { ... }` always makes the match itself, so the scene's build owns it and keeps it, under the same id, from one rebuild to the next. Called from an ordinary script instead (outside a build), it finds a match already in the scene by that name and updates its fields rather than adding a second one.
To switch the match type, change one field: `format = "firstToScore"`, `"bestOf"`, `"lastStanding"`, and so on. The screens are restyled the same way:
```lua
MatchFlow {
format = "bestOf", rounds = 3, targetScore = 5,
countdownStyle = "trafficLight", resultsScreen = "recap", hudLayout = "scoreBug",
resultsLook = "cartoon", hudLook = "cartoon", lobbyLook = "cartoon",
}
```
The component works without the front door too: `entity.spawnSynced("Match").component.add("MatchFlow", { format = "timed", roundSeconds = 30 })`.
## Hooking your game in
Get the component from any script, report what happens, and listen for what changes:
```lua
local m = require("MatchFlow.api").find() -- the MatchFlow on the entity named "Match"
-- report (call from any machine; non-authority calls are forwarded to the one in charge)
m:addScore(avatar, 1) -- who = peer id, an entity (its owner is the player) or nil for "me"
m:knockOut(victimAvatar) -- lastStanding, or a player going down in waves
m:finish(avatar) -- race: crossing the line
m:clearWave() -- waves: the team cleared a wave
m:endTurn() -- turnBased: the local player ends their turn early
m:setOnHill(avatar, true) -- kingOfTheHill: only needed without a Hill zone (see below)
-- listen
m.events.onStateChanged:connect(function(e) print(e.previous, "->", e.phase) end)
m.events.onRoundEnded:connect(function(e) print("round", e.round, "won by", e.winnerName, e.outcome) end)
m.events.onMatchEnded:connect(function(e) print("match won by", e.winnerName) end)
m.events.onCountdown:connect(function(e) if e.n == 0 then unfreezePlayers() end end)
```
A typical game spawns its pickups, enemies or checkpoints only while `m:getPhase() == "playing"`, and only on the machine where `m:isAuthority()` is true. The example `game/OrbRush.component` in this kit's world does exactly that in about 100 lines: synced orbs, and `m:addScore(body, 1)` on pickup.
A score reported outside `playing`, or for a player who is out or watching, is ignored. You don't need to guard your calls.
## Holding the match (a ready check)
`m:setHold(true)` keeps the match in the waiting room however many players are in. `m:setHold(false)` lets it go: the lobby counts down `lobbySeconds` and the round begins as usual. Holding again while that countdown runs stops it and goes back to waiting, which is how a ready check works: hold while anyone is not ready.
```lua
local m = require("MatchFlow.api").find()
m:setHold(true, "Waiting for everyone to be ready") -- any machine; the one in charge applies it
-- ... later, when everyone pressed Ready:
m:setHold(false)
```
A hold never interrupts a round being played. A match that has ended and is held waits at the end of its break and goes back to waiting with fresh scores instead of starting the next match. `start()` starts regardless of a hold. A kit that draws its own lobby sets `showLobby = false` (and `showHud = false` if it draws its own scoreboard), so MatchFlow's waiting panel steps aside while its HUD, countdown and results still show. lobbyKit's ready check is built this way.
## Waves with breaks (a tower defense, a horde survival)
A `waves` match can pace its waves itself: give it `waveBreakSeconds` and every wave after the first is preceded by a break of that many seconds (build time), and `firstBreakSeconds` sets the break before wave 1 (`-1`, the default, uses `waveBreakSeconds`). The break counts down on every screen on the shared clock. Your game listens for the wave starting and sends its enemies, and reports the wave cleared:
```lua
local m = require("MatchFlow.api").find()
m.events.onWaveStarted:connect(function(e)
if m:isAuthority() then sendWave(e.wave) end -- e.early, e.left: called early, with this many seconds to spare
end)
-- when the last enemy of the wave is gone (report once, on one machine):
m:clearWave() -- the next break begins, or the last wave wins
m:callWave() -- a "send it now" button: cuts the break short
m:endRound("defeat") -- the base fell: the team loses together
local w = m:waveInfo() -- { state = "break" | "wave", wave, waves, left, ... }
```
- `waves = 0` is endless: clearing waves never wins, only a defeat (or `roundSeconds`) ends the round.
- `endRound(outcome)` ends the round now in any format; in `waves` it is how a game loses when its own rule says so (lives at zero) without knocking every player out.
- `joinInProgress = true` lets someone who joins mid-round play at once, which a co-op match wants; without it they watch until the next round.
- `showResults = false` hides only the results screen, for a game that draws its own victory and defeat screens. With `hold = true` a finished match then waits in the waiting room, and `start()` is "Play again".
- With breaks, a `clearWave()` that arrives during a break is ignored, so a wave reported twice counts once. Without `waveBreakSeconds` a waves match runs exactly as before.
- towerDefenseKit runs its whole match this way: build time, waves, the call-early bonus, a defeat when the lives run out, and Play again.
## Formats
| `format` | Round ends when | Winner | Fields it reads |
|---|---|---|---|
| `timed` | the clock runs out | highest score | `roundSeconds` |
| `firstToScore` | someone reaches the target (or time runs out) | first to `targetScore` | `targetScore`, `roundSeconds` |
| `bestOf` | as `firstToScore`, per round | most round wins over up to `rounds` rounds; a majority ends it early | `rounds`, `targetScore`, `roundSeconds` |
| `lastStanding` | one player (or none) is left | the survivor; earlier knockouts place lower | `roundSeconds` (0 = no limit) |
| `kingOfTheHill` | someone holds the hill alone for `targetScore` seconds | longest uncontested hold | `targetScore`, `roundSeconds` |
| `race` | everyone has finished (or time runs out) | finish order | `roundSeconds` |
| `waves` | `waves` waves cleared (victory), or everyone down, `endRound("defeat")` or out of time (defeat) | the team; the top scorer is shown as MVP | `waves`, `roundSeconds`, `waveBreakSeconds`, `firstBreakSeconds` |
| `turnBased` | every player has had `turns` turns | highest score | `turnSeconds`, `turns` |
A round with no time limit (`roundSeconds = 0`) shows elapsed time. A turn-based round shows the current turn's clock.
### The names first asked for
Every one of these works and stays working beside the current name. MatchFlow reads them as the current one, and the machine in charge writes the current name back into `format` and the length into `roundSeconds`, so other kits reading those fields see the usual values.
| First name | Current name |
|---|---|
| `seconds` (field) | `roundSeconds`: above 0, `seconds` wins; 0 leaves `roundSeconds` in charge |
| `format = "scoreLimit"` / `"bestOfRounds"` / `"lastOneStanding"` / `"raceToFinish"` / `"surviveWaves"` | `firstToScore` / `bestOf` / `lastStanding` / `race` / `waves` |
| `countdownStyle = "bigDigits"` / `"scifiHologram"` / `"cartoonPop"` | `bold` / `hologram` / `cartoon` (also for the `Countdown` component's `style`) |
| `resultsScreen = "winnerBanner"` / `"roundRecap"` | `banner` / `recap` |
| event `onState` / `onRoundEnd` | `onStateChanged` / `onRoundEnded`: both fire, with the same fields |
## King of the hill: the Hill zone
Drop a `Hill` on any entity in a level. A player standing in it alone is holding it, two or more is contested, and the match counts the hold time with no code of yours: the machine in charge tells the match who is on the hill.
```lua
-- in a scene's build.luau, inside content()
local MatchFlow = require("MatchFlow.api")
MatchFlow { format = "kingOfTheHill", targetScore = 20, seconds = 90, hudLayout = "holdMeter" }
local hill = entity.spawn("Hill", { position = { 0, 0, 8 } })
hill.component.add(MatchFlow.component("Hill"), { look = "scifiPad", radius = 3 })
```
**A hill that moves:** give it `spots` and `moveEvery`. During a round it hops to the next spot every `moveEvery` seconds, flashing for `warnSeconds` before it goes. Every machine works out the spot from the match clock, so they all agree with nothing extra sent.
```lua
hill.component.add(MatchFlow.component("Hill"), { look = "glowRing", spots = "10,0; -10,0; 0,10", moveEvery = 20 })
```
| Look (`look`) | What it is |
|---|---|
| `glowRing` | a glowing ring on the floor with a soft light column |
| `flagPlatform` | a low platform with a flag that takes the hill's state colour |
| `scifiPad` | a tech pad with segmented light strips and a holo column |
| `runeCircle` | a fantasy stone circle of glowing runes |
| `outline` | a plain thin outline, nothing else |
Each look shows three states readable from across a level: idle, held, and contested (pulsing red). The fields, events and methods are in `Hill.component/README.md`. A hill also works with no match in the scene, lighting up from who stands in it.
## In-round HUD layouts
`hudLayout` picks how the round is shown. Every layout draws the same match, in the `minimal`, `scifi` and `cartoon` looks (`hudLook`), and has its own phone layout.
| `hudLayout` | What it is |
|---|---|
| `classic` (default) | timer at the top centre with the format line, live scoreboard at the side |
| `cornerTimer` | a compact timer in a corner with your place and score |
| `scoreBug` | a sports-TV score bug with a LIVE dot |
| `versusBar` | you against the best other player across the top, with a tug bar |
| `timerStrip` | a thin timer-only strip, nothing else |
| `rankedSidebar` | every player ranked down the side, with gaps to the leader |
| `holdMeter` | king of the hill: who holds it, each player's hold time against the target, CONTESTED |
Draw one yourself with `require("MatchFlow.hud").render(look, data, { w, h, layout, narrow, t })`; `data` comes from `MatchFlow.view.hud(...)`, and `Hud.sample(layout)` gives sample data.
## Every field and its default
| Field | Default | What it does |
|---|---|---|
| `format` | `"timed"` | one of the eight formats above (or a first name) |
| `roundSeconds` | `30` | round length (0 = no limit; `timed` treats 0 as 60) |
| `seconds` | `0` | the round length under its first name; above 0 it wins |
| `targetScore` | `10` | score to win `firstToScore`/`bestOf`, seconds to hold in `kingOfTheHill` |
| `rounds` | `3` | maximum rounds in `bestOf` |
| `waves` | `5` | waves to clear in `waves` (0 = endless) |
| `waveBreakSeconds` | `0` | `waves`: a break of this many seconds before each wave after the first, cut short by `callWave()`; 0 = no breaks |
| `firstBreakSeconds` | `-1` | `waves`: the break before wave 1; -1 = the same as `waveBreakSeconds` |
| `joinInProgress` | `false` | someone who joins mid-round plays at once (co-op) instead of watching until the next round |
| `turnSeconds` / `turns` | `10` / `3` | turn length and turns per player in `turnBased` |
| `minPlayers` | `2` | players needed before the lobby counts down |
| `lobbySeconds` | `5` | lobby countdown once enough players are in |
| `countdownSeconds` | `3` | the 3-2-1-GO before each round (0 skips it) |
| `resultsSeconds` | `7` | how long results stay up |
| `breakSeconds` | `5` | break before the next round |
| `autoStart` | `true` | start by itself at `minPlayers`; when false, call `m:start()` |
| `hold` | `false` | while true no match starts: the waiting room stays up, a lobby countdown stops, a finished match waits instead of starting the next (see Holding the match) |
| `holdText` | `"Waiting for everyone to be ready"` | what the waiting panel says while held |
| `showLobby` | `true` | false hides only the waiting / lobby countdown / next-round panel, for a kit that draws its own lobby; the HUD, countdown and results still show |
| `showHud` | `true` | false hides only the in-round HUD (timer and scoreboard), for a kit that draws its own scoreboard; the 3-2-1-GO and the results still show |
| `showResults` | `true` | false hides only the results screen, for a game that draws its own end screen; the lobby, HUD and countdown still show |
| `includePeers` | `true` | everyone in the world is a player; when false, call `m:addPlayer(id, name)` yourself |
| `countdownStyle` | `"bold"` | one of the ten countdown styles |
| `resultsScreen` | `"podium"` | `podium`, `table`, `banner` or `recap` |
| `hudLayout` | `"classic"` | one of the seven HUD layouts |
| `resultsLook` / `hudLook` / `lobbyLook` | `"scifi"` | `minimal`, `scifi` or `cartoon` |
| `showUi` | `true` | false draws nothing, so you can build your own UI from `getState()` |
| `sounds` / `volume` | `true` / `0.8` | the countdown's tick and GO sounds |
## Styles and tags
Every style in the kit is in one tagged catalog: the 8 formats, 10 countdowns, 4 results screens, 7 HUD layouts, 5 hill looks and 3 looks.
```lua
local Catalog = require("MatchFlow.api").catalog -- or require("MatchFlow.catalog")
Catalog.list("countdown") -- { { kind, id, name, description, tags, aliases, field } }
Catalog.filter({ tag = "retro" }) -- every retro style, of any kind
Catalog.filter({ kind = "hudLayout", anyTag = { "sports", "racing" } })
Catalog.filter({ kind = "countdown", tags = { "sports", "racing" } }) -- all of the tags
Catalog.get("results", "winnerBanner").id -- "banner": first names resolve
Catalog.tags() -- every tag in use, sorted
```
Kinds: `format`, `countdown`, `results`, `hudLayout`, `hillLook`, `look`. Tags come from a fixed vocabulary: retro, scifi, sports, fantasy, cartoon, minimal, party, arena, racing, arcade, broadcast, competitive, coop, casual, strategy, versus, team.
| Kind | id: tags |
|---|---|
| format | `timed`: arena, party, arcade, competitive · `firstToScore`: arena, sports, party, competitive · `bestOf`: sports, arena, competitive, versus · `lastStanding`: arena, party, competitive · `kingOfTheHill`: arena, party, competitive · `race`: racing, sports, competitive · `waves`: arena, coop, team, scifi · `turnBased`: party, strategy, casual |
| countdown | `bold`: arena, sports, party, arcade · `trafficLight`: racing, sports · `pixel`: retro, arcade · `hologram`: scifi, arena · `cartoon`: cartoon, party, casual · `minimal`: minimal, casual · `fantasy`: fantasy · `flipClock`: retro, minimal · `neon`: retro, arcade, scifi · `broadcast`: sports, broadcast, racing |
| results | `podium`: party, sports, arena · `table`: minimal, arena, racing, competitive · `banner`: party, sports, cartoon · `recap`: sports, arena, competitive |
| hudLayout | `classic`: arena, party · `cornerTimer`: minimal, racing, casual · `scoreBug`: sports, broadcast, racing · `versusBar`: versus, arena, sports, competitive · `timerStrip`: minimal, casual · `rankedSidebar`: arena, party, racing, competitive · `holdMeter`: arena, party, competitive |
| hillLook | `glowRing`: scifi, arena, arcade · `flagPlatform`: sports, party, cartoon · `scifiPad`: scifi, arena · `runeCircle`: fantasy · `outline`: minimal |
| look | `minimal`: minimal, casual · `scifi`: scifi, arena · `cartoon`: cartoon, party, casual |
## Countdown styles
Every style has its own tick (3, 2, 1) and GO sound. The ticks climb a little in pitch as the count nears GO, so the last second sounds urgent. In a match the sounds play on every machine, at the moment each number appears on its screen.
| `countdownStyle` | Look | Sound |
|---|---|---|
| `bold` | big bold slam-in numbers with a glow streak | punch |
| `trafficLight` | red → amber → green racing lights | race beeps |
| `pixel` | 8-bit block digits on a CRT panel | chiptune |
| `hologram` | cyan sci-fi ring, scanlines, "ENGAGE" | sci-fi sweep |
| `cartoon` | bouncy number on a starburst, "GO!" | toy boing |
| `minimal` | thin progress ring, clean type | soft tone |
| `fantasy` | golden runic circle, "BEGIN" | bell |
| `flipClock` | split-flap cards that flip each second | mechanical click |
| `neon` | buzzing neon tube sign | synth |
| `broadcast` | sports-TV lower-third with a LIVE tag | stadium beeps and an air horn |
### A countdown on its own
`Countdown` is the same visuals and sounds as a standalone component, for any other timer in your game: a respawn, a bomb or a door. It is local to each machine.
```lua
local MatchFlow = require("MatchFlow.api")
local cd = entity.spawn("RespawnTimer").component.add(MatchFlow.component("Countdown"), { style = "neon", seconds = 5, autoStart = false, anchor = "top" })
cd.events.onFinished:connect(respawn)
cd:start() -- or cd:start(10)
```
Fields: `style`, `seconds` (3), `autoStart` (true), `loop` / `loopDelay`, `goText` and `caption` (override the words), `sounds`, `volume`, `showUi`, `anchor` (`center`/`top`/`bottom`), `scale`, `layer`. Events: `onTick{n}`, `onFinished`. Methods: `start(seconds?)`, `stop()`, `isRunning()`, `timeLeft()`.
To draw one inside your own UI, call `require("MatchFlow.countdowns").render(style, secondsLeft, { w = 420, h = 320 })`, which returns a widget node.
## Screens
| Screen | Choices | Looks |
|---|---|---|
| Results (`resultsScreen`) | `podium` (top three on steps, then the rest), `table` (full standings with places, score and rounds won), `banner` (one big winner card), `recap` (round-by-round grid with each round's winner) | `minimal`, `scifi`, `cartoon` |
| In-round HUD (`hudLayout`) | the seven layouts above | `minimal`, `scifi`, `cartoon` |
| Lobby / break panel | "Waiting for players 1 / 2" with player chips, "Starting in 5", "Next round in 5" | `minimal`, `scifi`, `cartoon` |
All of them are plain functions over data (`results.render(kind, look, data)`, `hud.render`, `lobby.render`), so you can draw them yourself with `showUi = false`.
### Small screens
- **Every panel sizes itself from the screen.** MatchFlow reads the safe area (the part no notch or system bar covers) each frame through `require("MatchFlow.theme").viewport()`, which returns `{ w, h, narrow, short }` in UI points. `narrow` is a phone held upright (under 640 wide), `short` is one held sideways (under 480 tall).
- **Phones get compact layouts, not smaller text.** Each HUD layout has its own phone arrangement. The podium lists 4th place onwards under the steps, the standings table folds its detail column into each row, the banner stacks the runners-up, and the round-by-round recap turns on its side. Pass `narrow = true` or `false` in the opts of `results.render` and `hud.render` to choose for yourself.
- **Checked** in the engine at a 412 × 892 pt phone, a 248 pt sliver and a 1280 × 702 desktop; a test renders every screen and every HUD layout at phone and desktop sizes. It has not been run on a real phone, and this release has not been checked in a web browser.
- **Touch buttons stay uncovered.** On a touch screen every HUD layout reads where the on-screen buttons sit (the engine's touch overlay, including its Menu button, and buttons kits such as controlsKit draw themselves) and moves any top panel a button would cover down below the buttons. Pass `touch = false` to `hud.render` to turn it off.
- **Fonts** are engine-bundled families (Anton, Archivo Black, Arimo, Bricolage Grotesque, Comic Neue, EB Garamond, JetBrains Mono).
- **Sound** in a browser plays once the page has had a click or tap: browsers keep audio locked until then.
- **Drawing your own panels?** The UI reads a plain number strictly between 0 and 1 in `width`, `height`, `left`, `top` (and their min/max/right/bottom/flexBasis cousins) as a fraction of the parent. Wrap your tree in `require("MatchFlow.theme").solid(node)`, as every kit panel does, to snap those to whole points.
## Methods
| Method | |
|---|---|
| `addScore(who?, amount?)`, `setScore(who?, value)` | add to or set a player's score |
| `knockOut(who?)`, `finish(who?)`, `setOnHill(who?, on)` | knockouts, race finishes, hill presence |
| `setStatus(who?, text)` | what happened to a player this round, in a few words ("Caught by the storm", "Fell"): shown beside them in the standings and results instead of Racing/Out, until the next round starts |
| `clearWave()`, `callWave()`, `waveInfo()`, `endTurn(who?)` | waves (cleared, called early, the break as shown) and turns |
| `endRound(outcome?)` | end the round now, e.g. `"defeat"` when a waves game's base falls |
| `addPlayer(id, name)`, `removePlayer(id)` | add bots or hand-picked players (any id that is not a peer id) |
| `setHold(on, text?)`, `isHeld()` | hold the match in the waiting room (a ready check) or let it go, from any machine |
| `start()`, `reset()` | start now regardless of head-count; throw the match away and wait again |
| `getState()`, `getStandings()`, `getPhase()`, `timeLeft()` | read the match as it is on screen (see How multiplayer works) |
| `hillInfo()` | the hill as shown: phase, elapsed, holder, holderName, contested, count, target; cheap enough for every frame |
| `syncInfo()` | clock offset, round trip, display delay and grace on this machine, for checking a multiplayer setup |
| `isAuthority()`, `localPlayer()` | whether this machine is in charge; the local player's id |
Events: `onStateChanged{phase, previous}` (also as `onState`), `onCountdown{n}` (3, 2, 1, then 0 = GO), `onRoundEnded{round, winner, winnerName, outcome}` (also as `onRoundEnd`), `onMatchEnded{winner, winnerName, outcome}`, `onTurn{player, name}`, `onWave{wave}`, `onWaveBreak{wave, seconds}`, `onWaveStarted{wave, early, left}`. Events fire on every machine. `outcome` is one of `time`, `target`, `lastStanding`, `allFinished`, `victory`, `defeat`, `turns` or `empty`.
The front door, `require("MatchFlow.api")`: call it (`MatchFlow { ... }`) or `start(opts)` to spawn or update the match, `find(name?)` for the MatchFlow component on the entity named `Match`, `component("MatchFlow" | "Countdown" | "Hill")` for the component types wherever the package is installed, `catalog`, and `VERSION`.
## How multiplayer works
- **One machine is in charge:** the owner of the synced `Match` entity, normally whoever created it. Only it runs the rules. It keeps a match clock and publishes the whole match (phase, clock, players, scores, history) in a synced snapshot stamped with that clock. It publishes whenever something changes, and at least four times a second.
- **Every screen shows the same moment.** Each machine matches its clock to the match clock by pinging the machine in charge; the quickest of the last eight round trips sets it. It keeps the last few snapshots and shows the match as it stood a short **display delay** ago. The machine in charge shows it that way too. Every snapshot has landed before its moment comes up, so the countdown numbers, the timer, the round end and the results change on every screen at the same instant.
- **The display delay** is long enough for the slowest player's snapshots to have landed: the worst lateness other machines measured in the last 20 s plus 0.05 s, or half the slowest round trip plus 0.1 s if that is longer, kept between 0.15 and 0.6 s. On a live two-machine test with a 60 to 70 ms round trip it sat at 0.18 to 0.21 s. When it changes, the new value is published half a second ahead and slides in the same way on every machine.
- **Reads trail by the same delay.** `getState()`, `getStandings()`, `getPhase()`, `timeLeft()`, `hillInfo()` and every event describe the match as it is on screen.
- **The 0:00 hold.** A timed round stays open for a short grace after 0:00 (about 0.2 to 0.3 s) so reports made just before it still count. The timer sits at 0:00 on every screen for that moment, then the results appear everywhere at once.
- **Reports** (`addScore` and the rest) are sent to the machine in charge, stamped with the time on the reporter's screen. A score, knockout, finish or cleared wave counts if it was made on screen after GO and before 0:00. Calling a report on every machine for the same event would count it more than once, so report each event from one place, typically the authority as OrbRush does. A Hill zone reports from the machine in charge only.
- **Players** are the peers in the room the `Match` entity lives in. Someone who joins mid-round sees "Watching · you join next round" and plays from the next round. Someone who leaves mid-round is counted out of that round, and drops off the board when the match ends.
- **Checking a setup:** `m:syncInfo()` returns whether this machine is in charge, its clock offset and round trip, the display delay and grace, the newest snapshot's age, and the player count.
### If the host quits mid-round
The match carries on for everyone else, on the same clock and with the same scores. Nothing restarts. It is not instant: expect a pause of about 10 seconds first (see Known limits, #9546). And in some cases the match can disappear for a player who stays instead of carrying on (see Known limits, #19490).
1. **The wait.** When the host's game closes, the engine takes about 10 seconds to notice the player has left. Until it does, the relay still counts the host as the `Match` entity's owner, and no other machine may take the match over. For that time the match does not move on: the round does not end, phase changes wait and nothing new is counted. Every machine keeps the last snapshot the host published, at most a quarter of a second old.
2. **The takeover.** Once the engine reports the host gone, the relay hands the `Match` entity to a player who stays, and that machine takes charge at once. It continues from the host's last snapshot on the same match clock, with the same phase, round and scores. It does not wait on the quit host's last snapshot. If the relay does not hand the entity on, the remaining player with the lowest peer id claims it about half a second after the host drops off the room, and anyone else after 4 s.
3. **After it.** The other machines keep the clock they already matched and start pinging the new machine. The player who quit is counted out of the round. A phase change that fell due in the gap (the clock reaching zero, say) happens on every screen at once. A report made between the host quitting and the takeover is lost. A Hill zone re-reports who is on it from the new machine within a second, so hold time keeps counting.
Tested on two real machines with 1.1.0: the machine running the match was quit in the middle of a round. The other machine took over about 10 seconds later; the clock carried on, the scores were kept and the round ended normally. The tests also check the handover from the host's last snapshot: the new machine's clock matches what the other screens showed, scores carry over, a long gap is carried over whole, and the round ends on the same clock.
If everyone leaves, the round ends with outcome `empty`, and the match waits for players again.
## Using it offline or in single-player
With nobody else connected, the local machine is in charge. Set `minPlayers = 1` to play solo, or add bots with `m:addPlayer(1001, "Bot")` and drive their scores yourself.
## What's inside
| Asset | Role |
|---|---|
| `MatchFlow.component` | the match: the rules, sync, events, UI |
| `Hill.component` | the king-of-the-hill zone, five looks, optionally moving |
| `Countdown.component` | standalone countdown |
| `api.module` | the front door: `MatchFlow { ... }`, `find`, `component`, `catalog`, `VERSION` |
| `catalog.module` | every style with its tags |
| `rules.module` | pure state machine for all eight formats (no engine calls, unit tested) |
| `timeline.module` | the shared clock, display delay and host handover (pure, tested with simulated latency) |
| `hill.module` | the hill's pure maths: who is inside, which spot, which state |
| `countdowns.module` | the ten countdown styles as widget-tree renderers |
| `results.module`, `hud.module`, `lobby.module` | the screens and HUD layouts |
| `theme.module` | the minimal, sci-fi and cartoon design tokens and helpers, `viewport()` and `solid()` |
| `view.module` | turns match state into the data each screen draws |
| `audio.module` + `sounds/` | 20 short tick and GO clips, two for each of the ten sound sets |
| `matchflow.testSuite` | the tests (see below) |
| `guides/` | the how-to guide and the best-of-three example guide (see Guides) |
Run the tests with `tools.use("tests", "run", { suite = "matchflow" })` in edit mode. They cover every format, the roster rules, every renderer and HUD layout at desktop and phone sizes, the sound sets, two simulated machines over a jittery network, the host handover, the hill's maths, every first name, the catalog and its tags, and this README's version.
## Known limits
Only open issues are listed here, each by its number: engine issues as `#number`, ZeroMind issues as `ZeroMind#number`.
- **When the host stops mid-round, the match can disappear for a player who stays (#19490).** Sometimes, not every time (it happened in one of two live tries), the match a scene builds, as the first example builds it, vanishes on the remaining player's machine when the host stops in the middle of a round. That player then has no match: no timer, no scoreboard and no results, and the round does not carry on for them. MatchFlow cannot keep the match alive when the engine removes it.
- **When the host quits, the match waits about 10 seconds before another machine takes over (#9546).** The engine takes that long to notice that a player whose game closed has left, and until it does no other machine may take the match over. Nothing moves on during the wait; then the takeover carries on with the same clock and scores (see "If the host quits mid-round"). A host who only leaves play, without closing the game, was noticed within about a second in the 1.0.0 live test.
- **Two players can't be tested inside one engine (#18688, #19114).** The suite tests multiplayer through simulated machines; two-machine behaviour was last checked by hand on two real machines for 1.1.0.
- **The guides inside this package don't show up in ZeroMind search yet (ZeroMind#3099).** A ZeroMind search worded like a guide's title (for example "how to add a pause menu to my game" for menusKit's guide) finds the package, not the guide inside it. Once MatchFlow is installed, the `guides` tool and the Docs panel find them; see Guides.
- **A guide does not open by its short name (#22286).** In the Docs panel, `how-to-add-rounds-a-countdown-and-a-scoreboard-to-my-game` alone opens nothing. Use the full name, `MatchFlow.guides.<name>`, there, and the path, `MatchFlow.package/guides/<name>`, with the `guides` tool. The guides link to each other by path.
## Changelog
### 1.4.3
- Both guides open by naming the package and the version they describe (1.4.3), with its ZeroMind install line. Behaviour is unchanged.
### 1.4.2
- **A race that ends with runners still out says so, and why.** Once a race round is over (results, intermission) an unfinished runner reads `Did not finish` and `DNF` instead of `Racing` and `-`. New `match:setStatus(who, text)` puts a game's own words beside a player (up to 40 characters, any machine, any phase; cleared when the next round starts): Skyhook marks runners the storm swallowed the finish ahead of as "Caught by the storm". Rows from `getStandings()` carry `status`. Found by Skyhook, where a runner still flying looked like they were "Racing" on the results table.
- One new test (96).
### 1.4.1
- **A player who leaves and rejoins resumes their own row.** A rejoin arrives with a new peer id, so a race used to show that player twice: the old row as Left/DNF and a new empty one. Now a player added under the name of a row that left (not a bot) takes that row over: the id moves to the new one, score, finish and time stay, `left` clears, and whether they play on at once follows `joinInProgress` as for any late joiner. Found by Skyhook.
- **The HUD keeps clear of on-screen touch buttons.** On a touch screen at tablet or desktop size the engine's touch Menu button and controlsKit's corner Controls button sat on top of the classic layout's scoreboard. Every HUD layout now reads `Zin.touchControls.layout()` (safely; nothing changes where it can't be read or the overlay is off screen) and moves any top panel a button covers down below the buttons, with whatever is stacked under it. `hud.render` takes `touch = false` to turn it off, or a list of `{ x, y, r }` circles of your own.
- Six new tests (95).
### 1.4.0
- **Waves with breaks**, asked for by towerDefenseKit: `waveBreakSeconds` and `firstBreakSeconds` put a counted-down break (build time) before each wave, `callWave()` cuts it short (`onWaveStarted` says it was early and how many seconds were left, for a bonus), `waveInfo()` reads the break as shown, and `onWaveBreak` / `onWaveStarted` fire on every machine. The HUD's wave line shows "Wave 3 of 10 in 12s" during a break.
- **`endRound(outcome)`**: end the round now, so a waves game loses when its base falls without knocking every player out.
- **Endless waves**: `waves = 0` never wins by count (it was raised to 1 before).
- **`joinInProgress`**: a late joiner plays at once in a co-op match instead of watching until the next round.
- **`showResults = false`** hides only the results screen, for a game with its own end screens.
- Eight new tests (89). Without the new fields every format behaves exactly as in 1.3.2.
### 1.3.2
- Its tests find the package's own files wherever it is installed (at /source, or under /source/deps when another package installs it). In a world where platformer3dKit installed it, 10 of its tests failed because they read README.md, package.yaml and source files from a fixed /source/MatchFlow.package path.
### 1.3.1
- `MatchFlow.component("MatchFlow")` looks the component up by `~MatchFlow.MatchFlow` first again, as 1.2.1 did, so MatchFlow is found wherever it was installed, including as another kit's dependency. The merge that brought 1.3.0 had turned that first lookup into a second copy of the bare-name one.
### 1.3.0
- **Hold the match for a ready check.** New `hold` and `holdText` fields and `setHold(on, text?)` / `isHeld()` methods: while held no match starts, a lobby countdown stops and goes back to waiting, and a finished match waits at its break instead of starting the next. A round being played is never interrupted. Asked for by lobbyKit's ready check.
- **`showLobby = false`** hides only the waiting, lobby countdown and next-round panel, so another kit can draw the lobby while MatchFlow's HUD, countdown and results still show.
- **`showHud = false`** hides only the in-round HUD, so another kit can draw the scoreboard (lobbyKit's team scoreboards) while the 3-2-1-GO countdown and the results still show.
- Five new tests for the hold (81 tests).
### 1.2.1
- **No long dashes left in any file of the kit, code included.** A comment in `Countdown.component` now uses a colon. The placeholder the HUD and results screens draw for an empty score, an empty versus side or a missing round value is now a plain hyphen (`-`). A new test fails if a long dash ever comes back into any text file of the package (76 tests).
- **The store listing names the two guides.** The world's description and page text now say the kit ships with the how-to guide and the best-of-three example guide, and what each one teaches (see Guides).
### 1.2.0
- **Two guides ship in the package**, in `guides/`: *How to add rounds, a countdown and a scoreboard to my game* (the how-to: starting a match, every format's win condition, scoring and teams, the hill zone, HUD layouts, countdown and results styles, what players see when the host leaves) and *A best-of-three arena match with a countdown, live scores and a results screen* (an example from a brand-new world, using menusKit for the end screens and barsKit for score bars). They link to each other, and the README's new Guides section points to both. The example was followed from start to finish in a fresh world.
- **Checked on today's engine**: MatchFlow installed alone in a brand-new world runs the first example as written (lobby, countdown, round, podium, break, next round, and editing 30 to 45 takes effect), and the tests pass. No code changes.
- **Known limits**: the bare-name lookup for a copy that came as another kit's dependency (#19199) is fixed in the engine and comes out; added that package guides don't show up in ZeroMind search yet (ZeroMind#3099) and that a guide doesn't open by its short name (#22286).
### 1.1.0
- **Hill zone** (`Hill` component): drop it in a level and king of the hill counts hold time on its own. Five looks (`glowRing`, `flagPlatform`, `scifiPad`, `runeCircle`, `outline`), idle / held / contested states, and an optional hill that moves between spots during a round.
- **Seven HUD layouts** behind `hudLayout`: `classic`, `cornerTimer`, `scoreBug`, `versusBar`, `timerStrip`, `rankedSidebar`, `holdMeter`, each in all three looks and on a phone. `classic` is unchanged and still the default.
- **Tags on every style** and `MatchFlow.catalog` to list and filter them.
- **The names first asked for work**: `seconds`, `scoreLimit`, `bestOfRounds`, `lastOneStanding`, `raceToFinish`, `surviveWaves`, `bigDigits`, `scifiHologram`, `cartoonPop`, `winnerBanner`, `roundRecap`, `onState`, `onRoundEnd`. Nothing was renamed.
- **The front door**: `MatchFlow { format = "timed", seconds = 30 }` from `require("MatchFlow.api")`. Inside a scene's `content()` it always makes the match itself, so editing the numbers and saving rebuilds the scene and updates the match on every machine and on a fresh load. (Before this fix, a second build found the match the first build had saved and tried to change it, which the engine refuses: the rebuild failed, and on a machine loading the world everything the build placed after the match, such as a Hill, was missing.)
- **Known limits** now names the ~10 second wait before another machine takes over when the host's game is closed (#9546), and that the match can disappear for a player who stays when the host stops mid-round (#19490).
- **Host quitting mid-round**: the machine the match is handed to no longer defers to the quit host's last snapshot, and a gap of any length is carried over (it was capped at 5 s, which could pull the clock back on every screen).
- **Gallery**: the world opens on it, one page with no tabs, readable from the spawn. Each of the ten countdowns stands beside a results screen, a live card shows the five hill looks with each one labelled under its hill, and the seven HUD layouts sit in one row. "Walk around" puts you next to a live hill to step into. Orb Rush is the second scene.
- **matchFlowKit** is named in this README as this package; the package keeps its name, MatchFlow.
### 1.0.0
- First release: one component for lobby, countdown, round, results and break; eight formats; ten countdowns with sounds; four results screens; HUD and lobby in three looks; shared match clock and host migration.
# api
The one interface to SecondWind: `local HK = require("SecondWind.api")`.
- **Damage:** `damage`, `heal`, `kill`, `revive`, `explode`.
- **Configure:** `attach`, `configure`, `setModel`, `setDeathStyle`, `applyPreset`, `setRules`, `endRound`.
- **Query:** `state`, `isAlive`, `isDowned`, `config`, `get`, `lifeline`, `all`, `rules`, `ruleValues`, `nameOf`, `isPlayer`, `catalog`, `killFeed`.
- **Hooks:** `on` (events) and `setDamageFilter`.
Calls on a target this peer does not own are sent to its owner, who checks them (attacker ownership, teams, the damage cap, config permission) before applying them. The package README lists every argument.
# MatchFlow
Runs a whole multiplayer match from one component: the lobby, a 3-2-1-GO countdown, the round with its timer, results, a break, then the next round. Put it on a **synced** entity (`entity.spawnSynced("Match")`); it needs no sibling components.
- `format` picks one of eight match types: `timed`, `firstToScore`, `bestOf`, `lastStanding`, `kingOfTheHill`, `race`, `waves`, `turnBased`. Each reads a couple of fields (`roundSeconds`, `targetScore`, `rounds`, `waves`, `turnSeconds`, `turns`).
- `countdownStyle`, `resultsScreen`, `resultsLook`, `hudLook` and `lobbyLook` restyle the screens. Set `showUi = false` to draw your own.
- The entity's owner is in charge. It runs `MatchFlow.rules` and publishes the match in the synced `snapshot` field. Everyone else follows that snapshot and forwards their reports. If the owner leaves, the lowest remaining peer id takes over from the last snapshot and the match carries on.
- Game code reports `addScore`, `setScore`, `knockOut`, `finish`, `clearWave`, `endTurn` and `setOnHill`, and listens to `onStateChanged`, `onCountdown`, `onRoundEnded`, `onMatchEnded`, `onTurn` and `onWave`.
```lua
local match = entity.spawnSynced("Match")
local m = match.component.add("MatchFlow", { format = "timed", roundSeconds = 30 })
m.events.onRoundEnded:connect(function(e) print(e.winnerName, "wins round", e.round) end)
```
The package README has every format, style, field and the full multiplayer behaviour.
# turretsKit.api
The one interface to turretsKit. Turrets are `turretsKit.Turret` components on synced
entities. The peer in charge of a turret (see `turretsKit.net`) picks its targets, fires
and deals damage; every other peer follows the synced target and draws the same shots.
Every setter works from any peer: on a peer not in charge it is sent to the one that is.
```luau
local TK = require("turretsKit.api")
TK.addTurret(entity.spawnSynced("Gun", { position = { 0, 0, 5 } }), { def = "machineGun", targeting = "first" })
TK.setDef(gun, "tesla") -- swap what it is (its def), live
TK.setTargeting(gun, "strongest") -- swap how it picks, live
TK.upgrade(gun) -- next tier (asks your economy hook)
TK.sell(gun) -- removes it, `sold` event carries the value
TK.info(gun) -- every number, read back
```
A turret argument (`t`) may be an entity, an entity id or the component.
## Fields
- `VERSION` (`"1.0.0"`), `TURRET` (the Turret component asset), `EVENTS`.
- Sub-modules: `catalog`, `targeting`, `aim`, `targets`, `combat`, `net`, `looks`,
`projectiles` (projectileKit.api).
- Pass-throughs: `define`, `defineStyle` (catalog), `defineTargeting` (targeting),
`addTarget`, `removeTarget`, `setProgress` (targets), `speedMultiplier`, `onSpeed` (combat).
## Placing and changing turrets
- `addTurret(e: any, opts: any?): any`: puts a Turret on an entity (use
`entity.spawnSynced`) or updates the one it has. `opts` = any Turret fields; walls
(and `withHealth = true`) also get SecondWind health. Returns the component.
- `place(pos: any, typeId: string, opts: any?, by: any?): (any, string?)`: builds a new
turret at runtime, paying the build cost; extra opts `yaw` (degrees) and `name`.
- `set(t, field: string, value: any, by: any?): (boolean, string?)`: changes `def`,
`targeting`, `tier`, `style`, `team`, `active` or `targetPlayers` (validated).
- `setDef(t, typeId)`, `setTargeting(t, mode)`, `setTier(t, tier)` (no money),
`setTurretStyle(t, styleId)`: shorthands for `set`.
- `cycle(t, field: string, dir: number?): any`: steps `def`, `targeting`, `tier` or
`style` to the next (1) or previous (-1) value; returns it.
- `setStyle(styleId: string)` / `defaultStyle(): string`: the world default for turrets
whose `style` is `"auto"`, on this peer (call it where every peer runs, e.g. a scene
entrypoint).
- `setStyleAll(styleId: string)`: writes every turret's own synced style.
- `styleOf(t): string`: the style a turret actually draws with.
## Money
- `setEconomy(hooks: any?)`: `{ spend = fn(cost, info) -> boolean, refund = fn(amount, info) }`,
`info = { turret, def, tier, by, reason = "build" | "upgrade" | "sell" }`. Without
hooks, building and upgrading are free and selling refunds nothing.
- `upgrade(t, by: any?): (boolean, string?)`: next tier; reasons `"max"`, `"money"`, `"sent"`.
- `sellValue(t): number`: what selling gives back now.
- `sell(t, by: any?): (number, string?)`: refunds, fires `sold`, despawns the turret.
## Reading back
- `info(t): any`: `{ id, def, label, description, tags, role, delivery, damageType,
targeting, tier, tierName, maxTier, style, state, target, kills, stats, base, boost,
special, specialLabel, specialValue, costs, limits, aim, owner }`.
- `stats(t): any`: the resolved numbers with support boosts (see `catalog.stats`).
- `types(): { any }`: every turret type with its tiers, costs and stats.
- `styles(): { any }`: `{ id, label, description }` per style.
- `modes(): { any }`: `{ id, label }` per targeting mode.
- `all(): { [string]: any }` / `runtime(t): any`: turret runtimes on this peer (`comp`,
`stats`, `type`, `focus`, ...).
- `idOf(x): string?`, `componentOf(x): any`: resolve a turret argument.
- `boostFor(t): any`: `{ fireRate, damage, range, from }` from same-team support beacons
in reach (strongest counts, no stacking).
- `report(): any`: turrets, how many this peer is in charge of, projectile, combat and
net stats, default style.
## Events
- `on(event: string, fn: (any) -> ()): any`: listen to `built`, `upgraded`, `sold`,
`changed`, `fired`, `kill`, `targetChanged`, or `"*"`. `payload.event` names it;
`payload.local` is true on the peer that made it happen. Money events reach every peer,
so act on them where `payload.local` is true. Returns `{ Disconnect }`.
## Budget and frame
- `setBudget(b: any)`: projectile budget preset (`"desktop"`, `"web"`, `"phone"`) or
numbers; otherwise the kit picks `projectileKit`'s suggested preset on first use.
- `_frame(dt)`: once-a-frame shared work (combat tick, cloud visuals, net flush), called
by every Turret; extra calls in a frame do nothing. `_register`, `_unregister`, `_emit`,
`_ensureHealth`, `_cloudVisual` are internal to the kit.
# Health
Gives any entity health, an optional shield, regeneration, invulnerability frames, armor, death and a respawn / reset / remove rule. Attach it to a player body, enemy or prop; no sibling components are required. On a CharacterController body it disables movement while dead. Only the owning peer changes it; use `Lifeline.damage/heal/kill/revive` or the `damage`/`heal` methods. Fires typed events `damaged`, `healed`, `blocked`, `died`, `respawned`. See the package README for fields.
# turretsKit
Towers, turrets and targeting for tower defense, base defense and sentry-gun games. Put **one Turret part** on an entity and give it two names: **which turret it is** and **how it picks targets**. Change either name while it fires and it changes on the spot, with no other code.
- **12 turrets, all data**: machine gun, cannon, mortar, laser, tesla, frost, poison cloud, missile, sniper, flamethrower, support beacon and wall. A designer tweaks or adds one by editing a `.data` file.
- **5 targeting modes**: `first` (furthest along the path), `last`, `nearest`, `strongest`, `weakest`. You can add your own.
- **Real turret feel**: every turret has left/right and up/down turn limits and turn speeds. Anything outside its arc is never picked. It sweeps when idle, tracks, leads moving targets and holds its aim for a moment when a target is lost (the brain is a [Watchful Minds aiKit](https://origozero.ai) state machine shaped like aiKit's own turret).
- **3 upgrade tiers per turret** that change the model and every number, each with a cost. Selling pays back a sell value through a hook your money system listens to. Every number reads back.
- **3 looks**: sci-fi, medieval fantasy and cartoon toy. One call swaps the whole world, or swap a single turret.
- **Built for crowds**: projectiles, beams and effects come from [projectileKit](../projectileKit.package/README.md) pools, and damage is batched, so many turrets firing into a big crowd stays smooth on web and phones.
- **Multiplayer**: one machine decides each turret's target and deals its damage, so a hit lands once. Other players see that machine's targets, health and kill counts after a sync delay, which can be a second or more (see [Multiplayer](#multiplayer)).
Health and damage come from **SecondWind** (burns, poison, chill, chain lightning, teams, kill feed). It works with **Wavecaller spawnerKit** enemies walking a path, and with **Gaugeworks barsKit** health bars.
## Install
One install, one id, nothing else to install:
```
zeromind_install { guid: "fc8b64ab-27cc-4d1a-9746-a0f55ac9e442" } // turretsKit 2.1.4
```
That brings everything turretsKit runs on, each kit from its own world: projectileKit for the pooled projectiles, Second Wind (health and damage, with the Lifeline and MatchFlow pieces it needs), Wavecaller spawnerKit (the enemy stream; turretsKit also reads its enemies' routes for `first` / `last`) and Watchful Minds aiKit (the turret brain's state machine and presets).
**Use those kits by their own names.** Every kit the install brings is a package of your world, so your own scripts require it the plain way:
```lua
local TK = require("turretsKit.api")
local SK = require("spawnerKit.api") -- Wavecaller spawnerKit
local HK = require("SecondWind.api") -- Second Wind
local FSM = require("aiKit.fsm") -- Watchful Minds aiKit's state machine (and "aiKit.presets")
```
They are the very modules turretsKit runs on. `TK.kits` is still there as a shortcut to the same modules (`TK.kits.spawnerKit`, `TK.kits.SecondWind`, `TK.kits.aiKit.fsm` / `.presets`), so code written for 2.0.2 keeps working.
Checked on 2026-10-31 (engine library `fe09783`, before the `ab1aa41` this release is built on), in a brand-new empty world with turretsKit as its only install: 711 files and 11 dependencies arrived with no problems, every kit answered to its own name, turretsKit's and projectileKit's 43 tests passed, and the quick start below ran exactly as written. That check was made with 2.1.0; 2.1.1 changes no code, only the docs, the guides and two numbers in the quick start (see Version).
### What it depends on, and which version
turretsKit 2.1.4 was built and tested against exactly these versions. The *published version* column is the start of the content id ZeroMind installs (`zm status` shows the same short id for each install). *How it arrives* says what an install of turretsKit alone brings.
| Package | From (world) | Version | Published version | Asset id | How it arrives |
|---|---|---|---|---|---|
| projectileKit | Bastion Works (this world) | 1.0.2 | the latest 1.0.2 | `0b2aaa66-56b2-4f3e-80f8-05f8a9f07d04` | the whole package, with turretsKit |
| SecondWind | Second Wind (`7a497fbf…`) | 1.2.0 | `b4d0918` | `5da0a53c-5953-4adc-80fb-f5afb02f6568` | the whole package; `require("SecondWind.api")` |
| spawnerKit | Wavecaller (`428a5541…`) | 1.0.0 | `049ac51` | `866b48e5-deed-4e7f-84a8-94ec29134c81` | the whole package; `require("spawnerKit.api")` |
| aiKit | Watchful Minds (`1d574edc…`) | 1.1.0 | `a45e765` | `549ff927-79bc-4db2-b5b2-35d5f3fd59cb` | the whole package; `require("aiKit.fsm")`, `require("aiKit.presets")` |
| navKit | Watchful Minds (`75ad3c13…`) | 1.2.1 | `3832dcf` | `286dd3bb-0744-4157-b9f0-c98cc03ee326` | the whole package, with aiKit |
| Lifeline | Lifeline (`45f92606…`) | 1.0.1 | `c8e3fae` | `7b85ce05-3903-4374-b654-2d4ffea295a5` | the whole package, with Second Wind |
| MatchFlow | Match Flow Kit (`40bc9b7f…`) | 1.1.0 | `4c6c52e` | `31cf13b4-df7d-4888-85e2-7947a7301614` | part of the package, with Second Wind and spawnerKit: the `MatchFlow` and `Countdown` components and most of its modules, but not its `api` module, so `require("MatchFlow.api")` answers "module not found" ([#22186](https://github.com/OrigoZero/zero/issues/22186)). Reach it through its component by name, `entity.find("Match").component.get("MatchFlow")`, as the tower defense guide does |
| juiceKit | juiceKit (`46548c0c…`) | 1.2.2 | `be142e5` | `eed55f6d-afaf-4767-83c5-539ef91e0dc5` | the whole package, with spawnerKit |
| barsKit (optional) | Gaugeworks (`d9f6c7f4…`) | 1.3.0 | `046996d` | `c154eb07-ce7c-48ca-8232-4ce1a8754214` | not brought; install it yourself for its health bars |
| Zero engine library (`@builtin`) | the engine (`07158574…`) | branch `main`, pinned commit | `ab1aa41` | none | provided by the engine, plus pinned copies of two engine files a kit was published with (see Known limits) |
Bastion Works itself has Second Wind, spawnerKit and the whole aiKit installed, each fresh from its own world, which is what lets an install of turretsKit bring each of them from its own world rather than from this one.
Gaugeworks **barsKit** is optional (its health bars, see below).
## Three turrets shooting a stream of enemies, in five minutes
Make a scene (or open your scene's `build.luau`) and use this as its build. It runs as written in a world where turretsKit is the only install: an endless stream of spawnerKit grunts and runners walks a path past a tesla coil, a cannon and a machine gun, in that order, and all three shoot from the first wave on (the tesla coil first, so it gets enemies before the others have thinned the stream).
```lua
local TK = require("turretsKit.api")
local SK = require("spawnerKit.api") -- Wavecaller spawnerKit, brought by turretsKit
local HK = require("SecondWind.api") -- Second Wind, brought by turretsKit
function content()
-- ground and light
local ground = entity.spawn("ground")
ground.component.add("Model", { model = asset.resolve("@builtin::meshes.cube", "mesh"),
material = asset.resolve("@builtin::materials.lit_checkerboard", "material") })
ground.component.add("BoxCollider", {})
ground.localPosition = { 0, -0.1, 8 }
ground.localScale = { 60, 0.2, 40 }
entity.spawn("sun").component.add("Light", { kind = "directional", intensity = 0.9, directionX = -0.3, directionY = -0.8, directionZ = 0.4 })
entity.spawn("sky").component.add("ProceduralSky", { timeOfDay = 15 })
-- SecondWind's health rules: one per scene, on a synced entity
entity.spawnSynced("HealthRules").component.add(HK.RULES, {})
-- a path of eight points, left to right in front of the player
for i = 1, 8 do
local p = entity.spawn(`Path{i}`, { position = { -21 + i * 5, 0, 12 } })
SK.addSpawnPoint(p, { group = "Path", order = i, kind = "path" })
end
-- an endless stream of spawnerKit enemies walking that path
SK.addSpawner(entity.spawnSynced("Stream", { position = { -16, 0, 12 } }), {
pattern = "path", points = "Path", effect = "none", curve = "flat", advance = "timer", maxAlive = 12,
waveTable = { loop = true, waves = { {
delay = 1, gap = 1.2, points = { "Path" },
enemies = { { kind = "grunt", count = 8 }, { kind = "runner", count = 4 } },
} } },
})
-- three turrets, each set up by two names: which turret, and how it picks targets
local function turret(name: string, pos: { number }, kind: string, mode: string)
TK.addTurret(entity.spawnSynced(name, { position = pos }), { def = kind, targeting = mode })
end
turret("Gun", { 8, 0, 6 }, "machineGun", "first")
turret("Cannon", { 0, 0, 6 }, "cannon", "strongest")
turret("Tesla", { -8, 0, 6 }, "tesla", "nearest")
-- the player
local setups = entity.spawn("PlayerSetups")
local prototype = entity.spawn("Player", { parent = setups })
prototype:setParticipation("PrototypeOnly")
local body = entity.spawn("body", { parent = prototype })
body.component.add("Asset", { source = asset.resolve("@builtin::avatars.humanoid", "avatar") })
local rig = entity.spawn("CameraRig", { parent = prototype })
rig:setNetworkScope("OwnerOnly")
rig.component.add("Camera", { behavior = asset.resolve("@builtin::controller.orbital_follow", "component") })
rig.localPosition = { 0, 2.6, -5 }
rig.localRotation = { 0, -0.9961332, -0.0878564, 0 }
prototype.component.add("PlayerPrototype", { body = body, camera = rig })
local start = entity.spawn("Start", { parent = entity.spawn("Spawns"), position = { 0, 0, -2 } })
start.component.add("PlayerSpawn", { prototype = prototype })
end
```
Press play. The enemies carry spawnerKit's own health bars. For Gaugeworks barsKit bars instead, set `healthBars = false` on the spawner and add a bar to each enemy as it spawns, in the scene's `entrypoint.luau`:
```lua
local SK = require("spawnerKit.api")
local BK = require("barsKit.api")
function onLoad()
SK.on("spawned", function(e)
local id = if type(e) == "table" then (e.enemy or e.id) else e
if type(id) == "table" then id = id.id end
if type(id) == "string" and entity.exists(id) and BK.barOf(entity(id)) == nil then
BK.bar(entity(id), { look = "overhead" })
end
end)
end
```
Now change things while it plays:
```lua
local TK = require("turretsKit.api")
local gun = entity.find("Gun")
TK.set(gun, "def", "laser") -- it is a laser now, mid-fight (TK.setDef(gun, "laser") does the same)
TK.setTargeting(gun, "weakest") -- and finishes off the weak ones
TK.upgrade(gun) -- Mk II
TK.setStyle("toy"); TK.setStyleAll("toy") -- every turret in the cartoon toy look
print(TK.info(gun).stats.fireRate, TK.info(gun).costs.sell)
```
You can also set the same fields in the editor's inspector on the Turret component.
## The Turret part (`turretsKit.Turret`)
Put it on a **synced** entity (`entity.spawnSynced`). `TK.addTurret(e, fields)` does that and validates the names. The entity's forward (+Z) is the turret's home facing, which its turn limits are measured from.
| field | default | meaning |
|---|---|---|
| `def` | `machineGun` | which turret it is, by name (any turret type's `id`). Change this one field live to swap the turret |
| `targeting` | `first` | how it picks: `first`, `last`, `nearest`, `strongest`, `weakest`. Change it live |
| `tier` | 1 | upgrade tier 1 to 3: model and numbers |
| `style` | `auto` | `scifi`, `medieval`, `toy`, or `auto` (the world default, `TK.setStyle`) |
| `team` | `defenders` | SecondWind team. It never shoots its own team |
| `targetPlayers` | false | also shoot players (sentry guns) |
| `active` | true | off: it stands idle |
| `label`, `note` | true, "" | floating label, two lines: the name, then tier · targeting mode (support: tier · its boost; wall: tier · health), plus an optional extra line. It stands a little toward the camera of the screen drawing it, so no part of the turret, in any look, covers its text |
| `labelSize`, `labelLift`, `labelAt` | 1, 0, 0 | label size; extra height above the model; or a fixed height above the base (`labelAt` > 0), to line labels up in rows that never cross. See [Labels on any screen](#labels-on-any-screen) for phones held upright |
| `showRange` | false | draw its range on the ground |
| `target`, `state`, `aimYaw`, `aimPitch`, `kills` | | written by the machine in charge, read them anywhere |
## The twelve turrets
| name | what it does | its special number per tier |
|---|---|---|
| `machineGun` | fast tracer bursts at one target; turns fast | bullets per burst 1 / 2 / 3 (barrels 1 / 2 / 4) |
| `cannon` | heavy shell on a low arc, splash damage | splash radius 1.8 / 2.4 / 3.2 m |
| `mortar` | lobs shells high over walls (no line of sight needed), minimum range 5 m | splash radius 2.5 / 3.2 / 4 m |
| `laser` | continuous beam that ramps up while it holds one target | ramp ×1.5 / ×2 / ×3 |
| `tesla` | lightning that jumps from enemy to enemy | chain jumps 2 / 4 / 6 |
| `frost` | ice shards that slow everything they chill | slow 30 / 45 / 60 % |
| `poison` | lobs a glob that leaves a toxic cloud: damage over time in an area | cloud damage 8 / 12 / 18 per s |
| `missile` | homing missiles that climb and chase | missiles per salvo 1 / 2 / 4 |
| `sniper` | long range, slow, huge hits that pierce through a line | enemies pierced 1 / 2 / 3 |
| `flame` | short cone of fire that sets things burning | burn 4 / 6 / 9 per s |
| `support` | never fires; turrets in its aura fire faster, hit harder, reach further (the strongest beacon counts) | fire-rate boost 15 / 25 / 40 % |
| `wall` | never fires; blocks enemies that walk into it and soaks their damage, rebuilds after breaking | health 400 / 700 / 1100 (thorns from Mk II) |
Every tier also raises fire rate, range and damage. `TK.types()` lists every type with its tags and every number of every tier (`TK.types("splash")` lists only the types tagged `splash`, see [Tags](#tags)); `TK.info(turret)` reads a placed turret's current numbers, costs, turn limits and aim.
### Adding or tweaking a turret
Each turret is a `.data` file bound to the `turretsKit.turretType` contract (the kit's twelve are in `turretsKit.package/turrets/`). Copy one anywhere in your world, change its `id` and numbers, and a Turret can use it by that `id` at once. The contract's README explains every field. From code:
```lua
TK.define("heavyGun", { label = "Heavy Gun", turn = { yawSpeed = 120, yawMin = -60, yawMax = 60 } }, "machineGun")
```
## Targeting
- `first` targets the enemy furthest along its path, `last` the one least far along. For spawnerKit path enemies the kit reads their place on the route. For your own movers, give it a number with `TK.setProgress(function(id, pos) return myProgress[id] end)`, or per target with `TK.addTarget(e, { progress = fn })`. Otherwise the enemy seen longest counts as furthest.
- `nearest` is the closest enemy to the turret. `strongest` and `weakest` compare health plus shield.
- Ties fall back to progress, then to the entity id, so every machine agrees.
- Only candidates inside range (and outside the mortar's minimum range), inside the turn limits and in clear line of sight are picked. Mortars and poison throwers lob over walls, so they need no sight line and ignore the up/down limit.
- A mode of your own: `TK.defineTargeting("lowestArmor", function(a, b) return armor(a.id) < armor(b.id) end, "Lowest armour", { "targeting", "armor" })`. The label and tags are optional.
Targets are anything with SecondWind health on another team: spawnerKit enemies, aiKit characters, props, and players when `targetPlayers` is on. `TK.addTarget(e, { team, progress, health, layer, hidden })` adds something without SecondWind health.
### Layers (air and ground) and stealth
Every target has a **layer**, `"ground"` or `"air"`, and can be **hidden** (stealthed). A turret type says which layers it can shoot and whether it can see hidden targets, with three optional fields in its `.data` file (or `TK.define`):
| field | default | meaning |
|---|---|---|
| `hits` | `[]` (both) | the layers it shoots: `["ground"]`, `["air"]` or `["ground", "air"]`. Empty means both, so every turret written before layers existed shoots everything, as before. |
| `detects` | `false` | it can see and shoot hidden targets. |
| `detectRange` | `0` | how far it sees hidden targets, in metres; 0 = its whole range. A tier may set its own `detectRange`. |
Where a target's layer and stealth come from:
- **A hook**: `TK.setTargetInfo(function(id, cand) return { layer = "air", hidden = true, lift = 2.2 } end)`. Return nil to keep the defaults. `lift` raises the point turrets aim at and measure range to, for a flier drawn above its entity; `progress` (optional) replaces the path progress the kit worked out, which arrives as `cand.progress`. An enemy roster kit (such as creepsKit) installs this hook; `TK.setTargetInfo(nil)` removes it.
- **Per target**: `TK.addTarget(e, { layer = "air", hidden = false })`.
- **By default**: a spawnerKit enemy whose kind hovers (`hover > 0`, such as the sample `flyer`) is `"air"`, everything else `"ground"`, and nothing is hidden.
What each attack does with them:
- **Picking a target** (every targeting mode) skips layers the turret does not hit and hidden targets it cannot detect. A tracked target that turns hidden or moves out of the turret's layers is dropped at once.
- **Chain lightning** only jumps to targets the turret could pick itself; a **sniper's pierce** only hurts those.
- **Splash, clouds and flame cones** hurt every target in a layer the turret hits, **hidden ones included**: a blast needs no sight. That is how a game reveals stealthed enemies, by noticing they were hit.
- **Walls** only block ground targets; fliers pass over them.
None of the twelve turrets declares `hits` or `detects`, so they all shoot both layers and none detects. Make a ground-only cannon or a detecting sniper with one line each:
```lua
TK.define("cannon", { hits = { "ground" } }, "cannon")
TK.define("sniper", { detects = true, detectRange = 9 }, "sniper")
```
`TK.canEngage(ctx, cand, dist)` is the rule itself (`targeting.canEngage`), for games that pick targets of their own.
## Tags
Every entry in the three lists carries its tags, so a build menu, a shop or a designer tool can filter and pick from them without opening each asset:
```lua
local TK = require("turretsKit.api")
for _, t in TK.types() do print(t.id, t.label, table.concat(t.tags, ", ")) end
for _, s in TK.styles() do print(s.id, table.concat(s.tags, ", ")) end
for _, m in TK.modes() do print(m.id, table.concat(m.tags, ", ")) end
TK.types("splash") -- only the turret types tagged "splash": cannon, mortar
TK.styles("fantasy") -- medieval
TK.modes("health") -- strongest, weakest
print(table.concat(TK.info(entity.find("Gun")).tags, ", ")) -- a placed turret's type tags
```
- **Turret types and looks** take their tags from the `tags` list in their `.data` file (`tags: ["turret", "tower-defense", "cannon", "splash"]`). Both contracts have the field, so a turret or look you add carries its own tags. `TK.define` / `TK.defineStyle` take a `tags` list the same way.
- **Targeting modes** carry the kit's tags: `first` path, progress, front, stop-leaks; `last` path, progress, back, rear-guard; `nearest` distance, close-range, fast-switch; `strongest` health, tank-buster, boss; `weakest` health, finisher, crowd-thinning (all also `targeting`). A mode you define takes its tags as the fourth argument of `TK.defineTargeting`.
- A tag filter is one tag, matched without regard to case. An unknown tag gives an empty list.
## Turn limits
Each type's `turn` block sets `yawMin`/`yawMax` (left and right of the home facing, -180..180 = all the way round), `pitchMin`/`pitchMax` (down and up) and `yawSpeed`/`pitchSpeed` in degrees per second. A turret never turns past its limits: aim is rate-limited and clamped, and targeting skips anything outside the arc. A turret with limits sweeps inside its own arc when idle.
## Upgrades, selling and money
```lua
TK.setEconomy({
spend = function(cost, info) if gold >= cost then gold -= cost; return true end; return false end,
refund = function(amount, info) gold += amount end,
})
TK.upgrade(t) -- true, or false + "money" / "max"
TK.sellValue(t) -- what selling gives back now: 70% of everything spent, by default (`sellRate` per type)
TK.sell(t) -- refunds through the hook, fires `sold`, removes the turret
TK.place(pos, "cannon", { targeting = "strongest", yaw = 90 }) -- build from code, paying tier 1's cost
```
`info` is `{ turret, def, tier, by, reason = "build" | "upgrade" | "sell" }` (`turret` is the turret entity's id, `def` its type). The hooks run on the machine in charge of the turret. Calls made on another player's machine are sent to it. Without hooks, building and upgrading are free and selling refunds nothing.
Events: `TK.on(name, fn)` for `built`, `upgraded`, `sold`, `changed`, `fired`, `kill`, `targetChanged` or `"*"`. The payload names the turret (its entity id), its `def`, tiers, cost or value, and `by`. Money events reach every player, with `payload["local"] == true` on the machine where it happened, so act on money only there. `fired` is raised once per shot; the laser and the flamethrower fire continuously and raise no `fired`.
## Looks
`TK.setStyle("medieval")` sets the world default for every turret whose `style` is `auto`. Call it in code every player runs, such as a scene entrypoint. `TK.setStyleAll(id)` writes every turret's own synced style, and `TK.setTurretStyle(t, id)` changes one. Each style is a `.data` file of the `turretsKit.turretStyle` contract: materials and colours per part, base shape (sci-fi plate, medieval stone tower with battlements and a banner, toy block with studs), and which projectile looks its shots use (blue tracers and plasma, crossbow bolts and cannonballs, foam darts and rubber balls). `TK.defineStyle(id, fields, base)` adds one from code.
## Labels on any screen
Every screen draws its own turret labels, so each player can have the layout that suits their screen. Nothing here is synced.
- `TK.setLabelLayout("wide")` (the default): two lines per label, the name, then tier and targeting.
- `TK.setLabelLayout("stacked", { scale = 1.9, rowSpread = 1.6 })`: one word per line, bigger, for a tall narrow screen such as a phone held upright. A stacked label stands on its row height instead of centring on it, and rows lined up with `labelAt` move apart by `rowSpread`, so a tall label never reaches the row above.
- `TK.labelLayout()` reads this screen's layout back.
- `TK.setLabelPlacement(turret, { size, lift, at })` places one turret's label on this screen only, overriding its `labelSize` / `labelLift` / `labelAt` here (leave one out to keep the Turret's; `nil` clears it). `TK.labelPlacement(turret)` reads it back. A turret is a synced entity that only its owner may change, so a screen that lays labels out for itself, such as another player's phone held upright, does it through this rather than by writing the Turret's own fields (the engine refuses those writes from anyone but the owner).
Labels always stand a little toward the camera the screen is drawn from, so a tall part of a model (the support beacon's dish and mast in the medieval and toy looks, say) passes behind the text rather than in front of it.
The Bastion Works gallery lays its labels out for each player's own screen with its `gallery.PhoneFraming` part on the player's camera rig. It is gallery code, not part of the kit; copy it for your own scene, or call `TK.setLabelLayout` and `TK.setLabelPlacement` from your own camera code. What it does:
- **One layout, not a shuffle.** When the screen changes shape it hides the labels, frames the camera, waits until the camera has stopped moving, measures every turret label, pad sign and title line once (as the engine's billboard shader draws it: facing the camera, horizontal edge level), works the whole layout out as arithmetic for the largest text that fits, applies it in one go, checks it on screen and shows the labels. If the on-screen check disagrees with the arithmetic, it starts over from a still camera (up to three times). Nothing moves on screen meanwhile, and the work is spread over frames (12 ms at a time), so the game keeps running. How long the labels take to appear depends on the screen: about 2 to 6 s on a desktop window, about 5 to 15 s on a phone held upright, and up to about 20 s on a phone held sideways, where it may step the camera back a few times to find room.
- **What it keeps clear of:** other labels and signs (a gap of at least max(3 px, 0.8% of the width), plus a couple of pixels of margin sideways), the screen's edges, Second Wind's kill feed (measured from the HUD's own layout and its row count), the wall's health bar and this player's own name tag. Every gallery line is at least 10 px tall.
- **Per shape:** held upright, the view widens, labels stack one word per line and the title, subtitle and hint stack above the top row. Sideways and on a desktop, labels stay two lines in rows that spread across the width (sliding sideways by their anchor, and re-aimed at their row as they slide), and the title sits in one band beside the kill feed, or in two tiers when the band doesn't fit. On a short sideways screen the camera starts further back.
- **The kill feed on a short screen:** on a sideways screen under 600 px tall (a phone held sideways, or a window that size), this player's own kill feed shows **2 rows** instead of the scene's 4, whatever size the UI is drawn at. The rule is checked four times a second, so it holds after a HUD is rebuilt, and the scene's 4 rows come back when the screen grows. Second Wind's files are untouched; it is the HUD's own `maxFeed` field on this screen.
- **When labels change** (a look swapped, a pad pressed, a joining player's turrets arriving) it lays out again from where things stand, without hiding. If a look swap rebuilds a label while a layout is being applied, it shows the labels and lays out again rather than getting stuck.
- **On a joining player** it places turret labels with `TK.setLabelPlacement`, since only a turret's owner may change the turret. A pad pressed on a joining player's screen shows the requested value on its sign at once; the turret itself changes when the host has applied it (about 3 s in our check).
- **If nothing fits cleanly** even after giving the view more room, it shows its closest layout at the 10 px size and reports `laidOut = "closest"`. That didn't happen in any run of the final build listed below.
Checked with a measuring script that projects every text box on screen the same way. On the final build of 2.1.0, as the host, 17 runs, all clean:
- **Phone held sideways (844×390), 9 runs:** with the UI drawn at desktop size (as in an 844×390 window) toy three times, one right after a swap from sci-fi, plus medieval and sci-fi once each; with the UI sized like a real phone's, toy twice, plus medieval and sci-fi once each. The kill feed showed 2 rows in every run.
- **Phone held upright (390×844), 5 runs:** medieval twice, toy and sci-fi with a phone-sized UI, and toy with a desktop-sized UI.
- **1280×720 window, 3 runs:** sci-fi, medieval and toy, every line at least 12.7 px.
"Clean" means no text overlapping or touching another, none near an edge, none under the kill feed, and every gallery line at least 10 px tall. The engine's own player name tag can be smaller than 10 px; it is kept clear of but not sized by the gallery. As a player who joined the host's game, upright, sideways and desktop were checked on the build before these sideways fixes (all clean then) and were not repeated on the final build. Screen sizes other than these weren't checked.
## Performance budget
Designed for **12 to 30 turrets firing into 30 to 60 enemies at once**. Measured in the gallery with all twelve turrets firing into 60 dummies under the web budget:
- **turretsKit and projectileKit together cost about 31 ms of script time per second of play**, about 0.5 ms a frame at 60 fps. That's 3% of the frame time measured in that fight.
- **Nothing is made fresh per shot.** In an 8-second window: 73 shots fired, 73 reused shot records and 0 new ones; 0 new pooled entities; the world's entity count stayed exactly flat.
**Shots in the air:**
| budget | shots flying at once | drawn at once | effects (puffs, bolts, rings) |
|---|---|---|---|
| desktop | 1,500 | 600 | 900 |
| web | 1,000 | 360 | 500 |
| phone | 600 | 220 | 260 |
- **Past the flying limit,** a new shot lands at once, so no hit is ever lost.
- **Past the drawn limit,** a shot still flies and hits; it just isn't drawn.
- **The budget is picked automatically when the first turret runs**, from the platform the engine reports and the screen: the desktop app gets `desktop`, a browser gets `web`, and Android or a screen whose short side is under 700 px gets `phone` (`PK.budgetFor` in projectileKit is the rule). `TK.setBudget("web")` forces one.
- **Real fights use a small part of it:** the 60-dummy test peaked at 13 shots in flight, because beams, lightning, sniper rays and flames aren't projectiles.
**Why it stays smooth:**
- **No garbage per frame:** moving, aiming and drawing a thousand shots allocates nothing (a test checks it). Shot records, effect records and pooled entities are recycled, including shots that land over budget or are cleared mid-flight. Scanning a crowd shares one target list per team.
- **Cost of the shot loop on desktop:** 300 shots in flight cost 0.2 ms a step, 600 cost 0.3 ms, 1,000 cost 1.35 ms.
- **Damage is batched:** hits on one target are added up per damage type and handed to Second Wind every 0.12 s on desktop, 0.2 s on web and 0.25 s on phones (`TK.DAMAGE_FLUSH`). Each Second Wind hit flashes the target, shows a number and, in multiplayer, sends a message.
- **No knockback** from turret hits (`TK.combat.KNOCKBACK = 0`). Second Wind's default shove for explosions moved every enemy every frame, and was the biggest cost the kit measured: about 90 ms a frame with one cannon. Set it above 0 if you want shoves.
- **One network message a frame** carries every shot the machine in charge fired. Aim is synced 4 times a second; labels refresh 4 times a second.
- **Models are built once:** each turret's model is 15 to 40 local parts, rebuilt only when its type, tier or style changes.
## Multiplayer
- The machine in charge of a turret (its owner, or the room host while nobody owns it) picks its target, turns, fires and deals the damage through SecondWind. It writes `target`, `state` and its aim to synced fields.
- Every other machine turns the same model onto the same target and draws the same shots, from one batched message a frame. It never deals damage itself, so a hit lands once. Health, deaths and burns come from SecondWind's synced state.
- `TK.set`, `TK.upgrade` and `TK.sell` work from any machine. They are sent to the one in charge, and the change syncs to everyone.
- **Every peer picks the same target.** Only the machine in charge picks; the others read its synced `target`. The rule itself is deterministic too: ties fall back to progress along the path, then to the entity id, so the same enemies give the same pick in any order.
- **Slows and wall holds land on the enemy's owner.** An enemy's speed belongs to the machine that moves it (the spawnerKit host). A frost turret or wall placed by another player sends that machine a short *speed lease*, renewed every 0.3 s while the slow or hold lasts. The owner applies the strongest one, and a lease that isn't renewed ends after 0.6 s, so an enemy never stays stuck if a player leaves. Damage needs no lease: SecondWind already sends a hit to the target's owner.
- **Turrets belong on synced entities** (`entity.spawnSynced`, which `TK.place` uses). A turret on a plain local entity is run by the room host alone, so it can never fire twice, but other players see it idle. `TK.addTurret` warns when that happens.
- The tests cover this side: the same pick from any order, a replayed shot dealing no damage, slows on another peer's enemy sent as leases, and leases applied and expiring on the owner.
- **What other players see is late, not different.** Targets, health and kill counts reach every other screen as synced values, after the engine's sync delay. Our own two-player runs on one machine measured about 0.1 s, but a second player on another connection saw the host's game **1.5 to 3 seconds behind**. A synced value carries only its latest state, so when health changes several times within that delay, the in-between values can be skipped on the other screen (it jumps, say, from 80 to 40); the final value and the death always arrive. Nothing here makes the screens agree at the same instant.
- **Checked with two players** in the Bastion Works gallery (2.1.0): a second player joined the host's game, and both screens sampled every turret's target and every dummy's health four times a second for about 90 s. Every target the host held for 0.7 s or more showed on the second screen too (188 of 188), matching at the same moment in 97% of samples; the rest were moments when one screen had just switched. Every health value the host showed reached the second screen in the same order, usually within 0.1 s. Right after joining, turret targets were correct from the first frame; a dummy's health could be stale for a while, an engine delivery delay that has since been fixed ([#19353](https://github.com/OrigoZero/zero/issues/19353)). A second run on the released 2.1.0 code, in a freshly started game, also compared kill counts: over 60 s every target (124 of 124), health value (55 of 55) and turret kill count (37 of 37) the host showed reached the second screen, and the kill totals went from 93 to 122 on both.
- **Checked with two players again on 2026-10-31 (2.1.1)**, the host in a web browser and a second player in the desktop app. On the second player's screen over 30 s: all 13 gallery turrets were run by the host and none by the second player, their targets switched 96 times and their aim moved 569 times, and 285 shots were drawn. The second player's machine dealt no damage and made no Second Wind calls. Every damage event carries the target's health after the hit: 117 of 117 hits lowered health by exactly their own amount, none twice (8 more fell across a dummy's respawn and were left out). The host's game reached the second player about 2 s behind.
## Living beside spawnerKit's turret
Wavecaller spawnerKit ships a small zapper turret of its own, `spawnerKit.Turret` (`SK.addTurret`). It is a different component in a different package, so both can stand in one world. turretsKit's API is `TK.addTurret`, its component is `turretsKit.Turret`, and neither kit reads the other's turrets. Both shoot spawnerKit enemies through SecondWind.
## Reference
- `turretsKit.api` (`TK`): `addTurret`, `place`, `set`, `setDef`, `setTargeting`, `setTier`, `setTurretStyle`, `setStyle`, `setStyleAll`, `defaultStyle`, `styleOf`, `cycle`, `upgrade`, `sell`, `sellValue`, `setEconomy`, `on`, `info`, `stats`, `types`, `styles`, `modes`, `all`, `runtime`, `define`, `defineStyle`, `defineTargeting`, `addTarget`, `removeTarget`, `setProgress`, `setTargetInfo`, `canEngage`, `speedMultiplier`, `onSpeed`, `boostFor`, `setBudget`, `report`, `setLabelLayout`, `labelLayout`, `setLabelPlacement`, `labelPlacement`, `kits` (a shortcut to the spawnerKit, SecondWind and aiKit modules, which are also required by their own names), `VERSION`
- `turretsKit.catalog`: data reading, `stats(type, tier, boost)`, `costs(type, tier)`
- `turretsKit.targeting`, `turretsKit.aim`: the pure targeting and turning rules (used by the tests)
- `turretsKit.targets`, `turretsKit.combat`, `turretsKit.net`, `turretsKit.brain`, `turretsKit.looks`: candidates, damage and status effects, networking, the aiKit state machine, and the models
- Slows: spawnerKit enemies are slowed by scaling their speed. For your own movers, read `TK.speedMultiplier(id)` or subscribe with `TK.onSpeed(fn)`.
## Tests
`tools.use("tests", "run", { suites = { "turretsKit" } })` in edit mode runs 30 tests:
- **targeting**: all five modes, ties, range, minimum range, arc reasons, custom modes
- **turn limits**: rate and clamp, the short way round, a real turret ignoring a target behind it and seeing it once turned
- **data**: the twelve types and three styles, every tier improving, the special numbers per tier, costs and sell values
- **live swapping**: targeting, type (the one `def` field), tier and style changed on a running turret, with bad names refused
- **money**: upgrade cost, refusal and max tier through the economy hook; selling's value, refund, event and removal; `place`
- **damage**: pooled damage reaching SecondWind health, and slows
- **multiplayer**: the same pick from any order, replayed shots dealing no damage, slows on another peer's enemy sent as leases, and leases applied and expiring on the enemy's owner
- **tags**: every turret type, look and targeting mode listed with its tags, the lists filtering by a tag, and a placed turret reading its tags back
- **labels**: the wide and stacked label layouts, switching, options and refusing an unknown layout; a per-screen label placement that leaves the turret's own synced fields alone
- **install**: the kits turretsKit is built on come with it, answer to their own names (`require("spawnerKit.api")`, `"SecondWind.api"`, `"aiKit.fsm"`, `"aiKit.presets"`) and are the same modules as `TK.kits`; kill credit keeps counting after Second Wind reloads
projectileKit has its own 13, so 43 tests run in all. In a world where turretsKit is the only install, both suites show up and pass. The suites wait for nothing and take about 13 s; a test run itself can sit waiting a long time before it reports ([#19849](https://github.com/OrigoZero/zero/issues/19849)).
## Known limits
- **The web build runs at about 18 fps in the gallery.** Measured by the world's owner in a browser on 2026-10-31: 20 seconds of play in the Bastion Works gallery (thirteen turrets firing into the dummies), about 18 fps on average and 23 fps median. The numbers above this section are from the desktop app with the web budget forced, because the web build can't be checked from the session that builds the kit ([#20946](https://github.com/OrigoZero/zero/issues/20946)). The web build's frame rate drops in busy multiplayer scenes whatever the kit does ([#20750](https://github.com/OrigoZero/zero/issues/20750)).
- **A big crowd costs more than the turrets do.** With 60 dummies walking, frames were slow in the desktop editor even with every turret switched off (about 180 ms). That time went to the engine replicating 60 moving synced enemies and their parts. turretsKit can't remove this cost. A web or phone game should keep its crowd smaller, use simpler enemy models, or both.
- **Hits cost the health kits time.** Every hit that reaches Second Wind runs its and Lifeline's hit handling: health sync, hit number, and a red flash that recolours every part of the target. With fire spread over a large crowd that was about 6% of the frame. turretsKit already batches hits (see `TK.DAMAGE_FLUSH`). Switching off Lifeline's `flashOnHit` on crowd enemies saves a little more.
- **What can differ between screens, by design:**
- **Delay:** a shot appears on other screens about one network delay after it fires.
- **Aim:** a turret's aim angle is sent 4 times a second when it moves more than 2°, so other screens turn it a little later.
- **Projectiles:** a tracer or missile flies toward where *that* screen sees the target, so its impact flash can sit a few centimetres off. The damage, health bars, deaths and kills are SecondWind's synced values and match exactly.
- **Flames:** the puffs of a flamethrower are scattered at random on each screen. They are cosmetic only; burn damage is dealt once by the owner.
- **Slows from another player's turret:** one network delay late to start and to end, plus up to 0.1 s.
- **If the player who owns a turret leaves:** what happens depends on the engine handing its entity to someone else. The kit follows the owner, or the room host while nobody owns it, but that hand-over hasn't been tested.
- **On a long-running engine, the owning player can treat its own synced things as nobody's.** Damage and synced changes it should apply then never land: hits on its turrets' targets, a wall's health, a turret's synced setting. This is the engine's ownership bookkeeping, not turretsKit; a fresh session starts clean. [#20713](https://github.com/OrigoZero/zero/issues/20713).
- **A player who joins a world with many turrets can get a much lower frame rate than the host** ([#20957](https://github.com/OrigoZero/zero/issues/20957)). It is the engine's cost of receiving many synced, moving things; the joining player's turrets deal no damage and run no targeting.
- **Two sessions on one account are one player.** Two engines signed in to the same account collide as one player ([#14448](https://github.com/OrigoZero/zero/issues/14448)), so trying turrets with a second player needs a second account.
- **An install lays down pinned copies of two engine files.** A brand-new world that installs turretsKit also gets copies of the engine's spline module and debug-geometry shader under `deps/07158574…/versions/`, pinned at the version a kit it brings was published against, instead of using the engine's own ([#20268](https://github.com/OrigoZero/zero/issues/20268)). In the 2026-10-31 check nothing logged an error and the quick start ran; the old editor fly-camera copy that used to switch the editor cameras off is no longer laid down.
- **Installs take a while.** One install of turretsKit brings 11 kits and dependencies (711 files). It took about 10 s in our check, but installs with many dependencies can take a minute or more ([#21420](https://github.com/OrigoZero/zero/issues/21420)).
- **An install can list missing-reference problems on module versions that didn't change**, even though everything resolves ([#22120](https://github.com/OrigoZero/zero/issues/22120)). The installs of turretsKit made on 2026-10-31 listed none.
- **Match Flow's own module doesn't arrive with an install.** In a fresh world, `require("MatchFlow.api")` answers "module not found": the install lays down Match Flow's components and most of its modules but not `api` ([#22186](https://github.com/OrigoZero/zero/issues/22186)). The `MatchFlow` component works; use it by name, as the tower defense guide does.
- **The guides and the tower defense scene don't come up in library search.** Both guides ship inside the package and arrive with every install (`turretsKit.package/addTurretsToYourGame.guide` and `turretsKit.package/makeATowerDefenseGame.guide`), and the scene is in the Bastion Works world, but none of the three has a library record, so ZeroMind's library search doesn't find them ([#22181](https://github.com/OrigoZero/zero/issues/22181)). Open the guides from the installed package.
- **ZeroMind's description can lag a release.** For a while after a release, the description ZeroMind shows for turretsKit can still be the previous version's ([#19258](https://github.com/OrigoZero/zero/issues/19258)). This README and `package.yaml` are the ones the release ships.
- Turret models are built from the engine's simple shapes, not authored meshes. (A choice, not a platform issue.)
The limits on browser speed, crowd cost and hit cost, the screen-to-screen differences and the owner hand-over are measurements and design notes; the others are open engine issues, all open on 2026-10-31.
## Version
**2.3.2**: the copy of SecondWind in this kit's world is SecondWind's own release again. It still carried an unreleased crowd patch to `api.module`, so turretsKit recorded that file and every world that installed it got a second copy of SecondWind's API beside its own: turrets read targets from the copy no enemy registers with and never fired. The crowd patch waits in SecondWind's own tracker. No turretsKit code changed.
**2.3.1**: SecondWind brought to its current release (1.4.6 as published). 2.3.0 pinned an older SecondWind copy, so a world that installed turretsKit beside the current SecondWind got a second copy of its API, and turrets looked for targets in a registry no enemy registers with: they never fired. No turretsKit code changed.
**2.3.0**: brings MatchFlow 1.4.0 (waves with build breaks and call-early, `endRound`, endless waves, late joiners in co-op, `showResults`), which towerDefenseKit runs its match on. The dependency copies that came with it (Lifeline, juiceKit) are their current releases. No turretsKit code changed.
**2.2.0**: target layers and stealth. Turret types may say which layers they hit (`hits`: ground, air) and whether they see hidden targets (`detects`, `detectRange`); targets get a `layer` and `hidden` flag from `TK.setTargetInfo`, `TK.addTarget` or spawnerKit's hovering kinds. Every existing turret still hits both layers and nothing is hidden by default, so nothing you already wrote changes (see [Layers (air and ground) and stealth](#layers-air-and-ground-and-stealth)). Four new tests.
**2.1.4**, published from the Bastion Works world, whose gallery shows every turret, mode, tier and style, and whose `towerDefense` scene is the finished level of the tower defense guide.
What changed since 2.1.3 (no change to the kit's code; nothing you already wrote breaks):
- **Clearer library descriptions** for turretsKit and projectileKit (now 1.0.2): what you get, how to install, where to start.
- Built and tested on the engine library `ab1aa41` (was `7fd8247`).
What changed in 2.1.3, since 2.1.2 (no change to the kit's code; nothing you already wrote breaks):
- **The dependency table says what really arrives for Match Flow:** part of the package, without its `api` module, so it is reached through its component ([#22186](https://github.com/OrigoZero/zero/issues/22186), now also in Known limits).
- **Known limits name [#22181](https://github.com/OrigoZero/zero/issues/22181):** the guides and the tower defense scene have no library records and don't come up in library search.
- Built and tested on the engine library `7fd8247` (was `d1046d5`).
What changed in 2.1.2, since 2.1.1 (no change to the kit's code; nothing you already wrote breaks):
- **The tower defense guide's level starts a new round properly.** After a win or a loss the towers are removed, the keep comes back with 20 lives and enemies that get through cost lives again. In 2.1.1 the round reset read `TK.all()` as a list of entities; it is keyed by the turret's entity id, so the reset stopped with an error before reviving the keep.
- **Pressing Play again no longer pays twice.** turretsKit, spawnerKit and Second Wind keep their listeners for the engine session, so the level now disconnects everything it listens to in `onUnload`.
- **Wave pay is stated and paid the same way:** 60 gold when wave 2 starts, then 80, 100 and 120 (2.1.1 paid 80 at wave 2 while the guide said 60).
- **The guide says what the menu does:** menusKit covers the whole screen while the build menu is open; the guide no longer claims the battle stays in view.
What changed in 2.1.1, since 2.1.0 (no code changes; nothing you already wrote breaks):
- **Two guides ship in the package.** "Add turrets and towers to your game" (`addTurretsToYourGame`) says what the kit is, how its parts fit with the kits it brings, and what to do first. "How to make a tower defense game" (`makeATowerDefenseGame`) builds a five-wave level from an empty world: enemies on a road, towers you pay for, upgrade and sell at build pads, gold from kills and waves, a keep with 20 lives, victory after the last wave and defeat when the keep falls. It uses turretsKit with spawnerKit, Second Wind and MatchFlow, plus economyKit (gold), menusKit (the menu), interactKit (the pads) and barsKit (health bars).
- **The quick start's tesla coil fires.** The tesla coil and the machine gun swapped places, so the coil stands first along the path. In 2.1.0 the machine gun upstream killed nearly everything before it reached the coil, which never fired.
- **A test no longer depends on the world's look.** "a turret ignores what is outside its arc" failed in a world whose default look was medieval (the stone tower raises the gun, so a target 7 m away on the ground falls below that test turret's pitch limit). The test turrets now use a fixed look.
- **Docs:** `fired` is now documented as once per shot (the laser and flamethrower raise none); built and tested on the engine library `d1046d5` (was `729614c`); Known limits list only open issues, each with its issue number, and [#19353](https://github.com/OrigoZero/zero/issues/19353) is gone because it was fixed.
What changed in 2.1.0, since 2.0.2 (nothing you already wrote breaks):
- **The kits turretsKit brings answer to their own names.** The engine now installs Second Wind, spawnerKit and aiKit as whole packages of the installing world, so a game's own scripts use `require("spawnerKit.api")`, `require("SecondWind.api")`, `require("aiKit.fsm")` and `require("aiKit.presets")`. The quick start and the barsKit snippet use them the plain way. `TK.kits` stays as a shortcut to the same modules. A test checks both.
- **Labels on another player's screen.** New `TK.setLabelPlacement(turret, { size, lift, at })` / `TK.labelPlacement(turret)` place a turret's label on this screen only. The gallery's per-screen layout used to write the Turret's own `labelSize` / `labelAt` fields, which the engine refuses from anyone but the turret's owner, so a second player's phone held upright kept the as-built labels, overlapping. The Turret now reads this screen's placement first.
- **Kill credit after Second Wind reloads.** A turret's `kills` count (and the `kill` event) stopped when Second Wind's module re-ran, because turretsKit's subscription stayed on the old one. It now subscribes again. A test checks it.
- **The gallery on every screen shape** (gallery code, not the kit): labels are measured the way the engine draws them (facing the camera) and the whole layout is worked out once, from a camera that has stopped moving, and applied in one go, with the labels hidden meanwhile, instead of being nudged on screen until it settled. It keeps clear of the kill feed (measured from Second Wind's own HUD), the wall's health bar and the player's name tag, lays out sideways and on desktop too, works on a joining player, and recovers if a look swap rebuilds a label mid-layout. A phone held sideways (844×390) lays out cleanly in every look, with the UI drawn at desktop size or phone size, and its kill feed holds to 2 rows. See [Labels on any screen](#labels-on-any-screen) for what was checked.
- **Pad signs keep up.** The "STYLE OF EVERY TURRET" sign shows the look the turrets actually wear (it showed one screen's default before, so it could say scifi after a switch to medieval), and a pad pressed on a joining player's screen shows the requested value at once instead of waiting for the host's change to come back.
- **Checked with two players:** the second screen showed every turret's target and the dummies' health and kill counts the host showed, after a sync delay (about 0.1 s in our runs on one machine, 1.5 to 3 s for a player on another connection, who could also miss in-between health values). A joining player can see a dummy's health stale for a while: that is the engine's [#19353](https://github.com/OrigoZero/zero/issues/19353), now in Known limits. [#20838](https://github.com/OrigoZero/zero/issues/20838) was fixed in the engine and its limit is gone.
- **Docs:** the dependency table says how each kit arrives (whole packages, with navKit listed and MatchFlow's current published version). 30 tests (43 with projectileKit's 13).
What changed in 2.0.2, since 2.0.1:
- **One install is all a game needs.** turretsKit now hands out the kits it brings as `TK.kits`: `TK.kits.spawnerKit`, `TK.kits.SecondWind` and `TK.kits.aiKit` (its `fsm` and `presets`). An install of turretsKit brings Second Wind, spawnerKit and aiKit as copies pinned to the tested versions, which code outside turretsKit can't `require` by name, so in 2.0.1 a world with only turretsKit installed could run turretsKit but not its own quick start.
- **The quick start runs as written in an empty world.** It now takes spawnerKit and Second Wind from `TK.kits` instead of requiring them by name. It was run that way in a brand-new world where turretsKit was the only install.
- **Docs:** Install says what an install actually brings and how to reach it; the dependency table's *How it arrives* column says the same per kit; Known limits lists the `TK.kits` limit; a test checks `TK.kits`.
- **The gallery held upright on a phone:** the title, the outer turret labels and the pad signs no longer run off the sides. On a screen taller than wide, the gallery's new `gallery.PhoneFraming` part widens the view to fit and lays every turret label, pad sign and title line out by measuring it on that screen (readable size, none touching, none near an edge), and turretsKit gained the per-screen `TK.setLabelLayout` / `TK.labelLayout` for it. Landscape is as before.
- **The support beacon's label in every look:** labels now stand a little toward the camera drawing them, so the beacon's dish and mast in the medieval and toy looks pass behind "+25% fire rate" instead of covering it. The rows stay where they were.
- **Known limits** describe each limit the way its open public issue does: [#20713](https://github.com/OrigoZero/zero/issues/20713) (the owner treating its own synced things as nobody's), [#20838](https://github.com/OrigoZero/zero/issues/20838) (`TK.kits`), [#20268](https://github.com/OrigoZero/zero/issues/20268) (pinned engine-file copies). A label-layout test brings the count to 27 (40 with projectileKit's).
- **Correction:** the 2.0.1 README said the quick start ran as written in a fresh world. It didn't: it stopped at `require("spawnerKit.api")`. That sentence was written before the check was run.
What changed in 2.0.1, since 2.0.0:
- An install of turretsKit brings the kits it runs on from their own worlds. 2.0.0 needed a four-id install call ([OrigoZero/zero#20714](https://github.com/OrigoZero/zero/issues/20714), fixed in the engine). Second Wind, spawnerKit and aiKit were installed fresh in Bastion Works on the fixed engine so turretsKit records each as coming from its own world.
- The turret brain uses Watchful Minds aiKit 1.1.0 as published instead of a two-module copy, and Bastion Works no longer publishes a package of its own named aiKit.
What changed in 2.0.0, since 1.0.0:
- **Breaking:** a turret is set up with exactly two named settings, **`def`** (which turret it is; it was `turret` in 1.0.0) and **`targeting`** (how it picks targets). Set one up with `{ def = "tesla", targeting = "nearest" }`. Swap it with `TK.set(e, "def", "laser")` or `TK.setDef(e, "laser")` (it was `TK.setTurret`), and step through the types with `TK.cycle(e, "def")`. `TK.info` and the kit's events report the type as `def` too (they said `type` in 1.0.0). To update a 1.0.0 world, rename `turret =` to `def =` in its `TK.addTurret` / `component.add` tables, `setTurret` to `setDef`, and `.type` to `.def` where it reads `TK.info` or an event.
- **Tags in every list:** `TK.types()`, `TK.styles()` and `TK.modes()` return each entry's tags, take an optional tag to filter by, and `TK.info` carries the type's tags. The turret type and look contracts gained a `tags` field, and the targeting modes now have tags.
- **Budgets on the web and phones:** the automatic budget recognises a browser (`web`) and a small or Android screen (`phone`).
Release history, honestly:
- **1.0.0** was meant to be one release, but it went out on 2026-10-23 as five published versions (around 17:01, 17:22, 17:36, 17:54 and 18:14 UTC), one per fix round (packaging, multiplayer, performance, gallery polish), all under the version number 1.0.0. That can't be undone.
- **2.0.0** was published around 20:00 UTC on 2026-10-23, then twice more the same evening under the same number (around 20:39 and 21:50: the last `def` naming, issue links, and the web and phone budgets). So 2.0.0 has three published versions.
- **2.0.1** was published once, around 06:50 UTC on 2026-10-24. Its fresh-world check then found that the quick start didn't run with turretsKit as the only install.
- **2.0.2** was published around 07:20 UTC on 2026-10-24, then twice more the same morning under the same number, as asked: once with the phone-portrait gallery, the support beacon's label and the corrected Known limits, and once with the measured phone layout. So 2.0.2 has three published versions. The last one's phone layout still overlapped on a real upright phone (it measured labels as flat to the screen, and on a second player's screen its writes were refused); 2.1.0 fixes both.
- **2.1.0** was published on 2026-10-24 and then twice more the same evening under the same number, as asked: the second time with the gallery's layout rebuilt (no shuffling, the real kill feed, sideways and desktop, joining players) and the pad signs fixed; the third time with a phone held sideways laying out cleanly in every look, the kill feed holding to 2 rows on a short screen, and the multiplayer wording corrected to say other players see the host's game after a delay. The kit's own code is the same in all three; only the gallery and the docs changed. projectileKit is unchanged and stays 1.0.0.
- **2.1.1** was published once, on 2026-10-31.
- **2.1.2** was published once, on 2026-10-31.
- **2.1.3** was published once, on 2026-10-31.
- **2.1.4** was published once, on 2026-10-31, and is the current version. projectileKit moved to 1.0.2 with it (its description only, no code changes).
# Lifeline, health, damage & respawn kit
Drop-in health for anything that can get hurt (players, enemies, breakable props), with damage zones, heal zones, projectiles, respawning, events for your own scripts, and a large wardrobe of looks: **13 health bar styles, 7 damage-number styles (4 presets) and 5 mix-and-match hit effects**, all switched by changing one field. Multiplayer-safe: only the peer that owns an entity decides what happens to its health.

## Installing it into your world
The package is called **Lifeline**, asset `Lifeline.package`, guid `7b85ce05-3903-4374-b654-2d4ffea295a5`, MIT licensed. (Its showcase world is *Lifeline, Health, Damage & Respawn Kit*.)
One install, any of these ways:
- **From the ZeroMind library in the editor**, search for `health` or `Lifeline` and install the **Lifeline** package.
- **By guid, from the engine shell:**
```
zero zeromind installAsset 7b85ce05-3903-4374-b654-2d4ffea295a5
```
- **From Luau:**
```lua
tools.use("zeromind", "preview", "7b85ce05-3903-4374-b654-2d4ffea295a5") -- what it would write
tools.use("zeromind", "installAsset", "7b85ce05-3903-4374-b654-2d4ffea295a5") -- do it
```
- **From an agent:** `zeromind.install { guid = "7b85ce05-3903-4374-b654-2d4ffea295a5" }`.
It lands in your `/source` as `Lifeline.package/`, so after installing, every piece resolves by that name: `Lifeline.Health`, `Lifeline.LifelineHUD`, `Lifeline.DamageZone`, `Lifeline.HealZone`, `Lifeline.Projectile`, `Lifeline.ProjectileLauncher`, `Lifeline.SpawnPoint`, and `require("Lifeline.api")` / `require("Lifeline.bars")`. Nothing in it is world-specific, you bring the entities. Run `zeromind.update` later to pull new versions.
## Five-minute start
**1. Give things health.** Add `Lifeline.Health` to the player body on your scene's PlayerPrototype, and to any enemy or prop. Put enemies and props on **synced** entities (`entity.spawnSynced`) so every player sees the same health.
```lua
body.component.add("Lifeline.Health", { maxHealth = 100, regenRate = 5, maxShield = 25 })
crate.component.add("Lifeline.Health", { maxHealth = 40, onDeath = "remove" })
```
**2. Show it.** Add `Lifeline.LifelineHUD` to one plain (non-synced) entity in the scene. Every peer runs its own copy.
```lua
entity.spawn("HUD").component.add("Lifeline.LifelineHUD", { playerBar = "hearts", worldBar = "overhead" })
```
**3. Hurt and heal.** Add a zone to any entity. It's a box of `sizeX × sizeY × sizeZ` around the entity and moves with it.
```lua
lava.component.add("Lifeline.DamageZone", { sizeX = 4, sizeZ = 4, kind = "fire", amount = 5, mode = "perSecond" })
spikes.component.add("Lifeline.DamageZone", { kind = "spikes", amount = 25, mode = "onEnter" })
pad.component.add("Lifeline.HealZone", { amount = 10, interval = 0.5 })
```
**4. From code.**
```lua
local Lifeline = require("Lifeline.api")
Lifeline.damage(target, 20, { kind = "fire", source = attacker, crit = false })
Lifeline.heal(target, 15)
Lifeline.fire { origin = muzzlePos, direction = aim, damage = 15, source = shooter } -- projectile
Lifeline.on("died", function(e) print(e.target, "died to", e.kind) end)
```
**5. Respawn.** Dead players come back after `respawnDelay` seconds at a random free `Lifeline.SpawnPoint` (or at the scene's `PlayerSpawn` if you haven't placed any), with full health and a moment of spawn protection.
That's it. The `scenes.main` showcase in this world uses every piece.
## What happens on death (`onDeath`, per entity)
| value | effect |
|---|---|
| `auto` (default) | `respawn` for players, `reset` for everything else |
| `respawn` | back at a spawn point after `respawnDelay`, full health |
| `reset` | back where it started after `respawnDelay`, full health |
| `remove` | disappears after `removeDelay` |
| `stay` | stays dead until `Lifeline.revive(target)` |
## Health fields (most useful)
`maxHealth`, `health`, `maxShield`/`shield` (soaks damage first), `regenRate` + `regenDelay`, `shieldRegenRate` + `shieldRegenDelay`, `invulnerabilityTime` (i-frames after a hit; damage-over-time ticks ignore it), `invulnerable` (god mode → "IMMUNE"), `armor` (flat reduction → "BLOCKED"), `respawnDelay`, `spawnProtection`, `displayName`, `team`, `barStyle` (bar drawn over this entity, `none` hides it), `bossBar` (show the big boss bar when near), `bodyHeight`/`bodyRadius` (bar placement and hit volume), `killBelowY`. Read-only: `isDead`, `deaths`.
## Events
`Lifeline.on(name, fn)` fires on **every** peer for `damaged`, `healed`, `blocked`, `died`, `respawned`, or `"*"` for all. The payload is `{ event, target, amount, shieldAmount, kind, source, crit, health, shield, maxHealth, reason, origin, pos, isPlayer, name }`. It returns a connection with `:Disconnect()`.
Each Health component also exposes typed events: `entity.component.get("Lifeline.Health").events.died:connect(fn)`.
## Styles: change one field
On `LifelineHUD` (or at runtime per player with `Lifeline.setStyle { bar = …, worldBar = …, number = …, feedback = … }`):
- **Bars** (`playerBar`, `worldBar`, Health's `barStyle`): `classic` (lost chunk drains away), `segmented`, `ring`, `hearts` (half hearts, shield hearts, heartbeat at low HP), `boss`, `overhead`, `minimal`, `stacked` (shield on health), `scifi`, `fantasy`, `cartoon`, `pixel`, `orb`.
- **Numbers** (`numberStyle`): `classic` (pop / shaky crit / green heal / IMMUNE-BLOCKED), `combo` (hits on one target add up into a running total), `comic`, `minimal`.
- **Feedback** (`feedback`, any mix): `flash shake vignette heartbeat direction`, or `all` / `none`.
## Multiplayer & anti-cheat
Health fields are `Sync`. Only the entity's owner mutates them, and the relay refuses writes from anyone else, so one player cannot set another player's health from their own machine.
- **Hit something you own** (your avatar, or a prop your peer took), it changes on your machine and the new value goes on the wire. Every other peer draws exactly that number: health bars, numbers and death screens all read the same synced field.
- **Hit something another player owns**, `Lifeline.damage` doesn't decide anything. It sends a request to that entity's owner over `multiplayer.send`, and the owner validates it before applying. `Lifeline.setDamageFilter(function(comp, amount, info, fromPeer) ... end)` is where that validation goes: return the amount to allow (clamped if you like), or 0 to refuse. `fromPeer` is set only when the hit arrived from another peer's request.
- **Zones** run on every peer but act only on entities that peer owns, so a player in a fire zone is burned exactly once, by their own machine. A player's damage events are broadcast by the owner, so remote players see the same flash, numbers and score hooks.
- **Events** (`Lifeline.on`) fire on every peer, same channel the kit uses for its own visuals.
**The honest limit:** the engine's model is that the owning peer is the authority for its own entities. That is what stops *other* players from touching your health, and it is what this kit is built on. It does not, by itself, stop a modified client from lying about *its own* health (a hacked client could ignore a fire zone). If your game needs damage that a cheating client can't dodge, run the damage on a peer you control and funnel it through `setDamageFilter`, the filter runs on the owner, so it's the place to require proof, rate-limit, or refuse anything that doesn't match your own simulation.
## Other hooks
`Lifeline.kill`, `Lifeline.revive`, `Lifeline.get(target)`, `Lifeline.all()`, `Lifeline.isAlive`, `Lifeline.setSpawnPicker(fn(comp, points) -> entity)`, `Lifeline.kinds` (damage kinds → colour/label, add your own).
## Contents
**Components**
| Component | What it does |
|---|---|
| `Lifeline.Health` | Health, shield, regen, i-frames, armor, death, and respawn / reset / remove / stay. Fires typed events. |
| `Lifeline.DamageZone` | A box that damages what's inside: once on entry (spikes, a hammer head) or every interval (fire, poison). Damage kind, crits, knockback, team filters. Moves with its entity. |
| `Lifeline.HealZone` | A box that restores health (and optionally shield) every interval: a healing pad, campfire or fountain. |
| `Lifeline.Projectile` | A bolt that damages the first Health body it touches and stops at solid geometry. |
| `Lifeline.ProjectileLauncher` | Player blaster on a key, or an auto turret that tracks and shoots the local player. |
| `Lifeline.SpawnPoint` | Where dead players respawn (falls back to the scene's PlayerSpawn). |
| `Lifeline.LifelineHUD` | Your health bar, bars over everything else, the boss bar, floating damage numbers, hit feedback and the death screen. |
**Modules**: `Lifeline.api` (damage, heal, kill, revive, fire, events, filters), `Lifeline.bars` (13 bar styles), `Lifeline.numbers` (damage-number styles and presets), `Lifeline.feedback` (hit effects and death screen), `Lifeline.zone` (shared zone overlap).
**Health bar styles (13):** classic (lost chunk drains away), segmented, ring, hearts (half hearts, shield hearts, heartbeat at low health), boss (name and phase marks across the top of the screen), overhead, minimal line, stacked (shield on health), sci-fi hologram, ornate fantasy, bouncy cartoon, chunky pixel art, glass orb.
**Damage numbers (7 styles, 4 presets):** pop, shaky critical with a burst, floating green heal, combo running total, IMMUNE / BLOCKED, minimal, comic. Presets: `classic`, `combo`, `comic`, `minimal`.
**Hit feedback (5, mix and match):** character flash, camera shake, red vignette, low-health heartbeat, hit-direction indicator, plus a death screen with a respawn countdown.
A playable showcase lives in the source world: a spike pit, fire zone, swinging hammer, turret, healing pad, breakable crates, a boss dummy, and 13 training dummies, one per bar style.