Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read pixels in WebGLTexture (Rendering WebGL to texture)

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!

like image 864
Jón Trausti Arason Avatar asked Feb 24 '13 23:02

Jón Trausti Arason


People also ask

How is texture mapping implemented in WebGL?

Texture mapping maps a location in a 2D image to a location on a 3D triangle. WebGL uses texture coordinates to perform this mapping. As with so many other aspects of graphics, texture coordinates are percentages. The notation for texture coordinates uses (s,t) to represent an image location.

How many textures WebGL?

WebGL provides a minimum of 8 texture units; the first of these is gl. TEXTURE0 .

What is texture in WebGL?

In WebGL, texture coordinates are usually input to the vertex shader as an attribute of type vec2. They are communicated to the fragment shader in a varying variable. Often, the vertex shader will simply copy the value of the attribute into the varying variable.

What is a frame buffer WebGL?

In WebGL, a framebuffer is a data structure that organizes the memory resources that are needed to render an image. A WebGL graphics context has a default framebuffer, which is used for the image that appears on the screen. The default framebuffer is created by the call to canvas.


1 Answers

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);
}
like image 56
gman Avatar answered Oct 21 '22 03:10

gman