Search code examples
javaopengllwjgllandscape

How to generate forests in java


I am creating a game where a landscape is generated all of the generations work perfectly, a week ago I have created a basic 'forest' generation system which just is a for loop that takes a chunk, and places random amounts of trees in random locations. But that does not give the result I would like to achieve.

Code:

for(int t = 0; t <= randomForTrees.nextInt(maxTreesPerChunk); t++){

    // generates random locations for the X, Z positions\\
    // the Y position is the height on the terrain gain with the X, Z coordinates \\
    float TreeX = random.nextInt((int) (Settings.TERRAIN_VERTEX_COUNT + Settings.TERRAIN_SIZE)) + terrain.getX();
    float TreeZ = random.nextInt((int) (Settings.TERRAIN_VERTEX_COUNT + Settings.TERRAIN_SIZE)) + terrain.getZ();
    float TreeY = terrain.getTerrainHeightAtSpot(TreeX, TreeZ);

    // creates a tree entity with the previous generated positions \\
    Entity tree = new Entity(TreeStaticModel, new Vector3f(TreeX, TreeY, TreeZ), 0, random.nextInt(360), 0, 1);

    // checks if the tree is on land \\
    if(!(tree.getPosition().y <= -17)){
        trees.add(tree);
    }
}

Result:

Image with the result of the basic above seen generation code


Solution

  • First of all take a look at my:

    as you can see you can compute Biomes from elevation, slope, etc... more sophisticated generators create a Voronoi map dividing your map into Biomes regions assigning randomly (with some rules) biome types based on neighbors already assigned...

    Back to your question you should place your trees more dense around some position instead of uniformly cover large area with sparse trees... So you need slightly different kind of randomness distribution (like gauss). See the legendary:

    on how to get a different distribution from uniform one...

    So what you should do is get few random locations that would be covering your region shape uniformly. And then generate trees with density dependent on minimal distance to these points. The smaller distance the dense trees placement.

    placemet