Fixed minor issues in the parallized version of render loop

This commit is contained in:
Ishan Jain 2020-02-28 22:15:33 +05:30
parent df6d27d5c8
commit 232d3350a2
2 changed files with 36 additions and 42 deletions

View File

@ -19,7 +19,11 @@ pub use surface_normal_sphere::SurfaceNormalSphere;
use { use {
crate::{HORIZONTAL_PARTITION, VERTICAL_PARTITION}, crate::{HORIZONTAL_PARTITION, VERTICAL_PARTITION},
rayon::prelude::*, rayon::prelude::*,
std::{fs::File, io::Write}, std::{
fs::File,
io::Write,
sync::{Arc, Mutex},
},
}; };
#[derive(Debug)] #[derive(Debug)]
@ -38,51 +42,41 @@ pub trait Demo: std::marker::Sync {
let nx = width / VERTICAL_PARTITION; let nx = width / VERTICAL_PARTITION;
let ny = height / HORIZONTAL_PARTITION; let ny = height / HORIZONTAL_PARTITION;
let mut chunks: Vec<Chunk> = Vec::with_capacity(HORIZONTAL_PARTITION * VERTICAL_PARTITION); let buf = Arc::new(Mutex::new(buf));
for j in 0..VERTICAL_PARTITION { (0..VERTICAL_PARTITION).into_par_iter().for_each(move |j| {
for i in 0..HORIZONTAL_PARTITION { let buf = buf.clone();
let start_y = j * ny; (0..HORIZONTAL_PARTITION)
let start_x = i * nx; .into_par_iter()
let chunk = Chunk { .for_each(move |i| {
x: width, let start_y = j * ny;
y: height, let start_x = i * nx;
nx, let x = width;
ny, let y = height;
start_x, let mut chunk = Chunk {
start_y, x,
buffer: vec![0; nx * ny * 4], y,
}; nx,
chunks.push(chunk); ny,
} start_x,
} start_y,
buffer: vec![0; nx * ny * 4],
};
self.render_chunk(&mut chunk, samples);
chunks let mut buf = buf.lock().unwrap();
.par_iter_mut()
.for_each(|mut chunk| self.render_chunk(&mut chunk, samples));
for chunk in chunks { let mut temp_offset = 0;
let x = chunk.x; for j in start_y..start_y + ny {
let y = chunk.y; let real_offset = ((y - j - 1) * x + start_x) * 4;
let nx = chunk.nx;
let ny = chunk.ny;
let start_x = chunk.start_x;
let start_y = chunk.start_y;
let buffer = chunk.buffer;
let mut temp_offset = 0; buf[real_offset..real_offset + nx * 4]
for j in start_y..start_y + ny { .copy_from_slice(&chunk.buffer[temp_offset..temp_offset + nx * 4]);
for i in start_x..start_x + nx {
let real_offset = ((y - j - 1) * x + i) * 4;
for k in 0..4 { temp_offset += nx * 4;
buf[real_offset + k] = buffer[temp_offset + k];
} }
})
temp_offset += 4; });
}
}
}
} }
fn render_chunk(&self, chunk: &mut Chunk, samples: u8); fn render_chunk(&self, chunk: &mut Chunk, samples: u8);

View File

@ -100,8 +100,8 @@ fn main() -> Result<(), String> {
} }
if should_update { if should_update {
active_demo.render(&mut buffer, width, height, NUM_SAMPLES); active_demo.render(&mut buffer, width, height, NUM_SAMPLES);
texture.update(None, &buffer, width * 4); texture.update(None, &buffer, width * 4).unwrap();
canvas.copy(&texture, None, None); canvas.copy(&texture, None, None).unwrap();
canvas.present(); canvas.present();
should_update = false; should_update = false;
} }