Hello I'm new to shader's logic in unity and currently I'm learning GrabPass. I saw several implementations of GrabPass and they contained this code: Code (CSharp): v2f vert(appdata_t v) { v2f o; ... o.vertex = UnityObjectToClipPos(v.vertex); o.uvgrab.xy = (float2(o.vertex.x, o.vertex.y) + o.vertex.w) * 0.5; ... } Could someone please explain, why after applying MVP matrix we do some calculations on X and Y of uvgrab? And of course explain this math. Thanks! P.S. Why no tutorial explain math of shader they using?
Clip space is a type of screen space coordinate system. The range of clip.xy for what appears on screen is values between -clip.w and +clip.w. If you want to understand why, look up “homogeneous clip space coordinates”. The short version is if you’re using an orthographic camera, the w value is always 1.0. So the above code is taking x and y, and rescaling a -1.0 to 1.0 range to a 0.0 to 1.0 range. But in a way that’ll only work with an orthographic camera. With a perspective camera, w is the world scale view depth. So the above code without also passing the clip space w value and dividing the xy in the fragment by that w value will at worst produce complete junk, or at best a warped image. Again, look up “homogeneous coordinates” to find out why. The short version: Just use the example code in Unity’s documentation. https://docs.unity3d.com/Manual/SL-GrabPass.html
First of all, @bgolus I want to say thanks to you , because I'm learning shaders logic surfing this forum and reading your comments. Second, I know homogeneous coordinates and thats why I asked this question. Several tutorials used line 5 in their code with perspective camera, looks like without understanding what they are doing. This broke my brain. Why do we need to rescale -1..1 to 0..1 in the shader context? Where the profit is?
Unless there's a bit of code also passing the w component, yeah, it's broken. If it is passing the w component, then it's fine. It's rescaling to 0.0 to 1.0 because it's a UV for sampling the grab pass texture, which is a copy of the render target.