1
0
Fork 0
2018-soft-3d-renderer/src/light.cpp

49 lines
1.3 KiB
C++
Raw Normal View History

2018-09-20 02:15:53 +00:00
#include "camera.h"
2018-09-19 03:02:12 +00:00
#include "color.h"
#include "light.h"
// PUBLIC FUNCTIONS
2018-09-20 02:15:53 +00:00
ColorF32 ComputeLight(
2018-09-21 03:06:27 +00:00
Point &position, Vector &normal, Material &material, Light &light, Camera &camera)
2018-09-19 03:02:12 +00:00
{
2018-09-21 03:06:27 +00:00
// Point light intensity is a function of the falloff factors and the distance
Vector direction = light.position - position;
VectorNormalize(direction);
2018-09-19 05:33:52 +00:00
float distance = VectorLength(direction);
2018-09-19 03:02:12 +00:00
ColorF32 intensity =
(light.intensity * light.color)
2018-09-21 03:06:27 +00:00
/ (light.falloffConstant + (light.falloffLinear * distance));
2018-09-19 03:02:12 +00:00
2018-09-21 03:06:27 +00:00
// Diffuse Light = Kr * I * (alpha + (1 - alpha) * n.d)
float dotNormalDirection = MAX(VectorDot(normal, direction), 0.0f);
float alpha = 0.2f;
2018-09-20 02:15:53 +00:00
2018-09-21 03:06:27 +00:00
ColorF32 diffuseLight =
material.diffuse
* intensity
* (alpha + (1.0f - alpha) * dotNormalDirection);
2018-09-20 02:15:53 +00:00
2018-09-19 03:02:12 +00:00
2018-09-21 03:06:27 +00:00
// Specular Light = Ks * I * (r.v)^sp
Vector view = camera.position - position;
2018-09-20 02:15:53 +00:00
VectorNormalize(view);
2018-09-21 03:06:27 +00:00
Vector reflection = (2.0f * dotNormalDirection * normal) - direction;
float dotReflectionView = MAX(VectorDot(reflection, view), 0.0f);
2018-09-20 02:15:53 +00:00
2018-09-21 03:06:27 +00:00
ColorF32 specularLight =
material.specular
* intensity
* powf(dotReflectionView, material.glossiness);
2018-09-20 02:15:53 +00:00
2018-09-19 03:02:12 +00:00
2018-09-21 03:06:27 +00:00
// Total light is sum of all lights
ColorF32 result = diffuseLight + specularLight;
2018-09-20 02:15:53 +00:00
2018-09-19 03:02:12 +00:00
return result;
}