What are the means to reuse shader code?

I am writing shaders for my projectto be published on asset store. I am interested in facilities to reuse code instead of copy-paste chunks of code in every shader file. I have some questions about the matter.

Consider the following shader:

Shader "Uplus/Erosion/GaussianX"
{
    Properties
    {
        _MainTex("Texture", 2D) = "white" {}
    }
        SubShader
    {
        Tags{ "RenderType" = "Opaque" }
        LOD 100

        Pass
    {
        CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 4.0
#include "UnityCG.cginc"

        struct appdata
    {
        float4 vertex : POSITION;
        float2 uv : TEXCOORD0;
    };

    struct v2f
    {
        float2 uv : TEXCOORD0;
        float4 vertex : SV_POSITION;
    };

    sampler2D _MainTex;
    float4 _MainTex_ST;
    float4 _MainTex_TexelSize;
    sampler2D tex;

    v2f vert(appdata v)
    {
        v2f o;
        o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
        o.uv = TRANSFORM_TEX(v.uv, _MainTex);
        return o;
    }

    float4 Gaussianx(float2 pos, float2 texelSize)
    {
        float2 texelX = float2(texelSize.x, 0);
        return 0.0109551894f*(tex2D(tex, pos - 4 * texelX) + tex2D(tex, pos + 4 * texelX))
            + 0.0429914258f*(tex2D(tex, pos - 3 * texelX) + tex2D(tex, pos + 3 * texelX))
            + 0.11415568f*(tex2D(tex, pos - 2 * texelX) + tex2D(tex, pos + 2 * texelX))
            + 0.2051006f*(tex2D(tex, pos - texelX) + tex2D(tex, pos + texelX))
            + 0.24933891f*tex2D(tex, pos);
    }

    float4 frag(v2f i) : SV_Target
    {
        return Gaussianx(i.uv, _MainTex_TexelSize.xy);
    }
    ENDCG
    }
    }
}

Assuming I have more shaders very similar to this one, how much of it can be put on a shared place and reused in all shaders? If we try to abstract keywords and concepts here we can have a list. What I see here is Properties, SubShader, Tags, Pass, CGPROGRAM, #pragma, #include, struct, uniforms, and functions.

Now Imagine we want to have a separate include file and put in it as much of this code as possible. All the functions and structs and uniforms may be used in other shaders so the more reuse we can have is the better. What will the code and the include file be?

Everything within CGPROGRAM should be reusable except #pragma. And you can include marco in the .cginc for maximise reusability.

1 Like

Thanks for the answer.