Skip to content

Instantly share code, notes, and snippets.

@findstr
Created June 13, 2017 13:27
Show Gist options
  • Save findstr/c775d66e76d83e10f49bb8f5a5b28935 to your computer and use it in GitHub Desktop.
Save findstr/c775d66e76d83e10f49bb8f5a5b28935 to your computer and use it in GitHub Desktop.
unity shader include specular and diffuse light
Shader "Template" {
Properties {
_Color("Color", Color) = (1, 1, 1, 1)
_Specular("Specular Color", Color) = (1, 1, 1, 1)
_Gloss("Gloss", Range(8.0, 256.0)) = 20
}
SubShader {
Tags { "RenderType"="Opaque" "Queue"="Geometry"}
Pass {
Tags { "LightMode"="ForwardBase" }
CGPROGRAM
#pragma multi_compile_fwbase
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc"
fixed4 _Color;
fixed4 _Specular;
float _Gloss;
struct a2v {
float4 vertex:POSITION;
float3 normal:NORMAL;
float4 tangent:TANGENT;
float4 texcoord:TEXCOORD0;
};
struct v2f {
float4 vertex:SV_POSITION;
float2 uv:TEXCOORD0;
//blinn_phong light model
float4 TtoW1:TEXCOORD1;
float4 TtoW2:TEXCOORD2;
float4 TtoW3:TEXCOORD3;
float3 worldNormal:TEXCOORD4;
SHADOW_COORDS(5)
};
v2f vert (a2v v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
//blinn_phong light model
TANGENT_SPACE_ROTATION;
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
float3 worldNormal = UnityObjectToWorldNormal(v.normal);
float3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
float3 worldBinormal = cross(worldNormal, worldTangent) * v.tangent.w;
o.TtoW1 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
o.TtoW2 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
o.TtoW3 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
o.worldNormal = worldNormal;
TRANSFER_SHADOW(o)
return o;
}
fixed4 frag (v2f i) : SV_Target
{
fixed3 albedo = _Color.rgb;
//blinn_phong_light_model
float3 worldPos = float3(i.TtoW1.w, i.TtoW2.w, i.TtoW3.w);
fixed3 lightDir = normalize(UnityWorldSpaceLightDir(worldPos));
fixed3 viewDir = normalize(UnityWorldSpaceViewDir(worldPos));
fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz * albedo;
fixed3 worldNormal = normalize(i.worldNormal);
fixed halfLamber = dot(worldNormal, lightDir);
fixed3 diffuse = _LightColor0.rgb * _Color.rgb * halfLamber;
fixed3 halfDir = normalize(lightDir + viewDir);
fixed3 specular = _LightColor0.rgb * _Specular.rgb * pow(max(0, dot(worldNormal, halfDir)), _Gloss);
UNITY_LIGHT_ATTENUATION(atten, i, worldPos)
fixed3 color = ambient + (diffuse + specular) * atten;
return fixed4(color, 1.0);
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment