http://www.iquilezles.org/blog/?p=2848
Yet another example of code simplification that people don’t seem to want to do. It must be the 5th ot 6th time I ask people to do this change when programming a point-to-line distance computation: please, replace this ugly
float sdLine( vec2 a, vec2 b, vec2 p )
{
vec2 ba = b - a;
vec2 pa = p - a;
float dist = (ba.x*pa.y - ba.y*pa.x) / distance(a, b);
if( dot(a-b,p-b) < 0.0 )
return distance(b, p);
if( dot(b-a,p-a) < 0.0 )
return distance(a, p);
return abs(dist);
}
by the much more beautiful:
float sdLine( vec2 a, vec2 b, vec2 p )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
Do it for the karma or something.