UnityShader 學習筆記 12 高階紋理之折射
阿新 • • 發佈:2018-12-25
Shader "_MyShader/7_Advanced/1_Refraction" { Properties { _Color("Color", COLOR) = (1,1,1,1) _CubeMap("CubeMap", Cube) = "SkyBox" {} _RefractionColor("RefractionColor", COLOR) = (1,1,1,1) _RefractionAmount("RefractionAmount", Range(0,1.5)) = 1 _RefractionRatio("RefractionRatio", Range(0,1.5)) = 1 } SubShader { Tags { "RenderType"="ForwardBase" } Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" #include "Lighting.cginc" #include "AutoLight.cginc" struct a2v { float4 vertex : POSITION; float3 normal : NORMAL; }; struct v2f { float4 pos : SV_POSITION; float4 worldPos : TEXCOORD1; float3 worldNormal : TEXCOORD2; float3 worldLight : TEXCOORD3; float3 worldView : TEXCOORD4; float3 worldRefraction : TEXCOORD5; SHADOW_COORDS(5) }; fixed4 _Color; samplerCUBE _CubeMap; fixed4 _RefractionColor; float _RefractionAmount; float _RefractionRatio; v2f vert (a2v v) { v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); o.worldPos = mul(_Object2World,v.vertex); o.worldNormal = UnityObjectToWorldNormal(v.normal); o.worldLight = UnityWorldSpaceLightDir(o.worldPos); o.worldView = UnityWorldSpaceViewDir(o.worldPos); o.worldRefraction = refract(normalize(-o.worldView), normalize(o.worldNormal), _RefractionRatio); TRANSFER_SHADOW(o); return o; } fixed4 frag (v2f i) : SV_Target { fixed3 worldNormalDir = normalize(i.worldNormal); fixed3 worldLightDir = normalize(i.worldLight); fixed3 worldViewDir = normalize(i.worldView); fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.xyz; fixed3 diffuseColor = _LightColor0.rgb * _Color.rgb * max(0, dot(worldNormalDir, worldLightDir)); fixed3 refraction = texCUBE(_CubeMap, i.worldRefraction).rgb * _RefractionColor.rgb; UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos); fixed3 color = ambient + lerp(diffuseColor, refraction, _RefractionAmount) * atten; return fixed4(color, 1); } ENDCG } } }