//example robot program //www.timestocome.com //to compile under mac osx gcc -framework OpenGL -framework GLUT -o robot robot.c #include #define BASE_HEIGHT 2.0 #define BASE_RADIUS 1.0 #define LOWER_ARM_HEIGHT 5.0 #define LOWER_ARM_WIDTH 0.5 #define UPPER_ARM_HEIGHT 5.0 #define UPPER_ARM_WIDTH 0.5 typedef float point [3]; static GLfloat theta[] = {0.0, 0.0, 0.0}; static GLint axis = 0; GLUquadricObj *p; void base(){ glPushMatrix(); //rotate to align w/ y axis glRotatef(-90.0, 1.0, 0.0, 0.0); //angle, x, y, z //cylinder aligned w/ z axis render w/ 5 slices for base and length gluCylinder(p, BASE_RADIUS, BASE_RADIUS, BASE_HEIGHT, 15, 10);//pointer, base radius, top radius, height, slices, stacks glPopMatrix(); } void upper_arm(){ glPushMatrix(); glTranslatef(0.0, 0.5*LOWER_ARM_HEIGHT, 0.0); glScalef(UPPER_ARM_WIDTH, UPPER_ARM_HEIGHT, UPPER_ARM_WIDTH); glutWireCube(1.0); glPopMatrix(); } void lower_arm(){ glPushMatrix(); glTranslatef(0.0, 0.5*UPPER_ARM_HEIGHT, 0.0); glScalef(LOWER_ARM_WIDTH, LOWER_ARM_HEIGHT, LOWER_ARM_WIDTH); glutWireCube(1.0); glPopMatrix(); } void display(void){ //accumulate modelview matrix as we traverse tree glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glColor3f(1.0, 0.0, 0.0); glRotatef(theta[0], 0.0, 1.0, 0.0); base(); glTranslatef(0.0, BASE_HEIGHT, 0.0); glRotatef(theta[1], 0.0, 0.0, 1.0); lower_arm(); glTranslatef(0.0, LOWER_ARM_HEIGHT, 0.0); glRotatef(theta[2], 0.0, 0.0, 1.0); upper_arm(); glFlush(); glutSwapBuffers(); } void mouse(int btn, int state, int x, int y){ //left button increases joint angle, right decreases if(btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN){ theta[axis] += 5.0; if(theta[axis] > 360.0){ theta[axis] -= 360.0; } } if(btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN){ theta[axis] -= 5.0; if(theta[axis] < 360.0){ theta[axis] += 360.0; } } display(); } void menu(int id){ //select which angle to change or quit if(id == 1) axis = 0; if(id == 2) axis = 1; if(id == 3) axis = 2; if(id == 4) axis = 3; } void myReshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if(w <=h ){ glOrtho(-10.0, 10.0, -5.0*(GLfloat)h/(GLfloat)w, 15*(GLfloat)h/(GLfloat)w, -10.0, 10.0); }else{ glOrtho(-10.0*(GLfloat)w/(GLfloat)h, 10.0*(GLfloat)w/(GLfloat)h, -5.0, 15.0, 10.0, 10.0); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void myinit(){ glClearColor(1.0, 1.0, 1.0, 1.0); glColor3f(1.0, 0.0, 0.0); p = gluNewQuadric(); //allocate object gluQuadricDrawStyle(p, GLU_LINE); //wireframe rendering } void main(int argc, char**argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize( 500, 500); glutCreateWindow("robot"); myinit(); glutReshapeFunc(myReshape); glutDisplayFunc(display); glutMouseFunc(mouse); glutCreateMenu(menu); glutAddMenuEntry("base", 1); glutAddMenuEntry("lower arm", 2); glutAddMenuEntry("upper arm", 3); glutAddMenuEntry("quit" , 4); glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); }