aboutsummaryrefslogtreecommitdiff
path: root/src/crepe/system/AudioSystem.cpp
blob: c1cde8b7b12cb7a8e3d2892d1f783a54ea60308a (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
#include "AudioSystem.h"

#include "../manager/ComponentManager.h"
#include "../manager/ResourceManager.h"
#include "../types.h"

using namespace crepe;
using namespace std;

void AudioSystem::update() {
	ComponentManager & component_manager = this->mediator.component_manager;
	ResourceManager & resource_manager = this->mediator.resource_manager;
	RefVector<AudioSource> components
		= component_manager.get_components_by_type<AudioSource>();

	for (AudioSource & component : components) {
		Sound & resource = resource_manager.get<Sound>(component.source);

		this->diff_update(component, resource);

		this->update_last(component);
	}
}

void AudioSystem::diff_update(AudioSource & component, Sound & resource) {
	SoundContext & context = this->get_context();

	if (component.active != component.last_active) {
		if (component.active) {
			component.oneshot_play = component.play_on_awake;
		} else {
			context.stop(component.voice);
			return;
		}
	}
	if (!component.active) return;

	if (component.oneshot_play) {
		component.voice = context.play(resource);
		component.oneshot_play = false;
	}
	if (component.oneshot_stop) {
		context.stop(component.voice);
		component.oneshot_stop = false;
	}
	if (component.volume != component.last_volume) {
		context.set_volume(component.voice, component.volume);
	}
	if (component.loop != component.last_loop) {
		context.set_loop(component.voice, component.loop);
	}
}

void AudioSystem::update_last(AudioSource & component) {
	component.last_active = component.active;
	component.last_loop = component.loop;
	component.last_volume = component.volume;
}

SoundContext & AudioSystem::get_context() {
	if (this->context == nullptr)
		this->context = make_unique<SoundContext>();
	return *this->context.get();
}