我正在尝试使用 CoreGL 和 Framebuffer 在 OSX 上进行渲染:似乎三角形渲染根本不起作用,而例如带有颜色的 glClear 将显示在生成的 PPM 图像中。
我已经尝试了以下代码的几种变体,但现在在我看来,这在 OSX 上是一项不可能完成的任务。
#include <stdio.h>
#include <OpenGL/OpenGL.h>
#include <Opengl/glext.h>
#include <stdlib.h>
#include <assert.h>
#include <opengl/gl3.h>
int main(int argc, const char * argv[])
{
CGLContextObj context;
CGLPixelFormatAttribute attributes[13] = {
kCGLPFAOpenGLProfile,
(CGLPixelFormatAttribute) kCGLOGLPVersion_3_2_Core,
kCGLPFAAccelerated,
kCGLPFAColorSize, (CGLPixelFormatAttribute)24,
kCGLPFAAlphaSize, (CGLPixelFormatAttribute)8,
kCGLPFADoubleBuffer,
kCGLPFASampleBuffers, (CGLPixelFormatAttribute)1,
kCGLPFASamples, (CGLPixelFormatAttribute)4,
(CGLPixelFormatAttribute) 0
};
CGLPixelFormatObj pix; CGLError errorCode; GLint num;
errorCode = CGLChoosePixelFormat( attributes, &pix, &num );
errorCode = CGLCreateContext(pix, NULL, &context);
CGLDestroyPixelFormat( pix );
errorCode = CGLSetCurrentContext( context );
// -------
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
//--------
GLuint fboid, rboid, dboid;
glGenFramebuffers( 1, &fboid );
glBindFramebuffer( GL_FRAMEBUFFER, fboid );
glGenRenderbuffers( 1, &rboid );
glBindRenderbuffer( GL_RENDERBUFFER, rboid );
glRenderbufferStorage( GL_RENDERBUFFER, GL_RGBA, 1440, 900);
glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rboid );
glBindRenderbuffer( GL_RENDERBUFFER, 0 );
glGenRenderbuffers( 1, &dboid );
glBindRenderbuffer( GL_RENDERBUFFER, dboid );
glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT, 1440, 900);
glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, dboid );
glBindRenderbuffer( GL_RENDERBUFFER, 0 );
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// --------
glBindFramebuffer( GL_FRAMEBUFFER, fboid );
static const GLfloat g_vertex_buffer_data[] = {-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f};
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
assert(glGetError()==0);
// -------
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );
glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0; 3 vertices total -> 1 triangle
glDisableVertexAttribArray(0);
// -------
errorCode = CGLFlushDrawable(context);
char data[1440*900*3];
glReadPixels(0, 0, 1440, 900, GL_BGR, GL_UNSIGNED_BYTE, &data[0]);
FILE* ff = fopen("/Users/invernizzi/pippo.ppm", "w");
char* header = "P6 1440 900 255 ";
size_t i = fwrite(header, sizeof(char), 16, ff);
i = fwrite(&data[0], sizeof(char), 1440*900*3, ff);
fclose(ff);
return 0;
}