summaryrefslogtreecommitdiffhomepage
path: root/editor/tests/raycast-test.cpp
blob: 50e060631357da35b015fa7ca799cac9aed9d064 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#include "../tests-private.hpp"
#include "editor/app.hpp"
#include "floormat/main.hpp"
#include "compat/shared-ptr-wrapper.hpp"
#include "src/critter.hpp"
#include "../imgui-raii.hpp"
#include <memory>
#include <array>
#include <vector>
#include <Magnum/Math/Functions.h>
#include <Magnum/Math/Vector2.h>

namespace floormat::tests {

namespace {

using namespace imgui;

struct aabb_result
{
    Vector2 ts;
    bool result;
};

template<typename T>
requires std::is_arithmetic_v<T>
std::array<uint8_t, 2> ray_aabb_signs(Math::Vector2<T> ray_dir_inv_norm)
{
    bool signs[2];
    for (unsigned d = 0; d < 2; ++d)
        signs[d] = std::signbit(ray_dir_inv_norm[d]);
    return { signs[0], signs[1] };
}

// https://tavianator.com/2022/ray_box_boundary.html
// https://www.researchgate.net/figure/The-slab-method-for-ray-intersection-detection-15_fig3_283515372
aabb_result ray_aabb_intersection(Vector2 ray_origin, Vector2 ray_dir_inv_norm,
                                  std::array<Vector2, 2> box_minmax, std::array<uint8_t, 2> signs)
{
    using Math::min;
    using Math::max;

    float ts[2];
    float tmin = 0, tmax = 16777216;

    for (unsigned d = 0; d < 2; ++d)
    {
        float bmin = box_minmax[signs[d]][d];
        float bmax = box_minmax[!signs[d]][d];

        float dmin = (bmin - ray_origin[d]) * ray_dir_inv_norm[d];
        float dmax = (bmax - ray_origin[d]) * ray_dir_inv_norm[d];

        ts[d] = dmin;
        tmin = max(dmin, tmin);
        tmax = min(dmax, tmax);
    }

    return { {ts[0], ts[1] }, tmin < tmax };
}

struct bbox
{
    point center;
    Vector2ui size;
};

struct result_s
{
    point from, to;
    Vector3d vec;
    std::vector<bbox> path;
    bool has_result : 1 = false;
};

struct pending_s
{
    point from, to;
    bool exists : 1 = false;
};

} // namespace

struct raycast_test : base_test
{
    result_s result;
    pending_s pending;

    ~raycast_test() noexcept override;

    bool handle_key(app& a, const key_event& e, bool is_down) override
    {
        return false;
    }

    bool handle_mouse_click(app& a, const mouse_button_event& e, bool is_down) override
    {
        if (e.button == mouse_button_left && is_down)
        {
            auto& M = a.main();
            auto& w = M.world();
            if (auto pt_ = a.cursor_state().point())
            {
                auto C = a.ensure_player_character(w).ptr;
                auto pt0 = C->position();
                pending = { .from = pt0, .to = *pt_, .exists = true, };
                return true;
            }
        }

        return false;
    }

    bool handle_mouse_move(app& a, const mouse_move_event& e) override
    {
        return false;
    }

    void draw_overlay(app& a) override
    {
        if (!result.has_result)
            return;

        const auto color = ImGui::ColorConvertFloat4ToU32({1, 0, 0, 1});
        ImDrawList& draw = *ImGui::GetForegroundDrawList();

        for (const auto& p : result.path)
        {
            auto p0 = object::normalize_coords(p.center, -Vector2i(p.size/2));
            auto p1 = object::normalize_coords(p.center, Vector2i(p.size));
            auto r0 = a.point_screen_pos(p0), r1 = a.point_screen_pos(p1);
            draw.AddRect({r0.x(), r0.y()}, {r1.x(), r1.y()}, color);
        }
    }

    void draw_ui(app& a, float width) override
    {

    }

    void update_pre(app& a) override
    {

    }

    void update_post(app& a) override
    {
        if (pending.exists)
        {
            pending.exists = false;
            if (pending.from.chunk3().z != pending.to.chunk3().z)
            {
                fm_warn("raycast: wrong Z value");
                return;
            }
            if (pending.from == pending.to)
            {
                fm_warn("raycast: from == to");
                return;
            }

            do_raycasting(a, pending.from, pending.to);
        }
    }

    void do_raycasting(app& a, point from, point to)
    {
        constexpr auto inv_tile_size = 1. / Vector2d(iTILE_SIZE2);
        constexpr auto chunk_size = Vector2d{TILE_MAX_DIM};
        constexpr double eps = 1e-6;
        constexpr double inv_eps = 1/eps;
        constexpr double sqrt_2 = Math::sqrt(2.);
        constexpr double inv_sqrt_2 = 1. / sqrt_2;

        result.has_result = false;

        auto vec = Vector2d{};
        vec += (Vector2d(to.chunk()) - Vector2d(from.chunk())) * chunk_size;
        vec += Vector2d(to.local()) - Vector2d(from.local());
        vec += (Vector2d(to.offset()) - Vector2d(from.offset())) * inv_tile_size;

        auto dir = vec.normalized();

        if (Math::abs(dir.x()) < eps && Math::abs(dir.y()) < eps)
        {
            fm_error("raycast: bad dir? {%f, %f}", dir.x(), dir.y());
            return;
        }

        double step;
        unsigned long_axis, short_axis;

        if (Math::abs(dir.y()) > Math::abs(dir.x()))
        {
            long_axis = 1;
            short_axis = 0;
        }
        else
        {
            long_axis = 0;
            short_axis = 1;
        }

        if (Math::abs(dir[short_axis]) < eps)
            step = chunk_size[short_axis] * .5;
        else
        {
            step = Math::abs(inv_sqrt_2 / dir[short_axis]);
            step = Math::clamp(step, 1., TILE_MAX_DIM*.5);
            Debug{} << "step" << step;
        }
        auto nsteps = (uint32_t)Math::ceil(vec.length() / step);

        result.path.clear();
        result.path.reserve(nsteps);
        result.has_result = true;

        {
            auto center = object::normalize_coords(from, Vector2i(dir * .5));
            Vector2d size;
            size[short_axis] = (double)iTILE_SIZE2[short_axis];
            size[long_axis] = step * (double)iTILE_SIZE2[long_axis];
            Debug{} << "size" << size;
            result.path.push_back(bbox{center, Vector2ui(size)});
        }



        auto dir_inv_norm = Vector2d{
            Math::abs(dir.x()) < eps ? std::copysign(inv_eps, dir.x()) : 1. / dir.x(),
            Math::abs(dir.y()) < eps ? std::copysign(inv_eps, dir.y()) : 1. / dir.y(),
        };
        auto signs = ray_aabb_signs(dir_inv_norm);

        for (auto i = 1u; i < nsteps; i++)
        {

        }
    }
};

raycast_test::~raycast_test() noexcept = default;

Pointer<base_test> tests_data::make_test_raycast() { return Pointer<raycast_test>{InPlaceInit}; }

} // namespace floormat::tests