/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Stereo Flyby. Link orch90, input and bcontrol, in that order. */
#include <cmoc.h>
#include <coco.h>
#include <vcc/input.h>
#include <vcc/orch90.h>

#define FRAMES 2048
#define FIRST_COLUMN 2
#define LAST_COLUMN 29
#define STAR_ROW 8
#define SHIP_ROW 10

/* Keep the sample in guest RAM for as long as the interrupt can read it. */
static struct orch90_frame beacon[FRAMES];

static void makeBeacon(void)
{
    static const byte wave[] = {
        128, 146, 162, 172, 176, 172, 162, 146,
        128, 110,  94,  84,  80,  84,  94, 110
    };
    unsigned i;
    for (i = 0; i < FRAMES; ++i) {
        /* The first note comes from the left. The right note is an octave up.
           128 in both channels is the quiet space between notes. */
        beacon[i].left = i < 768 ? wave[i & 15] : 128;
        beacon[i].right = i >= 1024 && i < 1792 ? wave[(i << 1) & 15] : 128;
    }
}

static void mark(byte column, byte row, char symbol)
{
    locate(column, row);
    putchar(symbol);
}

int main(void)
{
    VccInput stick;
    unsigned lastUpdate, now;
    byte ship = 15, star = LAST_COLUMN, key;

    width(32);
    cls(1);
    makeBeacon();
    input_init(&stick, INPUT_RIGHT);
    printf("STEREO FLYBY\n\n1  TRANSMIT BEACON\nRIGHT STICK  STEER     Q  QUIT\n");
    locate(1, 7);  printf("+----------------------------+");
    locate(1, 12); printf("+----------------------------+");
    mark(ship, SHIP_ROW, '^');
    mark(star, STAR_ROW, '*');
    lastUpdate = getTimer();
    for (;;) {
        key = inkey();
        if (key == 'Q' || key == 'q')
            break;
        if (key == '1' && !orch90_active()) {
            locate(0, 5);
            if (orch90_start(beacon, FRAMES, 1, ORCH90_CLOCK_NORMAL))
                printf("BEACON ON AIR");
            else
                printf("PLAYBACK UNAVAILABLE");
        }
        /* The guest clock drives the flight display. Audio advances between
           updates, even when this loop is busy drawing or reading input. */
        now = getTimer();
        if ((unsigned)(now - lastUpdate) < 4)
            continue;
        lastUpdate = now;
        input_sample(&stick);
        mark(ship, SHIP_ROW, ' ');
        if (stick.dx < 0 && ship > FIRST_COLUMN) --ship;
        if (stick.dx > 0 && ship < LAST_COLUMN) ++ship;
        mark(ship, SHIP_ROW, '^');
        mark(star, STAR_ROW, ' ');
        star = star == FIRST_COLUMN ? LAST_COLUMN : star - 1;
        mark(star, STAR_ROW, '*');
    }
    orch90_stop();
    locate(0, 14);
    printf("FLYBY COMPLETE\n");
    return 0;
}
