Resolved.
How to export Heightmap(Terrain) Raw.(Script)
public byte[] ToByteArray(float[,] nmbs)
{
byte[] nmbsBytes = new byte[nmbs.GetLength(0) * nmbs.GetLength(1) * 4];
int k = 0;
for (int i = 0; i < nmbs.GetLength(0); i++)
{
for (int j = 0; j < nmbs.GetLength(1); j++)
{
byte[] array = System.BitConverter.GetBytes(nmbs[i, j]);
for (int m = 0; m < array.Length; m++)
{
nmbsBytes[k++] = array[m];
}
}
}
return nmbsBytes;
}
public float[,] ImportRaw(string path)
{
//reading file
System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
System.IO.FileStream stream = fileInfo.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read);
int size = (int)Mathf.Sqrt(stream.Length / 2);
byte[] vals = new byte[size * size * 2];
float[,] rawHeights = new float[size, size];
stream.Read(vals, 0, vals.Length);
stream.Close();
//setting matrix
Rect rect = new Rect(0, 0, size, size);
int i = 0;
for (int z = size - 1; z >= 0; z--)
for (int x = 0; x < size; x++)
{
rawHeights[x,z] = (vals[i + 1] * 256f + vals[i]) / 65535f;
i += 2;
}
return rawHeights;
}
public void ExportTerrainData(string path)
{
if (path != null && path.Length != 0)
{
path = path.Replace(Application.dataPath, "Assets");
Terrain terrain = GetComponent<Terrain>();
TerrainData data = terrain.terrainData;
int h = data.heightmapHeight;
int w = data.heightmapWidth;
float[,] rawHeights = data.GetHeights(0, 0, w, h);
//reading file
System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
System.IO.FileStream stream = fileInfo.Create();
byte[] bytes = ToByteArray(rawHeights);
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
}
How to export Heightmap(Terrain) Raw.
I can easily export / import the HeightMap through the editor GUI buttons supported by unity.
What I want to do is to automate export / import of HeightMap to black and white raw files on 16bit channel.
When I scripted them, Import works fine. But the export is not working well.
Plz, help me.
Your solution for export works (as I'm guessing you know since you closed it the same day you opened it). But for others who come here...
If you use his export code, note that one float number is stored across 4 bytes. His export code writes those 4 bytes (for each value) to the bytes array before saving and closing it.
If you have a terrain that is 512-513, and you export it - it seems to end up around 1$$anonymous$$B of raw data.
When importing it, you have to reverse the process, and translate those 4 bytes at a time into a single floating point value. Store that in your height map, and jump ahead to the next 4 bytes.
To the OP, thanks for asking the question.