O'Reilly logo

Killer Game Programming in Java by Andrew Davison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating a Fractal Landscape

My FractalMesh class utilizes a plasma fractal to generate a mesh of Point3d objects, centered at (0, 0) on the (x, z) plane, at intervals of 1 unit, extending out to WORLD_LEN/2 units in the positive and negative x- and z-directions. (In my code, WORLD_LEN is 64 units.) The y-coordinates of these points become their heights in the scene.

The objects are stored in a 2D array called mesh, with mesh[0][0] storing the back, left-most point in the scene. A row in mesh[][] stores all the points for a given z-value.

The mesh is generated using the algorithm described by Jason Shankel in "Fractal Terrain Generation—Midpoint Displacement" from Game Programming Gems. The mesh is seeded with four corner points, and a two-stage process is repeated until sufficient extra points have been created. In the first stage (the diamond step), the height of the midpoint of the four corner points is calculated by averaging their heights and adding a random displacement in the range -dHeight/2 to dHeight/2. For example, the height of the E point in Figure 26-8 is calculated this way:

E = (A + B + C + D)/4 + random(-dHeight/2, dHeight/2)

Mesh creation: first iteration

Figure 26-8. Mesh creation: first iteration

The next stage (the square step) is to calculate the heights of the midpoints of the four sides (F, G, H, and I in Figure 26-8). For example, G's height is:

G = (A + E + C + E)/4 + random(-dHeight/2,

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required