T3 Using Images as Textures (MS3)

Use Sphere u, v texture Coordinates

Add a private static member function in class sphere to calcuate the spherical texture coordinates

class sphere : public hittable {
  private:
    point3 center;
    double radius;
    shared_ptr<material> mat; 
    aabb bbox;  

    // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    static void get_sphere_uv(const point3& p, double& u, double& v) {
        // p: a given point on the sphere of radius one, centered at the origin.
        // u: returned value [0,1] of angle around the Y axis from X=-1.
        // v: returned value [0,1] of angle from Y=-1 to Y=+1.
        //     <1 0 0> yields <0.50 0.50>       <-1  0  0> yields <0.00 0.50>
        //     <0 1 0> yields <0.50 1.00>       < 0 -1  0> yields <0.50 0.00>
        //     <0 0 1> yields <0.25 0.50>       < 0  0 -1> yields <0.75 0.50>

        auto theta = std::acos(-p.y());
        auto phi = std::atan2(-p.z(), p.x()) + pi;

        u = phi / (2*pi);
        v = theta / pi;
    }
    // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    
    // ...
};

Update sphere::hit() to use get_sphere_uv()

Use Images as Textures

Note: This chapter is slightly different from Prof. Shirley's tutorial.

We are using images in a similar way to our Semester 1.

Use stb_image.h

We have been using stb_image.h from semester 1.

It is similar to use it here

Download stb_image.h from github

Copy stb_image.h to include/stb in your root folder.

Check your CMakeLists.txt to ensure the include directory is set

Add class image_texture in texture.h

Do not forget to add rtw_stb_image.h in the header section

Create and use the images folder

Create a images folder in your root folder

Add instructions at the end of your CMakeLists.txt to copy those images to your build folder

Download earthmap.jpg

Download earthmap.jpg from https://raytracing.github.io/images/earthmap.jpgarrow-up-right and save it in the images folder.

Add rtw_stb_image.h in your source folder

You don't need to study this file, we just use it directly.

You can directly download the file from https://github.com/RayTracing/raytracing.github.io/blob/release/src/TheNextWeek/rtw_stb_image.harrow-up-right

I changed #include "external/stb_image.h" to my #include "stb/stb_image.h".

If you are following Prof. Shirley's tutorial totally, you can stick to the original version.

Draw a textured sphere in main.cpp

Build and Run

If successful, you can see a texture mapped globe. Mine looks too dark because there is no Gamma correction.

The following is the rendering with Gamma correction:

Last updated