From 3935a609141623e7cfb3fa339da1a166e3917018 Mon Sep 17 00:00:00 2001 From: ladevieq Date: Sun, 20 Dec 2020 14:49:20 +0100 Subject: Ray tracer renderer Use ray for rendering Setup basic rendering stuff camera / viewport --- src/main.cpp | 63 +++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 16 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 8049bac..e3b69b1 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,31 +2,62 @@ #include "color.hpp" #include "vec3.hpp" +#include "ray.hpp" + +color ray_color(ray& r) { + auto unit_dir = r.direction.unit(); + auto t = (unit_dir.y + 1.0) * 0.5; + + return (1.0 - t) * color(1.0, 1.0, 1.0) + t * color(0.5, 0.7, 1.0); +} int main() { - size_t width = 256; - size_t height = 256; + // Image dimensions + const size_t width = 400; + const size_t height = width / (16.0 / 9.0); + // const size_t width = 256; + // const size_t height = 256; - // PPM format header - std::cout << "P3" << std::endl; + const double aspect_ratio = width / height; + + // Viewport dimensions + const double viewport_width = 2.0; + const double viewport_height = viewport_width / aspect_ratio; + + // Unit vectors for viewport pixels + const vec3 horizontal { viewport_width / width, 0.0, 0.0 }; + const vec3 vertical { 0.0, viewport_height / height, 0.0 }; + std::cerr << "Horizontal : " << horizontal << std::endl; + std::cerr << "Vertical : " << vertical << std::endl; - std::cout << width << std::endl; - std::cout << height << std::endl; + // We use a right handed coord system + const point3 eye_pos {}; + const double focal_length = 1.0; - // Max color - std::cout << "255" << std::endl; + const point3 viewport_first_pixel = + horizontal * -(viewport_width / 2.0) + + vertical * -(viewport_height / 2.0) + + point3{ 0.0, 0.0, -focal_length }; + + const point3 first_pixel = eye_pos + viewport_first_pixel; + + // PPM format header + std::cout << "P3\n" << width << '\n' << height << "\n 255" << std::endl; std::cerr << "Generating image" << std::endl; - for (size_t column = 0; column < width; column++) { - std::cerr << width - column << " lines remaining" << std::endl; + for (ssize_t row = height - 1; row >= 0; row--) { + std::cerr << height - row << " lines remaining" << std::endl; + for (size_t column = 0; column < width; column++) { + vec3 x = horizontal * column; + vec3 y = vertical * row; + + vec3 pixel_pos = first_pixel + x + y; + vec3 direction = pixel_pos - eye_pos; + + ray ray { eye_pos, direction }; - for (size_t row = 0; row < height; row++) { - auto r = double(column) / (width-1); - auto g = double(row) / (height-1); - auto b = 0.25; - color c(r, g, b); - write_color(std::cout, c); + write_color(std::cout, ray_color(ray)); } } -- cgit v1.3