Advertisement
tonynogo

Demo 90 - Flat shading

Jul 6th, 2017
10,799
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Shader "Custom/Geometry/FlatShading"
  2. {
  3.     Properties
  4.     {
  5.         _Color("Color", Color) = (1,1,1,1)
  6.         _MainTex("Albedo", 2D) = "white" {}
  7.     }
  8.    
  9.     SubShader
  10.     {
  11.  
  12.         Tags{ "Queue"="Geometry" "RenderType"= "Opaque" "LightMode" = "ForwardBase" }
  13.  
  14.         Pass
  15.         {
  16.             CGPROGRAM
  17.  
  18.             #include "UnityCG.cginc"
  19.             #pragma vertex vert
  20.             #pragma geometry geom
  21.             #pragma fragment frag
  22.  
  23.             float4 _Color;
  24.             sampler2D _MainTex;
  25.  
  26.             struct v2g
  27.             {
  28.                 float4 pos : SV_POSITION;
  29.                 float2 uv : TEXCOORD0;
  30.                 float3 vertex : TEXCOORD1;
  31.             };
  32.  
  33.             struct g2f
  34.             {
  35.                 float4 pos : SV_POSITION;
  36.                 float2 uv : TEXCOORD0;
  37.                 float light : TEXCOORD1;
  38.             };
  39.  
  40.             v2g vert(appdata_full v)
  41.             {
  42.                 v2g o;
  43.                 o.vertex = v.vertex;
  44.                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
  45.                 o.uv = v.texcoord;
  46.                 return o;
  47.             }
  48.  
  49.             [maxvertexcount(3)]
  50.             void geom(triangle v2g IN[3], inout TriangleStream<g2f> triStream)
  51.             {
  52.                 g2f o;
  53.  
  54.                 // Compute the normal
  55.                 float3 vecA = IN[1].vertex - IN[0].vertex;
  56.                 float3 vecB = IN[2].vertex - IN[0].vertex;
  57.                 float3 normal = cross(vecA, vecB);
  58.                 normal = normalize(mul(normal, (float3x3) unity_WorldToObject));
  59.  
  60.                 // Compute diffuse light
  61.                 float3 lightDir = normalize(_WorldSpaceLightPos0.xyz);
  62.                 o.light = max(0., dot(normal, lightDir));
  63.  
  64.                 // Compute barycentric uv
  65.                 o.uv = (IN[0].uv + IN[1].uv + IN[2].uv) / 3;
  66.  
  67.                 for(int i = 0; i < 3; i++)
  68.                 {
  69.                     o.pos = IN[i].pos;
  70.                     triStream.Append(o);
  71.                 }
  72.             }
  73.  
  74.             half4 frag(g2f i) : COLOR
  75.             {
  76.                 float4 col = tex2D(_MainTex, i.uv);
  77.                 col.rgb *= i.light * _Color;
  78.                 return col;
  79.             }
  80.  
  81.             ENDCG
  82.         }
  83.     }
  84.     Fallback "Diffuse"
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement