写一个unity的基础光照模型shader
时间: 2023-09-11 14:05:34 浏览: 199
### 回答1:
下面是一个简单的Unity基础光照模型Shader的代码:
```
Shader "Custom/BasicLighting" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Metallic ("Metallic", Range(0,1)) = 0.0
_Smoothness ("Smoothness", Range(0,1)) = 0.5
_Emission ("Emission", 2D) = "white" {}
}
SubShader {
Tags {"Queue"="Geometry" "RenderType"="Opaque"}
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD0;
};
struct v2f {
float2 uv : TEXCOORD0;
float3 normal : TEXCOORD1;
float3 viewDir : TEXCOORD2;
float3 worldPos : TEXCOORD3;
float4 pos : SV_POSITION;
};
sampler2D _MainTex;
sampler2D _Emission;
float4 _Color;
float _Metallic;
float _Smoothness;
v2f vert (appdata v) {
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
o.normal = UnityObjectToWorldNormal(v.normal);
o.viewDir = normalize(_WorldSpaceCameraPos - v.vertex.xyz);
o.worldPos = v.vertex.xyz;
return o;
}
float4 frag (v2f i) : SV_Target {
float4 col = _Color * texture(_MainTex, i.uv);
float3 diffuse = col.rgb * max(0, dot(i.normal, -_WorldSpaceLightPos0.xyz));
float3 specular = pow(max(0, dot(reflect(i.viewDir, i.normal), -_WorldSpaceLightPos0.xyz)), _Gloss);
float4 emission = texture(_Emission, i.uv);
float4 finalColor = col * (diffuse + specular) + emission;
finalColor.a = col.a;
return finalColor;
}
ENDCG
}
}
FallBack "Diffuse"
}
```
这是一个使用简单的基础光照模型,其中包含颜色,主纹理,金属感,光滑度和发射量等
### 回答2:
Unity的基础光照模型shader可以通过在顶点和片段着色器中进行编写来实现。以下是一个简单的Unity基础光照模型shader的示例:
顶点着色器:
```
Shader "Custom/BasicLightingShader" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
}
SubShader {
Tags {"Queue"="Transparent" "RenderType"="Opaque"}
LOD 200
CGPROGRAM
#pragma surface surf Lambert
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutput o) {
o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb;
o.Alpha = tex2D (_MainTex, IN.uv_MainTex).a;
}
ENDCG
}
}
```
片段着色器:
```
Shader "Custom/BasicLightingShader" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
}
SubShader {
Tags {"Queue"="Transparent" "RenderType"="Opaque"}
LOD 200
CGPROGRAM
#pragma surface surf Lambert
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
void surf (Input IN, inout SurfaceOutput o) {
fixed3 lightDir = normalize(UnityLight.dir);
float lambertTerm = dot(normalize(o.Normal), lightDir);
o.Albedo = tex2D (_MainTex, IN.uv_MainTex).rgb * lambertTerm;
o.Alpha = tex2D (_MainTex, IN.uv_MainTex).a;
}
ENDCG
}
}
```
这个shader使用了Lambert光照模型来计算每个像素的颜色,实现了基本的光照效果。在顶点着色器中,我们通过获取_MainTex纹理的uv坐标,并将其存储在Input结构体中。然后,在surf函数中,我们使用tex2D函数来获取_MainTex纹理的颜色值,并将其赋给SurfaceOutput结构体的Albedo成员,以实现纹理贴图。在片段着色器中,我们通过获取UnityLight的dir属性来获取光照的方向,并将其与表面法线计算出的兰伯特项相乘,得到每个像素的最终颜色。最后,我们将最终颜色赋给SurfaceOutput结构体的Albedo成员,以实现光照效果。
阅读全文