17. Complete simulation algorithms
This chapter is the simulation written out as algorithms: one game frame in exact order, then every object the frame touches (your ship, aliens, missiles, pods, shots, satellites, the other players' copies), each with its state machine, its integer arithmetic and the order of its checks. Chapters 4 to 8 explain the same behaviour gently; here nothing is left to guess. If you write the pseudocode below in your language, with the same integer rules, you get the same game, frame for frame.
Read it like a reference: section 1 is the frame and the cross-cutting rules (randomness, counters, "this frame or last frame"), section 2 the helpers everything else uses, sections 3 to 9 the objects and the level, section 10 the multiplayer side. Every section ends with an Exact rules box. Tags: O read in the reconstructed code (which is byte-identical to the original) or seen in a recorded run, D derived from the code but not watched, H hypothesis.
0. Conventions used in the pseudocode
| Notation | Meaning |
|---|---|
int16, int32 | signed integers that wrap around like the
original's 16- and 32-bit registers. Every plain variable below is int16 unless said
otherwise. |
a >> n | arithmetic shift right (rounds toward minus infinity:
-1 >> 7 = -1). In JavaScript: >> on a value that fits
in 32 bits, not Math.trunc(a / 2**n). |
a << n on an int16 | wraps to 16 bits (for example
0xC0 << 8 = 0xC000 = −16384). |
| position, velocity (lvec) | three signed 64-bit integers ("raw"). One
world unit = 65,536 raw (chapter 3). mid32(x) = x >> 16
cut to 32 bits; mid16(x) = x >> 16 cut to 16 bits (the
"middle word"). Writing mid(x) = v means x = v · 216 with all other
bits 0 (only satelliteSpawn does this, on a cleared vector). The exponent law of 2.2 assumes
every axis difference is below 231 units, because mid32 drops the bits
above 47. |
a / b | integer division, truncated toward zero (the original's IDIV); every division in this chapter has non-negative operands. |
-w < r < w | pseudocode for "-w < r and
r < w", not a chained comparison (in JavaScript write both tests). |
x & m == v | never used without brackets: bit tests are always
written (x & m) == v. |
switch … k: | a case ends where the next case label
starts: there is no fall-through unless a comment says "falls through" (only the
Fighter, 4.4). break leaves the switch and goes on with the code after it;
continue goes to the next pass of the enclosing loop. |
| records | field names of bodies (type, pos, home, distExp, dir, camX/Y/Z,
fwd, right, up, pitchRate, rollRate, yawRate, model, state, speed, maxTurn, maxSpeed, accel,
particles, hp, visible, target) and shots (state, pos, vel, fwd, right, up)
are those of chapter 14; scale(model) is the model's
first word (chapter 16). |
| axes, directions | three int16 in Q14 (16384 = 1.0,
chapter 3). |
| angles, rates | steps of 1/2048 turn per frame. |
speed of a body | raw units: a body moves fwd · speed raw
per frame, which is speed / 4 world units (Q14 axis × speed = speed · 214 raw
= speed / 4 units). |
| frame | one pass of the flight loop: 18.2 per second in single player, about 70 per second in multiplayer (our emulator runs, chapter 2). |
sound(n), message(text, frames) | side effects that do not
change the simulation: PC-speaker effect n (chapter 10); the centre message
messagePtr = text; messageTimer = frames. |
1. The frame, exactly
1.1 Single player
The flight loop of main (src/main.c).
Each line is one call or one assignment, in the original order O.
loop forever: // one iteration = one frame
if key latch ESC: // set by the key handler, chapter 11
score[me] = 0 // an abandoned game scores nothing
leave loop // -> 9.4 "after the loop"
if aliensLeft == 0 and shields > 0:
leave loop // level cleared -> 9.4
tick = 0 // timer ticks (18.2 Hz) counted from here
show the page drawn in the previous frame // waits for the vertical retrace
if key latch F2: // pause
clear F2; busy-wait until F2 latched again; clear F2
frameCount += 1
if bumpImmunity > 0: bumpImmunity -= 1
if tumble > 0: tumble -= 1
clear the hidden page with flashColor; flashColor = 0; empty the draw list
playerUpdate() // 3
if not spectator: playerShotsUpdate() // 7.2 (spectator is always 0 here)
if (frameCount & 63) == 0: alienSpawn() // 4.2
aliensUpdate() // 4.1
enemyMissilesUpdate() // 5.2
playerMissilesUpdate() // 5.4
podsUpdate() // 6
alienShotsUpdate() // 7.5
if (frameCount & 127) == 0 and not spectator: satelliteSpawn() // 8.1
satelliteUpdate() // 8.2
draw stars, flush the draw list, draw the score text
if shields > 0:
draw radar and instruments
if messageTimer > 0: draw message; messageTimer -= 1
else if playerDeadScreen() == 1: // 9.3
leave loop
busy-wait while tick < 1 // at most 18.2 frames per second
1.2 Multiplayer (the local step)
Same loop, other branches O. There are no aliens, missiles or pods; the other players exist only as copies filled from their packets (section 10).
loop forever:
if key latch ESC:
if not spectator: score[me] = 0
leave loop // player: name screen, new life; spectator: lobby
postPeerListens() // 10.1: re-arm one receive per live peer
if not spectator: sendStateIfIdle() // 10.1: broadcast the state as it is NOW,
// i.e. as the previous frame left it
tick = 0
show the previous page
if key latch F2: clear F2; clear F2 // no pause in multiplayer
frameCount += 1; count down bumpImmunity and tumble as above
clear the page with flashColor; flashColor = 0; empty the draw list
playerUpdate() // 3 (Enter toggles the cloak here)
if not spectator: playerShotsUpdate() // 7.2, multiplayer branch
remotePlayersUpdate() // 10.2
remoteShotsUpdate() // 10.3
if (frameCount & 127) == 0 and not spectator: satelliteSpawn()
satelliteUpdate() // 8.2 incl. the peers' satellites
draw stars, list; if not spectator: draw score
if shields > 0: radar, instruments, message as above
else: playerDeadScreen() // never returns 1 in multiplayer
netSyncFrame() // 10.4: wait for peers, apply their hits
1.3 Which values each step sees
The order decides who sees whose old position. "Previous frame" means the value as the previous frame left it O.
| Step | Reads | As of |
|---|---|---|
| playerUpdate | keys, mouse; haveTarget and the aliens'
visible == 2 marks (missile launch) | input: now; marks: previous frame's aliensUpdate |
| playerShotsUpdate | aliens, enemy missiles, pods, own satellite; the peers' ships and satellites | aliens, missiles, pods: end of the previous frame (they move later). The ship and the shots: this frame. Peers: their last packet |
| alienSpawn | ship position and axes | this frame (after playerUpdate) |
| alien behaviour (AI) | its own display exponent distExp | its previous frame's move (a new alien: 0) |
| alien steering | ship position; the pod it is after | ship: this frame; pod: previous frame (pods move after aliens), but pod states changed earlier this frame by your shots are seen |
| alien ram test | ship position, axes, bumpImmunity | this frame; immunity may have been set by an earlier alien slot in this same frame |
| enemyMissilesUpdate | ship position | this frame; missiles launched this frame move at once |
| playerMissilesUpdate | its target alien | this frame (aliens already moved); deaths from this frame are seen |
| podsUpdate | the captor (towing alien) | this frame |
| alienShotsUpdate | ship position | this frame; shots fired this frame move and are tested at once |
| satelliteUpdate | ship position, bumpImmunity; peers' item events |
this frame; peers' events: their last packet |
| netSyncFrame | peers' hit reports and status words | their last packet (see 10.4 about repeats) |
1.4 Randomness
The game uses the Borland C library generator and nothing else O (a full search of the sources finds exactly the five call sites below).
srand(t): seed32 = t // called once at program start with time(0) cut to 16 bits
rand(): seed32 = seed32 * 0x015A4E35 + 1 (mod 2^32)
return (seed32 >> 16) & 0x7FFF // 0 .. 32767
| Where | When | Calls, in order | Formula |
|---|---|---|---|
| playerBump (9.1) | each bump: in aliensUpdate (single player) or remotePlayersUpdate (multiplayer) | 2: pitch, then roll | rate = (rand() * 2 /
32768) * 0x60 − 0x30 (32-bit arithmetic) = −48 or +48 |
| satelliteSpawn (8.1) | a frame with (frameCount & 127) == 0 and no own
satellite | 3: x, then y, then z | mid = rand() * 20000 / 32768 − 10000
(32-bit, then a 64-bit subtraction) = −10000 … 9999 |
Within one frame the order is therefore: bumps (in alien-slot order) before the satellite.
A single-player game replays identically given the same inputs D: the
seed (time(0) cut to 16 bits at program start, and every rand() call made
since, including earlier games of the session), the input sampled in every frame, and, for each
level, the number of level-introduction frames (they set the camera's starting roll, 9.4).
1.5 Counters and periodic events
| Counter | Reset | Changed | Used for |
|---|---|---|---|
frameCount | 0 at every level start (single player) and every life (multiplayer, after the name screen) | +1 near the start of each frame, before any object moves, so the first simulated frame has 1 | alien spawn when (frameCount & 63) == 0
(frames 64, 128, …); satellite when (… & 127) == 0 (128, 256, …); Fighter fires
when (… & 3) == 0; Guardian when (… & 1) == 1 |
bumpImmunity | 0 at program start, never reset | −1 per frame while > 0 (frame start); set to 8 by a bump | no ram, no peer collision, no satellite pick-up while > 0 |
tumble, tumbleRates | 0 at program start, never reset | −1 per frame while > 0 (frame start); 0x30 by a bump | forced spin, no velocity control (3) |
fireCooldown | 0 at program start, never reset | in playerUpdate | auto-fire every 3rd frame |
messageTimer | 0 at level/life start | −1 per frame while alive and > 0 | centre message |
deathCountdown | 0 at program start | 0x40 at death; −1 per frame in playerDeadScreen | input ignored on the death screen |
spawnDir, spawnTypeRot | 0 at level start | +1 after each successful spawn | side of appearance, kind rotation |
satelliteCounter | never (program start: 0) | +1 per satellite spawned (a signed 16-bit number: 32767 + 1 wraps to −32768) | kind cycle |
| shot lifetime, explosion age | per object, sections 5–8 | ||
| other start values | at program start: keyboard turn rates
(pitch, roll, yaw) 0, haveTarget 0, flashColor 0, radar zoom −1; none of
them is reset by a level or a new game O | ||
- The level-cleared test is at the top of the frame and needs shields > 0; the frame that freed the last alien is still drawn completely O.
frameCount,bumpImmunityandtumblechange beforeplayerUpdate; a bump set in frame N makes immunity 7 at the start of frame N+1 and 0 at the start of frame N+8, so the frames N+1 … N+7 and the rest of frame N are protected O.flashColorset during frame N colours the background cleared at the start of frame N+1 (the last one set wins) O.- Keys and the mouse are read by the original at the moment the code looks at them (the handlers run asynchronously). For a rebuild, sample all input once at the start of the frame D.
- In multiplayer the send is started at the top of frame N+1, when the records hold what frame N left; hits found in frame N therefore normally travel in packet N+1. Caveat: IPX gathers the packet from the live game records (the send's fragments point at them) and may do so later than the call, while frame N+1 already changes them, so a packet can mix both frames H. If the previous send is still busy, that frame's packet is skipped and its hit reports are lost (playerShotsUpdate clears them again) D.
2. Shared helpers
Everything below is built from these few routines (src/input_math.asm, src/render.c, src/steer.c). Chapter 3 explains the number formats; here are the exact operations.
2.1 Vector arithmetic
dot(a, b): s = int32(a0*b0 + a1*b1 + a2*b2) // wraps at 32 bits
return int16((s << 2) >> 16) // = floor(s / 16384)
cross(a, b): out0 = h(a1*b2, a2*b1); out1 = h(a2*b0, a0*b2); out2 = h(a0*b1, a1*b0)
where h(p, q): lo = (p & 0xFFFF) - (q & 0xFFFF); hi = (p >> 16) - (q >> 16)
// the borrow of the low-word subtraction is LOST (original quirk):
return int16(((hi << 16) | (lo & 0xFFFF)) << 2 >> 16)
rotate(a, toward b, angle): // vec3_rotate
k = angle & 2047; s = SIN[k]; c = COS[k] // Q14 tables, chapter 3
for i in 0..2: a[i] = int16((int32(b[i]*s + a[i]*c) << 2) >> 16)
e = int16((int32(a0*a0 + a1*a1 + a2*a2) << 1) >> 16) - 0x2000
for i in 0..2: if a[i] > 0: a[i] -= e else if a[i] < 0: a[i] += e
axisShl(q, n): // vec3_to_lvec3_shl: a Q14 vector into an lvec
for each component c: x = (n >= 0) ? c : -c
r = int32(x << |n|) // bits above 32 lost
result = int64(r) // sign-extended
axisMul(q, k): for each component c: result = int64(int32(c * k))
In world units, axisShl(unit axis, n) is 2n−2 units long (n = 8: 64
units, 12: 1024, 16: 16,384) and points backwards for negative n; axisMul(unit axis, k)
is k/4 units long.
2.2 Nearness exponents
A relative vector (goal minus body, or object minus you) is turned into a 16-bit direction and an
exponent by normalize:
normalize(d, e, limit = 8): // d: lvec, changed in place; e: exponent, in/out
while some axis has mid32(d) < -0x4001 or mid32(d) > 0x4000:
d = d >> 1 (each axis, 64-bit arithmetic shift); e -= 1
while every axis has -0x2000 <= mid32(d) <= 0x1FFF:
d = d << 1; e += 1
if e == limit: stop
direction = (mid16(d.x), mid16(d.y), mid16(d.z))
Two exponents are used. The steering exponent starts at e = 0. The
display exponent distExp is computed by the renderer for every moved body with
e starting at the model's scale (1 for ships, aliens, the mutant and the pod; 0 for
missiles and satellites). Both say "how near", larger = nearer. The exact meaning, checked
by emulating the routine on 200,000 random vectors O:
Let d be the raw 64-bit difference per axis and k = threshold − start value (display: threshold − scale). Then e ≥ threshold exactly when every axis satisfies −L ≤ d < L, with L = 230−k raw for k ≥ 1 and L = 0x4001 · 216−k raw for k ≤ 0 (and k ≤ 8 − start because of the limit).
| k | every axis within (world units) | used by |
|---|---|---|
| 7 | [−128, 128) | satellite touch (display ≥ 7, scale 0), returning pod home (steering ≥ 7); for an alien (scale 1) display 8, where the lock window fails |
| 6 | [−256, 256) | ram (display ≥ 7 with scale 1), missile hits, grab / destroy a pod |
| 4 | [−1024, 1024) | Commander retreat (display ≥ 5) |
| 3 | [−2048, 2048) | Pirate / Fighter retreat (display ≥ 4), brake near a pod |
| 2 | [−4096, 4096) | Guardian arrival |
| 1 | [−8192, 8192) | Pirate may fire, Fighter / Pirate "far enough" (display < 2 is the negation) |
| 0 | [−16385, 16385) (raw below 0x4001 · 216) | Commander "far" (display < 1), missiles giving up (display < 0) |
| −1 | [−32770, 32770) | Pirate escape (display < 0), satellite lost (display < −1) |
"Display ≥ t" for a scale-1 body is row k = t − 1; for a scale-0 body row k = t. A test
"< t" is the negation: at least one axis outside. The law holds while every axis difference
is below 231 units (mid32 drops the bits above 47).
Worked example. A pod 1000 units straight ahead of an alien along x: the raw difference is (1000 · 65536, 0, 0) = (65,536,000, 0, 0). Steering exponent: 65,536,000 < 230−4 = 67,108,864 but not < 230−5 = 33,554,432, so e = 4 (rows 1–4 hold, row 5 does not). Step by step: the middle value 1000 doubles to 2000, 4000, 8000 (all ≤ 0x1FFF = 8191), then 16000 = 0x3E80 stops the loop after 4 doublings. The display exponent of the same pod seen from you at that distance starts at its scale 1, so it is 1 + 4 = 5.
2.3 Moving and seeing a body
objectMove(o): // object_move
if o.pitchRate != 0: rotate(o.fwd toward o.up, o.pitchRate); o.up = cross(o.fwd, o.right)
if o.rollRate != 0: rotate(o.right toward o.up, o.rollRate); o.up = cross(o.fwd, o.right)
if o.yawRate != 0: rotate(o.fwd toward o.right, o.yawRate); o.right = cross(o.up, o.fwd)
if o.speed != 0: o.pos += axisMul(o.fwd, o.speed) // along the NEW nose
return see(o)
see(o, noDraw = false): // render_object, simulation part
o.visible = 0
d = o.pos - shipPos; o.distExp = scale(o.model); normalize(d, o.distExp)
touch = (o.distExp >= 7 and bumpImmunity == 0)
o.dir = direction of d
o.camX = dot(camB, o.dir); o.camY = dot(camC, o.dir); o.camZ = dot(camA, o.dir)
if o.camZ <= 0x200 or noDraw: return touch
if o.camZ < o.camX or -o.camZ > o.camX: return touch
t = int16(o.camY << 1)
if o.camZ < t or -o.camZ > t: return touch
o.visible = 1; queue the model for drawing (chapter 9)
return touch
explosionStep(o): // draw_explosion: age, then draw
o.distExp += 1
draw the sparks (chapter 9; it also rewrites o.dir and o.cam* with a down-only
normalisation, which only drawing uses)
shipPos and camA/camB/camC (forward, right, "up") are your ship's,
as playerUpdate left them this frame.
2.4 Steering helpers
All five start the same way O:
aim(b, goal): // shared preamble
d = goal - b.pos; e = 0; normalize(d, e)
dir = direction of d
r = dot(b.right, dir); u = dot(b.up, dir); f = dot(b.fwd, dir)
b.pitchRate = 0; b.rollRate = 0; b.yawRate = 0
return e, r, u, f
turnToward(b, r, u):
p = u >> 7; if p == 0: p = 1
if p > b.maxTurn: p = b.maxTurn; if p < -b.maxTurn: p = -b.maxTurn
y = r >> 7; if y == 0: y = 1
if y > b.maxTurn: y = b.maxTurn; if y < -b.maxTurn: y = -b.maxTurn
b.pitchRate = p; b.yawRate = y
inCone(r, u, w): return -w < r < w and -w < u < w // strict
steerChase(b): // toward you; returns 1 = "aimed"
e, r, u, f = aim(b, shipPos)
if f < 0:
if b.speed > 200: b.speed -= b.accel
b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn
return 0
if inCone(r, u, 0x80):
if b.speed < b.maxSpeed: b.speed += b.accel
return 1
turnToward(b, r, u); return 0
steerFlee(b): // away from you; returns nothing
e, r, u, f = aim(b, shipPos)
if f > 0:
if b.speed > 200: b.speed -= b.accel
b.pitchRate = (u > 0) ? -b.maxTurn : b.maxTurn
return
if b.speed < b.maxSpeed: b.speed += b.accel
if inCone(r, u, 0x80): return
turnToward(b, r, u); b.yawRate = -b.yawRate; b.pitchRate = -b.pitchRate
steerToObject(b, t): // returns the steering exponent
e, r, u, f = aim(b, t.pos)
if f < 0:
if b.speed > 0: b.speed -= b.accel
b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn
return e
if inCone(r, u, 0x100):
if b.speed < b.maxSpeed: b.speed += b.accel
return e
turnToward(b, r, u); return e
steerTow(b, t): // tail toward t; returns 1 = t dead astern
e, r, u, f = aim(b, t.pos)
if f > 0:
b.pitchRate = (u < 0) ? b.maxTurn : -b.maxTurn
return 0
if inCone(r, u, 0x100): return 1
turnToward(b, r, u); b.pitchRate = -b.pitchRate; b.yawRate = -b.yawRate
return 0
steerToPoint(b, p): // returns e; never changes speed
e, r, u, f = aim(b, p)
if f < 0: b.pitchRate = (u < 0) ? -b.maxTurn : b.maxTurn; return e
if inCone(r, u, 0x100): return e
turnToward(b, r, u); return e
- Roll is always 0 after a helper; only idle pods set a roll rate O.
- Aliens spawn with
accel = 0, so for them every speed step inside a helper adds or subtracts 0; the mutant (accel 0x32), the missiles and nothing else really change speed there O. - Braking is "if above the floor, subtract": it lands exactly on 200 (or 0) only because the shipped speeds are multiples of the shipped accelerations O.
- A helper that is not called in a frame leaves the previous frame's rates and speed in place, and objectMove applies them again. This matters for the frames in which a behaviour skips steering (sections 4.3–4.6) O.
3. Your ship: playerUpdate
Chapter 4 explains the flying; this is the exact step
(src/control.c) O. Screen
centre during flight: ox = 320, oy = 175.
playerUpdate():
// --- 1. steering rates ---
if mouse enabled:
pitch = (mouseY - oy + 4) >> 2; yaw = (mouseX - ox + 4) >> 3; roll = 0
if pitch < 0: pitch += 1
if yaw < 0: yaw += 1
if yaw == 0: (if mouseX > ox: yaw = 1); (if ox - 8 > mouseX: yaw = -1)
if pitch == 0: (if mouseY > oy: pitch = 1); (if oy - 8 > mouseY: pitch = -1)
else: // keyboard: rates persist between frames
roll = 0
if pitch == 1 or pitch == -1: pitch = 0
if yaw == 1 or yaw == -1: yaw = 0
if Down held: (if pitch < 0: pitch = 0); (if pitch < 24: pitch += 2)
elif Up held: (if pitch > 0: pitch = 0); (if pitch > -24: pitch -= 2)
else: (if pitch > 0: pitch -= 2); (if pitch < 0: pitch += 2)
same for yaw with Right (+) / Left (-)
if tumble > 0:
move each of tumbleRates[0..2] one step toward 0
if mouse enabled: pitch += tR[0]; roll += tR[1]; yaw += tR[2]
else: pitch = tR[0]; roll = tR[1]; yaw = tR[2]
// --- 2. turn the ship (a = forward, b = right, c = "up") ---
if pitch != 0: rotate(a toward c, pitch); c = cross(a, b)
if roll != 0: rotate(b toward c, roll); c = cross(a, b)
if yaw != 0: rotate(a toward b, yaw); b = cross(c, a)
// --- 3. radar zoom (one step per key press, latch cleared) ---
keypad +: zoom = min(zoom + 1, 2); keypad -: zoom = max(zoom - 1, -6)
if shields == 0: return // dead: no thrust, weapons, cloak, movement
// --- 4. throttle (32-bit; only its low 16 bits are used below) ---
if Shift held and throttle < 0x90: throttle += 8
if Ctrl held and throttle > -0x70: throttle -= 8
// --- 5. guns ---
if mouseLatch != 0 or SpaceLatch != 0:
if fireCooldown == 0:
if cloakOn == 0 or cloakTime == 0: playerFire() // 7.1
fireCooldown = 2
else: fireCooldown -= 1
if mouse button not held and Space not held:
mouseLatch = 0; SpaceLatch = 0; fireCooldown = 0
// --- 6. Enter / Caps Lock, once per press ---
if EnterLatch or CapsLatch:
clear both
if multiplayer: cloakOn = not cloakOn
else: playerFireMissile() // 5.3
// --- 7. cloak ---
if cloakTime > 0 and cloakOn: cloakTime -= 1; statusOut = -1
else: statusOut = 0
// --- 8. velocity control (body components of the velocity's middle words) ---
v = (mid16(vel.x), mid16(vel.y), mid16(vel.z))
vb0 = dot(v, b); vb1 = dot(v, c); vb2 = dot(v, a)
if tumble == 0:
if vb0 != 0: n = steps(vb0); vel += (vb0 < 0) ? axisShl(b, n) : axisShl(b, -n)
if vb1 != 0: n = steps(vb1); vel += (vb1 < 0) ? axisShl(c, n) : axisShl(c, -n)
want = int16(throttle); if extraThrust != 0: want = want << 1
if vb2 != want:
dd = want - vb2; n = steps(dd)
vel += (dd > 0) ? axisShl(a, n) : axisShl(a, -n)
// --- 9. move ---
shipPos += vel // full 64 bits
steps(x): // the correction is 2^(n-2) units: 0.5 ... 8, or 16 with extra thrust
n = 1
if |x| > 2: n += 1; if |x| > 4: n += 1; if |x| > 8: n += 1; if |x| > 16: n += 1
if extraThrust > 0 and |x| > 32: n += 1; extraThrust -= 1
return n
- Order inside the step: rates → rotation → zoom → (dead? stop) → throttle → fire → missile or cloak → cloak drain → velocity → position. Shots and missiles are therefore launched with this frame's new axes but from the position before this frame's move, and a shot inherits the velocity before this frame's correction O.
- "Held" is bit 7 of the key byte; a "latch" is the byte being non-zero (a press since the game last cleared it, chapter 11). Down is tested before Up and Right before Left, so with both held Down / Right win O.
- Both Ctrl operands of the original test scan code 1Dh, so the throttle keys are Shift (left or right) and Ctrl (left or right) O.
- Extra thrust is used up by
steps(): one unit per axis correction that needed the extra step, so up to 3 per frame O. - While tumbling, the velocity is whatever the bump preset (9.1) made it: no damping, no throttle O.
4. Aliens (single player)
Gentle description: chapter 7. Records: 8 alien slots; only slots below
alienMax are used by spawning. Type table (src/tables.c)
O:
| type | name | hp | maxSpeed (raw; units = ÷4) | maxTurn | missile kind | score |
|---|---|---|---|---|---|---|
| 1 | Pirate | 2 | 500 up to level index 7, then 500 + 100·(L−7), at most 1000 (set per level) | 24 | 1 | 100 |
| 2 | Fighter | 2 | 700 | 24 | (1, unused) | 150 |
| 3 | Guardian | 4 | 1100 | 32 | (2, unused) | 200 |
| 4 | Commander / mutant | 8 | 900 | 32 | 2 | 400 |
4.1 The alien step: aliensUpdate
Per alien, the order is: sense (read last frame's display exponent) → decide (the behaviour switch, which also fires and sets turn rates and speed) → turn and move (objectMove: rotate, then advance along the new nose) → see (new display exponent, touch flag, camera position) → ram → lock mark (src/aliens.c) O.
aliensUpdate():
haveTarget = 0
for i in 0..7: // all 8 slots, in order
a = aliens[i]
if a.type <= 0: continue
if a.state == -1: // dying
a.pos += axisMul(a.fwd, a.speed) // drifts on at its last speed
explosionStep(a)
if a.distExp > 0x40: a.type = 0; aliensLeft -= 1
continue
switch a.type: // decide (+ fire)
1: pirate(a) 2: fighter(a) 3: guardian(a) 4: commander(a)
touch = objectMove(a) // turn, move, see
if touch and shields > 0: // ram
sound(1); shields -= 1; flashColor = COLLISION
if shields <= 0: shields = 0; deathCountdown = 0x40
else: playerBump() // 9.1 (sets bumpImmunity = 8)
a.hp -= 1
if a.hp == 0: a.state = -1; a.distExp = scale(a.model) // = 1; no points
lim = (a.distExp >= 0) ? int16(0xC0 << a.distExp) : (0xC0 >> -a.distExp)
if a.camZ > 0 and -lim < a.camY < lim and -lim < a.camX < lim:
haveTarget = 1; a.visible = 2 // lock mark
- Everything after the behaviour runs even if the behaviour just set
type = 0(a Pirate that escaped): it is moved, seen and lock-tested once more; a lock mark from it setshaveTargetalthough no alien can be chosen (a missile launched next frame then flies unguided) D. - The lock test also runs in the frame an alien is rammed to death (its state is already −1),
but the ram has just set
distExp = 1, solim = 0x180whilecamX/camYwere computed at exponent 7 or 8: the window shrinks to about 6 units (3 at exponent 8) around your line of sight, and this rarely lights the lock D. The escaped Pirate of the previous point uses the normal window. limis a 16-bit value: atdistExp = 8it is −16384 and nothing passes, so an alien within 128 units cannot be locked O. In world units the window is |x|, |y| < 384 around your line of sight at any distance D.- Ram damage happens only while
shields > 0; a ram never gives points; the alien dies only athp == 0exactly (a living alien always has hp ≥ 1) O. - A dying alien keeps its slot (and keeps counting in
aliensLeft) until its age passes 0x40: 64 frames for an age that starts at 1 O.
4.2 Spawning: alienSpawn and the level budget
levelSetup(L): // L = level index, 0 for level 1 (main, before the intro)
if (L & 3) == 0: podsReset() // 6.1
podsPlace()
alienMax = (L > 12) ? min(L - 8, 8) : 4
counts = [8, 2L, (L > 1) ? 2(L-1) : 0, (L > 3) ? 2(L-3) : 0]
TYPES[0].maxSpeed = (L > 7) ? min((L-7)*100 + 500, 1000) : 500
each count = min(count, 8); aliensLeft = sum(counts)
if podsLeft == 0: counts = [0, 0, 0, aliensLeft] // whole wave: type 4 (mutants)
spawnDir = 0; spawnTypeRot = 0
alienSpawn(): // frames with (frameCount & 63) == 0
i = first slot in 0 .. alienMax-1 with aliens[i].type == 0; none: return
a = aliens[i]; a.target = none
k = first k in 0..3 with counts[(k + spawnTypeRot) & 3] > 0; none: return
t = (k + spawnTypeRot) & 3
counts[t] -= 1 // used even if it becomes a mutant
if podsLeft == 0: a.type = 4; a.state = 4; a.model = MUTANT; t = 3
else: a.type = t + 1; a.model = TYPES[t].model; a.state = 0
a.maxSpeed = TYPES[t].maxSpeed; a.speed = a.maxSpeed; a.accel = 0
a.maxTurn = TYPES[t].maxTurn; a.hp = TYPES[t].hp; a.distExp = 0
a.particles = explosionParticles // 12 Lines / 38 Polygons; drawing only
a.pos = shipPos + [axisShl(camB, 16), axisShl(camB, -16),
axisShl(camC, 16), axisShl(camC, -16)][spawnDir & 3]
spawnDir += 1; spawnTypeRot += 1
- Place: 16,384 units from you along your right axis, then left, then along "up" (down the screen), then the opposite, repeating; never ahead or behind O.
- The new alien runs its behaviour and moves in the same frame (aliensUpdate follows), with
distExp = 0for that first decision O. - Not set at spawn and kept from the slot's previous occupant: the axes
(
fwd, right, up), the turn rates andvisible. At level startaliensCleargives every slot type 0, position 0, axes fwd = +z, right = +x, up = +y, pitch and roll rate 0 (yaw rate is not cleared) and state 0 O. The inherited rates never matter, because every starting state steers in its first frame (which zeroes all rates) D; the inherited orientation does: a reused slot starts facing where the dead alien faced. podsLeftis read at spawn time: once the last pod is lost in the middle of a level, every later spawn is a mutant (type 4, state 4, Commander numbers) whatever kind's budget it uses O.- A free slot with no budget left gets
target = noneand nothing else O.
4.3 Pirate (type 1, ai_abductor)
pirate(a):
switch a.state:
0: // attack
if steerChase(a) == 1 and a.distExp >= 2 and enemyMissileLaunch(a) == 1:
a.state = 1 // steerChase always runs; the launch only if the two tests before it hold
if a.distExp > 3: a.state = 1
1: // retreat
steerFlee(a)
if a.distExp >= 2: break
p = first pod j in 0..5 with pods[j].state == 0 and pods[j].type > 0
if none: a.state = 0; break
a.target = p; p.state = 1; p.target = a; a.state = 2 // claim
2: // approach
if a.target.state == -1: a.state = 0; break // no steering this frame
s = steerToObject(a, a.target)
if s >= 3 and a.speed > 200: a.speed -= 50
if s < 6: break
a.speed = 0; a.state = 3; a.target.state = 2 // grab: the pod is towed
message("WARNING: POD IN DANGER", 0x10); sound(3)
3: // turn
if a.target.state == -1: a.state = 0; break
if steerTow(a, a.target) == 1: a.state = 4
4: // escape
if a.target.state == -1: a.state = 0; break
if a.speed < a.maxSpeed: a.speed += 50
a.yawRate = 0; a.pitchRate = 0 // roll stays as left (0)
if a.distExp >= 0: break
a.type = 0; aliensLeft -= 1 // escaped: no explosion
a.target.type = 0; podsLeft -= 1
message("POD DESTROYED", 0x10)
| Transition | Condition (priority) | New state acts | This frame's motion |
|---|---|---|---|
| 0 → 1 | aimed and D ≥ 2 and a missile slot free (missile launched); or D ≥ 4. Both lead to 1 | next frame | chase rates |
| 1 → 2 | D < 2 and a pod with state 0 and type > 0 exists (lowest index) | next frame | flee rates |
| 1 → 0 | D < 2 and no such pod | next frame | flee rates |
| 2/3/4 → 0 | the pod's state is −1; tested first in each of these states | next frame | last frame's rates and speed (no helper called) |
| 2 → 3 | steering exponent to the pod ≥ 6 | next frame | turns with this frame's rates, does not move (speed 0) |
| 3 → 4 | steerTow reports the pod within the ±256 cone behind | next frame | rates 0 (the helper returned from the cone) |
| 4 → gone | D < 0 (some axis 32,770 units or more from you, as of the previous frame; row k = −1 of 2.2) | at once | moved and seen once more (4.1) |
- Fires only missiles of kind 1 (5.1); the launch is attempted only when the chase says "aimed" and D ≥ 2, and a launch failing for lack of a slot keeps it in attack unless D ≥ 4 O.
- Speeds: approach brakes 50 raw (12.5 units) per frame while S ≥ 3 and speed > 200; escape
accelerates 50 per frame to its maxSpeed. Its own
accelis 0, so chase and flee never change its speed O. - Escape is measured from you: D is the display exponent to your ship O.
- An escape removes the pod outright (type 0, no explosion) and counts the Pirate as done
(
aliensLeft − 1) O. - Stuck Pirate: only approach (brake) and escape (accelerate) change a Pirate's speed. One whose pod is destroyed while it turns (state 3, speed 0) goes back to attack at speed 0 and stays at 0 for ever: it can only turn and fire missiles, can never reach another pod, and the level cannot end until you kill it. One whose pod is destroyed during the approach keeps its braked speed (down to 200 raw, 50 units) D.
4.4 Fighter (type 2, ai_fighter)
fighter(a):
switch a.state:
0: if steerChase(a) == 1 and (frameCount & 3) == 0: alienFire(a) // 7.4
if a.distExp < 4: break
a.state = 1
// falls through into state 1 in the same frame
1: steerFlee(a) // overwrites the chase rates
if a.distExp < 2: a.state = 0
- Constant speed 700 raw (175 units) per frame: accel 0 O.
- In the frame it switches to retreat it has already chased (and maybe fired); then it flees, and objectMove uses the flee rates O.
- Both tests read the same D (last frame's), so the fall-through can never switch straight back O.
4.5 Guardian (type 3, ai_turret)
guardian(a):
switch a.state:
0: s = steerToPoint(a, (0,0,0)) // the "rally point", always the origin
if s >= 2:
if a.speed > 0: a.speed -= 100
else: a.speed = 0; a.state = 1
else: a.speed = a.maxSpeed // drifted out again: full speed
1: if steerChase(a) == 1 and (frameCount & 1) == 1: alienFire(a)
- "S ≥ 2" is every axis within [−4096, 4096) of the origin O.
- In the turret state speed and accel are 0: it only turns (max 32 steps per frame) and never moves again O.
- Fires on odd frame numbers only, while aimed (±128 cone) O.
4.6 Commander and mutant (type 4, ai_pod_killer)
commander(a):
switch a.state:
0: if steerChase(a) == 1:
enemyMissileLaunch(a) // kind 2; result ignored
a.state = 1
if a.distExp >= 5: a.state = 1
1: steerFlee(a)
if a.distExp < 1: a.state = 2
2: p = first pod j in 0..5 with pods[j].state == 0 and pods[j].type > 0
if none: a.state = 0; break
a.state = 3; a.target = p; p.state = 1; p.target = a
3: if a.target.state == -1: a.state = 0; break
s = steerToObject(a, a.target)
if s >= 3 and a.speed > 200: a.speed -= 100
if s < 6: break
a.speed = 0; a.state = 4
a.target.state = -1 // pod explodes; its age = its current distExp
a.model = MUTANT; podsLeft -= 1
message("POD DESTROYED", 0x10); sound(0)
4: a.accel = 0x32
if steerChase(a) == 1: alienFire(a)
| Transition | Condition | New state acts | This frame's motion |
|---|---|---|---|
| 0 → 1 | aimed (a missile is launched if one of the 4 slots is free); or D ≥ 5 | next frame | chase rates |
| 1 → 2 | D < 1 | next frame | flee rates |
| 2 → 3 / 2 → 0 | a free pod exists / none | next frame | the flee rates and speed of the previous frame, again |
| 3 → 0 | its pod has state −1 | next frame | last frame's rates and speed |
| 3 → 4 | steering exponent to the pod ≥ 6 | next frame | turns with this frame's rates, speed 0 |
- The mutant keeps type 4, its hit points and the score 400; only the model and state change O.
accel = 0x32is set at every mutant frame before chasing, so the mutant brakes (by 12.5 units per frame down to 50 while you are behind it) and accelerates (up to 225 units per frame while aimed) O.- A mutant spawned with no pods left starts at full speed; a Commander that mutated starts at 0 O.
- The approach brakes 100 raw (25 units) per frame while S ≥ 3 and speed > 200 O.
- A Commander whose pod is destroyed by someone else during the approach goes back to attack at its braked speed and keeps it (accel 0) until it destroys a pod and becomes a mutant D.
4.7 Death, escape and removal of aliens
| Cause | Where in the frame | Effect | Explosion age starts |
|---|---|---|---|
| your laser, hp reaches ≤ 0 | playerShotsUpdate, before the aliens move | state −1, score added, sound 0 | 1 |
| ram, hp reaches 0 | aliensUpdate after its move | state −1, no score | model scale = 1 |
| your missile | playerMissilesUpdate | hp −16 (always fatal), state −1, score | model scale = 1 |
| Pirate escape | its behaviour | type 0 at once, aliensLeft − 1 | — |
A dying alien (state −1) is skipped by your shots, missiles and the lock window; each frame it
drifts along its old nose at its last speed, its age goes up by 1, and when the age exceeds 0x40
the slot is freed and aliensLeft drops by 1 O.
5. Missiles
Four slots for the aliens' missiles, four for yours (src/aliens.c, src/missiles.c). Missile models have scale 0.
5.1 Enemy launch: enemyMissileLaunch(a)
enemyMissileLaunch(a):
m = first of the 4 enemy slots with type == 0; none: return 0
m.pos = a.pos; m.fwd = a.fwd; m.right = a.right; m.up = a.up // before a's move this frame
m.type = TYPES[a.type - 1].missileKind // Pirate 1, Commander 2
m.distExp = 0; m.state = 0; m.particles = 12
if m.type == 1: m.accel = 0; m.maxTurn = 8; model = MISSILE_0
else: m.accel = 0x32; m.maxTurn = 0x20; model = MISSILE_1
m.maxSpeed = 0x640; m.speed = 0x640 // 400 units per frame
message("WARNING: MISSILE LAUNCH DETECTED", 0x10); sound(3)
return 1
5.2 Enemy flight and hit: enemyMissilesUpdate
enemyMissilesUpdate():
for each enemy slot m in order:
if m.type <= 0: continue
if m.state == -1:
explosionStep(m); if m.distExp > 0x40: m.type = 0
continue // an exploding missile does not move
steerChase(m) // toward you, even if you are dead
objectMove(m) // its touch flag is ignored
if m.distExp < 0 and m.type == 1: m.type = 0 // kind 1 gives up
if m.distExp >= 6 and shields > 0: // hit you
sound(1); shields -= 1; flashColor = HIT
if shields <= 0: shields = 0; deathCountdown = 0x40
m.state = -1; m.distExp = 0
5.3 Your launch: playerFireMissile (Enter / Caps Lock, single player)
playerFireMissile():
if haveTarget == 0: message("No Target", 0x10); return // previous frame's lock
if missiles == 0: return
m = first of your 4 slots with type == 0; none: return // stock not used
missiles -= 1; message("Missile Launched", 0x10)
m.pos = shipPos + axisShl(camC, 8) // 64 units along "up", before your move
m.fwd = camA; m.right = camB; m.up = camC
m.type = 1; m.distExp = 0; m.state = 1; m.particles = 12
m.speed = 0x640; m.maxSpeed = 0x640; m.accel = 0x64; m.maxTurn = 0x80
m.model = PLAYER_MISSILE // scale 0
m.target = none
for i in 0..7: // FIRST marked alien, not the nearest
if aliens[i].type > 0 and aliens[i].state != -1 and aliens[i].visible == 2:
m.target = aliens[i]; m.state = 0; break
5.4 Your missile's flight: playerMissilesUpdate
playerMissilesUpdate():
i = 0
while i < 4:
m = yours[i]
if m.type <= 0: i += 1; continue
switch m.state:
-1: explosionStep(m); if m.distExp > 0x40: m.type = 0
i += 1; continue // no movement
0: t = m.target
if t.state == -1 or t.type == 0: m.state = 1; break // unguided from now; this
// frame it still turns with last frame's rates
e = steerToObject(m, t) // brakes 25/frame to 0 if t is behind
if e >= 6: // contact: every axis within 256 units
t.hp -= 16
if t.hp <= 0: t.hp = 0; t.state = -1; t.distExp = scale(t.model)
addScore(TYPES[t.type - 1].score)
m.state = -1; m.distExp = 1
sound(0)
continue // WITHOUT i += 1: the same slot again, now
// in case -1: explosionStep ages it to 2,
// it does not move this frame
break // no hit: objectMove below
1: m.yawRate = 0; m.pitchRate = 0
if m.distExp < 0: m.type = 0 // previous frame's exponent
objectMove(m) // also runs once for a missile just expired
i += 1
- Lock selection is the first alien slot whose mark is 2 from the previous frame's
aliensUpdate, alive and not exploding O.
haveTargetis not reset at level start, so the first frame of a level sees the last frame of the previous one O; an escaping last Pirate can leave it at 1, so a missile fired in the first frame of the next level is used up and flies unguided D. - Homing: yours uses steerToObject (±256 cone, brakes to 0 while the target is behind, turn 0x80); enemy ones use steerChase on your ship (±128 cone, brakes to 200 raw, turn 8 or 0x20) O.
- Hit tests: yours is the steering exponent missile→target ≥ 6; the enemy's is its display exponent to you ≥ 6 (scale 0: every axis within [−256, 256)), not blocked by bump immunity and never followed by a bump O.
- Give-up: an enemy kind-1 missile when its display exponent is < 0 after this frame's move; kind 2 never; yours only after it lost its target (state 1) and its exponent was < 0 in the previous frame O.
- Your missile cannot hit anything but its target; enemy missiles cannot hit aliens. Your laser can destroy enemy missiles (7.2) O.
- When the target is freed and the slot reused, your missile has already seen state −1 (the dying alien holds its slot for 64 frames), so it never chases the newcomer D.
6. Pods
Six pod records (src/pods.c); target
links a pod and the alien that claimed it in both directions. Pod model scale 1.
6.1 Placement and counting
podsReset(): for each pod: pod.type = 1; podsLeft = 6 // new game and level index L&3==0
podsPlace(): // every level start, after podsReset
for j in 0..5:
p = pods[j]; if p.type <= 0: continue // lost pods stay lost
p.fwd = (0,0,0x4000); p.up = (0,0x4000,0); p.right = (0x4000,0,0)
p.pos = axisMul(p.right, PX[j]) + axisMul(p.up, PY[j]) + axisMul(p.fwd, PZ[j])
p.home = p.pos
p.state = 0; p.model = POD; p.maxTurn = 0x80; p.accel = 0; p.speed = 0
p.particles = explosionParticles
// PX = [-4000, 0, 4000, 0, 0, 0], PY = [0, 0, 0, 0, -4000, 4000], PZ = [0, -4000, 0, 4000, 0, 0]
// i.e. pods at x = -1000, z = -1000, x = +1000, z = +1000, y = -1000, y = +1000 units
podsLeft goes down by 1 when your laser hits a pod, when a Commander reaches its
pod, and when a Pirate escapes with one. Nothing else changes it until the next podsReset
O.
6.2 The pod step: podsUpdate
podsUpdate():
for j in 0..5:
p = pods[j]; if p.type == 0: continue
switch p.state:
-1: explosionStep(p); if p.distExp >= 0x40: p.type = 0 // note: >=, not >
continue
0: p.rollRate = 0x20; p.pitchRate = 0x20; p.yawRate = 0; p.speed = 0
1: if p.target.state == -1: p.state = 0 // claimer is dying
2: if p.target.state == -1: p.state = 3 // captor is dying...
steerToObject(p, p.target) // ...but still follow it now
p.speed = p.target.speed
3: e = steerToPoint(p, p.home); p.speed = 200
if e >= 7: p.state = 0; p.speed = 0 // every axis within 128 of home
objectMove(p) // touch flag ignored
- Claim: only a pod with state 0 and type > 0, the lowest index first; the claim sets both links and pod state 1 (Pirate state 1, Commander state 2) O.
- Capture: Pirate approach with steering exponent ≥ 6 → pod state 2 in the same frame; the pod, updated after the aliens, follows at the captor's speed (0 while the Pirate turns), turning with its own maxTurn 0x80 O.
- Carry and escape: 4.3. Return: when the captor dies the pod goes to state 3 and flies home at 200 raw (50 units) per frame; home = within [−128, 128) on every axis O.
- Destruction by a Commander: pod state −1 with its age starting at its own current display exponent (whatever the previous frame's draw left), so far-away pods explode longer O.
- Pods never collide with you or anything else O.
- Revival quirk: podsPlace resets every pod with type > 0, including one still
exploding (state −1) when the level ends. That pod returns home intact although
podsLeftalready counted it as lost; it can then be lost (and counted) a second time, sopodsLeftcan go below the number of pods present, even negative, until the next podsReset. Reached by shooting a pod in a frame after the last alien died (while its explosion still runs). WithpodsLeftnegative, alienSpawn's testpodsLeft == 0fails, so normal aliens (not mutants) spawn, and the level bonus (L + 1) · podsLeft · 1000 becomes negative D.
7. Shots
Records: 8 slots for your shots, 8 shared by all aliens, 8 per peer for copies of other players' shots (src/shots.c, src/pods.c, src/players.c).
7.1 Firing: playerFire
playerFire():
if spectator: return
i = first of your 8 slots with state == 0; none: return
s.pos = shipPos + axisShl(camC, 8) // 64 units along "up"
s.fwd = camA; s.right = camB; s.up = camC
s.state = 0x18; myShots[i] = 1 // 24 frames
if firePower > 0: firePower -= 1; s.state |= 0x100; myShots[i] = 2 // powered
s.vel = shipVel + axisShl(camA, 12) // your velocity + 1024 units forward
sound(5)
State word: 0 free; low byte = frames left; bit 0x100 = powered; negative = exploding (counts
up from −8). myShots[i] is the network flag: 0 free, 1 flying, 2 flying powered,
3 exploding.
7.2 Your shots each frame: playerShotsUpdate
playerShotsUpdate():
eventOut[0..2] = 0; itemEventOut = 0 // last frame's reports are gone
for i in 0..7:
s = shots[i]
if (s.state & 0xFF) == 0: s.state = 0; myShots[i] = 0; continue // expired / free
if int16(s.state) < 0: // exploding
myShots[i] = 3; s.state += 1
if int16(s.state) < 0: draw the ring
continue
s.state -= 1; s.pos += s.vel; draw the shot
if multiplayer:
for j in 0..2: // peer ships
q = peerShips[j]
if q.state != -1 and q.type != 0 and shotHits(s, q):
eventOut[j] = peerSlot[j] + 1
if (s.state & 0x100) != 0: eventOut[j] += 0x100
s.state = 0xFFF8; addScore(50); break
for j in 0..2: // peer satellites: NO break
if peerItems[j].type > 0 and shotHits(s, peerItems[j]):
s.state = 0xFFF8; itemEventOut = peerSlot[j] + 0x101; sound(0)
else:
for j in 0..7: // 1. aliens
o = aliens[j]
if o.type > 0 and o.state >= 0 and shotHits(s, o):
s.state = 0xFFF8; o.hp -= 1
if firePower > 0: o.hp -= 1 // the STOCK now, not the shot's bit
if o.hp <= 0: o.state = -1; o.distExp = 1
addScore(TYPES[o.type - 1].score); sound(0)
break
if an alien was hit: continue
for j in 0..3: // 2. enemy missiles
o = enemyMissiles[j]
if o.type > 0 and o.state >= 0 and shotHits(s, o):
s.state = 0xFFF8; o.state = -1; o.distExp = 0; addScore(25); sound(0); break
if a missile was hit: continue
for j in 0..5: // 3. pods (friendly fire)
o = pods[j]
if o.type > 0 and o.state >= 0 and shotHits(s, o):
s.state = 0xFFF8; o.state = -1; o.distExp = 0; podsLeft -= 1; sound(0); break
if a pod was hit: continue
if myItem.type > 0 and shotHits(s, myItem): // 4. own satellite (always in multiplayer)
myItem.type = -1; myItem.distExp = 0; sound(0); s.state = 0xFFF8
7.3 The hit test: shotHits(s, o)
shotHits(s, o):
sc = scale(o.model) // 1: aliens, pods, ships; 0: missiles, satellites
r = 0x200; if sc > 1: r = int16(r << (sc - 1))
h = int16(0x60 << sc) // 0xC0 for scale 1, 0x60 for scale 0
d = o.pos - s.pos
for each axis: m = mid32(d.axis); if m > r or m < -r: return false
v = (mid16(d.x), mid16(d.y), mid16(d.z)) // exact: the first test bounded them
dr = dot(v, s.right); du = dot(v, s.up); df = dot(v, s.fwd)
if df > r or df < -r: return false
if dr > h or dr < -h: return false
if du > h or du < -h: return false
return true
7.4 Alien laser: alienFire(a)
alienFire(a): // Fighter, Guardian, mutant
s = first of the 8 alien-shot slots with state == 0; none: return
s.pos = a.pos; s.fwd = a.fwd; s.right = a.right; s.up = a.up // before a's turn and move
s.state = 0x18
7.5 Alien shots each frame: alienShotsUpdate
alienShotsUpdate():
for each alien shot s in order:
if s.state == 0: continue
s.state -= 1 // reaching 0 frees it after this frame's test
s.pos += axisShl(s.fwd, 12) // 1024 units along its nose, no inherited speed
draw it
if shields == 0: continue
d = shipPos - s.pos
for each axis: if mid32(d.axis) > 0x400 or mid32(d.axis) < -0x400: skip to next shot
v = mid16 of each axis
a = dot(v, s.fwd); u = dot(v, s.up); r = dot(v, s.right)
if r > 0x400 or r < -0x400 or a > 0x100 or a < -0x100 or u > 0x100 or u < -0x100: continue
sound(1); flashColor = HIT; s.state = 0
shields -= 1; if shields == 0: deathCountdown = 0x40
- Your shot moves and is tested 24 times; it is tested in the frame its counter reaches 0 and freed at the next frame's top. A slot whose unpowered shot expires in frame N can be fired again from frame N+1 (its word is 0). A powered shot's word reaches 0x100 instead; playerUpdate runs before playerShotsUpdate, so in frame N+1 the slot is still busy, it is cleared later in N+1 and reusable from frame N+2 O.
- After a hit the ring is drawn for the states −7 … −1 (7 frames); the slot is 0 the frame
after and
myShotsstays 3 until then O. - Your shot tests aliens, missiles and pods where they were at the end of the previous frame, in table order; single player stops at the first hit; multiplayer always continues to the item loops O.
- All limits are inclusive (−r ≤ value ≤ r); the first test uses 32-bit middle values, the second the 16-bit middle words O.
- An alien shot fired in frame N first moves in frame N (from the alien's position before its move), lives 24 updates, has no explosion and can only hit you, while you are alive, with no bump and regardless of bump immunity O.
- Neither your shots nor alien shots are cleared at level start or at a new game: shots in flight carry over into the next level O.
8. Satellites
One own satellite record (myItem) and, in multiplayer, one copy per peer
(src/satellite.c). Kinds: 1 shields, 2 missiles
(multiplayer: cloak), 3 extra thrust, 4 fire power; type −1 = exploding. Model scale 0.
8.1 Spawning
satellitesClear(): // level start / life start
myItem.type = 0; myItem.fwd = (0,0,0x4000); myItem.right = (0x4000,0,0); myItem.up = (0,0x4000,0)
myItem.particles = 12
for each peer copy: type = 0, model = SAT_SHIELDS, same axes, particles 12
satelliteSpawn(): // frames with (frameCount & 127) == 0, not for spectators
if myItem.type != 0: return // also while it explodes
satelliteCounter += 1 // 16-bit signed, wraps
myItem.pos = 0
mid(myItem.pos.x) = rand() * 20000 / 32768 // in this order: x, y, z
mid(myItem.pos.y) = rand() * 20000 / 32768
mid(myItem.pos.z) = rand() * 20000 / 32768
myItem.pos -= (10000, 10000, 10000) units // 64-bit: −10000 … 9999 around the ORIGIN
switch satelliteCounter & 3:
0: type 2 (model: cloak in multiplayer, missiles in single player)
1: type 3 2: type 4 3: type 1
8.2 The satellite step: satelliteUpdate
satelliteUpdate():
if multiplayer: // 1. did a peer take / shoot mine?
for each peer i:
if (peerEvents[i][4] & 0xFF) == playerIndex + 1:
if (peerEvents[i][4] & 0x100) != 0: myItem.type = -1; myItem.distExp = 0 // shot
else: myItem.type = 0 // collected
if myItem.type != 0: // 2. my own satellite
if myItem.type > 0:
rotate(myItem.fwd toward myItem.right, 0x20); myItem.right = cross(myItem.up, myItem.fwd)
touch = see(myItem)
if not multiplayer and myItem.distExp < -1: myItem.type = 0 // lost far away
if touch and not spectator: applyPickup(myItem.type); myItem.type = 0
else:
explosionStep(myItem); if myItem.distExp > 0x40: myItem.type = 0; myItem.distExp = 0
if multiplayer: // 3. the peers' satellites
for each peer i:
c = peerItems[i]; if c.type == 0: continue
if peerAlive[i] == 0: c.type = 0; continue
if c.type > 0:
c.state = 0; c.model = SAT_MODEL[c.type]
rotate(c.fwd toward c.up, 0x20); c.up = cross(c.fwd, c.right)
if see(c) and not spectator:
applyPickup(c.type); itemEventOut = peerSlot[i] + 1
else:
if c.state == 0: c.state = 1; c.distExp = 0 // start the explosion once
explosionStep(c) // never freed here
applyPickup(kind):
messageTimer = 0x20
if multiplayer: shields = 0x20; message "SHIELDS RESTORED"
kind 1: single: shields = min(shields + 8, 0x20), "EXTRA SHIELDS"
kind 2: multi: cloakTime = 0x200; cloakOn = 0 single: missiles = min(missiles + 3, 0x20), "MISSILES"
kind 3: multi: extraThrust = 0x400 single: min(extraThrust + 0x400, 0x1000), "EXTRA THRUST"
kind 4: multi: firePower = 0x40 single: min(firePower + 0x40, 0x100), "EXTRA FIRE POWER"
sound(2)
- Kind cycle:
satelliteCounteris never reset, so the first satellite after the program starts is kind 3 (thrust), then 4, 1, 2, 3, … across levels, games and modes O. - Pick-up = display exponent ≥ 7 (every axis within [−128, 128)) and bump immunity 0; it is applied at once, inside satelliteUpdate O.
- Shooting your own satellite (7.2) explodes it (age 0, freed when the age passes 0x40, 65 frames); no points; no new satellite can spawn while it explodes O.
- Single player only: the satellite disappears when its display exponent is < −1 (some axis beyond about 32,770 units from you) O.
- No shields test: a dead ship (which no longer moves, section 3) that touches a satellite still
collects it. A shields satellite then gives it 8 shields: the frame ends in the "alive" branch,
the death screen is gone without Enter, the death countdown keeps its value and the next frame
flies normally O (original code run in an emulator,
tools/doccheck/; not seen in a recorded run: satellites appear within 10,000 units of the origin, so the dead ship must happen to lie within 128 units of one). - Multiplayer: the copy of a peer's satellite keeps its type until the owner's packet clears
it, so a pick-up is applied again on every frame you touch it until that packet arrives: seen
twice in a row during a flight, and on almost every frame for 23 s while the owner sat on the
name screen, which never runs satelliteUpdate (run satrep,
evidence/runtime/probe_satrep_note.json;
chapter 8, "Satellites between players")
O.
itemEventOutfrom a pick-up overwrites a "shot a satellite" report from playerShotsUpdate in the same frame O. - The two spins differ: own satellite fwd toward right (yaw), peer copies fwd toward up (pitch) O.
9. Contacts, damage, death and the level
9.1 Every way your shields change, in frame order
| Step | Event | Shields | Flash | Bump | At 0 |
|---|---|---|---|---|---|
| aliensUpdate | an alien touches you (display ≥ 7, immunity 0) | −1 | collision | yes, if still > 0 | countdown 0x40 |
| enemyMissilesUpdate | missile display ≥ 6 | −1 | hit | no | countdown |
| alienShotsUpdate | slab test | −1 | hit | no | countdown (only at exactly 0) |
| satelliteUpdate | pick-up | +8 (max 32) / multiplayer = 32 | — | — | — |
| remotePlayersUpdate | a peer ship touches you | −1 | collision (via the bump) | yes, if still > 0 | status 1, killer = slot + 4, countdown |
| netSyncFrame | a peer's hit report for your slot | −1 (−2 powered) | hit / powered hit | no | status 1, killer = slot, countdown |
| level transition | level completed | +8 (max 32) | |||
playerBump(): // players.c
bumpImmunity = 8; tumble = 0x30; flashColor = COLLISION
message("COLLISION", 0x30)
tumbleRates[0] = (rand() * 2 / 32768) * 0x60 - 0x30 // pitch, first rand()
tumbleRates[1] = (rand() * 2 / 32768) * 0x60 - 0x30 // roll, second rand()
tumbleRates[2] = 0
shipVel = PRESET[playerIndex] // slot 0: (0,0,+64), 1: (0,0,-64), 2: (0,+64,0), 3: (0,-64,0) units/frame
- Damage is applied at once, at the point of the frame where it is found; several hits in one frame all count, the flash colour of the last one wins O.
- No local test hurts a dead ship (rams, enemy missiles and peer collisions require shields > 0, alien shots shields != 0); your own shots and missiles keep flying and scoring while you are dead O. Exception in multiplayer: netSyncFrame applies a peer's hit report without a shields test, so it restarts the death countdown of a dead player (10.4) O. The satellite pick-up has no shields test either: a dead ship that touches a shields satellite lives again with 8 shields (8, "Exact rules") O.
- Only one ram per bump: the first touching alien in slot order bumps you and sets immunity, so later slots in the same frame do not touch O.
- There is no collision between aliens, pods, missiles or shots other than those listed O.
9.2 Score
addScore(points): // 32-bit
score[me] += points
if score[me] > 1000000: score[me] -= 1000000
scoreText = format("SCORE: %6ld", score[me])
Points: alien killed by laser or missile: its type's score (a mutant 400); enemy missile shot down: 25; level bonus; multiplayer: 50 per laser hit on a peer. Rams, pods and satellites give nothing O.
9.3 Death: playerDeadScreen
Called in place of the radar and instruments in every frame with shields 0; the world keeps running (src/screens.c) O.
playerDeadScreen():
draw "Game Over" (single) / "You were killed by <name of slot killerIndex & 3>" (multi)
if deathCountdown > 0:
clear the Enter latch and the mouse latch; deathCountdown -= 1; return 0
if single player and score[0] > lowest high score:
shields = 0x20; return 1 // straight to initials entry
draw "Press ENTER to restart"
if neither Enter nor mouse latched: return 0
shields = 0x20; sound(4); clear both latches
if single player: return 1 // ends the flight loop
// multiplayer respawn, inside the loop:
throttle = 0; statusOut = 0; cloakTime = 0; cloakOn = 0; firePower = 0; extraThrust = 0
shipPos += axisShl(camC, 12) // 1024 units along "up"
return 0 // velocity is NOT reset: the new life keeps the
// velocity from before death (a dead ship only
// stopped moving because playerUpdate returned early)
9.4 After the single-player loop, and the level transition
after the flight loop (single player):
if shields == 0: new game // ESC pressed while dead
if aliensLeft > 0: new game // ESC, or a death (shields already 32 again)
if levelComplete() == ESC: new game
goto level start
levelComplete():
addScore((level + 1) * podsLeft * 1000) // 32-bit; podsLeft as it is now
shields = min(shields + 8, 0x20)
ship: axes = identity (a = +z, b = +x, c = +y), position 0, velocity 0
wait for Enter (level += 1) or ESC
level start (single player):
explosionParticles = wireframe ? 12 : 38
levelSetup(level) // 4.2: pods, budget, Pirate speed, rotations
levelIntro() // ESC: new game. This screen ROLLS the camera
throttle = 0
aliensClear() // 8 alien slots + 8 missile slots
satellitesClear()
frameCount = 0; messageTimer = 0
capture the keyboard; clear the ESC latch
enter the flight loop
new game (single player):
attract screens, start-level menu (level 0..7)
score[me] = 0; missiles = 16; firePower = 0; extraThrust = 0; cloak = 0
ship: identity axes, position 0, velocity 0, throttle 0, shields 32
podsReset(); then "level start"
- The level ends at the top of the first frame in which
aliensLeft == 0and shields > 0: every budgeted alien has spawned and either finished exploding or escaped O. - A player who dies while the last alien explodes and then presses Enter has shields 32 and
aliensLeft == 0when the loop ends, so the level counts as completed D. - Carried into the next level: score, shields (+8), missiles, fire power, extra thrust, the
satellite kind cycle, the keyboard turn rates,
tumble,tumbleRates,bumpImmunity,fireCooldown,haveTarget, radar zoom, and all shots in flight O. Reset: aliens, all missiles, your satellite, the frame counter, the message, position, velocity and throttle. - The camera is not at the identity when the flight starts. Starting from the
identity, every frame of the level introduction does
rotate(camB toward camC, −16); camC = cross(camA, camB). The intro runs at the retrace rate (about 70 frames per second) until you press Enter, so the number of intro frames is an input of the simulation: record it to replay a game (runtime #35) O. - Pods: surviving pods are put back home with state 0 (see the revival quirk in 6); all six are restored when the new level index is a multiple of 4 O.
10. Multiplayer: the local step around the network
What one machine does with the other players (src/net.c,
src/players.c). Chapter 8 explains the design; the
packet layout is in chapter 8 and docs/network-protocol.md. Peers are numbered 0–2 (a spectator:
0–3); peerSlot[i] is the slot (0–3) of peer i.
10.1 Sending and receiving
postPeerListens(): for each peer i with peerAlive[i] != 0: arm the receive for peer i
sendStateIfIdle(): if the previous send has finished: broadcast
{ name, camA/camB/camC, shipPos, shipVel, eventOut[0..2], statusOut,
itemEventOut, score[me], myItem.type + myItem.pos, myShots[0..7] }
on receive from peer i (at most one per armed receive):
name -> names[peerSlot[i]] axes -> peerShips[i].fwd/right/up
pos -> peerShips[i].pos vel -> peerShips[i].home (used for shot copies)
events -> peerEvents[i][0..4] score -> score[peerSlot[i]]
item -> peerItems[i].type, .pos shot flags -> peerShots[i][0..7]
In the original a packet is written into these records the moment it arrives, at any point
between postPeerListens and the end of netSyncFrame's wait
O. A rebuild that wants determinism should apply each received packet at
one fixed point; applying it just before step 3 of netSyncFrame matches the common case
(design proposal, not the original).
10.2 The other ships: remotePlayersUpdate
remotePlayersUpdate():
for each peer i:
q = peerShips[i]
if q.type == 0: continue
if peerEvents[i][3] == 2: continue // peer not in play
if peerAlive[i] == 0: q.type = 0; continue
if q.state == -1: // killed (started by netSyncFrame)
if q.distExp == 3:
message("<name> has been killed", 0x40); sound(0)
explosionStep(q)
if q.distExp > 0x40: q.state = 0; q.type = 0
continue
touch = see(q, noDraw = (peerEvents[i][3] == -1)) // cloaked: not drawn, still touches
if touch and shields > 0 and not spectator:
shields -= 1
if shields == 0: statusOut = 1; killerIndex = peerSlot[i] + 4; deathCountdown = 0x40
else: playerBump()
10.3 Copies of their shots: remoteShotsUpdate
remoteShotsUpdate():
for each peer i (same presence tests as above: type != 0, status != 2):
for k in 0..7:
s = copies[i][k]; f = peerShots[i][k]
if s.state == 0 or f == 4:
if f == 0 or f == 3: continue
s.pos = peerShips[i].pos + axisShl(peerShips[i].up, 8)
s.state = 0x18; if f == 2: s.state |= 0x100
s.vel = peerShips[i].home + axisShl(peerShips[i].fwd, 12)
s.state -= 1 // 16-bit
if int16(s.state) >= 0:
if f == 3: s.state = 0xFFF9 // explosion ring
else: s.pos += s.vel
else: s.state += 1 // exploding copies stay as they are
if s.state != 0: draw it
if f == 0: s.state = 0
Copies never hit anything; the shooter's machine decides hits (7.2) O.
10.4 The end of the frame: netSyncFrame
netSyncFrame():
// 1. wait
while tick < 5 and some peer i in 0..3 has peerAlive[i] != 0 and its receive still pending: wait
// 2. liveness
for each peer i:
if peerAlive[i] != 0 and receive pending:
if peerAlive[i] > 0: peerAlive[i] -= 1
if peerAlive[i] > 0: cancel the receive (re-armed next frame)
elif peerAlive[i] < 4 and receive completed: peerAlive[i] = 4
for each peer i:
// 3. hits on me (reads the LAST packet of peer i, new or not)
if not spectator:
for j in 0..2:
w = peerEvents[i][j]
if (w & 0xFF) == playerIndex + 1:
sound(1)
if (w & 0x100) != 0: shields -= 2; flashColor = POWERED_HIT
else: shields -= 1; flashColor = HIT
if shields <= 0: shields = 0; statusOut = 1; killerIndex = peerSlot[i]; deathCountdown = 0x40
if cloakTime > 0: cloakTime = 0; message("Cloak Destroyed!", 0x30)
// 4. peer status
st = int16(peerEvents[i][3])
if st == 1 and peerShips[i].state == 0: peerShips[i].state = -1; peerShips[i].distExp = 3
if st <= 0 and peerShips[i].type == 0 and peerAlive[i] != 0:
peerShips[i].state = 0; peerShips[i].type = 1
if st == 2: peerShips[i].type = 0; peerShips[i].state = 0
- Hits on you are applied after drawing, at the end of the frame; they are read from the receive buffer every frame, so a peer that stops sending right after a hit repeats it every frame (runtime #24) O.
- A hit report also lands while you are already dead: shields stay 0 but the death countdown starts again O.
- A killed peer's explosion starts at age 3; the "has been killed" message appears in the next remotePlayersUpdate (age still 3). After the explosion ends the record is freed, and while the peer still reports status 1 netSyncFrame sets the freed record to state −1, age 3 again, but with type 0: nothing draws, ages or tests it, so this has no visible or simulated effect; status 0 brings the ship back D.
- Your satellite is spawned and kept locally like in single player, except that it never expires by distance; peers learn about it only from your packets O.
- A new life (after the name screen) resets missiles, fire power, extra thrust and cloak to 0 and statusOut to 0 and places the ship at its slot's corner with 32 shields; a respawn after death (9.3) keeps the score and missiles O.
- Your shots hit where targets were a frame ago; alien shots and missiles hit where you are now (1.3).
- Bodies that skip steering for a frame repeat the previous frame's turn (Commander picking a pod, any Pirate or Commander whose pod was just destroyed, your missile in the frame its target is lost).
- An escaped Pirate is lock-tested once more, which can light the lock and waste a missile, even in the first frame of the next level; a rammed-dead alien rarely does (its window is about 6 units).
- A Pirate that loses its pod while turning stays at speed 0 for ever; a Pirate or Commander that loses it during the approach keeps its braked speed (4.3, 4.6).
- An exploding pod at level end comes back (6).
- Shots survive level changes (7).
Write one function per heading of this chapter and call them in the order of 1.1 (single
player) or 1.2 (multiplayer). Use 64-bit integers for positions (BigInt or a pair of 32-bit
numbers in JavaScript), the exact dot, rotate and cross of
2.1 (with the lost borrow) and the exponent rule of 2.2: then every threshold, every turn and every
hit lands on the same frame as in the original. Test a few frames against chapter 21's reference
cases before adding drawing.