Skip to content

Instantly share code, notes, and snippets.

@cfsamson
Last active March 9, 2019 17:52
Show Gist options
  • Save cfsamson/87ece37db60f58b015ba16150a9817c1 to your computer and use it in GitHub Desktop.
Save cfsamson/87ece37db60f58b015ba16150a9817c1 to your computer and use it in GitHub Desktop.
raytracer_memincrease_fix_2
// For the sake of brevity I won't repeat the code we replace here instead point out
// that this replaces lines 307-328 in our original code
const BYTES_PER_PIXEL: usize = 3;
fn main() {
// {...}
// first allocate a zeroed Vec<u8> to hold our results.
// btw: this initialization method is the fastest way to ask
// for zeroed memory: see https://github.com/rust-lang/rust/issues/54628
let mut bytes = vec![0u8; h as usize * w as usize * BYTES_PER_PIXEL];
bytes
// take mutable chunks of three items
.par_chunks_mut(BYTES_PER_PIXEL)
// Turn this into a parallel iterator using Rayon
.into_par_iter()
// reverse the order in which we iterate so our picture doesn't end upside down
.rev()
// enumerate() changes the closure argument from |item| => |(index, item)| tuple
.enumerate()
.for_each(|(idx, chunk)| {
// determine the x- and y-coordinates based on the index in row-major order
// https://en.wikipedia.org/wiki/Row-major_order
let y = (idx / w as usize) as f32;
let x = (idx % w as usize) as f32;
let mut color = Vec3::from(0.0);
for _ in 0..samples_count {
color = color
+ trace(
position,
!(goal
+ left * (x - w / 2.0 + random_val()).into()
+ up * (y - h / 2.0 + random_val()).into()),
);
}
color = color * (1.0 / samples_count as f32).into() + (14.0 / 241.0).into();
let o: Vec3 = color + Vec3::from(1.0);
color = Vec3::new_abc(color.x / o.x, color.y / o.y, color.z / o.z) * Vec3::from(255.0);
// We write the new values to our buffer
chunk[0] = color.x as u8;
chunk[1] = color.y as u8;
chunk[2] = color.z as u8;
});
file.write_all(&bytes).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment