# DistanceToNearestSurface doesn't blend

I’m currently trying to create a water material, that recognizes objects inside of it to create foam around it. I researched a lot and found about this node called “DistanceToNearestSurface” and people seemed to get some proper results with it.

I may at first explain my understanding of this node.
Apparently it calculates the distance between the nearest DistanceField and the desired position. This works very well with the landscape mesh and after seeing images of it working also with static mesh, I tried to put some rocks into the river (from the Starter Content).

Here I got my problems. These objects just create a spot that’s not blending at all. Every image I’m looking at in the web, shows objects blending perfectly fine, so I couldn’t find a solution. Also it seems like some weird artifacts are appearing randomly. Same happens with the “DistanceFieldGradient”.

What I did was:

Obviously change the settings to “Generate Mesh Distance Fields”.

I turned off “Cast Shadows” of the water mesh, which is basically a plane and put the material on it.

I also made the Skylight movable as suggested on some other site.

Maybe I’m missing some kind of setting or I misunderstood how this node works and I would be glad if somebody could explain to me, what I’m doing wrong.

This is the scene:

This is the DistanceField scene:

And this is my material, it’s very basic:

The following shows results that I would like to see for myself.

[Tidal Water Foam - Rendering - Unreal Engine Forums][4]
[Image from Engine Features Preview 5/29/2015][5]

Thank you guys very much for your time!

“Apparently it calculates the distance between the nearest DistanceField and the desired position.”

This is not entirely correct. It gives the approximate distance in centimeters to the nearest surface from the given position. Which is positive when the given position is outside of the mesh, and negative when the given position is inside of a mesh.

Since you clamp the value between 0 and 1 anything negative is going to be zero. Next you invert it using the lerp(1,0) so this means all the negative values will become white.

Your mesh is probably a bit to small, and approximately the distance towards the surface is inside the mesh, giving you since it is clamped and inverted the white spots.

In all my demos I used fairly large meshes. You could also play around with the console settings. All settings start with r.DF or r.DistanceField.

Bonus tip: Since at the end you have a value between 0 and 1, doing a lerp(1,0) as doing a OneMinus.
Expample, lets say you have a value of 0.3, these would be the equations:

``````Lerp: 0.3 * (0 - 1) + 1 = 0.7;
OneMinus: 1 - 0.3 = 0.7;
``````

OneMinus basically inverts a value between 0 and 1. Lerp linearly interpolates between 2 values based on a single value between 0 and 1.

Enjoy!