Read pixels in WebGLTexture (Rendering WebGL to texture)
Asked Answered
T

1

6

I'm generating a texture on the GPU and rendering it to my own framebuffer object. It works fine and the texture is rendered to a WebGLTexture that I can pass to other shaders. However I want to access the WebGLTexture pixels in javascript. Is there a way to accomplish that?

At the moment I'm using gl.ReadPixels to read the pixels after I've drawn the texture to my framebuffer. That works fine but wouldn't it be better if I could directly access the pixels in the WebGLTextureObject?

What I'm trying to accomplish is this: I have GLSL perlin noise shader that can render high def heightmap and normal map on the GPU. I want to pass the heightmap to the CPU so that I can generate the vertices for the mesh. I could of course just position the vertices in the vertex shader but I need it in the CPU for collision detection.

I hope my question is clear. Any feedback is welcome!

Thanks!

Trishatriskelion answered 24/2, 2013 at 23:0 Comment(1)
i think this is the only solution because glGetTexImagedoes not exist. but anyway, i don't think that this is a bad solution. Probably you should think of, if it is possible to do the collision detection on GPU.Usm
I
13

You can read the pixels out of most textures by attaching them to a framebuffer.

var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) == gl.FRAMEBUFFER_COMPLETE) {
  var pixels = new Uint8Array(width * height * 4);
  gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
}
Intuitivism answered 25/2, 2013 at 10:35 Comment(3)
That's what I'm currently doing as I described in my question. I'm wondering if there's alternative way, such as reading straight from the WebGLTexture. Thanks.Pritchard
Okay, that wasn't clear from your description. "I've drawn the texture to my framebuffer". You don't have to draw the texture. You only have to attach the texture to a framebuffer and then call readPixels. Sorry for the mis-understanding. There is no other direct way in WebGL.Intuitivism
Ok thanks a lot! :-) You might want to update your answer and state that there's no other direct way available in WebGL (for others).Pritchard

© 2022 - 2024 — McMap. All rights reserved.