From 4e9778bffcdf1f5e77ef6fe9bafdc0c756d4dc95 Mon Sep 17 00:00:00 2001 From: mindv0rtex Date: Fri, 26 Feb 2021 14:46:43 -0500 Subject: [PATCH] Make horizontal blur parallel. --- src/blur.rs | 31 +++++++++++++++++-------------- src/main.rs | 2 ++ src/model.rs | 13 +++++++++---- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/blur.rs b/src/blur.rs index 72e8261..5dcf603 100644 --- a/src/blur.rs +++ b/src/blur.rs @@ -1,4 +1,5 @@ use itertools::multizip; +use rayon::prelude::*; #[derive(Debug)] pub struct Blur { @@ -56,21 +57,23 @@ impl Blur { let weight = 1.0 / (2 * radius + 1) as f32; let width = self.width; - for (src_row, dst_row) in src.chunks_exact(width).zip(dst.chunks_exact_mut(width)) { - // First we build a value for the beginning of each row. We assume periodic boundary - // conditions, so we need to push the left index to the opposite side of the row. - let mut value = src_row[width - radius - 1]; - for j in 0..radius { - value += src_row[width - radius + j] + src_row[j]; - } + src.par_chunks_exact(width) + .zip(dst.par_chunks_exact_mut(width)) + .for_each(|(src_row, dst_row)| { + // First we build a value for the beginning of each row. We assume periodic boundary + // conditions, so we need to push the left index to the opposite side of the row. + let mut value = src_row[width - radius - 1]; + for j in 0..radius { + value += src_row[width - radius + j] + src_row[j]; + } - for i in 0..width { - let left = (i + width - radius - 1) & (width - 1); - let right = (i + radius) & (width - 1); - value += src_row[right] - src_row[left]; - dst_row[i] = value * weight; - } - } + for i in 0..width { + let left = (i + width - radius - 1) & (width - 1); + let right = (i + radius) & (width - 1); + value += src_row[right] - src_row[left]; + dst_row[i] = value * weight; + } + }) } /// Perform one pass of the 1D box filter of the given radius along y axis. Applies the decay diff --git a/src/main.rs b/src/main.rs index 702765c..3143b55 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,4 +5,6 @@ fn main() { println!("{:#?}", model); model.step(); println!("{:#?}", model); + model.step(); + println!("{:#?}", model); } diff --git a/src/model.rs b/src/model.rs index 927f650..6c84cc6 100644 --- a/src/model.rs +++ b/src/model.rs @@ -134,10 +134,13 @@ impl Model { /// Perform a single simulation step. pub fn step(&mut self) { // To avoid borrow-checker errors inside the parallel loop. - let sensor_distance = self.config.sensor_distance; - let sensor_angle = self.config.sensor_angle; - let rotation_angle = self.config.rotation_angle; - let step_distance = self.config.step_distance; + let PopulationConfig { + sensor_distance, + sensor_angle, + rotation_angle, + step_distance, + .. + } = self.config; let (width, height) = (self.width, self.height); let grid = &self.grid; @@ -161,5 +164,7 @@ impl Model { }); // Deposit + Diffuse + Decay + + self.iteration += 1; } }