5
$\begingroup$

I am trying to implement this formula to generate bump but I am facing some issue. The result doesn't look the same it's much darker.

enter image description here

Here is my result (without same parameters) but it is much darker and I don't get why.

enter image description here

And here is the associated code.

// randx, randy and frequencies are array with some random values for each sin wave.
for (int x = 0; x < _width; ++x)
{
    for (int y = 0; y < _height; ++y)
    {
        float color = 0.0f;
        for (int i = 0; i < _iterations; ++i)
        {
            val += Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
        }
        color /= (float)_iterations;
    }
}

Any idea why I am getting this result ?
Thanks a lot !

EDIT: Thanks to @trichoplax it works by doing this.

float tmp = Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
tmp = tmp * 0.5f + 0.5f;
val += tmp;
$\endgroup$
1
  • 2
    $\begingroup$ Pro tips, unrelated to your question: you can expect (foo * foo) to be a lot faster than pow(foo, 2.0f); if your data is organized row by row (as opposed to column by column), you should swap the for loops to traverse data in a more coherent order. $\endgroup$ Apr 8, 2016 at 2:02

1 Answer 1

8
$\begingroup$

As you are taking the mean of a number of sine waves, your colour values will range from -1 to 1. From your example image, it looks like only the top half of this range of values (from 0 to 1) is resulting in colour, with everywhere else remaining black.

If whatever you are using to display the result can only handle positive values, then you will need to convert the result to the correct range of values. For example, to convert from the range [-1 to 1] into the range [0 to 1], you would add 1 and divide by 2.

In the context of your example code, this could be by following the line

color /= (float)_iterations;

with

color += 1;
color /= 2;
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.