Caffe2 - C++ API
A deep learning, cross platform ML framework
GLPBO.cc
1 
2 #include "GLPBO.h"
3 
4 #include "caffe2/core/logging.h"
5 
6 GLPBO::~GLPBO() {
7  if (pboId != 0) {
8  gl_log(GL_LOG, "deleting PBO buffer %d\n", pboId);
9  glDeleteBuffers(1, &pboId);
10  pboId = 0;
11  }
12  if (pboFrameBuffer != 0) {
13  gl_log(GL_LOG, "deleting PBO frame buffer %d\n", pboFrameBuffer);
14  glDeleteFramebuffers(1, &pboFrameBuffer);
15  pboFrameBuffer = 0;
16  }
17 }
18 
19 GLPBO* GLPBO::pboContext = NULL;
20 
21 GLPBO* GLPBO::getContext() {
22  if (pboContext == NULL) {
23  pboContext = new GLPBO();
24  }
25  return pboContext;
26 }
27 
28 void GLPBO::mapTextureData(GLuint _textureId,
29  GLsizei _width,
30  GLsizei _height,
31  GLsizei _stride,
32  GLsizei _channels,
33  const GLTexture::Type& _type,
34  std::function<void(const void* buffer,
35  size_t width,
36  size_t height,
37  size_t stride,
38  size_t channels,
39  const GLTexture::Type& type)> process) {
40  GLint defaultFramebuffer = 0;
41  glGetIntegerv(GL_FRAMEBUFFER_BINDING, &defaultFramebuffer);
42 
43  if (pboFrameBuffer == 0) {
44  glGenFramebuffers(1, &pboFrameBuffer);
45  gl_log(GL_VERBOSE, "created PBO frame buffer %d\n", pboFrameBuffer);
46  }
47 
48  glBindFramebuffer(GL_FRAMEBUFFER, pboFrameBuffer);
49 
50  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _textureId, 0);
51 
52  int fbs = glCheckFramebufferStatus(GL_FRAMEBUFFER);
53  if (fbs != GL_FRAMEBUFFER_COMPLETE) {
54  std::stringstream errmsg;
55  errmsg << ": Frame buffer incomplete: " << fbs;
56  throw std::runtime_error(errmsg.str());
57  }
58 
59  if (pboId == 0) {
60  glGenBuffers(1, &pboId);
61  gl_log(GL_VERBOSE, "created PBO buffer %d\n", pboId);
62  }
63  glBindBuffer(GL_PIXEL_PACK_BUFFER, pboId);
64 
65  size_t buffer_size = _stride * _height * _channels * _type.dataSize();
66 
67  if (buffer_size > pboSize) {
68  LOG(INFO) << "Allocating PBO of capacity " << buffer_size;
69 
70  glBufferData(GL_PIXEL_PACK_BUFFER, buffer_size, NULL, GL_DYNAMIC_READ);
71  pboSize = buffer_size;
72  }
73 
74  glReadBuffer(GL_COLOR_ATTACHMENT0);
75  glReadPixels(0, 0, _stride, _height, _type.format, _type.type, 0);
76 
77  GLhalf* ptr = (GLhalf*)glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, buffer_size, GL_MAP_READ_BIT);
78 
79  if (ptr) {
80  process(ptr, _width, _height, _stride, _channels, _type);
81  } else {
82  std::stringstream errmsg;
83  errmsg << ": glMapBufferRange using PBO incomplete";
84  throw std::runtime_error(errmsg.str());
85  }
86 
87  // Unmap buffer
88  glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
89  glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
90 
91  // Bind to the default FrameBuffer
92  glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer);
93 }
Definition: GLPBO.h:7