# battle.training: Air theater, controller API (prototype rules `air-s1.0.0-proto.5`)

Air is the third theater of battle.training and it is still being built. These are prototype rules:
the numbers will change, so read them from `h.rules` and never hard-code them. The Air ladder is open at
https://battle.training/ladders/air (free, no prize, its own ratings). Besides the ladder there is this
document, a starter, a simulator you run yourself, and a page that flies your controller in the browser.
We are asking for controllers that try to break the rules: a plan that wins without fighting, an order the
engine accepts and should not, anything that looks wrong.

You write a controller that drafts two or three jets under a point budget and flies them against another
squad over mountains. Each side also has five ground targets to protect, and the other side's to strike.
The controller is called twenty times per simulated second and returns orders. A game lasts at most 240
seconds.

```js
globalThis.controller = {
  draft(h) { return ["anvil", "lance", "kestrel"]; },  // optional: 2 or 3 aircraft within h.draft.budget
  hello(h) { /* once: rules, terrain, weather, the ground targets, your aircraft */ },
  tick(o)  { /* every tick: return { tick: o.tick, units: [ ...orders ] } */ },
};
```

## Getting started

1. Download three files into one folder:
   - https://battle.training/air-kit/air-sim.mjs (the engine and the house pilots, one file)
   - https://battle.training/air-kit/air-test.mjs (the test runner)
   - https://battle.training/air-kit/controller-air.js (a starter that circles over its own targets and does nothing else)
2. Run `node air-test.mjs controller-air.js`. It plays every house squad on six seeds from both sides and
   prints wins, points, what your aircraft were lost to, which orders were refused and why, a missile
   report (locks begun and completed, what broke them and for how long, launches, hits, why the rest missed)
   and any exception from `tick`. Options: `--vs ace,hauler` (or `--vs other-bot.js`), `--seeds 10`, `--trace`.
3. Watch its games: once the bot is enrolled on the Air ladder, its sets are listed at
   https://battle.training/ladders/air and play on https://battle.training/air.

House squads, weakest to strongest in our own tests: `drone` (circles), `rammer`, `runner` (flees),
`striker` (a bomber and two escorts), `hauler` (two bombers and an escort), `boomer` (two Lances and a
Kestrel), `turner` (three Kestrels), `ace` (two Wardens and a Kestrel).

The local runner has no sandbox and no time limit. The ladder has both: about 10 ms of CPU per tick
(counted in bytecode, so it is the same on every machine), no network, a clock that only knows the tick,
and no randomness you did not seed yourself. A tick that runs over is dropped and the aircraft fly on
their last controls.

## Entering the ladder

1. Create a bot that plays only Air: `POST https://api.battle.training/api/bots {"name": "...", "theater": "air"}`
   (or use one controller for several theaters and branch on `hello(h).rules.theater === "air"`).
2. Upload the controller as for any bot. It is tested under these rules first: it must load, make a legal
   draft or none, and steer (send `roll` or `pull`). The report says what failed.
3. Enrol: `POST https://api.battle.training/api/ladders/air/enrol {"bot": "<name>"}`.
4. Sets are two games on one seed with the sides swapped. Watch them from the ladder page.

The four scripted house bots spar there as air squads (`house-brawler` flies `ace`, `house-holder` flies
`hauler`, `house-hunter` flies `turner`, `house-random` flies `drone`). The ladder's `enrolled` count is
players' bots only; the house bots are listed in the standings as sparring partners.

## Units of measure

| Quantity | Encoding |
|---|---|
| position, altitude, distance | Q16.16 decametres: `metres / 10 × 65536`. The arena is 32 km square (`rules.size`). |
| velocity | Q16.16 metres per second, `[east, south, up]` |
| direction (`fwd`, `up`) | Q16.16 unit vector, `[east, south, up]` |
| angle | integer, 4096 = full turn, 0 = east, increasing clockwise towards south |
| load factor | Q16.16 g |
| time | ticks, 20 per second |

Every number you send must be an integer.

## The flight model

Each tick, for every aircraft:

```
q        = density(alt) × (speed / 100 m/s)²           density = exp(-alt / 8500 m)
weight   = 1 − spec.fuelMass × (fuel burnt) − spec.storeMass × (stores gone)      as a share of the full load
n        ≤ min(spec.gMax, what the pilot can hold, q / spec.qStall / weight)      o.units[i].gAvailable is the last term
mach     = speed / (340 m/s − 4 m/s per km of altitude, at least 295)
drag     = spec.cd0 × q × (1 + spec.wave × ramp(mach)² + rules.aero.sepDrag × over)  +  spec.ki × (n × weight)² / q
thrust   = (boost ? spec.thrustBoost : spec.thrustMil × throttle) × density^0.7
accel    = 9.81 m/s² × [ (thrust × cos(aoa) − drag) / weight × fwd + (n + thrust × sin(aoa) / weight) × up − vertical ]
```

`ramp(mach)` is 0 below Mach 0.85 and 1 from Mach 1.05: drag climbs steeply towards the speed of sound, more
for a blunt aircraft (`spec.wave`) than for a slender one.

**Angle of attack.** Lift comes from the nose being above the flight path. `aoa` is 0 in a ballistic arc and
reaches `rules.aero.alphaMax` (18°) when the wing gives all it has. Ask for more g than `gAvailable` and the
nose keeps coming up, towards `rules.aero.alphaDeep` (40°): `over` grows, the lift falls by up to
`rules.aero.liftLoss` and the drag multiplies. That is a stall. It points the nose somewhere useful for a
moment and costs speed you will not get back quickly. The gun, the seekers and the radar look along `nose`,
not along `fwd`.

**Corner speed.** Below a certain speed the wing limits your g (`q / qStall / weight`); above it the
structure does (`spec.gMax`). Where the two meet you turn fastest. It moves with altitude and with weight.

**Weight.** Fuel and stores are part of the aircraft. A bomber with its bombs gone, or a fighter late in a
fight, gets more g from the same wing and more acceleration from the same engine.

**The pilot.** Every tick above `rules.pilot.tol` (5.5 g) adds to `strain`; below `rules.pilot.rest` (4 g) it
recovers. Past 0.6 the g the pilot can hold falls towards `rules.pilot.greyG` (6.2 g), which is still above the
tolerance: keep pulling all you are allowed and the strain keeps building. Ease off below 4 g and it clears. At 1 the pilot blacks out for
`rules.pilot.blackoutTicks` ticks: the aircraft flies at 1 g with the wings where they were and takes no orders.

`fwd` is the direction of flight and `up` is the direction of lift, square to it. You control two things
about them: `roll` turns `up` around `fwd` (at up to `spec.rollRate` per tick, less when slow), and `pull`
sets the load factor `n` you want (it changes by at most `spec.gOnset` per tick). There is no rudder and no
"turn left" order: to turn you roll the lift vector to where you want to go and pull.

What follows from the equations and is not handled for you:

- An aircraft cannot stop or hover. When `q / qStall` falls below 1 the wing carries less than the weight
  and the nose drops whatever you order.
- Pulling g costs speed through the `n²` term. Altitude and speed trade through gravity.
- Thrust and drag both fade with altitude. Fuel is finite; the afterburner burns `spec.boostBurn` times the
  dry rate. With no fuel there is no thrust.
- Wind moves everything: aircraft, bombs, flares. **You are never told the wind.** `vel` is your velocity
  through the air; the difference between that and how your position changes from tick to tick is the
  wind where you are. It changes in strength and direction with altitude. In a blizzard the air below the
  cloud top also buffets the aircraft at random.
- The ground destroys an aircraft. So does touching another aircraft, including your own wingman. More
  than `rules.bounds.graceTicks` ticks outside the arena and the aircraft is lost.

| | kestrel | lance | warden | anvil |
|---|---|---|---|---|
| role | light, turns best | fast interceptor, big radar | heavy fighter, most fuel | bomber |
| draft cost (budget 11) | 3 | 4 | 4 | 4 |
| hp | 90 | 100 | 130 | 190 |
| g limit | 9 | 7 | 7.5 | 4.5 |
| radar-guided / heat-seeking missiles | 0 / 4 | 4 / 2 | 2 / 2 | none |
| bombs | 0 | 0 | 2 | 8 |
| flares | 14 | 10 | 24 | 30 |
| gun | yes | yes | yes | a tail gun that fires on its own at an enemy close behind |
| radar range, half cone | 15 km, 50° | 24 km, 60° | 20 km, 60° | 12 km, 45° |

The full figures are in `h.rules.craft`.

## Orders

```ts
{ id: number,
  throttle?: number,   // 0..65536
  boost?: boolean,     // afterburner
  roll?: number,       // -65536..65536, share of the roll rate; positive rolls right
  pull?: number,       // load factor wanted, Q16.16 g; 65536 keeps a level aircraft level
  fire?: boolean,      // gun, straight along fwd, one burst per tick
  launch?: { weapon: "heat" | "radar", target: number },   // target: an enemy aircraft id. Hold the same order every tick: the seeker needs 14 ticks (heat) or 30 ticks (radar) with every launch condition met before the missile leaves. A tick without the order, or with a condition unmet, starts the lock over. Your unit's `lock` shows the progress. A radar lock shows on the target's warning receiver as "lock"; a heat lock gives no warning.
  flare?: boolean,
  drop?: boolean }     // release one bomb
```

Controls stay as they are until you change them. Orders that cannot be carried out are refused one part at
a time and listed in `o.lastRefused` with a reason; the rest of the order still counts.

## Weapons

- **Gun.** Shells leave at `rules.gun.muzzle` plus your own velocity, fall under gravity and live
  `rules.gun.life` ticks. The gun is fixed: you aim the aircraft. Ammunition is `spec.gunTicks` ticks of fire.
- **Heat-seeking missile.** Launch needs the target inside a 30° cone off your nose, a clear line (no
  terrain, no cloud) and a tone: the lock range depends on what the seeker sees of the target's engine.
  From behind an aircraft on afterburner it reaches furthest; from the front, or against a throttled-back
  engine, far less. In flight the seeker follows the brightest heat source in its cone, which may be a flare.
- **Radar-guided missile.** Launch needs your radar on the target. Your radar must stay on the target
  until the missile is within `rules.missiles.radar.range` of it; after that its own seeker takes over.
  Lose the lock for more than `rules.supportGrace` ticks before then and the missile is lost.
- Missiles burn for a few seconds, then coast. They obey the same drag law as aircraft, so every turn
  slows them, and their guidance corrects only part of its error each tick. A missile that falls below its
  minimum speed drops away.
- **Bombs.** A bomb leaves with your velocity and then falls: gravity, drag along its path
  (`rules.bomb.cd`, same dynamic-pressure law as the aircraft) and the wind of every layer it passes
  through. There is no bombsight. It damages enemy targets within `rules.bomb.blast` of where it lands,
  most at the centre and nothing at the edge. Level from high up, in a dive, or tossed in a climb: the
  same rule covers all three.
- **Strafing.** A gun shell that lands within `rules.targets.radius` of an enemy target does
  `rules.targets.strafe` damage.
- **Flak.** Every standing target defends itself. An enemy aircraft within `rules.flak.radius` of it and
  less than `rules.flak.ceiling` above it risks a hit each tick; the risk is highest low and close.
- **Flares.** Finite. A flare burns `rules.flare.burn` ticks and fades as it burns. They mean nothing to a
  radar-guided missile.

## What you see

```ts
o.units      // your aircraft, in full: position, vel, fwd, up, nose, aoa, heading, climb, bank, g, gAvailable,
             // strain, blackout, weight,
             // fuel, ammo, heat, radar, flares, ground (terrain below), outTicks, launchReady, lock ({weapon, target, ticks, needed} or null)
o.contacts   // enemy aircraft someone on your side detects:
             //   by radar (inside the cone and range, terrain not in the way): position and velocity
             //   by eye (within rules.visual.range, less in bad weather, no cloud or terrain between): position only
o.warnings   // your warning receiver: { unit, bearing, level }. A noisy bearing, no range.
             //   "search": an enemy radar has you. "lock": it is guiding a missile at you.
             //   "missile": a missile's own radar has you.
o.threats    // enemy missiles one of your aircraft can see (within rules.visual.missileRange): position only
o.missiles   // your missiles in flight
o.flares     // flares in sight
o.targets    // every ground target of both sides: { id, side, x, y, alt, hp, maxHp }
o.bombs      // your bombs in the air
o.score      // points: damage done to the other side's targets, plus 100 for every aircraft the other side has lost (to anything)
```

A heat-seeking missile gives no warning at all. You see it or you do not.

`h.map` has the terrain lattice (`heights`, `cells` per edge, spacing `rules.cell`, altitude per unit
`rules.heightUnit`), the cloud mask and layer (`cloud`, `cloudBase`, `cloudTop`) and `weather`. `h.targets`
lists the ground targets.

## Winning

- Destroy every enemy aircraft and you win at once.
- Destroy every enemy ground target and you win at once.
- Otherwise, after 240 seconds, the side with more points wins. Points are the damage you have done to
  enemy ground targets (a target has `rules.targets.hp` hit points) plus `rules.killPoints` for every
  aircraft the other side has lost, whether you shot it down or it flew into a mountain. Level on points:
  more damage done to aircraft, then more aircraft left, then a draw.

A squad without a bomber can still strafe, but in practice it has to win in the air.

## Telling us what you found

Post in the Discord (https://discord.gg/jtkXzkSKca) or write to hello@battle.training with the controller,
the seed and what happened. The prototype changes most days; the version string in `h.rules.version` and at
the top of this page says which rules you are reading.
