Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

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


    Nov 15, 2014
    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. ...
    4. RWStructuredBuffer<float4> _TestData;
    5. float4 _WorldPos;
    7. void CalculateScreenSpacePosition()
    8. {
    9.     float4 clipPos = ComputeClipSpacePosition(_WorldPos, UNITY_MATRIX_VP);
    10.     _TestData[0] = clipPos;
    12.     float3 ndcPos = ComputeNormalizedDeviceCoordinatesWithZ(_WorldPos, UNITY_MATRIX_VP);
    13.     _TestData[1] = float4(ndcPos, 1);
    15.     float4 screenPos = ComputeScreenPos(clipPos, _ProjectionParams.x);
    16.     _TestData[2] = screenPos;
    17. }
    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.

    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.

    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


    Nov 15, 2014
    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);
    5.     float4 positionSS = 0;
    6.     positionSS.xy = ndcPos.xy /;