Sunday, May 13, 2018

c++ - Optimized rendering of a cube mesh world


I want to render a cube-mesh (a.k.a. Minecraft-style) world. If I render each existing cube it will eat up FPS pretty quickly. How can I optimize it? I understand that the point is to not render invisible meshes (faces?) but my problem is to find out what is invisible and what isn't.



Answer



You'll have good use of a isSolidAt(x,y,z) function. This will be useful for not only the action you want to preform, but other things such as collision checking.


Basically you want to iterate through your cubes and check which faces will be hidden. You know they're hidden when the adjacent cube is solid. For example some pseudo code:


Verticies[] verticesToDraw
for(x = 0 to x = chunkXMax)
for(y = 0 to y = chunkYMax)

for(z = 0 to z = chunkZMax)
if(!isSolidAt(x+1,y,z))
verticesToDraw += AddXPlusFace(x,y,z)
if(!isSolidAt(x-1,y,z))
verticesToDraw += AddXMinusFace(x,y,z)
if(!isSolidAt(x,y+1,z))
verticesToDraw += AddYPlusFace(x,y,z)
//and so on for the rest of the faces
Buffer(verticesToDraw)


Of course you'll be more detailed. You can also keep track of the faces in a separate array, perhaps using a byte with bit positions 0 through 5 indicating whether a face is set or not.


Eventually you'll probably want to improve upon this with special checks for "short cubes", transparent but solid cubes and so on.


EDIT


I've updated the code to show that you run this on a per chunk basis. This only address the issue of faces that are invisible because they are adjacent to a solid cube. Sending the vertices for all the cubes and "letting the GPU do the culling" would be a bad idea. I assume you may know that already since you asked this question. The above code is only run when the chunk is dirty, as in, something has changed. It's not to be run every frame.


You'll see significant performance improvements with the above change. I know because I've gone through the process before. You may also find performance improvements with spacial partitioning, but the improvements are unlikely to be as significant as drastically reducing the number of vertices sent to the GPU (as you will do when you implement the above).


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...