OpenGL - 3점을 찍어 삼각형 그리기


설명


마우스로 폼위의 3점을 찍으면 그 점을 꼭지점으로 삼각형을 그린다.




소스설명


설명은 주석으로 대체하였다.


parameter

#define POINTS 100
 
GLfloat pos[POINTS][2];//point array
GLfloat Width = 600.0//form width
GLfloat Height = 600.0//form height
GLint n = 0//number of points


렌더링함수

/// <summary>
/// Renders the scene.
/// </summary>
void RenderScene(void)
{
	int i;
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(100);//red color
	glPointSize(10.0f);//size 10
	glEnableClientState(GL_VERTEX_ARRAY);// enable array
 
	
	for (i = 0i < 3i++)
	{
		glBegin(GL_POINTS);//dot
		glVertex2f(pos[i][0], pos[i][1]);//dot position
	}
	if (i>2 && (pos[2][0] != 0))//draw triangle when the number of points are greater than two
	{
		glBegin(GL_TRIANGLES);
		glVertex2f(pos[0][0], pos[0][1]);
		glVertex2f(pos[1][0], pos[1][1]);
		glVertex2f(pos[2][0], pos[2][1]);
	}
	glEnd();
	glFlush();//flush
}


마우스 클릭 이벤트

/// <summary>
/// Mouse button event.
/// </summary>
/// <param name="button">The button.</param>
/// <param name="state">The state.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
void mousebutton(int buttonint stateint xint y)
{
	if (button == GLUT_LEFT_BUTTON)
	{
		if (state == GLUT_DOWN)
		{
			pos[n][0] = x / Width;
			pos[n][1] = (Height - y) / Height;
			if (n > 2)//when then number of points greater than two
			{
				pos[n % 3][0] = pos[n][0];//x
				pos[n % 3][1] = pos[n][1];//y
			}
			n++;
			RenderScene();//rendering
		}
	}
}


윈폼 크기 변경 함수

/// <summary>
/// winform size changed
/// </summary>
/// <param name="w">width</param>
/// <param name="h">height</param>
void ChangeSize(int wint h)
{
	GLfloat asepectRatio;
 
	Width = w;
	Height = h;
 
	if (Height == 0)
		Height = 1;
	glViewport(00wh);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	gluOrtho2D(0.01.00.01.0);
}
void main(int argcchar *argv[])
{
	glutInit(&argcargv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
	glutInitWindowSize(WidthHeight);
	glutInitWindowPosition(00);
	glutCreateWindow("ex2");
	glClearColor(1.0f1.0f1.0f1.0f);
	glMatrixMode(GL_PROJECTION);
 
	glutDisplayFunc(RenderScene);
	glutReshapeFunc(ChangeSize);
	glutMouseFunc(mousebutton);
 
	glutMainLoop();
}


결과물


'3점'에 해당되는 글 1건

1 →