OpenGL Program to create a cylinder

Algorithm (Cylinder):

Step 1: Start
Step 2: Let (h, k) be the central axis of cylinder.
Step 3: Let ‘r’ be the radius of cylinder.
Step 4: For each pair (h, k), find all the points on the circle with (h, k) as center.
Step 5: Display these points which make a circle.
Step 6: Increment the y-coordinate by some constant to draw the next adjacent circle.
Step 7: Repeat Step 6
Step 8: Stop  

Algorithm (parallelepiped)
Step 1: Start
Step 2: Let (x1, y1), (x2, y1), (x1, y2), (x2, y2) be the four vertices of a rectangle.
Step 3: Draw a rectangle with these values using a line loop primitive.
Step 4: Increment all the eight values by some constant value to draw next adjacent rectangle.
Step 5: RepeatStep 4
Step 6: Stop

				
					#include<stdio.h> 
#include<GL/glut.h> 
#include<math.h> 
GLint xc,yc,r,i,n=50,num_segments=50; 
GLint a,b,c,d; 
void DrawCircle(float cx, float cy, float r, int num_segments) 
{ 
glColor3f(1.0,0.0,0.0); 
glBegin(GL_LINE_LOOP); 
for(int ii = 0; ii < num_segments; ii++) 
{ 
float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle
float x = r * cos(theta);//calculate the x component 
float y = r * sin(theta);//calculate the y component 
glVertex2f(x + cx, y + cy);//output vertex 
} 
glEnd(); 
} 
void cylinder_draw() 
{ 
for(i=0;i<n;i+=3) 
{ 
DrawCircle(xc,yc+i,r,num_segments); 
} 
} 
void parapiped(int x1,int y1,int x2,int y2) 
{ 
glColor3f(0.0,0.0,1.0); 
glPointSize(2.0); 
glBegin(GL_LINE_LOOP); 
glVertex2i(x1,y1); 
glVertex2i(x2,y1); 
glVertex2i(x2,y2); 
glVertex2i(x1,y2); 
glEnd(); 
} 
void parapiped_draw() 
{ 
for(i=0;i<n;i+=2) 
{ 
parapiped(a+i,b+i,c+i,d+i); 
} 
} 
void init(void) 
{ 
glClearColor(1.0,1.0,1.0,1.0); 
glMatrixMode(GL_PROJECTION); 
gluOrtho2D(0.0,499.0,0.0,499.0); 
} 
void display(void) 
{ 
glClear(GL_COLOR_BUFFER_BIT); 
cylinder_draw(); 
parapiped_draw(); 
glFlush(); 
} 
void main(int argc, char ** argv) 
{ 
printf("ENTER THE CENTER & RADIUS OF CIRCLE"); 
scanf("%d%d%d",&xc,&yc,&r); 
printf("ENTER POINTS FOR quadrilateral "); 
scanf("%d%d%d%d",&a,&b,&c,&d);// x1, y1 , x2, y2 
glutInit(&argc,argv); 
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); 
glutInitWindowPosition(0,0); 
glutInitWindowSize(500,500); 
glutCreateWindow("CYLINDER_PARALLELOPIPED DISPLAY BY EXTRUDING CIRCLE & QUADRILATERAL"); 
init(); 
glutDisplayFunc(display); 
glutMainLoop(); 
} 
				
			

Leave a Reply