Directx 线性深度到世界位置

Directx 线性深度到世界位置,directx,shader,hlsl,ogre3d,Directx,Shader,Hlsl,Ogre3d,我有以下片段和顶点着色器 HLSL码 ` //顶点着色器 //----------------------------------------------------------------------------------- void mainVP( float4 position : POSITION, out float4 outPos : POSITION, out float2 outDepth : TEXCOORD0, uniform f

我有以下片段和顶点着色器

HLSL码 ` //顶点着色器 //-----------------------------------------------------------------------------------

void mainVP( 
   float4 position     : POSITION, 
   out float4 outPos   : POSITION, 
   out float2 outDepth : TEXCOORD0, 
   uniform float4x4 worldViewProj,
   uniform float4 texelOffsets,
   uniform float4 depthRange)   //Passed as float4(minDepth, maxDepth,depthRange,1 / depthRange)
{ 
    outPos = mul(worldViewProj, position);
    outPos.xy += texelOffsets.zw * outPos.w;
    outDepth.x = (outPos.z - depthRange.x)*depthRange.w;//value [0..1]
    outDepth.y = outPos.w; 
} 

// Fragment shader  
void mainFP( float2 depth: TEXCOORD0, out float4 result : COLOR) { 
    float finalDepth = depth.x;
    result = float4(finalDepth, finalDepth, finalDepth, 1);
}
`

此着色器生成深度贴图

然后必须使用此深度贴图重建深度值的世界位置。我已经搜索了其他帖子,但是没有一个帖子使用我正在使用的公式来存储深度。唯一类似的帖子如下

因此,我很难使用深度贴图和相应深度的x和y坐标重建点


我需要一些帮助来构造着色器,以获取特定纹理坐标处深度的世界视图位置。

看起来您并没有规范化深度。试试这个。在VS中,执行以下操作:

outDepth.xy=outPos.zw

在PS中,要渲染深度,可以执行以下操作:

float finalDepth=depth.x/depth.y

下面是一个函数,用于从深度纹理中提取特定像素的视图空间位置。我假设您正在渲染与屏幕对齐的四边形,并在像素着色器中执行位置提取

// Function for converting depth to view-space position
// in deferred pixel shader pass.  vTexCoord is a texture
// coordinate for a full-screen quad, such that x=0 is the
// left of the screen, and y=0 is the top of the screen.
float3 VSPositionFromDepth(float2 vTexCoord)
{
    // Get the depth value for this pixel
    float z = tex2D(DepthSampler, vTexCoord);  
    // Get x/w and y/w from the viewport position
    float x = vTexCoord.x * 2 - 1;
    float y = (1 - vTexCoord.y) * 2 - 1;
    float4 vProjectedPos = float4(x, y, z, 1.0f);
    // Transform by the inverse projection matrix
    float4 vPositionVS = mul(vProjectedPos, g_matInvProjection);  
    // Divide by w to get the view-space position
    return vPositionVS.xyz / vPositionVS.w;  
}

有关一种更高级的方法,可以减少所涉及的计算数量,但需要使用和一种特殊的方式渲染屏幕对齐的四边形,请参见。

不过,您的解决方案似乎不适用于线性深度。我有一个着色器按照你说的方式工作,但是我需要另一个着色器处理线性深度。