// SPDX-License-Identifier: CC0-1.0
//
// SPDX-FileContributor: Antonio Niño Díaz, 2024-2026

#include <nds.h>

// This is autogenerated from forest_town.png and forest_town.grit
#include "forest_town.h"

int main(int argc, char *argv[])
{
    videoSetMode(MODE_5_2D);

    vramSetPrimaryBanks(VRAM_A_MAIN_BG, VRAM_B_LCD, VRAM_C_LCD, VRAM_D_LCD);

    int bg = bgInitHidden(2, BgType_ExRotation, BgSize_ER_256x256, 0, 1);

    memcpy(bgGetGfxPtr(bg), forest_townTiles, forest_townTilesLen);
    memcpy(bgGetMapPtr(bg), forest_townMap, forest_townMapLen);
    memcpy(BG_PALETTE, forest_townPal, forest_townPalLen);

    bgShow(bg);

    consoleDemoInit();

    printf("ABXY:  Move rotation center\n");
    printf("PAD:   Scroll background\n");
    printf("L/R:   Rotate\n");
    printf("SELECT/START: Scale\n");

    int x = 50, y = 70;
    int cx = 0, cy = 0;

    int angle = 256;
    int scale = 1 << 8;

    while (1)
    {
        swiWaitForVBlank();

        // Update registers during the vertical blanking period to prevent
        // screen tearing.
        bgUpdate();

        scanKeys();

        u16 keys_held = keysHeld();

        if (keys_held & KEY_UP)
            y++;
        else if (keys_held & KEY_DOWN)
            y--;
        if (keys_held & KEY_LEFT)
            x++;
        else if (keys_held & KEY_RIGHT)
            x--;

        if (keys_held & KEY_L)
            angle -= 1 << 4;
        else if (keys_held & KEY_R)
            angle += 1 << 4;

        if (keys_held & KEY_SELECT)
            scale += 1 << 3;
        else if (keys_held & KEY_START)
            scale -= 1 << 3;

        if (keys_held & KEY_X)
            cy--;
        else if (keys_held & KEY_B)
            cy++;
        if (keys_held & KEY_Y)
            cx--;
        else if (keys_held & KEY_A)
            cx++;

        bgSetCenter(bg, cx, cy);
        bgSetRotateScale(bg, angle, scale, scale);
        bgSetScroll(bg, x, y);
    }

    return 0;
}
