I'm calculating the light of a pixel using the Phong shading model. To calculate the diffuse light, I need the half vector of:
The hit point towards the light source and hit point towards the camera.
Here is my code:
Vector3 Phong::shade(const Ray& ray, const HitInfo& hit, const Scene& scene) const
{
Vector3 L = Vector3(0, 0, 0);
const Vector3 viewDir = -ray.d; // d is a unit vector
const Lights *lightlist = scene.lights();
// loop over all of the lights
Lights::const_iterator lightIter;
for (lightIter = lightlist->begin(); lightIter != lightlist->end(); ++lightIter)
{
PointLight* pLight = *lightIter;
Vector3 l = pLight->position() - hit.P; // find the vector from the hit point to the light
//l = l.normalized();
Vector3 I = pLight->color();
L += I * ka; // add ambient component
// add specular highlights
HitInfo hit2;
if( !scene.trace(hit2, Ray(hit.P, pLight->position()), 0.001f) )
{
L += I * kd * fabs(dot(l.normalized(), hit.N.normalized())); // add diffuse component
Vector3 H = ((l + ray.d) * 0.5f).normalized(); // find the half vector, H
L += I * ks * pow(fabs(dot(hit.N.normalized(), H)), m);
}
}
return L;
}
The H vector is calculate like this:
Vector3 H = ((l + ray.d) * 0.5f).normalized(); // find the half vector, H
l is not normalized.
I don't think
ray.d is normalized as well.
If I write Vector3 H = ((l.normalized() + ray.d.normalized()) * 0.5f).normalized();
the results don't seem to be correct - no diffuse light is visible on my objects (spheres).
With the prev equation specular highlights appear correctly (I think).