- Home /
Screen-space Shader Debug
I'm trying to write a fragment shader that works in screen-space, to produce an even gradient across the screen. I've made some progress thanks to this Unity Answer, but for some reason my shader's gradient doesn't stretch the whole width of the screen, only some of the middle. Here's an image of the effect.
Here is the shader. It could be shorter but I've tried to keep it verbose for clarity for myself.
Shader "Debug/AllInput" {
SubShader {
Pass {
CGPROGRAM
#include "UnityCG.cginc"
#pragma vertex vert
#pragma fragment frag
struct vertexInput {
float4 vertex : POSITION;
};
struct vertexOutput {
float4 pos : SV_POSITION;
float4 vertPos : TEXCOORD5;
};
vertexOutput vert(vertexInput input) {
vertexOutput output;
output.pos = mul(UNITY_MATRIX_MVP, input.vertex);
// We're now in clipspace, ranging from -1,-1,-1, to 1,1,1
float4 clipSpace = mul(UNITY_MATRIX_MVP, input.vertex);
// Convert from -1~1 to 0~1
clipSpace.xy = 0.5*(clipSpace.xy+1.0);
// Convert from 0~1 to 0~1280 (etc.)
// Skip this, 0~1 more useful for debug rendering
//clipSpace.xy *= _ScreenParams.xy;
output.vertPos = clipSpace;
return output;
}
float4 frag(vertexOutput input) : COLOR {
return float4(input.vertPos.x, input.vertPos.x, input.vertPos.x, 1.0);
}
ENDCG
}
}
}
Could someone tell me why this is?
I'm guessing the output of the transform isn't what you are expecting. Try just plotting intput.vertPos.x, input.vertPos.x/1000 etc - see what you are actually getting. No pic BTW!
Answer by Ben Humphreys · May 03, 2013 at 06:49 AM
I went back to the original post, and I think I fixed it. I was forgetting to divide by the width of the screen, to convert from Clip Space which is square, to the actual perspective. It's mentioned as "perspective divide" in the CG article from the previous Answer
So the calculations now look like:
float4 clipSpace = mul(UNITY_MATRIX_MVP, input.vertex);
clipSpace.xy /= clipSpace.w;
clipSpace.xy = 0.5*(clipSpace.xy+1.0);
Thanks again everyone :)
Optimized for mad:
clipSpace.xy = clipSpace.xy * 0.5f + 0.5f;
(Always multiply then add, in that order)
just curious, why would that be an optimization? is there any difference in execution speed?
Because multiplication is adding same value multiple times. Sometimes it can be just bitwise offset, and modern compilers optimise such operations. That's why @psantoki called it "for mad" - just because it takes place, but not so much helpful )
Your answer

Follow this Question
Related Questions
Show only specific part of UI.Image 0 Answers
cast shadow - export lightmap from 3ds max to unity 2 Answers
Culling part of a sprite in Sprite Manager 2 1 Answer
How to remove URP from the project 0 Answers