Created
March 4, 2019 18:15
-
-
Save cfsamson/87b90a9704da75fdc81e3a28142c18c9 to your computer and use it in GitHub Desktop.
Optimizing the code part 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -------- Our main function will change from this -------- | |
fn main() { | |
// {...} | |
for y in (0..h as u64).rev() { | |
for x in (0..w as u64).rev() { | |
let mut color = Vec3::from(0.0); | |
for _ in (0..samples_count).rev() { | |
color = color | |
+ trace( | |
position, | |
!(goal | |
+ left * (x as f32 - w / 2.0 + random_val()).into() | |
+ up * (y as f32 - 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); | |
file.write_all(&[color.x as u8, color.y as u8, color.z as u8]).unwrap(); | |
} | |
} | |
} | |
// -------- Into this --------- | |
fn main() { | |
// {...} | |
let mut pixels: Vec<(f32, f32)> = vec![]; | |
for y in (0..h as u64).rev() { | |
for x in (0..w as u64).rev() { | |
pixels.push((y as f32, x as f32)); | |
} | |
} | |
let bytes: Vec<u8> = pixels.iter().flat_map(|(y, x)| { | |
let mut color = Vec3::from(0.0); | |
for _ in (0..samples_count).rev() { | |
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); | |
vec![color.x as u8, color.y as u8, color.z as u8] | |
}).collect(); | |
file.write_all(&bytes).unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment