Skip to content

Instantly share code, notes, and snippets.

@admsyn
Last active January 16, 2018 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save admsyn/54663fb81234aa987f8491c5d457fb84 to your computer and use it in GitHub Desktop.
Save admsyn/54663fb81234aa987f8491c5d457fb84 to your computer and use it in GitHub Desktop.
NSView to ofTexture
void viewToTex(NSView * view, ofTexture& tex) {
// this is based on listing 11-3 at
// https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_texturedata/opengl_texturedata.html
NSBitmapImageRep * bitmap = [view bitmapImageRepForCachingDisplayInRect:view.visibleRect];
[view cacheDisplayInRect:view.visibleRect toBitmapImageRep:bitmap];
glPixelStorei(GL_UNPACK_ROW_LENGTH, bitmap.bytesPerRow / bitmap.samplesPerPixel);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (tex.getTextureData().textureID == 0) {
throw std::runtime_error("texture isn't allocated");
}
glBindTexture(GL_TEXTURE_RECTANGLE_ARB, tex.getTextureData().textureID);
glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
if(!bitmap.isPlanar && (bitmap.samplesPerPixel == 3 || bitmap.samplesPerPixel == 4)) {
glTexImage2D(GL_TEXTURE_RECTANGLE_ARB,
0,
bitmap.samplesPerPixel == 4 ? GL_RGBA8 : GL_RGB8,
bitmap.pixelsWide,
bitmap.pixelsHigh,
0,
bitmap.samplesPerPixel == 4 ? GL_RGBA : GL_RGB,
GL_UNSIGNED_BYTE,
bitmap.bitmapData);
} else {
throw std::runtime_error("unsupported bitmap data");
}
// hail-mary reset back to default
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
}
NSView * view = ...;
renderedTexture = ofTexture();
renderedTexture.allocate(512, 512, GL_RGBA);
viewToTex(view, renderedTexture);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment