#include <stdint.h>

enum { WIDTH = 320, HEIGHT = 240, STRIDE = 512 };
#define VIDEO ((volatile uint32_t *)(uintptr_t)0xff203020u)

static volatile uint16_t *pixels;

static void put(int x, int y, uint16_t rgb)
{
    pixels[y * STRIDE + x] = rgb;
}

static void clear_frame(void)
{
    for (int y = 0; y < HEIGHT; ++y)
        for (int x = 0; x < WIDTH; ++x)
            put(x, y, 0);
}

static int magnitude(int value)
{
    return value < 0 ? -value : value;
}

static void line(int x, int y, int end_x, int end_y, uint16_t rgb)
{
    int dx = magnitude(end_x - x);
    int dy = -magnitude(end_y - y);
    int sx = x < end_x ? 1 : -1;
    int sy = y < end_y ? 1 : -1;
    int error = dx + dy;
    for (;;) {
        put(x, y, rgb);
        if (x == end_x && y == end_y) return;
        int twice = 2 * error;
        if (twice >= dy) {
            error += dy;
            x += sx;
        }
        if (twice <= dx) {
            error += dx;
            y += sy;
        }
    }
}

static void vertical_blank(void)
{
    VIDEO[0] = 1u;
    while ((VIDEO[3] & 1u) != 0u) { }
}

enum { BOX = 5, CAPACITY = 6 };
typedef struct { int x, y, dx, dy; uint16_t rgb; } Particle;
static Particle dots[CAPACITY] = {
    {2, 1, -1, -1, 0xf800}, {110, 75, 1, -1, 0x07e0},
    {190, 160, -1, 1, 0x001f}, {305, 229, 1, 1, 0xffe0},
    {77, 148, 1, -1, 0xf81f}, {145, 21, -1, 1, 0x07ff}
};
static uint16_t frames[2][HEIGHT][STRIDE] __attribute__((aligned(1024)));

static void draw_scene(unsigned count, int links)
{
    if (links) {
        for (unsigned i = 1; i < count; ++i)
            line(dots[i-1].x + BOX/2, dots[i-1].y + BOX/2,
                 dots[i].x + BOX/2, dots[i].y + BOX/2, 0xffff);
    }
    for (unsigned i = 0; i < count; ++i)
        for (int y = 0; y < BOX; ++y)
            for (int x = 0; x < BOX; ++x)
                put(dots[i].x + x, dots[i].y + y, dots[i].rgb);
}

static void advance(int *place, int *motion, int limit)
{
    if ((*place == 0 && *motion < 0) || (*place == limit && *motion > 0))
        *motion = -*motion;
    *place += *motion;
}

static void move(unsigned count, unsigned steps)
{
    while (steps-- > 0) {
        for (unsigned i = 0; i < count; ++i) {
            advance(&dots[i].x, &dots[i].dx, WIDTH - BOX);
            advance(&dots[i].y, &dots[i].dy, HEIGHT - BOX);
        }
    }
}

/* Draw into the memory that the controller is not currently displaying. */
static void present(unsigned next, unsigned count, int links)
{
    pixels = &frames[next][0][0];
    clear_frame();
    draw_scene(count, links);
    VIDEO[1] = (uint32_t)(uintptr_t)pixels;
    vertical_blank();
}

int main(void)
{
    unsigned next = 0;
    for (;;) {
        present(next, 4, 1);
        next ^= 0u; /* TODO: alternate the drawing buffers. */
        move(4, 1);
    }
}
