plane.h 982 Bytes
Newer Older
TheNumbat's avatar
TheNumbat committed
1
2
3
4

#pragma once

#include <algorithm>
TheNumbat's avatar
TheNumbat committed
5
#include <cmath>
TheNumbat's avatar
TheNumbat committed
6
7
8
9
10
11
12
#include <ostream>

#include "line.h"
#include "vec4.h"

struct Plane {

TheNumbat's avatar
TheNumbat committed
13
14
    Plane() = default;

TheNumbat's avatar
TheNumbat committed
15
    /// Create plane from (a,b,c,d)
TheNumbat's avatar
TheNumbat committed
16
    explicit Plane(Vec4 p) : p(p) {}
TheNumbat's avatar
TheNumbat committed
17
18
19
20
21
22
23
24
    /// Create plane from point and unit normal
    explicit Plane(Vec3 point, Vec3 n) {
        p.x = n.x;
        p.y = n.y;
        p.z = n.z;
        p.w = dot(point, n.unit());
    }

TheNumbat's avatar
TheNumbat committed
25
26
27
    Plane(const Plane &) = default;
    Plane &operator=(const Plane &) = default;
    ~Plane() = default;
TheNumbat's avatar
TheNumbat committed
28
29
30

    /// Calculate intersection point between plane and line.
    /// Returns false if the hit point is 'backward' along the line relative to pt.dir
TheNumbat's avatar
TheNumbat committed
31
    bool hit(Line line, Vec3 &pt) const {
TheNumbat's avatar
TheNumbat committed
32
33
34
35
36
37
38
39
40
        Vec3 n = p.xyz();
        float t = (p.w - dot(line.point, n)) / dot(line.dir, n);
        pt = line.at(t);
        return t >= 0.0f;
    }

    Vec4 p;
};

TheNumbat's avatar
TheNumbat committed
41
42
43
inline std::ostream &operator<<(std::ostream &out, Plane v) {
    out << "Plane" << v.p;
    return out;
TheNumbat's avatar
TheNumbat committed
44
}