GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
SoundStage.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_AUDIO_SOUND_STAGE_HPP
5#define GREM_AUDIO_SOUND_STAGE_HPP
6
8
16#include <GREM/core/math.hpp>
19
20#include <new> // std::launder
21#include <type_traits> // std::remove_cvref_t
22#include <utility> // std::move
23
24namespace grem::audio {
25
26class Sound; // Forward declaration, to avoid including Sound.hpp.
27
31struct Panning {
40 [[nodiscard]] static Panning fromNormalizedCenterOffset(float normalizedOffset) {
41 return {
42 .leftVolume = cos((1.0f + normalizedOffset) * (numbers::PI * 0.25f)),
43 .rightVolume = sin((1.0f + normalizedOffset) * (numbers::PI * 0.25f)),
44 };
45 }
46
47 float leftVolume = 1.0f;
48 float rightVolume = 1.0f;
49};
50
61
69 float outputVolume = 1.0f;
70
81 float speedOfSound = 343.3f;
82
89
100 bool useRoundoff = true;
101
109 bool enableStatistics = false;
110};
111
123public:
138 GREM_API(audio) explicit SoundStage(const SoundStageOptions& options = {});
139
149 GREM_API(audio) void update(const Listener& listener);
150
169 GREM_API(audio) SoundInstanceID playSound(const Sound& sound, float volume = -1.0f, Panning panning = {});
170
192 GREM_API(audio) SoundInstanceID play3DSound(const Sound& sound, vec3 position, vec3 velocity, float volume = -1.0f);
193
208 GREM_API(audio) SoundInstanceID playSoundInBackground(const Sound& sound, float volume = -1.0f);
209
228 GREM_API(audio) SoundInstanceID createPausedSound(const Sound& sound, float volume = -1.0f, Panning panning = {});
229
252 GREM_API(audio) SoundInstanceID createPaused3DSound(const Sound& sound, vec3 position, vec3 velocity, float volume = -1.0f);
253
269 GREM_API(audio) SoundInstanceID createPausedSoundInBackground(const Sound& sound, float volume = -1.0f);
270
292 GREM_API(audio) SoundInstanceID playSoundClocked(Duration time, const Sound& sound, float volume = -1.0f, Panning panning = {});
293
320 GREM_API(audio) SoundInstanceID play3DSoundClocked(Duration time, const Sound& sound, vec3 position, vec3 velocity, float volume = -1.0f);
321
335 [[nodiscard]] GREM_API(audio) bool isSoundPaused(SoundInstanceID id) const noexcept;
336
349 [[nodiscard]] GREM_API(audio) bool isSoundStopped(SoundInstanceID id) const noexcept;
350
363 [[nodiscard]] GREM_API(audio) bool isSoundLooping(SoundInstanceID id) const noexcept;
364
376 [[nodiscard]] GREM_API(audio) Optional<Duration> getSoundTime(SoundInstanceID id) const;
377
390 GREM_API(audio) void stopSound(SoundInstanceID id) noexcept;
391
405 GREM_API(audio) void pauseSound(SoundInstanceID id);
406
420
436 GREM_API(audio) void scheduleSoundStop(SoundInstanceID id, Duration timePointInSound);
437
453 GREM_API(audio) void scheduleSoundPause(SoundInstanceID id, Duration timePointInSound);
454
469 GREM_API(audio) void setSoundLooping(SoundInstanceID id, bool newLooping);
470
486 GREM_API(audio) void seekToSoundTime(SoundInstanceID id, Duration timePointInSound);
487
504 GREM_API(audio) void setSoundPosition(SoundInstanceID id, vec3 newPosition);
505
521 GREM_API(audio) void setSoundVelocity(SoundInstanceID id, vec3 newVelocity);
522
541 GREM_API(audio) void setSoundPositionAndVelocity(SoundInstanceID id, vec3 newPosition, vec3 newVelocity);
542
555 GREM_API(audio) void setSoundPanning(SoundInstanceID id, Panning newPanning);
556
570 GREM_API(audio) void setSoundVolume(SoundInstanceID id, float newVolume);
571
586 GREM_API(audio) void fadeSoundVolume(SoundInstanceID id, float targetVolume, Duration fadeDuration);
587
605 GREM_API(audio) void setSoundPlaybackSpeed(SoundInstanceID id, float newPlaybackSpeed);
606
622 GREM_API(audio) void fadeSoundPlaybackSpeed(SoundInstanceID id, float targetPlaybackSpeed, Duration fadeDuration);
623
631 GREM_API(audio) void setOutputChannelSpeakerPosition(size_t outputChannelIndex, vec3 newPosition);
632
641 GREM_API(audio) void setOutputVolume(float newVolume);
642
653 GREM_API(audio) void fadeOutputVolume(float targetVolume, Duration fadeDuration);
654
661 GREM_API(audio) void setSpeedOfSound(float newSpeedOfSound);
662
671 GREM_API(audio) void setMaxSimultaneousSoundInstanceCount(size_t newMaxSimultaneousSoundInstanceCount);
672
682 GREM_API(audio) void setStatisticsEnabled(bool newEnableStatistics);
683
689 [[nodiscard]] GREM_API(audio) size_t getOutputChannelCount() const noexcept;
690
700 [[nodiscard]] GREM_API(audio) vec3 getOutputChannelSpeakerPosition(size_t outputChannelIndex) const noexcept;
701
708 [[nodiscard]] GREM_API(audio) float getOutputVolume() const noexcept;
709
715 [[nodiscard]] GREM_API(audio) float getSpeedOfSound() const noexcept;
716
723 [[nodiscard]] GREM_API(audio) size_t getMaxSimultaneousSounds() const noexcept;
724
739 [[nodiscard]] GREM_API(audio) Array<float, 256> calculateOutputFastFourierTransformStatistics() const;
740
753 [[nodiscard]] GREM_API(audio) Array<float, 256> getOutputWaveStatistics() const;
754
771 [[nodiscard]] GREM_API(audio) float getOutputChannelVolumeStatistics(size_t outputChannelIndex) const;
772
796 template <filter F>
797 void setGlobalFilter(size_t filterSlotIndex, const F& newFilter) {
798 if constexpr (requires(const void* data) { F::GREM_private_createBuiltinFilter(data); }) {
799 detail::Filter filter{F::GREM_private_createBuiltinFilter(static_cast<const void*>(static_cast<const F*>(&newFilter)))};
800 setGlobalFilterImplementation(filterSlotIndex, std::move(filter));
801 } else {
802 static_assert(trivially_copyable<F>);
803 static constexpr detail::FilterFunction doFilter =
804 [](byte* data, Span<float> samples, size_t channelCount, size_t sampleCountPerChannel, float sampleRate, double time) -> void {
805 std::launder(reinterpret_cast<F*>(data))->filter(samples, channelCount, sampleCountPerChannel, sampleRate, time);
806 };
807 if constexpr (requires { newFilter.parameters; }) {
808 using Parameters = std::remove_cvref_t<decltype(newFilter.parameters)>;
809 const size_t parametersOffset = std::launder(reinterpret_cast<const byte*>(&newFilter.parameters)) - std::launder(reinterpret_cast<const byte*>(&newFilter));
810 detail::Filter filter{
811 detail::createCustomFilter(asBytes(Span{static_cast<const F*>(&newFilter), 1}), parametersOffset, detail::FILTER_PARAMETER_DESCRIPTIONS<Parameters>,
812 detail::FILTER_PARAMETER_INFOS<Parameters>, doFilter),
813 };
814 setGlobalFilterImplementation(filterSlotIndex, std::move(filter));
815 } else {
816 detail::Filter filter{detail::createCustomFilter(asBytes(Span{static_cast<const F*>(&newFilter), 1}), 0, {}, doFilter)};
817 setGlobalFilterImplementation(filterSlotIndex, std::move(filter));
818 }
819 }
820 }
821
828 GREM_API(audio) void clearGlobalFilter(size_t filterSlotIndex) noexcept;
829
857 template <auto Member>
859 setSoundFilterParameterImplementation(id, filterSlotIndex, meta::member_pointer_index_v<Member>, static_cast<float>(newValue));
860 }
861
883 template <auto Member>
885 setGlobalFilterParameterImplementation(filterSlotIndex, meta::member_pointer_index_v<Member>, static_cast<float>(newValue));
886 }
887
917 template <auto Member>
918 void fadeSoundFilterParameter(SoundInstanceID id, size_t filterSlotIndex, meta::member_pointer_target_type_t<Member> targetValue, Duration fadeDuration) {
919 fadeSoundFilterParameterImplementation(id, filterSlotIndex, meta::member_pointer_index_v<Member>, static_cast<float>(targetValue), fadeDuration);
920 }
921
944 template <auto Member>
945 void fadeGlobalFilterParameter(size_t filterSlotIndex, meta::member_pointer_target_type_t<Member> targetValue, Duration fadeDuration) {
946 fadeGlobalFilterParameterImplementation(filterSlotIndex, meta::member_pointer_index_v<Member>, static_cast<float>(targetValue), fadeDuration);
947 }
948
975 template <auto Member>
977 return getSoundFilterParameterImplementation(id, filterSlotIndex, meta::member_pointer_index_v<Member>);
978 }
979
1000 template <auto Member>
1001 [[nodiscard]] meta::member_pointer_target_type_t<Member> getGlobalFilterParameter(size_t filterSlotIndex) const {
1002 return getGlobalFilterParameterImplementation(filterSlotIndex, meta::member_pointer_index_v<Member>);
1003 }
1004
1015 [[nodiscard]] void* get() noexcept { // NOLINT(readability-make-member-function-const)
1016 return engine.get();
1017 }
1018
1029 [[nodiscard]] const void* get() const noexcept {
1030 return engine.get();
1031 }
1032
1033private:
1034 struct EngineDeleter {
1035 GREM_API(audio) void operator()(void* handle) const noexcept;
1036 };
1037
1038 GREM_API(audio) void setGlobalFilterImplementation(size_t filterSlotIndex, detail::Filter filter);
1039
1040 GREM_API(audio) void setSoundFilterParameterImplementation(SoundInstanceID id, size_t filterSlotIndex, size_t attributeIndex, float newValue);
1041 GREM_API(audio) void setGlobalFilterParameterImplementation(size_t filterSlotIndex, size_t attributeIndex, float newValue);
1042
1043 GREM_API(audio) void fadeSoundFilterParameterImplementation(SoundInstanceID id, size_t filterSlotIndex, size_t attributeIndex, float targetValue, Duration fadeDuration);
1044 GREM_API(audio) void fadeGlobalFilterParameterImplementation(size_t filterSlotIndex, size_t attributeIndex, float targetValue, Duration fadeDuration);
1045
1046 [[nodiscard]] GREM_API(audio) float getSoundFilterParameterImplementation(SoundInstanceID id, size_t filterSlotIndex, size_t attributeIndex) const;
1047 [[nodiscard]] GREM_API(audio) float getGlobalFilterParameterImplementation(size_t filterSlotIndex, size_t attributeIndex) const;
1048
1050 UniquePointer<detail::Filter[]> globalFilters{};
1051};
1052
1053} // namespace grem::audio
1054
1055#endif
Optional value type that holds either a value or no value.
Definition Optional.hpp:58
Definition Span.hpp:146
Generic nullable RAII resource handle with exclusive ownership of a resource that is automatically de...
Definition UniqueHandle.hpp:26
float getOutputVolume() const noexcept
Get the global master volume of the sound stage.
SoundInstanceID createPausedSoundInBackground(const Sound &sound, float volume=-1.0f)
Create a new sound instance without any panning, but don't start playing it yet.
void setStatisticsEnabled(bool newEnableStatistics)
Set whether to enable statistics gathering or not.
void setSoundFilterParameter(SoundInstanceID id, size_t filterSlotIndex, meta::member_pointer_target_type_t< Member > newValue)
Set a live parameter of an active filter at a particular filter slot of a sound instance in the sound...
Definition SoundStage.hpp:858
void pauseSound(SoundInstanceID id)
Pause a specific sound instance.
void setSoundVelocity(SoundInstanceID id, vec3 newVelocity)
Set the current 3D velocity of a specific sound instance.
Optional< Duration > getSoundTime(SoundInstanceID id) const
Get the current playback time point of a specific sound instance.
void seekToSoundTime(SoundInstanceID id, Duration timePointInSound)
Set the current playback time point of a specific sound instance.
void scheduleSoundStop(SoundInstanceID id, Duration timePointInSound)
Schedule for a specific sound instance to stop playing and remove itself when the playback reaches a ...
SoundInstanceID play3DSoundClocked(Duration time, const Sound &sound, vec3 position, vec3 velocity, float volume=-1.0f)
Create a new 3D sound instance and start playing it at a specific time relative to other sounds that ...
vec3 getOutputChannelSpeakerPosition(size_t outputChannelIndex) const noexcept
Get the listener-relative speaker position of an output audio channel.
void setOutputVolume(float newVolume)
Set the global master volume of the sound stage.
void setGlobalFilter(size_t filterSlotIndex, const F &newFilter)
Set the filter at a particular global filter slot of the sound stage.
Definition SoundStage.hpp:797
float getOutputChannelVolumeStatistics(size_t outputChannelIndex) const
Get an approximation of the volume of the audio currently playing through a specific channel of the s...
void update(const Listener &listener)
Update the 3D parameters of the sound stage.
void setSoundPositionAndVelocity(SoundInstanceID id, vec3 newPosition, vec3 newVelocity)
Set both the 3D position and 3D velocity of a specific sound instance at the same time.
void scheduleSoundPause(SoundInstanceID id, Duration timePointInSound)
Schedule for a specific sound instance to pause itself when the playback reaches a specific time poin...
size_t getMaxSimultaneousSounds() const noexcept
Get the maximum total number of sound instances that can play simultaneously.
void setGlobalFilterParameter(size_t filterSlotIndex, meta::member_pointer_target_type_t< Member > newValue)
Set a live parameter of an active filter at a particular global filter slot of the sound stage.
Definition SoundStage.hpp:884
void resumeSound(SoundInstanceID id)
Unpause and resume a specific sound instance.
void * get() noexcept
Get an opaque handle to the internal representation of the sound stage.
Definition SoundStage.hpp:1015
bool isSoundLooping(SoundInstanceID id) const noexcept
Check if a specific sound instance is set to repeat instead of stopping.
void stopSound(SoundInstanceID id) noexcept
Stop a specific sound instance and remove it.
void setSoundPlaybackSpeed(SoundInstanceID id, float newPlaybackSpeed)
Set the relative playback speed of a specific sound instance.
SoundStage(const SoundStageOptions &options={})
Construct a sound stage.
float getSpeedOfSound() const noexcept
Get the speed of sound in the sound stage.
void fadeSoundVolume(SoundInstanceID id, float targetVolume, Duration fadeDuration)
Fade the volume of a specific sound instance towards a target volume over a given duration.
void fadeSoundPlaybackSpeed(SoundInstanceID id, float targetPlaybackSpeed, Duration fadeDuration)
Fade the relative playback speed of a specific sound instance towards a target relative playback spee...
void fadeOutputVolume(float targetVolume, Duration fadeDuration)
Fade the global master volume of the sound stage towards a target volume over a given duration.
void fadeSoundFilterParameter(SoundInstanceID id, size_t filterSlotIndex, meta::member_pointer_target_type_t< Member > targetValue, Duration fadeDuration)
Fade a live parameter of an active filter at a particular filter slot of a sound instance in the soun...
Definition SoundStage.hpp:918
SoundInstanceID createPausedSound(const Sound &sound, float volume=-1.0f, Panning panning={})
Create a new relative sound instance, but don't start playing it yet.
void setSpeedOfSound(float newSpeedOfSound)
Set the speed of sound in the sound stage.
void setMaxSimultaneousSoundInstanceCount(size_t newMaxSimultaneousSoundInstanceCount)
Set the maximum total number of sound instances that can play simultaneously.
const void * get() const noexcept
Get an opaque handle to the internal representation of the sound stage.
Definition SoundStage.hpp:1029
void fadeGlobalFilterParameter(size_t filterSlotIndex, meta::member_pointer_target_type_t< Member > targetValue, Duration fadeDuration)
Fade a live parameter of an active filter at a particular global filter slot of the sound stage towar...
Definition SoundStage.hpp:945
void setSoundPanning(SoundInstanceID id, Panning newPanning)
Set the panning of a specific sound instance.
SoundInstanceID playSoundClocked(Duration time, const Sound &sound, float volume=-1.0f, Panning panning={})
Create a new 3D sound instance and start playing it at a specific time relative to other sounds that ...
SoundInstanceID play3DSound(const Sound &sound, vec3 position, vec3 velocity, float volume=-1.0f)
Create a new 3D sound instance and start playing it.
void setOutputChannelSpeakerPosition(size_t outputChannelIndex, vec3 newPosition)
Set the listener-relative speaker position of an output audio channel.
SoundInstanceID createPaused3DSound(const Sound &sound, vec3 position, vec3 velocity, float volume=-1.0f)
Create a new 3D sound instance, but don't start playing it yet.
void clearGlobalFilter(size_t filterSlotIndex) noexcept
Remove the filter at a particular global filter slot of the sound stage.
size_t getOutputChannelCount() const noexcept
Get the number of output audio channels.
SoundInstanceID playSoundInBackground(const Sound &sound, float volume=-1.0f)
Create a new sound instance without any panning and start playing it.
SoundInstanceID playSound(const Sound &sound, float volume=-1.0f, Panning panning={})
Create a new relative sound instance and start playing it.
Array< float, 256 > getOutputWaveStatistics() const
Get the sound wave currently playing through the sound stage.
meta::member_pointer_target_type_t< Member > getSoundFilterParameter(SoundInstanceID id, size_t filterSlotIndex) const
Get a live parameter of an active filter at a particular filter slot of a sound instance in the sound...
Definition SoundStage.hpp:976
Array< float, 256 > calculateOutputFastFourierTransformStatistics() const
Calculate the fast Fourier transform of the audio currently playing through the sound stage.
void setSoundPosition(SoundInstanceID id, vec3 newPosition)
Set the current 3D position of a specific sound instance.
void setSoundLooping(SoundInstanceID id, bool newLooping)
Set whether a specific sound instance should repeat or stop when it ends.
void setSoundVolume(SoundInstanceID id, float newVolume)
Set the volume of a specific sound instance.
meta::member_pointer_target_type_t< Member > getGlobalFilterParameter(size_t filterSlotIndex) const
Get a live parameter of an active filter at a particular global filter slot of the sound stage.
Definition SoundStage.hpp:1001
bool isSoundPaused(SoundInstanceID id) const noexcept
Check if a specific sound instance is currently paused.
bool isSoundStopped(SoundInstanceID id) const noexcept
Check if a specific sound instance has finished playing.
Container for a particular sound wave that can be played in a SoundStage.
Definition Sound.hpp:233
Concept that checks if a type is a valid sound filter type.
Definition filters.hpp:246
Definition concepts.hpp:187
Definition Error.hpp:12
constexpr size_t member_pointer_index_v
Index of the field referenced by a given pointer-to-member in its outer struct.
Definition metaprogramming.hpp:1988
typename member_pointer_target_type< Member >::type member_pointer_target_type_t
Target member type of a given pointer-to-member.
Definition metaprogramming.hpp:1938
constexpr float PI
Definition math.hpp:44
Clock::duration Duration
Definition Clock.hpp:25
GREM_ALWAYS_INLINE constexpr vec< N, T > GREM_VECTORCALL cos(vec< N, T > a)
Definition math.hpp:1389
GREM_ALWAYS_INLINE constexpr vec< N, T > GREM_VECTORCALL sin(vec< N, T > a)
Definition math.hpp:1393
vec< 3, float > vec3
Definition math.hpp:439
auto asBytes(Span< T, N > s) noexcept
Definition Span.hpp:359
Definition Array.hpp:20
Current state of the sound listener, i.e. the user perceiving the audio, within a SoundStage.
Definition Listener.hpp:20
Panning parameters for a listener-relative sound.
Definition SoundStage.hpp:31
float leftVolume
Left volume.
Definition SoundStage.hpp:47
float rightVolume
Right volume.
Definition SoundStage.hpp:48
static Panning fromNormalizedCenterOffset(float normalizedOffset)
Calculate left/right panning based on an offset from the center.
Definition SoundStage.hpp:40
Opaque handle to a specific instance of a sound or sound mix playing in a sound stage or sound mix.
Definition SoundInstanceID.hpp:23
Configuration options for a SoundStage.
Definition SoundStage.hpp:54
float speedOfSound
The speed of sound in the sound stage.
Definition SoundStage.hpp:81
float outputVolume
Global master output volume.
Definition SoundStage.hpp:69
bool enableStatistics
Whether to enable statistics gathering or not.
Definition SoundStage.hpp:109
size_t maxSimultaneousSoundInstanceCount
The maximum total number of sound instances that can play simultaneously.
Definition SoundStage.hpp:88
bool useRoundoff
Whether to use roundoff when clipping the audio samples sent to the output.
Definition SoundStage.hpp:100
size_t outputChannelCount
The number of output channels to produce audio for.
Definition SoundStage.hpp:60