#include <v_lib.h>

void gl_lsmooth(vboolean on)
{
	if(on)
	{
    	glLineWidth(2.0f);
    	glEnable(GL_LINE_SMOOTH);
    	glEnable(GL_BLEND);
    	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	}
	else
	{
    	glLineWidth(1.0f);
    	glDisable(GL_LINE_SMOOTH);
    	glDisable(GL_BLEND);
	}
}

void draw_grid(vec_t left,vec_t top,vec_t right,vec_t bottom,int nx,int ny)
{
	int i;
	vec2_t p1, p2, dp;
	vec2_t top_left, top_right, bottom_left, bottom_right;
	vec2Set(top_left,left,top);
	vec2Set(top_right,right,top);
	vec2Set(bottom_left,left,bottom);
	vec2Set(bottom_right,right,bottom);
	gl_lsmooth(false);

	glBegin(GL_QUADS);
		glColor3f(1,1,1);
		VGL_VERTEX2V(bottom_left);
		glColor3f(1,0,0);
		VGL_VERTEX2V(bottom_right);
		glColor3f(0,1,0);
		VGL_VERTEX2V(top_right);
		glColor3f(0,0,1);
		VGL_VERTEX2V(top_left);
	glEnd(); /* GL_QUADS */

	/* gl_lsmooth(true); */

	vec2Copy(p1,top_left);
	vec2Copy(p2,bottom_left);
	vec2Sub(dp,top_right,top_left);
	vec2Scale(dp,dp,1.0f / (nx+1));
	glBegin(GL_LINES);
		glColor4f(0.9f,0.9f,0.9f,0.7f);
		for(i=0;i<nx;i++)
		{
			vec2Add(p1,p1,dp);
			vec2Add(p2,p2,dp);
			VGL_VERTEX2V(p1);
			VGL_VERTEX2V(p2);
		}
	glEnd(); /* GL_LINES */
}


void draw_scene(void)
{
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    glScalef(.9f,.9f,1);
    draw_grid(-100,100,100,-100,3,3);
    glPopMatrix();
}

int main()
{
	input_record_t r;
    logStartConsoleLog();
    logUpperLevel(LOG_TRACE);
	vglCreateWindow("ndraw",0,0,640,480);
	if(vglGetCurrentWindow() == LIBV_INVALID_HANDLE)
		return -1;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-100,100,-100,100,-1,1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
	glClearColor(0,0,0,1);
	glDisable(GL_DEPTH_TEST);
    do
    {
    	while(!vglPending())
		{
			draw_scene();
     		vglSwapBuffers();
      		timeDelay(30);
		}
        vglNextEvent(&r);
	} while(r.event!=ev_key_down);
	vglDestroyWindow(vglGetCurrentWindow());
	memPrintStats();
	return 0;
}
