shogo-library

競技プログラミング用の C++ ライブラリ

View the Project on GitHub shogo314/shogo-library

:heavy_check_mark: 平面 (包含・平行判定、距離、直線との交点)
(src/geometry/plane.hpp)

平面上の一直線上にない 3 点 p1, p2, p3 を持つ Plane<T> と、平面の関数です。T の既定は long long で、3 点から座標型を推論します。

using P = Vector<long long, 3>;
Plane plane(P(0, 0, 0), P(1, 0, 0), P(0, 1, 0));
Plane other(P(2, 3, 0), P(2, 4, 0), P(3, 3, 0));
bool same = plane == other;  // true
bool on = plane.contains(P(2, 3, 0));  // true
bool inside = plane.contains(Line(P(0, 0, 0), P(1, 1, 0)));  // true
Line outside(P(0, 0, 1), P(1, 0, 1));
bool parallel = is_parallel(outside, plane);  // true
bool contained = plane.contains(outside);    // false
using D = Vector<double, 3>;
auto x = line_plane_intersection(Line(D(0, 0, 5), D(1, 1, 4)), Plane(D(0, 0, 0), D(1, 0, 0), D(0, 1, 0)));  // (5, 5, 0)

係数への変換・正規化はしません。法線は cross(p2 - p1, p3 - p1) です。3 点が一直線上にある場合 (重複した点を含む場合も含む) は assert で落ちます。公開メンバを変更するときもこの条件を保ってください。

整数座標の外積・体積は __int128_t で計算し、座標の絶対値が $10^9$ 程度まで使えます。浮動小数点型の判定では誤差を考慮しません。

メンバ関数

関数 説明 計算量
Plane<T>(p1, p2, p3) 3 点を通る平面を作る $O(1)$
contains(p) 点 p (Vector<T, 3>) が平面上にあるか $O(1)$
contains(line) Line<T, 3> 全体が平面内にあるか。平行でも平面外なら false $O(1)$
a == b / a != b 同じ平面か / 異なる平面か。点の選び方・順序・法線の向きによらない $O(1)$

関数

関数 説明 計算量
is_parallel(line, plane) / is_parallel(plane, line) 直線と平面が平行か。直線が平面内にある場合も true $O(1)$
is_parallel(a, b) (Plane<T> 同士) 平面が平行か。一致する場合も true $O(1)$
distance_point_plane(plane, p) 点と平面の距離 (double)。整数型でも使える $O(1)$
line_plane_intersection(line, plane) 交点を std::optional<Vector<T, 3>> で返す。平行 (平面に含まれる場合も含む) なら std::nullopt。浮動小数点型のみ $O(1)$

line は異なる 2 点で表した Line<T, 3> を渡します。

メンバ変数

変数 説明
p1 / p2 / p3 平面上の一直線上にない 3 点 (Vector<T, 3>)

関連

Depends on

Verified with

Code

#pragma once

/**
 * @file plane.hpp
 * @brief 平面 (包含・平行判定、距離、直線との交点)
 */

#include <cassert>
#include <cmath>
#include <optional>
#include <type_traits>

#include "internal/predicates.hpp"
#include "line.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 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);
}
Back to top page