Falsebound Archive
5 Bugs & quirks 5.4

Lightning that divides by zero

Several attacks draw lightning: a jagged line between two points, redrawn each frame with random kinks. To place each kink the effect takes a random number and keeps the remainder after dividing by a whole number n, 200 times the length of a segment of the bolt (times a random strength factor), then centres and scales the result:

Where
Attack effect library, bolt steps (fx_bolts_step, fx_cbolts_step, fx_vbolts_step)
Division by zero in the original
Yes, when a bolt’s two ends coincide or nearly so
Result on the GameCube
No crash; points jitter by up to about 20 units
Visible
Only when it happens; not known to occur in normal playUnconfirmed
n      = 200 * strength * segment length     (rounded down to a whole number)
offset = ((rand() >> 4) % n - n / 2) / 100

If the two ends of a bolt are in the same place, or so close that n rounds down to 0, this divides by zero.

On most computers that stops the program. The GameCube’s PowerPC processor does not trap: its divide instruction gives some quotient, and because the remainder is worked out as the number minus the quotient times 0, it comes out as the number that was being divided, whatever that quotient is. Instead of crashing, the console moves each inner point of that bolt by the raw random value (0 to 2,047) in hundredths, up to about 20 units along each axis, and the lightning jitters for as long as its ends coincide.

The same kind of division appears in other places where a data value could be zero (colour fades divided by a maximum brightness, particle counts), and a few in the main game code: a battle’s experience share divided by the number of monsters still standing, a mission script’s fade divided by its length in frames. One of them can be reached in play. A monster under a counter status (Mirror Force gives one) hits back before an attack’s damage lands; if that counter knocks out the last monster of the attacking side and the attack still knocks out the target, the experience share is divided by 0. Nobody is left to receive it, so nothing changes. In shipped data none of the others is known to hit zero.

Evidence

The bolt functions were decompiled, and the original machine code computes the remainder with the PowerPC divw instruction followed by a multiply and a subtract. The PowerPC manual leaves the quotient of a division by zero undefined and promises no trap; the remainder does not depend on that quotient, because it is multiplied by the zero divisor.