aboutsummaryrefslogtreecommitdiff
path: root/src/engine/engine.cpp
blob: f947a45075e2d48a91e645925fe49c3ff5f7c90b (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
#include "engine.hpp"

#include "util/function.hpp"

#include <chrono>
#include <thread>
#include <utility>

CLIGameEngine::CLIGameEngine(
	IGameFactory game_factory,
	ISceneFactory scene_factory,
	IComponentRendererFactory component_renderer_factory,
	std::shared_ptr<IUserInputObserver> user_input_observer,
	std::shared_ptr<ICursorController> cursor_controller) noexcept
	: _game_factory(std::move(game_factory)),
	  _scene_factory(std::move(scene_factory)),
	  _component_renderer_factory(std::move(component_renderer_factory)),
	  _user_input_observer(std::move(user_input_observer)),
	  _cursor_controller(std::move(cursor_controller))
{
}

void CLIGameEngine::start() noexcept
{
	std::shared_ptr<IScene> scene = _scene_factory(_cursor_controller);

	auto component_renderer = _component_renderer_factory(_cursor_controller);

	scene->enter();

	_cursor_controller->set_bounds(scene->size());

	auto game = _game_factory(scene, _cursor_controller, _user_input_observer);

	game->on_start();

	std::atexit(normalize_lambda(
		[this, scene, &game]()
		{
			scene->leave();

			game->on_exit();
		}));

	auto listen_input_thread = std::thread(normalize_lambda(
		[this]()
		{
			_user_input_observer->listen();
		}));

	auto last_update_time = std::chrono::system_clock::now();

	const auto get_millis_since_update = [&last_update_time]()
	{
		return std::chrono::duration_cast<std::chrono::milliseconds>(
			std::chrono::system_clock::now() - last_update_time);
	};

	while (true)
	{
		const auto time_since_last_update = get_millis_since_update();

		if (time_since_last_update.count() < MIN_TIME_SINCE_LAST_UPDATE_MILLIS)
		{
			while (get_millis_since_update().count() < MIN_TIME_SINCE_LAST_UPDATE_MILLIS)
			{
			}
		}

		game->on_update();

		for (auto [component, position] : scene->get_components())
		{
			if (component->get_need_render())
			{
				component_renderer->render(component, position);
				component->set_need_render(false);
			}
		}

		_user_input_observer->clear_currently_pressed();

		last_update_time = std::chrono::system_clock::now();
	}
}