Beispiel #1
0
  /**
   * Write Terrain to a JSON file
   *
   * @param file
   * @throws IOException
   */
  public static void save(Terrain terrain, File file) throws IOException {
    JSONObject json = new JSONObject();

    Dimension size = terrain.size();
    json.put("width", size.width);
    json.put("depth", size.height);

    JSONArray jsonSun = new JSONArray();
    float[] sunlight = terrain.getSunlight();
    jsonSun.put(sunlight[0]);
    jsonSun.put(sunlight[1]);
    jsonSun.put(sunlight[2]);
    json.put("sunlight", jsonSun);

    JSONArray altitude = new JSONArray();
    for (int i = 0; i < size.width; i++) {
      for (int j = 0; j < size.height; j++) {
        altitude.put(terrain.getGridAltitude(i, j));
      }
    }
    json.put("altitude", altitude);

    JSONArray trees = new JSONArray();
    for (Tree t : terrain.trees()) {
      JSONObject j = new JSONObject();
      double[] position = t.getPosition();
      j.put("x", position[0]);
      j.put("z", position[2]);
      trees.put(j);
    }
    json.put("trees", trees);

    JSONArray roads = new JSONArray();
    for (Road r : terrain.roads()) {
      JSONObject j = new JSONObject();
      j.put("width", r.width());

      JSONArray spine = new JSONArray();
      int n = r.size();

      for (int i = 0; i <= n * 3; i++) {
        double[] p = r.controlPoint(i);
        spine.put(p[0]);
        spine.put(p[1]);
      }
      j.put("spine", spine);
      roads.put(j);
    }
    json.put("roads", roads);

    FileWriter out = new FileWriter(file);
    json.write(out);
    out.close();
  }