1
\$\begingroup\$

I'm writing a shader in CG language for Unity3d. When making transparent object you need to create two similar passes in SubShader. First to render only back faces (with Cull Front) and second to render only front faces (with Cull Back). But the code for vertex and fragment function is the same.

Is it possible not to double a code and declare some functions, that would be shared between passes?
I want to have something like in my code example.

Shader "cool shader" {
Properties {
    ...
}
SubShader {

    CGPROGRAM
    // need to declare vertexOutput somewhow here
    float4 sharedFragFoo(vertexOutput i) : COLOR  // How to make smth like this?
    {
        ....
        return float4(...);
    }
    ENDCG

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;     
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }

    pass {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        vertexOutput vert(vertexInput v) {
            vertexOutput o;
            ...
            return o;
        }

        float4 frag(vertexOutput i) : COLOR
        {
            return sharedFragFoo(i); // call the shared between passes function
        }

        ENDCG
    }
}
}
\$\endgroup\$
  • \$\begingroup\$ Have you looked into the #include directive? I use that to share functions from Unity's libraries all the time, so presumably it could be used with custom files (not making this an answer because I haven't confirmed it works, or details of where to put the .cginc file) \$\endgroup\$ – DMGregory May 29 '15 at 12:25
1
\$\begingroup\$

We can define all that lies between CGPROGRAM and ENDCG in separate *.cginc file and include it inside each pass.

For details look https://stackoverflow.com/a/30530184/1351629 .

Sorry for the cross-post. I have found out how to do it using includes and posted the answer on SO.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.