# 【一步步学OpenGL 21】 -《聚光灯光源》

2490人阅读 评论(0)

## 聚光灯光源

### 源代码详解

(lighting_technique.h:68)

struct SpotLight : public PointLight
{
Vector3f Direction;
float Cutoff;

SpotLight()
{
Direction = Vector3f(0.0f, 0.0f, 0.0f);
Cutoff = 0.0f;
}
};

(lighting.fs:39)

struct SpotLight
{
struct PointLight Base;
vec3 Direction;
float Cutoff;
};
...
uniform int gNumSpotLights;
...
uniform SpotLight gSpotLights[MAX_SPOT_LIGHTS];

(lighting.fs:85)

vec4 CalcPointLight(struct PointLight l, vec3 Normal)
{
vec3 LightDirection = WorldPos0 - l.Position;
float Distance = length(LightDirection);
LightDirection = normalize(LightDirection);

vec4 Color = CalcLightInternal(l.Base, LightDirection, Normal);
float Attenuation = l.Atten.Constant +
l.Atten.Linear * Distance +
l.Atten.Exp * Distance * Distance;

return Color / Attenuation;
}

(lighting.cpp:fs)

vec4 CalcSpotLight(struct SpotLight l, vec3 Normal)
{
vec3 LightToPixel = normalize(WorldPos0 - l.Base.Position);
float SpotFactor = dot(LightToPixel, l.Direction);

if (SpotFactor > l.Cutoff) {
vec4 Color = CalcPointLight(l.Base, Normal);
return Color * (1.0 - (1.0 - SpotFactor) * 1.0/(1.0 - l.Cutoff));
}
else {
return vec4(0,0,0,0);
}
}

(lighting.fs:122)

...
for (int i = 0 ; i < gNumSpotLights ; i++) {
TotalLight += CalcSpotLight(gSpotLights[i], Normal);
}
...

(lighting_technique.cpp:367)

void LightingTechnique::SetSpotLights(unsigned int NumLights, const SpotLight* pLights)
{
glUniform1i(m_numSpotLightsLocation, NumLights);

for (unsigned int i = 0 ; i < NumLights ; i++) {
glUniform3f(m_spotLightsLocation[i].Color, pLights[i].Color.x, pLights[i].Color.y, pLights[i].Color.z);
glUniform1f(m_spotLightsLocation[i].AmbientIntensity, pLights[i].AmbientIntensity);
glUniform1f(m_spotLightsLocation[i].DiffuseIntensity, pLights[i].DiffuseIntensity);
glUniform3f(m_spotLightsLocation[i].Position, pLights[i].Position.x, pLights[i].Position.y, pLights[i].Position.z);
Vector3f Direction = pLights[i].Direction;
Direction.Normalize();
glUniform3f(m_spotLightsLocation[i].Direction, Direction.x, Direction.y, Direction.z);
glUniform1f(m_spotLightsLocation[i].Atten.Constant, pLights[i].Attenuation.Constant);
glUniform1f(m_spotLightsLocation[i].Atten.Linear, pLights[i].Attenuation.Linear);
glUniform1f(m_spotLightsLocation[i].Atten.Exp, pLights[i].Attenuation.Exp);
}
}

1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：454905次
• 积分：4962
• 等级：
• 排名：第6671名
• 原创：91篇
• 转载：17篇
• 译文：30篇
• 评论：229条
关于我
人生苦短，道阻且艰；修行不易，且行且努力。

【专业兴趣】：
游戏开发，图形学，图像处理与计算机视觉，iOS平台

【专业技能】：
iOS，游戏开发

【个人主页】：信厚的独立博客
【个人项目】：个人项目
【GitHub】：jiangxh1992
【邮箱】：jiangxinhou艾特outlook点com
我的微博
时空隧道
博客专栏
 iOS沉思录 文章：49篇 阅读：84594
 一步步学OpenGL3.3+ 文章：30篇 阅读：123056
世界在看我>_<
把广告压下去