How do I render a .obj file (in 3d)? And how do I add color to that? I’m on an OS X, and using XCode 4. Here’s my little ‘test lab’.
#include <GLUT/glut.h>
#include <iostream>
void render(void);
void keyboard(unsigned char c, int x, int y);
void mouse(int button, int state, int x, int y);
int main(int argc, char ** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(500, 500);
glutCreateWindow("Simple GLUT Application");
glutDisplayFunc(render);
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMainLoop();
}
void keyboard(unsigned char c, int x, int y) {
if (c == 27){
exit(0);
}
}
void mouse(int button, int state, int x, int y) {
if (button == GLUT_RIGHT_BUTTON){
exit(0);
}
}
void render(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//RENDER STUFF HERE
glBegin(GL_POLYGON);
glVertex3f( 0.0, -0.8, 0.5);
glVertex3f( 0.0, 0.2, 0.5);
glVertex3f( 0.5, 0.8, -0.5);
glVertex3f( 0.5, -0.2, -0.5);
glEnd();
glutSwapBuffers();
}
OpenGL is a low level 3D API. It doesn’t have high level features like loading model files. So to render a .obj file you’ll write code to load the data yourself and then write OpenGL code that draws the polygons you’ve loaded.
There are a few ways to add colors and textures to the OpenGL primitives you draw. Your current code uses OpenGL in ‘immediate mode’, and the immediate mode method of adding color is to set the color using
glColor*()functions before producing a vertex.In the last few years there have been some significant changes to the OpenGL API. OpenGL tutorials you find online frequently cover the older methods of using OpenGL. I would strongly recommend picking up the latest edition of the book OpenGL SuperBible: Comprehensive Tutorial and Reference. It covers modern usage of OpenGL (i.e., a non-immediate mode) in detail, including a chapter on using OpenGL with OS X’s native windowing API, Cocoa.
Although the 5th edition (the latest at the time of this writing) of the OpenGL Superbible was written somewhat before the new OpenGL stuff was supported in OS X, the new features have since been added. You’ll need to read Apple’s docs on enabling the “OpenGL Core Profile” in Cocoa or OS X’s implementation of GLUT to use them.