LanLou123 / Webgl-Erosion

Interactive Erosion simulation in Web Browser
https://lanlou123.github.io/Webgl-Erosion/
MIT License
227 stars 31 forks source link

add heightmap exporter #34

Open Qix- opened 3 months ago

Qix- commented 3 months ago

This probably isn't the cleanest implementation of this but I figured for people who want a quick and dirty exporter, here it is.

Downloads a .bin file upon clicking on "Export Heightmap" with IEEE-754 packed floats in a binary format. The count is the square of the heightmap resolution (1024, 2048, etc.) and they're un-normalized (i.e. they will almost certainly be >1.0).

If you're using Unity, you can rename it to have an extension .f32 and drop this in a script somewhere in your project to load it as a texture.

```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor.AssetImporters; #endif namespace MegaMine { #if UNITY_EDITOR [ScriptedImporter(1, "f32")] public class F32Loader : ScriptedImporter { public override void OnImportAsset(AssetImportContext ctx) { // Load in the float 32 values from the file. // The file is just a packed list of f32 values in binary // format. There is no header information; the number of values // is always a square number. byte[] bytes = System.IO.File.ReadAllBytes(ctx.assetPath); int numFloats = bytes.Length / 4; int numFloatsPerSide = (int)Mathf.Sqrt(numFloats); float[] values = new float[numFloats]; for (int i = 0; i < numFloats; i++) { values[i] = System.BitConverter.ToSingle(bytes, i * 4); } // Find the min and max values float min = values[0]; float max = values[0]; for (int i = 1; i < numFloats; i++) { if (values[i] < min) { min = values[i]; } if (values[i] > max) { max = values[i]; } } // Normalize the values for (int i = 0; i < numFloats; i++) { values[i] = (values[i] - min) / (max - min); } // Create a new texture to store the values Texture2D tex = new Texture2D(numFloatsPerSide, numFloatsPerSide, TextureFormat.RFloat, false); tex.wrapMode = TextureWrapMode.Repeat; tex.filterMode = FilterMode.Point; tex.SetPixelData(values, 0); tex.Apply(); // Add the texture to the asset database ctx.AddObjectToAsset("main", tex); ctx.SetMainObject(tex); } } #endif } ```