Skip to content

Commit

Permalink
chunk: Load chunks progressively
Browse files Browse the repository at this point in the history
  • Loading branch information
obiwac committed Dec 26, 2023
1 parent 5853662 commit 59746e1
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 16 deletions.
6 changes: 5 additions & 1 deletion chunk.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ class Chunk:
self.ibo = gl.GLuint(0)
gl.glGenBuffers(1, self.ibo)

@property
def loaded(self):
return self.c.index_count > 0

def get_block(self, x, y, z):
return self.c.get_blocks(
x * CHUNK_LENGTH * CHUNK_HEIGHT +
Expand Down Expand Up @@ -175,7 +179,7 @@ class Chunk:
update_mesh(self)

def draw(self):
if not self.c.index_count:
if not self.loaded:
return

gl.glBindVertexArray(self.vao)
Expand Down
28 changes: 28 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import world
import hit

from chunk_common import CHUNK_WIDTH, CHUNK_HEIGHT, CHUNK_LENGTH

class Window(pyglet.window.Window):
def __init__(self, **args):
super().__init__(**args)
Expand Down Expand Up @@ -40,6 +42,32 @@ def update(self, delta_time):

self.world.player.update(delta_time)

# load the closest chunk which hasn't been loaded yet

x, y, z = self.world.player.position
closest_chunk = None
min_distance = math.inf

for chunk_pos, chunk in self.world.chunks.items():
if chunk.loaded:
continue

cx, cy, cz = chunk_pos

cx *= CHUNK_WIDTH
cy *= CHUNK_HEIGHT
cz *= CHUNK_LENGTH

dist = (cx - x) ** 2 + (cy - y) ** 2 + (cz - z) ** 2

if dist < min_distance:
min_distance = dist
closest_chunk = chunk

if closest_chunk is not None:
closest_chunk.update_subchunk_meshes()
closest_chunk.update_mesh()

# update other entities

for entity in self.world.entities:
Expand Down
10 changes: 0 additions & 10 deletions save.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,6 @@ def load_chunk(self, chunk_position):
self.world.chunks[chunk_position] = chunk.Chunk(self.world, chunk_position)
self.world.chunks[chunk_position].copy_blocks(blocks)

"""
for x in range(chunk.CHUNK_WIDTH):
for y in range(chunk.CHUNK_HEIGHT):
for z in range(chunk.CHUNK_LENGTH):
self.world.chunks[chunk_position].blocks[x][y][z] = blocks[
x * chunk.CHUNK_LENGTH * chunk.CHUNK_HEIGHT +
z * chunk.CHUNK_HEIGHT +
y]
"""

# load entities from chunk

for entity in entities:
Expand Down
5 changes: 0 additions & 5 deletions world.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,8 @@ def __init__(self, width, height):

self.chunks = {}
self.entities = []

self.save.load()

for chunk_position in self.chunks:
self.chunks[chunk_position].update_subchunk_meshes()
self.chunks[chunk_position].update_mesh()

# create player

self.player = player.Player(self, width, height)
Expand Down

0 comments on commit 59746e1

Please sign in to comment.