Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

15.2 KB
Raw Blame
#!/usr/bin/env python3
"""src/data.h: Jetpack Joyride's own tables, from the game's Android package (1.3.5, unzipped).

    python3 -I tools/data.py APK_DIR src/data.h

APK_DIR holds the package's assets/ folder. Its xml/ files are Halfbrick's binary XML ("bxml": a string table,
then nodes of name, attributes and children), read here; nothing of the package is run. What comes out: level
pacing, zapper, laser, missile, coin, vehicle and Final Spin tables, with the original's numbers (points and
60ths of a second). The spec beside the port says where each one comes from.
"""
import os
import struct
import sys
import xml.etree.ElementTree as ET


def bxml(path):
    """Halfbrick bxml -> an ElementTree element."""
    b = open(path, 'rb').read()
    if b[:4] != b'bxml':
        return ET.fromstring(b)
    size = struct.unpack_from('<I', b, 8)[0]
    table = b[12:12 + size]
    pos = 12 + size

    def s(o):
        return table[o:table.index(b'\0', o)].decode('latin1')

    def u32():
        nonlocal pos
        v = struct.unpack_from('<I', b, pos)[0]
        pos += 4
        return v

    def node():
        nonlocal pos
        kind = b[pos]
        pos += 1
        if kind == 4:  # text
            return s(u32())
        assert kind == 1, kind
        e = ET.Element(s(u32()))
        for _ in range(u32()):
            k = s(u32())
            e.set(k, s(u32()))
        text = []
        for _ in range(u32()):
            c = node()
            if isinstance(c, str):
                text.append(c)
            else:
                e.append(c)
        e.text = ''.join(text) or None
        return e

    roots = [node() for _ in range(u32())]
    return roots[0]


def f(e, tag, default=0.0):
    c = e.find(tag)
    if c is None:
        return default
    v = c.get('value', c.text)
    return float(str(v).strip().rstrip('f'))


def schedule(e):
    """<probability value startDistance> list -> [(metres, weight)]."""
    out = [(int(float(p.get('startDistance', 0))), float(p.get('value'))) for p in e.findall('probability')]
    return out or [(0, 0.0)]


class Out:
    def __init__(self):
        self.lines = []

    def __call__(self, s=''):
        self.lines.append(s)

    def arr(self, kind, name, values, per=16):
        self(f'static const {kind} {name}[] = {{')
        for i in range(0, len(values), per):
            self('  ' + ', '.join(str(v) for v in values[i:i + per]) + ',')
        self('};')


def w100(x):
    """A weight in hundredths (the files give at most two decimals)."""
    return int(round(x * 100))


def main():
    apk, dst = sys.argv[1], sys.argv[2]
    A = os.path.join(apk, 'assets')
    X = lambda p: bxml(os.path.join(A, 'xml', p))
    o = Out()
    o('/* Generated by tools/data.py from Jetpack Joyride 1.3.5\'s own files (Halfbrick). Points, 60ths of a second;')
    o(' * weights in hundredths. See the spec for where each number comes from. */')
    o('#ifndef JJ_DATA_H')
    o('#define JJ_DATA_H')
    o('#include <stdint.h>')
    o()

    # ---------------------------------------------------------------- weights by distance
    sched = []  # flat (metres, weight*100), each schedule ends with 0xffff

    def add_sched(s):
        start = len(sched)
        for m, w in s:
            sched.append((m, w100(w)))
        sched.append((0xffff, 0))
        return start

    # ---------------------------------------------------------------- settings
    st = X('settings.xml')
    sv = {s.get('name'): float(s.get('value')) for s in st.iter('setting')}
    wp = X('weapons.xml').find('weapon')
    wv = {c.tag: (c.text or '').strip().rstrip('f') for c in wp}
    o(f'#define JJ_GRAVITY {float(wv["BARRY_GRAVITY"])}f')
    o(f'#define JJ_BOOST {float(wv["BARRY_BOOST"])}f')
    o(f'#define JJ_FRICTION {float(wv["BARRY_FRICTION"])}f')
    o(f'#define JJ_VSCALAR {float(wv["BARRY_VELOCITY_SCALAR"])}f')
    o(f'#define JJ_FIRE_EVERY {int(wv["rateOfFire"])}')
    o(f'#define JJ_BULLET_SPEED {float(wv["initialVelocity"])}f')
    o(f'#define JJ_BULLET_ANGLE {float(wv["initialAngle"])}f')
    o(f'#define JJ_BULLET_SPREAD {float(wv["spreadAngle"])}f')
    o(f'#define JJ_DIST_DIV {int(sv["DISTANCE_DIVISOR"])}')
    o(f'#define JJ_IMMUNITY_MS {int(sv["IMMUNITY_TIME"])}')
    o(f'#define JJ_DEATH_GRAVITY {sv["DEATH_GRAVITY"]}f')
    o(f'#define JJ_DEATH_GROUND_FRICTION {sv["DEATH_X_GROUND_FRICTION"]}f')
    o(f'#define JJ_MIN_BOUNCE {sv["MIN_BOUNCE_VELOCITY"]}f')

    # ---------------------------------------------------------------- level pacing
    lp = X('levelpacing.xml')
    ls = {s.get('name'): float(s.get('value')) for s in lp.findall('setting')}
    o(f'#define JJ_START_SPEED {ls["START_VELOCITY"]}f')
    o(f'#define JJ_END_SPEED {ls["END_VELOCITY"]}f')
    o(f'#define JJ_SPEED_DIST {int(ls["VELOCITY_STOP_DISTANCE"])}')
    d = lp.find('Default')
    mins, maxs = {}, {}
    for s in d.findall('setting'):
        m = int(s.get('distance', 0))
        (mins if s.get('name') == 'MIN_SPAWN_INTERVAL' else maxs)[m] = int(float(s.get('value')))
    steps = sorted(mins)
    assert steps == sorted(maxs)
    o(f'#define JJ_PACE_STEPS {len(steps)}')
    o.arr('uint16_t', 'jj_pace_from', steps)
    o.arr('uint16_t', 'jj_pace_min', [mins[m] for m in steps])
    o.arr('uint16_t', 'jj_pace_max', [maxs[m] for m in steps])
    streaks = {}
    for s in lp.findall('Streak'):
        sset = {x.get('name'): float(x.get('value')) for x in s.findall('setting')}
        files = {x.get('type'): x.get('filename').lower() for x in s.findall('File')}
        streaks[s.get('name')] = (float(s.get('probability')), int(s.get('minIntervalCount')), int(s.get('maxIntervalCount')),
                                  int(sset['MIN_SPAWN_INTERVAL']), int(sset['MAX_SPAWN_INTERVAL']), files)
    defaults = {x.get('type'): x.get('filename').lower() for x in d.findall('File')}

    # ---------------------------------------------------------------- coins
    pat_names = []
    pat_index = {}

    def pattern(name):
        name = name.lower().replace('patterns/', '')
        if name not in pat_index:
            pat_index[name] = len(pat_names)
            pat_names.append(name)
        return pat_index[name]

    coin_files = []  # (sched, top, bottom, tophalf, bottomhalf, [(pattern, sched)])

    def coin_file(name):
        e = X(name)
        pats = [(pattern(c.get('filename')), add_sched(schedule(c))) for c in e.findall('coin_pattern')]
        coin_files.append((add_sched(schedule(e)), int(f(e, 'TopWeight')), int(f(e, 'BottomWeight')),
                           int(f(e, 'TopHalfWeight')), int(f(e, 'BottomHalfWeight')), pats))
        return len(coin_files) - 1

    zap_files = []

    def zap_file(name):
        e = X(name)
        pats = []
        for p in e.findall('obstacle_pattern'):
            ang = int(f(p, 'startAngle'))
            rot = int(f(p, 'rotateTime'))
            cw = (p.find('clockwise') is None) or p.find('clockwise').get('value') == 'true'
            pats.append((add_sched(schedule(p)), int(f(p, 'minScale')), int(f(p, 'maxScale')), ang, rot if cw else -rot,
                         int(f(p, 'scaleTime'))))
        zap_files.append((add_sched(schedule(e)), int(f(e, 'TopWeight')), int(f(e, 'BottomWeight')),
                          int(f(e, 'TopHalfWeight')), int(f(e, 'BottomHalfWeight')), pats))
        return len(zap_files) - 1

    mis_files = []

    def mis_file(name):
        e = X(name)
        mis_files.append((add_sched(schedule(e)), f(e, 'chaseSpeed'), f(e, 'missileSpeed')))
        return len(mis_files) - 1

    # the pacing sets: Default, then each streak (MISSILE, COIN, and one per vehicle)
    sets = []  # (name, prob, minc, maxc, imin, imax, coin, zap, mis, laser)

    def file_or(kind, files, fn):
        return fn(files[kind]) if kind in files else 255

    sets.append(('DEFAULT', 0, 0, 0, 0, 0, coin_file(defaults['COINS']), zap_file(defaults['GATES']),
                 mis_file(defaults['MISSILE']), 1))
    order = ['MISSILE_STREAK', 'COIN_STREAK', 'MECH_STREAK', 'HOG_STREAK', 'BIRD_STREAK', 'GRAVITY_STREAK', 'CFT_STREAK']
    for n in order:
        p, a, b, imin, imax, files = streaks[n]
        files = {k: ('streaks/' + v.split('/')[-1]) if v.startswith('streaks/') else v for k, v in files.items()}
        sets.append((n, p, a, b, imin, imax, file_or('COINS', files, coin_file), file_or('GATES', files, zap_file),
                     file_or('MISSILE', files, mis_file), 0))
    o(f'enum {{ {", ".join("JJ_SET_" + s[0].replace("_STREAK", "") for s in sets)} }};')
    o('typedef struct { uint16_t prob, imin, imax; uint8_t minc, maxc, coin, zap, mis; } jj_set_t;')
    o('static const jj_set_t jj_sets[] = {')
    for n, p, a, b, imin, imax, c, z, m, l in sets:
        o(f'  {{{w100(p)}, {imin}, {imax}, {a}, {b}, {c}, {z}, {m}}}, /* {n} */')
    o('};')

    # lasers
    lz = X('lazerpatterns.xml')
    laser_sched = add_sched(schedule(lz))
    lasers = []
    for p in lz.findall('lazer_pattern'):
        beams = []
        for l in p.findall('lazer'):
            pos = [(int(q.get('y')), int(q.get('transitionTime', 0)), int(q.get('holdTime', 0) or 0)) for q in l.findall('position')]
            assert 1 <= len(pos) <= 2
            beams.append((int(l.get('onInterval')), int(l.get('offInterval')), int(l.get('initialWaitDelay')), pos))
        lasers.append((p.get('name'), int(p.get('patternTime')), add_sched(schedule(p)), beams))
    assert max(len(b) for _, _, _, b in lasers) <= 7

    # spin tokens
    tk = X('slottokens.xml')
    g = tk.find('slotGaurantees')
    o(f'#define JJ_TOKEN_WEIGHT {w100(f(tk, "probability"))}')
    o(f'#define JJ_TOKEN_DRIFT {f(tk, "MAX_Y_MOVE_SPEED")}f')
    o(f'#define JJ_TOKEN_FIRST_MIN {int(g.get("SLOT_FIRST_SLOT_MIN"))}')
    o(f'#define JJ_TOKEN_FIRST_MAX {int(g.get("SLOT_FIRST_SLOT_MAX"))}')
    o(f'#define JJ_TOKEN_MAX_GAP {int(g.get("SLOT_MAX_DIST_WITHOUT_SLOT"))}')
    o(f'#define JJ_TOKEN_PER_KM {int(g.get("SLOT_MAX_SLOTS_PER_KILOMETER"))}')
    o(f'#define JJ_TOKEN_KM {int(g.get("SLOT_LENGTH_OF_KILOMETER"))}')

    # vehicles
    vp = X('vehicleprobability.xml')
    o(f'#define JJ_VEHICLE_RANGE {int(f(vp, "spawnRange"))}')
    o(f'#define JJ_VEHICLE_EXCLUSION {int(f(vp, "DestroyExclusionDistance"))}')
    o(f'#define JJ_VEHICLE_TOPHALF {int(f(vp, "TopHalfWeight"))}')
    vnames = [('mech', 'MECH'), ('hog', 'HOG'), ('profitbird', 'BIRD'), ('gravitysuit', 'GRAVITY'), ('teleporter', 'CFT')]
    o('typedef struct { float gravity, initial, boost, final_boost, friction, start, max, increase; uint8_t frames, jumps, weight, set; } jj_vehicle_t;')
    o('static const jj_vehicle_t jj_vehicles[] = {')
    for fn, set_name in vnames:
        e = X('vehicles/' + fn + '.xml')
        set_id = [s[0] for s in sets].index(set_name + '_STREAK')
        o(f'  {{{f(e, "GRAVITY")}f, {f(e, "INITIAL_BOOST")}f, {f(e, "BOOST")}f, {f(e, "FINAL_BOOST")}f, {f(e, "FRICTION")}f, '
          f'{f(e, "START_VELOCITY")}f, {f(e, "MAX_VELOCITY")}f, {f(e, "VELOCITY_INCREASE")}f, {int(f(e, "BOOST_FRAME_COUNT"))}, '
          f'{int(f(e, "JUMP_COUNT"))}, {int(f(e, "probability"))}, {set_id}}}, /* {fn} */')
    o('};')

    # final spin
    sl = X('slots.xml')
    kinds = ['COINS_100', 'COINS_500', 'COINS_1000', 'EXPLOSION1', 'EXPLOSION2', 'EXPLOSION3', 'REVIVE', 'TOKENS',
             'DOUBLE_COINS', 'START_500M']
    weight = {k: 0 for k in kinds}
    after = {k: 1000 for k in kinds}
    for s in sl.findall('slot'):
        k = s.find('type').get('value')
        if k not in weight:
            continue
        weight[k] += int(f(s, 'probability'))
        if s.find('afterWinProbPercent') is not None:
            after[k] = int(round(f(s, 'afterWinProbPercent') * 1000))
    o(f'enum {{ {", ".join("JJ_PRIZE_" + k for k in kinds)}, JJ_PRIZES }};')
    o.arr('uint16_t', 'jj_prize_weight', [weight[k] for k in kinds])
    o('/* after a win, the prize\'s weight times this / 1000 (afterWinProbPercent) */')
    o.arr('uint16_t', 'jj_prize_after', [after[k] for k in kinds])

    # ---------------------------------------------------------------- tables
    o('typedef struct { uint16_t sched; uint8_t top, bottom, tophalf, bottomhalf, first, count; } jj_file_t;')
    pats_flat = []
    o('static const jj_file_t jj_coin_files[] = {')
    for sc, t, b, th, bh, pats in coin_files:
        o(f'  {{{sc}, {t}, {b}, {th}, {bh}, {len(pats_flat)}, {len(pats)}}},')
        pats_flat += pats
    o('};')
    o('/* coin files\' patterns: (pattern, schedule) */')
    o.arr('uint8_t', 'jj_coin_pick', [p for p, _ in pats_flat])
    o.arr('uint16_t', 'jj_coin_pick_sched', [s for _, s in pats_flat])
    zflat = []
    o('static const jj_file_t jj_zap_files[] = {')
    for sc, t, b, th, bh, pats in zap_files:
        o(f'  {{{sc}, {t}, {b}, {th}, {bh}, {len(zflat)}, {len(pats)}}},')
        zflat += pats
    o('};')
    o('typedef struct { uint16_t sched, min, max; int16_t angle, rotate; uint8_t grow; } jj_zap_t;')
    o('static const jj_zap_t jj_zaps[] = {')
    for sc, mn, mx, ang, rot, grow in zflat:
        o(f'  {{{sc}, {mn}, {mx}, {ang}, {rot}, {grow}}},')
    o('};')
    o('typedef struct { uint16_t sched; float chase, speed; } jj_mis_t;')
    o('static const jj_mis_t jj_mis_files[] = {')
    for sc, ch, sp in mis_files:
        o(f'  {{{sc}, {ch}f, {sp}f}},')
    o('};')

    # coin patterns: rows of bits, LSB = leftmost
    bits, offs, dims = [], [], []
    for n in pat_names:
        rows = [r for r in open(os.path.join(A, 'patterns', n), encoding='latin1').read().replace('\r', '').split('\n')]
        while rows and not rows[-1].strip():
            rows.pop()
        w = max(len(r) for r in rows)
        offs.append(len(bits))
        dims.append((w, len(rows)))
        for r in rows:
            v = 0
            for i, c in enumerate(r):
                if c == '1':
                    v |= 1 << i
            nb = (w + 7) // 8
            bits += [(v >> (8 * k)) & 255 for k in range(nb)]
    o(f'#define JJ_PATTERNS {len(pat_names)}')
    o('/* coin patterns (patterns, one .txt each): width, height, then rows of bits, the first coin in bit 0 */')
    o.arr('uint8_t', 'jj_pat_w', [w for w, _ in dims], 32)
    o.arr('uint8_t', 'jj_pat_h', [h for _, h in dims], 32)
    o.arr('uint16_t', 'jj_pat_off', offs)
    o.arr('uint8_t', 'jj_pat_bits', bits, 24)

    o(f'#define JJ_LASER_SCHED {laser_sched}')
    o(f'#define JJ_LASER_PATTERNS {len(lasers)}')
    o('typedef struct { uint16_t time, sched; uint8_t first, count; } jj_lpat_t;')
    o('typedef struct { int8_t y0, y1; uint16_t on, off, wait, move; } jj_beam_t;')
    o('static const jj_lpat_t jj_lpats[] = {')
    beams = []
    for name, t, sc, bs in lasers:
        o(f'  {{{t}, {sc}, {len(beams)}, {len(bs)}}}, /* {name} */')
        for on, off, wait, pos in bs:
            y0 = pos[0][0]
            y1, move = (pos[1][0], pos[1][1]) if len(pos) > 1 else (y0, 0)
            beams.append((y0, y1, on, off, wait, move))
    o('};')
    o('static const jj_beam_t jj_beams[] = {')
    for b in beams:
        o('  {%d, %d, %d, %d, %d, %d},' % b)
    o('};')

    o('/* weights by distance: (from metres, weight) pairs, each list ended by 0xffff */')
    o.arr('uint16_t', 'jj_sched', [v for p in sched for v in p], 16)
    o('#endif')
    open(dst, 'w').write('\n'.join(o.lines) + '\n')
    print(f'{dst}: {len(pat_names)} coin patterns, {len(zflat)} zappers in {len(zap_files)} files, '
          f'{len(lasers)} laser patterns, {len(beams)} beams, {len(sets)} pacing sets')


if __name__ == '__main__':
    main()