如果你正在使用OSX,我强烈建议使用XCode并使用NSOpenGLView。这本书涵盖了多种可用的API相关材料。GLUT绝对是最容易上手和设置的。
如果你想使用GLUT并在终端编译,可以尝试这个方法:
#include <GLUT/glut.h>
void display(void) {
//clear white, draw with black
glClearColor(255, 255, 255, 0);
glColor3d(0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//this draws a square using vertices
glBegin(GL_QUADS);
glVertex2i(0, 0);
glVertex2i(0, 128);
glVertex2i(128, 128);
glVertex2i(128, 0);
glEnd();
//a more useful helper
glRecti(200, 200, 250, 250);
glutSwapBuffers();
}
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//set the coordinate system, with the origin in the top left
gluOrtho2D(0, width, height, 0);
glMatrixMode(GL_MODELVIEW);
}
void idle(void) {
glutPostRedisplay();
}
int main(int argc, char *argv) {
//a basic set up...
glutInit(&argc, &argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(640, 480);
//create the window, the argument is the title
glutCreateWindow("GLUT program");
//pass the callbacks
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glutMainLoop();
//we never get here because glutMainLoop() is an infinite loop
return 0;
}
然后使用以下方式进行编译:
gcc /System/Library/Frameworks/GLUT.framework/GLUT /System/Library/Frameworks/OpenGL.framework/OpenGL main.c -o myGlutApp
这样应该就可以了。不过我建议不要试图反抗XCode,与其对抗不如与其合作,这样可以节省时间和挫败感。
clang++ -framework glut -framework opengl hello.cpp
上述代码应该可以编译。但是,主函数的签名是不正确的。
<int main(int argc, char *argv)
>int main(int argc, char **argv)
这就使得 glutInit
是错误的,
<glutInit(&argc, &argv);
>glutInit(&argc, argv);
输出结果不太好,但它创建了一个窗口并展示了如何使用clang框架。感谢提供的起始文件。
尝试使用GLUT并编写一个小的C++程序。您可以使用类似macports的工具来安装必要的库。
/*
* As a first example of using OpenGL in C,
* https://math.hws.edu/graphicsbook/source/glut/first-triangle.c
*/
#include <GLUT/glut.h> // freeglut.h might be a better alternative, if available.
#include <stdio.h>
#include <stdlib.h>
void display(void) { // Display function will draw the image.
glClearColor( 0, 0, 0, 1 ); // (In fact, this is the default.)
glClear( GL_COLOR_BUFFER_BIT );
glBegin(GL_TRIANGLES);
glColor3f( 1, 0, 0 ); // red
glVertex2f( -1, -1 );
glColor3f( 0, 1, 0 ); // green
glVertex2f( 1, -1 );
glColor3f( 0, 0, 1 ); // blue
glVertex2f( 0, 1 );
glEnd();
glutSwapBuffers(); // Required to copy color buffer onto the screen.
}
int main( int argc, char** argv ) { // Initialize GLUT and
///GL 3D drawing
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE); // Use single color buffer and no depth buffer.
glutInitWindowSize(500,500); // Size of display area, in pixels.
glutInitWindowPosition(300,100); // Location of window in screen coordinates.
glutCreateWindow("Hello OpenGL"); // Parameter is window title.
glutDisplayFunc(display); // Called when the window needs to be redrawn.
glutMainLoop(); // Run the event loop! This function does not return.
// Program ends when user closes the window.
return EXIT_SUCCESS;
}