# OpenGL学习脚印: 光照基础(basic lighting)

1. learnopengl.com Basic Lighting
2.Modern OpenGL 06 – Diffuse Point Lighting

• 颜色与光照的关系
• 简单实现的Phong Reflection Model

## 颜色与光照的关系

LightIntensityObjectColor=Reflectcolor$LightIntensity * ObjectColor = Reflectcolor$

(R,G,B)(X,Y,Z)=(XR,YG,ZB)$(R,G,B)*(X,Y,Z)=(XR,YG,ZB)$

(1,1,1)(1,0,0)=(1,0,0)$(1,1,1)*(1,0,0) = (1,0,0)$

glm::vec3 lightColor(0.33f, 0.42f, 0.18f);
glm::vec3 toyColor(1.0f, 0.5f, 0.31f);
glm::vec3 result = lightColor * toyColor; // = (0.33f, 0.21f, 0.06f);

## Phong Reflection Model

### 环境光成分

// 环境光成分
float   ambientStrength = 0.1f;
vec3    ambient = ambientStrength * lightColor * objectColor;

### 漫反射光成分

1.光源和顶点位置之间的向量L 需要计算。
2.法向量N 通过顶点属性里指定 经过模型和视变换后需要重新计算。

// 顶点属性 位置 纹理坐标  法向量
GLfloat vertices[] = {
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f,1.0f,    // A
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,  0.0f, 0.0f, 1.0f,   // B
0.5f, 0.5f, 0.5f,  1.0f, 1.0f,   0.0f, 0.0f, 1.0f,  // C
0.5f, 0.5f, 0.5f,  1.0f, 1.0f,   0.0f, 0.0f, 1.0f,  // C
-0.5f, 0.5f, 0.5f,  0.0f, 1.0f,  0.0f, 0.0f, 1.0f,  // D
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f,   // A
...省略

FragPos=vec3(modelvec4(position,1.0));()$FragPos = vec3(model * vec4(position, 1.0));\tag{变换后顶点位置}$

Normal=mat3(transpose(inverse(model)))normal()$Normal = mat3(transpose(inverse(model)))*normal \tag{变换后法向量}$

#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 textCoord;
layout(location = 2) in vec3 normal;

out vec3 FragPos;
out vec2 TextCoord;
out vec3 FragNormal;

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;

void main()
{
gl_Position = projection * view * model * vec4(position, 1.0);
FragPos = vec3(model * vec4(position, 1.0)); // 在世界坐标系中指定
TextCoord = textCoord;
mat3 normalMatrix = mat3(transpose(inverse(model)));
FragNormal = normalMatrix * normal; // 计算法向量经过模型变换后值
}

// 漫反射光成分 此时需要光线方向为指向光源
vec3    lightDir = normalize(lightPos - FragPos);
vec3    normal = normalize(FragNormal);
float   diffFactor = max(dot(lightDir, normal), 0.0);
vec3    diffuse = diffFactor * lightColor * objectColor;

## 镜面反射光成分

specFactor=cos(θ)s$specFactor = cos(\theta)^{s}$

// 镜面反射成分 此时需要光线方向为由光源指出
float   specularStrength = 0.5f;
vec3    reflectDir = normalize(reflect(-lightDir, normal));
vec3    viewDir = normalize(viewPos - FragPos);
float   specFactor = pow(max(dot(reflectDir, viewDir), 0.0), 32); // 32为镜面高光系数
vec3    specular = specularStrength * specFactor * lightColor * objectColor;

   vec3 reflectDir = normalize(reflect(-lightDir, normal));

   vec3 result = ambient + diffuse + specular
color = vec4(result , 1.0f);