Splitting Heightmap

This probably isn't completely jME related… but im developing the game with jME so this is the place I go :slight_smile:



I have many heightmaps that are 1024x1024 and a dynamic map loader that takes 128x128 squares of terrain. How would I go about splitting the heightmap into 128x128 squares? (AKA 8 squares)



I am using FreeWorld3D if that helps anything…

Bump

Where is the problem? Load your heightmap into memory and then calculate how many tiles you'll get. Loop through the map and save the parts at a specific offset (index * tile edge length).

A little bit of programming is normal when using a game engine … :slight_smile:

Are you saying write a converter or write that as part of the tile-loader?

I would do that only once - so yes, you could call it a converter. Try keeping the complexity of loading one tile to a minimum so that it's fast and don't affect your game performance too much.

Galun said:

I would do that only once - so yes, you could call it a converter. Try keeping the complexity of loading one tile to a minimum so that it's fast and don't affect your game performance too much.


That's what I was going to say to you, if you were suggesting that I like chop up the tiles right before the game  :mrgreen:

So you're saying there's a way to export a 128x128 heightmap?

With Java there is always a way :wink: and I can see the word "developer" in your title…



As I wrote before: load the big map into memory and write out tiles. Think of a heightmap as a stream of bytes (or floats or shorts) describing a grid line by line.

Okay-- I moved off-topic to other things for a while and now am back on this, hoping to get it done soon. What I want to do is to create a stand-alone application that will do this:



-accept input as to the location of a heightmap file

-accept input as to the size of that heightmap file

-accept input as to the sizes of the individual tiles

-accept input as to the tile-coordinate that the top-left corner will represent (in order to name them appropriately… this is pretty specific to my game)

-convert the single heightmap into several heightmaps of a specific size (see point #2) and name them based on their tile-coordinate (see point #4).



My only question is how to save only a small portion of the heightmap. I know you can save a heightmap simply by using myMap.save("filename.raw"); but how do I reference just the first 64x64 of a 2056 x 2056 map?

Aren't the height map values just sequential by x and y?



So you could easily do something like this:


for(int x = startX, i = 0; x < startX + newSize; ++x, ++i)
   for(int y = startY, j = 0; y < startY + newSize; ++y, ++j)
   {
        newMap[i*newSize + j] = origMap[x*oldSize + y];
   }



Maybe I am missing something here?

Still confusing but I'll be giving it a shot. Any way to chop up BufferedImages like that too? My map creator exports the alphas along with the heightmaps so I'd love to be able to chop up those alphas and drop them onto the tiles…

GAH! I have failed!



Here is what I got, something is def. wrong though:



HeightMapSplitterTest.java:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package heightmapsplitter;

import com.jmex.terrain.util.RawHeightMap;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

/**
 *
 * @author Tyler Trussell
 */
public class HeightMapSplitterTest
{
    public static void main(String args[]) throws FileNotFoundException, IOException
    {
        int oldSize = 512;
        int newSize = 64;
       
        String originalName = "mymap.raw";
        String fileName = "output/";
       
        int startX = 0;
        int startY = 0;
       
        int numMaps = oldSize / newSize;
       
        RawHeightMap oldMap;
        int[] oldMapData;
       
        oldMap = new RawHeightMap(HeightMapSplitterTest.class.getClassLoader().getResource(originalName), oldSize + 1, RawHeightMap.FORMAT_16BITLE, false);
        oldMapData = oldMap.getHeightMap();
       
       
        for(int i=0; i<numMaps; i++) //x
        {
            for(int n=0; n<numMaps; n++) //y
            {
                int[] newMap = new int[newSize * newSize];
                for (int x = 0; x < newSize; x++)
                {
                    for (int y = 0; y < newSize; y++)
                    {
                        newMap[y * newSize + x] = oldMapData[(n + y) * oldSize + (i + x)];
                    }
                }
                for(int r=0; r<newMap.length; r++)
                    System.out.print(newMap[i] + " ");
                System.out.println();
                FyrestoneMap map = new FyrestoneMap(newMap);
                map.save(fileName + (i+startX) + "," + (n+startY) + ".raw");
            }
        }
       
    }
}



FyrestoneMap is a RawHeightMap with a default format of 16bit LE instead of 8bit, but here's the code:

/*
 * Copyright (c) 2003-2007 jMonkeyEngine
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package heightmapsplitter;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.logging.Logger;

import com.jme.math.FastMath;
import com.jme.system.JmeException;
import com.jme.util.LittleEndien;
import com.jmex.terrain.util.AbstractHeightMap;

/**
 * @author Tyler Trussell
 * @version $Id: FyrestoneMap.java,v 1.10 2007/09/11 15:44:28 nca Exp $
 */
public class FyrestoneMap extends AbstractHeightMap {
    private static final Logger logger = Logger.getLogger(HeightMapSplitterTest.class
            .getName());

    /**
     * Format specification for 8 bit precision heightmaps
     */
    public static final int FORMAT_8BIT = 0;

    /**
     * Format specification for 16 bit little endian heightmaps
     */
    public static final int FORMAT_16BITLE = 1;

    /**
     * Format specification for 16 bit big endian heightmaps
     */
    public static final int FORMAT_16BITBE = 2;

    private int format;
    private boolean swapxy;

   private InputStream stream;

    /**
     * Constructor creates a new <code>FyrestoneMap</code> object and loads a
     * RAW image file to use as a height field. The greyscale image denotes the
     * height of the terrain, where dark is low point and bright is high point.
     * The values of the RAW correspond directly with the RAW values or 0 - 255.
     *
     * @param filename
     *            the RAW file to use as the heightmap.
     * @param size
     *            the size of the RAW (must be square).
     * @throws JmeException
     *             if the filename is null or not RAW, and if the size is 0 or
     *             less.
     */
    public FyrestoneMap(String filename, int size) {
        this(filename, size, FORMAT_8BIT, false);
    }

    public FyrestoneMap(int heightData[]) {
        this.heightData = heightData;
        this.size = (int) FastMath.sqrt(heightData.length);
        this.format = FORMAT_16BITLE;
        this.swapxy = true;
    }

    public FyrestoneMap(String filename, int size, int format, boolean swapxy) {
        // varify that filename and size are valid.
        if (null == filename || size <= 0) {
            throw new JmeException("Must supply valid filename and "
                    + "size (> 0)");
        }
        try {
         setup(new FileInputStream(filename), size, format, swapxy);
      } catch (FileNotFoundException e) {
            throw new JmeException("height file not found: "+filename);
      }
    }

    public FyrestoneMap(InputStream stream, int size, int format, boolean swapxy) {
        setup(stream, size, format, swapxy);
    }

    public FyrestoneMap(URL resource, int size, int format, boolean swapxy) {
       // varify that resource and size are valid.
        if (null == resource || size <= 0) {
            throw new JmeException("Must supply valid resource and "
                    + "size (> 0)");
        }

        try {
         setup(resource.openStream(), size, format, swapxy);
      } catch (IOException e) {
            throw new JmeException("Unable to open height url: "+resource);
      }
   }

   private void setup(InputStream stream, int size, int format, boolean swapxy) {
      // varify that filename and size are valid.
        if (null == stream || size <= 0) {
            throw new JmeException("Must supply valid stream and "
                    + "size (> 0)");
        }

        this.stream = stream;
        this.size = size;
        this.format = format;
        this.swapxy = swapxy;
        load();
   }

   /**
     * <code>load</code> fills the height data array with the appropriate data
     * from the set RAW image. If the RAW image has not been set a JmeException
     * will be thrown.
     *
     * @return true if the load is successfull, false otherwise.
     */
    @Override
    public boolean load() {
        // confirm data has been set. Redundant check...
        if (null == stream || size <= 0) {
            throw new JmeException("Must supply valid stream and "
                    + "size (> 0)");
        }

        // clean up
        if (null != heightData) {
            unloadHeightMap();
        }

        // initialize the height data attributes
        heightData = new int[size * size];

        // attempt to connect to the supplied file.
        BufferedInputStream bis = null;

        try {
            bis = new BufferedInputStream(stream);
            if (format == FyrestoneMap.FORMAT_16BITLE) {
                LittleEndien dis = new LittleEndien(bis);
                int index;
                // read the raw file
                for (int i = 0; i < size; i++) {
                    for (int j = 0; j < size; j++) {
                        if (swapxy) {
                            index = i + j * size;
                        } else {
                            index = (i * size) + j;
                        }
                        heightData[index] = dis.readUnsignedShort();
                    }
                }
                dis.close();
            } else {
                DataInputStream dis = new DataInputStream(bis);
                // read the raw file
                for (int i = 0; i < size; i++) {
                    for (int j = 0; j < size; j++) {
                        int index;
                        if (swapxy) {
                            index = i + j * size;
                        } else {
                            index = (i * size) + j;
                        }
                        if (format == FyrestoneMap.FORMAT_16BITBE) {
                            heightData[index] = dis.readUnsignedShort();
                        } else {
                            heightData[index] = dis.readUnsignedByte();
                        }
                    }
                }
                dis.close();
            }
            bis.close();
        } catch (IOException e1) {
            logger.warning("Error reading height data from stream.");
            return false;
        }
        return true;
    }

    /**
     * <code>setFilename</code> sets the file to use for the RAW data. A call
     * to <code>load</code> is required to put the changes into effect.
     *
     * @param filename
     *            the new file to use for the height data.
     * @throws JmeException
     *             if the file is null or not RAW.
     */
    public void setFilename(String filename) {
        if (null == filename) {
            throw new JmeException("Must supply valid filename.");
        }
      try {
         this.stream = new FileInputStream(filename);
      } catch (FileNotFoundException e) {
         throw new JmeException("height file not found: " + filename);
      }
    }

    /**
     * <code>setHeightStream</code> sets the stream to use for the RAW data. A call
     * to <code>load</code> is required to put the changes into effect.
     *
     * @param stream
     *            the new stream to use for the height data.
     * @throws JmeException
     *             if the stream is null or not RAW.
     */
    public void setHeightStream(InputStream stream) {
        if (null == stream) {
            throw new JmeException("Must supply valid stream.");
        }
      this.stream = stream;
    }
}



If you see something please tell me!

Remember that you are working with two coordinate systems simulaneously.  I draw a simple diagram with a 4x4 orig map and 2x2 submaps to help me figure this out.  When you translate down by "n" in your code, you have to translate noldSizenewSize units. 







newMap[y * newSize + x] = oldMapData[(n + y) * oldSize + (i + x)];


Should be


newMap[y*newSize + x] = oldMapData[newSize * (n*oldSize + i) + y*oldSize + x];



Also,
replace the "i" in


                for(int r=0; r<newMap.length; r++)
                    System.out.print(newMap[i] + " ");



with "r"