aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/system/ReplaySystem.cpp
blob: a6b8fb163dcf90ffd81660b2cb2d1c5336fb8de1 (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 "../util/Log.h"
#include "../manager/ReplayManager.h"
#include "../manager/SystemManager.h"

#include "RenderSystem.h"
#include "ReplaySystem.h"

using namespace crepe;
using namespace std;

void ReplaySystem::fixed_update() {
	ReplayManager & replay = this->mediator.replay_manager;

	switch (replay.state) {
		case ReplayManager::IDLE: break;
		case ReplayManager::RECORDING: {
			this->update_recording();
			break;
		}
		case ReplayManager::PLAYING: {
			this->update_playing();
			break;
		}
	}

	this->last_state = replay.state;
}

void ReplaySystem::update_recording() {
	ReplayManager & replay = this->mediator.replay_manager;
	ComponentManager & components = this->mediator.component_manager;

	ReplayManager::Recording & recording = replay.recording;
	recording.frames.push_back(components.save());
	recording.frame++;
}

void ReplaySystem::update_playing() {
	ReplayManager & replay = this->mediator.replay_manager;

	if (this->last_state != ReplayManager::PLAYING) {
		this->playback_begin();
	}

	ReplayManager::Recording & recording = replay.recording;

	if (recording.frames.size() == recording.frame) {
		dbg_log("Finished playback");
		this->playback_end();
		return;
	}

	ComponentManager & components = this->mediator.component_manager;
	ComponentManager::Snapshot & frame = recording.frames.at(recording.frame);

	dbg_logf("Playing recording frame {}", recording.frame);
	components.restore(frame);
	recording.frame++;
}

void ReplaySystem::playback_begin() {
	SystemManager & systems = this->mediator.system_manager;
	ComponentManager & components = this->mediator.component_manager;

	this->playback = {
		.components = components.save(),
		.systems = systems.save(),
	};

	systems.disable_all();
	systems.get_system<RenderSystem>().active = true;
	systems.get_system<ReplaySystem>().active = true;
}

void ReplaySystem::playback_end() {
	SystemManager & systems = this->mediator.system_manager;
	ComponentManager & components = this->mediator.component_manager;

	components.restore(this->playback.components);
	systems.restore(this->playback.systems);

	ReplayManager & replay = this->mediator.replay_manager;
	replay.state = ReplayManager::IDLE;
}