Skip to content

Commit

Permalink
Render sphere hits
Browse files Browse the repository at this point in the history
The left sphere looks deformed, look into it.
  • Loading branch information
jstasiak committed Jul 8, 2019
1 parent a020f84 commit 2d5b3bf
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 12 deletions.
Binary file modified output.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 15 additions & 10 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,20 +281,21 @@ pub fn posunit_to_unit(value: f32) -> f32 {

pub struct Radians(pub f32);

pub fn render(width: usize, height: usize) -> Image {
pub fn render(spheres: &[Sphere], camera: &Camera, width: usize, height: usize) -> Image {
let mut image = Image::new(width, height);
let max = (width * height) as f32;
for i in 0..width {
for j in 0..height {
image.set_color(
i,
j,
Color::new(
i as f32 / width as f32,
j as f32 / height as f32,
i as f32 * j as f32 / max,
),
// -1s here because we want to provide x and y coordinates between 0 and 1 inclusive
let ray = camera.screen_ray(
i as f32 / (width - 1) as f32,
j as f32 / (height - 1) as f32,
);
let intersection = closest_intersection(&spheres, &ray);
let color = match intersection {
Intersection::None => Color::new_black(),
Intersection::Hit(_) => Color::new_red(),
};
image.set_color(i, j, color);
}
}
image
Expand Down Expand Up @@ -390,4 +391,8 @@ impl Color {
pub fn new_black() -> Color {
Self::new(0.0, 0.0, 0.0)
}

pub fn new_red() -> Color {
Self::new(1.0, 0.0, 0.0)
}
}
37 changes: 35 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use raytracer::{image_to_file, render};
use raytracer::{image_to_file, render, Camera, Radians, Sphere, Vector};
use std::env;
use std::fs::File;
use std::io::{self, Write};
Expand All @@ -20,6 +20,39 @@ fn main() {
_ => Box::new(File::create(filename).expect("Cannot open file for writing")),
};

let image = render(200, 100);
let spheres = [
Sphere {
center: Vector {
x: 0.0,
y: 0.0,
z: -5.0,
},
radius: 1.0,
},
Sphere {
center: Vector {
x: -3.0,
y: 1.0,
z: -5.0,
},
radius: 1.0,
},
Sphere {
center: Vector {
x: 5.0,
y: 1.0,
z: -10.0,
},
radius: 1.0,
},
];
let camera = Camera {
position: Vector::zero(),
forward: -Vector::unitz(),
up: Vector::unity(),
aspect_ratio: 4.0 / 3.0,
fovx: Radians(90.0f32.to_radians()),
};
let image = render(&spheres, &camera, 800, 600);
image_to_file(&image, &mut file);
}

0 comments on commit 2d5b3bf

Please sign in to comment.