Example usage for java.util Deque addFirst

List of usage examples for java.util Deque addFirst

Introduction

In this page you can find the example usage for java.util Deque addFirst.

Prototype

void addFirst(E e);

Source Link

Document

Inserts the specified element at the front of this deque if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.

Usage

From source file:org.shaman.terrain.polygonal.PolygonalMapGenerator.java

/**
 * Step 4: assign elevation/*from   w  w w.j av a2 s  .  c o m*/
 */
private void assignElevation() {
    if (graph == null) {
        return;
    }
    Random rand = new Random(seed * 2);
    //initialize border corners with zero elevation
    Deque<Graph.Corner> q = new ArrayDeque<>();
    for (Graph.Corner c : graph.corners) {
        if (c.border) {
            c.elevation = 0;
            q.add(c);
        } else {
            c.elevation = Float.POSITIVE_INFINITY;
        }
    }
    // Traverse the graph and assign elevations to each point. As we
    // move away from the map border, increase the elevations. This
    // guarantees that rivers always have a way down to the coast by
    // going downhill (no local minima).
    while (!q.isEmpty()) {
        Graph.Corner c = q.poll();
        for (Graph.Corner a : c.adjacent) {
            if (c.ocean && a.ocean && a.elevation > 0) {
                a.elevation = 0;
                q.addFirst(a);
                continue;
            }
            float elevation = c.elevation + (a.ocean ? 0 : 0.01f);
            if (!c.water && !a.water) {
                elevation += 1;
            }
            //add some more randomness
            //elevation += rand.nextDouble()/4;
            if (elevation < a.elevation) {
                a.elevation = elevation;
                q.add(a);
            }
        }
    }

    //redistribute elevation
    float SCALE_FACTOR = 1.1f;
    ArrayList<Graph.Corner> corners = new ArrayList<>();
    for (Graph.Corner c : graph.corners) {
        if (!c.ocean) {
            corners.add(c);
        }
    }
    Collections.sort(corners, new Comparator<Graph.Corner>() {
        @Override
        public int compare(Graph.Corner o1, Graph.Corner o2) {
            return Float.compare(o1.elevation, o2.elevation);
        }
    });
    for (int i = 0; i < corners.size(); i++) {
        // Let y(x) be the total area that we want at elevation <= x.
        // We want the higher elevations to occur less than lower
        // ones, and set the area to be y(x) = 1 - (1-x)^2.
        float y = (float) i / (float) (corners.size() - 1);
        float x = (float) (Math.sqrt(SCALE_FACTOR) - Math.sqrt(SCALE_FACTOR * (1 - y)));
        if (x > 1.0)
            x = 1; // TODO: does this break downslopes?
        corners.get(i).elevation = x;
    }

    assignCenterElevations();

    //update mesh
    updateElevationGeometry();
}