Shader代码重复利用

20 篇文章 4 订阅

有时候一段代码,我们可能在不同的地方调用,如果每个地方复制一份,一方面不美观,代码冗余,另一方面,如果这段代码出问题了就gg了,你得找到所有使用的地方,改吧。Shader中的代码也可以模块化的,主要使用define指令。例子如下:

创建.cginc文件

创建一个myinclude.cginc文件,在该文件中写入如下代码:

#ifndef MY_CG_INCLUDE
#define MY_CG_INCLUDE

fixed4 _MyColor;

//半兰伯特光照模型
inline fixed4 LightingHalfLambert (SurfaceOutput s, fixed3 lightDir, fixed atten)
{
    fixed diff = max (0, dot(s.Normal, lightDir));
    //如果定义了HalfLambert宏,则采用半兰伯特光照模型,否则采用普通的NdotL漫反射模型。
    #ifdef HalfLambert
    diff = (diff + 0.5)*0.5;
    #endif

    fixed4 c;
    c.rgb = s.Albedo*_LightColor0.rgb*((diff*_MyColor.rgb)*atten*2);
    c.a = s.Alpha;
    return c;
}

#endif

创建一个简单的surfaceshader

创建一个简单的surfaceshader着色器,代码如下:

Shader "Custom/HalfLambertShaderTest" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
        _DesatValue ("Desaturate", Range(0, 1)) = 0.5
        _MyColor ("My Color", Color) = (1,1,1,1)
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200

        CGPROGRAM
        //定义HalfLambert宏,以便启用半兰伯特光照模型。
        #define HalfLambert
        #include "myinclude.cginc"  //类似C++的include,把自己写的.cginc文件加载进来
        #pragma surface surf HalfLambert  //启用.cginc文件中LightingHalfLambert 光照模型,名字是固定格式“Lighting”+“光照模型名称”

        sampler2D _MainTex;

        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;
        }
        ENDCG
    } 
    FallBack "Diffuse"
}

以后就能把通用重复的代码整理在自己的小黑屋里洛,直接include就能使用哦,然后配合宏定义,很方便。如有不明白的欢迎留言。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值