CameraMotionVectors.shader 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. Shader "Hidden/kMotion/CameraMotionVectors"
  2. {
  3. SubShader
  4. {
  5. Pass
  6. {
  7. Cull Off
  8. ZWrite On
  9. ZTest Always
  10. HLSLPROGRAM
  11. // Required to compile gles 2.0 with standard srp library
  12. #pragma prefer_hlslcc gles
  13. #pragma exclude_renderers d3d11_9x
  14. #pragma target 2.0
  15. #pragma vertex vert
  16. #pragma fragment frag
  17. // -------------------------------------
  18. // Includes
  19. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
  20. #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl"
  21. #if defined(USING_STEREO_MATRICES)
  22. float4x4 _PrevViewProjMStereo[2];
  23. #define _PrevViewProjM _PrevViewProjMStereo[unity_StereoEyeIndex]
  24. #else
  25. #define _PrevViewProjM _PrevViewProjMatrix
  26. #endif
  27. // -------------------------------------
  28. // Structs
  29. struct Attributes
  30. {
  31. uint vertexID : SV_VertexID;
  32. };
  33. struct Varyings
  34. {
  35. float4 position : SV_POSITION;
  36. };
  37. // -------------------------------------
  38. // Vertex
  39. Varyings vert(Attributes input)
  40. {
  41. Varyings output;
  42. output.position = GetFullScreenTriangleVertexPosition(input.vertexID);
  43. return output;
  44. }
  45. // -------------------------------------
  46. // Fragment
  47. half4 frag(Varyings input, out float outDepth : SV_Depth) : SV_Target
  48. {
  49. // Calculate PositionInputs
  50. half depth = LoadSceneDepth(input.position.xy).x;
  51. outDepth = depth;
  52. half2 screenSize = _ScreenSize.zw;
  53. PositionInputs positionInputs = GetPositionInput(input.position.xy, screenSize, depth, UNITY_MATRIX_I_VP, UNITY_MATRIX_V);
  54. // Calculate positions
  55. float4 previousPositionVP = mul(_PrevViewProjM, float4(positionInputs.positionWS, 1.0));
  56. float4 positionVP = mul(UNITY_MATRIX_VP, float4(positionInputs.positionWS, 1.0));
  57. previousPositionVP.xy *= rcp(previousPositionVP.w);
  58. positionVP.xy *= rcp(positionVP.w);
  59. // Calculate velocity
  60. float2 velocity = (positionVP.xy - previousPositionVP.xy);
  61. #if UNITY_UV_STARTS_AT_TOP
  62. velocity.y = -velocity.y;
  63. #endif
  64. // Convert velocity from Clip space (-1..1) to NDC 0..1 space
  65. // Note it doesn't mean we don't have negative value, we store negative or positive offset in NDC space.
  66. // Note: ((positionVP * 0.5 + 0.5) - (previousPositionVP * 0.5 + 0.5)) = (velocity * 0.5)
  67. return half4(velocity.xy * 0.5, 0, 0);
  68. }
  69. ENDHLSL
  70. }
  71. }
  72. }