Skip to content

Commit b316da0

Browse files
ziadzananirisu-ah
andauthored
[#145] Basic Spot Light Shader Functionality (#147)
* Implemented standard functionality for spot light shader * Small comment for question * Changing light choking logic for spotlight * add note for future change for a param * Slight modifications based on feedback * re-add range into attenuation --------- Co-authored-by: su-ah <emmrald4@gmail.com>
1 parent 43157b2 commit b316da0

1 file changed

Lines changed: 42 additions & 3 deletions

File tree

shaders/shader_lights.slang

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,13 @@ struct DirLight {
4545
};
4646

4747
struct SpotLight {
48-
// TODO: add required data
48+
float3 position;
49+
float intensity;
50+
float3 direction;
51+
float innerConeAngle;
52+
float3 color;
53+
float outerConeAngle;
54+
float range;
4955
};
5056

5157
ConstantBuffer<PointLight[4]> pointLights;
@@ -76,8 +82,41 @@ float3 computeDir(DirLight light, float3 fragPos, float3 normal, float3 viewDir)
7682
}
7783

7884
float3 computeSpot(SpotLight light, float3 fragPos, float3 normal, float3 viewDir) {
79-
// TODO: return light contribution from a given spot light
80-
return float3(0.0, 0.0, 0.0);
85+
// Direction from fragment to light
86+
float3 lightDir = light.position - fragPos;
87+
float distance = length(lightDir);
88+
lightDir = normalize(lightDir);
89+
90+
// Distance attenuation
91+
float attenuation = (light.range * light.range) / max(200 * 200 * distance * distance, 0.0001); // Incase distance is 0
92+
93+
// We may start choking the light after it has travelled at least 80% of the distance
94+
// attenuation *= smoothstep(light.range, light.range * 0.8, distance);
95+
96+
// Spotlight cone attenuation
97+
float theta = dot(lightDir, -normalize(light.direction));
98+
float cosInner = cos(light.innerConeAngle);
99+
float cosOuter = cos(light.outerConeAngle);
100+
float spotIntensity = smoothstep(cosOuter, cosInner, theta);
101+
102+
// Blinn-Phong lighting components
103+
float3 norm = normalize(normal);
104+
105+
// Diffuse
106+
float diff = max(dot(norm, lightDir), 0.0);
107+
float3 diffuse = diff * light.color;
108+
109+
// Specular
110+
float3 halfDir = normalize(lightDir + viewDir);
111+
// NOTE: change 32.0 to a 'shininess' param when switching to textures (blinn-phong only)
112+
float spec = pow(max(dot(norm, halfDir), 0.0), 32.0);
113+
float3 specular = spec * light.color;
114+
115+
// Ambient
116+
float3 ambient = 0.1 * light.color;
117+
118+
float3 result = (ambient + diffuse + specular) * light.intensity * spotIntensity * attenuation;
119+
return result;
81120
}
82121

83122
[shader("fragment")]

0 commit comments

Comments
 (0)