- Home /
Improve fractal noise function
I am trying to improve this code without having to make the terrain "borring", so I would need some way to optimize this code to make it run faster, because right now it takes 0.9 seconds to generate a heightmap for 3 tiles. Which is way to much when the terrain is infinite and generated on the run. Here is how I run the code:
if (perlin == null) {
perlin = new PerlinNoise(Seed);
}
mountains = Mathf.Max(0f, perlin.FractalNoise2D(worldPosX+250, worldPosZ+250, Octaves, mountainFrq, 0.5f) - 0.1f) * 1.5;
plain = perlin.FractalNoise2D(worldPosX-250, worldPosZ-250, 1, groundFrq, 0.4f) + 0.3f;
Here is the function:
public float FractalNoise2D(float x, float y, int octNum, float frq, float amp)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise2D(x*gain/frq, y*gain/frq) * amp/gain;
gain *= 2.0f;
}
return sum;
}
Full code noise code: http://pastebin.com/8VL66dzV
How many octaves are you using? And how many points are you sampling per terrain? $$anonymous$$y knowledge of writing noise functions is limited at best, but I don't spy any obvious improvements to be made.
I am using 3 Octaves for the mountains, and the terrain is 257*257
Distribute your calculations over several frames using coroutines, or move the calculations to another thread.
How can I move it to another thread, does unity support multithreading? I have distributed the 3 Chunks moving procces with a second between each of them, but it still seems to lag with a 0.3 second "delay"
@AlwaysSunny, thank you the trick with distributing it over several frames worked :)
Answer by AlwaysSunny · Nov 04, 2014 at 11:01 PM
You can create worker threads, yes. The process is similar to using co-routines. Either way, you'll need to insert yields/waits into the nested loop of sampling checks such that only N% of the whole job is done per frame. This means your terrain object will not be "ready" for several frames after requesting it. Your game must accommodate this shortcoming by loading terrains before they'll become visible / necessary.