11 void render(const std::vector<Sphere> &spheres, const std::vector<Light> &lights,const Cam &cam) {
12 const float fov = cam.fov;
13 std::vector<vec3> framebuffer(SCREEN_WIDTH*SCREEN_HEIGHT);
16 #pragma omp parallel for
17 for (size_t j = 0; j<SCREEN_HEIGHT; j++) { // actual rendering loop
18 for (size_t i = 0; i<SCREEN_WIDTH; i++) {
19 float dir_x = (i + 0.5) - SCREEN_WIDTH/2.;
20 float dir_y = -(j + 0.5) + SCREEN_HEIGHT/2.; // this flips the image at the same time
21 float dir_z = -SCREEN_HEIGHT/(2.*tan(fov/2.));
22 framebuffer[i+j*SCREEN_WIDTH] = cast_ray(cam.pos, ((vec3{dir_x, dir_y, dir_z}+cam.dir)).normalize(), spheres, lights);
26 char * texture_pixels = sdl_pixels_lock();
28 for (vec3 &c : framebuffer) {
29 float max = std::max(c[0], std::max(c[1], c[2]));
30 if (max>1) c = c*(1./max);
31 texture_pixels[index++] = (char)(255 * c[0]);
32 texture_pixels[index++] = (char)(255 * c[1]);
33 texture_pixels[index++] = (char)(255 * c[2]);
40 void signal_hand(int signum) {
41 std::cout << "Caught signal " << signum << std::endl;
46 int winsizeX, winsizeY;
47 signal(SIGINT, signal_hand);
50 printf( "Failed to initialize!\n" );
54 //Free resources and close SDL
55 const Material ivory = {1.0, {0.6, 0.3, 0.1, 0.0}, {0.4, 0.4, 0.3}, 50.};
56 const Material glass = {1.5, {0.0, 0.5, 0.1, 0.8}, {0.6, 0.7, 0.8}, 125.};
57 const Material red_rubber = {1.0, {0.9, 0.1, 0.0, 0.0}, {0.3, 0.1, 0.1}, 10.};
58 const Material mirror = {1.0, {0.0, 10.0, 0.8, 0.0}, {1.0, 1.0, 1.0}, 1425.};
60 std::vector<Sphere> spheres = {
61 Sphere{vec3{-3, 0, -16}, 2, ivory},
62 Sphere{vec3{-1.0, -1.5, -12}, 2, glass},
63 Sphere{vec3{ 1.5, -0.5, -18}, 3, red_rubber},
64 Sphere{vec3{ 7, 5, -18}, 4, mirror}
67 std::vector<Light> lights = {
69 {{ 30, 50, -25}, 1.8},
84 while( SDL_PollEvent( &event ) )
86 if( event.type == SDL_QUIT )
88 if(event.type == SDL_MOUSEMOTION){
89 SDL_GetMouseState(&x,&y);
90 SDL_GetWindowSize(sdl_getwindow(), &winsizeX,&winsizeY);
91 cam.dir = vec3{((float)x)*((float)SCREEN_WIDTH/(float)winsizeX),((float)-y)*((float)SCREEN_HEIGHT/(float)winsizeY),0};
93 if( event.type == SDL_KEYDOWN )
95 //Select surfaces based on key press
96 switch( event.key.keysym.sym )
121 render(spheres, lights,cam);
125 return -2; // We shouldn't get here