Tuesday, December 17, 2019

unity - Antialiasing shader grid lines


I would like to have in-game grid lines similar to ones found in Unity editor. There is simple solution(first listing) based on shaders found on unity forums(on right image). However, that solution does not take in account antialiasing and drawn lines looks terrible even few units away from camera.


float4 frag(vertexOutput input) : COLOR {
if (frac(input.worldPos.x / _GridSpacing) < _GridThickness
|| frac(input.worldPos.z / _GridSpacing) < _GridThickness) {
return _GridColour;

}
else return _BaseColour;
}

overview In order to address that, I tried using typical fwidth/smoothstep combination:


float4 frag(vertexOutput input) : COLOR{
float distX = min(frac(input.worldPos.x / _GridSpacing), 1.0 - frac(input.worldPos.x / _GridSpacing));
float distZ = min(frac(input.worldPos.z / _GridSpacing), 1.0 - frac(input.worldPos.z / _GridSpacing));
float dist = min(distX, distZ);
float delta = fwidth(dist);

float alpha = smoothstep(_GridThickness - delta, _GridThickness, dist);
return lerp(_GridColour, _BaseColour, alpha);
}

Even though it has nice fade, the result is not quite near to perfect - not only the lines looks thinner(which can be somewhat fixed by increasing width), but also have various artifacts(e.g. in joints) and horizontal lines disappear much sooner than vertical ones. Detail image(anti aliased on left): detail I am interested in shader solutions, since according to answer to similar question relying textures there in can be no solution with textures. In addition I would like grid lines fade at reasonable distance(when closely inspecting aliased overview image you can see where plane ends) rather than continuing to infinity.
Full current version(for testing purposes) with signed distance.




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...