ICT290 / src / engine / audio.cpp
audio.cpp
Raw
#include "audio.h"
#include <iostream>

AudioManager::AudioManager() {
    m_audio = irrklang::createIrrKlangDevice();

    if (!m_audio) {
        throw std::runtime_error("Error starting irrKlang.\n");
    }
}

AudioManager::~AudioManager() {
    m_audio->drop();
}

void AudioManager::playSound(const Sound& sound) {
    if (sound.is3D) {
        irrklang::vec3d<float> location{sound.position.x,
                                        sound.position.y,
                                        sound.position.z};
        irrklang::ISound*
            snd = m_audio->play3D((AUDIO_RES_PATH + sound.filename).c_str(),
                                  location,
                                  sound.loop,
                                  true);
        if (snd) {
            snd->setMinDistance(sound.soundRadius);
            snd->setVolume(sound.volume / 100);
            snd->setIsPaused(false);
        }
    } else {
        irrklang::ISound*
            snd = m_audio->play2D((AUDIO_RES_PATH + sound.filename).c_str(),
                                  sound.loop,
                                  true);

        if (snd) {
            snd->setVolume(sound.volume / 100);
            snd->setIsPaused(false);
        }
    }
}

void AudioManager::setListener(const glm::vec3& location,
                               const glm::vec3& lookDirection) {
    irrklang::vec3df position(location.x, location.y, location.z);
    irrklang::vec3df look(-lookDirection.x, -lookDirection.y, -lookDirection.z);
    irrklang::vec3df velPerSecond(0, 0, 0);  // Irrelevant
    irrklang::vec3df upVector(0, 1, 0);

    m_audio->setListenerPosition(position, look, velPerSecond, upVector);
}

void AudioManager::stopAllSounds() {
    m_audio->stopAllSounds();
}

void AudioManager::pauseSounds(bool pause) {
    m_paused = pause;
    m_audio->setAllSoundsPaused(pause);
}

bool AudioManager::isPaused() const {
    return m_paused;
}

void AudioManager::setMasterVolume(float volume) {
    if (volume > 100) {
        volume = 100;
    } else if (volume < 0) {
        volume = 0;
    }
    m_masterVolume = volume;
    if (!m_muted) {
        m_audio->setSoundVolume(volume / 100);
    }
}

float AudioManager::getMasterVolume() const {
    return m_masterVolume;
}

void AudioManager::toggleMute() {
    if (m_muted) {
        m_audio->setSoundVolume(m_masterVolume / 100);
    } else {
        m_audio->setSoundVolume(0.f);
    }
    m_muted = !m_muted;
}

bool AudioManager::isMuted() const {
    return m_muted;
}

void AudioManager::setMute(bool mute) {
    m_muted = mute;
    if (!m_muted) {
        m_audio->setSoundVolume(m_masterVolume / 100);
    } else {
        m_audio->setSoundVolume(0.f);
    }
}