gluOrtho2D作用

时间:2024-04-08 13:43:06

glViewport(0, 0, WIDTH, HEIGHT);

gluOrtho2D是用来指定屏幕区域对应的模型坐标范围,我们自己所绘制的图形的坐标必须在这个范围内,不然不能看到自己绘制的图形。

在没调用gluOthor2d函数之前,窗口的中心坐标为(0,0);调用了这个函数之后窗口的中心坐标不再是(0,0)了,窗口的左下角才是(0,0)。

在没调用gluOthor2d函数之前,坐标范围是 X:-1~1,Y:-1~1;调用了这个函数之后坐标范围是 X:0~WIDTH,Y:0~HEIGHT

gluOrtho2D作用

下面代码用两种方式画上图的两条线,一种是调用gluOthor2d方式,一种是不调用gluOthor2d

#include <GLTools.h>            // OpenGL toolkit
#include <GLShaderManager.h>    // Shader Manager Class


#define FREEGLUT_STATIC
#include <GL/glut.h>            // Windows FreeGlut equivalent

GLBatch	triangleBatch;
GLShaderManager	shaderManager;
#define WINWIDTH  500
#define WINHEIGHT 500

bool IS_USE_gluOrtho2D = false;
void ChangeSize(int w, int h)
{
	glViewport(0, 0, w, h);
}


///////////////////////////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
	if (IS_USE_gluOrtho2D)
	{
		//画分割线 ,分成四个视图区域
		glClear(GL_COLOR_BUFFER_BIT);////把窗口清除为当前颜色
		glColor3f(1.0, 0.0, 0.0);
		glViewport(0, 0, WINWIDTH, WINHEIGHT);
		glBegin(GL_LINES);
			glVertex2f(WINWIDTH / 2, 0);
			glVertex2f(WINWIDTH / 2, WINHEIGHT);
			glVertex2f(0, WINHEIGHT / 2);
			glVertex2f(WINWIDTH, WINHEIGHT / 2);
		glEnd();
	}
	else
	{
		//画分割线 ,分成四个视图区域
		glClear(GL_COLOR_BUFFER_BIT);////把窗口清除为当前颜色
		glColor3f(1.0, 0.0, 0.0);
		glViewport(0, 0, WINWIDTH, WINHEIGHT);
		glBegin(GL_LINES);
			glVertex2f(-1, 0);
			glVertex2f(1.0, 0);
			glVertex2f(0, -1.0);
			glVertex2f(0, 1.0);
		glEnd();

	}
	glFlush();

}

///////////////////////////////////////////////////////////////////////////////
// Main entry point for GLUT based programs
int main(int argc, char* argv[])
{
	gltSetWorkingDirectory(argv[0]);

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL);
	glutInitWindowPosition(500, 100);
	glutInitWindowSize(WINWIDTH, WINWIDTH);
	glutCreateWindow("Triangle");
	if (IS_USE_gluOrtho2D)
	{
		gluOrtho2D(0, WINWIDTH, 0, WINWIDTH);
	}
	glutReshapeFunc(ChangeSize);
	glutDisplayFunc(RenderScene);

	GLenum err = glewInit();
	if (GLEW_OK != err) {
		fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
		return 1;
	}

	glutMainLoop();
	return 0;
}