[:|] robot frog
news
3d
games
icons
picts
misc
links
 

Terrain Generation Tutorial: Code

previous | next | code

I've written a complete C++ class you can use to generate terrains using the described algorithm. The class takes care of managing the heightmap memory for you as well. It does not perform any rendering; it only creates and generates the heightmaps. It has parameters to allow you to set the size of the heightmap, the range of hill sizes, the number of hills, whether or not to generate an island, the amount of flattening, and the random seed used. To use it, all you need to do is this:

#include "rfHillTerrain.h"

using namespace RobotFrog; // the class is in this namespace

int main( void )
{
    HillTerrain terrain(); // you can also specify terrain params here
    terrain.Generate();
        
    for( int x = 0; x < terrain.GetSize(); ++x )
    {
        for( int y = 0; y < terrain.GetSize(); ++y )
        {
            float z = terrain.GetCell( x, y );
            // do whatever with the z values here to draw your terrain
        }
    }
}

The constructor has parameters for all of the variables affecting the algorithm. In addition, you can also change the parameters on an existing terrain and regenerate it. The terrain also stores the random seed it uses to generate itself so that you can create the same terrain when you need to.

Platforms

The code has been tested and it runs fine on MacOS and Windows. It should theoretically run without problems on any platform that has <math.h> for sin() and cos(), <stdlib.h> for rand() and srand(), <assert.h> for assert(), and <new.h> for std::bad_alloc. The class is put inside the namespace RobotFrog, so you will need to either specify the namespace when using it, or just import it. The constructor also throws an exception if it can't allocate enough memory, so you will need to enable exception handling.

Inheritance

The class was not designed to be inherited, but if you felt like implementing other algorithms using it as a base, it should be fairly easy to modify. Basically, you would need to make Generate() virtual, and then override it.

Downloading

The two links below download the class in either .sit or .zip format. This includes only the class files, you'll have to write your own main().

StuffIt Archive (Mac Text) | ZIP Archive (PC Text)

Licensing

This code is licensed under the MIT license. This basically means you can do whatever you want with it except hold me responsible. If you want to use this in your game, personal or professional, feel free. You can do whatever you want with it. I would appreciate it if you would let me know when you use it, for my personal gratification.

Copyright © 1999-2002 Bob Nystrom.