競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// 3 次元の直線・線分・平面・三角形の関数を愚直な方法と比べる
// 距離は、線分や平面のパラメータについて凸なので、三分探索で最小化したものと比べる
// segment_triangle_intersect は、平面を貫く場合は交点を有理数で正確に求めて三角形の内外を調べたものと、
// 同じ平面上の場合は z = 0 の平面で 2 次元の判定をしてから、行列式 ±1 の整数の行列で空間に移したものと比べる
// 問題の入力は使わず、すべて成り立ったら Hello World を出力する
#include "../../../src/geometry/plane.hpp"
#include <cmath>
#include <functional>
#include <iostream>
#include <random>
#include <vector>
#include "../../../src/geometry/polygon.hpp"
#include "../../../src/geometry/triangle.hpp"
#include "../../../src/geometry/vector.hpp"
using P = Vector<long long, 3>;
constexpr Plane horizontal(P(0, 0, 0), P(1, 0, 0), P(0, 1, 0));
static_assert(std::is_same_v<std::decay_t<decltype(horizontal)>, Plane<long long>>);
static_assert(horizontal == Plane(P(3, 4, 0), P(3, 5, 0), P(4, 4, 0)));
static_assert(horizontal != Plane(P(0, 0, 1), P(1, 0, 1), P(0, 1, 1)));
static_assert(horizontal != Plane(P(0, 0, 0), P(1, 0, 0), P(0, 0, 1)));
static_assert(is_parallel(horizontal, Plane(P(0, 0, 1), P(0, 1, 1), P(1, 0, 1))));
static_assert(!is_parallel(horizontal, Plane(P(0, 0, 0), P(1, 0, 0), P(0, 0, 1))));
static_assert(horizontal.contains(P(3, -4, 0)));
static_assert(!horizontal.contains(P(3, -4, 1)));
using D = Vector<double, 3>;
using L = long double;
bool ok = true;
void check(bool cond, const char* what) {
if (!cond) {
if (ok) std::cerr << "failed: " << what << std::endl;
ok = false;
}
}
bool near(double a, double b) { return std::abs(a - b) <= 1e-6 * std::max(1.0, std::abs(b)); }
// [lo, hi] で凸な関数の最小値
L minimize(const std::function<L(L)>& f, L lo, L hi) {
for (int i = 0; i < 80; i++) {
L m1 = (2 * lo + hi) / 3, m2 = (lo + 2 * hi) / 3;
if (f(m1) < f(m2))
hi = m2;
else
lo = m1;
}
return f((lo + hi) / 2);
}
Vector<L, 3> at(const P& p, const P& q, L t) { return Vector<L, 3>(p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t); }
L dist(const Vector<L, 3>& a, const Vector<L, 3>& b) {
L s = 0;
for (int i = 0; i < 3; i++) s += (a[i] - b[i]) * (a[i] - b[i]);
return std::sqrt(s);
}
Vector<L, 3> to_l(const P& p) { return Vector<L, 3>(p[0], p[1], p[2]); }
// 平面を貫く場合の愚直な判定: 交点を p1 * den + (p2 - p1) * num (の 1/den) として正確に求める
__int128_t vol(const P& a, const P& b, const P& c, const P& d) {
__int128_t m[3][3];
for (int i = 0; i < 3; i++) m[0][i] = b[i] - a[i], m[1][i] = c[i] - a[i], m[2][i] = d[i] - a[i];
return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
}
bool naive_crossing(const P& p1, const P& p2, const P& a, const P& b, const P& c) {
__int128_t v1 = vol(a, b, c, p1), v2 = vol(a, b, c, p2);
if ((v1 > 0 && v2 > 0) || (v1 < 0 && v2 < 0)) return false;
// 交点は p1 + (p2 - p1) * v1 / (v1 - v2)。den 倍した座標で三角形の内外を調べる
__int128_t num = v1, den = v1 - v2;
if (den < 0) num = -num, den = -den;
using W = Vector<__int128_t, 3>;
auto scale = [&](const P& p) { return W(p[0] * den, p[1] * den, p[2] * den); };
W q(p1[0] * den + (p2[0] - p1[0]) * num, p1[1] * den + (p2[1] - p1[1]) * num, p1[2] * den + (p2[2] - p1[2]) * num);
W A = scale(a), B = scale(b), C = scale(c);
W n = cross(B - A, C - A);
__int128_t x = dot(n, cross(B - A, q - A)), y = dot(n, cross(C - B, q - B)), z = dot(n, cross(A - C, q - C));
return x >= 0 && y >= 0 && z >= 0;
}
int main() {
std::mt19937 rng(314);
auto rnd = [&](int w) { return static_cast<long long>(rng() % (2 * w + 1)) - w; };
auto rp = [&](int w) { return P(rnd(w), rnd(w), rnd(w)); };
for (int rep = 0; rep < 400 && ok; rep++) {
const int w = rng() % 2 ? 3 : 100;
P p1 = rp(w), p2 = rp(w), q1 = rp(w), q2 = rp(w), p = rp(w);
if (rng() % 4 == 0) q2 = q1 + (p2 - p1) * (rng() % 3); // 平行
// 点と線分・直線
{
L e = minimize([&](L t) { return dist(at(p1, p2, t), to_l(p)); }, 0, 1);
check(near(distance_point_segment(Segment(p1, p2), p), e), "distance_point_segment");
if (p1 != p2) {
L f = minimize([&](L t) { return dist(at(p1, p2, t), to_l(p)); }, -1000, 1000);
check(near(distance_point_line(Line(p1, p2), p), f), "distance_point_line");
}
}
// 線分どうし: s を外側、t を内側で三分探索する (距離は (s, t) について凸)
{
L e = minimize([&](L s) { return minimize([&](L t) { return dist(at(p1, p2, s), at(q1, q2, t)); }, 0, 1); }, 0, 1);
check(near(distance_segments(Segment(p1, p2), Segment(q1, q2)), e), "distance_segments");
}
// 直線どうし
if (p1 != p2 && q1 != q2) {
L e = minimize([&](L s) { return minimize([&](L t) { return dist(at(p1, p2, s), at(q1, q2, t)); }, -1000, 1000); }, -1000, 1000);
check(near(distance_lines(Line(p1, p2), Line(q1, q2)), e), "distance_lines");
}
// 点と平面、直線と平面
{
P a = rp(w), b = rp(w), c = rp(w);
if (cross(b - a, c - a) == P()) continue;
const Plane plane(a, b, c);
const Plane same(a + (b - a) * 2, a + (c - a) * 3, a - (b - a) - (c - a));
check(plane == same && same == plane && plane == Plane(c, b, a), "Plane equality");
P normal = cross(b - a, c - a);
check(plane.contains(a) && plane.contains(b) && plane.contains(c), "Plane contains defining points");
check(plane.contains(a + (b - a) * 3 - (c - a) * 2), "Plane contains affine combination");
check(!plane.contains(a + normal) && !plane.contains(a - normal), "Plane excludes points off plane");
check(plane.contains(Line(a, b)) && plane.contains(Line(c, c + b - a)), "Plane contains line");
check(plane.contains(Line(b, a)), "Plane contains reversed line");
check(!plane.contains(Line(a + normal, b + normal)), "Plane excludes parallel line");
check(!plane.contains(Line(a, a + normal)) && !plane.contains(Line(a + normal, a)), "Plane excludes crossing line");
const Plane shifted(a + normal, b + normal, c + normal);
check(is_parallel(plane, same) && is_parallel(plane, shifted) && is_parallel(shifted, plane), "parallel planes");
check(is_parallel(Line(a, b), plane) && is_parallel(plane, Line(c + normal, c + normal + b - a)), "parallel line and plane");
check(!is_parallel(Line(a, a + normal), plane) && !is_parallel(plane, Line(a, a + normal)), "line crossing plane");
check(is_parallel(Line(a, b), Line(c, c - (b - a) * 3)), "parallel lines");
check(!is_parallel(Line(a, b), Line(a, c)), "nonparallel lines");
check(plane != Plane(a + normal, b + normal, c + normal), "Plane parallel and distinct");
L e = minimize([&](L s) { return minimize([&](L t) {
Vector<L, 3> x = to_l(a) + (to_l(b) - to_l(a)) * s + (to_l(c) - to_l(a)) * t;
return dist(x, to_l(p));
},
-1000, 1000); },
-1000, 1000);
check(near(distance_point_plane(Plane(a, b, c), p), e), "distance_point_plane");
if (p1 == p2) continue;
auto to_d = [](const P& v) { return D(v[0], v[1], v[2]); };
auto x = line_plane_intersection(Line(to_d(p1), to_d(p2)), Plane(to_d(a), to_d(b), to_d(c)));
const bool parallel = dot(cross(b - a, c - a), p2 - p1) == 0;
check(is_parallel(Line(p1, p2), plane) == parallel, "is_parallel and intersection");
check(x.has_value() != parallel, "line_plane_intersection (平行)");
if (x) {
check(distance_point_plane(Plane(to_d(a), to_d(b), to_d(c)), *x) < 1e-6, "line_plane_intersection (平面上)");
check(distance_point_line(Line(to_d(p1), to_d(p2)), *x) < 1e-6, "line_plane_intersection (直線上)");
}
}
}
// 線分と三角形: 平面を貫く (または端点が平面上にある) 場合
for (int rep = 0; rep < 200000 && ok; rep++) {
const int w = rng() % 2 ? 2 : 5;
P p1 = rp(w), p2 = rp(w), a = rp(w), b = rp(w), c = rp(w);
if (cross(b - a, c - a) == P()) continue;
if (vol(a, b, c, p1) == 0 && vol(a, b, c, p2) == 0) continue;
check(segment_triangle_intersect(Segment(p1, p2), Triangle(a, b, c)) == naive_crossing(p1, p2, a, b, c), "segment_triangle_intersect (貫く)");
}
// 同じ平面上の場合: z = 0 で 2 次元の判定をして、行列式 ±1 の行列と平行移動で空間に移す
for (int rep = 0; rep < 100000 && ok; rep++) {
const int w = rng() % 2 ? 2 : 6;
using V2 = Vector<long long, 2>;
auto r2 = [&]() { return V2(rnd(w), rnd(w)); };
V2 p1 = r2(), p2 = r2(), a = r2(), b = r2(), c = r2();
if (cross(b - a, c - a) == 0) continue;
std::vector<V2> tri = {a, b, c};
if (cross(b - a, c - a) < 0) tri = {a, c, b};
bool expect = polygon_contains(tri, p1) > 0 || polygon_contains(tri, p2) > 0;
if (p1 != p2) expect = expect || segments_intersect(Segment(p1, p2), Segment(a, b)) || segments_intersect(Segment(p1, p2), Segment(b, c)) || segments_intersect(Segment(p1, p2), Segment(c, a));
// 基本変形 (ある行に別の行の整数倍を足す) を何回か掛けた行列
long long m[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
for (int k = 0; k < 4; k++) {
int i = rng() % 3, j = (i + 1 + rng() % 2) % 3;
long long f = rnd(2);
for (int col = 0; col < 3; col++) m[i][col] += f * m[j][col];
}
P shift = rp(10);
auto lift = [&](const V2& v) {
P r;
for (int i = 0; i < 3; i++) r[i] = m[i][0] * v[0] + m[i][1] * v[1] + shift[i];
return r;
};
check(segment_triangle_intersect(Segment(lift(p1), lift(p2)), Triangle(lift(a), lift(b), lift(c))) == expect, "segment_triangle_intersect (同じ平面上)");
}
// 3 次元の型推論と、同じ直線・線分の判定。ねじれの位置も区別する
{
Line line(P(0, 0, 0), P(1, 2, 3));
static_assert(std::is_same_v<decltype(line), Line<long long, 3>>);
Segment segment(P(0, 0, 0), P(1, 2, 3));
static_assert(std::is_same_v<decltype(segment), Segment<long long, 3>>);
check(line == Line(P(3, 6, 9), P(-2, -4, -6)), "Line equality");
check(line != Line(P(0, 0, 1), P(1, 2, 4)), "Line parallel and distinct");
check(line != Line(P(0, 1, 0), P(1, 1, 0)), "Line skew");
check(segment == Segment(P(1, 2, 3), P(0, 0, 0)), "Segment equality");
check(segment != Segment(P(0, 0, 0), P(2, 4, 6)), "Segment distinct");
}
// 座標が 1e9 でも体積の計算があふれない
const long long G = 1000000000;
const Plane large(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0));
check(large == Plane(P(0, 0, 0), P(G, G, 0), P(-G, G, 0)), "Plane equality (1e9)");
check(large != Plane(P(-G, -G, G), P(G, -G, G), P(0, G, G)), "Plane distinct (1e9)");
const Plane large_shifted(P(-G, -G, G), P(0, G, G), P(G, -G, G));
check(is_parallel(large, large_shifted), "parallel planes (1e9)");
check(is_parallel(Line(P(-G, G, G), P(G, G, G)), large), "parallel line and plane (1e9)");
check(!is_parallel(Line(P(-G, -G, -G), P(G, G, G)), large), "nonparallel line and plane (1e9)");
check(is_parallel(Line(P(-G, -G, -G), P(G, G, G)), Line(P(G, G, G), P(0, 0, 0))), "parallel lines (1e9)");
check(near(distance_point_plane(large, P(G, G, G)), G), "distance_point_plane (1e9)");
check(large.contains(P(G, G, 0)) && !large.contains(P(G, G, G)), "Plane contains point (1e9)");
check(large.contains(Line(P(-G, G, 0), P(G, G, 0))), "Plane contains line (1e9)");
check(!large.contains(Line(P(-G, G, G), P(G, G, G))), "Plane excludes line (1e9)");
const Plane floating(D(0, 0, 0.5), D(1, 0, 0.5), D(0, 1, 0.5));
static_assert(std::is_same_v<std::decay_t<decltype(floating)>, Plane<double>>);
check(floating == Plane(D(2, 3, 0.5), D(3, 3, 0.5), D(2, 4, 0.5)), "Plane equality (double)");
check(floating.contains(D(2, -3, 0.5)) && !floating.contains(D(2, -3, 0.500001)), "Plane contains point (double)");
check(floating.contains(Line(D(1, 2, 0.5), D(3, 4, 0.5))), "Plane contains line (double)");
check(!floating.contains(Line(D(1, 2, 1.5), D(3, 4, 1.5))), "Plane excludes line (double)");
check(!line_plane_intersection(Line(D(0, 0, 0.5), D(1, 0, 0.5)), floating), "line contained in plane");
check(!line_plane_intersection(Line(D(0, 0, 1.5), D(1, 0, 1.5)), floating), "line parallel to plane");
check(is_parallel(floating, floating) && is_parallel(Line(D(0, 0, 1.5), D(1, 0, 1.5)), floating), "parallel (double)");
check(!is_parallel(floating, Line(D(0, 0, 0), D(0, 0, 1))), "nonparallel (double)");
check(segment_triangle_intersect(Segment(P(0, 0, -G), P(0, 0, G)), Triangle(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0))), "segment_triangle_intersect (1e9)");
check(!segment_triangle_intersect(Segment(P(G, G, -G), P(G, G, G)), Triangle(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0))), "segment_triangle_intersect (1e9, 外)");
check(near(distance_point_line(Line(P(-G, -G, -G), P(G, G, G)), P(G, -G, 0)), std::sqrt(2.0) * G), "distance_point_line (1e9)");
if (ok) std::cout << "Hello World" << std::endl;
}#line 1 "test/unittest/geometry/plane.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
// 3 次元の直線・線分・平面・三角形の関数を愚直な方法と比べる
// 距離は、線分や平面のパラメータについて凸なので、三分探索で最小化したものと比べる
// segment_triangle_intersect は、平面を貫く場合は交点を有理数で正確に求めて三角形の内外を調べたものと、
// 同じ平面上の場合は z = 0 の平面で 2 次元の判定をしてから、行列式 ±1 の整数の行列で空間に移したものと比べる
// 問題の入力は使わず、すべて成り立ったら Hello World を出力する
#line 2 "src/geometry/plane.hpp"
/**
* @file plane.hpp
* @brief 平面 (包含・平行判定、距離、直線との交点)
*/
#include <cassert>
#include <cmath>
#include <optional>
#include <type_traits>
#line 2 "src/geometry/internal/predicates.hpp"
/**
* @file predicates.hpp
* @brief 幾何の内部計算 (整数座標の拡張、向き、ノルム)
*/
#line 10 "src/geometry/internal/predicates.hpp"
#line 2 "src/geometry/vector.hpp"
/**
* @file vector.hpp
* @brief 幾何ベクトル
*/
#include <array>
#line 11 "src/geometry/vector.hpp"
#include <istream>
#include <ostream>
#line 14 "src/geometry/vector.hpp"
#include <utility>
#line 2 "src/utility/traits.hpp"
/**
* @file traits.hpp
* @brief 型特性
*/
#include <cstddef>
#include <functional>
#include <iterator>
#include <set>
#line 14 "src/utility/traits.hpp"
#if __cplusplus >= 202002L
#include <concepts>
#include <ranges>
#endif
namespace internal_traits {
using std::begin, std::end;
#if __cplusplus >= 202002L
template <class T>
struct is_range_impl : std::bool_constant < requires(T& t) {
begin(t);
end(t);
}>{};
#else
template <class T, class = void>
struct is_range_impl : std::false_type {};
template <class T>
struct is_range_impl<T, std::void_t<decltype(begin(std::declval<T&>()), end(std::declval<T&>()))>> : std::true_type {};
#endif
// サイズ付き範囲から要素を直接構築するコンストラクタで共有する。
#if __cplusplus >= 202002L
template <class R, class S>
concept sized_constructible_range = std::ranges::input_range<R> && std::ranges::sized_range<R> &&
std::is_constructible_v<S, std::ranges::range_reference_t<R>>;
template <class R>
auto range_size(R& r) {
return std::ranges::size(r);
}
template <class R>
auto range_begin(R& r) {
return std::ranges::begin(r);
}
template <class R>
using range_value_t = std::ranges::range_value_t<R>;
#else
using std::size;
template <class R>
auto range_size(R& r) -> decltype(size(r)) {
return size(r);
}
template <class R>
auto range_begin(R& r) -> decltype(begin(r)) {
return begin(r);
}
template <class R>
using range_value_t = typename std::iterator_traits<decltype(range_begin(std::declval<R&>()))>::value_type;
template <class R, class S, class = void>
struct is_sized_constructible_range : std::false_type {};
template <class R, class S>
struct is_sized_constructible_range<R, S, std::void_t<decltype(range_size(std::declval<R&>())), decltype(++std::declval<decltype(begin(std::declval<R&>()))&>()), decltype(begin(std::declval<R&>()) != end(std::declval<R&>())), decltype(*begin(std::declval<R&>()))>>
: std::is_constructible<S, decltype(*begin(std::declval<R&>()))> {};
#endif
} // namespace internal_traits
template <class T>
struct is_range : internal_traits::is_range_impl<T>::type {};
template <class T>
inline constexpr bool is_range_v = is_range<T>::value;
#if __cplusplus >= 202002L
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(); }; \
} \
template <class T> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T>> {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, class U> \
concept has_##func_name##_impl = requires { std::declval<T>().func_name(std::declval<U>()); }; \
} \
template <class T, class U> \
struct has_##func_name : std::bool_constant<internal_traits::has_##func_name##_impl<T, U>> {}; \
template <class T, class U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#else
#define HAS_METHOD(func_name) \
namespace internal_traits { \
template <class T, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T> \
struct has_##func_name##_impl<T, std::void_t<decltype(std::declval<T>().func_name())>> \
: std::true_type {}; \
} \
template <class T> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T>::type {}; \
template <class T> \
inline constexpr bool has_##func_name##_v = has_##func_name<T>::value;
#define HAS_METHOD_ARG(func_name) \
namespace internal_traits { \
template <class T, typename U, class = void> \
struct has_##func_name##_impl : std::false_type {}; \
template <class T, typename U> \
struct has_##func_name##_impl<T, U, std::void_t<decltype(std::declval<T>().func_name(std::declval<U>()))>> \
: std::true_type {}; \
} \
template <class T, typename U> \
struct has_##func_name : internal_traits::has_##func_name##_impl<T, U>::type {}; \
template <class T, typename U> \
inline constexpr bool has_##func_name##_v = has_##func_name<T, U>::value;
#endif
HAS_METHOD(repr)
HAS_METHOD(type_str)
HAS_METHOD(initializer_str)
HAS_METHOD(max)
HAS_METHOD(min)
HAS_METHOD(reversed)
HAS_METHOD(sorted)
HAS_METHOD(sum)
HAS_METHOD(product)
HAS_METHOD(product_xor)
HAS_METHOD_ARG(count)
HAS_METHOD_ARG(find)
HAS_METHOD_ARG(lower_bound)
HAS_METHOD_ARG(upper_bound)
#define ENABLE_IF_T_IMPL(expr) std::enable_if_t<expr, std::nullptr_t> = nullptr
#define ENABLE_IF_T(...) ENABLE_IF_T_IMPL((__VA_ARGS__))
namespace internal_traits {
// 射影 (proj) の既定値
#if __cplusplus >= 202002L
using identity = std::identity;
#else
struct identity {
using is_transparent = void;
template <class T>
constexpr T&& operator()(T&& x) const noexcept {
return std::forward<T>(x);
}
};
#endif
} // namespace internal_traits
template <class C>
using mem_value_type = typename C::value_type;
template <class C>
using mem_difference_type = typename C::difference_type;
namespace internal_traits {
template <class T, class = void>
struct is_sorted_container_impl : std::false_type {};
template <class T>
struct is_sorted_container_impl<std::set<T>> : std::true_type {};
template <class T>
struct is_sorted_container_impl<std::multiset<T>> : std::true_type {};
} // namespace internal_traits
template <class T>
struct is_sorted_container : internal_traits::is_sorted_container_impl<T>::type {};
template <class T>
inline constexpr bool is_sorted_container_v = is_sorted_container<T>::value;
#line 17 "src/geometry/vector.hpp"
/**
* @brief 幾何学としてのベクトル
*
* @tparam T 型 省略したらdouble
* @tparam Dim 次元 省略したら2
*/
template <typename T = double, int Dim = 2, ENABLE_IF_T(std::is_scalar_v<T> && (Dim > 0))>
struct Vector {
std::array<T, Dim> v; //!< ベクトルの成分表示
/**
* @brief デフォルトコンストラクタ
* ゼロベクトル
*/
constexpr Vector() noexcept : v() {}
/**
* @brief 可変長引数によるコンストラクタ
*
* 各成分を T に変換して入れる (Vector(1, 2.5) のように型が混ざっても縮小変換の警告を出さない)
* @tparam Args
*/
template <typename... Args>
constexpr Vector(Args... args) noexcept : v{static_cast<T>(args)...} {}
/**
* @brief i番目の成分を返す
*
* @param i
* @return T&
*/
constexpr T& operator[](long long i) noexcept {
return v[i];
}
/**
* @brief i番目の成分を返す
*
* @param i
* @return T&
*/
constexpr const T& operator[](long long i) const noexcept {
return v[i];
}
/**
* @brief 加算代入演算子
*
* @param rhs
* @return Vector&
*/
constexpr Vector& operator+=(const Vector& rhs) noexcept {
for (int i = 0; i < Dim; i++) v[i] += rhs[i];
return *this;
}
/**
* @brief 減算代入演算子
*
* @param rhs
* @return Vector&
*/
constexpr Vector& operator-=(const Vector& rhs) noexcept {
for (int i = 0; i < Dim; i++) v[i] -= rhs.v[i];
return *this;
}
/**
* @brief スカラー倍代入演算子
*
* @param coef
* @return Vector&
*/
constexpr Vector& operator*=(const T& coef) noexcept {
for (int i = 0; i < Dim; i++) v[i] *= coef;
return *this;
}
/**
* @brief スカラーの逆数倍代入演算子
*
* @param coef
* @return Vector&
*/
constexpr Vector& operator/=(const T& coef) {
for (int i = 0; i < Dim; i++) {
if constexpr (std::is_integral_v<T>) {
assert(v[i] % coef == 0 && "Vector::operator/= : coef must be a divisor of all elements");
}
v[i] /= coef;
}
return *this;
}
/**
* @brief 単項プラス演算子
*
* @return Vector
*/
[[nodiscard]]
constexpr Vector operator+() const noexcept {
return *this;
}
/**
* @brief 単項マイナス演算子
*
* @return Vector
*/
[[nodiscard]]
constexpr Vector operator-() const noexcept {
return *this * (-1);
}
/**
* @brief 加算演算子
*
* @param lhs
* @param rhs
* @return Vector
*/
[[nodiscard]]
friend constexpr Vector operator+(const Vector& lhs, const Vector& rhs) noexcept {
return std::move(Vector(lhs) += rhs);
}
/**
* @brief 減算演算子
*
* @param lhs
* @param rhs
* @return Vector
*/
[[nodiscard]]
friend constexpr Vector operator-(const Vector& lhs, const Vector& rhs) noexcept {
return std::move(Vector(lhs) -= rhs);
}
/**
* @brief スカラー倍演算子
*
* @param lhs
* @param coef
* @return Vector
*/
[[nodiscard]]
friend constexpr Vector operator*(const Vector& lhs, const T& coef) noexcept {
return std::move(Vector(lhs) *= coef);
}
/**
* @brief スカラー倍演算子
*
* @param coef
* @param rhs
* @return Vector
*/
[[nodiscard]]
friend constexpr Vector operator*(const T& coef, const Vector& rhs) noexcept {
return std::move(Vector(rhs) *= coef);
}
/**
* @brief スカラーの逆数倍演算子
*
* @param lhs
* @param coef
* @return Vector
*/
[[nodiscard]]
friend constexpr Vector operator/(const Vector& lhs, const T& coef) {
return std::move(Vector(lhs) /= coef);
}
/**
* @brief 等価演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator==(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v == rhs.v;
}
/**
* @brief 非等価演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator!=(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v != rhs.v;
}
/**
* @brief 小なり演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator<(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v < rhs.v;
}
/**
* @brief 大なり演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator>(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v > rhs.v;
}
/**
* @brief 小なりイコール演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator<=(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v <= rhs.v;
}
/**
* @brief 大なりイコール演算子
*
* @param lhs
* @param rhs
* @return bool
*/
[[nodiscard]]
friend constexpr bool operator>=(const Vector& lhs, const Vector& rhs) noexcept {
return lhs.v >= rhs.v;
}
/**
* @brief 入力ストリームからの読み込み
*
* @tparam CharT 入力ストリームの文字型
* @tparam Traits 入力ストリームの文字型特性
* @param is
* @param rhs
* @return std::basic_istream<CharT, Traits>&
*/
template <class CharT, class Traits>
friend std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, Vector& rhs) {
for (int i = 0; i < Dim; i++) is >> rhs.v[i];
return is;
}
/**
* @brief 出力ストリームへの書き込み
*
* @tparam CharT 出力ストリームの文字型
* @tparam Traits 出力ストリームの文字型特性
* @param is
* @param rhs
* @return std::basic_ostream<CharT, Traits>&
*/
template <class CharT, class Traits>
friend std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Vector& rhs) {
for (int i = 0; i < Dim; i++) {
if (i != 0) os << CharT(' ');
os << rhs.v[i];
}
return os;
}
/**
* @brief 内積
*
* @param lhs
* @param rhs
* @return T
*/
friend constexpr T dot(const Vector& lhs, const Vector& rhs) noexcept {
T ret = 0;
for (int i = 0; i < Dim; i++) ret += lhs[i] * rhs[i];
return ret;
}
/**
* @brief 絶対値の2乗
*
* @return T
*/
constexpr T squared_norm() const noexcept {
return dot(*this, *this);
}
/**
* @brief 絶対値
*
* @return double
*/
constexpr double abs() const noexcept {
return std::sqrt(squared_norm());
}
};
/**
* @brief 成分から作るときの推論ガイド。型は成分の共通の型、次元は成分の個数にする
*
* Vector(2LL, 3LL) は Vector<long long, 2>、Vector(1, 2, 3) は Vector<int, 3>、Vector(0.0, 0.0) は Vector<double, 2>
* (これがないと、テンプレート引数の省略時の値から Vector<double, 2> になってしまう)
*/
template <typename T, typename... U, ENABLE_IF_T(std::is_scalar_v<T> && (std::is_scalar_v<U> && ...))>
Vector(T, U...) -> Vector<std::common_type_t<T, U...>, 1 + sizeof...(U)>;
/**
* @brief 二次元ベクトルどうしの外積(平行四辺形の符号付き面積)
*
* @param lhs
* @param rhs
* @tparam T 座標の型
* @return T
*/
template <typename T>
constexpr T cross(const Vector<T, 2>& lhs, const Vector<T, 2>& rhs) noexcept {
return lhs[0] * rhs[1] - lhs[1] * rhs[0];
}
/**
* @brief 三次元ベクトルどうしの外積
*
* @param lhs
* @param rhs
* @tparam T 座標の型
* @return Vector<T, 3>
*/
template <typename T>
constexpr Vector<T, 3> cross(const Vector<T, 3>& lhs, const Vector<T, 3>& rhs) noexcept {
Vector<T, 3> ret;
ret[0] = lhs[1] * rhs[2] - lhs[2] * rhs[1];
ret[1] = lhs[2] * rhs[0] - lhs[0] * rhs[2];
ret[2] = lhs[0] * rhs[1] - lhs[1] * rhs[0];
return ret;
}
/**
* @brief 3点の位置関係 (counter-clockwise)
*
* 整数型でも使える。浮動小数点型では誤差を考えずに比較する
*
* @tparam T 座標の型
* @return int 1: a→b→c が反時計回り, -1: 時計回り, 2: c, a, b の順に一直線上, -2: a, b, c の順に一直線上, 0: c が線分 ab 上
*/
template <typename T>
constexpr int ccw(const Vector<T, 2>& a, const Vector<T, 2>& b, const Vector<T, 2>& c) {
Vector<T, 2> u = b - a, v = c - a;
T cr = cross(u, v);
if (cr > 0) return 1;
if (cr < 0) return -1;
if (dot(u, v) < 0) return 2;
if (u.squared_norm() < v.squared_norm()) return -2;
return 0;
}
#line 12 "src/geometry/internal/predicates.hpp"
namespace internal_predicates {
// 整数座標の外積・体積の計算に使う型 (座標が 1e9 なら体積は 1e27 程度になる)
template <typename T>
using Wide = std::conditional_t<std::is_integral_v<T>, __int128_t, T>;
template <typename T, int Dim>
constexpr Vector<Wide<T>, Dim> widen(const Vector<T, Dim>& p) {
Vector<Wide<T>, Dim> result;
for (int i = 0; i < Dim; ++i) result[i] = static_cast<Wide<T>>(p[i]);
return result;
}
// 四面体 abcd の符号付き体積の 6 倍の符号 (d が平面 abc の、abc が反時計回りに見える側なら正)
template <typename T>
int orient(const Vector<T, 3>& a, const Vector<T, 3>& b, const Vector<T, 3>& c, const Vector<T, 3>& d) {
const auto wa = widen(a);
const auto v = dot(cross(widen(b) - wa, widen(c) - wa), widen(d) - wa);
return (v > 0) - (v < 0);
}
template <typename T>
double norm(const Vector<T, 3>& v) {
const double x = static_cast<double>(v[0]), y = static_cast<double>(v[1]), z = static_cast<double>(v[2]);
return std::sqrt(x * x + y * y + z * z);
}
} // namespace internal_predicates
#line 2 "src/geometry/line.hpp"
/**
* @file line.hpp
* @brief 2 次元・3 次元の直線 (平行・直交、射影・反射、交点、距離)
*/
#line 12 "src/geometry/line.hpp"
#line 15 "src/geometry/line.hpp"
/**
* @brief 2 点で表す直線。p1 != p2 が必要。等値比較は同じ直線かを判定する
*/
template <typename T = long long, int Dim = 2>
struct Line {
static_assert(Dim >= 2, "dimension must be at least 2");
Vector<T, Dim> p1, p2;
constexpr Line(const Vector<T, Dim>& p1, const Vector<T, Dim>& p2) : p1(p1), p2(p2) {
assert(p1 != p2 && "Line: degenerate line");
}
constexpr bool operator==(const Line& other) const {
assert(p1 != p2 && other.p1 != other.p2 && "Line: degenerate line");
using Wide = std::conditional_t<std::is_integral_v<T>, __int128_t, T>;
auto on_line = [&](const Vector<T, Dim>& p) {
for (int i = 0; i < Dim; ++i) {
for (int j = i + 1; j < Dim; ++j) {
Wide di = static_cast<Wide>(p2[i]) - p1[i], dj = static_cast<Wide>(p2[j]) - p1[j];
Wide vi = static_cast<Wide>(p[i]) - p1[i], vj = static_cast<Wide>(p[j]) - p1[j];
if (di * vj != dj * vi) return false;
}
}
return true;
};
return on_line(other.p1) && on_line(other.p2);
}
constexpr bool operator!=(const Line& other) const { return !(*this == other); }
};
template <typename T, int Dim>
Line(const Vector<T, Dim>&, const Vector<T, Dim>&) -> Line<T, Dim>;
/**
* @brief 直線 p1p2 と直線 q1q2 が平行か (整数型でも使える)
*/
template <typename T>
constexpr bool is_parallel(const Line<T>& first, const Line<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
return cross(p2 - p1, q2 - q1) == 0;
}
/**
* @brief 直線 p1p2 と直線 q1q2 が直交するか (整数型でも使える)
*/
template <typename T>
constexpr bool is_orthogonal(const Line<T>& first, const Line<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
return dot(p2 - p1, q2 - q1) == 0;
}
/**
* @brief 点 p から直線 p1p2 に下ろした垂線の足 (射影)。浮動小数点型限定
*/
template <typename T>
constexpr Vector<T, 2> projection(const Line<T>& object, const Vector<T, 2>& p) {
const auto& [p1, p2] = object;
static_assert(std::is_floating_point_v<T>, "projection: T must be a floating point type");
assert(p1 != p2 && "projection: degenerate line");
Vector<T, 2> d = p2 - p1;
return p1 + d * (dot(p - p1, d) / d.squared_norm());
}
/**
* @brief 直線 p1p2 について点 p と対称な点 (反射)。浮動小数点型限定
*/
template <typename T>
constexpr Vector<T, 2> reflection(const Line<T>& object, const Vector<T, 2>& p) {
return projection(object, p) * T(2) - p;
}
/**
* @brief 直線 p1p2 と直線 q1q2 の交点。浮動小数点型限定。p1 != p2 かつ q1 != q2 であること
* @return std::optional<Vector<T, 2>> 交点 (平行 (重なる直線も含む) なら std::nullopt)
*/
template <typename T>
constexpr std::optional<Vector<T, 2>> line_intersection(const Line<T>& first, const Line<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
static_assert(std::is_floating_point_v<T>, "line_intersection: T must be a floating point type");
assert(p1 != p2 && q1 != q2 && "line_intersection: degenerate line");
Vector<T, 2> d = p2 - p1, e = q2 - q1;
T c = cross(e, d);
if (c == 0) return std::nullopt;
// p1 + d t が直線 q1q2 上にある t
return p1 + d * (cross(e, q1 - p1) / c);
}
/**
* @brief 点 p と直線 p1p2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_point_line(const Line<T>& object, const Vector<T, 2>& p) {
const auto& [p1, p2] = object;
assert(p1 != p2 && "distance_point_line: degenerate line");
return std::abs(static_cast<double>(cross(p2 - p1, p - p1))) / (p2 - p1).abs();
}
/** @brief 3 次元の直線同士が平行か。一致する場合も true */
template <typename T>
constexpr bool is_parallel(const Line<T, 3>& first, const Line<T, 3>& second) {
using internal_predicates::widen;
const auto u = widen(first.p2) - widen(first.p1), v = widen(second.p2) - widen(second.p1);
assert((u[0] != 0 || u[1] != 0 || u[2] != 0) && "is_parallel: degenerate line");
assert((v[0] != 0 || v[1] != 0 || v[2] != 0) && "is_parallel: degenerate line");
const auto n = cross(u, v);
return n[0] == 0 && n[1] == 0 && n[2] == 0;
}
/**
* @brief 点 p から直線 p1p2 に下ろした垂線の足 (射影)。浮動小数点型限定
*/
template <typename T>
constexpr Vector<T, 3> projection(const Line<T, 3>& object, const Vector<T, 3>& p) {
const auto& [p1, p2] = object;
static_assert(std::is_floating_point_v<T>, "projection: T must be a floating point type");
assert(p1 != p2 && "projection: degenerate line");
Vector<T, 3> d = p2 - p1;
return p1 + d * (dot(p - p1, d) / d.squared_norm());
}
/**
* @brief 点 p と直線 p1p2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_point_line(const Line<T, 3>& object, const Vector<T, 3>& p) {
const auto& [p1, p2] = object;
using namespace internal_predicates;
assert(p1 != p2 && "distance_point_line: degenerate line");
return norm(cross(widen(p2) - widen(p1), widen(p) - widen(p1))) / norm(p2 - p1);
}
/**
* @brief 直線 p1p2 と直線 q1q2 の距離 (整数型でも使える)。p1 != p2 かつ q1 != q2 であること
*/
template <typename T>
double distance_lines(const Line<T, 3>& first, const Line<T, 3>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
using namespace internal_predicates;
assert(p1 != p2 && q1 != q2 && "distance_lines: degenerate line");
const auto n = cross(widen(p2) - widen(p1), widen(q2) - widen(q1));
// 平行なら、一方の直線上の点ともう一方の直線の距離
if (n == decltype(n)()) return distance_point_line(Line(p1, p2), q1);
return std::abs(static_cast<double>(dot(n, widen(q1) - widen(p1)))) / norm(n);
}
#line 15 "src/geometry/plane.hpp"
/**
* @brief 一直線上にない 3 点で表す平面。等値比較は点の選び方・順序によらず同じ平面かを判定する
* @tparam T 座標の型。省略したら long long
*/
template <typename T = long long>
struct Plane {
Vector<T, 3> p1, p2, p3;
private:
constexpr void assert_valid() const {
using internal_predicates::widen;
const auto n = cross(widen(p2) - widen(p1), widen(p3) - widen(p1));
assert((n[0] != 0 || n[1] != 0 || n[2] != 0) && "Plane: collinear points");
}
public:
constexpr Plane(const Vector<T, 3>& p1, const Vector<T, 3>& p2, const Vector<T, 3>& p3) : p1(p1), p2(p2), p3(p3) {
assert_valid();
}
/** @brief 点 p が平面上にあるか。浮動小数点型では誤差を考慮しない */
constexpr bool contains(const Vector<T, 3>& p) const {
assert_valid();
using internal_predicates::widen;
const auto a = widen(p1), n = cross(widen(p2) - a, widen(p3) - a);
return dot(n, widen(p) - a) == 0;
}
/** @brief 直線全体が平面内にあるか。平面と平行でも離れている直線は false */
constexpr bool contains(const Line<T, 3>& line) const {
assert((line.p1[0] != line.p2[0] || line.p1[1] != line.p2[1] || line.p1[2] != line.p2[2]) && "Plane::contains: degenerate line");
return contains(line.p1) && contains(line.p2);
}
constexpr bool operator==(const Plane& other) const {
assert_valid();
other.assert_valid();
using internal_predicates::widen;
const auto a = widen(p1), n = cross(widen(p2) - a, widen(p3) - a);
return dot(n, widen(other.p1) - a) == 0 && dot(n, widen(other.p2) - a) == 0 && dot(n, widen(other.p3) - a) == 0;
}
constexpr bool operator!=(const Plane& other) const { return !(*this == other); }
};
template <typename T>
Plane(const Vector<T, 3>&, const Vector<T, 3>&, const Vector<T, 3>&) -> Plane<T>;
/** @brief 直線と平面が平行か。直線が平面に含まれる場合も true */
template <typename T>
constexpr bool is_parallel(const Line<T, 3>& line, const Plane<T>& plane) {
using internal_predicates::widen;
const auto d = widen(line.p2) - widen(line.p1);
const auto a = widen(plane.p1), n = cross(widen(plane.p2) - a, widen(plane.p3) - a);
assert((d[0] != 0 || d[1] != 0 || d[2] != 0) && "is_parallel: degenerate line");
assert((n[0] != 0 || n[1] != 0 || n[2] != 0) && "is_parallel: degenerate plane");
return dot(n, d) == 0;
}
/** @brief 平面と直線が平行か。直線が平面に含まれる場合も true */
template <typename T>
constexpr bool is_parallel(const Plane<T>& plane, const Line<T, 3>& line) {
return is_parallel(line, plane);
}
/** @brief 平面同士が平行か。一致する場合も true */
template <typename T>
constexpr bool is_parallel(const Plane<T>& first, const Plane<T>& second) {
using internal_predicates::widen;
const auto a = widen(first.p1), n = cross(widen(first.p2) - a, widen(first.p3) - a);
const auto b = widen(second.p1), u = widen(second.p2) - b, v = widen(second.p3) - b;
const auto m = cross(u, v);
assert((n[0] != 0 || n[1] != 0 || n[2] != 0) && "is_parallel: degenerate plane");
assert((m[0] != 0 || m[1] != 0 || m[2] != 0) && "is_parallel: degenerate plane");
// 法線同士の外積 (座標の差の 4 乗) を避け、3 乗までの計算で判定する。
return dot(n, u) == 0 && dot(n, v) == 0;
}
/**
* @brief 点 p と平面 abc の距離 (整数型でも使える)。a, b, c は一直線上にないこと
*/
template <typename T>
double distance_point_plane(const Plane<T>& plane, const Vector<T, 3>& p) {
const auto& [a, b, c] = plane;
using namespace internal_predicates;
const auto wa = widen(a);
const auto n = cross(widen(b) - wa, widen(c) - wa);
assert(n != decltype(n)() && "distance_point_plane: degenerate plane");
return std::abs(static_cast<double>(dot(n, widen(p) - wa))) / norm(n);
}
/**
* @brief 直線 p1p2 と平面 abc の交点。浮動小数点型限定。p1 != p2 で、a, b, c は一直線上にないこと
* @return std::optional<Vector<T, 3>> 交点 (平行 (平面に含まれる場合も含む) なら std::nullopt)
*/
template <typename T>
std::optional<Vector<T, 3>> line_plane_intersection(const Line<T, 3>& object, const Plane<T>& plane) {
const auto& [p1, p2] = object;
const auto& [a, b, c] = plane;
static_assert(std::is_floating_point_v<T>, "line_plane_intersection: T must be a floating point type");
assert(p1 != p2 && "line_plane_intersection: degenerate line");
const Vector<T, 3> n = cross(b - a, c - a), d = p2 - p1;
assert((n != Vector<T, 3>()) && "line_plane_intersection: degenerate plane");
const T den = dot(n, d);
if (den == 0) return std::nullopt;
// p1 + d t が平面上にある t
return p1 + d * (dot(n, a - p1) / den);
}
#line 10 "test/unittest/geometry/plane.test.cpp"
#line 13 "test/unittest/geometry/plane.test.cpp"
#include <iostream>
#include <random>
#include <vector>
#line 2 "src/geometry/polygon.hpp"
/**
* @file polygon.hpp
* @brief 多角形 (面積、重心、内外判定、凸性、凸包、凸多角形の切断)
*/
#include <algorithm>
#line 14 "src/geometry/polygon.hpp"
#line 16 "src/geometry/polygon.hpp"
/**
* @brief 多角形の符号付き面積の2倍
*
* @tparam T 座標の型
* @param polygon 頂点の座標
* @return T 面積の2倍(反時計回りなら正、時計回りなら負)
*/
template <typename T>
T polygon_area_doubled(const std::vector<Vector<T, 2>>& polygon) {
T ret = 0;
for (int i = 0; i < static_cast<int>(polygon.size()); i++) {
int j = i + 1;
if (j == static_cast<int>(polygon.size())) j = 0;
ret += cross(polygon[i], polygon[j]);
}
return ret;
}
/**
* @brief 多角形の面積
*
* @tparam T 座標の型
* @param polygon 頂点の座標(順番、反時計回りか時計回りかは問わない)
* @return double 面積
*/
template <typename T>
double polygon_area(const std::vector<Vector<T, 2>>& polygon) {
return std::abs(polygon_area_doubled(polygon)) / 2.;
}
/**
* @brief 多角形の面積と一次モーメント (polygon_edge_moment の戻り値)
* 辺ごとの値を足すと、多角形全体の値になる。+ と - があるので、CircularSum などの累積和に載せられる
*
* @tparam T 座標の型。整数型なら値は __int128_t で持つ (座標が 1e9 なら mx は 1e27 程度になる)
*/
template <typename T>
struct PolygonMoment {
using W = std::conditional_t<std::is_integral_v<T>, __int128_t, T>;
W area2 = 0; //!< 符号付き面積 S の 2 倍 (反時計回りなら正)
W mx = 0, my = 0; //!< 一次モーメントの 6 倍 (6S gx, 6S gy。(gx, gy) は重心)
PolygonMoment& operator+=(const PolygonMoment& rhs) {
area2 += rhs.area2, mx += rhs.mx, my += rhs.my;
return *this;
}
PolygonMoment& operator-=(const PolygonMoment& rhs) {
area2 -= rhs.area2, mx -= rhs.mx, my -= rhs.my;
return *this;
}
friend PolygonMoment operator+(PolygonMoment lhs, const PolygonMoment& rhs) { return lhs += rhs; }
friend PolygonMoment operator-(PolygonMoment lhs, const PolygonMoment& rhs) { return lhs -= rhs; }
friend bool operator==(const PolygonMoment& lhs, const PolygonMoment& rhs) {
return lhs.area2 == rhs.area2 && lhs.mx == rhs.mx && lhs.my == rhs.my;
}
friend bool operator!=(const PolygonMoment& lhs, const PolygonMoment& rhs) { return !(lhs == rhs); }
/**
* @brief 符号付き面積 (反時計回りなら正)
*/
double area() const { return static_cast<double>(area2) / 2; }
/**
* @brief 重心 (面積が 0 なら assert で落ちる)
*/
Vector<double, 2> centroid() const {
assert(area2 != 0 && "PolygonMoment::centroid: area must be nonzero");
const double a = static_cast<double>(area2) * 3;
return Vector<double, 2>(static_cast<double>(mx) / a, static_cast<double>(my) / a);
}
};
/**
* @brief 多角形の辺 p→q の寄与 (原点と p, q でできる三角形の面積と一次モーメント)
* 全辺の寄与の和が多角形の値になる。部分多角形のクエリは、寄与の累積和 (CircularSum など) で求められる
*
* @tparam T 座標の型
*/
template <typename T>
PolygonMoment<T> polygon_edge_moment(const Vector<T, 2>& p, const Vector<T, 2>& q) {
using W = typename PolygonMoment<T>::W;
const W c = static_cast<W>(p[0]) * q[1] - static_cast<W>(p[1]) * q[0];
return {c, (static_cast<W>(p[0]) + q[0]) * c, (static_cast<W>(p[1]) + q[1]) * c};
}
/**
* @brief 多角形 (の領域) の重心
*
* @tparam T 座標の型
* @param polygon 頂点の座標(順番、反時計回りか時計回りかは問わない。面積が 0 なら assert で落ちる)
* @return Vector<double, 2> 重心
*/
template <typename T>
Vector<double, 2> polygon_centroid(const std::vector<Vector<T, 2>>& polygon) {
const int n = static_cast<int>(polygon.size());
PolygonMoment<T> m;
for (int i = 0; i < n; i++) m += polygon_edge_moment(polygon[i], polygon[i + 1 == n ? 0 : i + 1]);
return m.centroid();
}
/**
* @brief 多角形の凸性判定
*
* @tparam T 座標の型
* @param polygon 頂点の座標(反時計回り)
* @return true 凸
* @return false 凹
*/
template <typename T>
bool polygon_is_convex(const std::vector<Vector<T, 2>>& polygon) {
int n = polygon.size();
for (int i = 0; i < n; i++) {
int j = i + 1;
if (j == n) j = 0;
int k = j + 1;
if (k == n) k = 0;
if (cross(polygon[j] - polygon[i], polygon[k] - polygon[j]) < 0) return false;
}
return true;
}
/**
* @brief 点の多角形内包含判定
*
* @tparam T 座標の型
* @param polygon 頂点の座標(反時計回り)
* @param p 点の座標
* @return int 0: 外部, 1: 辺上, 2: 内部
*/
template <typename T>
int polygon_contains(const std::vector<Vector<T, 2>>& polygon, const Vector<T, 2>& p) {
bool in = false;
for (int i = 0; i < static_cast<int>(polygon.size()); i++) {
int j = i + 1;
if (j == static_cast<int>(polygon.size())) j = 0;
Vector<T> v1 = polygon[i] - p, v2 = polygon[j] - p;
if (v1[1] > v2[1]) std::swap(v1, v2);
T c = cross(v1, v2);
if (v1[1] <= 0 && v2[1] > 0 && c < 0) in = !in;
if (c == 0 && dot(v1, v2) <= 0) return 1;
}
return in ? 2 : 0;
}
/**
* @brief 多角形の半凸包
* 与えられた頂点リストの順番を保って反時計回りに凸包を構成する
* xの昇順にソートされていれば下凸包、xの降順にソートされていれば上凸包が得られる
*
* @tparam T 座標の型
* @param points 頂点リスト
* @param include_straight 内角が180度の頂点を含むかどうか
* @return std::vector<Vector<T, 2>> 半凸包の頂点の座標(反時計回り)
*/
template <typename T>
std::vector<Vector<T, 2>> select_convex(const std::vector<Vector<T, 2>>& points, bool include_straight = false) {
std::vector<Vector<T, 2>> ret;
for (auto& p : points) {
while (static_cast<int>(ret.size()) >= 2) {
T c = cross(ret.back() - ret[static_cast<int>(ret.size()) - 2], p - ret.back());
if (c > 0 || (c == 0 && include_straight)) break;
ret.pop_back();
}
ret.push_back(p);
}
return ret;
}
/**
* @brief 多角形の凸包
*
* @tparam T 座標の型
* @param points 頂点リスト
* @param include_straight 内角が180度の頂点を含むかどうか
* @return std::vector<Vector<T, 2>> 凸包の頂点の座標(反時計回り)
*/
template <typename T>
std::vector<Vector<T, 2>> convex_hull(const std::vector<Vector<T, 2>>& _points, bool include_straight = false) {
std::vector<Vector<T, 2>> points = _points;
std::sort(points.begin(), points.end());
points.erase(std::unique(points.begin(), points.end()), points.end());
std::vector<Vector<T, 2>> ret = select_convex(points, include_straight);
std::reverse(points.begin(), points.end());
std::vector<Vector<T, 2>> tmp = select_convex(points, include_straight);
// 全点が一直線上にある場合、下側と上側が同じ点列になるので片方だけ使う
if (ret.size() == points.size() && tmp.size() == points.size()) return ret;
for (int i = 1; i < static_cast<int>(tmp.size()) - 1; i++) ret.push_back(tmp[i]);
return ret;
}
/**
* @brief 凸多角形を直線 p1p2 で切り、直線の左側 (p1 から p2 を見て左) の部分を返す。浮動小数点型限定
*
* @tparam T 座標の型
* @param polygon 凸多角形の頂点の座標 (反時計回り)
* @return std::vector<Vector<T, 2>> 左側の凸多角形の頂点 (反時計回り)。直線上の頂点も含む。左側に何もなければ空
*/
template <typename T>
std::vector<Vector<T, 2>> convex_cut(const std::vector<Vector<T, 2>>& polygon, const Vector<T, 2>& p1, const Vector<T, 2>& p2) {
static_assert(std::is_floating_point_v<T>, "convex_cut: T must be a floating point type");
assert(p1 != p2 && "convex_cut: degenerate line");
std::vector<Vector<T, 2>> res;
const int n = static_cast<int>(polygon.size());
for (int i = 0; i < n; i++) {
const Vector<T, 2>&a = polygon[i], &b = polygon[i + 1 == n ? 0 : i + 1];
T ca = cross(p2 - p1, a - p1), cb = cross(p2 - p1, b - p1);
if (ca >= 0) res.push_back(a);
// 辺 ab が直線をまたぐなら、交点を入れる
if ((ca > 0 && cb < 0) || (ca < 0 && cb > 0)) res.push_back(a + (b - a) * (ca / (ca - cb)));
}
return res;
}
#line 2 "src/geometry/triangle.hpp"
/**
* @file triangle.hpp
* @brief 2 次元・3 次元の三角形
*/
#line 10 "src/geometry/triangle.hpp"
#line 2 "src/geometry/segment.hpp"
/**
* @file segment.hpp
* @brief 2 次元・3 次元の線分 (交差判定、共有点、距離)
*/
#line 13 "src/geometry/segment.hpp"
#line 16 "src/geometry/segment.hpp"
/**
* @brief 2 端点で表す線分。長さ 0 も許す。等値比較では端点の順序を無視する
*/
template <typename T = long long, int Dim = 2>
struct Segment {
static_assert(Dim >= 2, "dimension must be at least 2");
Vector<T, Dim> p1, p2;
constexpr Segment() = default;
constexpr Segment(const Vector<T, Dim>& p1, const Vector<T, Dim>& p2) : p1(p1), p2(p2) {}
constexpr bool operator==(const Segment& other) const {
return (p1 == other.p1 && p2 == other.p2) || (p1 == other.p2 && p2 == other.p1);
}
constexpr bool operator!=(const Segment& other) const { return !(*this == other); }
};
template <typename T, int Dim>
Segment(const Vector<T, Dim>&, const Vector<T, Dim>&) -> Segment<T, Dim>;
/**
* @brief 線分の交差判定
*
* 整数型でも使える。外積を計算するため、座標の絶対値の2乗の数倍がTに収まる必要がある
*
* @param first 1 本目の線分
* @param second 2 本目の線分
* @tparam T 座標の型
* @return bool 共有点を持つか
*/
template <typename T>
constexpr bool segments_intersect(const Segment<T>& first, const Segment<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
assert(p1 != p2 && q1 != q2 && "segments_intersect: degenerate segment");
auto sign = [](T x) { return (x > 0) - (x < 0); };
int q1_section = sign(cross(p2 - p1, q1 - p1)); // 直線p1p2に対してq1がどの位置にあるか
int q2_section = sign(cross(p2 - p1, q2 - p1)); // 直線p1p2に対してq2がどの位置にあるか
int p1_section = sign(cross(q2 - q1, p1 - q1)); // 直線q1q2に対してp1がどの位置にあるか
int p2_section = sign(cross(q2 - q1, p2 - q1)); // 直線q1q2に対してp2がどの位置にあるか
if (q1_section == 0 && q2_section == 0) {
// 4点が同一直線上にある場合
return dot(q1 - p1, q2 - p1) <= 0 || dot(q1 - p2, q2 - p2) <= 0 || dot(p1 - q1, p2 - q1) <= 0;
}
return q1_section * q2_section <= 0 && p1_section * p2_section <= 0;
}
/**
* @brief 線分の交差判定と共有点の計算
*
* 共有点の座標は一般に整数にならないため、浮動小数点型限定
* 整数座標で交差判定だけしたい場合は segments_intersect を使う
*
* @param first 1 本目の線分
* @param second 2 本目の線分
* @tparam T 座標の型
* @return std::optional<Vector<T, 2>> 共有点の1例 (共有点がなければ std::nullopt)
*/
template <typename T>
constexpr std::optional<Vector<T, 2>> segment_intersection(const Segment<T>& first, const Segment<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
static_assert(std::is_floating_point_v<T>, "segment_intersection: T must be a floating point type (use segments_intersect for integers)");
if (!segments_intersect(first, second)) return std::nullopt;
if (cross(p2 - p1, q1 - p1) == 0 && cross(p2 - p1, q2 - p1) == 0) {
// 4点が同一直線上にある場合
if (dot(q1 - p1, q2 - p1) <= 0) return p1;
if (dot(q1 - p2, q2 - p2) <= 0) return p2;
return q1;
}
T area = cross(p2 - p1, q2 - q1); // 4点を頂点とする四角形の符号付き面積
T partial_area = cross(q2 - q1, p1 - q1); // 三角形q1q2p1の符号付き面積
return p1 + (p2 - p1) * partial_area / area;
}
/**
* @brief 点 p と線分 p1p2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_point_segment(const Segment<T>& object, const Vector<T, 2>& p) {
const auto& [p1, p2] = object;
if (p1 == p2) return (p - p1).abs();
// 垂線の足が線分の外なら、近い方の端点との距離
if (dot(p2 - p1, p - p1) < 0) return (p - p1).abs();
if (dot(p1 - p2, p - p2) < 0) return (p - p2).abs();
return distance_point_line(Line(p1, p2), p);
}
/**
* @brief 線分 p1p2 と線分 q1q2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_segments(const Segment<T>& first, const Segment<T>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
if (p1 != p2 && q1 != q2 && segments_intersect(first, second)) return 0;
return std::min({distance_point_segment(first, q1), distance_point_segment(first, q2),
distance_point_segment(second, p1), distance_point_segment(second, p2)});
}
/**
* @brief 点 p と線分 p1p2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_point_segment(const Segment<T, 3>& object, const Vector<T, 3>& p) {
const auto& [p1, p2] = object;
using namespace internal_predicates;
if (p1 == p2) return norm(p - p1);
// 垂線の足が線分の外なら、近い方の端点との距離
if (dot(widen(p2) - widen(p1), widen(p) - widen(p1)) < 0) return norm(p - p1);
if (dot(widen(p1) - widen(p2), widen(p) - widen(p2)) < 0) return norm(p - p2);
return distance_point_line(Line(p1, p2), p);
}
/**
* @brief 線分 p1p2 と線分 q1q2 の距離 (整数型でも使える)
*/
template <typename T>
double distance_segments(const Segment<T, 3>& first, const Segment<T, 3>& second) {
const auto& [p1, p2] = first;
const auto& [q1, q2] = second;
double res = std::min({distance_point_segment(first, q1), distance_point_segment(first, q2),
distance_point_segment(second, p1), distance_point_segment(second, p2)});
if (p1 == p2 || q1 == q2) return res;
// 距離の 2 乗は (s, t) ∈ [0, 1]^2 で凸なので、最小は内部の停留点か境界 (端点と線分の距離) にある
using L = long double;
auto to = [](const Vector<T, 3>& v) { return Vector<L, 3>(v[0], v[1], v[2]); };
const Vector<L, 3> d = to(p2) - to(p1), e = to(q2) - to(q1), r = to(p1) - to(q1);
const L a = dot(d, d), b = dot(d, e), c = dot(e, e), f = dot(d, r), g = dot(e, r);
const L den = a * c - b * b;
if (den > 0) {
// p1 + d s と q1 + e t が最も近い s, t
const L s = (b * g - c * f) / den, t = (a * g - b * f) / den;
if (0 <= s && s <= 1 && 0 <= t && t <= 1) res = std::min(res, static_cast<double>((r + d * s - e * t).abs()));
}
return res;
}
#line 14 "src/geometry/triangle.hpp"
/**
* @brief 一直線上にない 3 頂点で表す三角形。等値比較では頂点の順序を無視する
* @tparam T 座標の型。省略したら long long
* @tparam Dim 次元 (2 または 3)。省略したら 2
*/
template <typename T = long long, int Dim = 2>
struct Triangle {
static_assert(Dim == 2 || Dim == 3, "Triangle: dimension must be 2 or 3");
Vector<T, Dim> p1, p2, p3;
private:
constexpr void assert_valid() const {
using internal_predicates::widen;
const auto a = widen(p1), u = widen(p2) - a, v = widen(p3) - a;
if constexpr (Dim == 2) {
assert(cross(u, v) != 0 && "Triangle: collinear vertices");
} else {
const auto n = cross(u, v);
assert((n[0] != 0 || n[1] != 0 || n[2] != 0) && "Triangle: collinear vertices");
}
}
public:
constexpr Triangle(const Vector<T, Dim>& p1, const Vector<T, Dim>& p2, const Vector<T, Dim>& p3) : p1(p1), p2(p2), p3(p3) {
assert_valid();
}
constexpr bool operator==(const Triangle& other) const {
assert_valid();
other.assert_valid();
auto has_vertex = [&](const Vector<T, Dim>& p) { return p == other.p1 || p == other.p2 || p == other.p3; };
return has_vertex(p1) && has_vertex(p2) && has_vertex(p3);
}
constexpr bool operator!=(const Triangle& other) const { return !(*this == other); }
};
template <typename T, int Dim>
Triangle(const Vector<T, Dim>&, const Vector<T, Dim>&, const Vector<T, Dim>&) -> Triangle<T, Dim>;
/**
* @brief 線分 p1p2 と三角形 abc (周を含む) が共有点を持つか (整数型でも使える。整数座標なら正確)
* 三角形は退化していない (a, b, c が一直線上にない) こと
*/
template <typename T>
bool segment_triangle_intersect(const Segment<T, 3>& object, const Triangle<T, 3>& triangle) {
const auto& [p1, p2] = object;
const auto& [a, b, c] = triangle;
using internal_predicates::orient;
using internal_predicates::widen;
const auto n = cross(widen(b) - widen(a), widen(c) - widen(a));
assert(n != decltype(n)() && "segment_triangle_intersect: degenerate triangle");
const int s1 = orient(a, b, c, p1), s2 = orient(a, b, c, p2);
if (s1 * s2 > 0) return false;
if (s1 != 0 || s2 != 0) {
// 線分が平面を貫くか片方の端点が平面上にある。直線 p1p2 から見て、3 辺が同じ向きに回っていれば三角形を通る
const int o1 = orient(p1, p2, a, b), o2 = orient(p1, p2, b, c), o3 = orient(p1, p2, c, a);
return !((o1 < 0 || o2 < 0 || o3 < 0) && (o1 > 0 || o2 > 0 || o3 > 0));
}
// 同じ平面上: 法線の成分が最も大きい軸を落として 2 次元で判定する
int k = 0;
for (int i = 1; i < 3; i++) {
if ((n[i] < 0 ? -n[i] : n[i]) > (n[k] < 0 ? -n[k] : n[k])) k = i;
}
const int i0 = k == 0 ? 1 : 0, i1 = k == 2 ? 1 : 2;
auto flat = [&](const Vector<T, 3>& p) { return Vector<T, 2>(p[i0], p[i1]); };
const Vector<T, 2> q1 = flat(p1), q2 = flat(p2), ta = flat(a), tb = flat(b), tc = flat(c);
// 端点 q1 が三角形の内部 (周を含む) にあるか、線分が辺と交わる (q1 が外で q2 が内なら辺と交わる)
// 3 辺から見た向きが混ざらなければ内部。辺の延長上 (ccw が ±2) の点は、残りの 2 辺で向きが逆になる
bool pos = false, neg = false;
for (int o : {ccw(ta, tb, q1), ccw(tb, tc, q1), ccw(tc, ta, q1)}) pos |= o == 1, neg |= o == -1;
if (!(pos && neg)) return true;
if (q1 == q2) return false;
return segments_intersect(Segment(q1, q2), Segment(ta, tb)) || segments_intersect(Segment(q1, q2), Segment(tb, tc)) || segments_intersect(Segment(q1, q2), Segment(tc, ta));
}
#line 20 "test/unittest/geometry/plane.test.cpp"
using P = Vector<long long, 3>;
constexpr Plane horizontal(P(0, 0, 0), P(1, 0, 0), P(0, 1, 0));
static_assert(std::is_same_v<std::decay_t<decltype(horizontal)>, Plane<long long>>);
static_assert(horizontal == Plane(P(3, 4, 0), P(3, 5, 0), P(4, 4, 0)));
static_assert(horizontal != Plane(P(0, 0, 1), P(1, 0, 1), P(0, 1, 1)));
static_assert(horizontal != Plane(P(0, 0, 0), P(1, 0, 0), P(0, 0, 1)));
static_assert(is_parallel(horizontal, Plane(P(0, 0, 1), P(0, 1, 1), P(1, 0, 1))));
static_assert(!is_parallel(horizontal, Plane(P(0, 0, 0), P(1, 0, 0), P(0, 0, 1))));
static_assert(horizontal.contains(P(3, -4, 0)));
static_assert(!horizontal.contains(P(3, -4, 1)));
using D = Vector<double, 3>;
using L = long double;
bool ok = true;
void check(bool cond, const char* what) {
if (!cond) {
if (ok) std::cerr << "failed: " << what << std::endl;
ok = false;
}
}
bool near(double a, double b) { return std::abs(a - b) <= 1e-6 * std::max(1.0, std::abs(b)); }
// [lo, hi] で凸な関数の最小値
L minimize(const std::function<L(L)>& f, L lo, L hi) {
for (int i = 0; i < 80; i++) {
L m1 = (2 * lo + hi) / 3, m2 = (lo + 2 * hi) / 3;
if (f(m1) < f(m2))
hi = m2;
else
lo = m1;
}
return f((lo + hi) / 2);
}
Vector<L, 3> at(const P& p, const P& q, L t) { return Vector<L, 3>(p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t, p[2] + (q[2] - p[2]) * t); }
L dist(const Vector<L, 3>& a, const Vector<L, 3>& b) {
L s = 0;
for (int i = 0; i < 3; i++) s += (a[i] - b[i]) * (a[i] - b[i]);
return std::sqrt(s);
}
Vector<L, 3> to_l(const P& p) { return Vector<L, 3>(p[0], p[1], p[2]); }
// 平面を貫く場合の愚直な判定: 交点を p1 * den + (p2 - p1) * num (の 1/den) として正確に求める
__int128_t vol(const P& a, const P& b, const P& c, const P& d) {
__int128_t m[3][3];
for (int i = 0; i < 3; i++) m[0][i] = b[i] - a[i], m[1][i] = c[i] - a[i], m[2][i] = d[i] - a[i];
return m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
}
bool naive_crossing(const P& p1, const P& p2, const P& a, const P& b, const P& c) {
__int128_t v1 = vol(a, b, c, p1), v2 = vol(a, b, c, p2);
if ((v1 > 0 && v2 > 0) || (v1 < 0 && v2 < 0)) return false;
// 交点は p1 + (p2 - p1) * v1 / (v1 - v2)。den 倍した座標で三角形の内外を調べる
__int128_t num = v1, den = v1 - v2;
if (den < 0) num = -num, den = -den;
using W = Vector<__int128_t, 3>;
auto scale = [&](const P& p) { return W(p[0] * den, p[1] * den, p[2] * den); };
W q(p1[0] * den + (p2[0] - p1[0]) * num, p1[1] * den + (p2[1] - p1[1]) * num, p1[2] * den + (p2[2] - p1[2]) * num);
W A = scale(a), B = scale(b), C = scale(c);
W n = cross(B - A, C - A);
__int128_t x = dot(n, cross(B - A, q - A)), y = dot(n, cross(C - B, q - B)), z = dot(n, cross(A - C, q - C));
return x >= 0 && y >= 0 && z >= 0;
}
int main() {
std::mt19937 rng(314);
auto rnd = [&](int w) { return static_cast<long long>(rng() % (2 * w + 1)) - w; };
auto rp = [&](int w) { return P(rnd(w), rnd(w), rnd(w)); };
for (int rep = 0; rep < 400 && ok; rep++) {
const int w = rng() % 2 ? 3 : 100;
P p1 = rp(w), p2 = rp(w), q1 = rp(w), q2 = rp(w), p = rp(w);
if (rng() % 4 == 0) q2 = q1 + (p2 - p1) * (rng() % 3); // 平行
// 点と線分・直線
{
L e = minimize([&](L t) { return dist(at(p1, p2, t), to_l(p)); }, 0, 1);
check(near(distance_point_segment(Segment(p1, p2), p), e), "distance_point_segment");
if (p1 != p2) {
L f = minimize([&](L t) { return dist(at(p1, p2, t), to_l(p)); }, -1000, 1000);
check(near(distance_point_line(Line(p1, p2), p), f), "distance_point_line");
}
}
// 線分どうし: s を外側、t を内側で三分探索する (距離は (s, t) について凸)
{
L e = minimize([&](L s) { return minimize([&](L t) { return dist(at(p1, p2, s), at(q1, q2, t)); }, 0, 1); }, 0, 1);
check(near(distance_segments(Segment(p1, p2), Segment(q1, q2)), e), "distance_segments");
}
// 直線どうし
if (p1 != p2 && q1 != q2) {
L e = minimize([&](L s) { return minimize([&](L t) { return dist(at(p1, p2, s), at(q1, q2, t)); }, -1000, 1000); }, -1000, 1000);
check(near(distance_lines(Line(p1, p2), Line(q1, q2)), e), "distance_lines");
}
// 点と平面、直線と平面
{
P a = rp(w), b = rp(w), c = rp(w);
if (cross(b - a, c - a) == P()) continue;
const Plane plane(a, b, c);
const Plane same(a + (b - a) * 2, a + (c - a) * 3, a - (b - a) - (c - a));
check(plane == same && same == plane && plane == Plane(c, b, a), "Plane equality");
P normal = cross(b - a, c - a);
check(plane.contains(a) && plane.contains(b) && plane.contains(c), "Plane contains defining points");
check(plane.contains(a + (b - a) * 3 - (c - a) * 2), "Plane contains affine combination");
check(!plane.contains(a + normal) && !plane.contains(a - normal), "Plane excludes points off plane");
check(plane.contains(Line(a, b)) && plane.contains(Line(c, c + b - a)), "Plane contains line");
check(plane.contains(Line(b, a)), "Plane contains reversed line");
check(!plane.contains(Line(a + normal, b + normal)), "Plane excludes parallel line");
check(!plane.contains(Line(a, a + normal)) && !plane.contains(Line(a + normal, a)), "Plane excludes crossing line");
const Plane shifted(a + normal, b + normal, c + normal);
check(is_parallel(plane, same) && is_parallel(plane, shifted) && is_parallel(shifted, plane), "parallel planes");
check(is_parallel(Line(a, b), plane) && is_parallel(plane, Line(c + normal, c + normal + b - a)), "parallel line and plane");
check(!is_parallel(Line(a, a + normal), plane) && !is_parallel(plane, Line(a, a + normal)), "line crossing plane");
check(is_parallel(Line(a, b), Line(c, c - (b - a) * 3)), "parallel lines");
check(!is_parallel(Line(a, b), Line(a, c)), "nonparallel lines");
check(plane != Plane(a + normal, b + normal, c + normal), "Plane parallel and distinct");
L e = minimize([&](L s) { return minimize([&](L t) {
Vector<L, 3> x = to_l(a) + (to_l(b) - to_l(a)) * s + (to_l(c) - to_l(a)) * t;
return dist(x, to_l(p));
},
-1000, 1000); },
-1000, 1000);
check(near(distance_point_plane(Plane(a, b, c), p), e), "distance_point_plane");
if (p1 == p2) continue;
auto to_d = [](const P& v) { return D(v[0], v[1], v[2]); };
auto x = line_plane_intersection(Line(to_d(p1), to_d(p2)), Plane(to_d(a), to_d(b), to_d(c)));
const bool parallel = dot(cross(b - a, c - a), p2 - p1) == 0;
check(is_parallel(Line(p1, p2), plane) == parallel, "is_parallel and intersection");
check(x.has_value() != parallel, "line_plane_intersection (平行)");
if (x) {
check(distance_point_plane(Plane(to_d(a), to_d(b), to_d(c)), *x) < 1e-6, "line_plane_intersection (平面上)");
check(distance_point_line(Line(to_d(p1), to_d(p2)), *x) < 1e-6, "line_plane_intersection (直線上)");
}
}
}
// 線分と三角形: 平面を貫く (または端点が平面上にある) 場合
for (int rep = 0; rep < 200000 && ok; rep++) {
const int w = rng() % 2 ? 2 : 5;
P p1 = rp(w), p2 = rp(w), a = rp(w), b = rp(w), c = rp(w);
if (cross(b - a, c - a) == P()) continue;
if (vol(a, b, c, p1) == 0 && vol(a, b, c, p2) == 0) continue;
check(segment_triangle_intersect(Segment(p1, p2), Triangle(a, b, c)) == naive_crossing(p1, p2, a, b, c), "segment_triangle_intersect (貫く)");
}
// 同じ平面上の場合: z = 0 で 2 次元の判定をして、行列式 ±1 の行列と平行移動で空間に移す
for (int rep = 0; rep < 100000 && ok; rep++) {
const int w = rng() % 2 ? 2 : 6;
using V2 = Vector<long long, 2>;
auto r2 = [&]() { return V2(rnd(w), rnd(w)); };
V2 p1 = r2(), p2 = r2(), a = r2(), b = r2(), c = r2();
if (cross(b - a, c - a) == 0) continue;
std::vector<V2> tri = {a, b, c};
if (cross(b - a, c - a) < 0) tri = {a, c, b};
bool expect = polygon_contains(tri, p1) > 0 || polygon_contains(tri, p2) > 0;
if (p1 != p2) expect = expect || segments_intersect(Segment(p1, p2), Segment(a, b)) || segments_intersect(Segment(p1, p2), Segment(b, c)) || segments_intersect(Segment(p1, p2), Segment(c, a));
// 基本変形 (ある行に別の行の整数倍を足す) を何回か掛けた行列
long long m[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
for (int k = 0; k < 4; k++) {
int i = rng() % 3, j = (i + 1 + rng() % 2) % 3;
long long f = rnd(2);
for (int col = 0; col < 3; col++) m[i][col] += f * m[j][col];
}
P shift = rp(10);
auto lift = [&](const V2& v) {
P r;
for (int i = 0; i < 3; i++) r[i] = m[i][0] * v[0] + m[i][1] * v[1] + shift[i];
return r;
};
check(segment_triangle_intersect(Segment(lift(p1), lift(p2)), Triangle(lift(a), lift(b), lift(c))) == expect, "segment_triangle_intersect (同じ平面上)");
}
// 3 次元の型推論と、同じ直線・線分の判定。ねじれの位置も区別する
{
Line line(P(0, 0, 0), P(1, 2, 3));
static_assert(std::is_same_v<decltype(line), Line<long long, 3>>);
Segment segment(P(0, 0, 0), P(1, 2, 3));
static_assert(std::is_same_v<decltype(segment), Segment<long long, 3>>);
check(line == Line(P(3, 6, 9), P(-2, -4, -6)), "Line equality");
check(line != Line(P(0, 0, 1), P(1, 2, 4)), "Line parallel and distinct");
check(line != Line(P(0, 1, 0), P(1, 1, 0)), "Line skew");
check(segment == Segment(P(1, 2, 3), P(0, 0, 0)), "Segment equality");
check(segment != Segment(P(0, 0, 0), P(2, 4, 6)), "Segment distinct");
}
// 座標が 1e9 でも体積の計算があふれない
const long long G = 1000000000;
const Plane large(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0));
check(large == Plane(P(0, 0, 0), P(G, G, 0), P(-G, G, 0)), "Plane equality (1e9)");
check(large != Plane(P(-G, -G, G), P(G, -G, G), P(0, G, G)), "Plane distinct (1e9)");
const Plane large_shifted(P(-G, -G, G), P(0, G, G), P(G, -G, G));
check(is_parallel(large, large_shifted), "parallel planes (1e9)");
check(is_parallel(Line(P(-G, G, G), P(G, G, G)), large), "parallel line and plane (1e9)");
check(!is_parallel(Line(P(-G, -G, -G), P(G, G, G)), large), "nonparallel line and plane (1e9)");
check(is_parallel(Line(P(-G, -G, -G), P(G, G, G)), Line(P(G, G, G), P(0, 0, 0))), "parallel lines (1e9)");
check(near(distance_point_plane(large, P(G, G, G)), G), "distance_point_plane (1e9)");
check(large.contains(P(G, G, 0)) && !large.contains(P(G, G, G)), "Plane contains point (1e9)");
check(large.contains(Line(P(-G, G, 0), P(G, G, 0))), "Plane contains line (1e9)");
check(!large.contains(Line(P(-G, G, G), P(G, G, G))), "Plane excludes line (1e9)");
const Plane floating(D(0, 0, 0.5), D(1, 0, 0.5), D(0, 1, 0.5));
static_assert(std::is_same_v<std::decay_t<decltype(floating)>, Plane<double>>);
check(floating == Plane(D(2, 3, 0.5), D(3, 3, 0.5), D(2, 4, 0.5)), "Plane equality (double)");
check(floating.contains(D(2, -3, 0.5)) && !floating.contains(D(2, -3, 0.500001)), "Plane contains point (double)");
check(floating.contains(Line(D(1, 2, 0.5), D(3, 4, 0.5))), "Plane contains line (double)");
check(!floating.contains(Line(D(1, 2, 1.5), D(3, 4, 1.5))), "Plane excludes line (double)");
check(!line_plane_intersection(Line(D(0, 0, 0.5), D(1, 0, 0.5)), floating), "line contained in plane");
check(!line_plane_intersection(Line(D(0, 0, 1.5), D(1, 0, 1.5)), floating), "line parallel to plane");
check(is_parallel(floating, floating) && is_parallel(Line(D(0, 0, 1.5), D(1, 0, 1.5)), floating), "parallel (double)");
check(!is_parallel(floating, Line(D(0, 0, 0), D(0, 0, 1))), "nonparallel (double)");
check(segment_triangle_intersect(Segment(P(0, 0, -G), P(0, 0, G)), Triangle(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0))), "segment_triangle_intersect (1e9)");
check(!segment_triangle_intersect(Segment(P(G, G, -G), P(G, G, G)), Triangle(P(-G, -G, 0), P(G, -G, 0), P(0, G, 0))), "segment_triangle_intersect (1e9, 外)");
check(near(distance_point_line(Line(P(-G, -G, -G), P(G, G, G)), P(G, -G, 0)), std::sqrt(2.0) * G), "distance_point_line (1e9)");
if (ok) std::cout << "Hello World" << std::endl;
}