Wednesday, March 25, 2015

Screen Space Reflections

Here's a completely brute force implementation of screen space reflection, done in DX11.



At a high-level, screen space reflections is ray marching along pixels to see if you can use on-screen information to determine if you can calculate what the reflection should be. It's actually a fairly simple concept, but the math turns out to be fairly nasty if you aren't aware of the caveats.

Some tricky points to be aware of:
  1. You'll need to march along the ray in screen space coordinates since you want to go pixel by pixel 
    • You can optimize using a binary search, interesting blog entry on it here
  2. The depth in screen space coordinates is not linear 99% of the time.
    • This is due to the way the projection matrix is created, the depth is made logarithmic to prevent z-fighting between objects that are really close to the camera. 
  3. Because depth isn't linear in screen space, you'll actually want to do the ray intersection in view space
Now if you're reading closely, you may be wondering do I need to trace in screen space or view space? The tricky part is that you're kind of doing both. You'll want to traverse pixel by pixel, but then convert each point back to view space to calculate the intersection.

Source:

  1. Github
  2. Zipped Source

References:

  1. Morgan McGuire's post on Screen Space Reflection + Shader Source - Original source that my screen space tracing is based on
  2. Kode80's Unity 5 Implementation - Great descriptions of how you can take screen space reflections further
  3. D3D11 Samples - Original code was pulled from here