diff options
| author | Richard Qin <richard.qin.x@gmail.com> | 2026-03-09 23:31:27 +0800 |
|---|---|---|
| committer | Richard Qin <richard.qin.x@gmail.com> | 2026-03-09 23:31:27 +0800 |
| commit | 4014436905aace9acd47dde245b88bd5f69335ec (patch) | |
| tree | 412bb61300cdd225bf3f79f3927f6076f718f094 /apps | |
| parent | 7aa2a67d8381c9a88d69a3f53d74a7f079214263 (diff) | |
| download | ray-tracing-4014436905aace9acd47dde245b88bd5f69335ec.tar.gz ray-tracing-4014436905aace9acd47dde245b88bd5f69335ec.tar.xz | |
Sending Rays Into the Scene
Diffstat (limited to 'apps')
| -rw-r--r-- | apps/main.cc | 40 |
1 files changed, 36 insertions, 4 deletions
diff --git a/apps/main.cc b/apps/main.cc index b0b3aa4..d5702cd 100644 --- a/apps/main.cc +++ b/apps/main.cc @@ -15,16 +15,45 @@ * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "color.h" +#include "ray.h" #include "vec3.h" #include <iostream> +color ray_color( const ray& r ) +{ + vec3 unit_direction = unit_vector( r.direction() ); + auto a = 0.5 * ( unit_direction.y() + 1.0 ); + return ( 1.0 - a ) * color( 1.0, 1.0, 1.0 ) + a * color( 0.5, 0.7, 1.0 ); +} + int main() { // Image - const int image_width = 256; - const int image_height = 256; + auto aspect_ratio = 16.0 / 9.0; + const int image_width = 400; + // Calculate the image height, and ensure that it's at least 1. + int image_height = static_cast<int>( image_width / aspect_ratio ); + image_height = ( image_height < 1 ) ? 1 : image_height; + + // Camera + auto focal_length = 1.0; + auto viewport_height = 2.0; + auto viewport_width = viewport_height * ( double( image_width ) / image_height ); + auto camera_center = point3( 0, 0, 0 ); + + // Calculate the vectors across the horizontal and down the vertical viewport edges. + auto viewport_u = vec3( viewport_width, 0, 0 ); + auto viewport_v = vec3( 0, -viewport_height, 0 ); + + // Calculate the horizontal and vertical delta vectors from pixel to pixel. + auto pixel_delta_u = viewport_u / image_width; + auto pixel_delta_v = viewport_v / image_height; + + // Calculate the location of the upper left pixel. + auto viewport_upper_left = camera_center - vec3( 0, 0, focal_length ) - viewport_u / 2 - viewport_v / 2; + auto pixel00_loc = viewport_upper_left + 0.5 * ( pixel_delta_u + pixel_delta_v ); // Render @@ -32,8 +61,11 @@ int main() for ( int j = 0; j < image_height; j++ ) { std::clog << "\rScanlines remaining: " << ( image_height - j ) << ' ' << std::flush; for ( int i = 0; i < image_width; i++ ) { - auto pixel_color = color( - static_cast<double>( i ) / ( image_width - 1 ), static_cast<double>( j ) / ( image_height - 1 ), 0 ); + auto pixel_center = pixel00_loc + ( i * pixel_delta_u ) + ( j * pixel_delta_v ); + auto ray_direction = pixel_center - camera_center; + ray r( camera_center, ray_direction ); + + const color pixel_color = ray_color( r ); write_color( std::cout, pixel_color ); } } |
