2018-04-20 15:07:16 +10:00
|
|
|
/*
|
2018-08-04 15:14:06 +10:00
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
2018-04-20 15:07:16 +10:00
|
|
|
*
|
|
|
|
* Copyright 2018 Danny Robson <danny@nerdcruft.net>
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "../point.hpp"
|
|
|
|
|
|
|
|
|
2018-08-05 14:42:02 +10:00
|
|
|
namespace cruft::geom {
|
2019-03-21 17:29:26 +11:00
|
|
|
/// Represents a line that has a start and an end.
|
|
|
|
///
|
|
|
|
/// It is not valid to create an unbounded segment by fixing one of the
|
|
|
|
/// points at infinity.
|
2018-04-20 15:07:16 +10:00
|
|
|
template <size_t S, typename T>
|
|
|
|
struct segment {
|
2019-03-21 17:29:26 +11:00
|
|
|
cruft::point<S,T> a; /// The start of the segment.
|
|
|
|
cruft::point<S,T> b; /// The end of the segment.
|
2019-03-21 16:48:40 +11:00
|
|
|
|
2019-03-21 17:29:26 +11:00
|
|
|
/// Return a copy of this object with the underlying type casted to
|
|
|
|
/// the specified type.
|
2019-03-21 16:48:40 +11:00
|
|
|
template <typename CastT>
|
|
|
|
segment<S,CastT>
|
|
|
|
cast (void) const {
|
|
|
|
return {
|
|
|
|
.a = a.template cast<CastT> (),
|
|
|
|
.b = b.template cast<CastT> ()
|
|
|
|
};
|
|
|
|
}
|
2018-04-20 15:07:16 +10:00
|
|
|
};
|
|
|
|
|
|
|
|
|
2019-03-21 17:29:26 +11:00
|
|
|
/// Return the squared distance from the closest point of the segment `s`
|
|
|
|
/// to the point `p`.
|
2018-04-20 15:07:16 +10:00
|
|
|
template <size_t S, typename T>
|
|
|
|
T
|
|
|
|
distance2 (segment<S,T> s, point<S,T> p)
|
|
|
|
{
|
|
|
|
const auto dir = s.b - s.a;
|
|
|
|
const auto t1 = dot (p - s.a, dir);
|
|
|
|
if (t1 < 0)
|
|
|
|
return distance2 (p, s.a);
|
|
|
|
|
|
|
|
const auto t2 = dot (dir, dir);
|
|
|
|
if (t2 < t1)
|
|
|
|
return distance2 (p, s.b);
|
|
|
|
|
|
|
|
auto t = t1 / t2;
|
|
|
|
return distance2 (p, s.a + t * dir);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-03-21 17:29:26 +11:00
|
|
|
/// Return the distance from a the closest point of the segment `s` to
|
|
|
|
/// the point `p`.
|
2018-04-20 15:07:16 +10:00
|
|
|
template <size_t S, typename T>
|
|
|
|
T
|
|
|
|
distance (segment<S,T> s, point<S,T> p)
|
|
|
|
{
|
|
|
|
return std::sqrt (distance2 (s, p));
|
|
|
|
}
|
2019-03-21 17:29:26 +11:00
|
|
|
|
|
|
|
|
|
|
|
using segment2i = segment<2,int>;
|
|
|
|
using segment3i = segment<3,int>;
|
|
|
|
|
|
|
|
using segment2f = segment<2,float>;
|
|
|
|
using segment3f = segment<3,float>;
|
2019-03-11 18:56:39 +11:00
|
|
|
}
|