seveland's picture

Access Pixel Buffer Object Data without "unsafe" code

I am writing a simple color-picking scheme to use allow mouse selection using an off-screen frame buffer. I have it working using a double-pixel buffer, but I have only been able to get it working using "unsafe" pointers to access the color information in the PBO. Is there another way to read the color data, or am I stuck with "unsafe" pointers?

Here's a snippet of my PBO access code...

                uint readPBO, mapPBO;
		byte r, g, b, a;
		int screenX, screenY; // current coordinates of the mouse pointer
                // int w, h are the current GLControl width and height, of course
                if (useFirstPBO)
			readPBO = _PBOid[0];
			mapPBO = _PBOid[1];
			useFirstPBO = false;
			readPBO = _PBOid[1];
			mapPBO = _PBOid[0];
			useFirstPBO = true;
		GL.BindBuffer(BufferTarget.PixelPackBuffer, readPBO);
		GL.ReadPixels(0, 0, w, h, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero);
		GL.BindBuffer(BufferTarget.PixelPackBuffer, mapPBO);
		IntPtr ptr = GL.MapBuffer(BufferTarget.PixelPackBuffer, BufferAccess.ReadWrite);
                screenX = (int) currentMouseX;
		screenY = h - ((int) currentMouseY);
		if (screenX >= 0 && screenX < w && screenY >= 0 && screenY < h)
			pixelIndex = (screenX + screenY * w) * 4;
				byte* VideoMemory = (byte*) ptr.ToPointer();
				b = VideoMemory[pixelIndex];
				g = VideoMemory[pixelIndex + 1];
				r = VideoMemory[pixelIndex + 2];
				a = VideoMemory[pixelIndex + 3];
				byte[] temp = new byte[] { r, g, b, a };
		                ans = BitConverter.ToUInt32(temp, 0);
		GL.BindBuffer(BufferTarget.PixelPackBuffer, 0);


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

You can use the Marshal.ReadByte() to read directly IntPtr without casting to an unsafe pointer first.