Thursday, December 13, 2007

Week 7

On Week 7 of Sememster 2, Computer Graphics lab session was regarding lighting. Lighting was pretty easy... just declaring the light source position, changing colours and it wasn't all that rocket science after all that.


The code:

#include "glut.h"

GLfloat angle = 0.0f;
GLfloat width = 40.0f;
GLfloat height = 30.0f;

double x = 0, y = 0;

void init(void)
{
GLfloat ambient[] = { 0.0, 0.0, 0.0, 1.0 };
GLfloat diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat position[] = { 0.0, 3.0, 2.0, 0.0 };
GLfloat lmodel_ambient[] = { 0.4, 0.4, 0.4, 1.0 };
glClearColor(0.0, 0.1, 0.1, 0.0);

//Enable Depth test
glShadeModel(GL_SMOOTH);
glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
}

void DrawCylinder()
{
GLUquadricObj *Cylinder;
GLUquadricObj *Disk;

Cylinder = gluNewQuadric();
Disk = gluNewQuadric();

glColor3f(1,0,0);
gluCylinder(Cylinder,15,15,40,32,32);

glColor3f(0,1,0);
gluDisk(Disk,0.5,1.5,32,32);
gluQuadricDrawStyle(Cylinder, GLU_FILL);
}

void MyDisplay()
{
GLfloat mat_diffuse[] = { 0.2, 0.5, 1, 1.0 };
GLfloat mat_specular[] = { 0.8, 1.0, 1.0, 1.0 };
GLfloat low_shininess[] = { 2.0 };

glEnable(GL_DEPTH);
glClear(GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT);

glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, low_shininess);

glPopMatrix();
//Lines
glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(50,0,0);
glEnd();

glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(0,50,0);
glEnd();

glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(0,0,50);
glEnd();
//End of lines

glPushMatrix();
glTranslatef(::x,::y,0);

DrawCylinder();

glutSwapBuffers();
}

void Rescale(GLsizei w, GLsizei h)
{
glViewport(0,0,w,h);
}

void Keyboard(unsigned char key, int x, int y)
{
switch(key)
{
case 'd':
::x+=10;
break;
case 'a':
::x-=10;
break;
case 'w':
::y+=10;
break;
case 's':
::y-=10;
break;
}
glutPostRedisplay();
}

void SetupRC()
{
GLfloat final = width / height;
gluPerspective(60, final, 0, 1000);
gluLookAt(90,90,90,0,1,0,0,1,0);
glFlush();
glPushMatrix();
}

void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE GLUT_RGB GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("My Pratical 7");
glutDisplayFunc(MyDisplay);
init();
glutReshapeFunc(Rescale);
glutKeyboardFunc(Keyboard);
SetupRC();
glutMainLoop();
}


Some pictures:

No comments: