Skip to content

Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.

4.1 KB
Raw Blame
#!/usr/bin/env python3
"""Generate the integer trig tables the simulation runs on.

The game's logic may not call the C runtime's sin, cos or atan2.  Those are not
specified bit for bit, they are dispatched on the host CPU, and they ship with
the machine rather than with the game, so two players can compute two different
answers and a lockstep simulation diverges.  Every angle in the simulation
therefore goes through a committed table plus integer interpolation, which is
the same arithmetic everywhere.

This script writes that table.  Run it only to regenerate; the output is
checked in and is the authority at runtime.

    python gentrigtables.py >
        ../Libraries/Source/WWVegas/WWMath/dettrigtables.h

Two scales, both powers of two so that every conversion is exact:

  TRIG_VALUE_ONE   2^24, the value 1.0.  A float holds integers up to 2^24
                   exactly, so a wider table would buy nothing the result can
                   carry.
  one turn         2^32, the angle domain.  It is the natural width of an
                   UnsignedInt, which makes wrapping an angle free and makes
                   the quadrant the top two bits.

  SIN_QUARTER_ENTRIES  2048 samples of sin over [0, pi/2]
  ATAN_ENTRIES         1024 samples of atan over [0, 1]

Sampling a quarter turn rather than a whole one costs a quadrant fold at
runtime and buys four times the resolution for the same memory.  Linear
interpolation between samples leaves at most d^2/8 * |f''|, which is 7.4e-8 for
sin and 7.7e-8 for atan - under a float's own epsilon, and four orders below
the 7.7e-4 of the 4096-entry, 12-bit table EA left behind switched off.

Measured worst case against the reference, over the whole range: 1.6e-7 radians
for Sin and Cos, 2.2e-7 for ATan2, 4.2e-7 for ACos, 3.0e-7 for ASin.
"""

import math

TRIG_VALUE_ONE = 1 << 24
TURN_ONE = 1 << 32
SIN_QUARTER_ENTRIES = 2048
ATAN_ENTRIES = 1024

TIE_MARGIN = 1e-9   # a sample this close to .5 would make the rounding below
                    # depend on the last bits of Python's own math library


def scaled(exact, scale, what):
    """Round exact*scale to an integer, refusing anything near a rounding tie."""
    value = exact * scale
    if abs(value - math.floor(value) - 0.5) < TIE_MARGIN:
        raise SystemExit("%s lands on a rounding tie at %r" % (what, exact))
    return int(math.floor(value + 0.5))


def emit(name, size_expr, values, per_line=6):
    print("static const int %s[%s] = {" % (name, size_expr))
    for i in range(0, len(values), per_line):
        row = ", ".join("%12d" % v for v in values[i:i + per_line])
        print("\t%s%s" % (row, "," if i + per_line < len(values) else ""))
    print("};")
    print()


def main():
    # sin over [0, pi/2], in units of TRIG_VALUE_ONE == 1.0.  One entry past the
    # end so interpolation can always read index+1, and so the exact quarter
    # turn is a lookup rather than a special case.
    sines = [
        scaled(math.sin(math.pi / 2 * i / SIN_QUARTER_ENTRIES),
               TRIG_VALUE_ONE, "sin(%d)" % i)
        for i in range(SIN_QUARTER_ENTRIES + 1)
    ]
    assert sines[0] == 0 and sines[-1] == TRIG_VALUE_ONE

    # atan over [0, 1], measured in turns rather than radians so that the
    # quadrant reconstruction is an integer add.  atan(1) is an eighth turn.
    arctans = [
        scaled(math.atan(i / ATAN_ENTRIES) / (2 * math.pi), TURN_ONE,
               "atan(%d)" % i)
        for i in range(ATAN_ENTRIES + 1)
    ]
    assert arctans[0] == 0 and arctans[-1] == TURN_ONE // 8

    # both interpolations widen to Int64 before multiplying; check the reason
    assert max(sines[i + 1] - sines[i]
               for i in range(SIN_QUARTER_ENTRIES)) == 12868
    assert max(arctans[i + 1] - arctans[i]
               for i in range(ATAN_ENTRIES)) == 667544

    print("// GENERATED BY Tools/gentrigtables.py - DO NOT EDIT BY HAND.")
    print("// Regenerate with:")
    print("//   python Tools/gentrigtables.py > \\")
    print("//       Libraries/Source/WWVegas/WWMath/dettrigtables.h")
    print()
    emit("theSinQuarterTable", "SIN_QUARTER_ENTRIES + 1", sines)
    emit("theArcTanTable", "ATAN_ENTRIES + 1", arctans)


main()