/*
 * sdl_image.c - Q3Base SDL reimplementation of the 'R_LoadImage'
 *               routine
 *
 * Copyright (C) 2005  Ed Schouten <ed@fxq.nl>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "SDL_image.h"
#include "SDL_endian.h"

#include "../renderer/tr_local.h"

#define OUT_BPP	4

/*
 * R_LoadImage: Load and decompress image files
 */
void R_LoadImage (const char *name, byte **pic, int *width, int *height)
{
	int length, size;
	byte *fbuf;
	SDL_RWops *sdlbuf;
	SDL_Surface *iimg, *oimg;
	SDL_PixelFormat ofmt = {
		NULL,		/* Palette */
		32, OUT_BPP,	/* Depth */
		0, 0, 0, 0,	/* Loss */
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
		24, 16, 8, 0,	/* Shift */
		0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff /* Mask */
#else
		0, 8, 16, 24,	/* Shift */
		0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 /* Mask */
#endif
	};

	/* Set some default values for if we can't load the image */
	*pic = NULL; *width = 0; *height = 0;

	/* Don't allow too short filenames */
	if (strlen (name) < 5) return;

	/* Try to read the file from the filesystem */
	length = ri.FS_ReadFile ((char *) name, (void **)&fbuf);

	if (!fbuf)
	{
		/*
		 * In some cases, the file can not be found because
		 * it is saved in JPEG instead of TGA.
		 */
		strcpy ((char *) name + strlen (name) - 4, ".jpg");
		length = ri.FS_ReadFile (name, (void **)&fbuf);
	}

	/* It looks like we can't find the file */
	if (!fbuf) return;

	/* Feed the buffer to SDL */
	sdlbuf = SDL_RWFromMem (fbuf, length);

	/*
	 * IMG_Load_RW can't detect TGA files; that's why we must check
	 * for the '.tga' extension and throw it through IMG_LoadType_RW
	 * manually.
	 */
	if (!Q_stricmp (name + strlen (name) - 4, ".tga"))
		iimg = IMG_LoadTyped_RW (sdlbuf, 1, "TGA");
	else
		iimg = IMG_Load_RW (sdlbuf, 1);

	/* We can already close our file buffer now */
	ri.FS_FreeFile (fbuf);

	/* The image is probably damaged or so */
	if (iimg == NULL) return;

	/* Convert the image to Quake 3's internal format */
	oimg = SDL_ConvertSurface (iimg, &ofmt, 0);
	SDL_FreeSurface (iimg);

	/* Allocate our output buffer */
	*width = oimg->w; *height = oimg->h;
	size = oimg->w * oimg->h * OUT_BPP;
	*pic = ri.Malloc (size);

	/* And copy our results to it */
	memcpy (*pic, oimg->pixels, size);
	SDL_FreeSurface (oimg);
}
