Quantcast
Channel: C++博客-所有随笔
Viewing all articles
Browse latest Browse all 7882

please simplify me (again…)

$
0
0

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.  



LSH 2015-01-05 14:04 发表评论

Viewing all articles
Browse latest Browse all 7882

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>