Can I use OpenGL for off-screen rendering?

I want to try to create a simple program that takes a 3D model and turns it into an image. Is there a way to use OpenGL to render an image and put it in a variable that contains the image, rather than displaying the image? I do not want to see that I am rendering, I just want to save it. Is there any way to do this with OpenGL?

+4
source share
2 answers

I assume that you know how to draw material on the screen using OpenGL, and you wrote a function like drawStuff to do this.

, , ; 512512. , , , . OpenGL .

const int width = 512;
const int height = 512;

, ; , 1118321.

GLuint color;
GLuint depth;
GLuint fbo;

FBO ; , , . FBO, - , , :

glGenTextures(1, &color);
glBindTexture(GL_TEXTURE_2D, color);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);

glGenRenderbuffers(1, &depth);
glBindRenderbuffer(GL_RENDERBUFFER, depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth);
glBindFramebuffer(GL_FRAMEBUFFER, 0);

, ( ), , , FBO, . 6 :

  • glGenTextures ; OpenGL - , .
  • glBindTexture , GL_TEXTURE_2D; , , .
  • , 4- 5- , OpenGL.
  • glBindTexture . - drawStuff, , , OpenGL, , .

, - :

if (offscreen)
    glBindFramebuffer(GL_FRAMEBUFFER, fbo);
else
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

drawStuff();

if (offscreen)
    saveToFile();

, true, drawStuff fbo, .

saveToFile . , . , Mac OS X C :

void saveImage()
{
    void *imageData = malloc(width * height * 4);

    glBindTexture(GL_TEXTURE_2D, color);
    glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA, GL_UNSIGNED_BYTE, imageData);

    CGContextRef contextRef = CGBitmapContextCreate(imageData, width, height, 8, 4 * width, CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB), kCGImageAlphaPremultipliedLast);
    CGImageRef imageRef = CGBitmapContextCreateImage(contextRef);
    CFURLRef urlRef = (CFURLRef)[NSURL fileURLWithPath:@"/Users/JohnDoe/Documents/Output.png"];
    CGImageDestinationRef destRef = CGImageDestinationCreateWithURL(urlRef, kUTTypePNG, 1, NULL);
    CGImageDestinationAddImage(destRef, imageRef, nil);        
    CFRelease(destRef);

    glBindTexture(GL_TEXTURE_2D, 0);

    free(imageData);
}
+7

, . (FBO), . , , , .

+6

All Articles