aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/api/Script.hpp
blob: 547fb8b894a2a24d014b02ec5c04051758b98a85 (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
#pragma once

#include "../manager/ComponentManager.h"
#include "../manager/ReplayManager.h"

#include "BehaviorScript.h"
#include "Script.h"

namespace crepe {

template <typename T>
T & Script::get_component() const {
	using namespace std;
	RefVector<T> all_components = this->get_components<T>();
	if (all_components.size() < 1)
		throw runtime_error(
			format("Script: no component found with type = {}", typeid(T).name()));

	return all_components.back().get();
}

template <typename T>
RefVector<T> Script::get_components() const {
	return this->get_components_by_id<T>(this->game_object_id);
}

template <typename... Args>
void Script::logf(Args &&... args) {
	Log::logf(std::forward<Args>(args)...);
}

template <typename EventType>
void Script::subscribe_internal(const EventHandler<EventType> & callback,
								event_channel_t channel) {
	EventManager & mgr = this->mediator->event_manager;
	subscription_t listener = mgr.subscribe<EventType>(
		[this, callback](const EventType & data) -> bool {
			bool & active = this->active;
			if (!active) return false;
			ReplayManager & replay = this->mediator->replay_manager;
			if (replay.get_state() == ReplayManager::PLAYING) return false;
			return callback(data);
		},
		channel);
	this->listeners.push_back(listener);
}

template <typename EventType>
void Script::subscribe(const EventHandler<EventType> & callback, event_channel_t channel) {
	this->subscribe_internal(callback, channel);
}

template <typename EventType>
void Script::subscribe(const EventHandler<EventType> & callback) {
	this->subscribe_internal(callback, EventManager::CHANNEL_ALL);
}

template <typename T>
RefVector<T> Script::get_components_by_id(game_object_id_t id) const {
	Mediator & mediator = this->mediator;
	ComponentManager & mgr = mediator.component_manager;

	return mgr.get_components_by_id<T>(id);
}
template <typename T>
RefVector<T> Script::get_components_by_name(const std::string & name) const {
	Mediator & mediator = this->mediator;
	ComponentManager & mgr = mediator.component_manager;

	return mgr.get_components_by_name<T>(name);
}
template <typename T>
RefVector<T> Script::get_components_by_tag(const std::string & tag) const {
	Mediator & mediator = this->mediator;
	ComponentManager & mgr = mediator.component_manager;

	return mgr.get_components_by_tag<T>(tag);
}

} // namespace crepe