HBAO_Common.cginc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #ifndef HBAO_COMMON_INCLUDED
  2. #define HBAO_COMMON_INCLUDED
  3. #include "UnityCG.cginc"
  4. inline float FetchRawDepth(float2 uv) {
  5. return SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv * _TargetScale.xy);
  6. }
  7. inline float LinearizeDepth(float depth) {
  8. // References: https://docs.unity3d.com/Manual/SL-PlatformDifferences.html
  9. #if ORTHOGRAPHIC_PROJECTION
  10. #if UNITY_REVERSED_Z
  11. depth = 1 - depth;
  12. #endif // UNITY_REVERSED_Z
  13. float linearDepth = _ProjectionParams.y + depth * (_ProjectionParams.z - _ProjectionParams.y); // near + depth * (far - near)
  14. #else
  15. float linearDepth = LinearEyeDepth(depth);
  16. #endif // ORTHOGRAPHIC_PROJECTION
  17. return linearDepth;
  18. }
  19. inline float3 FetchViewPos(float2 uv) {
  20. float depth = LinearizeDepth(FetchRawDepth(uv));
  21. #if ORTHOGRAPHIC_PROJECTION
  22. return float3((uv * _UVToView.xy + _UVToView.zw), depth);
  23. #else
  24. return float3((uv * _UVToView.xy + _UVToView.zw) * depth, depth);
  25. #endif
  26. }
  27. inline float3 MinDiff(float3 P, float3 Pr, float3 Pl) {
  28. float3 V1 = Pr - P;
  29. float3 V2 = P - Pl;
  30. return (dot(V1, V1) < dot(V2, V2)) ? V1 : V2;
  31. }
  32. inline float3 FetchViewNormals(float2 uv, float2 delta, float3 P) {
  33. #if NORMALS_RECONSTRUCT
  34. float3 Pr, Pl, Pt, Pb;
  35. Pr = FetchViewPos(uv + float2(delta.x, 0));
  36. Pl = FetchViewPos(uv + float2(-delta.x, 0));
  37. Pt = FetchViewPos(uv + float2(0, delta.y));
  38. Pb = FetchViewPos(uv + float2(0, -delta.y));
  39. float3 N = normalize(cross(MinDiff(P, Pr, Pl), MinDiff(P, Pt, Pb)));
  40. #else
  41. #if NORMALS_CAMERA
  42. float3 N = DecodeViewNormalStereo(UNITY_SAMPLE_SCREENSPACE_TEXTURE(_CameraDepthNormalsTexture, uv * _TargetScale.xy));
  43. #else
  44. float3 N = UNITY_SAMPLE_SCREENSPACE_TEXTURE(_CameraGBufferTexture2, uv * _TargetScale.xy).rgb * 2.0 - 1.0;
  45. N = mul((float3x3)_WorldToCameraMatrix, N);
  46. #endif // NORMALS_CAMERA
  47. N = float3(N.x, -N.yz);
  48. #endif // NORMALS_RECONSTRUCT
  49. return N;
  50. }
  51. inline float3 FetchViewNormals(float2 uv, float2 delta) {
  52. float3 P = FetchViewPos(uv);
  53. return FetchViewNormals(uv, delta, P);
  54. }
  55. #endif // HBAO_COMMON_INCLUDED