Simple Opengl Program and Its Structure
Simple Opengl Program and Its Structure
Graphics with
OpenGL
Assignment
Submitted By:
Ashwini R.
1225911
V MCA
Question: Write Open GL program in C++ to draw two intersecting line segments.
Answer:
#include<iostream.h>
# include<GL/glut.h>
void init (void)
{
glClearColor(0,0,0,0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,200.0,0.0,155.0);
}
void LineSegment(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1,0.0,1.0);
glBegin (GL_LINES);
glVertex2i(50,180);
glVertex2i(115,10);
glVertex2i(150,200);
glVertex2i(45,100);
glEnd();
glFlush();
}
int main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowPosition(50,100);
glutCreateWindow("CIA Program");
init();
glutDisplayFunc(LineSegment);
glutMainLoop();
return 0;
}
Output:
Question: Explain the structure of an Open GL program with help of an example.
Answer:
Generally OpenGL programs have a similar structure that has the following functions
main():
Specifies where the program execution should start.
init():
Sets the state variables
Species the callback functions
Opens the windows with the required properties
Sets attributes
callbacks
User defined function such as function for display, input and window functions.
Sample Outline Structure :
int main( int argc, char *argv[] )
{ // initialize the toolkit, set display mode (RGB / Single etc ..) and create window
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_SINGLE | GLUT_RGB );
glutInitWindowSize( 640, 480 );
glutInitWindowPosition( 100, 150 );
glutCreateWindow( Sample Program );
// Register the callback functions
// Do the necessary initialisation
// wait in glutMainLoop for events
}
Sample Program:
#include<iostream.h>
#include <GL/glut.h>
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv)
{
glutInit(&argc,argv);
glutCreateWindow("simple");
glutDisplayFunc(display);
glutMainLoop();
}
Output: