# Accidental noise - Gradient function

Related to my previous question (2D Terra(ria)in generation - Accidental noise) I'm stuck on understanding how the gradient function itself works (in the Accidental library).

After help on chat (thanks Jon!) I understand that upon defining the gradient, for example, Gradient(0,0,0,1), it returns a function that upon its turn would return correct values between 0 & 1 for the arguments you provide.

So calling the this function with (0,40) would give you a value back between (0,1). However, I don't understand how it would do this without knowing the outer "range".

E.g. If you'd render the gradient image that's shown on his site: Would you do that by defining the gradient(0,0,0,1) and then calling it for each pixel? (0,1) (0,2), (50,50),...? In that case, pixel (0,200) would have to return 1, but if you'd have an image of 400 pixels high, (0,200) would have to return 0.5

And calling it with values between (0,0) & (0,1) with predefined steps (1/200 or 1/400 for example), seems to make the gradient noise function itself rather useless.

If possible, pseudo or python code would be very welcome to illustrate how the "internals" on that gradient function would work, perhaps I'm thinking of it too complex.

• Sorry I missed your chat, I made an answer for you. Hope that clears things up? Jun 19, 2013 at 14:50

The values specified when you create your gradient, are your endpoints. So for example, when you create a gradient with the values (x1=0, x2=0, y1=0, y2=1), you are creating a gradient line on the y-axis with its endpoints being 0 and 1, on the y-axis.

Okay, so you have a gradient on your y-axis, starting at point 0, all the way to point 1. What does this mean?

If it lies on or beyond P1, the value is assigned as 0. If it lies on or beyond P2 the value is assigned as 1. Anything in between is assigned as a linear interpolation between 0 and 1.

When you retrieve values from this function, you can scale according to your image.

For example:

for (int i = 0; i < imageWidth; i++)
{
for (int j = 0; j < imageHeight; j++)
{
double x = i / imageWidth;
double y = j / imageHeight;
}
}

• I guess we were writing our answers at the same time. Looks like we're thinking the same thing! Jun 19, 2013 at 17:39
• @Byte56 Yeah. Upvote for you my good man. Jun 19, 2013 at 18:33

Everything you pass into the function should be scaled by the size of your world. Since the gradient lies between 0 and 1 of the function, you essentially just normalize everything based on your maximum world height. To illustrate, here's a little function that would do something like that:

float gadientAt(worldX, worldY)

You can always create the gradient function with the size of your world Gradient(0,0,worldMinY,WorldMaxY), but people usually like to think in normalized values.