aboutsummaryrefslogtreecommitdiffstats
path: root/include/components/solid.hpp
blob: 87d18e3eada9a5ce50f80a7544d7b0d740757585 (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
#ifndef COMPONENTS_SOLID_HPP
#define COMPONENTS_SOLID_HPP

#include "components/point.hpp"
#include "window.hpp"

#include <algorithm>
#include <cstdint>
#include <string>

class Solid {
public:
    Solid(std::string path) {
        bitmap = sdl2LoadSolid(path.c_str());
    }

    ~Solid() {
        if (bitmap != nullptr)
            SDL_FreeSurface(bitmap);
    }

    float collision(Vec2 p) const noexcept {
        float dy = 0.f;

        if (at(p)) {
            auto up = p;
            while (up.y > 0 && at(up))
                up.y--;

            auto down = p;
            while (down.y < bitmap->h && at(down))
                down.y++;

            if (down.y - p.y > p.y - up.y)
                dy = -(p.y - up.y);
            else
                dy = down.y - p.y;
        }

        return dy;
    }

private:
    SDL_Surface *bitmap;

    bool at(Vec2 p) const noexcept {
        const auto bm = reinterpret_cast<std::uint8_t *>(bitmap->pixels);
        const int x = std::clamp(static_cast<int>(p.x), 0, bitmap->w);
        const int y = std::clamp(static_cast<int>(p.y), 0, bitmap->h);
        const int i = y * bitmap->w + x;
        const auto val = bm[i * bitmap->format->BytesPerPixel];
        return val > 0;
    }
};

#endif // COMPONENTS_SOLID_HPP