diff --git a/.gitmodules b/.gitmodules index 206ea0a3..758c9fac 100644 --- a/.gitmodules +++ b/.gitmodules @@ -49,3 +49,6 @@ [submodule "vendor/assimp"] path = vendor/assimp url = https://github.com/assimp/assimp.git +[submodule "vendor/miniaudio"] + path = vendor/miniaudio + url = https://github.com/mackron/miniaudio.git diff --git a/Makefile b/Makefile index 4d3b50d5..370aac66 100644 --- a/Makefile +++ b/Makefile @@ -44,6 +44,7 @@ export examplesDir := $(abspath examples) export utilsLib := $(libDir)/libutils.a export resourcesLib := $(libDir)/libresources.a export windowLib := $(libDir)/libwindow.a +export audioLib := $(libDir)/libaudio.a export coreLib := $(libDir)/libcore.a export renderLib := $(libDir)/librender.a export testApp := $(binDir)/tests/build/app @@ -70,7 +71,10 @@ $(resourcesLib): buildFlags $(utilsLib) $(windowLib): buildFlags $(utilsLib) "$(MAKE)" -C $(engineDir)/window CXXFLAGS="$(CXXFLAGS)" -$(coreLib): buildFlags $(utilsLib) +$(audioLib): buildFlags $(utilsLib) + "$(MAKE)" -C $(engineDir)/audio CXXFLAGS="$(CXXFLAGS)" + +$(coreLib): buildFlags $(utilsLib) $(audioLib) # TODO remove redundant audio dependency "$(MAKE)" -C $(engineDir)/core CXXFLAGS="$(CXXFLAGS)" $(renderLib): buildFlags $(utilsLib) $(windowLib) diff --git a/README.md b/README.md index f7730e99..1a0e5600 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,15 @@ [![macOS Status](../../workflows/macOS/badge.svg)](https://github.com/CapsCollective/siege-engine/actions/workflows/macOS.yml) [![Linux Status](../../workflows/Ubuntu/badge.svg)](https://github.com/CapsCollective/siege-engine/actions/workflows/ubuntu.yml) [![Windows Status](../../workflows/Windows/badge.svg)](https://github.com/CapsCollective/siege-engine/actions/workflows/windows.yml) -[![Tests Status](../../workflows/Tests/badge.svg)](https://github.com/CapsCollective/siege-engine/actions/workflows/tests.yml) [![Formatting Status](../../workflows/Formatting/badge.svg)](https://github.com/CapsCollective/siege-engine/actions/workflows/formatting.yml) [![License: Zlib](https://img.shields.io/badge/License-Zlib-lightgrey.svg)](https://opensource.org/licenses/Zlib) [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](CODE_OF_CONDUCT.md) -Sometimes game development can feel like a bit of a slog; an endless battle in which the developer is set against an overwhelming bulwark of required knowledge to create a functional game. On one hand, one must understand _linear algebra, calculus, and the intricacies of the rasterised rendering pipeline_ whilst also expecting a mastery of _memory mangement, build systems, algorithms, and coherent software architecture_. +Sometimes game development can feel like a bit of a slog; an endless battle in which the developer is set against an overwhelming bulwark of required knowledge to create a functional game. On one hand, one must understand _linear algebra, calculus, and the intricacies of the rasterised rendering pipeline_ whilst also expecting a mastery of _memory management, build systems, algorithms, and coherent software architecture_. The reality is that making games is hard, and making games can be even harder when one does not fully understand the underlying foundations below the many layers of abstraction present in many commercial and general game engines. Using them can often feel disempowering as they discourage deeper learning through sheer size and complexity. -The ultimate purpose of this project is to act as the metaphorical siege engine to break down the barriers to game engine development. To this end, Siege aims to be a **light-weight, cross platform, 3D game engine**. In doing so, we hope to create an engine for game developers, by game developers. +The ultimate purpose of this project is to act as the metaphorical siege engine to break down the barriers to game engine development. To this end, Siege aims to be a **light-weight, cross-platform, 3D game engine**. In doing so, we hope to create an engine for game developers, by game developers. ### Current Compatability @@ -156,6 +155,7 @@ You can see examples of this in any of the application targets under `examples`. ``` [root] ├─[engine] + │ ├─[audio] <- the engine's audio system │ ├─[core] <- the engine's core library │ ├─[render] <- the engine's renderer | ├─[resources] <- the engine's resource types and loading system diff --git a/engine/audio/AudioSystem.cpp b/engine/audio/AudioSystem.cpp new file mode 100644 index 00000000..e1814076 --- /dev/null +++ b/engine/audio/AudioSystem.cpp @@ -0,0 +1,343 @@ +// +// Copyright (c) 2020-present Caps Collective & contributors +// Originally authored by Jonathan Moallem (@jonjondev) & Aryeh Zinn (@Raelr) +// +// This code is released under an unmodified zlib license. +// For conditions of distribution and use, please see: +// https://opensource.org/licenses/Zlib +// + +#include "AudioSystem.h" + +#include + +#include +#include + +#define MA_NO_RESOURCE_MANAGER + +#define AUDIO_SYSTEM_MAX_VOICES 16 + +namespace Siege +{ + +struct Voice +{ + uint64_t playerId = 0; + ma_decoder decoder = {}; + ma_sound sound = {}; + bool pendingKill = false; +}; + +static ma_engine audioEngine; +static ma_decoder_config decoderConfig; + +static Voice voices[AUDIO_SYSTEM_MAX_VOICES]; +static std::mutex voicesMutex; + +bool SoundPlayer::Play() +{ + return AudioSystem::GetInstance().AssignPlayerToVoice(this); +} + +bool SoundPlayer::Stop() +{ + return AudioSystem::GetInstance().UnassignPlayerFromVoices(this); +} + +bool SoundPlayer::UpdateVoices() +{ + return AudioSystem::GetInstance().UpdateSoundPlayerVoices(this); +} + +bool SoundPlayer::IsPlaying() const +{ + return AudioSystem::GetInstance().IsSoundPlayingForPlayer(this); +} + +AudioSystem& AudioSystem::GetInstance() +{ + static AudioSystem audioSystem; + return audioSystem; +} + +bool AudioSystem::Initialise() +{ + decoderConfig = ma_decoder_config_init_default(); + ma_engine_config engineConfig = ma_engine_config_init(); + engineConfig.listenerCount = 1; + ma_result result = ma_engine_init(&engineConfig, &audioEngine); + return result == MA_SUCCESS; +} + +static int32_t FindPolyphonyCountForSound(const SoundPlayer* soundPlayer) +{ + int32_t count = 0; + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + const Voice& voice = voices[i]; + if (voice.playerId == soundPlayer->playerId) + { + ++count; + } + } + return count; +} + +static int32_t FindAvailableVoice() +{ + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + const Voice& voice = voices[i]; + uint64_t id = voice.playerId; + if (id == 0) + { + return i; + } + } + return -1; +} + +static void OnSoundEnded(void* userData, ma_sound* sound) +{ + std::scoped_lock lock(voicesMutex); + uint64_t voiceIdx = reinterpret_cast(userData); + Voice& voice = voices[voiceIdx]; + voice.pendingKill = true; + CC_LOG_INFO("Marked pending kill sound clip with id {} on voice idx {}", + voice.playerId, + voiceIdx) +} + +bool AudioSystem::AssignPlayerToVoice(SoundPlayer* soundPlayer) +{ + std::scoped_lock lock(voicesMutex); + + void* clipData = soundPlayer->clipData->data; + uint32_t clipDataLength = soundPlayer->clipData->dataSize; + + if (soundPlayer->playerId != 0 && soundPlayer->maxPolyphony != 0) + { + int32_t currentPolyphony = FindPolyphonyCountForSound(soundPlayer); + if (currentPolyphony >= soundPlayer->maxPolyphony) + { + CC_LOG_WARNING("Cannot play requested clip at address above {} max polyphony of {}", + reinterpret_cast(clipData), + soundPlayer->maxPolyphony); + return false; + } + } + + int32_t voiceIdx = FindAvailableVoice(); + if (voiceIdx == -1) + { + CC_LOG_WARNING("Failed to find available voice for requested clip at address {}", + reinterpret_cast(clipData)); + return false; + } + + Voice& voice = voices[voiceIdx]; + + ma_result result = + ma_decoder_init_memory(clipData, clipDataLength, &decoderConfig, &voice.decoder); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to initialise decoder for requested clip at address {}", + reinterpret_cast(clipData)) + return false; + } + + result = ma_sound_init_from_data_source(&audioEngine, &voice.decoder, 0, nullptr, &voice.sound); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to initialise sound for requested clip at address {}", + reinterpret_cast(clipData)) + result = ma_decoder_uninit(&voice.decoder); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to uninitialise decoder after bad sound initialisation") + } + return false; + } + + static uint64_t globalId = 0; + if (soundPlayer->playerId == 0) + { + soundPlayer->playerId = ++globalId; + } + voice.playerId = soundPlayer->playerId; + + result = + ma_sound_set_end_callback(&voice.sound, OnSoundEnded, reinterpret_cast(voiceIdx)); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to set sound ended callback for requested clip at address {}", + reinterpret_cast(clipData)) + ma_sound_uninit(&voice.sound); + result = ma_decoder_uninit(&voice.decoder); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to uninitialise decoder after failure to set callback") + } + --globalId; + return false; + } + + if (soundPlayer->looping) + { + ma_sound_set_looping(&voice.sound, true); + } + + ma_sound_set_spatialization_enabled(&voice.sound, !soundPlayer->disableSpatialisation); + if (!soundPlayer->disableSpatialisation) + { + const Vec3& pos = soundPlayer->location; + ma_sound_set_position(&voice.sound, pos.x, pos.y, pos.z); + } + + result = ma_sound_start(&voice.sound); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to start sound for requested clip at address {}", + reinterpret_cast(clipData)) + ma_sound_uninit(&voice.sound); + result = ma_decoder_uninit(&voice.decoder); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to uninitialise decoder after sound failed to start") + } + --globalId; + return false; + } + + CC_LOG_INFO("Started playing sound clip at address {} with id {} on voice idx {}", + reinterpret_cast(clipData), + voice.playerId, + voiceIdx) + return true; +} + +bool AudioSystem::UnassignPlayerFromVoices(const SoundPlayer* soundPlayer) +{ + std::scoped_lock lock(voicesMutex); + bool stoppedSounds = false; + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + Voice& voice = voices[i]; + if (voice.playerId != soundPlayer->playerId) + { + continue; + } + + ma_result result = ma_sound_stop(&voice.sound); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to stop sound with id {} on voice idx {}", voice.playerId, i) + } + CC_LOG_INFO("Stopped sound clip with id {} on voice idx {}", voice.playerId, i) + + voice.pendingKill = true; + CC_LOG_INFO("Marked pending kill sound clip with id {} on voice idx {}", voice.playerId, i) + stoppedSounds = true; + } + return stoppedSounds; +} + +bool AudioSystem::UpdateSoundPlayerVoices(const SoundPlayer* soundPlayer) +{ + std::scoped_lock lock(voicesMutex); + bool foundVoices = false; + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + Voice& voice = voices[i]; + if (voice.playerId != soundPlayer->playerId) + { + continue; + } + + const Vec3& pos = soundPlayer->location; + ma_sound_set_position(&voice.sound, pos.x, pos.y, pos.z); + foundVoices = true; + } + return foundVoices; +} + +bool AudioSystem::IsSoundPlayingForPlayer(const SoundPlayer* soundPlayer) const +{ + std::scoped_lock lock(voicesMutex); + int32_t currentPolyphony = FindPolyphonyCountForSound(soundPlayer); + return currentPolyphony > 0; +} + +void AudioSystem::SetSoundListenerTransform(const Xform& transform) +{ + uint32_t listenerIdx = 0; + ma_engine_listener_set_world_up(&audioEngine, listenerIdx, 0, 1, 0); + + const Vec3& pos = transform.GetPosition(); + const Vec3& rot = transform.GetRotation(); + ma_engine_listener_set_position(&audioEngine, listenerIdx, pos.x, pos.y, pos.z); + ma_engine_listener_set_direction(&audioEngine, listenerIdx, rot.x, rot.y, rot.z); +} + +void AudioSystem::Update() +{ + std::scoped_lock lock(voicesMutex); + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + Voice& voice = voices[i]; + uint64_t id = voice.playerId; + if (id == 0) + { + continue; + } + + if (!voice.pendingKill) + { + continue; + } + + ma_sound_uninit(&voice.sound); + ma_result result = ma_decoder_uninit(&voice.decoder); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to uninitialise decoder") + } + + std::memset(&voice, 0, sizeof(Voice)); + CC_LOG_INFO("Flushed voice playing sound clip with id {} on voice idx {}", id, i) + } +} + +void AudioSystem::Uninitialise() +{ + { + std::scoped_lock lock(voicesMutex); + for (int32_t i = 0; i < AUDIO_SYSTEM_MAX_VOICES; ++i) + { + Voice& voice = voices[i]; + uint64_t id = voice.playerId; + if (id == 0) + { + continue; + } + + ma_result result = ma_sound_stop(&voice.sound); + if (result != MA_SUCCESS) + { + CC_LOG_ERROR("Failed to stop sound with id {} on voice idx {}", voice.playerId, i) + } + CC_LOG_INFO("Stopped sound clip with id {} on voice idx {}", voice.playerId, i) + + voice.pendingKill = true; + CC_LOG_INFO("Marked pending kill sound clip with id {} on voice idx {}", + voice.playerId, + i) + } + } + Update(); + + ma_engine_uninit(&audioEngine); +} + +} // namespace Siege \ No newline at end of file diff --git a/engine/audio/AudioSystem.h b/engine/audio/AudioSystem.h new file mode 100644 index 00000000..b5e97ce6 --- /dev/null +++ b/engine/audio/AudioSystem.h @@ -0,0 +1,149 @@ +// +// Copyright (c) 2020-present Caps Collective & contributors +// Originally authored by Jonathan Moallem (@jonjondev) & Aryeh Zinn (@Raelr) +// +// This code is released under an unmodified zlib license. +// For conditions of distribution and use, please see: +// https://opensource.org/licenses/Zlib +// + +#ifndef SIEGE_ENGINE_AUDIOSYSTEM_H +#define SIEGE_ENGINE_AUDIOSYSTEM_H + +#include +#include +#include + +#include + +namespace Siege +{ + +class SoundPlayer +{ +public: + + // Public methods + + /** + * Plays the sound clip with the current configuration of the object + * @return true if the sound successfully began play, otherwise false + */ + bool Play(); + + /** + * Stops the sound across all active voices related to the player + * @return true if the sound successfully stopped play, otherwise false + */ + bool Stop(); + + /** + * Updates all active voices related to the player with the current + * configuration of the object + * @return true if the player updated any voices, otherwise false + */ + bool UpdateVoices(); + + /** + * Checks whether there are any playing or pending kill voices + * related to the player + * @return true if playing, false otherwise + */ + bool IsPlaying() const; + + // Public fields + + // An automatically assigned ID for the player + // (DO NOT modify this value) + uint64_t playerId = 0; + + // Pointer to raw data of audio clip + std::shared_ptr clipData; + + // Spatial location of the sound + Vec3 location; + + // Forces spatialisation off for this sound + bool disableSpatialisation = false; + + // Loops the clip upon reaching its end + bool looping = false; + + // The limit of concurrent voices allowed for + // this player (leave as 0 for no limiting) + uint8_t maxPolyphony = 0; +}; + +class AudioSystem +{ +public: + + // Public methods + + /** + * Retrieves the audio system singleton object + * @return a reference to the audio system + */ + static AudioSystem& GetInstance(); + + /** + * Initialises the audio engine and any other system configuration + * @return true if the initialisation was successful, otherwise false + */ + bool Initialise(); + + /** + * Finds and assigns a free voice to a given sound player + * @param soundPlayer - the sound player to assign + * @return true if the assignment was successful, otherwise false + * @note this method will also assign an ID to the player from if + * it does not already have one + */ + bool AssignPlayerToVoice(SoundPlayer* soundPlayer); + + /** + * Finds and marks all voices related to a particular sound player + * for pending kill on the next audio system update + * @param soundPlayer - the sound player to unassign + * @return true if the unassignment was successful, otherwise false + */ + bool UnassignPlayerFromVoices(const SoundPlayer* soundPlayer); + + /** + * Updates all voices related to a particular sound player, + * including audio spatialisation settings + * @param soundPlayer - the sound player to update + * @return true if any relevant voices were found, otherwise false + */ + bool UpdateSoundPlayerVoices(const SoundPlayer* soundPlayer); + + /** + * Checks whether there are any playing or pending kill voices + * @param soundPlayer - the sound player to check + * @return true if the sound is playing, otherwise false + */ + bool IsSoundPlayingForPlayer(const SoundPlayer* soundPlayer) const; + + /** + * Sets the transform of the audio system sound listener + * @param transform - the transform to apply + */ + void SetSoundListenerTransform(const Xform& transform); + + /** + * Updates the audio system for the current frame to free up any + * voices pending kill for future use + */ + void Update(); + + /** + * Stops all sounds, marks all active voices for pending kill, + * runs a final update frame to clear out playing sounds, and + * uninitialises the audio engine + */ + void Uninitialise(); +}; + +} // namespace Siege + +#endif // SIEGE_ENGINE_AUDIOSYSTEM_H diff --git a/engine/audio/Makefile b/engine/audio/Makefile new file mode 100644 index 00000000..44b28bb6 --- /dev/null +++ b/engine/audio/Makefile @@ -0,0 +1,33 @@ +# Copyright (c) 2020-present Caps Collective & contributors +# Originally authored by Jonathan Moallem (@jonjondev) & Aryeh Zinn (@Raelr) +# +# This code is released under an unmodified zlib license. +# For conditions of distribution and use, please see: +# https://opensource.org/licenses/Zlib + +include $(makeDir)/Functions.mk +include $(makeDir)/Platform.mk + +# Set build vars +audioSrcDir := ./ +audioBinDir := $(binDir)/engine/audio +audioSources := $(call rwildcard,$(audioSrcDir)/,*.cpp) +audioObjects := $(call findobjs,$(audioSrcDir),$(audioBinDir),$(audioSources)) +audioDepends := $(patsubst %.o, %.d, $(call rwildcard,$(audioBinDir)/,*.o)) + +# Set build vars +linkFlags += -l utils +compileFlags += -I $(vendorDir)/miniaudio + +# Build the static library +$(audioLib): $(audioObjects) + $(call MKDIR,$(call platformpth,$(libDir))) + ar -crs $(audioLib) $(audioObjects) + +# Add all rules from dependency files +-include $(audioDepends) + +# Compile object files to the bin directory +$(audioBinDir)/%.o: $(audioSrcDir)/%.cpp + $(call MKDIR,$(call platformpth,$(@D))) + $(CXX) -MMD -MP -c $(compileFlags) -I $(engineDir) $< -o $@ $(CXXFLAGS) \ No newline at end of file diff --git a/engine/utils/math/Xform.h b/engine/utils/math/Xform.h index ad8a2741..368e864d 100644 --- a/engine/utils/math/Xform.h +++ b/engine/utils/math/Xform.h @@ -26,6 +26,12 @@ struct Xform Xform(Vec3 position, float rotation) : Xform(position, rotation, Vec3::One()) {} + Xform(Vec3 position, Vec3 rotation, Vec3 scale) : + position(position), + rotation(rotation), + scale(scale) + {} + Xform(Vec3 position, float rotation, Vec3 scale) : position(position), rotation(Vec3 {0.f, rotation, 0.f}), diff --git a/examples/game/Makefile b/examples/game/Makefile index e7ee4a3d..8950b260 100644 --- a/examples/game/Makefile +++ b/examples/game/Makefile @@ -37,6 +37,8 @@ exampleGameAssets += $(patsubst ./%,%, $(call rwildcard,$(exampleGameSrcDir),*.j exampleGameAssets += $(patsubst $(engineRenderBuildDir)/%,%, $(call rwildcard,$(engineRenderBuildDir),*.spv)) exampleGameAssets += $(patsubst ./%,%, $(call rwildcard,$(exampleGameSrcDir),*.ttf)) exampleGameAssets += $(patsubst ./%,%, $(call rwildcard,$(exampleGameSrcDir),*.scene)) +exampleGameAssets += $(patsubst ./%,%, $(call rwildcard,$(exampleGameSrcDir),*.wav)) +exampleGameAssets += $(patsubst ./%,%, $(call rwildcard,$(exampleGameSrcDir),*.mp3)) ifneq ($(ENABLE_VALIDATION_LAYERS), 1) packagingExcludes := $(VALIDATION_LAYERS_INSTALL_DIR) @@ -50,14 +52,14 @@ packagingFlags = $(ENV_VARS) --excludes "$(packagingExcludes)" # Set build vars compileFlags += -I $(vendorDir)/glfw/include -I $(vendorDir)/glm -I $(vendorDir)/freetype/include -linkFlags += -l core -l window -l render -l resources -l utils +linkFlags += -l core -l window -l render -l audio -l resources -l utils .PHONY: all pack-assets all: $(exampleGameApp) pack-assets # Link the object files and create an executable -$(exampleGameApp): $(utilsLib) $(windowLib) $(renderLib) $(coreLib) $(exampleGameObjects) +$(exampleGameApp): $(utilsLib) $(windowLib) $(audioLib) $(renderLib) $(coreLib) $(exampleGameObjects) $(call MKDIR,$(call platformpth,$(@D))) $(CXX) $(exampleGameObjects) -o $(exampleGameApp) $(linkFlags) diff --git a/examples/game/assets/audio/call_to_adventure.mp3 b/examples/game/assets/audio/call_to_adventure.mp3 new file mode 100644 index 00000000..a3852076 Binary files /dev/null and b/examples/game/assets/audio/call_to_adventure.mp3 differ diff --git a/examples/game/assets/audio/click.wav b/examples/game/assets/audio/click.wav new file mode 100644 index 00000000..547f7aaa Binary files /dev/null and b/examples/game/assets/audio/click.wav differ diff --git a/examples/game/src/entities/FPSCamera.cpp b/examples/game/src/entities/FPSCamera.cpp index 890675a4..47d49b9b 100644 --- a/examples/game/src/entities/FPSCamera.cpp +++ b/examples/game/src/entities/FPSCamera.cpp @@ -9,6 +9,7 @@ #include "FPSCamera.h" +#include