#include <v_lib.h>

#define		T_WIDTH		512

u8_t		texture[T_WIDTH][T_WIDTH];
#define		texel(x,y,c)		(texture[(x)][(y)]=(u8_t)(c))

GLuint quad;
int frames=0;

void draw_scene()
{
	/*
	int i,j;
	for(i=0;i<T_WIDTH;i++)
	{
		for(j=0;j<T_WIDTH;j++)
			texel(j,i,(rand() % T_WIDTH) + 128);
	}
	*/
	int i;
	for(i=0;i<T_WIDTH;i++)
	{
		texel(i,rand() % T_WIDTH,(rand() % T_WIDTH) + 128);
	}

//	glTexSubImage2D(GL_TEXTURE_2D,0,0,0,T_WIDTH,T_WIDTH,GL_LUMINANCE,GL_UNSIGNED_BYTE,texture);
	glTexSubImage2D(GL_TEXTURE_2D,0,128,128,256,256,GL_LUMINANCE,GL_UNSIGNED_BYTE,texture);

	glCallList(quad);
	
	frames++;
}

vhandle_t c;

void V_CALL wt(void *param)
{
	vboolean *done = (vboolean*)param;
	c = condCreate(true);
	while(!*done)
	{
		condTimedWait(c,1000);
		printf("FPS: %d\n",frames);
		frames=0;
	}
	condDestroy(c);
	threadExit(0);
}
		
int main()
{
	int i,j;
	vhandle_t w;
	vboolean done=false;
	input_record_t r;

	for(i=0;i<T_WIDTH;i++)
		for(j=0;j<T_WIDTH;j++)
			texel(i,j,(rand() % 128) + 128);
	
    logStartConsoleLog();
    logUpperLevel(LOG_TRACE);

	vglCreateWindow("temp",0,0,512,512);

/*	vglCreateFullscreenWindow("temp",0,0,800,600); */
    
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(-1,1,-1,1,-1,1);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
    
    glTexImage2D(GL_TEXTURE_2D,0,1,T_WIDTH,T_WIDTH,0,GL_LUMINANCE,GL_UNSIGNED_BYTE,texture);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
    
	quad=glGenLists(1);
	glNewList(quad,GL_COMPILE);
		glBegin(GL_QUADS);
			glColor4f(.8f,.9f,.7f,0.5f);
			glTexCoord2f(1,1);
			glVertex2f(1,1);
			glTexCoord2f(0,1);
			glVertex2f(-1,1);
			glColor4f(.9f,.8f,.7f,0.5f);
			glTexCoord2f(0,0);
			glVertex2f(-1,-1);
			glTexCoord2f(1,0);
			glVertex2f(1,-1);
		glEnd();
	glEndList();

	glEnable(GL_TEXTURE_2D);
	
	w=threadCreate(wt,&done);
	
	do
	{
		while(!vglPending())
		{
			draw_scene();
			vglSwapBuffers();
		}
		vglNextEvent(&r);
	} while(r.event!=ev_key_down || r.first_code!=key_escape);

	/* Catch watcher */
	done=true;
	condPulse(c);
	threadJoin(w,NULL);
	
	vglDestroyWindow(vglGetCurrentWindow());
    memPrintStats();
    return 0;
}
