UnityShader实现线框渲染

线框渲染主要使用到的是手游不太常用的GeometryShader。代码如下:

Shader "Unlit/GeometryShaderTest"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        [HDR]_Color("Color",Color) = (1,0,0,1)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma geometry geom_02
            #include "UnityCG.cginc"

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

            struct v2g
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 normal:NORMAL;
            };

            struct g2f
            {
                float2 uv:TEXCOORD0;
                float4 vertex : SV_POSITION;
                float3 worldNormal:TEXCOORD1;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            half4 _Color;
            v2g vert (appdata v)
            {
                v2g o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.normal = v.normal;
                return o;
            }

            [maxvertexcount(9)]
            void geom(triangle v2g input[3],inout TriangleStream<g2f> outStream) 
            {
                for (int i = 0; i < 3; i++)
                {
                    g2f o = (g2f)0;
                    o.vertex = input[i].vertex;
                    o.uv = input[i].uv;
                    o.worldNormal = UnityObjectToWorldNormal(input[i].normal);
                    outStream.Append(o);
                }
                outStream.RestartStrip();
            }

            [maxvertexcount(9)]
            void geom_02(triangle v2g input[3], inout LineStream<g2f> outStream)
            {
                for (int i = 0; i < 3; i++)
                {
                    g2f o = (g2f)0;
                    o.vertex = input[i].vertex;
                    o.uv = input[i].uv;
                    o.worldNormal = UnityObjectToWorldNormal(input[i].normal);
                    outStream.Append(o);
                }
                outStream.RestartStrip();
            }

            half4 frag (g2f i) : SV_Target
            {
                half3 worldNormal = normalize(i.worldNormal);
                half4 col = tex2D(_MainTex, i.uv)*_Color;
                return col;
            }
            ENDCG
        }
    }
}

Geometry具体的使用方法非常易懂,主要就是输入和输出。

输入有点、线、三角形等几种模式,输出也有TriangleStream、LineStream等,这里着重实现,代码中留有法线传递过程,作为正常数据在加入几何着色器后传递方式的参考。

效果如下(加个bloom烘托一下科技感):

 

简单粗暴,非常好用。

 

posted @ 2021-11-29 20:02  syb7384  阅读(1142)  评论(0编辑  收藏  举报