//-----------------------------------------------------------------------------
//
//  $Logfile:: /Source/cl_scrn.c                                              $
// $Revision:: 2                                                              $
//   $Author:: Burgermac                                                      $
//     $Date:: 12/27/00 7:22 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:
// master for refresh, status bar, console, chat, notify, etc
//

/*

  full screen console
  put up loading plaque
  blanked background with loading plaque
  blanked background with menu
  cinematics
  full screen image for quit and victory

  end of unit intermissions

  */

#include "client.h"

float		scr_con_current;	// aproaches scr_conlines at scr_conspeed
float		scr_conlines;		// 0.0 to 1.0 lines of console to display

qboolean	scr_initialized;		// ready to draw

int			scr_draw_loading = false;

vrect_t		scr_vrect;		// position of render window on screen


cvar_t		*scr_viewsize;
cvar_t		*scr_conspeed;
cvar_t		*scr_centertime;
cvar_t		*scr_showturtle;
cvar_t		*scr_showpause;
cvar_t		*scr_printspeed;

cvar_t		*scr_netgraph;
cvar_t		*scr_timegraph;
cvar_t		*scr_debuggraph;
cvar_t		*scr_graphheight;
cvar_t		*scr_graphscale;
cvar_t		*scr_graphshift;
cvar_t		*scr_drawall;

cvar_t		*scr_showhud;
cvar_t      *scr_dialogtime;

/* FS: cl_draw*** friends */
cvar_t		*cl_drawfps;
cvar_t		*cl_drawtime;
cvar_t		*cl_drawuptime;
cvar_t		*cl_drawaltcolours;

typedef struct
{
	int		x1, y1, x2, y2;
} dirty_t;

dirty_t		scr_dirty, scr_old_dirty[2];

char		crosshair_pic[MAX_QPATH];
int			crosshair_width, crosshair_height;
char		zoom_crosshair_pic[MAX_QPATH];
int			zoom_crosshair_width, zoom_crosshair_height;

void SCR_TimeRefresh_f (void);
void SCR_Loading_f (void);

/*
===============================================================================

FS: CL_DRAW*** FRIENDS

===============================================================================
*/

static void SCR_DrawUptime (void)
{
	char	str[80];
	int	minutes, seconds, tens, units;
	int	x, y;

	if ((cls.state != ca_active) || !(cl_drawuptime->intValue))
	{
		return;
	}

	SCR_DirtyScreen();

	// time
	if (cl_drawuptime->intValue == 1)
	{
		minutes = (cl.frame.serverframe/10) / 60;
	}
	else
	{
		minutes = (Sys_Milliseconds()/1000) / 60;
	}

	if (cl_drawuptime->intValue == 1)
	{
		seconds = (cl.frame.serverframe/10) - 60*minutes;
	}
	else
	{
		seconds = (Sys_Milliseconds()/1000) - 60*minutes;
	}

	tens = seconds / 10;
	units = seconds - 10*tens;
	Com_sprintf (str, sizeof(str), "%3i:%i%i", minutes, tens, units);
	x = viddef.width - (int)strlen(str) * 8;
	y = viddef.height - 110;

	if(cl_drawaltcolours->intValue)
	{
		DrawAltString(x, y, str);
	}
	else
	{
		SINDrawString(x, y, str);
	}
}

static void SCR_DrawTime (void)
{
	int	x, y;
	struct tm	*local;
	time_t	utc;
	const char *timefmt;
	char	st[80];

	if (cls.state != ca_active || cl_drawtime->intValue <= 0)
		return;

	SCR_DirtyScreen();

	utc = time (NULL);
	local = localtime (&utc);

	if (cl_drawtime->intValue == 1)
		timefmt = "%H:%M:%S %p";
	else	timefmt = "%I:%M:%S %p";

	strftime (st, sizeof (st), timefmt, local);

	x = viddef.width - (int)strlen(st) * 8;
	y = viddef.height - 102;
	if(cl_drawaltcolours->intValue)
	{
		DrawAltString(x, y, st);
	}
	else
	{
		SINDrawString(x, y, st);
	}
}

#define FPS_FRAMES		4
static void SCR_ShowFPS (void)
{
	static int	previousTimes[FPS_FRAMES];
	static int	previousTime, index, fpscounter;
	static char	fpsText[32];
	int			i, time, total, fps, x, y;

	if ((cls.state != ca_active) || !(cl_drawfps->value))
	{
		return;
	}

	if ((cl.time + 1000) < fpscounter)
	{
		fpscounter = cl.time + 100;
	}

	SCR_DirtyScreen();

	time = Sys_Milliseconds();
	previousTimes[index % FPS_FRAMES] = time - previousTime;
	previousTime = time;
	index++;

	if (index <= FPS_FRAMES)
	{
		return;
	}

	total = 0;
	for (i = 0; i < FPS_FRAMES; i++)
	{
		total += previousTimes[i];
	}
	total = max (total, 1);
	fps = 1000 * FPS_FRAMES / total;

	if (cl.time > fpscounter)
	{
		Com_sprintf(fpsText, sizeof(fpsText), "%3ifps", fps);
		fpscounter = cl.time + 100;
	}

	x = (viddef.width - (int)strlen(fpsText)*8);
	y = (viddef.height - 93);

	if(cl_drawaltcolours->intValue)
	{
		DrawAltString(x, y, fpsText);
	}
	else
	{
		SINDrawString(x, y, fpsText);
	}
}

/*
===============================================================================

BAR GRAPHS

===============================================================================
*/

/*
==============
CL_AddNetgraph

A new packet was just parsed
==============
*/
void CL_AddNetgraph (void)
{
	int i;
	int in;
	int ping;

	// if using the debuggraph for something else, don't
	// add the net lines
	if (scr_debuggraph->value || scr_timegraph->value)
		return;

	for (i = 0; i < cls.netchan.dropped; i++)
		SCR_DebugGraph (30, 0x40);

	for (i = 0; i < cl.surpressCount; i++)
		SCR_DebugGraph (30, 0xdf);

	// see what the latency was on this packet
	in = cls.netchan.incoming_acknowledged & (CMD_BACKUP-1);
	ping = cls.realtime - cl.cmd_time[in];
	ping /= 30;
	if (ping > 30)
	    ping = 30;
	SCR_DebugGraph (ping, 0xd0);
}


typedef struct
{
	float	value;
	int		color;
} graphsamp_t;

static	int			current;
static	graphsamp_t	values[1024];

/*
==============
SCR_DebugGraph
==============
*/
void SCR_DebugGraph (float value, int color)
{
	values[current&1023].value = value;
	values[current&1023].color = color;
	current++;
}

/*
==============
SCR_DrawDebugGraph
==============
*/
static void SCR_DrawDebugGraph (void)
{
	int		a, x, y, w, i, h;
	float	v;
	int		color;

	//
	// draw the graph
	//
	w = scr_vrect.width;

	x = scr_vrect.x;
	y = scr_vrect.y+scr_vrect.height;
	re.DrawFill (x, y-scr_graphheight->value,
		w, scr_graphheight->value, 0.5, 0.5, 0.5);

	for (a=0 ; a<w ; a++)
	{
		i = (current-1-a+1024) & 1023;
		v = values[i].value;
		color = values[i].color;
		v = v*scr_graphscale->value + scr_graphshift->value;

		if (v < 0)
			v += scr_graphheight->value * (1+(int)(-v/scr_graphheight->value));
		h = (int)v % (int)scr_graphheight->value;
		re.DrawFill (x+w-1-a, y - h, 1,	h, color, color, color);
	}
}

/*
===============================================================================

CENTER PRINTING

===============================================================================
*/

char		scr_centerstring[1024];
float		scr_centertime_start;	// for slow victory printing
float		scr_centertime_off;
int			scr_center_lines;
int			scr_erase_center;

/*
==============
SCR_CenterPrint

Called for important messages that should stay in the center of the screen
for a few moments
==============
*/
void SCR_CenterPrint (const char *str)
{
	const char *s;

	strncpy (scr_centerstring, str, sizeof(scr_centerstring)-1);
	scr_centertime_off = scr_centertime->value;
	scr_centertime_start = cl.time;

	// count the number of lines for centering
	scr_center_lines = 1;
	s = str;
	while (*s)
	{
		if (*s == '\n')
			scr_center_lines++;
		s++;
	}
}

/*
==============
SCR_CenterPrintf
==============
*/
void SCR_CenterPrintf( const char *fmt, ... )
{
	va_list		argptr;
	char		msg[MAXPRINTMSG];

	va_start (argptr,fmt);
	Q_vsnprintf(msg, sizeof(msg), fmt, argptr);
	va_end (argptr);
	msg[sizeof(msg)-1] = 0;

	SCR_CenterPrint( msg );
}

static void SCR_DrawCenterString (void)
{
	char	*start;
	int		l;
	int		j;
	int		x, y;
	int		remaining;

// the finale prints the characters one at a time
	remaining = 9999;

	scr_erase_center = 0;
	start = scr_centerstring;

	if (scr_center_lines <= 4)
		y = viddef.height*0.35;
	else
		y = 48;

	do
	{
		// scan the width of the line
		for (l=0 ; l < ( viddef.width / 8 ) ; l++)
			if (start[l] == '\n' || !start[l])
				break;
		x = (viddef.width - l*8)/2;
		SCR_AddDirtyPoint (x, y);
		for (j=0 ; j<l ; j++, x+=8)
		{
			re.DrawChar (x, y, start[j]);
			if (!remaining--)
				return;
		}
		SCR_AddDirtyPoint (x, y+8);

		y += 8;

		while (*start && *start != '\n')
			start++;

		if (!*start)
			break;
		start++;		// skip the \n
	} while (1);
}

static void SCR_CheckDrawCenterString (void)
{
	scr_centertime_off -= cls.renderFrametime;

	if (scr_centertime_off <= 0)
		return;

	SCR_DrawCenterString ();
}

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

/*
=================
SCR_CalcVrect

Sets scr_vrect, the coordinates of the rendered window
=================
*/
static void SCR_CalcVrect (void)
{
	int		size;

	// bound viewsize
	if (scr_viewsize->value < 40)
		Cvar_Set ("viewsize","40");
	if (scr_viewsize->value > 110)
		Cvar_Set ("viewsize","110");

	if (scr_viewsize->value > 100)
		size = 100;
	else
		size = scr_viewsize->value;

	scr_vrect.width = viddef.width*size/100;
	scr_vrect.width &= ~7;

	scr_vrect.height = viddef.height*size/100;
	scr_vrect.height &= ~1;

	scr_vrect.x = (viddef.width - scr_vrect.width)/2;
	scr_vrect.y = (viddef.height - scr_vrect.height)/2;
}


/*
=================
SCR_SizeUp_f

Keybinding command
=================
*/
static void SCR_SizeUp_f (void)
{
	Cvar_SetValue ("viewsize",scr_viewsize->value+10);
}


/*
=================
SCR_SizeDown_f

Keybinding command
=================
*/
static void SCR_SizeDown_f (void)
{
	Cvar_SetValue ("viewsize",scr_viewsize->value-10);
}

/*
=================
SCR_Sky_f

Set a specific sky and rotation speed
=================
*/
static void SCR_Sky_f (void)
{
	float	rotate;
	vec3_t	axis;

	if (Cmd_Argc() < 2)
	{
		Com_Printf ("Usage: sky <basename> <rotate> <axis x y z>\n");
		return;
	}
	if (Cmd_Argc() > 2)
		rotate = Sinatof(Cmd_Argv(2));
	else
		rotate = 0;
	if (Cmd_Argc() == 6)
	{
		axis[0] = Sinatof(Cmd_Argv(3));
		axis[1] = Sinatof(Cmd_Argv(4));
		axis[2] = Sinatof(Cmd_Argv(5));
	}
	else
	{
		axis[0] = 0;
		axis[1] = 0;
		axis[2] = 1;
	}

	re.SetSky (Cmd_Argv(1), rotate, axis);
}

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

/*
==================
SCR_Init
==================
*/
void SCR_Init (void)
{
	scr_viewsize = Cvar_Get ("viewsize", "100", CVAR_ARCHIVE);
	scr_conspeed = Cvar_Get ("scr_conspeed", "3", 0);
	scr_showturtle = Cvar_Get ("scr_showturtle", "0", 0);
	scr_showpause = Cvar_Get ("scr_showpause", "1", 0);
	scr_centertime = Cvar_Get ("scr_centertime", "2.5", 0);
	scr_printspeed = Cvar_Get ("scr_printspeed", "8", 0);
	scr_netgraph = Cvar_Get ("netgraph", "0", 0);
	scr_timegraph = Cvar_Get ("timegraph", "0", 0);
	scr_debuggraph = Cvar_Get ("debuggraph", "0", 0);
	scr_graphheight = Cvar_Get ("graphheight", "32", 0);
	scr_graphscale = Cvar_Get ("graphscale", "1", 0);
	scr_graphshift = Cvar_Get ("graphshift", "0", 0);
	scr_drawall = Cvar_Get ("scr_drawall", "0", 0);

	scr_showhud = Cvar_Get ("scr_showhud", "1", 0);
	scr_dialogtime = Cvar_Get ("scr_dialogtime", "2.5", 0);

	/* FS: cl_draw*** friends */
	cl_drawfps = Cvar_Get ("cl_drawfps", "0", CVAR_ARCHIVE);
	cl_drawfps->description = "Draw FPS counter on the screen.";
	cl_drawtime = Cvar_Get ("cl_drawtime", "0", CVAR_ARCHIVE);
	cl_drawtime->description = "Draw current time on the screen.  1 -  Military time.  2 - AM/PM.";
	cl_drawuptime = Cvar_Get ("cl_drawuptime", "0", CVAR_ARCHIVE);
	cl_drawuptime->description = "Draw current uptime on the screen.  1 - Current level time.  2 - Total uptime of Sin.";
	cl_drawaltcolours = Cvar_Get ("cl_drawaltcolours", "0", CVAR_ARCHIVE);
	cl_drawaltcolours->description = "Draw yellow text instead of white for the cl_draw*** CVARs.";

//
// register our commands
//
	Cmd_AddCommand ("timerefresh",SCR_TimeRefresh_f);
	Cmd_AddCommand ("loading",SCR_Loading_f);
	Cmd_AddCommand ("sizeup",SCR_SizeUp_f);
	Cmd_AddCommand ("sizedown",SCR_SizeDown_f);
	Cmd_AddCommand ("sky",SCR_Sky_f);

	Com_RegisterUpdateFunctions( &SCR_UpdateStatus, &SCR_UpdateStatusString, &SCR_IncrementStatusCount );
	scr_initialized = true;
}


/*
==============
SCR_DrawNet
==============
*/
static void SCR_DrawNet (void)
{
	if (cls.netchan.outgoing_sequence - cls.netchan.incoming_acknowledged < CMD_BACKUP-1)
		return;

	re.DrawPic (scr_vrect.x+64, scr_vrect.y, "net");
}

/*
==============
SCR_DrawPause
==============
*/
static void SCR_DrawPause (void)
{
	int		w, h;

	if (!scr_showpause->value)		// turn off for screenshots
		return;

	if (!cl_paused->value)
		return;

	re.DrawGetPicSize (&w, &h, "pause");
	re.DrawPic ((viddef.width-w)/2, viddef.height/2 + 8, "pause");
}

/*
==============
SCR_DrawLoading
==============
*/
#if 0
static void SCR_DrawLoading (void)
{
	int		w, h;

	if (!scr_draw_loading)
		return;

	scr_draw_loading = false;
	re.DrawFadeScreen( 0,0,0,0 );
	re.DrawStretchPic (0, 0, viddef.width, viddef.height, "sin_loadback");
	re.DrawGetPicSize (&w, &h, "loadgame");
	re.DrawPic ((viddef.width-w)/2, (viddef.height-h)/2, "loadgame");
}
#endif

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

/*
==================
SCR_RunConsole

Scroll it up or down
==================
*/
void SCR_RunConsole (void)
{
// decide on the height of the console
	if (cls.key_dest == key_console)
		scr_conlines = 0.5;		// half screen
	else
		scr_conlines = 0;				// none visible

	if (scr_conlines < scr_con_current)
	{
		scr_con_current -= scr_conspeed->value*cls.renderFrametime;
		if (scr_conlines > scr_con_current)
			scr_con_current = scr_conlines;

	}
	else if (scr_conlines > scr_con_current)
	{
		scr_con_current += scr_conspeed->value*cls.renderFrametime;
		if (scr_conlines < scr_con_current)
			scr_con_current = scr_conlines;
	}

}

/*
==================
SCR_DrawConsole
==================
*/
static void SCR_DrawConsole (void)
{
	Con_CheckResize ();

	if (cls.state == ca_disconnected || cls.state == ca_connecting)
	{	// forced full screen console
		Con_DrawConsole (1.0);
		return;
	}

	if (cls.state != ca_active || !cl.refresh_prepped)
	{	// connected, but can't render
		Con_DrawConsole (0.5);
		re.DrawFill (0, viddef.height/2, viddef.width, viddef.height/2, 0, 0, 0);
		return;
	}

	if (scr_con_current)
	{
		Con_DrawConsole (scr_con_current);
	}
	else
	{
		if (cls.key_dest == key_game || cls.key_dest == key_message ||
			cls.key_dest == key_console3d || cls.key_dest == key_menu3d)
		if ( !(cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_STATS ) || !scr_showhud->value || (scr_viewsize->value > 100) )
               Con_DrawNotify ();	// only draw notify in game and the player does not have stats up
	}
}

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

/*
================
SCR_BeginLoadingPlaque
================
*/
void SCR_BeginLoadingPlaque (void)
{
	S_StopAllSounds ();
	cl.sound_prepped = false;		// don't play ambients
	CDAudio_Stop ();
	if (cls.disable_screen)
		return;
	if (developer->value || scr_skip_loading->intValue) /* FS */
		return;

	if (cl.cinematictime > 0)
		scr_draw_loading = 2;	// clear to black first
	else
		scr_draw_loading = 1;
	SCR_UpdateScreen ();

	cls.disable_servercount = cl.servercount;
}

/*
================
SCR_EndLoadingPlaque
================
*/
void SCR_EndLoadingPlaque (void)
{
	cls.disable_screen = 0;
   scr_draw_loading = 0;
	Con_ClearNotify ();

   if ( cl.attractloop )
      cls.intermission_active = false;
}

/*
================
SCR_Loading_f
================
*/
void SCR_Loading_f (void)
{
	SCR_BeginLoadingPlaque ();
}

/*
================
SCR_TimeRefresh_f
================
*/
int entitycmpfnc( const void *a, const void *b )
{
	/*
	** all other models are sorted by model then skin
	*/
	if ( ((entity_t *)a)->model == ((entity_t *)b)->model ) {
		return ((intptr_t) ((entity_t *)a)->skin - (intptr_t) ((entity_t *)b)->skin);
	}
	return ((intptr_t) ((entity_t *)a)->model - (intptr_t) ((entity_t *)b)->model);
}

void SCR_TimeRefresh_f (void)
{
	int		i;
	int		start, stop;
	float	time;

	if ( cls.state != ca_active )
		return;

	start = Sys_Milliseconds ();

	if (Cmd_Argc() == 2)
	{	// run without page flipping
		re.BeginFrame( 0 );
		V_ResolveOffspring();

		for (i=0 ; i<128 ; i++)
		{
			cl.refdef.viewangles[1] = i/128.0*360.0;
			re.RenderFrame (&cl.refdef);
		}
		re.EndFrame();
	}
	else
	{
		for (i=0 ; i<128 ; i++)
		{
			cl.refdef.viewangles[1] = i/128.0*360.0;

			re.BeginFrame( 0 );
			V_ResolveOffspring();
			re.RenderFrame (&cl.refdef);
			re.EndFrame();
		}
	}

	stop = Sys_Milliseconds ();
	time = (stop-start)/1000.0;
	Com_Printf ("%f seconds (%f fps)\n", time, 128/time);
}

/*
=================
SCR_AddDirtyPoint
=================
*/
void SCR_AddDirtyPoint (int x, int y)
{
	if (x < scr_dirty.x1)
		scr_dirty.x1 = x;
	if (x > scr_dirty.x2)
		scr_dirty.x2 = x;
	if (y < scr_dirty.y1)
		scr_dirty.y1 = y;
	if (y > scr_dirty.y2)
		scr_dirty.y2 = y;
}

void SCR_DirtyScreen (void)
{
	SCR_AddDirtyPoint (0, 0);
	SCR_AddDirtyPoint (viddef.width-1, viddef.height-1);
}

/*
==============
SCR_TileClear

Clear any parts of the tiled background that were drawn on last frame
==============
*/
static void SCR_TileClear (void)
{
	int		i;
	int		top, bottom, left, right;
	dirty_t	clear;

	if (scr_drawall->value)
		SCR_DirtyScreen ();	// for power vr or broken page flippers...

	if (scr_con_current == 1.0)
		return;		// full screen console

	if (scr_viewsize->value >= 100)
		return;		// full screen rendering

	if (cl.cinematictime > 0)
		return;		// full screen cinematic

	// erase rect will be the union of the past three frames
	// so tripple buffering works properly
	clear = scr_dirty;
	for (i=0 ; i<2 ; i++)
	{
		if (scr_old_dirty[i].x1 < clear.x1)
			clear.x1 = scr_old_dirty[i].x1;
		if (scr_old_dirty[i].x2 > clear.x2)
			clear.x2 = scr_old_dirty[i].x2;
		if (scr_old_dirty[i].y1 < clear.y1)
			clear.y1 = scr_old_dirty[i].y1;
		if (scr_old_dirty[i].y2 > clear.y2)
			clear.y2 = scr_old_dirty[i].y2;
	}

	scr_old_dirty[1] = scr_old_dirty[0];
	scr_old_dirty[0] = scr_dirty;

	scr_dirty.x1 = 9999;
	scr_dirty.x2 = -9999;
	scr_dirty.y1 = 9999;
	scr_dirty.y2 = -9999;

	// don't bother with anything convered by the console)
	top = scr_con_current*viddef.height;
	if (top >= clear.y1)
		clear.y1 = top;

	if (clear.y2 <= clear.y1)
		return;		// nothing disturbed

	top = scr_vrect.y;
	bottom = top + scr_vrect.height-1;
	left = scr_vrect.x;
	right = left + scr_vrect.width-1;

	if (clear.y1 < top)
	{	// clear above view screen
		i = clear.y2 < top-1 ? clear.y2 : top-1;
		re.DrawTileClear (clear.x1 , clear.y1,
			clear.x2 - clear.x1 + 1, i - clear.y1+1, "backtile");
		clear.y1 = top;
	}
	if (clear.y2 > bottom)
	{	// clear below view screen
		i = clear.y1 > bottom+1 ? clear.y1 : bottom+1;
		re.DrawTileClear (clear.x1, i,
			clear.x2-clear.x1+1, clear.y2-i+1, "backtile");
		clear.y2 = bottom;
	}
	if (clear.x1 < left)
	{	// clear left of view screen
		i = clear.x2 < left-1 ? clear.x2 : left-1;
		re.DrawTileClear (clear.x1, clear.y1,
			i-clear.x1+1, clear.y2 - clear.y1 + 1, "backtile");
		clear.x1 = left;
	}
	if (clear.x2 > right)
	{	// clear left of view screen
		i = clear.x1 > right+1 ? clear.x1 : right+1;
		re.DrawTileClear (i, clear.y1,
			clear.x2-i+1, clear.y2 - clear.y1 + 1, "backtile");
		clear.x2 = right;
	}

}


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


#define STAT_MINUS		10	/* num frame for '-' stats digit */
static const char *sb_nums[2][11] =
{
	{"num_0", "num_1", "num_2", "num_3", "num_4", "num_5",
	"num_6", "num_7", "num_8", "num_9", "num_minus"},
	{"anum_0", "anum_1", "anum_2", "anum_3", "anum_4", "anum_5",
	"anum_6", "anum_7", "anum_8", "anum_9", "anum_minus"}
};

#define	ICON_WIDTH	24
#define	ICON_HEIGHT	24
#define	CHAR_WIDTH	16
#define	ICON_SPACE	8

/*
===============
SCR_TouchPics

Allows rendering code to cache all needed sbar graphics
===============
*/
void SCR_TouchPics (void)
{
	int i, j;
	char temp[128];

	for (i=0 ; i<2 ; i++)
		for (j=0 ; j<11 ; j++)
			re.RegisterPic (sb_nums[i][j]);

	if (crosshair->value)
	{
		if (crosshair->value > 5 || crosshair->value < 0)
			crosshair->value = 1;

		Com_sprintf (crosshair_pic, sizeof(crosshair_pic), "ch%i", (int)(crosshair->value));
		Com_sprintf (temp, sizeof(temp), "%s_off", crosshair_pic );
		re.DrawGetPicSize (&crosshair_width, &crosshair_height, temp);
		if (!crosshair_width)
			crosshair_pic[0] = 0;
		Com_sprintf (zoom_crosshair_pic, sizeof(zoom_crosshair_pic), "ch%i_zoom", (int)(crosshair->value));
		Com_sprintf (temp, sizeof(temp), "%s_off", zoom_crosshair_pic );
		re.DrawGetPicSize (&zoom_crosshair_width, &zoom_crosshair_height, temp);
		if (!zoom_crosshair_width)
			zoom_crosshair_pic[0] = 0;
	}
}

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

/*
==================
SCR_UpdateScreen

This is called every frame, and can also be called explicitly to flush
text to the screen.
==================
*/
void SCR_UpdateScreen (void)
{
	int numframes;
	int i;
	float separation[2] = { 0, 0 };

 	/*
	** range check cl_camera_separation so we don't inadvertently fry someone's
	** brain
	*/
	if ( cl_stereo_separation )
	{
		if ( cl_stereo_separation->value > 1.0 )
			Cvar_SetValue( "cl_stereo_separation", 1.0 );
		else if ( cl_stereo_separation->value < 0 )
			Cvar_SetValue( "cl_stereo_separation", 0.0 );
	}

	// Stereo glasses
	if ( cl_stereo && cl_stereo->value )
	{
		numframes = 2;
		separation[0] = -cl_stereo_separation->value / 2;
		separation[1] =  cl_stereo_separation->value / 2;
	}
	else
	{
		separation[0] = 0;
		separation[1] = 0;
		numframes = 1;
	}

	if (!scr_initialized || !con.initialized || cls.disable_screen)
		return;				// not initialized yet

	// just before entering the game
	if ( cls.state == ca_connected && cl.refresh_prepped )
	{
		// Draw the loading screen before returning
		if ( scr_draw_loading || cls.intermission_active )
		{
			// Update the loading screen if it's active
			CONSOLE_DrawLoadingStatus();
			// Draw the generic menu
			MENU_DrawGeneric();
			re.EndFrame();
			return;
		}
		// If we're not in developer, and the console is not down.
		// This will allow us to toggle the console when we are
		// connected, but not really in the game yet.
		if ( (!developer->value) && (!scr_skip_loading->intValue) && ( cls.key_dest != key_console ) ) /* FS */
			return;
	}

	for ( i = 0; i < numframes; i++ )
	{
		re.BeginFrame( separation[i] );

		//
		// Took out cinematic code here
		//
		// if a cinematic is supposed to be running, handle menus
		// and console specially
		if (cl.cinematictime > 0)
		{
			SCR_DrawCinematic();
			continue;
		}

		if ( scr_draw_loading || cls.intermission_active )
		{
			// Update the loading screen if it's active
			CONSOLE_DrawLoadingStatus ();
			// Draw the generic menu
			MENU_DrawGeneric();
			re.EndFrame();
			return;
		}

		// do 3D refresh drawing, and then update the screen
		SCR_CalcVrect ();

		// clear any dirty part of the background
		SCR_TileClear ();

		// Render the game scene
		V_RenderView ( separation[i] );

		// HUD
		if ( scr_showhud->value )
		{
			if ( (cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_STATS ) )
			{
				CONSOLE_DrawHUD ();
			}
		}
		// Mission computer
		if ( (cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_MISSIONCPU ) )
		{
			CONSOLE_DrawMissionComputer ();
		}
		// Spectator infor
		if (cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_SPECTATOR )
		{
			CONSOLE_DrawSpectator ();
		}
		// Generic overlays
		if ( (cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_OVERLAY ) )
		{
			CONSOLE_DrawGenericOverlay ();
		}
		// Draw deathmatch scores
		if (cl.frame.playerstate.stats[STAT_LAYOUTS] & DRAW_SCORES )
		{
			CONSOLE_DrawScores ();
		}

		// Draw dialog
		CONSOLE_DrawDialog ();

		// Draw print overlays
		CONSOLE_DrawPrintScreen ();

		// Draw networking status icon
		SCR_DrawNet ();

		// Check to see if there is a centerstring and update if necessary
		SCR_CheckDrawCenterString ();

		// Debug graphs
		if (scr_timegraph->value)
			SCR_DebugGraph (cls.netFrametime*300, 0);

		if (scr_debuggraph->value || scr_timegraph->value || scr_netgraph->value)
			SCR_DrawDebugGraph ();

		// Draw cinematic fades
		CONSOLE_DrawFades();

		// Draw pause plaque
		SCR_DrawPause ();

		// Draw the console
		SCR_DrawConsole ();

		/* FS: cl_draw*** friends */
		SCR_DrawTime ();
		SCR_DrawUptime();
		SCR_ShowFPS ();

		// Draw the menu
		MENU_Draw ();

		// Draw the generic menu
		MENU_DrawGeneric ();

		// Draw a global layout
		CONSOLE_DrawGlobalLayout ();

#if 0
		// Draw the loading plaque
		SCR_DrawLoading ();
#endif
	}

	// Do the buffer swap
	re.EndFrame();
}

void SCR_UpdateStatus(int current, int total, const char *str)
{
	cl_status_current  = current;
	cl_status_total    = total;
	cl_status_string2  = str;
	SCR_UpdateScreen();
}

void SCR_IncrementStatusCount(int i)
{
	cl_status_current += i;
	SCR_UpdateScreen();
}

void SCR_UpdateStatusString(const char *str)
{
	cl_status_string1  = str;
	SCR_UpdateScreen();
}
