Generating chunked terrain for my flight simulator

Part 2 - flight simulator with C++ and OpenGL

A picture of the author, Jakob Maier
Jakob Maier
Apr 15, 2020

When building a flight simulator you need some terrain to fly over, and because the plane moves pretty fast you need a lot of it. I decided to generate my terrain at runtime, using height data of austria as a basis.

In graphics programming surface normals are used to calculate the proper lighting. Usually they are calculated for each vertex individually so that the transition between individual triangles is smoothed out as best as possible. In keeping with my art style however I decided to calculate the normal just once per triangle, a style called flat shading.

Here is the code I use to calculate the normals:

glm::vec3 compute_normal(glm::vec3 a, glm::vec3 b, glm::vec3 c) {
	glm::vec3 v0 = a - c;
	glm::vec3 v1 = b - c;
	return glm::normalize(cross(v0, v1));

Even when I kept the terrain resolution quite low, keeping with my theme of a lofi 90s game, I quickly ran into performance issues. The solution to this problem is to use different resolutions for terrain at different distances to the player. This means the terrain is loaded in and out of memory in chunks, new chunks being loaded when the player moves across the map. This caused a new problem: whenever a chunk is loaded it takes some time to read the heightmap from the csv and calculate the normals, causing a visible drop in framerate.

My solution to this is to load the new chunks asynchronously using std::thread:

std::thread worker(load_chunk, this);

While using std::thread::detach is often discouraged, it works in this case and fixed my framerate problems. Success!

Image 1

If you are interested in my code you can find it here.

↑ back to top

© 2022 Jakob Maier
edit this page