sfxSystem.h

Engine/source/sfx/sfxSystem.h

More...

Classes:

class

This class provides access to the sound system.

class

SFXSystemPlugins are used to allow other subsystems hook into core functionality of the sound system.

Public Defines

define
SFX() ()

Less verbose macro for accessing the SFX singleton.

Public Enumerations

enum
SFXSystemEventType {
  SFXSystemEvent_Update 
  SFXSystemEvent_CreateDevice 
  SFXSystemEvent_DestroyDevice 
}

SFX system events that can be received notifications on.

Detailed Description

Public Defines

SFX() ()

Less verbose macro for accessing the SFX singleton.

This should be the prefered method for accessing the system.

Public Enumerations

SFXSystemEventType

Enumerator

SFXSystemEvent_Update

SFX is being updated.

SFXSystemEvent_CreateDevice

New SFXDevice has been created.

SFXSystemEvent_DestroyDevice

SFXDevice is about to be destroyed.

SFX system events that can be received notifications on.

  1
  2//-----------------------------------------------------------------------------
  3// Copyright (c) 2012 GarageGames, LLC
  4//
  5// Permission is hereby granted, free of charge, to any person obtaining a copy
  6// of this software and associated documentation files (the "Software"), to
  7// deal in the Software without restriction, including without limitation the
  8// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  9// sell copies of the Software, and to permit persons to whom the Software is
 10// furnished to do so, subject to the following conditions:
 11//
 12// The above copyright notice and this permission notice shall be included in
 13// all copies or substantial portions of the Software.
 14//
 15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 20// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 21// IN THE SOFTWARE.
 22//-----------------------------------------------------------------------------
 23
 24#ifndef _SFXSYSTEM_H_
 25#define _SFXSYSTEM_H_
 26
 27#ifndef _SFXCOMMON_H_
 28   #include "sfx/sfxCommon.h"
 29#endif
 30#ifndef _TSIGNAL_H_
 31   #include "core/util/tSignal.h"
 32#endif
 33#ifndef _TVECTOR_H_
 34   #include "core/util/tVector.h"
 35#endif
 36#ifndef _THREADSAFEREFCOUNT_H_
 37   #include "platform/threads/threadSafeRefCount.h"
 38#endif
 39
 40
 41class SFXTrack;
 42class SFXDevice;
 43class SFXProfile;
 44class SFXStream;
 45class SFXAmbience;
 46class SFXSoundscapeManager;
 47class SFXSource;
 48class SFXSound;
 49class SFXBuffer;
 50class SFXDescription;
 51
 52
 53/// SFX system events that can be received notifications on.
 54enum SFXSystemEventType
 55{
 56   /// SFX is being updated.
 57   SFXSystemEvent_Update,
 58   
 59   /// New SFXDevice has been created.
 60   SFXSystemEvent_CreateDevice,
 61   
 62   /// SFXDevice is about to be destroyed.
 63   SFXSystemEvent_DestroyDevice,
 64};
 65
 66/// SFXSystemPlugins are used to allow other subsystems hook into core functionality
 67/// of the sound system.
 68class SFXSystemPlugin
 69{
 70   public:
 71   
 72      ///
 73      virtual void update() {}
 74   
 75      ///
 76      virtual SFXSource* createSource( SFXTrack* track ) { return NULL; }
 77      
 78      /// Filter the given reverb setup before it is set up on the device.  This
 79      /// allows to, for example, modify the current reverb depending on listener
 80      /// location.
 81      virtual void filterReverb( SFXReverbProperties& reverb ) {}
 82};
 83
 84
 85/// This class provides access to the sound system.
 86///
 87/// There are a few script preferences that are used by
 88/// the sound providers.
 89///
 90///   $pref::SFX::frequency - This is the playback frequency
 91///   for the primary sound buffer used for mixing.  Although
 92///   most providers will reformat on the fly, for best quality
 93///   and performance match your sound files to this setting.
 94///
 95///   $pref::SFX::bitrate - This is the playback bitrate for
 96///   the primary sound buffer used for mixing.  Although most
 97///   providers will reformat on the fly, for best quality
 98///   and performance match your sound files to this setting.
 99///
100class SFXSystem
101{
102      friend class SFXSound;           // _assignVoices
103      friend class SFXSource;          // _onAddSource, _onRemoveSource.
104      friend class SFXProfile;         // _createBuffer.
105
106   public:
107   
108      typedef Signal< void( SFXSystemEventType event ) > EventSignalType;
109      typedef Vector< SFXSource*> SFXSourceVector;
110      typedef Vector< SFXSound*> SFXSoundVector;
111      
112   protected:
113
114      /// The one and only instance of the SFXSystem.
115      static SFXSystem* smSingleton;
116
117      /// The protected constructor.
118      ///
119      /// @see SFXSystem::init()
120      ///
121      SFXSystem();
122
123      /// The non-virtual destructor.  You shouldn't
124      /// ever need to overload this class.
125      ~SFXSystem();
126
127      /// The current output sound device initialized
128      /// and ready to play back.
129      SFXDevice* mDevice;
130      
131      ///
132      SFXSoundVector mSounds;
133
134      /// This is used to keep track of play once sources
135      /// that must be released when they stop playing.
136      SFXSourceVector mPlayOnceSources;
137            
138      /// The last time the sources got an update.
139      U32 mLastSourceUpdateTime;
140      
141      ///
142      U32 mLastAmbientUpdateTime;
143      
144      ///
145      U32 mLastParameterUpdateTime;
146
147      /// The distance model used for rolloff curve computation on 3D sounds.
148      SFXDistanceModel mDistanceModel;
149      
150      /// The current doppler scale factor.
151      F32 mDopplerFactor;
152      
153      /// The current curve rolloff factor.
154      F32 mRolloffFactor;
155            
156      /// The current position and orientation of all listeners.
157      Vector< SFXListenerProperties> mListeners;
158      
159      /// Current global reverb properties.
160      SFXReverbProperties mReverb;
161      
162      /// SFX system event signal.
163      EventSignalType mEventSignal;
164            
165      /// Ambient soundscape manager.
166      SFXSoundscapeManager* mSoundscapeMgr;
167      
168      /// List of plugins currently linked to the SFX system.
169      Vector< SFXSystemPlugin*> mPlugins;
170
171      /// @name Stats
172      ///
173      /// Stats reported back to the console for tracking performance.
174      ///
175      /// @{
176
177      S32 mStatNumSources;
178      S32 mStatNumSounds;
179      S32 mStatNumPlaying;
180      S32 mStatNumCulled;
181      S32 mStatNumVoices;
182      S32 mStatSourceUpdateTime;
183      S32 mStatParameterUpdateTime;
184      S32 mStatAmbientUpdateTime;
185
186      /// @}
187
188      /// Called to reprioritize and reassign buffers as
189      /// sources change state, volumes are adjusted, and 
190      /// the listener moves around.
191      ///
192      /// @see SFXSource::_update()
193      ///
194      void _updateSources();
195
196      /// This called to reprioritize and reassign
197      /// voices to sources.
198      void _assignVoices();
199      
200      ///
201      void _assignVoice( SFXSound* sound );
202
203      ///
204      void _sortSounds( const SFXListenerProperties& listener );
205
206      /// Called from SFXSource::onAdd to register the source.
207      void _onAddSource( SFXSource* source );
208                       
209      /// Called from SFXSource::onRemove to unregister the source.
210      void _onRemoveSource( SFXSource* source );
211
212      /// Called from SFXProfile to create a device specific
213      /// sound buffer used in conjunction with a voice in playback.
214      SFXBuffer* _createBuffer( const ThreadSafeRef< SFXStream>& stream, SFXDescription* description );
215      
216      /// Load file directly through SFXDevice.  Depends on
217      /// availability with selected SFXDevice.
218      ///
219      /// @return Return new buffer or NULL.
220      SFXBuffer* _createBuffer( const String& filename, SFXDescription* description );
221      
222      ///
223      SFXDevice* _getDevice() const { return mDevice; }
224
225   public:
226
227      /// Returns the one an only instance of the SFXSystem 
228      /// unless it hasn't been initialized or its been disabled
229      /// in your build.
230      ///
231      /// For convienence you can use the SFX-> macro as well.
232      ///
233      /// @see SFXSystem::init()
234      /// @see SFX
235      static SFXSystem* getSingleton() { return smSingleton; }
236
237      /// This is called from initialization to prepare the
238      /// sound system singleton.  This also includes registering
239      /// common resource types and initializing available sound
240      /// providers.
241      static void init();
242
243      /// This is called after Sim::shutdown() in shutdownLibraries()
244      /// to free the sound system singlton.  After this the SFX
245      /// singleton is null and any call to it will crash.
246      static void destroy();
247
248      /// This is only public so that it can be called by 
249      /// the game update loop.  It updates the current 
250      /// device and all sources.
251      void _update();
252      
253      /// Register the given plugin with the system.
254      void addPlugin( SFXSystemPlugin* plugin );
255      
256      /// Unregister the given plugin with the system.
257      void removePlugin( SFXSystemPlugin* plugin );
258      
259      /// @name Device Management
260      /// @{
261
262      /// This initializes a new device.
263      ///
264      /// @param providerName    The name of the provider.
265      /// @param deviceName      The name of the provider device.
266      /// @param useHardware     Toggles the use of hardware processing when available.
267      /// @param maxBuffers      The maximum buffers for this device to use or -1 
268      ///                        for the device to pick its own reasonable default.
269      /// @param changeDevice    Allows this to change the current device to a new one
270      /// @return Returns true if the device was created.
271      bool createDevice(   const String& providerName, 
272                           const String& deviceName, 
273                           bool useHardware,
274                           S32 maxBuffers,
275                           bool changeDevice = false);
276
277      /// Returns the current device information or NULL if no
278      /// device is present.  The information string is in the
279      /// following format:
280      /// 
281      /// Provider Name\tDevice Name\tUse Hardware\tMax Buffers
282      String getDeviceInfoString();
283
284      /// This destroys the current device.  All sources loose their
285      /// playback buffers, but otherwise continue to function.
286      void deleteDevice();
287
288      /// Returns true if a device is allocated.
289      bool hasDevice() const { return mDevice != NULL; }
290      
291      /// @}
292      
293      /// @name Source Creation
294      /// @{
295
296      /// Used to create new sound sources from a sound profile.  The
297      /// returned source is in a stopped state and ready for playback.
298      /// Use the SFX_DELETE macro to free the source when your done.
299      ///
300      /// @note The track must have at least the same lifetime as the
301      ///   source.  If the description disappears while the source is still
302      ///   there, the source will go with it.
303      ///
304      /// @param profile   The sound profile for the created source.
305      /// @param transform The optional transform if creating a 3D source.
306      /// @param velocity  The optional doppler velocity if creating a 3D source.
307      ///
308      /// @return The sound source or NULL if an error occured.
309      SFXSource* createSource(  SFXTrack* track, 
310                                const MatrixF* transform = NULL, 
311                                const VectorF* velocity = NULL );
312
313      /// Used to create a streaming sound source from a user supplied
314      /// stream object.  
315      ///
316      /// It is only intended for memory based streams.  For sound file
317      /// streaming use createSource() with a streaming SFXProfile.
318      ///
319      /// Use the SFX_DELETE macro to free the source when your done.
320      ///
321      /// @note The description must have at least the same lifetime as the
322      ///   sound.  If the description disappears while the source is still
323      ///   there, the sound will go with it.
324      ///
325      /// @param stream    The stream used to create the sound buffer.  It
326      ///                  must exist for the lifetime of the source and will
327      ///                  have its reference count decremented when the source
328      ///                  is destroyed.
329      ///
330      /// @param description  The sound description to apply to the source.
331      ///
332      /// @return The sound source or NULL if an error occured.
333      SFXSound* createSourceFromStream(   const ThreadSafeRef< SFXStream>& stream,
334                                          SFXDescription* description );
335
336      /// Creates a source which when it finishes playing will auto delete
337      /// itself.  Be aware that the returned SFXSource pointer should only
338      /// be used for error checking or immediate setting changes.  It may
339      /// be deleted as soon as the next system tick.
340      ///
341      /// @param profile   The sound profile for the created source.
342      /// @param transform The optional transform if creating a 3D source.
343      /// @param velocity  The optional doppler velocity if creating a 3D source.
344      ///
345      /// @return The sound source or NULL if an error occured.
346      SFXSource* playOnce( SFXTrack* track, 
347                           const MatrixF* transform = NULL,
348                           const VectorF* velocity = NULL,
349                           F32 fadeInTime = -1.f );
350      SFXSource* playOnce( SFXProfile* profile,
351                           const MatrixF* transform = NULL,
352                           const VectorF* velocity = NULL,
353                           F32 fadeInTime = -1.f )
354      { // Avoids having to require inclusion of sfxProfile.h
355         return playOnce( ( SFXTrack* ) profile, transform, velocity, fadeInTime );
356      }
357      
358      /// Stop the source and delete it.  This method will take care of
359      /// the fade-out time that the source may need before it will actually
360      /// stop and may be deleted.
361      void stopAndDeleteSource( SFXSource* source );
362      
363      /// Mark source for deletion when it is moving into stopped state.
364      /// This method is useful to basically make a source a play-once source
365      /// after the fact.
366      void deleteWhenStopped( SFXSource* source );
367      
368      /// @}
369            
370      /// @}
371      
372      /// @name Listeners
373      /// @{
374
375      /// Return the number of listeners currently configured.
376      U32 getNumListeners() const { return mListeners.size(); }
377      
378      /// Set the number of concurrent listeners.
379      /// @note It depends on the selected device if more than one listener is actually supported.
380      void setNumListeners( U32 num );
381
382      /// Set the property of the given listener.
383      const SFXListenerProperties& getListener( U32 index = 0 ) const { return mListeners[ index ]; }
384      
385      /// Set the 3D attributes of the given listener.
386      void setListener( U32 index, const MatrixF& transform, const Point3F& velocity );
387      void setListener( U32 index, const SFXListenerProperties& properties )
388      {
389         setListener( index, properties.getTransform(), properties.getVelocity() );
390      }
391      
392      /// @}
393      
394      /// @name 3D Sound Configuration
395      /// {
396      
397      /// Return the curve model currently used distance attenuation of positional sounds.
398      SFXDistanceModel getDistanceModel() const { return mDistanceModel; }
399      
400      ///
401      void setDistanceModel( SFXDistanceModel model );
402      
403      ///
404      F32 getDopplerFactor() const { return mDopplerFactor; }
405      
406      ///
407      void setDopplerFactor( F32 factor );
408      
409      ///
410      F32 getRolloffFactor() const { return mRolloffFactor; }
411      
412      ///
413      void setRolloffFactor( F32 factor );
414      
415      ///
416      const SFXReverbProperties& getReverb() const { return mReverb; }
417      
418      ///
419      void setReverb( const SFXReverbProperties& reverb );
420      
421      /// @}
422      
423      ///
424      SFXSoundscapeManager* getSoundscapeManager() const { return mSoundscapeMgr; }
425      
426      /// Dump information about all current SFXSources to the console or
427      /// to the given StringBuilder.
428      void dumpSources( StringBuilder* toString = NULL, bool excludeGroups = true );
429      
430      /// Return the SFX system event signal.
431      EventSignalType& getEventSignal() { return mEventSignal; }
432      
433      /// Notify the SFX system that the given description has changed.
434      /// All sources currently using the description will be updated.
435      void notifyDescriptionChanged( SFXDescription* description);
436      
437      ///
438      void notifyTrackChanged( SFXTrack* track );
439};
440
441
442/// Less verbose macro for accessing the SFX singleton.  This
443/// should be the prefered method for accessing the system.
444///
445/// @see SFXSystem
446/// @see SFXSystem::getSingleton()
447///
448#define SFX SFXSystem::getSingleton()
449
450
451#endif // _SFXSYSTEM_H_
452