

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <filesys.h>
#include <sys/process.h>


#include "ivram.h"


#define IV_PALETTE_A   15
#define IV_PALETTE_NA  8


void iv_adjust_sp();


/* テスト用・・これは遅いよ */
void ivs_add_sprite_fill(int charno, int x, int y, int w, int h)
{
    int sx, sy;
    int ex, ey;
    ex = x + w;
    ey = y + h;
    for (sx = x; sx < ex; sx++) {
        for (sy = y; sy < ey; sy++) {
            ivs_add_sprite(charno, sx, sy);
        }
    }
}


/* 'IV' からキャラクタを作る */
void ivs_make_chartable(BYTE* info_buf, iv_res_image_t far *ivres)
{
    memcpy(info_buf, iv_res_pcharinfo(ivres), iv_res_charmax(ivres));
}


/* 'BM' 3color から直接キャラクタを作る */
void ivs_make_chartable_bc3(BYTE* info_buf, BYTE* char_buf, WORD far* bc3_buf, int max)
{
    int i, j;
    WORD w, mask, allmask1, allmask2;
    BYTE info;
    WORD* pcb;

    pcb = (WORD*)char_buf;
    for (i = 0; i < max; i++) {
        allmask1 = 0;
        allmask2 = 0xFFFF;
        for (j = 0; j < IV_CH; j++) {
            w = *bc3_buf++;
            mask = ((w >> 8) | w) & 0xFF;
            mask |= (mask << 8);
            allmask1 |= mask;
            allmask2 &= mask;
            *pcb++ = ~mask;
            *pcb++ = w;
        }
        info = 0;
        if (allmask1 == 0) {
            info = IV_CHARINFO_NORENDER;
        } else if (allmask2 == 0xFFFF) {
            info = IV_CHARINFO_OPAQUE;
        }
        *info_buf++ = info;
    }
}




res_t far *iv_get_resource(void far* mapped, WORD type, short id)
{
    res_t far *res;

    if (mapped == NULL) {
        mapped = _pc->_resource;
    }

    res = (res_t far*)MK_FP(FP_SEG(mapped) + (FP_OFF(mapped) >> 4), 0);
    while (res->magic == RESID) {
        if ((res->type == type) && (res->id == id)) {
            return res;
        }
        
        res = (res_t far*)MK_FP(FP_SEG(res) + res->size, 0);
    }

    return NULL;
}




void iv_init(unsigned palette_mode)
{
    int i, x, y;
    int work;
    int palno;

    /* iv_adjust_sp(); */

    display_control(DCM_SCR2);

    lcd_set_color(0x6420, 0xFCB9);
/*
    palno = (palette_mode == IV_PALETTE_AWGB) ?
        IV_PALETTE_A : IV_PALETTE_NA;
*/
    palno = IV_PALETTE_NA;
    palette_set_color(palno, palette_mode);

    i = 0;
    for (y = 0; y < IV_CY; y++) {
        for (x = 0; x < IV_CX; x++) {
            work = ((palno << CFSFT_PALETTE) | i);
            screen_set_char(SCREEN2, x, y, 1, 1, &work);
            i++;
        }
    }

}


void iv_panic(int n)
{
    char s[16];
    text_screen_init();
    sprintf(s, "PANIC:%d", n);
    text_put_string(0, 0, s);
    key_wait();

    bios_exit();
}



