x


Need help with a shader.

I'm trying to write a simple diffuse shader that ignores lighting and ztesting and turns off culling. Additionally it takes in a float that specifyes the alpha value of what to draw. Here is what i have so far:

Shader "FadeOut"
{
    Properties  {
        _DiffuseMap("_DiffuseMap", 2D) = "white" {}
        _AlphaFade("_AlphaFade", Float) = 1
    }

    SubShader {
        Blend SrcAlpha OneMinusSrcAlpha 
        ZWrite Off 
        Cull Off 
        Fog { Mode Off } 


        CGPROGRAM
            #pragma surface surf BlinnPhongEditor alpha
            #pragma target 3.0


            sampler2D _DiffuseMap;
            float _AlphaFade;

            struct EditorSurfaceOutput {
                half3 Albedo;
                half3 Normal;
                half3 Emission;
                half3 Gloss;
                half Specular;
                half Alpha;
            };

            inline half4 LightingBlinnPhongEditor_PrePass (EditorSurfaceOutput s, half4 light) {
                half3 spec = light.a * s.Gloss;
                half4 c;
                c.rgb = (s.Albedo * light.rgb + light.rgb * spec);
                c.a = s.Alpha + Luminance(spec);
                return c;
            }

            inline half4 LightingBlinnPhongEditor (EditorSurfaceOutput s, half3 lightDir, half3 viewDir, half atten) {
                viewDir = normalize(viewDir);
                half3 h = normalize (lightDir + viewDir);

                half diff = max (0, dot (s.Normal, lightDir));

                float nh = max (0, dot (s.Normal, h));
                float3 spec = pow (nh, s.Specular*128.0) * s.Gloss;

                half4 res;
                res.rgb = _LightColor0.rgb * (diff * atten * 2.0);
                res.w = spec * Luminance (_LightColor0.rgb);

                return LightingBlinnPhongEditor_PrePass( s, res );
            }

            struct Input {
                float2 uv_DiffuseMap;
            };

            void surf (Input IN, inout EditorSurfaceOutput o) {
                o.Albedo = 0.0;
                o.Normal = float3(0.0,0.0,1.0);
                o.Emission = 0.0;
                o.Gloss = 0.0;
                o.Specular = 0.0;
                o.Alpha = 1.0;

                float4 Sampled2D0=tex2D(_DiffuseMap,IN.uv_DiffuseMap.xy);
                float4 Multiply1=float4( Sampled2D0.a) * float4(_AlphaFade);

                float4 Saturate0=saturate(Multiply1);

                o.Albedo = Sampled2D0;
                o.Emission = Sampled2D0;
                o.Alpha = Saturate0;
            }
        ENDCG
    }
    Fallback "Diffuse"
}

This works to an extent. My issue is when the script runs everything is saturated to green :( Can anyone help me out?

more ▼

asked Dec 15 '10 at 04:31 PM

Gabriel 4 gravatar image

Gabriel 4
57 10 11 18

(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first

What you describe is a Transparent/Unlit shader like this:

Shader "Transparent/Unlit" {
    Properties {
        _Alpha ("Alpha", Range(0,1)) = 1
        _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
    }

    SubShader {
        Blend SrcAlpha OneMinusSrcAlpha 
        ZWrite Off 
        Cull Off 
        Fog { Mode Off } 
        Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
        LOD 200

        CGPROGRAM
        #pragma surface surf Unlit alpha

        sampler2D _MainTex;
        float _Alpha;

        inline half4 LightingUnlit (SurfaceOutput s, half3 lightDir, half atten) {
            half diff = max (0, dot (s.Normal, lightDir));

            half4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        inline half4 LightingUnlit_PrePass (SurfaceOutput s, half4 light) {
            half4 c;
            c.rgb = s.Albedo;
            c.a = s.Alpha;
            return c;
        }

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half4 c = tex2D(_MainTex, IN.uv_MainTex);
            o.Albedo = c.rgb;
            o.Alpha = c.a * _Alpha;
        }
        ENDCG
    }

    Fallback "Transparent/VertexLit"
}

This won't ignore ambient lighting. It's almost like you want a to customize the standard Transparent/Cut-off/Soft-Edge Unlit. That would look something like:

/*
Renders doubled sides objects without lighting. Useful for
grass, trees or foliage.

This shader renders two passes for all geometry, one
for opaque parts and one with semitransparent details.

This makes it possible to render transparent objects
like grass without them being sorted by depth.
*/

Shader "Transparent/Unlit" {
    Properties {
        _MainTex ("Base (RGB) Alpha (A)", 2D) = "white" {}
        _Alpha ("Alpha", Range (0,1)) = 1
    }

    SubShader {
        Tags { "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
        Lighting off

        // Render both front and back facing polygons.
        Cull Off

        // first pass:
        //   render any pixels that are more than [_Alpha] opaque
        Pass {  
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float4 color : COLOR;
                    float2 texcoord : TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 color : COLOR;
                    float2 texcoord : TEXCOORD0;
                };

                sampler2D _MainTex;
                float4 _MainTex_ST;
                float _Alpha;

                v2f vert (appdata_t v)
                {
                    v2f o;
                    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                    o.color = v.color;
                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                    return o;
                }

                half4 frag (v2f i) : COLOR
                {
                    half4 col = tex2D(_MainTex, i.texcoord);
                    col.a *= _Alpha;
                    return col;
                }
            ENDCG
        }

        // Second pass:
        //   render the semitransparent details.
        Pass {
            Tags { "RequireOption" = "SoftVegetation" }

            // Dont write to the depth buffer
            ZWrite off

            // Set up alpha blending
            Blend SrcAlpha OneMinusSrcAlpha

            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag

                #include "UnityCG.cginc"

                struct appdata_t {
                    float4 vertex : POSITION;
                    float4 color : COLOR;
                    float2 texcoord : TEXCOORD0;
                };

                struct v2f {
                    float4 vertex : POSITION;
                    float4 color : COLOR;
                    float2 texcoord : TEXCOORD0;
                };

                sampler2D _MainTex;
                float4 _MainTex_ST;
                float _Alpha;

                v2f vert (appdata_t v)
                {
                    v2f o;
                    o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                    o.color = v.color;
                    o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);
                    return o;
                }

                half4 frag (v2f i) : COLOR
                {
                    half4 col = tex2D(_MainTex, i.texcoord);
                    col.a *= _Alpha;
                    return col;
                }
            ENDCG
        }
    }

    SubShader {
        Tags { "IgnoreProjector"="True" "RenderType"="TransparentCutout" }
        Lighting off

        // Render both front and back facing polygons.
        Cull Off

        // first pass:
        Pass {
            SetTexture [_MainTex] {}
        }

        // Second pass:
        //   render the semitransparent details.
        Pass {
            Tags { "RequireOption" = "SoftVegetation" }

            // Dont write to the depth buffer
            ZWrite off

            // Set up alpha blending
            Blend SrcAlpha OneMinusSrcAlpha

            SetTexture [_MainTex] {}
        }
    }
}

Nothing in your shader will result in over-saturated greens so the problem must lie elsewhere.

more ▼

answered Dec 15 '10 at 04:55 PM

skovacs1 gravatar image

skovacs1
10k 11 25 91

Good, I think attempting to change shader clearly rules out a shader problem if the problem persists.

Dec 15 '10 at 05:05 PM Statement ♦♦

Those were my thoughts, plus it's actually clear what the shaders in my answer are doing and they are actually ignoring lighting like the op described, unlike their shader which still does lighting.

Dec 15 '10 at 05:40 PM skovacs1
(comments are locked)
10|3000 characters needed characters left

My issue is when the script runs everything is saturated to green.

Short answer:

  • Check your ambient light settings.
  • Check any procedurally generated textures for validity.
  • Check your license if you're using GL calls. GL calls are for Unity Pro only.
  • Check your texture binding. Your code set "_MainTex" while your shader expose "_DiffuseMap".
  • Check your alpha binding. Your code set "_Alpha" while your shader expose "_AlphaFade".
  • Check your render passes. You're only rendering pass 0, but using surface shaders which are multipass.

Long answer:

No green saturation

Cube using a material with the original shader posted, with standard assets "glass" texture and AlphaFade value of 1.0f, run in the editor.

I don't know your script (or do you mean your shader?), what texture you're using nor your alpha range but I just tried this with some random texture and fed alpha random values and I saw no green saturation. I don't know what you're talking about. I can't see any obvious errors. How can I reproduce your green saturated state?

A rule of thumb though when colors go wild, is to use saturate() in places such as function returns and parameter passing. If intermediate colors have other color ranges than 0 to 1, often errors can emerge. Make sure all your values are within expected ranges with saturate or clamp.


A possibility that struck me is that your ambient color in Render Settings is at bright green. I tested this and the result changed to behave like this:

Green ambient coloring

Here, strong green ambient is applied to the scene.


Another possibility is that you are creating render/textures improperly. If you know you are using rendertextures or creating textures manually, you might want to suspect that code doing something fishy.

more ▼

answered Dec 15 '10 at 04:39 PM

Statement gravatar image

Statement ♦♦
20.1k 35 70 175

Thanks for the reply's guys. I feel that i'm on the right track. skovacs1, i changed my shader to yours and i'm still getting the green effect... Can anyone please take a look at this for me? http://gaborszauer.com/NewSprites.rar Statement, your second possibility as to what the problem is seems head on, but my ambient light is not green...

Dec 15 '10 at 05:55 PM Gabriel 4

Do you have Unity Pro? Because the GL commands are for Unity Pro only.

Dec 15 '10 at 06:01 PM Statement ♦♦

Yes, i'm using Unity Pro.

Dec 15 '10 at 06:08 PM Gabriel 4

Did you check your console for any error messages at all? I am spammed with error "Material doesn't have a texture property '_MainTex' UnityEngine.Material:set_mainTexture(Texture)". It seems your shader has a property for a texture that isn't named _MainTex. Instead you call it _DiffuseMap. Either change the shader, or change the code to update _DiffuseMap instead of _MainTex.

Dec 15 '10 at 06:23 PM Statement ♦♦

I put the Main script on an empty game object, and the KZSpriteCamera on the main camera. I just noticed the outdated readme file, please ignore the word file that is attached. I don't get any output error messages at all, this is what it looks like on my machine: http://imagefrog.net/show.php/132476_Untitled1.png

Dec 15 '10 at 06:33 PM Gabriel 4
(comments are locked)
10|3000 characters needed characters left

FML... I right clicked on the shader and made a material out of it. Now everything works as it should... I guess i don't understand how to create a material trough code as well as i tought.

Another odd issue is if i try to convert the shader source into a string and make a material that way i get a "Error in [SHADER] on line1" error....

I'm confused, but something is working. Thanks for all the help guys!

more ▼

answered Dec 15 '10 at 06:38 PM

Gabriel 4 gravatar image

Gabriel 4
57 10 11 18

lol, so i deleted the newly made material and everything still works. I can no longer re-create the issue...

Dec 15 '10 at 06:43 PM Gabriel 4

Well you have several errors. You're updating _Alpha (that doesn't exist) instead of _AlphaFade. You're updating _MainTex (that doesn't exist) instead of _DiffuseMap. You're also only using the first pass, but IIRC surface shaders create additional passes. You're using Texture which I'm not sure if the class you should use, use Texture2D. I fiddled around a bit and managed to get it pulsating but the texture doesn't show up so I'm not sure what is going on with that thing.

Dec 15 '10 at 06:49 PM Statement ♦♦

If you set the variables on the material, it is bound to work since the inspector sets the correct variables. Your script does not. The error part I am not sure of, it might be a bad newline (mac/pc?). Clean your shader. Clean your code. Shader variables you're using from code should be called _Alpha and _MainTex. Make sure you do render with all passes. Finally, this solution seems overly complex (to my eyes, but I dont know your goals) but please try to finish it so you'll learn something out of it. :)

Dec 15 '10 at 06:54 PM Statement ♦♦

Also, to add insult to the injury - dont post replys as answes. This is not how unityAnswers work. It's not a forum. :)

Dec 15 '10 at 06:55 PM Statement ♦♦
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1655
x88
x75

asked: Dec 15 '10 at 04:31 PM

Seen: 3430 times

Last Updated: Dec 15 '10 at 04:31 PM