I’ve been quite interested lately in procedurally generated terrain and how I might be able to use this in upcoming projects, primarily just to see how to do it but it may end up in some actual games I want to develop in the future.
There are different ways to generate 3D terrain, but one of the slightly more common ways is by using height maps and Perlin noise. Using these we can make auto generated terrain that looks natural.
Heightmap
So, first things first a height map is a gray scale 2D raster image where the gray channel represents height where white is the maximum height and black is the minimum height, with the various shades of gray being somewhere inbetween. This heightmap can then be used to create terrain like hills, valeys, rocks etc. Now we could just create this heightmap ourselves, but this will quickly get dull. What we would like is some way to create a heightmap automatically, perhaps using a random number generator. Let’s say we did use a bog-standard pseudo-random number generator, we could iterate over a 2D array that represents the heightmap and run the number generator for each cell. This would certainly give us a heightmap, but it would be too random! We would have a terrain that would just have random blocks, one minute being at max height, the next at minimum with no smoothing inbetween. I.e. nothing like the real world, rather a set of lego towers that have been build by different people without looking at the towers.
Perlin Noise
What we are really looking for is a way to produce coherent pseudo-random noise, this is where perlin noise comes in. It’s a method to produce natural looking textures by having different layers of detail and then combining these. A fantastic example of its implementaiton and applications can be found on this post by Herman Tulleken. Another complete explanation can be found here, I really do advise you read the links if you are really interested in using perlin noise in your games.
Implementation
All credit goes to Herman Tulleken for his example code he posted online with his article, it was easy to follow and adapt to C. The link for my C version of his example code can be found here. It should be pretty straigt forward to use and seems to produce some nice randomised textures.
Image Output
To output the heightmap produced as an image I used a library called LodePNG that can be found here. An example of an image produced using the perlin noise function can be seen below.
I plan to use this in map generation and perhaps voxel engine, wait and see!