Procedural Terrain (2016)

C++, Unreal Engine 4, SQLite

Procedural terrain generator in the style of Sim City 2000, with network chunk replication.

While working on this I needed to solve three fundamental problems: heightmap generation, terrain mesh construction, and network replication.

Heightmap generation

The heightmap is generated in 33x33 chunks (32+1 samples per side, additional sample is needed for seamless tiling), by several octaves of two dimensional Improved Perlin Noise. New heightmap chunks are generated during gameplay within player's immediate vicinity, and are cached for future re-use in a SQLite database (indexed by 64-bit spatial hash). Chunk generation is off-loaded to worker threads in order to minimize blocking the game thread.

Mesh construction

Each terrain chunk is represented by an actor with a procedural mesh component. Due to the nature of UE4, mesh construction must happen on the game thread, and as such is amortized over several frames to prevent performance hiccups. Far away chunk actors are culled and/or despawned, again to maximize performance. Mesh construction itself is a relatively simple algorithm with some similarities to marching cubes, mainly in its approach of building a bit index of current cell (based on vertex height differences), and using that index in order to decide final cell topology. Each cell consists of two triangles whose vertices represent four adjacent heightmap samples.

Network replication

The whole process works quite well in multiplayer scenario. Server generates (and caches) terrain chunks which are later replicated to relevant clients. Each client receives only chunks within the vicinity of its character. Chunks are spawned in an outwards spiral pattern, so that those closer to the character are available sooner. Replicated heightmap data is about 1kB in size, per chunk.