# How does this normal() function works ?

This topic is 2029 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
}


Edited by amiC0der

##### Share on other sites

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...

Edited by haegarr

##### Share on other sites
Sorry for that , I have fixed the function.

##### Share on other sites

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....

Edited by Javier Meseguer de Paz

• ### Game Developer Survey

We are looking for qualified game developers to participate in a 10-minute online survey. Qualified participants will be offered a \$15 incentive for your time and insights. Click here to start!

• 14
• 30
• 9
• 16
• 22