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

79 lines
1.8 KiB
C++

#include "color.h"
#include "light.h"
// PRIVATE PROTOTYPES
static ColorF32 ComputeAmbientLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity);
static ColorF32 ComputeDiffuseLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity,
Point &vertPosition, Vector &vertNormal,
Point &lightPosition);
// PUBLIC FUNCTIONS
ColorF32 ComputeLight(Vertex &vert, Material &material, Light &light)
{
// Distance from light to vertex
Vector d = light.position - vert.point;
float distance = d.Length();
// Intensity is a function of the falloff factors and the distance
ColorF32 intensity =
(light.intensity * light.color)
/ (light.falloffConstant + light.falloffLinear * distance);
// Compute ambient light
ColorF32 ambientLight = ComputeAmbientLight(
material.ambient, intensity);
// Compute diffuse light
ColorF32 diffuseLight = ComputeDiffuseLight(
material.diffuse, intensity,
vert.point, vert.normal,
light.position);
// Total light is sum of all lights
ColorF32 result = ambientLight + diffuseLight;
return result;
}
// PRIVATE FUNCTIONS
static ColorF32 ComputeAmbientLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity)
{
ColorF32 result;
result = surfaceReflectivity * lightIntensity;
return result;
}
static ColorF32 ComputeDiffuseLight(
ColorF32 surfaceReflectivity, ColorF32 lightIntensity,
Point &vertPosition, Vector &vertNormal,
Point &lightPosition)
{
// Light is a function of the position of the light source and the surface
Vector direction = lightPosition - vertPosition;
direction.Normalize();
float dot = Vector::Dot(vertNormal, direction);
ColorF32 result = surfaceReflectivity * lightIntensity * dot;
return result;
}