aboutsummaryrefslogtreecommitdiff
path: root/src/common.hpp
blob: d35d1bca267cd68fb849ae02cc14acd13156b6e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#pragma once

// clang-format off
#define MSG_INFO  "[INFO] "
#define MSG_WARN  "[WARN] "
#define MSG_ERROR "[ERRO] "
// clang-format on

struct Pt {
    int x{}, y{};

    Pt operator+(Pt o) const { return { x + o.x, y + o.y }; }
    Pt operator-(Pt o) const { return { x - o.x, y - o.y }; }
    Pt operator*(int k) const { return { x * k, y * k }; }
    Pt operator/(int k) const { return { x / k, y / k }; }
    Pt& operator+=(Pt o) {
        x += o.x;
        y += o.y;
        return *this;
    }
    Pt& operator-=(Pt o) {
        x -= o.x;
        y -= o.y;
        return *this;
    }
    Pt& operator*=(Pt o) {
        x *= o.x;
        y *= o.y;
        return *this;
    }
    Pt& operator/=(Pt o) {
        x /= o.x;
        y /= o.y;
        return *this;
    }
    bool operator==(const Pt&) const = default;
};

// avoid including <algorithm>
#define MMIN(x, y) ((x) < (y) ? (x) : (y))
#define MMAX(x, y) ((x) > (y) ? (x) : (y))
inline Pt pt_min(Pt a, Pt b) {
    return Pt{ MMIN(a.x, b.x), MMIN(a.y, b.y) };
}
inline Pt pt_max(Pt a, Pt b) {
    return Pt{ MMAX(a.x, b.x), MMAX(a.y, b.y) };
}

struct Rect {
    Pt bl, tr;

    Rect() {}
    Rect(Pt tl, Pt br)
        : bl(tl), tr(br) {}
    Rect(int x0, int y0, int x1, int y1)
        : bl(x0, y0), tr(x1, y1) {}

    bool operator==(const Rect&) const = default;
};

inline Rect rect_union(Rect a, Rect b) {
    return Rect(pt_min(a.bl, b.bl), pt_max(a.tr, b.tr));
}
inline Rect rect_union(Rect a, Pt b) {
    return Rect(pt_min(a.bl, b), pt_max(a.tr, b));
}
inline Rect rect_intersect(Rect a, Rect b) {
    // https://stackoverflow.com/a/19754915
    int x0 = MMAX(a.bl.x, b.bl.x);
    int y0 = MMAX(a.bl.y, b.bl.y);
    int x1 = MMIN(a.tr.x, b.tr.x);
    int y1 = MMIN(a.tr.y, b.tr.y);
    return Rect(x0, y0, x1, y1);
}
#undef MMIN
#undef MMAX