title: OpenGL reading back buffer quickly
body: <p>I'm trying to read the contents of the back-buffer into a buffer of my own. <code>glReadPixels</code> by itself is way too slow and drops my FPS from 50 to 30.</p>
  
  <p>So I decided to try the "asynchronous" read with a PBuffer but it crashes.</p>
  
  <p>My code is as follows:</p>
  
  <p>If buffers don't exist, create them. Otherwise, read the back buffer into a specified memory location:</p>
  
  <pre><code>static int readIndex = 0;
  static int writeIndex = 1;
  static GLuint pbo[2] = {0};
  
  
  void FastCaptureBackBuffer()
  {
      //Create PBOs:
      if (!initBuffers)
      {
          initBuffers = true;
          glGenBuffers(2, pbo);
          glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[0]);
          glBufferData(GL_PIXEL_PACK_BUFFER, width * height * 1.0f, 0, GL_STREAM_READ);
  
          glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[1]);
          glBufferData(GL_PIXEL_PACK_BUFFER, width * height * 1.0f, 0, GL_STREAM_READ);
          glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
      }
  
      //swap read and write.
      writeIndex = (writeIndex + 1) % 2;
      readIndex = (writeIndex + 1) % 2;
  
      //read back-buffer.
      glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[writeIndex]);
      glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, nullptr);
      glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[readIndex]);
  
      void* data = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);
  
      if (data)
      {
          memcpy(myBuffer, data, width * height * 4);
          data = nullptr;
          glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
      }
  
      glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
  }
  </code></pre>
  
  <p>Then I do:</p>
  
  <pre><code>BOOL __stdcall HookSwapBuffers(HDC DC)
  {
      FastCaptureBackBufferPBO();
  
      return CallFunction&lt;BOOL&gt;(GetOriginalAddress(353), DC);
  }
  </code></pre>
  
  <p>So every time the application calls <code>wglSwapBuffers</code>, I read the back buffer right before it gets swapped.</p>
  
  <p>How can I read the back buffer fast? What am I missing in the above?</p>
  
  <p>Ideally I wanted to: Specify a pointer that the game could render directly to, instead of the screen, and then I can manually render the contents of the memory.</p>
  
  <p>Any other way and I end up copying the back buffer into my memory block and it's slow.</p>
  
  <p>Any ideas?</p>