0
101 Jul 21, 2005 at 05:05

For my first submission to the Code Spotlight, I have this little 2D terrain generation algorithm that I’m quite proud of. It requires you to have defined an std::list<float> called ‘terrain’ somewhere in your code, probably a global would be best (an updated version which takes the correct terrain list as a parameter is in the works).

The iterations parameter for MakeTerrain() simply controls how many times it loops over, adding more points as it goes, and the roughness parameter sort of controls how much the random range is reduced each time through the loop (basically, the higher the value, the less big spikes you will see in your terrain).

Don’t expect anything pretty when you run this - all this algorithm does is produce the raw data, it’s up to you to do something with it. My own testbed program which I used to give me something to build on only displays the results as a list of numbers, but it’s enough to show that it works!

Here’s the code:

void MakeTerrain( int iterations, double roughness )
{
int max_range = 127;

// both of these will be random later
terrain.push_back( (float)(rand() % (max_range * 2) - max_range ));  // start point
terrain.push_back( (float)(rand() % (max_range * 2) - max_range ));  // end point

int insertions = 1;

for( int a = 0; a < iterations; a++ )
{
for( int b = 0; b < insertions; b++ )
{
list<float>::iterator vIndex = terrain.begin();

for( int c = 0; c < (b*2); c++ )
{
vIndex++;
}

float pointA = *vIndex;
vIndex++;
float pointC = *vIndex;

// calculate new point, inserted at vIndex
terrain.insert( vIndex, ((pointA + pointC) / 2) + rand() % (max_range * 2) - max_range );
};
insertions *= 2;
// change the max range of the random alteration
max_range *= roughness;
};
};