56 lines
1.6 KiB
GLSL
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#version 330 core
// 从顶点着色器插值传入的变量
in vec3 Position_worldspace;
in vec3 Normal_cameraspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace;
in vec2 UV;
// 输出颜色
out vec3 color;
// Uniform 变量
uniform sampler2D myTextureSampler; // 纹理采样器
uniform vec3 lightColor; // 光源颜色
uniform float lightPower; // 光照强度
uniform vec3 viewPos; // 观察者位置(世界空间)
uniform vec3 lightPos_worldspace; // 光源位置(世界空间)
// 材质属性 (可以作为uniform传入这里为了简单硬编码)
vec3 materialDiffuseColor = vec3(1.0, 1.0, 1.0); // 从纹理获取
vec3 materialAmbientColor = vec3(0.1, 0.1, 0.1);
vec3 materialSpecularColor = vec3(0.5, 0.5, 0.5);
float materialShininess = 32.0;
void main(){
// 环境光
vec3 ambient = 0.3 * lightColor;
// 法线和光照方向
vec3 N = normalize(Normal_cameraspace);
vec3 L = normalize(LightDirection_cameraspace);
// 漫反射
float diff = max(dot(N, L), 0.0);
vec3 diffuse = diff * lightColor;
// 镜面反射
vec3 E = normalize(EyeDirection_cameraspace);
vec3 R = reflect(-L, N);
float spec = pow(max(dot(E, R), 0.0), 32.0);
vec3 specular = 0.5 * spec * lightColor;
// 距离衰减
float distance = length(lightPos_worldspace - Position_worldspace);
float attenuation = lightPower / (1.0 + 0.2 * distance * distance);
// 采样纹理
vec3 texColor = texture(myTextureSampler, UV).rgb;
// 合成最终颜色
color = (ambient + diffuse + specular) * texColor * attenuation;
color = clamp(color, 0.0, 1.0);
}