C# perlin Noise - c#

I have read some tutorials on perlin noise (for example this one) for my terrain generation, and I wanted to make sure that I understood it and can correctly implement it.
I start with 1 Dimension:
amplitude = persistence^i
// persistence can have any value but mostly it is 1 or lower. It changes the amplitude of the graphs with higher frequency since:
frequency = 2^i
//the 2 effects, that each graph reflects one octave, wich is not 100% necessary but the example happens do do it like this
'i' is the octave we are looking at.
Here is my attempt:
private float[] generateGraph()
{
float[] graph = new float[output.Width];
for (int i = 0; i < output.Width; i += 1/frequency)
{
graph[i] = random.Next((int)(1000000000000*persistence))/1000000000000f;
}
return graph;
}
I imagined the array as a graph, where the index is X and the value is Y. I search for a value for every multiple of texture.Width/frequency until the end of the array.
I have some random values I am using for now, which I have to connect with either Linear Interpolation/Cosine Interpolation or Cubic Interpolation.
Which one should I use? Which is the most performant when I want to use the noise for terrain generation in 2D?
I would like to put the graphs in a 2D-array after this and then check for each value, if its higher than 0.5, it should get some material or texture.
Is this situation, how should I do it? Am I totally on the wrong track?
edit1: Before I put the graph in a 2D array, I would like to generate perhaps 5 other graphs with a higher 'i' and blend them (which shouldn't be too hard).
edit2: this implementation is nice and 'easy'.

Define "too much performance" any kind of interpolation should be fine for 2D data. If you are really worried about performance, you might try implementing Simplex Noise, but that is much harder to understand and implement and it really becomes better at 3D and higher. In 2D they are somehow comparable.
Also, perlin noise is usually implemented as function of x parameters, where x is number of dimensions and the function has internal array of random values, that is accessed based on integer values of the parameters. You should try studying the original source code.

Related

For a very niche project: how to pass a C# class to a Compute Shader and get out multiple 2d float arrays

I'll do my best to explain the problem, which first requires an explanation of the project. I apologize ahead of time if it's a bit scattered. I have ADHD, which has made communicating on this platform massively difficult, so please bear with me. This is necessary to mention because stack overflow has consistently suppressed my questions for being scattered and I'm tired of this intolerance.
The project generates a 3D Worley noise map using my own unoptimized algorithm, which, at the moment, requires iterating through every index of the 3D array and individually calculating every element's value on the CPU one at a time. also, this will be in 3D world space.
Additionally, I needed to write my own class for the randomized points or "nodes" because this program iteratively moves these nodes in pseudorandom directions, and each node is associated with a procedure for calculating map index values, which is just assigned via an integer between 1 and 6. after each iteration, the map is regenerated. Without the nodes, this can't work.
Code for the Nodes on repl.it
Obviously, this is extremely slow, and I need to implement multithreading and compute shaders, which is the conclusion I've come to. Still, I'm faced with a massive problem: I've no idea how to use hlsl or compute shaders, and I cannot, for the life of me, find any resources on hlsl for C#/java/python programmers that would help me wrap my head around anything. ANY resources explaining hlsl on a basic level would be enormously helpful.
Now, for the specific problem of this question: I have no idea how to start. I have one vague idea of an approach that is derived from my ignorance about multithreading. I could use 32 individual 32x32 RWStructuredTexture2D<float> arrays that I stack after calling my shader to create a 3D texture; however, to do this, I need to be able to pass my nodes to the shader, and every use of compute shaders I've seen only has one parameter, uint3 id : SV_DispatchThreadID, which makes no sense to me. I've briefly considered making a struct for the nodes in my shader, but I still have no idea how to get that information to my shader.
For the actual question: how do I throw nodes at this and then get 32 32x32 float arrays out of it?
here's some pseudocode for the in-betweens.
//somehow set this up to have 32 different threads
//make an hlsl equivalent of a float[,]
#params NodeSet nodes and z coordinate
#return float[32,32]
//NodeSet is just a collection of Nodes that has some convenience methods.
float[,] CSMain(#params) {
for(int x = 0; x < 32; x++)
for(int y = 0; y < 32; y++)
//set value of element
return floatArr;
}
Second question: should I even be using Compute Shaders for this problem?
You should use 32 x 32 x 32 threads and output to a 1d buffer of length 32 x 32 x 32 based on the id of the thread
Pseudocode:
#pragma kernel PseudoCode
[numthreads(32, 32, 32)]
void PseudoCode (uint3 id : SV_DispatchThreadID) {
float3 pos = id; // or id - float3(15.5,15.5,15.5) to center, etc.
int outputIndex = id.x*32*32+id.y*32+id.z;
for (int i = 0; i < nodecount ; i++)
outputbuffer[outputIndex] += GetInfluence(nodeData[i], pos);
outputBuffer[outputIndex] = NormalizeOutput(outputBuffer[outputIndex]);
}

Is there a built in way of efficiently finding if a vector is in a vector array and if so what # variable it is

Hello I am creating a procedurally generated cave generation script and I have gotten down all the perlin noise garbage out of the way and am trying to transform the vertices into a mesh . I understand that I need to declare the faces for it and need some form of marching cubes algorithm. For me to know which direction to render the face in I need my script to be aware of all the vertices around it by searching through the vertices. Is there any way my script can efficiently search through a vector3 array to find if a vector3 is in there and if so what place in the array is the Vector3 in?
If you're using a triangulation lookup table based implementation of marching cubes, you could store a normal vector alongside the face in the same table entry. A video by Sebastian Lague mentions using such a table. I'm not exactly sure where he downloaded it from, but he includes it in his repo which is MIT licensed. Video, Table (EDIT: The order of a triangle's vertices alone may be sufficient to define its direction, and you may not need an explicit normal vector)
Also heads up: Old Perlin noise tends to be visibly grid aligned. Most times I see it used, appear to be because a library provided it or because it was mentioned in a tutorial, and not because it was actually the best choice for the application. Simplex-type noises generally produce less grid-aligned results. It's straightforward to import external noise into Unity. It looks like you might need to anyway, if your implementation depends on 3D noise. Here are the noises from my repo that use an open implementation for 3D, a tailored gradient table, and rotated evaluators that are good for terrain. There are a lot of other options out there too, though they may not have these aspects in particular. Note that the range is [-1,1] not [0,1] so if your current noise is [0, 1], you might need to do noise(...) * 0.5 + 0.5 to correct that. Choose the 2F version if you have a lot of octaves, or the 2S version if you have one octave or are doing ridged noise.

Random, Infinite Terrain Generation

I'm trying to generate random terrain for my game (In Unity3D, C#). All I need is water and grass. No height to it (no mountains or hills.) I'd preferably like to do it by placing individual cubes. On top of that the terrain needs to be infinite.
I've searched every where for even a hint on how to do it, but everything I found had either height to it, didn't use individual cubes (edited the terrain as a whole), or wasn't infinite.
Any help would be much appreciated! :)
EDIT: I'm looking for something somewhat similar to a game called Factorio. Here's a screenshot: http://i.ytimg.com/vi/Uns15OfPWbo/maxresdefault.jpg As you can see there is a big body of water, and a ton of land. I want to create something that randomly does that every time (random bodies of water and random land shapes). Something like Minecraft without all the height.
I've heard about something called Perlin noise, but because of a lack of tutorials and documentation, I can't figure out for the life of me on how to use it to generate random terrain.
Perlin noise would be great for your needs.
It generates natural looking random noise. It is infinite in all directions, so basically how it works is you choose a random starting point and use that as a base or your (0,0) point. The you add to that a sampling point. If you pass to it the same sampling point, you will get the same result. All you have to do then is give it different sampling points to get different values and spread out in all directions like this:
for (int x = 0; x < Width; x++) {
for (int y = 0; z < Length ; y++) {
terrain[x,y] = Mathf.PerlinNoise(randomLocation.x + (float)x/scale, randomLocation.y + (float)y/scale);
}
}
where you could then expand your Width/Length in the desired direction based on where the player wants to go or where you want to generate new terrain.
Your terrain[,] would then contain floats from 0 to 1 and the as another comment suggested you'd interpret everything above .5 as land and bellow as water. Then you'd just instantiate a cube at that location, color it blue(water) if terrain[x,y] <0.5 and as brown (land) if terrain[x,y]>0.5 and that would be it.
Keep in mind that you can adjust scale to get bigger/smaller islands of land. But it has to be the same for X and Y, otherwise you'll get a stretched looking islands.
Hope this helps or isn't too late :)

Desiring jagged results from simplex noise or another algorithm just as fast

I'm wanting to do some placement of objects like trees and the like based on noise for the terrain of a game/tech demo.
I've used value noise previously and I believe I understand perlin noise well enough. Simplex noise, however, escapes me quite well (just a tad over my head at present).
I have an implementation in C# of simplex noise, however, it's almost completely stolen from here. It works beautifully, but I just don't understand it well enough to modify it for my own purposes.
It is quite fast, but it also gives rather smooth results. I'm actually wanting something that is a little more jagged, like simple linear interpolation would give when I was doing value noise. My issue here is that due to the amount of calls I'd be doing for these object placements and using fractal Brownian motion, the speed of the algorithm becomes quite important.
Any suggestions on how to get more 'jagged' results like linear interpolation gives with value noise using a faster algorithm than value noise is?
if you are using a complex noise function to do a simple task like the placement of trees, your using completely the wrong type of maths function. It is a very specific function which is great for making textures and 3d shapes and irregular curves. Placing treas on 2d certainly doesn't need irregular curves! Unless you want to place trees along in lines that are irregular and curved!
unless you mean you want to place trees in areas of the noise which are a certain level, for example where the noise is larger than 0.98, which will give you nicely randomised zones that you can use as a central point saying some trees will be there.
it will be a lot faster and a lot easier to vary, if you just use any normal noise function, just program your placement code around the noise function. I mean a predictable pseudo-random noise function which is the same every time you use it.
use integers 0 to 10 and 20 to 30, multiplied by your level number, to select 10 X and 10 Y points on the same pseudo-random noise curve. this will give you 10 random spots on your map from where to do stuff using almost no calculations.
Once you have the central point where trees will be, use another 10 random points from the function to say how many trees will be there, another 10 to say how far apart they will be, for the distribution around the tree seed quite exceptional.
The other option, if you want to change the curve http://webstaff.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf is to read this paper and look at the polynomial function /whatever gradient function could be used in your code, looking the comments for the gradient function, commented out and do X equals Y, which should give you a straight interpolation curve.
if you vote this answer up, I should have enough points in order to comment on this forum:]
I realise this is a very old question, but I felt that the previous answer was entirely wrong, so I wanted to clarify how you should use a noise function to determine the placement of things like trees / rocks / bushes.
Basically, if you want to globally place items across a terrain, you're going to need some function which tells you where those are likely to occur. For instance, you might say "trees need to be on slopes of 45 degrees or less, and below 2000 meters". This gives you a map of possible places for trees. But now you need to choose random, but clustered locations for them.
The best way of doing this is to multiply your map of zeroes and ones by a fractal function (i.e. a Simplex noise function or one generated through subdivision and displacement - see https://fractal-landscapes.co.uk/maths).
This then gives you a probability density function, where the value at a point represents the relative probability of placing a tree at that location. Now you store the partial sum of that function for every location on the map. To place a new tree:
Choose a random number between 0 and the maximum of the summed function.
Do a binary search to find the location on the map in this range.
Place the tree there.
Rinse and repeat.
This allows you to place objects where they belong, according to their natural ranges and so on.

Uniform distribution from a fractal Perlin noise function in C#

My Perlin noise function (which adds up 6 octaves of 3D simplex at 0.75 persistence) generates a 2D array array of doubles.
These numbers each come out normalized to [-1, 1], with mean at 0. I clamp them to avoid exceptions, which I think are due to floating-point accuracy issues, but I am fairly sure my scaling factor is good enough for restricting the noise output to exactly this neighborhood in the ideal case.
Anyway, that's all details. The point is, here is a 256-by-256 array of noise:
The histogram with a normal fit looks like this:
Matlab's lillietest is a function which applies the Lilliefors test to determine if a set of numbers comes from a normal distribution. My result was, repeatedly, 1, which means that these numbers are not normally distributed.
I would like a function f(x) such that, when applied to the list of values from my noise function, the results appear uniformly distributed.
I would like this function to be implementable in C# and not take minutes to run.
Once again, it shouldn't matter where the numbers come from (the question is about transforming one distribution into another, specifically a normal-like one to uniform). Nevertheless, my noise function implementation is based on this and this. You can find the above array of values here.
Oddly enough I just wrote an article on your very question:
http://ericlippert.com/2012/02/21/generating-random-non-uniform-data/
There I discuss how to turn a uniform distribution into some other distribution, but of course you can use similar techniques to transform other distributions.
You will probably be interested in one of the following (related) techniques:
Probability integral transform
Histogram equalization

Categories