This is the first tutorial on GLUT. In this tutorial I am going to show you how to draw basic 2D shapes like triangle and rectangles using OpenGL. Although OpenGL is basically made for 3D programming, drawing 2D shapes gives the basic outline and introduction to OpenGL and gives the idea about how to start drawing objects in OpenGL. The following example draws a triangle and a rectangle to a GLUT window. Drawing rectangle and triangle is very easy on OpenGL because it provides a function for it. glBegin(GL_TRIANGLES) and glBegins(GL_QUADS) are functions for drawing triangle and rectangle respectively. We have to give a 3D coordinates of each vertex and OpenGL automatically draws the object as specified by the attribute passed to function glBegin. For example if we call glBegin(GL_QUADS) and provide coordinates of four vertices then OpenGL will draw a rectangle for us.
#include<windows.h>#include <iostream>#include <stdlib.h>#include <GL/glut.h>using namespace std;//Called when a key is pressedvoid handleKeypress(unsigned char key, int x, int y) {switch (key) {case 27: //Escape keyexit(0);}}//Initializes 3D renderingvoid initRendering() {//Makes 3D drawing work when something is in front of something elseglEnable(GL_DEPTH_TEST);}//Called when the window is resizedvoid handleResize(int w, int h) {//Tell OpenGL how to convert from coordinates to pixel valuesglViewport(0, 0, w, h);glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective//Set the camera perspectiveglLoadIdentity(); //Reset the cameragluPerspective(45.0, //The camera angle(double)w / (double)h, //The width-to-height ratio1.0, //The near z clipping coordinate200.0); //The far z clipping coordinate}//Draws the 3D scenevoid drawScene() {//Clear information from last drawglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspectiveglLoadIdentity(); //Reset the drawing perspectiveglBegin(GL_QUADS); //Begin quadrilateral coordinates//TrapezoidglVertex3f(-0.7f, -1.5f, -5.0f);glVertex3f(0.7f, -1.5f, -5.0f);glVertex3f(0.7f, -0.5f, -5.0f);glVertex3f(-0.7f, -0.5f, -5.0f);glEnd(); //End quadrilateral coordinatesglBegin(GL_TRIANGLES); //Begin triangle coordinates//TriangleglVertex3f(-0.5f, 0.5f, -5.0f);glVertex3f(-1.0f, 1.5f, -5.0f);glVertex3f(-1.5f, 0.5f, -5.0f);glEnd(); //End triangle coordinatesglutSwapBuffers(); //Send the 3D scene to the screen}int main(int argc, char** argv) {//Initialize GLUTglutInit(&argc, argv);glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);glutInitWindowSize(400, 400); //Set the window size//Create the windowglutCreateWindow("Basic Shapes - programming-technique.blogspot.com");initRendering(); //Initialize rendering//Set handler functions for drawing, keypresses, and window resizesglutDisplayFunc(drawScene);glutKeyboardFunc(handleKeypress);glutReshapeFunc(handleResize);glutMainLoop(); //Start the main loopreturn 0;}
تعليقات: 0
إرسال تعليق