summaryrefslogtreecommitdiff
path: root/ui/gameMainSelector.cpp
blob: ff9afb7afbb3359c6131307ab382b862371f62a3 (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
#include "gameMainSelector.h"
#include "collection.hpp"
#include "text.h"
#include "ui/uiComponent.h"
#include <SDL2/SDL.h>
#include <game/gamestate.h>
#include <game/geoData.h>
#include <game/selectable.h>
#include <game/worldobject.h> // IWYU pragma: keep
#include <gfx/gl/camera.h>
#include <optional>
#include <span>
#include <stream_support.hpp>
#include <typeinfo>
#include <vector>

GameMainSelector::GameMainSelector(const Camera * c, glm::vec2 size) : UIComponent {{{}, size}}, camera {c} { }
constexpr glm::vec2 TargetPos {5, 45};

void
GameMainSelector::render(const UIShader & shader, const Position & parentPos) const
{
	if (target) {
		target->render(shader, parentPos + position + TargetPos);
	}
	if (!clicked.empty()) {
		Text {clicked, {{50, 10}, {0, 15}}, {1, 1, 0}}.render(shader, parentPos);
	}
}

bool
GameMainSelector::handleInput(const SDL_Event & e, const Position & parentPos)
{
	const auto getRay = [this](const auto & e) {
		const auto mouse = glm::vec2 {e.x, e.y} / position.size;
		return camera->unProject(mouse);
	};
	if (target) {
		switch (e.type) {
			case SDL_MOUSEBUTTONDOWN:
				if (target->click(e.button, getRay(e.button))) {
					return true;
				}
				break;
			case SDL_MOUSEMOTION:
				if (target->move(e.motion, getRay(e.motion))) {
					return true;
				}
				break;
		}
		return target->handleInput(e, parentPos + position + TargetPos);
	}
	else {
		switch (e.type) {
			case SDL_MOUSEBUTTONDOWN:
				defaultClick(getRay(e.button));
				break;
		}
	}
	return false;
}

void
GameMainSelector::defaultClick(const Ray & ray)
{
	glm::vec2 baryPos {};
	float distance;

	if (const auto selected
			= gameState->world.applyOne<Selectable>(&Selectable::intersectRay, ray, &baryPos, &distance);
			selected != gameState->world.end()) {
		const auto & ref = *selected.base()->get();
		clicked = typeid(ref).name();
	}
	else if (const auto pos = gameState->geoData->intersectRay(ray)) {
		clicked = streamed_string(*pos);
	}
	else {
		clicked.clear();
	}
}

bool
GameMainSelector::Component::click(const SDL_MouseButtonEvent &, const Ray &)
{
	return false;
}

bool
GameMainSelector::Component::move(const SDL_MouseMotionEvent &, const Ray &)
{
	return false;
}

bool
GameMainSelector::Component::handleInput(const SDL_Event &, const Position &)
{
	return false;
}

void
GameMainSelector::Component::render(const UIShader &, const UIComponent::Position &) const
{
}