From cf49cdbb026719d49c2a806681fdef4af5c85f3b Mon Sep 17 00:00:00 2001 From: Nathan Vegdahl Date: Sun, 14 Aug 2016 16:03:17 -0700 Subject: [PATCH] Moved int hash functions into own file, and use in quick_select(). --- src/algorithm.rs | 13 ++++++++++++- src/hash.rs | 23 +++++++++++++++++++++++ src/main.rs | 1 + src/renderer.rs | 14 +------------- 4 files changed, 37 insertions(+), 14 deletions(-) create mode 100644 src/hash.rs diff --git a/src/algorithm.rs b/src/algorithm.rs index 5208691..8c81e6a 100644 --- a/src/algorithm.rs +++ b/src/algorithm.rs @@ -4,6 +4,7 @@ use std; use std::cmp; use std::cmp::Ordering; use lerp::{Lerp, lerp_slice}; +use hash::hash_u64; /// Partitions a slice in-place with the given unary predicate, returning /// the index of the first element for which the predicate evaluates @@ -120,9 +121,10 @@ pub fn quick_select(slc: &mut [T], n: usize, mut order: F) { let mut left = 0; let mut right = slc.len(); + let mut seed = n as u64; loop { - let i = (left + right) / 2; + let i = left + (hash_u64(right as u64, seed) as usize % (right - left)); slc.swap(i, right - 1); let ii = left + @@ -139,6 +141,8 @@ pub fn quick_select(slc: &mut [T], n: usize, mut order: F) } else { left = ii + 1; } + + seed += 1; } } @@ -241,4 +245,11 @@ mod tests { quick_select_ints(&mut list, 0); assert_eq!(list[0], 0); } + + #[test] + fn quick_select_4() { + let mut list = [8, 9, 7, 4, 6, 1, 0, 5, 3, 2]; + quick_select_ints(&mut list, 9); + assert_eq!(list[9], 9); + } } diff --git a/src/hash.rs b/src/hash.rs new file mode 100644 index 0000000..b9c5e0a --- /dev/null +++ b/src/hash.rs @@ -0,0 +1,23 @@ +pub fn hash_u32(n: u32, seed: u32) -> u32 { + let mut hash = n; + + for _ in 0..3 { + hash = hash.wrapping_mul(1936502639); + hash ^= hash.wrapping_shr(16); + hash = hash.wrapping_add(seed); + } + + return hash; +} + +pub fn hash_u64(n: u64, seed: u64) -> u64 { + let mut hash = n; + + for _ in 0..4 { + hash = hash.wrapping_mul(32416190071 * 314604959); + hash ^= hash.wrapping_shr(32); + hash = hash.wrapping_add(seed); + } + + return hash; +} diff --git a/src/main.rs b/src/main.rs index 555ee18..c6688ce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,6 +36,7 @@ mod scene; mod assembly; mod halton; mod sampling; +mod hash; mod color; mod shading; diff --git a/src/renderer.rs b/src/renderer.rs index 28a6937..1f3f7b8 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -12,6 +12,7 @@ use ray::Ray; use tracer::Tracer; use halton; use hilbert; +use hash::hash_u32; use math::{fast_logit, upper_power_of_two}; use image::Image; use surface; @@ -373,16 +374,3 @@ struct BucketJob { w: u32, h: u32, } - - -fn hash_u32(n: u32, seed: u32) -> u32 { - let mut hash = n; - - for _ in 0..3 { - hash = hash.wrapping_mul(1936502639); - hash ^= hash.wrapping_shr(16); - hash = hash.wrapping_add(seed); - } - - return hash; -}