Question by
sparkkhuang · Feb 24 at 03:19 AM ·
renderingshader programminggameplaycompute shaderhlsl
How to use the compute shader to sample the depth map under URP and calculate the corresponding world coordinates?
Here is my code, but the output is always weird.
compute shader:
#pragma kernel WaterSplash
struct Particle
{
float3 position;
float lifetime;
float showScale;
};
RWStructuredBuffer<Particle> particleBuffer;
RWTexture2D<float4> DeptTex;
float deltaTime;
float width;
float4x4 vpMatrixInv;
[numthreads(8,8,1)]
void WaterSplash(uint3 id : SV_DispatchThreadID)
{
float dept = DeptTex[id.xy].r;
#if defined(UNITY_REVERSED_Z)
dept = 1 - dept;
#endif
float4 ndc = float4(id.x * 2 - 1, id.y * 2 - 1, dept * 2 - 1, 1);
float4 worldPos = mul(vpMatrixInv, ndc);
worldPos /= worldPos.w;
int index = id.x * width + id.y;
particleBuffer[index].position = float3(worldPos.x, worldPos.y, worldPos.z);
particleBuffer[index].lifetime += deltaTime;
if (particleBuffer[index].lifetime > 2)
{
particleBuffer[index].lifetime = 0;
}
particleBuffer[index].showScale = dept;
}
C# pass parameter code :
computeShader.SetMatrix("vpMatrixInv", vpMatrixMake());
private Matrix4x4 vpMatrixMake()
{
Matrix4x4 projMat = GL.GetGPUProjectionMatrix(Camera.projectionMatrix, false);
var vpMatrix = projMat * Camera.worldToCameraMatrix;
//var vpMatrix = Camera.projectionMatrix * Camera.worldToCameraMatrix;
return vpMatrix.inverse;
}
computeShader.SetTexture(mComputeShaderKernelID, "DeptTex", DepthRT);
private void DepthMake()
{
RenderTexture tempRT;
tempRT = RenderTexture.GetTemporary(width, height, 0, DepthRT.format);
tempRT.filterMode = FilterMode.Point;
Graphics.Blit(Shader.GetGlobalTexture("_CameraDepthTexture"), tempRT);
Graphics.CopyTexture(tempRT, 0, 0, DepthRT, 0, 0);
}
width = Screen.width;
height = Screen.height;
computeShader.Dispatch(mComputeShaderKernelID, width / 8, height / 8, 1);
The calculated coordinates are always columnar, like:
Can anyone see where I am wrong? (:
7177.png
(207.6 kB)
Comment
Your answer
Follow this Question
Related Questions
Custom shader samples pixels per-texture rather than from the screen 1 Answer
Shader Graph Editor fails to open shaders 0 Answers
How can I read in the actual elements from an Append Compute Buffer? 2 Answers
How do I generate and compile a compute shader in the editor? 0 Answers
Unity Game mode overlapping frames,Unity Gamemode ¿render overlapping? 0 Answers