c44966e73ba4beaf86486aa9fc40acd2c1887019
[MicroTrace.git] / PhongShader.cxx
1 #include "PhongShader.hxx"
2 #include "Primitive.hxx"
3
4 PhongShader::PhongShader(Scene* scene,
5 const Vec3f& am_c,
6 const Vec3f& di_c,
7 const Vec3f& sp_c,
8 float ka,
9 float kd,
10 float ks,
11 float ke)
12 : Shader(scene),
13 m_ambient_color(am_c),
14 m_diffuse_color(di_c),
15 m_specular_color(sp_c),
16 m_ka(ka),
17 m_kd(kd),
18 m_ks(ks),
19 m_ke(ke)
20 {
21 }
22
23 PhongShader::PhongShader()
24 : Shader(0)
25 {
26 }
27
28 PhongShader::~PhongShader()
29 {
30 }
31
32 Vec3f
33 PhongShader::Shade(Ray& ray)
34 {
35 // surface normal at hit point of object
36 Vec3f normal = ray.hit()->GetNormal(ray);
37 // turn to front if angle > 90°
38 if(normal.dot(ray.direction()) < 0) {
39 normal = normal * -1;
40 }
41 // direction of reflection
42 Vec3f refl_dir = ray.direction() - normal * 2 * normal.dot(ray.direction());
43 refl_dir.normalize();
44
45 // ambient color term
46 Vec3f amb_color = m_ambient_color * m_ka;
47
48 Vec3f intensity, light_dir;
49
50 // diffuse and specular color for each light source
51 Vec3f diff_sum;
52 Vec3f spec_sum;
53 for(std::vector<Light*>::iterator it = m_scene->m_lights.begin();
54 it != m_scene->m_lights.end(); it++) {
55 Ray light_ray;
56 (*it)->Illuminate(light_ray, intensity);
57 diff_sum += intensity * light_ray.direction().dot(normal);
58 Vec3f view_dir = ray.direction()*-1; // direction from hitpoint to viewer
59 spec_sum += intensity * pow(fmax(view_dir.dot(refl_dir),0), m_ke);
60 }
61 Vec3f diff_color = m_diffuse_color * m_kd * diff_sum;
62 Vec3f spec_color = m_specular_color * m_ks * spec_sum;
63
64 return amb_color + diff_color + spec_color;
65 }
This page took 0.046012 seconds and 3 git commands to generate.