fixed chunk loading/saving freezes

Commit f6799850845e · mgecumshooter · 2026-10-22 07:26 +0300

Changeset
f6799850845e1637f23fc3b44c2c1f2ba937096d

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/src/world/mod.rs b/src/world/mod.rs
--- a/src/world/mod.rs
+++ b/src/world/mod.rs
@@ -31,11 +31,23 @@
 	}
     }
 
+
     pub fn load_around_player(&mut self, player_pos: Vector3) {
+	const LOAD_PER_FRAME: usize = 2;
+
+	let mut loaded_this_frame = 0;
+	
 	let p_chunk_x = (player_pos.x / CHUNK_SIZE as f32).floor() as i32;
 	let p_chunk_y = (player_pos.y / CHUNK_SIZE as f32).floor() as i32;
 	let p_chunk_z = (player_pos.z / CHUNK_SIZE as f32).floor() as i32;
 
+	let player_chunk = (p_chunk_x, p_chunk_y, p_chunk_z);
+	if !self.chunks.contains_key(&player_chunk) {
+            let pos_v3 = Vector3::new(player_chunk.0 as f32, player_chunk.1 as f32, player_chunk.2 as f32);
+            let chunk = Chunk::load_from_disk(pos_v3).unwrap_or_else(|| Chunk::new(pos_v3));
+            self.chunks.insert(player_chunk, chunk);
+	}
+
 	let mut needed_chunks = Vec::new();
 
 	let r = self.render_distance;
@@ -49,7 +61,7 @@
 			);
 			needed_chunks.push(chunk_coords);
 
-			if !self.chunks.contains_key(&chunk_coords) {
+			if  loaded_this_frame < LOAD_PER_FRAME && !self.chunks.contains_key(&chunk_coords) {
 			    let pos_v3 = Vector3::new(chunk_coords.0 as f32,
 						      chunk_coords.1 as f32,
 						      chunk_coords.2 as f32,
@@ -59,6 +71,7 @@
 			    });
 
 			    self.chunks.insert(chunk_coords, chunk);
+			    loaded_this_frame += 1;
 			}
 		    }
 		}
@@ -69,6 +82,9 @@
 	for &coords in self.chunks.keys() {
 	    if !needed_chunks.contains(&coords) {
 		to_unload.push(coords);
+		if to_unload.len() >= LOAD_PER_FRAME {
+		    break;
+		}
 	    }
 	}
 	for coords in to_unload {
@@ -78,3 +94,4 @@
 	}
     }
 }
+