//-----------------------------------------------------------------------------
//
//  $Logfile:: /Source/r_surf.c                                               $
// $Revision:: 3                                                              $
//   $Author:: Burgermac                                                      $
//     $Date:: 8/8/01 4:42 PM                                                 $
//
// Copyright (C) 1998 by Ritual Entertainment, Inc.
// All rights reserved.
//
// This source is may not be distributed and/or modified without
// expressly written permission by Ritual Entertainment, Inc.
//
// DESCRIPTION:
// surface-related refresh code
//

#include "r_local.h"

drawsurf_t	r_drawsurf;

int				lightleft, sourcesstep, blocksize, sourcetstep;
int				lightdelta, lightdeltastep;
int				lightright, lightleftstep, lightrightstep, blockdivshift;
unsigned		blockdivmask;
void			*prowdestbase;
unsigned char	*pbasesource;
int				surfrowbytes;	// used by ASM files
unsigned		*r_lightptr;
int				r_stepback;
int				r_lightwidth;
int				r_numhblocks, r_numvblocks;
unsigned char	*r_source, *r_sourcemax;

void R_DrawSurfaceBlock8_mip0 (void);
void R_DrawSurfaceBlock8_mip1 (void);
void R_DrawSurfaceBlock8_mip2 (void);
void R_DrawSurfaceBlock8_mip3 (void);

static void	(*surfmiptable[4])(void) = {
	R_DrawSurfaceBlock8_mip0,
	R_DrawSurfaceBlock8_mip1,
	R_DrawSurfaceBlock8_mip2,
	R_DrawSurfaceBlock8_mip3
};

void R_BuildLightMap (void);
extern	unsigned		blocklights[1024];	// allow some very large lightmaps

float           surfscale;
qboolean        r_cache_thrash;         // set if surface cache is thrashing

int         sc_size;
surfcache_t	*sc_rover, *sc_base;


//=============================================================================

static int D_log2 (int num)
{
	int     c;
	
	c = 0;
	
	while (num>>=1)
		c++;
	return c;
}

/*
===============
R_TextureAnimation

Returns the proper texture for a given time and base texture
===============
*/
static image_t *R_TextureAnimation (mtexinfo_t *tex)
{
	image_t * image;
	int c;

    image = tex->image;

	if ( tex->surf )
	{
		c = tex->surf->animation_frame;

		while ( c )
		{
			tex = tex->next;
			c--;
		}
	}

	if ( tex )
		image = tex->image;
    
	return image;
}

static int transurf_s, transurf_t;
static int surf_smax, surf_tmax;
static int surf_smask, surf_tmask;
static int surf_sshift;

/*
================
R_DrawTranslatingBlock8
================
*/
static void R_DrawTranslatingBlock8( void )
{
	int v, i, b, lightstep, lighttemp, light;
	int s, t;
	unsigned char pix, *prowdest;

	prowdest = (byte*)prowdestbase;

	for (v=0; v<r_numvblocks; v++)
	{
		// FIXME: make these locals?
		// FIXME: use delta rather than both right and left, like ASM?
		lightleft = r_lightptr[0];
		lightright = r_lightptr[1];
		r_lightptr += r_lightwidth;
		lightleftstep = ((int)r_lightptr[0] - lightleft) >> blockdivshift;
		lightrightstep = ((int)r_lightptr[1] - lightright) >> blockdivshift;

		for (i=0; i<blocksize; i++)
		{
			lighttemp = lightleft - lightright;
			lightstep = lighttemp >> blockdivshift;

			light = lightright;

			t = (transurf_t + i + (v<<blockdivshift)) & surf_tmask;
			for (b=blocksize-1; b>=0; b--)
			{
				s = (transurf_s + b) & surf_smask;
				pix = pbasesource[ (t<<surf_sshift) + s ];
				prowdest[b] = ((unsigned char *)vid.colormap)
				              [(light & 0xFF00) + pix];
				light += lightstep;
			}
			lightright += lightrightstep;
			lightleft += lightleftstep;
			prowdest += surfrowbytes;
		}
	}
}

/*
===============
R_DrawTranslatingSurface
===============
*/
static void R_DrawTranslatingSurface( msurface_t *surface )
{
	int u;
	unsigned char   *pcolumndest;
	image_t         *mt;
	mtexinfo_t     *tex;


	mt = r_drawsurf.image;

	tex = surface->texinfo;
	r_source = mt->pixels[r_drawsurf.surfmip];

	transurf_s = (r_drawsurf.surf->texturemins[0] + (int)(tex->surf->delta_s*mt->width)) >> r_drawsurf.surfmip;
	transurf_t = (r_drawsurf.surf->texturemins[1] + (int)(tex->surf->delta_t*mt->height)) >> r_drawsurf.surfmip;
	surf_smax = mt->width >> r_drawsurf.surfmip;
	surf_tmax = mt->height >> r_drawsurf.surfmip;
	surf_smask = surf_smax-1;
	surf_tmask = surf_tmax-1;
	surf_sshift = D_log2( surf_smax );

	pcolumndest = r_drawsurf.surfdat;

	for (u=0; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u;

		prowdestbase = pcolumndest;
		pbasesource = r_source;

		R_DrawTranslatingBlock8();

		transurf_s = transurf_s + blocksize;

		pcolumndest += blocksize;
	}
}

static unsigned short * prowdestbase16;
static byte * basepalette;
static int redlightleft, redlightright, redlightleftstep, redlightrightstep;
static int greenlightleft, greenlightright, greenlightleftstep, greenlightrightstep;
static int bluelightleft, bluelightright, bluelightleftstep, bluelightrightstep;
static int redfrac, greenfrac, bluefrac;
static int redfracstep, greenfracstep, bluefracstep;
static qboolean masked = false;
static int maskedcolor;
/*
================
R_DrawTranslating16bitBlock8
================
*/
static void R_DrawTranslating16bitBlock8( void )
{
	int v, i, b;
	int s, t;
	unsigned char pix;
	unsigned short *prowdest;

	prowdest = prowdestbase16;

	for (v=0; v<r_numvblocks; v++)
	{
		// FIXME: make these locals?
		// FIXME: use delta rather than both right and left, like ASM?
		redlightleft = r_lightptr[0];
		greenlightleft = r_lightptr[1];
		bluelightleft = r_lightptr[2];
		redlightright = r_lightptr[3];
		greenlightright = r_lightptr[4];
		bluelightright = r_lightptr[5];

		r_lightptr += r_lightwidth*3;

		redlightleftstep = ((int)r_lightptr[0] - redlightleft) >> blockdivshift;
		redlightrightstep = ((int)r_lightptr[3] - redlightright) >> blockdivshift;
		greenlightleftstep = ((int)r_lightptr[1] - greenlightleft) >> blockdivshift;
		greenlightrightstep = ((int)r_lightptr[4] - greenlightright) >> blockdivshift;
		bluelightleftstep = ((int)r_lightptr[2] - bluelightleft) >> blockdivshift;
		bluelightrightstep = ((int)r_lightptr[5] - bluelightright) >> blockdivshift;

		for (i=0; i<blocksize; i++)
		{
			redfracstep = (redlightleft - redlightright) >> blockdivshift;
			redfrac = redlightright;

			greenfracstep = (greenlightleft - greenlightright) >> blockdivshift;
			greenfrac = greenlightright;

			bluefracstep = (bluelightleft - bluelightright) >> blockdivshift;
			bluefrac = bluelightright;

			t = (transurf_t + i + (v<<blockdivshift)) & surf_tmask;
			for (b=blocksize-1; b>=0; b--)
			{
				byte * srccolor;

				s = (transurf_s + b) & surf_smask;
				pix = pbasesource[ (t<<surf_sshift) + s ];

				if ( masked && ( pix == maskedcolor ) )
				{
					prowdest[ b ] = TRANSPARENT_COLOR16;
				}
				else
				{
					srccolor = basepalette + (pix<<2);

					prowdest[ b ] =
						vid.redlightmap16[ (redfrac&0xff00) + srccolor[0] ] +
						vid.greenlightmap16[ (greenfrac&0xff00) + srccolor[1] ] +
						vid.bluelightmap16[ (bluefrac&0xff00) + srccolor[2] ];
				}

				redfrac += redfracstep;
				greenfrac += greenfracstep;
				bluefrac += bluefracstep;
			}
			redlightright += redlightrightstep;
			redlightleft += redlightleftstep;
			greenlightright += greenlightrightstep;
			greenlightleft += greenlightleftstep;
			bluelightright += bluelightrightstep;
			bluelightleft += bluelightleftstep;
			prowdest += surfrowbytes;
		}
	}
}

/*
===============
R_DrawTranslating16bitSurface
===============
*/
static void R_DrawTranslating16bitSurface( msurface_t *surface )
{
	int u;
	unsigned short	*pcolumndest;
	image_t			*mt;
	mtexinfo_t		*tex;


	mt = r_drawsurf.image;

	tex = surface->texinfo;
	r_source = mt->pixels[r_drawsurf.surfmip];
	basepalette = mt->palette;

	//
	// see if we are using a masked surface
	//
	if ( surface->texinfo->flags & SURF_MASKED )
	{
		masked = true;
		maskedcolor = mt->masked_color;
	}
	else
	{
		masked = false;
	}

	transurf_s = (r_drawsurf.surf->texturemins[0] + (int)(tex->surf->delta_s*mt->width)) >> r_drawsurf.surfmip;
	transurf_t = (r_drawsurf.surf->texturemins[1] + (int)(tex->surf->delta_t*mt->height)) >> r_drawsurf.surfmip;
	surf_smax = mt->width >> r_drawsurf.surfmip;
	surf_tmax = mt->height >> r_drawsurf.surfmip;
	surf_smask = surf_smax-1;
	surf_tmask = surf_tmax-1;
	surf_sshift = D_log2( surf_smax );

	pcolumndest = ( unsigned short * )r_drawsurf.surfdat;

	for (u=0; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u*3;

		prowdestbase16 = pcolumndest;
		pbasesource = r_source;

		R_DrawTranslating16bitBlock8();

		transurf_s = transurf_s + blocksize;

		pcolumndest += blocksize;
	}
}

/*
================
R_Draw16bitBlock8
================
*/
static void R_Draw16bitBlock8( void )
{
	int v, i, b;
	//int t;
	unsigned char pix;
	unsigned short	*prowdest;
	unsigned char	*psource;

	psource = pbasesource;
	prowdest = prowdestbase16;

	for (v=0; v<r_numvblocks; v++)
	{
		// FIXME: make these locals?
		// FIXME: use delta rather than both right and left, like ASM?
		redlightleft = r_lightptr[0];
		greenlightleft = r_lightptr[1];
		bluelightleft = r_lightptr[2];
		redlightright = r_lightptr[3];
		greenlightright = r_lightptr[4];
		bluelightright = r_lightptr[5];

		r_lightptr += r_lightwidth*3;

		redlightleftstep = ((int)r_lightptr[0] - redlightleft) >> blockdivshift;
		redlightrightstep = ((int)r_lightptr[3] - redlightright) >> blockdivshift;
		greenlightleftstep = ((int)r_lightptr[1] - greenlightleft) >> blockdivshift;
		greenlightrightstep = ((int)r_lightptr[4] - greenlightright) >> blockdivshift;
		bluelightleftstep = ((int)r_lightptr[2] - bluelightleft) >> blockdivshift;
		bluelightrightstep = ((int)r_lightptr[5] - bluelightright) >> blockdivshift;

		for (i=0; i<blocksize; i++)
		{
			redfracstep = (redlightleft - redlightright) >> blockdivshift;
			redfrac = redlightright;

			greenfracstep = (greenlightleft - greenlightright) >> blockdivshift;
			greenfrac = greenlightright;

			bluefracstep = (bluelightleft - bluelightright) >> blockdivshift;
			bluefrac = bluelightright;

			//t = (transurf_t + i + (v<<blockdivshift)) & surf_tmask;
			for (b=blocksize-1; b>=0; b--)
			{
				byte *srccolor;

				pix = psource[b];

				if (masked && pix == maskedcolor)
				{
					prowdest[b] = TRANSPARENT_COLOR16;
				}
				else
				{
					srccolor = basepalette + (pix<<2);
					prowdest[b] =
						vid.redlightmap16[(redfrac&0xff00) + srccolor[0]] +
						vid.greenlightmap16[(greenfrac&0xff00) + srccolor[1]] +
						vid.bluelightmap16[(bluefrac&0xff00) + srccolor[2]];
				}

				redfrac += redfracstep;
				greenfrac += greenfracstep;
				bluefrac += bluefracstep;
			}
			redlightright += redlightrightstep;
			redlightleft += redlightleftstep;
			greenlightright += greenlightrightstep;
			greenlightleft += greenlightleftstep;
			bluelightright += bluelightrightstep;
			bluelightleft += bluelightleftstep;
			prowdest += surfrowbytes;
			psource += sourcetstep;
		}
		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}

/*
===============
R_Draw16bitSurface
===============
*/
static void R_Draw16bitSurface( msurface_t *surface )
{
	int u;
	unsigned short	*pcolumndest;
	unsigned char	*basetptr;
	image_t			*mt;
	int smax, tmax;
	int soffset, basetoffset;


	mt = r_drawsurf.image;

	r_source = mt->pixels[r_drawsurf.surfmip];
	basepalette = mt->palette;

	//
	// see if we are using a masked surface
	//
	if ( surface->texinfo->flags & SURF_MASKED )
	{
		masked = true;
		maskedcolor = mt->masked_color;
	}
	else
	{
		masked = false;
	}

	smax = mt->width >> r_drawsurf.surfmip;
	tmax = mt->height >> r_drawsurf.surfmip;

	r_sourcemax = r_source + (tmax * smax);
	r_stepback = tmax * smax;

	soffset = r_drawsurf.surf->texturemins[0];
	basetoffset = r_drawsurf.surf->texturemins[1];

// << 16 components are to guarantee positive values for %
	soffset = ((soffset >> r_drawsurf.surfmip) + (smax << 16)) % smax;
	basetptr = &r_source[((((basetoffset >> r_drawsurf.surfmip)
	                        + (tmax << 16)) % tmax) * smax)];

	pcolumndest = (unsigned short *)r_drawsurf.surfdat;

	for (u=0; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u*3;

		prowdestbase16 = pcolumndest;

		pbasesource = basetptr + soffset;

		R_Draw16bitBlock8();

		soffset = soffset + blocksize;
		if (soffset >= smax)
			soffset = 0;

		pcolumndest += blocksize;
	}
}

/*
================
R_DrawTranslating8bitColorBlock8
================
*/
static void R_DrawTranslating8bitColorBlock8( void )
{
	int v, i, b;
	int s, t;
	unsigned char pix;
	byte *prowdest;

	prowdest = (byte*)prowdestbase;

	for (v=0; v<r_numvblocks; v++)
	{
		// FIXME: make these locals?
		// FIXME: use delta rather than both right and left, like ASM?
		redlightleft = r_lightptr[0];
		greenlightleft = r_lightptr[1];
		bluelightleft = r_lightptr[2];
		redlightright = r_lightptr[3];
		greenlightright = r_lightptr[4];
		bluelightright = r_lightptr[5];

		r_lightptr += r_lightwidth*3;

		redlightleftstep = ((int)r_lightptr[0] - redlightleft) >> blockdivshift;
		redlightrightstep = ((int)r_lightptr[3] - redlightright) >> blockdivshift;
		greenlightleftstep = ((int)r_lightptr[1] - greenlightleft) >> blockdivshift;
		greenlightrightstep = ((int)r_lightptr[4] - greenlightright) >> blockdivshift;
		bluelightleftstep = ((int)r_lightptr[2] - bluelightleft) >> blockdivshift;
		bluelightrightstep = ((int)r_lightptr[5] - bluelightright) >> blockdivshift;

		for (i=0; i<blocksize; i++)
		{
			redfracstep = (redlightleft - redlightright) >> blockdivshift;
			redfrac = redlightright;

			greenfracstep = (greenlightleft - greenlightright) >> blockdivshift;
			greenfrac = greenlightright;

			bluefracstep = (bluelightleft - bluelightright) >> blockdivshift;
			bluefrac = bluelightright;

			t = (transurf_t + i + (v<<blockdivshift)) & surf_tmask;
			for (b=blocksize-1; b>=0; b--)
			{
				byte * srccolor;

				s = (transurf_s + b) & surf_smask;
				pix = pbasesource[ (t<<surf_sshift) + s ];

				if ( masked && ( pix == maskedcolor ) )
				{
					prowdest[ b ] = 255;
				}
				else
				{
					srccolor = basepalette + (pix<<2);

					prowdest[ b ] = vid.color_16to8table
						            [
						vid.redlightmap16[ (redfrac&0xff00) + srccolor[0]] +
						vid.greenlightmap16[ (greenfrac&0xff00) + srccolor[1]] +
						vid.bluelightmap16[ (bluefrac&0xff00) + srccolor[2]]
					                ];
				}

				redfrac += redfracstep;
				greenfrac += greenfracstep;
				bluefrac += bluefracstep;
			}
			redlightright += redlightrightstep;
			redlightleft += redlightleftstep;
			greenlightright += greenlightrightstep;
			greenlightleft += greenlightleftstep;
			bluelightright += bluelightrightstep;
			bluelightleft += bluelightleftstep;
			prowdest += surfrowbytes;
		}
	}
}

/*
===============
R_DrawTranslating8bitColorSurface
===============
*/
static void R_DrawTranslating8bitColorSurface( msurface_t *surface )
{
	int u;
	byte			*pcolumndest;
	image_t			*mt;
	mtexinfo_t		*tex;


	mt = r_drawsurf.image;

	tex = surface->texinfo;
	r_source = mt->pixels[r_drawsurf.surfmip];
	basepalette = d_8to24table;

	//
	// see if we are using a masked surface
	//
	if ( surface->texinfo->flags & SURF_MASKED )
	{
		masked = true;
		maskedcolor = 255;
	}
	else
	{
		masked = false;
	}

	transurf_s = (r_drawsurf.surf->texturemins[0] + (int)(tex->surf->delta_s*mt->width)) >> r_drawsurf.surfmip;
	transurf_t = (r_drawsurf.surf->texturemins[1] + (int)(tex->surf->delta_t*mt->height)) >> r_drawsurf.surfmip;
	surf_smax = mt->width >> r_drawsurf.surfmip;
	surf_tmax = mt->height >> r_drawsurf.surfmip;
	surf_smask = surf_smax-1;
	surf_tmask = surf_tmax-1;
	surf_sshift = D_log2( surf_smax );

	pcolumndest = ( byte * )r_drawsurf.surfdat;

	for (u=0; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u*3;

		prowdestbase = pcolumndest;
		pbasesource = r_source;

		R_DrawTranslating8bitColorBlock8();

		transurf_s = transurf_s + blocksize;

		pcolumndest += blocksize;
	}
}

/*
================
R_Draw8bitColorBlock8
================
*/
static void R_Draw8bitColorBlock8( void )
{
	int v, i, b;
	//int t;
	unsigned char pix;
	byte			*prowdest;
	unsigned char	*psource;

	psource = pbasesource;
	prowdest = (byte*)prowdestbase;

	for (v=0; v<r_numvblocks; v++)
	{
		// FIXME: make these locals?
		// FIXME: use delta rather than both right and left, like ASM?
		redlightleft = r_lightptr[0];
		greenlightleft = r_lightptr[1];
		bluelightleft = r_lightptr[2];
		redlightright = r_lightptr[3];
		greenlightright = r_lightptr[4];
		bluelightright = r_lightptr[5];

		r_lightptr += r_lightwidth*3;

		redlightleftstep = ((int)r_lightptr[0] - redlightleft) >> blockdivshift;
		redlightrightstep = ((int)r_lightptr[3] - redlightright) >> blockdivshift;
		greenlightleftstep = ((int)r_lightptr[1] - greenlightleft) >> blockdivshift;
		greenlightrightstep = ((int)r_lightptr[4] - greenlightright) >> blockdivshift;
		bluelightleftstep = ((int)r_lightptr[2] - bluelightleft) >> blockdivshift;
		bluelightrightstep = ((int)r_lightptr[5] - bluelightright) >> blockdivshift;

		for (i=0; i<blocksize; i++)
		{
			redfracstep = (redlightleft - redlightright) >> blockdivshift;
			redfrac = redlightright;

			greenfracstep = (greenlightleft - greenlightright) >> blockdivshift;
			greenfrac = greenlightright;

			bluefracstep = (bluelightleft - bluelightright) >> blockdivshift;
			bluefrac = bluelightright;

			//t = (transurf_t + i + (v<<blockdivshift)) & surf_tmask;
			for (b=blocksize-1; b>=0; b--)
			{
				byte * srccolor;

				pix = psource[b];

				if (masked && pix == maskedcolor)
				{
					prowdest[b] = 255;
				}
				else
				{
					srccolor = basepalette + (pix<<2);

					prowdest[b] = vid.color_16to8table
						            [
						vid.redlightmap16[(redfrac&0xff00) + srccolor[0]] +
						vid.greenlightmap16[(greenfrac&0xff00) + srccolor[1]] +
						vid.bluelightmap16[(bluefrac&0xff00) + srccolor[2]]
					                ];
				}

				redfrac += redfracstep;
				greenfrac += greenfracstep;
				bluefrac += bluefracstep;
			}
			redlightright += redlightrightstep;
			redlightleft += redlightleftstep;
			greenlightright += greenlightrightstep;
			greenlightleft += greenlightleftstep;
			bluelightright += bluelightrightstep;
			bluelightleft += bluelightleftstep;
			prowdest += surfrowbytes;
			psource += sourcetstep;
		}
		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}

/*
===============
R_Draw8bitColorSurface
===============
*/
static void R_Draw8bitColorSurface( msurface_t *surface )
{
	int u;
	byte			*pcolumndest;
	unsigned char	*basetptr;
	image_t			*mt;
	int smax, tmax;
	int soffset, basetoffset;


	mt = r_drawsurf.image;

	r_source = mt->pixels[r_drawsurf.surfmip];
	basepalette = d_8to24table;

	//
	// see if we are using a masked surface
	//
	if ( surface->texinfo->flags & SURF_MASKED )
	{
		masked = true;
		maskedcolor = 255;
	}
	else
	{
		masked = false;
	}

	smax = mt->width >> r_drawsurf.surfmip;
	tmax = mt->height >> r_drawsurf.surfmip;

	r_sourcemax = r_source + (tmax * smax);
	r_stepback = tmax * smax;

	soffset = r_drawsurf.surf->texturemins[0];
	basetoffset = r_drawsurf.surf->texturemins[1];

// << 16 components are to guarantee positive values for %
	soffset = ((soffset >> r_drawsurf.surfmip) + (smax << 16)) % smax;
	basetptr = &r_source[((((basetoffset >> r_drawsurf.surfmip)
	                        + (tmax << 16)) % tmax) * smax)];


	pcolumndest = ( byte * )r_drawsurf.surfdat;

	for (u=0; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u*3;

		prowdestbase = pcolumndest;

		pbasesource = basetptr + soffset;

		R_Draw8bitColorBlock8();

		soffset = soffset + blocksize;
		if (soffset >= smax)
			soffset = 0;

		pcolumndest += blocksize;
	}
}

/*
===============
R_DrawSurface
===============
*/
void R_DrawSurface (msurface_t *surface)
{
	unsigned char	*basetptr;
	int				smax, tmax, twidth;
	int				u;
	int				soffset, basetoffset, texwidth;
	int				horzblockstep;
	unsigned char	*pcolumndest;
	void			(*pblockdrawer)(void);
	image_t			*mt;

	surfrowbytes = r_drawsurf.rowbytes;

	mt = r_drawsurf.image;
	
	r_source = mt->pixels[r_drawsurf.surfmip];
	
// the fractional light values should range from 0 to (VID_GRADES - 1) << 16
// from a source range of 0 - 255
	
	texwidth = mt->width >> r_drawsurf.surfmip;

	blocksize = 16 >> r_drawsurf.surfmip;
	blockdivshift = 4 - r_drawsurf.surfmip;
	blockdivmask = (1 << blockdivshift) - 1;
	
	r_lightwidth = (r_drawsurf.surf->extents[0]>>4)+1;

	r_numhblocks = r_drawsurf.surfwidth >> blockdivshift;
	r_numvblocks = r_drawsurf.surfheight >> blockdivshift;

//==============================

	pblockdrawer = surfmiptable[r_drawsurf.surfmip];
// TODO: only needs to be set when there is a display settings change
	horzblockstep = blocksize;

	smax = mt->width >> r_drawsurf.surfmip;
	twidth = texwidth;
	tmax = mt->height >> r_drawsurf.surfmip;
	sourcetstep = texwidth;
	r_stepback = tmax * twidth;

	if ( vid.bitdepth == 16 )
	{
		if (surface->texinfo->flags & SURF_TRANSLATE)
		{
			R_DrawTranslating16bitSurface( surface );
			return;
		}
		else
		{
			R_Draw16bitSurface( surface );
			return;
		}
	}
	else if ( vid.colorlighting )
	{
		if (surface->texinfo->flags & SURF_TRANSLATE)
		{
			R_DrawTranslating8bitColorSurface( surface );
			return;
		}
		else
		{
			R_Draw8bitColorSurface( surface );
			return;
		}
	}
   else
	{
		if (surface->texinfo->flags & SURF_TRANSLATE)
		{
			R_DrawTranslatingSurface( surface );
			return;
		}
	}

	r_sourcemax = r_source + (tmax * smax);

	soffset = r_drawsurf.surf->texturemins[0];
	basetoffset = r_drawsurf.surf->texturemins[1];

// << 16 components are to guarantee positive values for %
	soffset = ((soffset >> r_drawsurf.surfmip) + (smax << 16)) % smax;
	basetptr = &r_source[((((basetoffset >> r_drawsurf.surfmip) 
		+ (tmax << 16)) % tmax) * twidth)];

	pcolumndest = r_drawsurf.surfdat;

	for (u=0 ; u<r_numhblocks; u++)
	{
		r_lightptr = blocklights + u;

		prowdestbase = pcolumndest;

		pbasesource = basetptr + soffset;

		(*pblockdrawer)();

		soffset = soffset + blocksize;
		if (soffset >= smax)
			soffset = 0;

		pcolumndest += horzblockstep;
	}
}


//=============================================================================

#if	!id386

/*
================
R_DrawSurfaceBlock8_mip0
================
*/
void R_DrawSurfaceBlock8_mip0 (void)
{
	int				v, i, b, lightstep, lighttemp, light;
	unsigned char	pix, *psource, *prowdest;

	psource = pbasesource;
	prowdest = (byte*)prowdestbase;

	for (v=0 ; v<r_numvblocks ; v++)
	{
	// FIXME: make these locals?
	// FIXME: use delta rather than both right and left, like ASM?
		lightleft = r_lightptr[0];
		lightright = r_lightptr[1];
		r_lightptr += r_lightwidth;
		lightleftstep = (r_lightptr[0] - lightleft) >> 4;
		lightrightstep = (r_lightptr[1] - lightright) >> 4;

		for (i=0 ; i<16 ; i++)
		{
			lighttemp = lightleft - lightright;
			lightstep = lighttemp >> 4;

			light = lightright;

			for (b=15; b>=0; b--)
			{
				pix = psource[b];
				prowdest[b] = ((unsigned char *)vid.colormap)
						[(light & 0xFF00) + pix];
				light += lightstep;
			}
	
			psource += sourcetstep;
			lightright += lightrightstep;
			lightleft += lightleftstep;
			prowdest += surfrowbytes;
		}

		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}


/*
================
R_DrawSurfaceBlock8_mip1
================
*/
void R_DrawSurfaceBlock8_mip1 (void)
{
	int				v, i, b, lightstep, lighttemp, light;
	unsigned char	pix, *psource, *prowdest;

	psource = pbasesource;
	prowdest = (byte*)prowdestbase;

	for (v=0 ; v<r_numvblocks ; v++)
	{
	// FIXME: make these locals?
	// FIXME: use delta rather than both right and left, like ASM?
		lightleft = r_lightptr[0];
		lightright = r_lightptr[1];
		r_lightptr += r_lightwidth;
		lightleftstep = (r_lightptr[0] - lightleft) >> 3;
		lightrightstep = (r_lightptr[1] - lightright) >> 3;

		for (i=0 ; i<8 ; i++)
		{
			lighttemp = lightleft - lightright;
			lightstep = lighttemp >> 3;

			light = lightright;

			for (b=7; b>=0; b--)
			{
				pix = psource[b];
				prowdest[b] = ((unsigned char *)vid.colormap)
						[(light & 0xFF00) + pix];
				light += lightstep;
			}
	
			psource += sourcetstep;
			lightright += lightrightstep;
			lightleft += lightleftstep;
			prowdest += surfrowbytes;
		}

		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}


/*
================
R_DrawSurfaceBlock8_mip2
================
*/
void R_DrawSurfaceBlock8_mip2 (void)
{
	int				v, i, b, lightstep, lighttemp, light;
	unsigned char	pix, *psource, *prowdest;

	psource = pbasesource;
	prowdest = (byte*)prowdestbase;

	for (v=0 ; v<r_numvblocks ; v++)
	{
	// FIXME: make these locals?
	// FIXME: use delta rather than both right and left, like ASM?
		lightleft = r_lightptr[0];
		lightright = r_lightptr[1];
		r_lightptr += r_lightwidth;
		lightleftstep = (r_lightptr[0] - lightleft) >> 2;
		lightrightstep = (r_lightptr[1] - lightright) >> 2;

		for (i=0 ; i<4 ; i++)
		{
			lighttemp = lightleft - lightright;
			lightstep = lighttemp >> 2;

			light = lightright;

			for (b=3; b>=0; b--)
			{
				pix = psource[b];
				prowdest[b] = ((unsigned char *)vid.colormap)
						[(light & 0xFF00) + pix];
				light += lightstep;
			}
	
			psource += sourcetstep;
			lightright += lightrightstep;
			lightleft += lightleftstep;
			prowdest += surfrowbytes;
		}

		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}


/*
================
R_DrawSurfaceBlock8_mip3
================
*/
void R_DrawSurfaceBlock8_mip3 (void)
{
	int				v, i, b, lightstep, lighttemp, light;
	unsigned char	pix, *psource, *prowdest;

	psource = pbasesource;
	prowdest = (byte*)prowdestbase;

	for (v=0 ; v<r_numvblocks ; v++)
	{
	// FIXME: make these locals?
	// FIXME: use delta rather than both right and left, like ASM?
		lightleft = r_lightptr[0];
		lightright = r_lightptr[1];
		r_lightptr += r_lightwidth;
		lightleftstep = (r_lightptr[0] - lightleft) >> 1;
		lightrightstep = (r_lightptr[1] - lightright) >> 1;

		for (i=0 ; i<2 ; i++)
		{
			lighttemp = lightleft - lightright;
			lightstep = lighttemp >> 1;

			light = lightright;

			for (b=1; b>=0; b--)
			{
				pix = psource[b];
				prowdest[b] = ((unsigned char *)vid.colormap)
						[(light & 0xFF00) + pix];
				light += lightstep;
			}
	
			psource += sourcetstep;
			lightright += lightrightstep;
			lightleft += lightleftstep;
			prowdest += surfrowbytes;
		}

		if (psource >= r_sourcemax)
			psource -= r_stepback;
	}
}

#endif


//============================================================================


/*
================
R_InitCaches

================
*/
void R_InitCaches (void)
{
	int		size;
	int		pix;

	// calculate size to allocate
	if (sw_surfcacheoverride->value)
	{
		size = sw_surfcacheoverride->value;
	}
	else
	{
		pix = vid.width*vid.height;
		size = SURFCACHE_SIZE_AT_320X240;

		pix = vid.width*vid.height;
		if (pix > 64000)
			size += (pix-64000)*4;
	}		

	if ( vid.bitdepth > 8 )
		size *= 3;

	// round up to page size
	size = (size + 8191) & ~8191;

	ri.Con_Printf (PRINT_ALL,"%ik surface cache\n", size/1024);

	sc_size = size;
	sc_base = (surfcache_t *)malloc(size);
	sc_rover = sc_base;
	
	sc_base->next = NULL;
	sc_base->owner = NULL;
	sc_base->size = sc_size;
}


/*
==================
D_FlushCaches
==================
*/
void D_FlushCaches (void)
{
	surfcache_t     *c;
	
	if (!sc_base)
		return;

	for (c = sc_base ; c ; c = c->next)
	{
		if (c->owner)
			*c->owner = NULL;
	}
	
	sc_rover = sc_base;
	sc_base->next = NULL;
	sc_base->owner = NULL;
	sc_base->size = sc_size;
}

/*
=================
D_SCAlloc
=================
*/
static surfcache_t     *D_SCAlloc (int width, int size)
{
	surfcache_t             *newptr;
	qboolean                wrapped_this_time;

	if ((width < 0) || (width > 256))
		ri.Sys_Error (ERR_FATAL,"D_SCAlloc: bad cache width %d\n", width);

	if ((size <= 0) || (size > 0x10000))
		ri.Sys_Error (ERR_FATAL,"D_SCAlloc: bad cache size %d\n", size);


	size *= (vid.bitdepth >> 3);
	// width *= (vid.bitdepth >> 3);

	size = (int) ((intptr_t) &((surfcache_t *)0)->data[size]);
	size = (size + 3) & ~3;
	if (size > sc_size)
		ri.Sys_Error (ERR_FATAL,"D_SCAlloc: %i > cache size of %i",size, sc_size);

// if there is not size bytes after the rover, reset to the start
	wrapped_this_time = false;

	if ( !sc_rover || (byte *)sc_rover - (byte *)sc_base > sc_size - size)
	{
		if (sc_rover)
		{
			wrapped_this_time = true;
		}
		sc_rover = sc_base;
	}
		
// colect and free surfcache_t blocks until the rover block is large enough
	newptr = sc_rover;
	if (sc_rover->owner)
		*sc_rover->owner = NULL;
	
	while (newptr->size < size)
	{
	// free another
		sc_rover = sc_rover->next;
		if (!sc_rover)
			ri.Sys_Error (ERR_FATAL,"D_SCAlloc: hit the end of memory");
		if (sc_rover->owner)
			*sc_rover->owner = NULL;
			
		newptr->size += sc_rover->size;
		newptr->next = sc_rover->next;
	}

// create a fragment out of any leftovers
	if (newptr->size - size > 256)
	{
		sc_rover = (surfcache_t *)( (byte *)newptr + size);
		sc_rover->size = newptr->size - size;
		sc_rover->next = newptr->next;
		sc_rover->width = 0;
		sc_rover->owner = NULL;
		newptr->next = sc_rover;
		newptr->size = size;
	}
	else
		sc_rover = newptr->next;
	
	newptr->width = width;
// DEBUG
	if (width > 0)
		newptr->height = ( ( size / (vid.bitdepth>>3) ) - sizeof(*newptr) + sizeof(newptr->data)) / width;

	newptr->owner = NULL;              // should be set properly after return

	if (d_roverwrapped)
	{
		if (wrapped_this_time || (sc_rover >= d_initial_rover))
			r_cache_thrash = true;
	}
	else if (wrapped_this_time)
	{       
		d_roverwrapped = true;
	}

	return newptr;
}

//=============================================================================

/*
================
D_CacheSurface
================
*/
surfcache_t *D_CacheSurface (msurface_t *surface, int miplevel)
{
	surfcache_t     *cache;
	int maps;

//
// if the surface is animating or flashing, flush the cache
//
	r_drawsurf.image = R_TextureAnimation (surface->texinfo);

	for (maps = 0 ; maps < MAXLIGHTMAPS && surface->styles[maps] != 255 ; maps++)
	{
		r_drawsurf.lightadj[maps] = r_newrefdef.lightstyles[surface->styles[maps]].white*128;
	}
	
//
// see if the cache holds apropriate data
//
	cache = surface->cachespots[miplevel];

	if (cache && !cache->dlight && surface->dlightframe != r_framecount
		&& !surface->lightmap_modified[miplevel]
		&& cache->image == r_drawsurf.image
		&& !(surface->texinfo->flags & SURF_TRANSLATE))
	{
		qboolean virgin = true;
		for (maps = 0 ; maps < MAXLIGHTMAPS && surface->styles[maps] != 255 ; maps++)
		{
			if (cache->lightadj[maps] != r_drawsurf.lightadj[maps])
			{
				virgin = false;
				break;
			}
		}
		if (virgin)
			return cache;
	}

//
// determine shape of surface
//
	surfscale = 1.0 / (1<<miplevel);
	r_drawsurf.surfmip = miplevel;
	r_drawsurf.surfwidth = surface->extents[0] >> miplevel;
	r_drawsurf.rowbytes = r_drawsurf.surfwidth;
	r_drawsurf.surfheight = surface->extents[1] >> miplevel;
	
//
// allocate memory if needed
//
	if (!cache)     // if a texture just animated, don't reallocate it
	{
		cache = D_SCAlloc (r_drawsurf.surfwidth,
						   r_drawsurf.surfwidth * r_drawsurf.surfheight);
		surface->cachespots[miplevel] = cache;
		cache->owner = &surface->cachespots[miplevel];
		cache->mipscale = surfscale;
	}
	
	if (surface->dlightframe == r_framecount)
		cache->dlight = 1;
	else
		cache->dlight = 0;

	r_drawsurf.surfdat = (pixel_t *)cache->data;
	
	cache->image = r_drawsurf.image;

	for (maps = 0 ; maps < MAXLIGHTMAPS && surface->styles[maps] != 255 ; maps++)
		cache->lightadj[maps] = r_drawsurf.lightadj[maps];
	surface->lightmap_modified[miplevel] = false;

//
// draw and light the surface texture
//
	r_drawsurf.surf = surface;

	c_surf++;

	// calculate the lightings
	R_BuildLightMap ();
	
	// rasterize the surface into the cache
	R_DrawSurface (surface);

	return cache;
}
