- Home /
What is struct Input (Shader)?
Hi,
I was wondering what "struct Input" is ("tex2D" just needs for some reason to store the uvs, and it does it automatically with _MainTex in the first parameter?), and how do we know the "name" of what we define in the struct input (uv_MainTex etc.)? Is it an information we have to find in the Lambert shader?
For example :
SubShader {
Tags { "RenderType" = "Opaque" }
CGPROGRAM
#pragma surface surf Lambert
struct Input {
float2 uv_MainTex;
};
sampler2D _MainTex;
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb;
}
ENDCG
}
EDIT :
in this example, viewDir takes the viewing angle from Unity... so what's inside "Input" is also directly connected to our properties outside the shader? I am a bit confused between the two examples :
//...
struct Input {
float2 uv_MainTex;
float2 uv_BumpTex;
float3 viewDir; //We want to get the viewing angle
};
sampler2D _MainTex;
sampler2D _BumpTex;
float4 _RimColor;
float _RimPower;
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb;
o.Normal = UnpackNormal (tex2D (_BumpTex, IN.uv_BumpTex));
half rim = 1.0 - saturate(dot (normalize(IN.viewDir), o.Normal));
//...
(source : http://cgcookie.com/unity/2012/11/26/introduction-to-surface-shaders-in-unity-part-0/)
Thanks
$$anonymous$$y Noobs guide to shaders on Unity Gems attempts to demystify some of the "magic" things that happen when you defined variables in the input of a surface shader.
@whydoitdoit thanks whydoitdoit! Your website looks great, thanks for the link!
Answer by Owen-Reynolds · Apr 17, 2013 at 02:23 PM
Shaders are very specialized and strange animals. The Input you're looking at is magically interpolated from the vertex data of whichever face the pixel came from. Look up "renderer pipeline" (or GPU or shader pipeline) for an explanation. It's not a Unity thing. OpenGL sources often do the best job explaining it.
For ViewDir, each pixel could figure out the angle to the light itself, but that might be a lot of work. So, the person who wrote your code decided to have each vertex compute ViewDir. Then the pixels "guess" their viewDir, based on surrounding verts.
Suppose you're a pixel near the bottom of a "tip up" triangle. The system will magically produce a weighted average of the three verts for everything -- mostly UVs, and including ViewDir. For a middle bottom pixel, it will average the left and right vert values, with a hint of the top one (it Lerps them -- Lerp means linear interpolation. Non-linear is better, like a spline, but that's too much math.)
If you've ever weight-painted a model you can see this. You paint the verts, and the faces have the interpolated red/blue washing over them.
@OwenReynolds thanks Owen! It is actually the same as the normal map in purple that we can get with Gimp, and calculated each frame with the camera's view? If it is so, I think I got it. Thanks!