game/sdlpp/sdlpp_geometry_line.hpp

31 lines
1013 B
C++

#ifndef SDLPP_HPP_GEOMETRY_LINE
#define SDLPP_HPP_GEOMETRY_LINE
#include "sdlpp_common.hpp"
#include "sdlpp_vector.hpp"
#include "sdlpp_line.hpp"
#include <algorithm>
namespace SDLPP {
template<typename T>
Vec2D<T> pointProjectionOnLine( const Vec2D<T> &point, const Line<T> &line ) {
/* from here -
* https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment
*/
auto length_squared = line.lengthSquared();
if ( length_squared == 0.0 )
return point;
auto t =
std::max( 0.0, std::min( 1.0, ( ( point - line.getStart() ) *
( line.getEnd() - line.getStart() ) ) /
length_squared ) );
return line.getStart() + t * ( line.getEnd() - line.getStart() );
}
template<typename T>
double pointLineDistance( const Vec2D<T> &point, const Line<T> &line ) {
return vecDistance( point, pointProjectionOnLine( point, line ) );
}
} // namespace SDLPP
#endif