[英]Linear Depth to World Position
我有以下片段和頂點着色器。
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;
}
要獲得一種更高級的方法,該方法可以減少涉及的計算數量,但需要使用視錐台視圖和呈現與屏幕對齊的四邊形的特殊方法,請參見此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.