From 2b8bb0b705055bd6da8b09de1855254520c1a306 Mon Sep 17 00:00:00 2001
From: Quaternions <krakow20@gmail.com>
Date: Sun, 18 Aug 2024 14:42:02 -0700
Subject: [PATCH] bvh: remove unnecessary work

---
 src/bvh.rs | 28 +++++++++++++---------------
 1 file changed, 13 insertions(+), 15 deletions(-)

diff --git a/src/bvh.rs b/src/bvh.rs
index ee73355..b76c239 100644
--- a/src/bvh.rs
+++ b/src/bvh.rs
@@ -121,13 +121,11 @@ fn generate_bvh_node<T>(boxen:Vec<(T,Aabb)>,force:bool)->BvhNode<T>{
 			aabb,
 		}
 	}else{
-		let mut octant=std::collections::HashMap::with_capacity(n);//this ids which octant the boxen is put in
 		let mut sort_x=Vec::with_capacity(n);
 		let mut sort_y=Vec::with_capacity(n);
 		let mut sort_z=Vec::with_capacity(n);
 		for (i,(_,aabb)) in boxen.iter().enumerate(){
 			let center=aabb.center();
-			octant.insert(i,0);
 			sort_x.push((i,center.x()));
 			sort_y.push((i,center.y()));
 			sort_z.push((i,center.z()));
@@ -139,26 +137,26 @@ fn generate_bvh_node<T>(boxen:Vec<(T,Aabb)>,force:bool)->BvhNode<T>{
 		let median_x=sort_x[h].1;
 		let median_y=sort_y[h].1;
 		let median_z=sort_z[h].1;
-		for (i,c) in sort_x{
-			if median_x<c{
-				octant.insert(i,octant[&i]+1<<0);
-			}
+		//partition point gives the first index for which the predicate evaluates to false
+		let first_index_gt_median_x=sort_x.partition_point(|tup|!(median_x<tup.1));
+		let first_index_gt_median_y=sort_y.partition_point(|tup|!(median_y<tup.1));
+		let first_index_gt_median_z=sort_z.partition_point(|tup|!(median_z<tup.1));
+		//this ids which octant the boxen is put in
+		let mut octant=vec![0;n];
+		for &(i,_) in &sort_x[first_index_gt_median_x..]{
+			octant[i]+=1<<0;
 		}
-		for (i,c) in sort_y{
-			if median_y<c{
-				octant.insert(i,octant[&i]+1<<1);
-			}
+		for &(i,_) in &sort_y[first_index_gt_median_y..]{
+			octant[i]+=1<<1;
 		}
-		for (i,c) in sort_z{
-			if median_z<c{
-				octant.insert(i,octant[&i]+1<<2);
-			}
+		for &(i,_) in &sort_z[first_index_gt_median_z..]{
+			octant[i]+=1<<2;
 		}
 		//generate lists for unique octant values
 		let mut list_list=Vec::with_capacity(8);
 		let mut octant_list=Vec::with_capacity(8);
 		for (i,(data,aabb)) in boxen.into_iter().enumerate(){
-			let octant_id=octant[&i];
+			let octant_id=octant[i];
 			let list_id=if let Some(list_id)=octant_list.iter().position(|&id|id==octant_id){
 				list_id
 			}else{