/*
    Ninja Sample

    COPYRIGHT (C) SEGA ENTERSRISES,LTD.

    VMS LCD Sample for SET5

    1998.7.28
*/

#include <shinobi.h>
#include <sg_lcd.h>

extern const Uint8 cgdata[];

void njUserInit(void)
{
    njSetBorderColor( 0x00000000 ) ;
    sbInitSystem(NJD_RESOLUTION_640x480_NTSCNI, NJD_FRAMEBUFFER_MODE_RGB565, 1);
    njInitVertexBuffer(100000, 0, 200000, 0, 0);
    njInitPrint(NULL, 0, 0);
    njSetBackColor(0x00000000, 0x00000000, 0x0000a0a0);
}


Uint32 count = 0;

void DrawLcdImageToScreen(Sint32 x, Sint32 y, const Uint8* data)
{
    Sint32 i, j;

    for (i = 0; i < 32; i++) {
        for (j = 0; j < 48; j++, data++) {
            if (*data & 0x08) {
                njPrintC(NJM_LOCATION(x + j, y + i), "O");
            } else {
                njPrintC(NJM_LOCATION(x + j, y + i), " ");
            }
        }
    }
}

void DrawLcd(void)
{
    const NJS_PERIPHERAL* per;
    static Sint32 ofs = 0;
    Sint32 ret;
    Uint32 dir, flag;


    per = njGetPeripheral(NJD_PORT_A0);

    if (per->on & NJD_DGT_KU) ofs -= 48;
    if (per->on & NJD_DGT_KD) ofs += 48;

    if (ofs < 0) ofs = 0;
    if (ofs > 48 * (256 - 32)) ofs = 48 * (256 - 32);

    dir = pdLcdGetDirection(PDD_PORT_A1);

    switch (dir) {
        case PDD_LCD_DIRECTION_NORMAL:
            njPrintC(NJM_LOCATION(34, 46), "DIRECTION:NORMAL");
            flag = PDD_LCD_FLAG_NOFLIP;
            break;
        case PDD_LCD_DIRECTION_FLIP:
            njPrintC(NJM_LOCATION(34, 46), "DIRECTION:FLIP");
            flag = PDD_LCD_FLAG_HVFLIP;
            break;
        case PDD_LCD_DIRECTION_LEFT:
            njPrintC(NJM_LOCATION(34, 46), "DIRECTION:LEFT");
            flag = PDD_LCD_FLAG_NOFLIP;
            break;
        case PDD_LCD_DIRECTION_RIGHT:
            njPrintC(NJM_LOCATION(34, 46), "DIRECTION:RIGHT");
            flag = PDD_LCD_FLAG_NOFLIP;
            break;
    }
    ret = pdVmsLcdWrite(PDD_PORT_A1, &cgdata[ofs], flag);

    if (ret == PDD_LCDERR_OK) {
        DrawLcdImageToScreen(16, 5, &cgdata[ofs]);
    } else {
        njPrintC(NJM_LOCATION(30, 22), "LCD ERROR");
    }
}

Sint32 njUserMain(void)
{
    const PDS_PERIPHERALINFO* info;
    const NJS_PERIPHERAL* per;

    njPrintC(NJM_LOCATION(30, 0), "VMS LCD SAMPLE #1");

    per = njGetPeripheral(NJD_PORT_A0);

    if (!pdVmsLcdIsReady(PDD_PORT_A1)) {
        if (count & 0x00000010) {
            njPrintC(NJM_LOCATION(20, 50),
                "PLEASE CONNECT A VMS TO PORT A-1.");
        }
    } else {
        njPrintC(NJM_LOCATION(20, 50),
                "PRESS UP-DOWN KEY TO MOVE LCD GRAPHIC.");

        DrawLcd();
    }

    count++;
    return NJD_USER_CONTINUE;
}

void njUserExit(void)
{
    njExitPrint();
    sbExitSystem();
}

