I want to render each chunk in my voxel game separately from my main thread so I don’t get lag spikes each time I load part of the world, but I’m not sure how. I luckily have a diagram of my class structure below(I don’t know if this will format right on the forum here)
Player node may access Level
Level
|
L ChunkGrid
| |
| L ChunkGenerator
| |
| L ChunkRenderer
| |
| L Dictionary[Vector3i,Chunk]
| |
| |
| L PalettedVoxelGrid
| |
| L VoxelGrid
|
L (reference to filestructure)
Level = Node3D class that contains data referring to a point in the filesystem, and the ChunkGrid.
manages saving and loading to disk, and manages tracking the players that render the area around it
ChunkGrid = Node3D class that lets you manage contained chunks,
and contains methods for modifying data
ChunkGenerator = RefCounted class that contains data for how to generate a chunk,
and generates a chunk when passed in
Chunk = Node3D class that manages a single chunk, child of ChunkGrid, also has the mesh nodes as children
ChunkRenderer = Static RefCounted class that contains the methods for creating a chunks mesh data
VoxelGrid = simple RefCounted class for managing a 3d number array flattened into 1d
PalettedVoxelGrid = extension of VoxelGrid that uses indexes to let every block be a variant
also:
Block = The main Dictionary that holds all of the data for every block type, including the data to generate faces, and whether a block should backface cull neighbors.
Chunks inside ChunkGrid are stored inside a Dictionary[Vector3i, Chunk] variable, this is also where the render_chunk() method lives, that accesses ChunkRenderer with the chunk passed in and then sets the chunk ArrayMesh to its return value. So it seems like this is a good candidate to manage the multi-threading.
I was able to ask an LLM, and it told me to use something called a WorkerThreadPool to hold a bunch of worker threads, but I’m not sure how to get the logic to work with this, since generating any chunk can happen spontaneously here, and there will clearly be a lot of chunks. Perhaps I need a stack of the indexes of each chunk to render, and then I allocate one of the free threads to it when available?
(I’m really stumped on how Minecraft did this in 2009 on Java with one thread :p)
Ooh sorry forgot to explain that, by “render” I meant running the function that takes in a chunk class and it’s neighbors, scans through the PalettedVoxelGrid, generates faces, and outputs an ArrayMesh, which the chunk takes in and applies to its array mesh. Maybe face generation is the right term then. (This operation is very slow, and I’ve been meaning to rewrite it in C++)
Another feature of this, is I’m running array_mesh.create_trimesh_shape() on that arraymesh while it’s created to build the collision, which is also passed into the output chunk.
I’m not sure what you mean by profile the project, I do know that a 32^3 chunk face generation takes on average 200ms, and on average trimesh can take 10ms. Overall this slows down the project when new chunks are rendered immensely Either way I think multi threading is kinda the way.
I’m working on this exact same problem in my game right now.
I’ve got the basic system running.
You need:
A job scheduler
A job struct containing func < T > work (and whatever metadata you want to add like, job name, job category, date/ time depending on how ‘hardcore’ you want to be about it
The job scheduler has a ConcurrentQueue < T >(this is a specifically thread safe data structure)
A job worker (One per thread) that basically grabs jobs from the job queue as long as it’s active
Active threads will simply grab jobs as soon as they come up.
You can also have a job results struct with telemetry/ performance data if you want
That’s the simplest version of the system:
The main thread adds a bunch of Chunk bake jobs,
Threads grab them as fast as they can.
Boom. That’s pretty much it.
Worker thread loop:
private void WorkerLoop() {
while (running) {
if (JobQueue.TryDequeue(out var boxedJob)) {
ProcessJob(boxedJob);
}
else {
Thread.Sleep(10); // prevent CPU spin
}
}
}
And personally that’s about as far as I’m going to take it. Multithreading can become very complicated very quickly. Chunk bakes are pretty easy, low-hanging fruit because it’s unlikely that they’re going to have race conditions. Game logic, however? Multithreading patterns is a whole rabbit hole…
I just realized though I was talking to c sharp if you’re using GD script, you will have to create a workaround to the concurrent queue because GD script doesn’t have one. It does have something called a mutex class which you could use to replicate a concurrent queue.
Ooh that makes more sense that it lacks those features, I was looking at your code a little puzzled on how I would translate it to GDScript. I will report back on my look into Mutex.
In general, you can have a single worker thread that (slowly) builds anticipated chunks in the background so they are ready when the player/camera is in position to see them.
Btw using create_trimesh_shape() wastes time because it downloads mesh data from the GPU and potentially blocks the thread. Better to just use set_faces().
I finally came up with this class for a manager that lets you create jobs using WorkerThreadPool, and then execute them. I’m new to multi-threading so please give feedback. My game now runs reasonably at least now that I’ve applied this to both blockface generation, and world gen.
(Although large holes where chunks should be seem to happen randomly now, so maybe there’s a new problem…)
If anyone’s willing to peer-review this code, I would be happy so I could mark this as the answer for the next person.
# Creating a job is as simple as:
# var yourjobmanager = ThreadJobManager.new()
# yourjobmanager.create_job(
# "jobname",
# _background_threaded_function_to_run,
# _function_when_complete,
# )
# run a job as so:
# yourjobmanager.execute_job("jobname", unique_id, [arguments, go, here], bool for high priority)
# func _background_threaded_function_to_run( all, of, your, arguments, here):
# in here you can put the code that will run during the job
# please note a return is typically needed
# return value
# func _function_when_complete(id, returnvalue)
# you can do whatever you want with your return value here
# this part is now on the main thread
# would be nice if there was a way to cancel a job while it's active
extends RefCounted
class_name ThreadJobManager
var thread_jobs: Dictionary = {}
var jobs_to_redo: Dictionary = {}
var thread_job_outputs: Dictionary = {}
var job_list: Dictionary = {}
# I do not quite understand mutexes, I tried to follow what the docs do
var mutex: Mutex = Mutex.new()
# call this in a function that runs every frame please
func process_completed_jobs() -> void:
# jobs are grouped by type, and then id
# type is a string
# id is a variant and can be anything
var job_type_keys = thread_jobs.keys()
for job_type in job_type_keys:
var job_id_keys = thread_jobs[job_type].keys()
for job_id in job_id_keys:
var job_task_id = thread_jobs[job_type][job_id].task_id
# unsure of my usage of WorkerThreadPool here
# admittedly I asked for an LLM for help with that one
# would it be better to create the threads and assign them manually?
# I'm going to stick with this though
if WorkerThreadPool.is_task_completed(job_task_id):
WorkerThreadPool.wait_for_task_completion(job_task_id)
mutex.lock()
thread_jobs[job_type].erase(job_id)
mutex.unlock()
if thread_job_outputs.has(job_type) and thread_job_outputs[job_type].has(job_id):
var output = thread_job_outputs[job_type][job_id]
job_list[job_type].success_function.call(job_id, output)
mutex.lock()
thread_job_outputs[job_type].erase(job_id)
mutex.unlock()
if jobs_to_redo.has(job_type) and jobs_to_redo[job_type].has(job_id):
var redo_options = jobs_to_redo[job_type][job_id]
mutex.lock()
jobs_to_redo[job_type].erase(job_id)
mutex.unlock()
execute_job(redo_options.type, job_id, redo_options.arguments)
# create a job and add it to the job list
# if only we could do that in real life
func create_job(name: String, job_function: Callable, success_function: Callable) -> void:
job_list[name] = {
"job_function": job_function,
"success_function": success_function,
}
func execute_job(job_type: String, job_id: Variant, arguments: Array = [], high_priority := false) -> void:
if !job_list.has(job_type):
push_error("No such job \"" + job_type + "\" exists!")
return
var job = job_list[job_type]
mutex.lock()
if !thread_jobs.has(job_type):
thread_jobs[job_type] = {}
if thread_jobs[job_type].has(job_id):
if !jobs_to_redo.has(job_type):
jobs_to_redo[job_type] = {}
jobs_to_redo[job_type][job_id] = {
"type": job_type,
"arguments": arguments,
}
# don't forget to unlock the mutex before returning!
mutex.unlock()
return
var job_task = WorkerThreadPool.add_task(
_execute_job_thread.bind(
job_id,
job_type,
job["job_function"],
arguments,
),
high_priority
)
# task id is inside a dictionary here because of previous decisions
thread_jobs[job_type][job_id] = {"task_id": job_task}
mutex.unlock()
# now run the job called
func _execute_job_thread(job_id: Variant, job_type: String, job_function: Callable, args: Array) -> void:
var output = job_function.callv(args)
mutex.lock()
if !thread_job_outputs.has(job_type):
thread_job_outputs[job_type] = {}
thread_job_outputs[job_type][job_id] = output
mutex.unlock()
You could probably use WorkerThreadPool more directly, what is the function are you trying to background; specifically what is it’s input and output, the arguments it takes in and any global state it reads or alters?
Your bottlenecks here are Dictionary lookups and if statements. I would try to simplify.
I would remove job type as a layer. You can still include it as metadata but you can significantly speed things up by removing double lookups like.
thread_jobs[job_type][job_id].task_id
(dictionary lookups are slow)
And if you can reduce the number of branching statements that will help too
I haven’t had to work on the multi-threading much recently, so I’m decidedly happy with my solution, so I’m going to mark this as solved for now. Thanks to everyone for your help, I wouldn’t have been able to figure it out otherwise.