#include "main.h"

#include "graphics/intro_planet.pal.c"
#include "graphics/intro_planet.raw.c"

/**
 * Fade a palette to black
 * @param in input palette
 * @param out output palette
 * @param len number of entries in palette
 * @param amount amount to fade: 256 = no change, 0 = fully black
 */
void palette_fade_to_black(u16* in, u16* out, int len, int amount)
{
	int i;
	if(amount > 256 || amount < 0) return;

	for(i=0; i<len; i++)
	{
		u32 r, g, b;
		u16 cur;
		
		cur = in[i];
		r = cur & 0x1f;
		g = (cur >> 5) & 0x1f;
		b = (cur >> 10) & 0x1f;

		r = (r * amount) >> 8;
		g = (g * amount) >> 8;
		b = (b * amount) >> 8;

		cur = r | (g << 5) | (b << 10);
		out[i] = cur;
	}
}

void intro()
{
	Bg planetbg;
	u32 loop;
	u16* temp;
	u32 x, y;
	int start=0;

	InitialiseSprites();

	/* set to mode 0 */
	SetMode(MODE_0 | BG0_ENABLE | OBJ_ENABLE | OBJ_MAP_1D);
	
	planetbg.number = 0;
	planetbg.charBaseBlock = 0;
	planetbg.screenBaseBlock = 28;		//map data position on 2Kb boundary
	planetbg.colorMode = BG_COLOR_256;           //256-colour background
	planetbg.size = TEXTBG_SIZE_256x256;
	planetbg.mosaic = 0;                         //not enabled
	planetbg.x_scroll = 0;			//scrolling variables
	planetbg.y_scroll = 0;

	EnableBackground(&planetbg);

	/* load tile and palette data */

	temp = (u16*)intro_planet_Bitmap;
	for(loop=0; loop < 32 * (30 * 4); loop++)
		planetbg.tileData[loop] = temp[loop];
	
	/* generate map data */
	/* the planet map tiles consist of 60 (two lines of 30) tiles of random
	 * stars, followed by 60 tiles of planet image. */
	for(y=0; y < 30; y++)
	{
		for(x=0; x < 30; x++)
		{
			int f = (rand() / (RAND_MAX / 60));
			planetbg.mapData[(32 * y) + x] = f;
		}
	}
	for(y=30; y < 32; y++)
	{
		for(x=0; x < 30; x ++)
		{
			planetbg.mapData[(32 * y) + x] = 60 + (30 * (y - 30)) + x;
		}
	}
	
	for(loop=0; loop < 256; loop++)
		BGPaletteMem[loop] = intro_planet_Palette[loop];

	/* scroll map from starry screen at top to reveal planet at bottom */
	for(y=0; y < (256 - 160); y++)
	{
		u32 keys = *KEYS;
		if(!(keys & KEY_A)) y = (256 - 160);

		planetbg.y_scroll = y;
		UpdateBackground(&planetbg);
		gba_vsync();
		gba_vsync();
	}
	
	while(!start)
	{
		u32 keys = *KEYS;
		if(!(keys & KEY_START))
		{
			start = 1;
		}
		gba_vsync();
	}
	
	/* do a nice mosaic effect to fade out */
	REG_BG0CNT |= BG_MOSAIC_ENABLE;

	for(x=0; x < 16; x++)
	{
		REG_MOSAIC = x * 0x1111;
	
		for(y=0; y<16; y+=4)
		{
			palette_fade_to_black(intro_planet_Palette, BGPaletteMem, 256, 256 - ((x * 16) + y));
			gba_vsync();
		}
	}

	REG_MOSAIC = 0;
	memset(planetbg.mapData, 0, 32 * 32 * 2);
}
