How can I read the depth buffer in WebGL?

前端 未结 5 1051
逝去的感伤
逝去的感伤 2021-01-05 08:01

Using the WebGL API, how can I get a value from the depth buffer, or in any other way determine 3D coordinates from screen coordinates (i.e. to find a location clicked on),

5条回答
  •  Happy的楠姐
    2021-01-05 08:30

    Several years have passed, these days the WEBGL_depth_texture extension is widely available... unless you need to support IE.

    General usage:

    Preparation:

    1. Query the extension (required)
    2. Allocate a separate color and depth texture (gl.DEPTH_COMPONENT)
    3. Combine both textures in to a single framebuffer (gl.COLOR_ATTACHMENT0, gl.DEPTH_ATTACHMENT)

    Rendering:

    1. Bind the framebuffer, render your scene (usually a simplified version)
    2. Unbind the framebuffer, pass the depth texture to your shaders and read it like any other texture:

      texPos.xyz = (gl_Position.xyz / gl_Position.w) * 0.5 + 0.5;
      float depthFromZBuffer = texture2D(uTexDepthBuffer, texPos.xy).x;
      

提交回复
热议问题