11import gzip
2+ import os
23import pickle
34import nbtlib as nbt
45import base36
@@ -25,13 +26,23 @@ def chunk_position_to_path(self, chunk_position):
2526
2627 return chunk_path
2728
28- def load_chunk (self , chunk_position ):
29- # load the chunk file
30-
29+ def chunk_position_to_nbt_and_cache_path (self , chunk_position ):
3130 chunk_path = self .chunk_position_to_path (chunk_position )
3231 cache_path = f"{ chunk_path } .cache"
3332
33+ return chunk_path , cache_path
34+
35+ def load_chunk (self , chunk_position ):
36+ # Load the chunk file.
37+
38+ chunk_path , cache_path = self .chunk_position_to_nbt_and_cache_path (chunk_position )
39+
3440 try :
41+ # Invalidate cache if the chunk file is newer than it.
42+
43+ if os .path .getmtime (cache_path ) < os .path .getmtime (chunk_path ):
44+ raise FileNotFoundError ()
45+
3546 with gzip .open (cache_path ) as f :
3647 blocks = pickle .load (f )
3748
@@ -40,26 +51,26 @@ def load_chunk(self, chunk_position):
4051 chunk_data = nbt .load (chunk_path )
4152 blocks = list (map (int , chunk_data ["Level" ]["Blocks" ]))
4253
43- # cache blocks
54+ # Cache blocks.
4455
4556 with gzip .open (cache_path , "wb" ) as f :
4657 pickle .dump (blocks , f )
4758
4859 except FileNotFoundError :
49- return
60+ return # Fail quietly if chunk file not found.
5061
51- # create chunk and fill it with the blocks from our chunk file
62+ # Create chunk and fill it with the blocks from our chunk file.
5263
5364 self .world .chunks [chunk_position ] = Chunk (self .world , chunk_position )
5465 self .world .chunks [chunk_position ].copy_blocks (blocks )
5566
5667 def save_chunk (self , chunk_position ):
5768 x , y , z = chunk_position
5869
59- # try to load the chunk file
60- # if it doesn't exist, create a new one
70+ # Try to load the chunk file.
71+ # If it doesn't exist, create a new one.
6172
62- chunk_path = self .chunk_position_to_path (chunk_position )
73+ chunk_path , cache_path = self .chunk_position_to_nbt_and_cache_path (chunk_position )
6374
6475 try :
6576 chunk_data = nbt .load (chunk_path )
@@ -70,7 +81,7 @@ def save_chunk(self, chunk_position):
7081 chunk_data ["Level" ]["xPos" ] = x
7182 chunk_data ["Level" ]["zPos" ] = z
7283
73- # fill the chunk file with the blocks from our chunk
84+ # Fill the chunk file with the blocks from our chunk.
7485
7586 chunk_blocks = nbt .ByteArray ([0 ] * (CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_LENGTH ))
7687
@@ -80,7 +91,12 @@ def save_chunk(self, chunk_position):
8091 block = self .world .chunks [chunk_position ].blocks [x ][y ][z ]
8192 chunk_blocks [x * CHUNK_LENGTH * CHUNK_HEIGHT + z * CHUNK_HEIGHT + y ] = block
8293
83- # save the chunk file
94+ # Save a cache file.
95+
96+ with gzip .open (cache_path , "wb" ) as f :
97+ pickle .dump (chunk_blocks , f )
98+
99+ # Save the chunk file.
84100
85101 chunk_data ["Level" ]["Blocks" ] = chunk_blocks
86102 chunk_data .save (chunk_path , gzipped = True )
0 commit comments