Using shader for Camera render in Unity

user1021110 picture user1021110 · Oct 17, 2013 · Viewed 13.1k times · Source

I've written a shader and it works fine when I added it in a plane located in front of camera (in this case camera does not have shader). but then I add this shader to the camera, it does not show anything on the screen. Herein is my code, could you let me know how can I change it to be compatible with Camera.RenderWithShader method?

Shader "Custom/she1" {
    Properties {
    top("Top", Range(0,2)) = 1
    bottom("Bottom", Range(0,2)) = 1
}
    SubShader {

        // Draw ourselves after all opaque geometry
        Tags { "Queue" = "Transparent" }

        // Grab the screen behind the object into _GrabTexture
        GrabPass { }

        // Render the object with the texture generated above
        Pass {


CGPROGRAM
#pragma debug
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0

            sampler2D _GrabTexture : register(s0);
            float top;
            float bottom;

struct data {

    float4 vertex : POSITION;

    float3 normal : NORMAL;

};



struct v2f {

    float4 position : POSITION;

    float4 screenPos : TEXCOORD0;

};



v2f vert(data i){

    v2f o;

    o.position = mul(UNITY_MATRIX_MVP, i.vertex);

    o.screenPos = o.position;

    return o;

}



half4 frag( v2f i ) : COLOR

{

    float2 screenPos = i.screenPos.xy / i.screenPos.w;
    float _half = (top + bottom) * 0.5;
    float _diff = (bottom - top) * 0.5;
    screenPos.x = screenPos.x * (_half + _diff * screenPos.y);
      screenPos.x = (screenPos.x + 1) * 0.5;
    screenPos.y = 1-(screenPos.y + 1) * 0.5 ;
    half4 sum = half4(0.0h,0.0h,0.0h,0.0h);  
    sum = tex2D( _GrabTexture, screenPos);
    return sum;

}
ENDCG
        }
    }

Fallback Off
} 

Answer

MichaelTaylor3D picture MichaelTaylor3D · Oct 21, 2013

I think what your asking for is a replacement shader that shades everything in the camera with your shader.

Am I correct?

If so this should work

Camera.main.SetReplacementShader(Shader.Find("Your Shader"),"RenderType")

here is some more info: http://docs.unity3d.com/Documentation/Components/SL-ShaderReplacement.html

Edit: Are you expecting the entire camera to warp like a lens effect? Because your not going to get that using a shader like this by itself, because as it stands it will only apply to objects like your plane but not the full camera view, that requires a post image effect. First your need Unity Pro. If you do, import the Image effects package and look at the fisheye script. See if you can duplicate the fisheye script with your own shader. When I attached the fisheye shader without its corresponding script I was getting the same exact results as you are with your current shader code. If you dont have access to the image effects package let me know and ill send your the fisheye scripts and shaders.