/*
 * File: assets_graphics.h
 * Art import, terrain variants, runtime graphics and title generation.
 * Implementation include; compiled only through assets.c.
 */

#ifndef ASSETS_GRAPHICS_H
#define ASSETS_GRAPHICS_H

static void load_art(void)
{
    Node *art = read_json("assets/tiles.json"), *tiles = member(art, "tiles");
    Node *raster = member(art, "raster"), *sprites = member(art, "sprites");
    int i, y, x, band, t;
    for (i = 0; i < 4; ++i) {
        rgb(element(member(art, "palette"), i, 4), palette[i]);
        atari[i] = byte(element(member(art, "atari_palette"), i, 4));
        orange[i] = byte(element(member(raster, "orange_atari"), i, 4));
        blue[i] = byte(element(member(raster, "blue_atari"), i, 4));
    }
    for (band = 0; band < 4; ++band) {
        memcpy(raster_rgb[band], palette, sizeof(palette));
        rgb(element(member(raster, "orange_rgb"), band, 4), raster_rgb[band][2]);
        rgb(element(member(raster, "blue_rgb"), band, 4), raster_rgb[band][3]);
    }
    if (atari[2] != orange[0] || atari[3] != blue[0]) fail("base palette must match first raster band");
    for (i = 0; i < 16; ++i) {
        uint8_t check[3];
        title_colors[i] = byte(element(member(raster, "title_atari"), i, 16));
        rgb(element(member(raster, "title_rgb"), i, 16), check);
    }
    rgb(member(sprites, "light_rgb"), light_rgb);
    {
        uint8_t check[3];
        rgb(member(sprites, "cursor_rgb"), check);
    }
    light_color = byte(member(sprites, "light_atari"));
    cursor_color = byte(member(sprites, "cursor_atari"));
    for (i = 0; i < ART; ++i) {
        Node *tile = element(tiles, i, ART), *rows = member(tile, "pixels"), *row;
        int count = 0;
        const char *name = string(member(tile, "name"));
        if (!*name || strspn(name, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") != strlen(name))
            fail("tile names require ASCII letters, digits, '_' or '-'");
        if (rows->type != '[') fail("tile pixels must be an array");
        for (row = rows->child; row; row = row->next) ++count;
        if (count != 8 && count != 16) fail("tile pixels need 8 or 16 rows");
        for (y = 0; y < 16; ++y) {
            const char *s = string(element(rows, y / (16 / count), count));
            if (strlen(s) != 8 || strspn(s, "0123") != 8) fail("tile rows need eight pixels 0..3");
            for (x = 0; x < 8; ++x) pixels[i][y][x] = (uint8_t)(s[x] - '0');
        }
    }
    for (i = 0; i < ART; ++i) {
        int team, kind = art_kind(i, &team);
        for (y = 0; y < 16; ++y)
            for (x = 0; x < 8; ++x)
                opacity[i][y][x] = (uint8_t)(kind < 0 || pixels[i][y][x]
                    || (x && pixels[i][y][x-1]) || (x < 7 && pixels[i][y][x+1])
                    || (y && pixels[i][y-1][x]) || (y < 15 && pixels[i][y+1][x]));
    }
    for (i = 0; i < 6; ++i)
        for (y = 0; y < 16; ++y) {
            const char *s = string(element(element(member(sprites, "unit_highlights"), i, 6), y, 16));
            if (strlen(s) != 8 || strspn(s, "01") != 8) fail("highlight rows need eight bits");
            for (x = 0; x < 8; ++x)
                if (s[x] == '1') {
                    if (y < 2 || y > 13) fail("highlights need two blank rows at each end");
                    for (t = 0; t < 2; ++t)
                        if (!opacity[unit_art[t][i]][y][x]) fail("highlight outside unit silhouette");
                    lights[i][y] |= (uint8_t)(128 >> x);
                }
        }
    /* Names are needed only while writing the editable tileset. */
    {
        FILE *f = output("assets/tiles.tsx", "w");
        fputs("<?xml version='1.0' encoding='UTF-8'?>\n"
              "<tileset version=\"1.10\" tiledversion=\"1.11.0\" name=\"AtariWars\" "
              "tilewidth=\"16\" tileheight=\"16\" tilecount=\"23\" columns=\"8\">"
              "<image source=\"tiles.png\" width=\"128\" height=\"48\" />", f);
        for (i = 0; i < ART; ++i)
            fprintf(f, "<tile id=\"%d\" type=\"%s\" />", i, string(member(element(tiles, i, ART), "name")));
        fputs("</tileset>", f);
        close_file(f);
    }
    free_nodes();
}

static void terrain_graphics(Level *level)
{
    int connections, y, x, pos;
    memcpy(graphics, pixels, 16 * sizeof(Tile));
    for (connections = 0; connections < 16; ++connections) {
        uint8_t surface[16][8] = {{0}};
        Tile *road = &graphics[16 + connections], *water = &graphics[32 + connections];
        memcpy(*road, pixels[0], sizeof(Tile));
        memcpy(*water, pixels[2], sizeof(Tile));
        for (y = 0; y < 16; ++y)
            for (x = 0; x < 8; ++x)
                surface[y][x] = (uint8_t)((y >= 4 && y < 12 && x >= 2 && x < 6)
                    || ((connections & 1) && y < 8 && x >= 2 && x < 6)
                    || ((connections & 2) && y >= 4 && y < 12 && x >= 4)
                    || ((connections & 4) && y >= 8 && x >= 2 && x < 6)
                    || ((connections & 8) && y >= 4 && y < 12 && x < 4));
        for (y = 0; y < 16; ++y)
            for (x = 0; x < 8; ++x) {
                if (surface[y][x]) (*road)[y][x] = 0;
                else if ((x && surface[y][x-1]) || (x < 7 && surface[y][x+1])
                         || (y && surface[y-1][x]) || (y < 15 && surface[y+1][x]))
                    (*road)[y][x] = 2;
                if (((connections & 1) && y == 0) || ((connections & 2) && x == 7)
                    || ((connections & 4) && y == 15) || ((connections & 8) && x == 0))
                    (*water)[y][x] = 1;
                else if (((connections & 1) && y == 1) || ((connections & 2) && x == 6)
                         || ((connections & 4) && y == 14) || ((connections & 8) && x == 1))
                    (*water)[y][x] = (uint8_t)((x + y) % 3 ? 3 : 0);
            }
        if (connections & 1) (*road)[1][3] = (*road)[2][3] = 2;
        if (connections & 4) (*road)[13][3] = (*road)[14][3] = 2;
        if (connections & 8) (*road)[7][0] = 2;
        if (connections & 2) (*road)[7][7] = 2;
    }
    memcpy(graphics + 48, pixels + 16, 7 * sizeof(Tile));
    for (pos = 0; pos < CELLS; ++pos) {
        int tile = level->terrain[pos], road = 0, banks = 0, d;
        int neighbors[4] = {pos >= 16 ? level->terrain[pos-16] : -1,
            pos % 16 < 15 ? level->terrain[pos+1] : -1,
            pos < 144 ? level->terrain[pos+16] : -1,
            pos % 16 ? level->terrain[pos-1] : -1};
        for (d = 0; d < 4; ++d) {
            int n = neighbors[d];
            if (n == 1 || n == 3 || (n >= 6 && n <= 10)) road |= 1 << d;
            if (n != -1 && n != 2 && n != 3) banks |= 1 << d;
        }
        level->display[pos] = (uint8_t)(tile == 1 ? 16 + road : tile == 2 ? 32 + banks : tile == 10 ? 54 : tile);
    }
}

static uint8_t packed_row(const uint8_t *row)
{
    int i;
    uint8_t value = 0;
    for (i = 0; i < 4; ++i) value = gfx_pack_2bit(value, row[i]);
    return value;
}

static void write_graphics(void)
{
    uint8_t packed[TILES * 32], masks[TILES * 32], water[96];
    int i, y, x, used = 0, phase;
    FILE *f;
    terrain_graphics(&test_level);
    for (i = 0; i < TILES; ++i) {
        int art = i >= 48 ? i - 32 : i, team, kind = art_kind(art, &team);
        for (y = 0; y < 16; ++y) {
            uint8_t row[8];
            for (x = 0; x < 8; ++x)
                row[x] = (uint8_t)(((i >= 48 || (i >= 10 && i < 16)) && kind >= 0
                    ? opacity[art][y][x] : graphics[i][y][x] != 0) ? 3 : 0);
            for (x = 0; x < 2; ++x) {
                packed[i * 32 + y * 2 + x] = packed_row(graphics[i][y] + x * 4);
                masks[i * 32 + y * 2 + x] = packed_row(row + x * 4);
            }
        }
    }
    write_bytes("generated/tiles.bin", packed, sizeof(packed));
    write_bytes("generated/masks.bin", masks, sizeof(masks));
    for (phase = 0; phase < 4; ++phase)
        for (y = 2; y < 14; ++y) {
            uint8_t row[8];
            for (x = 0; x < 8; ++x) row[x] = pixels[2][y][(x - phase * 2 + 8) % 8];
            water[used++] = (uint8_t)(row[2] * 4 + row[3]);
            water[used++] = (uint8_t)(row[4] * 64 + row[5] * 16);
        }
    write_bytes("generated/water-frames.bin", water, sizeof(water));
    write_bytes("generated/lights.bin", lights, sizeof(lights));
    write_bytes("generated/title-colors.bin", title_colors, sizeof(title_colors));
    f = output("generated/raster.i", "w");
    fprintf(f, "MAP_BACKGROUND = %u\nMAP_GREEN = %u\nMAP_ORANGE = %u\nMAP_BLUE = %u\n"
            "SPRITE_LIGHT = %u\nSPRITE_CURSOR = %u\n", atari[0], atari[1], atari[2], atari[3],
            light_color, cursor_color);
    fputc('\n', f);
    for (i = 0; i < 2; ++i) {
        uint8_t bands[40], *colors = i ? blue : orange;
        const char *label = i ? "rasterBlue" : "rasterOrange";
        fprintf(f, "%sBands\n", label); byte_table(f, colors, 4);
        for (x = 0; x < 40; ++x) bands[x] = colors[x % 4];
        fprintf(f, "%s\n", label); byte_table(f, bands, 40);
    }
    close_file(f);
    f = output("generated/display.i", "w");
    fputs("\t.byte\t$70,$f0\n", f);
    for (y = 0; y < 160; ++y)
        fprintf(f, "\t.byte\t%s\n\t.word\tframeBuffer+%d*40\n\n", y % 4 == 3 && y < 159 ? "$ce" : "$4e", y);
    fputs("\t.byte\t$b0,$42\n\nhudDisplay .word\tPM_RAM\n\t.byte\t2,2,2,2,$41\n\t.word\tdisplayList\n\n", f);
    close_file(f);
    f = output("generated/map.i", "w");
    fprintf(f, "UNIT_COUNT = %d\nTILE_COUNT = %d\n\nterrain\n", test_level.count, TILES);
    byte_table(f, test_level.terrain, CELLS);
    fputs("terrainDisplay\n", f); byte_table(f, test_level.display, CELLS);
    {
        const char *const labels[] = {"initialX","initialY","initialKind","initialTeam"};
        for (i = 0; i < 4; ++i) {
            fprintf(f, "%s\n", labels[i]); byte_table(f, test_level.units[i], 16);
        }
    }
    close_file(f);
}

static void write_title(void)
{
    static const char *const letters[] = {
        "A01110110111101111111110111101111011", "T11111111110010000100001000010000100",
        "R11110110111101111110111001101011011", "I11111001000010000100001000010011111",
        "W11011110111101111011111111111101010", "S01111110001100001110000110001111110"
    };
    static const char *const credit_font[] = {
        "W101101111111101","R110101110101101","I111010010010111","T111010010010010",
        "E111100110100111","N101111111111101","/001001010100100","D110101101101110",
        "S111100111001111","G111100101101111","B110101110101110","Y101101010010010",
        "O111101101101111","L100100100100111","M101111111101101"
    };
    const char *words[2] = {"ATARI", "WARS"}, *credit = "WRITTEN/DESIGNED BY GOLDMOMO";
    uint8_t image[160][160] = {{0}}, packed[6400], runs[12801], credit_pixels[5][112] = {{0}}, credit_bytes[140];
    int word, letter, y, x, dy, dx, used = 0, offset = 0, i;
    for (word = 0; word < 2; ++word) {
        int left = (160 - ((int)strlen(words[word]) * 6 - 1) * 3) / 2;
        for (letter = 0; words[word][letter]; ++letter) {
            const char *font = NULL;
            for (i = 0; i < 6; ++i) if (letters[i][0] == words[word][letter]) font = letters[i] + 1;
            if (!font || strlen(font) != 35) fail("invalid title font");
            for (y = 0; y < 7; ++y)
                for (x = 0; x < 5; ++x)
                    if (font[y * 5 + x] == '1')
                        for (dy = 0; dy < 3; ++dy)
                            for (dx = 0; dx < 3; ++dx)
                                image[(word ? 40 : 12) + y * 3 + dy][left + letter * 18 + x * 3 + dx] = (uint8_t)(word + 2);
        }
    }
    for (y = 112; y < 160; ++y) memset(image[y], 1, 160);
    for (y = 136; y < 144; ++y) memset(image[y], 0, 160);
    for (i = 0; i < 2; ++i) {
        int left = i ? 104 : 24, color = i + 2;
        static const int waves[] = {0,0,1,1,0,0,-1,-1};
        for (y = 78; y < 123; ++y) { image[y][left-3] = 2; image[y][left-2] = 3; }
        for (y = 123; y < 125; ++y) memset(image[y] + left - 7, 0, 11);
        for (x = 0; x < 32; ++x)
            for (y = 0; y < 24; ++y) {
                int p = color;
                if (!x || x == 31 || !y || y == 23) p = 0;
                else if (color == 2 && abs(x - 16) + abs(y - 11) <= 6) p = 0;
                else if (color == 3 && x >= 8 && x <= 24 && ((y >= 6 && y <= 8) || (y >= 15 && y <= 17))) p = 2;
                image[82 + y + waves[x / 4]][left+x] = (uint8_t)p;
            }
    }
    for (y = 0; y < 160; ++y)
        for (x = 0; x < 160; x += 4) packed[used++] = packed_row(image[y] + x);
    used = 0;
    while (offset < 6400) {
        int count = 1;
        while (count < 255 && offset + count < 6400 && packed[offset + count] == packed[offset]) ++count;
        runs[used++] = (uint8_t)count; runs[used++] = packed[offset]; offset += count;
    }
    runs[used++] = 0;
    write_bytes("generated/title-rle.bin", runs, (size_t)used);
    for (letter = 0; credit[letter]; ++letter) {
        const char *font = NULL;
        if (credit[letter] == ' ') continue;
        for (i = 0; i < 15; ++i) if (credit_font[i][0] == credit[letter]) font = credit_font[i] + 1;
        if (!font || strlen(font) != 15) fail("invalid credit font");
        for (y = 0; y < 5; ++y)
            for (x = 0; x < 3; ++x)
                if (font[y * 3 + x] == '1') credit_pixels[y][letter * 4 + x] = 2;
    }
    used = 0;
    for (y = 0; y < 5; ++y)
        for (x = 0; x < 112; x += 4) credit_bytes[used++] = packed_row(credit_pixels[y] + x);
    write_bytes("generated/title-credit.bin", credit_bytes, sizeof(credit_bytes));
}

#endif
