How does this normal() function works ?

Started by
2 comments, last by jmpep 10 years ago

How does the following normal function work (pseudo code) ?

I couldn't see the math behind it directly so help me.

It finds the normal to the procedurally generated terrain


Vector2 normal(x,y)
{
    Vector2 avg
    for(int w = -5; w <= 5; w++)
    {
      for(int h = -5; h <= 5; h++)
      {
        if pixel at terrain is solid at (x+w,y+h)
        {
          avg -= (w,h)
        }
      }
    }
    return avg/hypot(avg.x,avg.y) //normalize
}

Advertisement

Besides missing the use of arguments x, y inside the function, it seems me that the function computes something like the direction (or its inverse) from the geometric center of a pixel area to the center of gravity of the same area. This is because the only thing that prevents avg to be not always computed to (0,0) is the condition to check whether the addressed pixel is solid (assuming that "pixel is solid" means something like "pixel at (x+w,y+h) is solid"). In the end the computed avg is normalized to yield in just the direction, although the normalization allows for a division by zero (namely if all pixels are solid or all are un-solid).

Things were different if not (w,h) but a normal vector or so for the pixel at (x+w,y+h) are summed up instead. Perhaps the conversion to pseudo code has dropped some meaningful information? I'm not sure about...

Sorry for that , I have fixed the function.

I get the feeling this is some pretty weird version of finite differences...

EDIT: Yep, basically you have the typical convolution with [-1, 0, +1] of central finite differences but augmented to a 11x11 matrix. If you can only know for a given pixel if it is solid or not, I kind of like this "finite differences of a binary 2d function".

However, if you have a heighmap where y=f(x) using this instead of traditional finite differences of the 1D function doesn't make much sense....

“We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil” - Donald E. Knuth, Structured Programming with go to Statements

"First you learn the value of abstraction, then you learn the cost of abstraction, then you're ready to engineer" - Ken Beck, Twitter

This topic is closed to new replies.

Advertisement