简体   繁体   English

从fragmenthader返回浮子

[英]Return floats from fragmentshader

For an application I need to create a depth-image of a mesh. 对于应用程序,我需要创建网格的深度图像。 Basically I want a image, where each pixel tells the distance between the camera center and the intersection point. 基本上我想要一张图像,其中每个像素都指示相机中心和相交点之间的距离。 I choose to do this task with OpenGL, so that most of the computation can be done on the GPU instead of the CPU. 我选择使用OpenGL执行此任务,以便大多数计算可以在GPU而不是CPU上完成。

Here is my code for the vertex-shader. 这是我的顶点着色器代码。 It computes the real-world coordinate of the intersection point and stores the coordinates in a varying vec4 , so that I have access to it in the fragment-shader. 它计算相交点的实际坐标,并将坐标存储在varying vec4 ,以便我可以在片段着色器中访问它。

varying vec4 verpos;
void main(void)
{
    gl_Position = ftransform();
    verpos = gl_ModelViewMatrix*gl_Vertex;
}

And here the code for the fragment-shader. 这里是片段着色器的代码。 In the fragment-shader I use these coordinates to compute the eulidean distance to the origin (0,0,0) using pythagoras. 在片段着色器中,我使用这些坐标来使用毕达哥拉斯计算到原点(0,0,0)的欧式距离。 To get access to the computed value on the CPU, my plan is to store the distance as a color using gl_FragColor , and extract the color values using glReadPixels(0, 0, width, height, GL_RED, GL_FLOAT, &distances[0]); 为了访问CPU上的计算值,我的计划是使用gl_FragColor将距离存储为颜色,并使用glReadPixels(0, 0, width, height, GL_RED, GL_FLOAT, &distances[0]);提取颜色值glReadPixels(0, 0, width, height, GL_RED, GL_FLOAT, &distances[0]);

varying vec4 verpos;
void main() 
{ 
    float x = verpos.x;
    float y = verpos.y;
    float z = verpos.z;

    float depth = sqrt(x*x + y*y + z*z) / 5000.0;
    gl_FragColor = vec4(depth, depth, depth, 1.0);
}

The problem is, that I receive the results only in the precision of 0.003921569 ( =1/255 ). 问题是,我仅以0.003921569=1/255 0.003921569的精度接收结果。 The resulting values contain for instance 0.364705890, 0.364705890, 0.364705890, 0.364705890, 0.368627459, 0.368627459, 0.368627459 . 结果值包含例如0.364705890, 0.364705890, 0.364705890, 0.364705890, 0.368627459, 0.368627459, 0.368627459 Most of the values in a row are exactly the same, and then there is a jump of 1/255. 连续的大多数值都完全相同,然后跳了1/255。 So somewhere inbetween gl_FragColor and glReadPixels OpenGL converts the floats to 8 bits and afterwards converts them back to float. 因此,OpenGL在gl_FragColorglReadPixels某个gl_FragColor将浮点数转换为8位,然后再将其转换回浮点数。

How can I extract distance-values as float without loosing precision? 如何在不损失精度的情况下将距离值提取为float?

Attach a R32F or R16F texture to a FBO and render to it. 将R32F或R16F纹理附加到FBO并渲染。 Then extract the pixels with glGetTexImage2D() like you would do with glReadPixels() . 然后使用glGetTexImage2D()提取像素,就像使用glReadPixels()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM