Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved In HDRP's compute shader how to correctly translate a World Position to ScreenSpace position?

Discussion in 'High Definition Render Pipeline' started by ryanflees, Apr 11, 2023.

  1. ryanflees

    ryanflees

    Joined:
    Nov 15, 2014
    Posts:
    59
    Hi. I have a compute shader that takes GameObject's world position ,and I want to get the screen space position of it for further operations. (Suppose there's only 1 camera in the scene)

    However I find it frustrating to do it.

    Code (CSharp):
    1. some includes
    2. ...
    3.  
    4. RWStructuredBuffer<float4> _TestData;
    5. float4 _WorldPos;
    6.  
    7. void CalculateScreenSpacePosition()
    8. {
    9.     float4 clipPos = ComputeClipSpacePosition(_WorldPos, UNITY_MATRIX_VP);
    10.     _TestData[0] = clipPos;
    11.  
    12.     float3 ndcPos = ComputeNormalizedDeviceCoordinatesWithZ(_WorldPos, UNITY_MATRIX_VP);
    13.     _TestData[1] = float4(ndcPos, 1);
    14.  
    15.     float4 screenPos = ComputeScreenPos(clipPos, _ProjectionParams.x);
    16.     _TestData[2] = screenPos;
    17. }
    18.  
    19. [numthreads(1,1,1)]
    20. void CSMain (uint3 id : SV_DispatchThreadID)
    21. {
    22.      CalculateScreenSpacePosition();
    23. }
    I did some tests and use a vector buffer to retrieve the results .
    However the positions don't look correct.

    upload_2023-4-11_19-39-18.png
    the elements in the array of the pic: clip pos, ndc pos, screen pos

    And I try to get the native matrices it doesn't feel very correct.

    upload_2023-4-11_19-41-6.png
    Code (CSharp):
    1.  _MatrixData[0] = UNITY_MATRIX_V;
    Above is the UNITY_MATRIX_V matrix I got from compute shader. It sort of lacks of position infomrations.

    However I manually log the Camera's worldToCameraMatrix in c# code, it gives correct result with positions informations.

    I can't find any related resources or guide in google/GPT/source code in HDRP to go further.
    So I need help with how to translate a world pos into screen space pos correctly in compute shader.
     
  2. ryanflees

    ryanflees

    Joined:
    Nov 15, 2014
    Posts:
    59
    OK, I've found that you need to translate the world pos to a relative WS as HDRP use camera as center for rendering.

    Code (CSharp):
    1.     float3 worldPosRelative = GetCameraRelativePositionWS(_WorldPos);
    2.     float4 clipPos = ComputeClipSpacePosition(worldPosRelative, UNITY_MATRIX_VP);
    3.     float3 ndcPos = ComputeNormalizedDeviceCoordinatesWithZ(worldPosRelative, UNITY_MATRIX_VP);
    4.  
    5.     float4 positionSS = 0;
    6.     positionSS.xy = ndcPos.xy / _ScreenSize.zw;