1 #ifndef BUMPMAP_HXX
 2 #define BUMPMAP_HXX
 3 
 4 #include "Texture2D.hxx"
 5 
 6 class BumpMapping : public Image
 7 {
 8     private:
 9         Texture2D* texture;
10         int resX;
11         int resY;
12 
13     public:
14         /**
15          * load the BumpMapping texture
16          * with wrap mode 'repeat' and interpolation mode 'nearest'
17          */
18         BumpMapping(char* filename) : Image(1,1)
19         {           
20             texture = new Texture2D(filename);
21             texture->setWrapMode(Texture::REPEAT);
22             texture->setInterpolationMode(Texture::NEAREST);
23             resX = texture->getWidth();
24             resY = texture->getHeight();
25         };
26         
27         ~BumpMapping()
28         {
29             if (texture)
30                 delete texture;
31         };
32         
33         /** 
34          * This function computes the vector which has to be added to the normal vector at the hit point.
35          * Attention: This vector is not normalized yet ! (This is done in the PhongShader.)
36          
37          *  First compute the UV values at the hitpoint.
38          *  With 
39          *      px = (int) (u * ResX)
40          *      py = (int) (v * ResY)
41          *  the gradient in x-direction is then computed by taking the difference of the textures at (px-1,py) and (px+1,py)
42          *  and equivalent in y-direction by taking the difference of the textures at (px,py-1) and (px,py+1).
43          */                 
44         Vec3f GetNormal(Ray &ray)
45         {
46             Vec2f UV = ray.hit->GetUV(ray);
47             float u = UV.x();
48             float v = UV.y(); 
49 
50             Vec4f grad_x = texture->GetTexel( u - 1.0 / (float) resX, v) - texture->GetTexel( u + 1.0 / (float) resX, v);
51             Vec4f grad_y = texture->GetTexel( u, v - 1.0 / (float) resY) - texture->GetTexel( u, v + 1.0 / (float) resY);
52             
53             Vec3f normal = ray.hit->GetNormal(ray);
54             
55             // orthogonal system
56             Vec3f U = Cross(normal, -ray.dir);
57             Vec3f V = Cross(normal, U);
58             Normalize(U);
59             Normalize(V);
60     
61             Vec3f D = U * grad_x.xyz() + V * grad_y.xyz(); 
62             return D;   
63         };
64 };
65 
66 #endif


syntax highlighted by Code2HTML, v. 0.9.1