2
0

sfxSystem.cpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "sfx/sfxSystem.h"
  24. #include "sfx/sfxProvider.h"
  25. #include "sfx/sfxDevice.h"
  26. #include "sfx/sfxInternal.h"
  27. #include "sfx/sfxSource.h"
  28. #include "sfx/sfxProfile.h"
  29. #include "sfx/sfxDescription.h"
  30. #include "sfx/sfxTrack.h"
  31. #include "sfx/sfxPlayList.h"
  32. #include "sfx/sfxSound.h"
  33. #include "sfx/sfxController.h"
  34. #include "sfx/sfxSoundscape.h"
  35. #include "console/console.h"
  36. #include "console/engineAPI.h"
  37. #include "T3D/gameBase/processList.h"
  38. #include "platform/profiler.h"
  39. #include "platform/platformTimer.h"
  40. #include "core/util/autoPtr.h"
  41. #include "core/module.h"
  42. MODULE_BEGIN( SFX )
  43. MODULE_INIT_BEFORE( Sim )
  44. MODULE_SHUTDOWN_BEFORE( Sim ) // Make sure all SimObjects disappear in time.
  45. MODULE_INIT
  46. {
  47. SFXSystem::init();
  48. }
  49. MODULE_SHUTDOWN
  50. {
  51. SFXSystem::destroy();
  52. }
  53. MODULE_END;
  54. SFXSystem* SFXSystem::smSingleton = NULL;
  55. /// Default SFXAmbience used to reset the global soundscape.
  56. SFXAmbience *sDefaultAmbience;
  57. // Excludes Null and Blocked as these are not passed out to the control layer.
  58. ImplementEnumType( SFXStatus,
  59. "Playback status of sound source.\n"
  60. "@ingroup SFX" )
  61. { SFXStatusPlaying, "Playing",
  62. "The source is currently playing." },
  63. { SFXStatusStopped, "Stopped",
  64. "Playback of the source is stopped. When transitioning to Playing state, playback will start at the beginning "
  65. "of the source." },
  66. { SFXStatusPaused, "Paused",
  67. "Playback of the source is paused. Resuming playback will play from the current playback position." },
  68. EndImplementEnumType;
  69. ImplementEnumType( SFXDistanceModel,
  70. "Type of volume distance attenuation curve.\n"
  71. "The distance model determines the falloff curve applied to the volume of 3D sounds over distance.\n\n"
  72. "@ref SFXSource_volume\n\n"
  73. "@ref SFX_3d\n\n"
  74. "@ingroup SFX" )
  75. { SFXDistanceModelLinear, "Linear",
  76. "Volume attenuates linearly from the references distance onwards to max distance where it reaches zero." },
  77. { SFXDistanceModelLogarithmic, "Logarithmic",
  78. "Volume attenuates logarithmically starting from the reference distance and halving every reference distance step from there on. "
  79. "Attenuation stops at max distance but volume won't reach zero." },
  80. { SFXDistanceModelExponent, "Exponential",
  81. "Volume attenuates exponentially starting from the reference distance and attenuating every reference distance step by the rolloff factor. "
  82. "Attenuation stops at max distance but volume won't reach zero." },
  83. EndImplementEnumType;
  84. ImplementEnumType( SFXChannel,
  85. "Channels are individual properties of sound sources that may be animated over time.\n\n"
  86. "@see SFXParameter\n\n"
  87. "@ref SFX_interactive\n\n"
  88. "@ingroup SFX" )
  89. { SFXChannelVolume, "Volume",
  90. "Channel controls volume level of attached sound sources.\n"
  91. "@see SFXDescription::volume" },
  92. { SFXChannelPitch, "Pitch",
  93. "Channel controls pitch of attached sound sources.\n"
  94. "@see SFXDescription::pitch" },
  95. { SFXChannelPriority, "Priority",
  96. "Channel controls virtualizaton priority level of attached sound sources.\n"
  97. "@see SFXDescription::priority" },
  98. { SFXChannelPositionX, "PositionX",
  99. "Channel controls X coordinate of 3D sound position of attached sources." },
  100. { SFXChannelPositionY, "PositionY",
  101. "Channel controls Y coordinate of 3D sound position of attached sources." },
  102. { SFXChannelPositionZ, "PositionZ",
  103. "Channel controls Z coordinate of 3D sound position of attached sources." },
  104. { SFXChannelRotationX, "RotationX",
  105. "Channel controls X rotation (in degrees) of 3D sound orientation of attached sources." },
  106. { SFXChannelRotationY, "RotationY",
  107. "Channel controls Y rotation (in degrees) of 3D sound orientation of attached sources." },
  108. { SFXChannelRotationZ, "RotationZ",
  109. "Channel controls Z rotation (in degrees) of 3D sound orientation of attached sources." },
  110. { SFXChannelVelocityX, "VelocityX",
  111. "Channel controls X coordinate of 3D sound velocity vector of attached sources." },
  112. { SFXChannelVelocityY, "VelocityY",
  113. "Channel controls Y coordinate of 3D sound velocity vector of attached sources." },
  114. { SFXChannelVelocityZ, "VelocityZ",
  115. "Channel controls Z coordinate of 3D sound velocity vector of attached sources." },
  116. { SFXChannelMinDistance, "ReferenceDistance",
  117. "Channel controls reference distance of 3D sound of attached sources.\n"
  118. "@see SFXDescription::referenceDistance" },
  119. { SFXChannelMaxDistance, "MaxDistance",
  120. "Channel controls max volume attenuation distance of 3D sound of attached sources.\n"
  121. "@see SFXDescription::maxDistance" },
  122. { SFXChannelConeInsideAngle, "ConeInsideAngle",
  123. "Channel controls angle (in degrees) of 3D sound inner volume cone of attached sources.\n"
  124. "@see SFXDescription::coneInsideAngle" },
  125. { SFXChannelConeOutsideAngle, "ConeOutsideAngle",
  126. "Channel controls angle (in degrees) of 3D sound outer volume cone of attached sources.\n"
  127. "@see SFXDescription::coneOutsideAngle" },
  128. { SFXChannelConeOutsideVolume, "ConeOutsideVolume",
  129. "Channel controls volume outside of 3D sound outer cone of attached sources.\n"
  130. "@see SFXDescription::coneOutsideVolume" },
  131. { SFXChannelCursor, "Cursor",
  132. "Channel controls playback cursor of attached sound sources.\n\n"
  133. "@note Be aware that different types of sound sources interpret play cursor positions differently "
  134. "or do not actually have play cursors (these sources will ignore the channel)." },
  135. { SFXChannelStatus, "Status",
  136. "Channel controls playback status of attached sound sources.\n\n"
  137. "The channel's value is rounded down to the nearest integer and interpreted in the following way:\n"
  138. "- 1: Play\n"
  139. "- 2: Stop\n"
  140. "- 3: Pause\n\n" },
  141. { SFXChannelUser0, "User0",
  142. "Channel available for custom use. By default ignored by sources.\n\n"
  143. "@see SFXSource::onParameterValueChange" },
  144. { SFXChannelUser1, "User1",
  145. "Channel available for custom use. By default ignored by sources.\n\n"
  146. "@see SFXSource::onParameterValueChange" },
  147. { SFXChannelUser2, "User2",
  148. "Channel available for custom use. By default ignored by sources.\n\n"
  149. "@see SFXSource::onParameterValueChange" },
  150. { SFXChannelUser3, "User3",
  151. "Channel available for custom use. By default ignored by sources.\n\n"
  152. "@see SFXSource::onParameterValueChange" },
  153. EndImplementEnumType;
  154. // Constants.
  155. static const U32 sDeviceCapsReverb = SFXDevice::CAPS_Reverb;
  156. static const U32 sDeviceCapsVoiceManagement = SFXDevice::CAPS_VoiceManagement;
  157. static const U32 sDeviceCapsOcclusion = SFXDevice::CAPS_Occlusion;
  158. static const U32 sDeviceCapsDSPEffects = SFXDevice::CAPS_DSPEffects;
  159. static const U32 sDeviceCapsMultiListener = SFXDevice::CAPS_MultiListener;
  160. static const U32 sDeviceInfoProvider = 0;
  161. static const U32 sDeviceInfoName = 1;
  162. static const U32 sDeviceInfoUseHardware = 2;
  163. static const U32 sDeviceInfoMaxBuffers = 3;
  164. //-----------------------------------------------------------------------------
  165. SFXSystem::SFXSystem()
  166. : mDevice( NULL ),
  167. mLastSourceUpdateTime( 0 ),
  168. mLastAmbientUpdateTime( 0 ),
  169. mLastParameterUpdateTime( 0 ),
  170. mStatNumSources( 0 ),
  171. mStatNumSounds( 0 ),
  172. mStatNumPlaying( 0 ),
  173. mStatNumCulled( 0 ),
  174. mStatNumVoices( 0 ),
  175. mStatSourceUpdateTime( 0 ),
  176. mStatParameterUpdateTime( 0 ),
  177. mDistanceModel( SFXDistanceModelLinear ),
  178. mStatAmbientUpdateTime( 0 ),
  179. mDopplerFactor( 0.5 ),
  180. mRolloffFactor( 1.0 ),
  181. mSoundscapeMgr( NULL )
  182. {
  183. VECTOR_SET_ASSOCIATION( mSounds );
  184. VECTOR_SET_ASSOCIATION( mPlayOnceSources );
  185. VECTOR_SET_ASSOCIATION( mPlugins );
  186. VECTOR_SET_ASSOCIATION( mListeners );
  187. // Always at least one listener.
  188. mListeners.increment();
  189. // Register stat variables.
  190. Con::addVariable( "SFX::numSources", TypeS32, &mStatNumSources,
  191. "Number of SFXSource type objects that are currently instantiated.\n"
  192. "@ingroup SFX" );
  193. Con::addVariable( "SFX::numSounds", TypeS32, &mStatNumSounds,
  194. "Number of SFXSound type objects (i.e. actual single-file sounds) that are currently instantiated.\n"
  195. "@ingroup SFX" );
  196. Con::addVariable( "SFX::numPlaying", TypeS32, &mStatNumPlaying,
  197. "Number of SFXSources that are currently in playing state.\n"
  198. "@ingroup SFX" );
  199. Con::addVariable( "SFX::numCulled", TypeS32, &mStatNumCulled,
  200. "Number of SFXSounds that are currently in virtualized playback mode.\n"
  201. "@ref SFXSound_virtualization\n\n"
  202. "@ingroup SFX" );
  203. Con::addVariable( "SFX::numVoices", TypeS32, &mStatNumVoices,
  204. "Number of voices that are currently allocated on the sound device.\n"
  205. "@ingroup SFX" );
  206. Con::addVariable( "SFX::sourceUpdateTime", TypeS32, &mStatSourceUpdateTime,
  207. "Milliseconds spent on the last SFXSource update loop.\n"
  208. "@ref SFX_updating\n\n"
  209. "@ingroup SFX" );
  210. Con::addVariable( "SFX::parameterUpdateTime", TypeS32, &mStatParameterUpdateTime,
  211. "Milliseconds spent on the last SFXParameter update loop.\n"
  212. "@ref SFX_updating\n\n"
  213. "@ref SFX_interactive\n\n"
  214. "@ingroup SFX" );
  215. Con::addVariable( "SFX::ambientUpdateTime", TypeS32, &mStatAmbientUpdateTime,
  216. "Milliseconds spent on the last ambient audio update.\n"
  217. "@ref SFX_updating\n\n"
  218. "@ref SFX_ambient\n\n"
  219. "@ingroup SFX" );
  220. // Register constants.
  221. Con::addConstant( "$SFX::DEVICE_CAPS_REVERB", TypeS32, &sDeviceCapsReverb,
  222. "Sound device capability flag indicating that the sound device supports reverb.\n\n"
  223. "@see sfxGetDeviceInfo\n\n"
  224. "@ref SFX_reverb\n\n"
  225. "@ingroup SFX" );
  226. Con::addConstant( "$SFX::DEVICE_CAPS_VOICEMANAGEMENT", TypeS32, &sDeviceCapsVoiceManagement,
  227. "Sound device capability flag indicating that the sound device implements its own voice virtualization.\n\n"
  228. "For these devices, the sound system will deactivate its own voice management and leave voice "
  229. "virtualization entirely to the device.\n\n"
  230. "@see sfxGetDeviceInfo\n\n"
  231. "@ref SFXSound_virtualization\n\n"
  232. "@ingroup SFX" );
  233. Con::addConstant( "$SFX::DEVICE_CAPS_OCCLUSION", TypeS32, &sDeviceCapsOcclusion,
  234. "Sound device capability flag indicating that the sound device implements sound occlusion.\n\n"
  235. "@note This is not yet used by the sound system.\n\n"
  236. "@see sfxGetDeviceInfo\n\n"
  237. "@ingroup SFX" );
  238. Con::addConstant( "$SFX::DEVICE_CAPS_DSPEFFECTS", TypeS32, &sDeviceCapsDSPEffects,
  239. "Sound device capability flag indicating that the sound device supports adding DSP effect chains to sounds.\n\n"
  240. "@see sfxGetDeviceInfo\n\n"
  241. "@note This is not yet used by the sound system.\n\n"
  242. "@see sfxGetDeviceInfo\n\n"
  243. "@ingroup SFX" );
  244. Con::addConstant( "$SFX::DEVICE_CAPS_MULTILISTENER", TypeS32, &sDeviceCapsMultiListener,
  245. "Sound device capability flag indicating that the sound device supports multiple concurrent listeners.\n\n"
  246. "@see sfxGetDeviceInfo\n\n"
  247. "@ingroup SFX" );
  248. Con::addConstant( "$SFX::DEVICE_INFO_PROVIDER", TypeS32, &sDeviceInfoProvider,
  249. "Index of sound provider field in device info string.\n\n"
  250. "@see sfxGetDeviceInfo\n\n"
  251. "@see sfxGetAvailableDevices\n\n"
  252. "@ingroup SFX" );
  253. Con::addConstant( "$SFX::DEVICE_INFO_NAME", TypeS32, &sDeviceInfoName,
  254. "Index of device name field in device info string.\n\n"
  255. "@see sfxGetDeviceInfo\n\n"
  256. "@see sfxGetAvailableDevices\n\n"
  257. "@ingroup SFX" );
  258. Con::addConstant( "$SFX::DEVICE_INFO_USEHARDWARE", TypeS32, &sDeviceInfoUseHardware,
  259. "Index of use hardware flag in device info string.\n\n"
  260. "@see sfxGetDeviceInfo\n\n"
  261. "@see sfxGetAvailableDevices\n\n"
  262. "@ingroup SFX" );
  263. Con::addConstant( "$SFX::DEVICE_INFO_MAXBUFFERS", TypeS32, &sDeviceInfoMaxBuffers,
  264. "Index of buffer limit number in device info string.\n\n"
  265. "@see sfxGetDeviceInfo\n\n"
  266. "@see sfxGetAvailableDevices\n\n"
  267. "@ingroup SFX" );
  268. Con::addConstant( "$SFX::DEVICE_INFO_CAPS", TypeS32, &sDeviceInfoMaxBuffers,
  269. "Index of device capability flags in device info string.\n\n"
  270. "@see sfxGetDeviceInfo\n\n"
  271. "@see sfxGetAvailableDevices\n\n"
  272. "@ingroup SFX" );
  273. // Create subsystems.
  274. mSoundscapeMgr = new SFXSoundscapeManager();
  275. }
  276. //-----------------------------------------------------------------------------
  277. SFXSystem::~SFXSystem()
  278. {
  279. // Unregister stat variables.
  280. Con::removeVariable( "SFX::numSources" );
  281. Con::removeVariable( "SFX::numSounds" );
  282. Con::removeVariable( "SFX::numPlaying" );
  283. Con::removeVariable( "SFX::numCulled" );
  284. Con::removeVariable( "SFX::numVoices" );
  285. Con::removeVariable( "SFX::sourceUpdateTime" );
  286. Con::removeVariable( "SFX::parameterUpdateTime" );
  287. Con::removeVariable( "SFX::ambientUpdateTime" );
  288. // Cleanup any remaining sources.
  289. if( Sim::getSFXSourceSet() )
  290. Sim::getSFXSourceSet()->deleteAllObjects();
  291. mSounds.clear();
  292. mPlayOnceSources.clear();
  293. mListeners.clear();
  294. // Delete subsystems.
  295. if( mSoundscapeMgr )
  296. SAFE_DELETE( mSoundscapeMgr );
  297. // Delete device if we still have one.
  298. deleteDevice();
  299. }
  300. //-----------------------------------------------------------------------------
  301. void SFXSystem::init()
  302. {
  303. AssertWarn( smSingleton == NULL, "SFX has already been initialized!" );
  304. SFXProvider::initializeAllProviders();
  305. // Create the stream thread pool.
  306. SFXInternal::SFXThreadPool::createSingleton();
  307. // Note: If you have provider specific file types you should
  308. // register them in the provider initialization.
  309. // Create the system.
  310. smSingleton = new SFXSystem();
  311. sDefaultAmbience = new SFXAmbience();
  312. }
  313. //-----------------------------------------------------------------------------
  314. void SFXSystem::destroy()
  315. {
  316. AssertWarn( smSingleton != NULL, "SFX has not been initialized!" );
  317. delete smSingleton;
  318. smSingleton = NULL;
  319. // Destroy the stream thread pool
  320. SFXInternal::SFXThreadPool::deleteSingleton();
  321. delete(sDefaultAmbience);
  322. }
  323. //-----------------------------------------------------------------------------
  324. void SFXSystem::addPlugin( SFXSystemPlugin* plugin )
  325. {
  326. for( U32 i = 0; i < mPlugins.size(); ++ i )
  327. AssertFatal( mPlugins[ i ] != plugin, "SFXSystem::addPlugin - plugin already added to the system!" );
  328. mPlugins.push_back( plugin );
  329. }
  330. //-----------------------------------------------------------------------------
  331. void SFXSystem::removePlugin( SFXSystemPlugin* plugin )
  332. {
  333. for( U32 i = 0; i < mPlugins.size(); ++ i )
  334. if( mPlugins[ i ] == plugin )
  335. {
  336. mPlugins.erase_fast( i );
  337. break;
  338. }
  339. }
  340. //-----------------------------------------------------------------------------
  341. bool SFXSystem::createDevice( const String& providerName, const String& deviceName, bool useHardware, S32 maxBuffers, bool changeDevice )
  342. {
  343. // Make sure we don't have a device already.
  344. if( mDevice && !changeDevice )
  345. return false;
  346. // Lookup the provider.
  347. SFXProvider* provider = SFXProvider::findProvider( providerName );
  348. if( !provider )
  349. return false;
  350. // If we have already created this device and are using it then no need to do anything.
  351. if( mDevice
  352. && providerName.equal( mDevice->getProvider()->getName(), String::NoCase )
  353. && deviceName.equal( mDevice->getName(), String::NoCase )
  354. && useHardware == mDevice->getUseHardware() )
  355. return true;
  356. // If we have an existing device remove it.
  357. if( mDevice )
  358. deleteDevice();
  359. // Create the new device..
  360. mDevice = provider->createDevice( deviceName, useHardware, maxBuffers );
  361. if( !mDevice )
  362. {
  363. Con::errorf( "SFXSystem::createDevice - failed creating %s device '%s'", providerName.c_str(), deviceName.c_str() );
  364. return false;
  365. }
  366. // Print capabilities.
  367. Con::printf( "SFXSystem::createDevice - created %s device '%s'", providerName.c_str(), deviceName.c_str() );
  368. if( mDevice->getCaps() & SFXDevice::CAPS_Reverb )
  369. Con::printf( " CAPS_Reverb" );
  370. if( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement )
  371. Con::printf( " CAPS_VoiceManagement" );
  372. if( mDevice->getCaps() & SFXDevice::CAPS_Occlusion )
  373. Con::printf( "\tCAPS_Occlusion" );
  374. if( mDevice->getCaps() & SFXDevice::CAPS_MultiListener )
  375. Con::printf( "\tCAPS_MultiListener" );
  376. // Set defaults.
  377. mDevice->setNumListeners( getNumListeners() );
  378. mDevice->setDistanceModel( mDistanceModel );
  379. mDevice->setDopplerFactor( mDopplerFactor );
  380. mDevice->setRolloffFactor( mRolloffFactor );
  381. //OpenAL requires slots for effects, this creates an empty function
  382. //that will run when a sfxdevice is created.
  383. mDevice->openSlots();
  384. mDevice->setReverb( mReverb );
  385. // Signal system.
  386. getEventSignal().trigger( SFXSystemEvent_CreateDevice );
  387. return true;
  388. }
  389. //-----------------------------------------------------------------------------
  390. String SFXSystem::getDeviceInfoString()
  391. {
  392. // Make sure we have a valid device.
  393. if( !mDevice )
  394. return String();
  395. return String::ToString( "%s\t%s\t%s\t%d\t%d",
  396. mDevice->getProvider()->getName().c_str(),
  397. mDevice->getName().c_str(),
  398. mDevice->getUseHardware() ? "1" : "0",
  399. mDevice->getMaxBuffers(),
  400. mDevice->getCaps() );
  401. }
  402. //-----------------------------------------------------------------------------
  403. void SFXSystem::deleteDevice()
  404. {
  405. // Make sure we have a valid device.
  406. if ( !mDevice )
  407. return;
  408. // Put all playing sounds into virtualized playback mode. Where this fails,
  409. // stop the source.
  410. for( U32 i = 0; i < mSounds.size(); ++ i )
  411. {
  412. SFXSound* sound = mSounds[ i ];
  413. if( sound->hasVoice() && !sound->_releaseVoice() )
  414. sound->stop();
  415. }
  416. // Signal everyone who cares that the
  417. // device is being deleted.
  418. getEventSignal().trigger( SFXSystemEvent_DestroyDevice );
  419. // Free the device which should delete all
  420. // the active voices and buffers.
  421. delete mDevice;
  422. mDevice = NULL;
  423. }
  424. //-----------------------------------------------------------------------------
  425. SFXSource* SFXSystem::createSource( SFXTrack* track,
  426. const MatrixF* transform,
  427. const VectorF* velocity )
  428. {
  429. if( !track )
  430. return NULL;
  431. SFXSource* source = NULL;
  432. // Try creating through a plugin first so that they
  433. // always get the first shot and may override our
  434. // logic here.
  435. for( U32 i = 0; !source && i < mPlugins.size(); ++ i )
  436. source = mPlugins[ i ]->createSource( track );
  437. // If that failed, try our own logic using the track
  438. // types that we know about.
  439. if( !source )
  440. {
  441. if( !mDevice )
  442. {
  443. Con::errorf( "SFXSystem::createSource() - no device initialized!" );
  444. return NULL;
  445. }
  446. if( dynamic_cast< SFXPlayList* >( track ) )
  447. {
  448. // Create a playback controller for the track.
  449. SFXPlayList* playList = static_cast< SFXPlayList* >( track );
  450. source = SFXController::_create( playList );
  451. }
  452. else if( dynamic_cast< SFXProfile* >( track ) )
  453. {
  454. // Create a sound.
  455. SFXProfile* profile = static_cast< SFXProfile* >( track );
  456. source = SFXSound::_create( mDevice, profile );
  457. if( !source )
  458. {
  459. Con::errorf(
  460. "SFXSystem::createSource() - Failed to create sound!\n"
  461. " Profile: %s\n"
  462. " Filename: %s",
  463. profile->getName(),
  464. profile->getSoundFileName().c_str() );
  465. }
  466. }
  467. else
  468. {
  469. Con::errorf( "SFXSystem::createSource - cannot create source for %i (%s) of type '%s'",
  470. track->getId(), track->getName(), track->getClassName() );
  471. Con::errorf( "SFXSystem::createSource - maybe you are using the wrong SFX provider for this type of track" );
  472. return NULL;
  473. }
  474. }
  475. if( source )
  476. {
  477. if( transform )
  478. source->setTransform( *transform );
  479. if( velocity )
  480. source->setVelocity( *velocity );
  481. }
  482. return source;
  483. }
  484. //-----------------------------------------------------------------------------
  485. SFXSound* SFXSystem::createSourceFromStream( const ThreadSafeRef< SFXStream >& stream,
  486. SFXDescription* description )
  487. {
  488. AssertFatal( mDevice, "SFXSystem::createSourceFromStream() - no device initialized!" );
  489. // We sometimes get null values from script... fail in that case.
  490. if( !stream || !description )
  491. return NULL;
  492. // Create the sound.
  493. SFXSound* sound = SFXSound::_create( mDevice, stream, description );
  494. if( !sound )
  495. return NULL;
  496. return sound;
  497. }
  498. //-----------------------------------------------------------------------------
  499. void SFXSystem::stopAndDeleteSource( SFXSource* source )
  500. {
  501. if( source->getFadeOutTime() > 0.f )
  502. {
  503. // Fade-out. Stop and put on play-once list to
  504. // ensure deletion when the source actually stops.
  505. source->stop();
  506. deleteWhenStopped( source );
  507. }
  508. else
  509. {
  510. // No fade-out. Just stop and delete the source.
  511. source->stop();
  512. SFX_DELETE( source );
  513. }
  514. }
  515. //-----------------------------------------------------------------------------
  516. void SFXSystem::deleteWhenStopped( SFXSource* source )
  517. {
  518. // If the source isn't already on the play-once source list,
  519. // put it there now.
  520. Vector< SFXSource* >::iterator iter = T3D::find( mPlayOnceSources.begin(), mPlayOnceSources.end(), source );
  521. if( iter == mPlayOnceSources.end() )
  522. mPlayOnceSources.push_back( source );
  523. }
  524. //-----------------------------------------------------------------------------
  525. void SFXSystem::_onAddSource( SFXSource* source )
  526. {
  527. if( dynamic_cast< SFXSound* >( source ) )
  528. {
  529. SFXSound* sound = static_cast< SFXSound* >( source );
  530. mSounds.push_back( sound );
  531. mStatNumSounds = mSounds.size();
  532. }
  533. // Update the stats.
  534. mStatNumSources ++;
  535. }
  536. //-----------------------------------------------------------------------------
  537. void SFXSystem::_onRemoveSource( SFXSource* source )
  538. {
  539. // Check if it was a play once source.
  540. Vector< SFXSource* >::iterator sourceIter = T3D::find( mPlayOnceSources.begin(), mPlayOnceSources.end(), source );
  541. if (sourceIter != mPlayOnceSources.end() )
  542. mPlayOnceSources.erase_fast(sourceIter);
  543. // Update the stats.
  544. mStatNumSources --;
  545. if( dynamic_cast< SFXSound* >( source ) )
  546. {
  547. SFXSoundVector::iterator vectorIter = T3D::find( mSounds.begin(), mSounds.end(), static_cast< SFXSound* >( source ) );
  548. if(vectorIter != mSounds.end() )
  549. mSounds.erase_fast(vectorIter);
  550. mStatNumSounds = mSounds.size();
  551. }
  552. }
  553. //-----------------------------------------------------------------------------
  554. SFXBuffer* SFXSystem::_createBuffer( const ThreadSafeRef< SFXStream >& stream, SFXDescription* description )
  555. {
  556. // The buffers are created by the active
  557. // device... without one we cannot do anything.
  558. if ( !mDevice )
  559. {
  560. Con::errorf( "SFXSystem::_createBuffer - No sound device initialized!!" );
  561. return NULL;
  562. }
  563. // Some sanity checking for streaming. If the stream isn't at least three packets
  564. // in size given the current settings in "description", then turn off streaming.
  565. // The device code *will* mess up if the stream input fails to match certain metrics.
  566. // Just disabling streaming when it doesn't make sense is easier than complicating the
  567. // device logic to account for bad metrics.
  568. bool streamFlag = description->mIsStreaming;
  569. if( description->mIsStreaming
  570. && stream->getDuration() < description->mStreamPacketSize * 1000 * SFXInternal::SFXAsyncQueue::DEFAULT_STREAM_QUEUE_LENGTH )
  571. description->mIsStreaming = false;
  572. SFXBuffer* buffer = mDevice->createBuffer( stream, description );
  573. description->mIsStreaming = streamFlag; // restore in case we stomped it
  574. return buffer;
  575. }
  576. //-----------------------------------------------------------------------------
  577. SFXBuffer* SFXSystem::_createBuffer( const String& filename, SFXDescription* description )
  578. {
  579. if( !mDevice )
  580. {
  581. Con::errorf( "SFXSystem::_createBuffer - No sound device initialized!!" );
  582. return NULL;
  583. }
  584. return mDevice->createBuffer( filename, description );
  585. }
  586. //-----------------------------------------------------------------------------
  587. SFXSource* SFXSystem::playOnce( SFXTrack* track,
  588. const MatrixF *transform,
  589. const VectorF *velocity,
  590. F32 fadeInTime )
  591. {
  592. // We sometimes get null profiles... nothing to play without a profile!
  593. if( !track )
  594. return NULL;
  595. SFXSource *source = createSource( track, transform, velocity );
  596. if( source )
  597. {
  598. mPlayOnceSources.push_back( source );
  599. source->play( fadeInTime );
  600. }
  601. return source;
  602. }
  603. //-----------------------------------------------------------------------------
  604. void SFXSystem::_update()
  605. {
  606. PROFILE_SCOPE( SFXSystem_Update );
  607. getEventSignal().trigger( SFXSystemEvent_Update );
  608. for( U32 i = 0; i < mPlugins.size(); ++ i )
  609. mPlugins[ i ]->update();
  610. const U32 SOURCE_UPDATE_MS = TickMs * 2;
  611. const U32 PARAMETER_UPDATE_MS = TickMs * 3;
  612. const U32 AMBIENT_UPDATE_MS = TickMs * 4;
  613. static AutoPtr< PlatformTimer > sTimer;
  614. if( sTimer.isNull() )
  615. sTimer = PlatformTimer::create();
  616. // The update of the sources can be a bit expensive
  617. // and it does not need to be updated every frame.
  618. const U32 currentTime = Platform::getRealMilliseconds();
  619. if( ( currentTime - mLastSourceUpdateTime ) >= SOURCE_UPDATE_MS )
  620. {
  621. S32 tick = sTimer->getElapsedMs();
  622. _updateSources();
  623. mLastSourceUpdateTime = currentTime;
  624. mStatSourceUpdateTime = ( sTimer->getElapsedMs() - tick );
  625. }
  626. if( ( currentTime - mLastParameterUpdateTime ) >= PARAMETER_UPDATE_MS )
  627. {
  628. S32 tick = sTimer->getElapsedMs();
  629. SimSet* set = Sim::getSFXParameterGroup();
  630. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  631. {
  632. SFXParameter* parameter = dynamic_cast< SFXParameter* >( *iter );
  633. if( parameter )
  634. parameter->update();
  635. }
  636. mLastParameterUpdateTime = currentTime;
  637. mStatParameterUpdateTime = ( sTimer->getElapsedMs() - tick );
  638. }
  639. if( mSoundscapeMgr && ( currentTime - mLastAmbientUpdateTime ) >= AMBIENT_UPDATE_MS )
  640. {
  641. S32 tick = sTimer->getElapsedMs();
  642. mSoundscapeMgr->update();
  643. mLastAmbientUpdateTime = currentTime;
  644. mStatAmbientUpdateTime = ( sTimer->getElapsedMs() - tick );
  645. }
  646. // If we have a device then update it.
  647. if( mDevice )
  648. mDevice->update();
  649. }
  650. //-----------------------------------------------------------------------------
  651. void SFXSystem::_updateSources()
  652. {
  653. PROFILE_SCOPE( SFXSystem_UpdateSources );
  654. SimSet* sources = Sim::getSFXSourceSet();
  655. if( !sources )
  656. return;
  657. // Check the status of the sources here once.
  658. //
  659. // NOTE: We do not use iterators in this loop because
  660. // SFXControllers can add to the source list during the
  661. // loop.
  662. //
  663. mStatNumPlaying = 0;
  664. for( S32 i=0; i < sources->size(); i++ )
  665. {
  666. SFXSource *source = dynamic_cast< SFXSource* >( sources->at( i ) );
  667. if ( source )
  668. {
  669. source->update();
  670. if( source->getStatus() == SFXStatusPlaying )
  671. ++ mStatNumPlaying;
  672. }
  673. }
  674. // First check to see if any play once sources have
  675. // finished playback... delete them.
  676. for( SFXSourceVector::iterator iter = mPlayOnceSources.begin(); iter != mPlayOnceSources.end(); )
  677. {
  678. SFXSource* source = *iter;
  679. if( source->getLastStatus() == SFXStatusStopped &&
  680. source->getSavedStatus() != SFXStatusPlaying )
  681. {
  682. S32 index = iter - mPlayOnceSources.begin();
  683. // Erase it from the vector first, so that onRemoveSource
  684. // doesn't do it during cleanup and screw up our loop here!
  685. mPlayOnceSources.erase_fast( iter );
  686. source->deleteObject();
  687. iter = mPlayOnceSources.begin() + index;
  688. continue;
  689. }
  690. ++ iter;
  691. }
  692. if( mDevice )
  693. {
  694. // Reassign buffers to the sounds (if voices are managed by
  695. // us instead of by the device).
  696. if( !( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement ) )
  697. _assignVoices();
  698. // Update the voice count stat.
  699. mStatNumVoices = mDevice->getVoiceCount();
  700. }
  701. }
  702. //-----------------------------------------------------------------------------
  703. void SFXSystem::_sortSounds( const SFXListenerProperties& listener )
  704. {
  705. PROFILE_SCOPE( SFXSystem_SortSounds );
  706. // Sort the source vector by the attenuated
  707. // volume and priorities. This leaves us
  708. // with the loudest and highest priority sounds
  709. // at the front of the vector.
  710. dQsort( ( void* ) mSounds.address(), mSounds.size(), sizeof( SFXSound* ), SFXSound::qsortCompare );
  711. }
  712. //-----------------------------------------------------------------------------
  713. void SFXSystem::_assignVoices()
  714. {
  715. AssertFatal( getNumListeners() == 1, "SFXSystem::_assignVoices() - must only have a single listener" );
  716. PROFILE_SCOPE( SFXSystem_AssignVoices );
  717. mStatNumVoices = 0;
  718. mStatNumCulled = 0;
  719. if( !mDevice )
  720. return;
  721. // Sort the sources in the SFX source set by priority. This also
  722. // updates each soures effective volume first.
  723. _sortSounds( getListener() );
  724. // We now make sure that the sources closest to the
  725. // listener, the ones at the top of the source list,
  726. // have a device buffer to play thru.
  727. mStatNumCulled = 0;
  728. for( SFXSoundVector::iterator iter = mSounds.begin(); iter != mSounds.end(); ++ iter )
  729. {
  730. SFXSound* sound = *iter;
  731. // Non playing sources (paused or stopped) are at the
  732. // end of the vector, so when i encounter one i know
  733. // that nothing else in the vector needs buffer assignment.
  734. if( !sound->isPlaying() )
  735. break;
  736. // If the source is outside it's max range we can
  737. // skip it as well, so that we don't waste cycles
  738. // setting up a buffer for something we won't hear.
  739. if( sound->getAttenuatedVolume() <= 0.0f )
  740. {
  741. ++ mStatNumCulled;
  742. continue;
  743. }
  744. // If the source has a voice then we can skip it.
  745. if( sound->hasVoice() )
  746. continue;
  747. // Ok let the device try to assign a new voice for
  748. // this source... this may fail if we're out of voices.
  749. if( sound->_allocVoice( mDevice ) )
  750. continue;
  751. // The device couldn't assign a new voice, so we go through
  752. // local priority sounds and try to steal a voice.
  753. for( SFXSoundVector::iterator hijack = mSounds.end() - 1; hijack != iter; -- hijack )
  754. {
  755. SFXSound* other = *hijack;
  756. if( other->hasVoice() )
  757. {
  758. // If the sound is a suitable candidate, try to steal
  759. // its voice. While the sound definitely is lower down the chain
  760. // in the total priority ordering, we don't want to steal voices
  761. // from sounds that are clearly audible as that results in noticable
  762. // sound pops.
  763. if( ( other->getAttenuatedVolume() < 0.1 // Very quiet or maybe not even audible.
  764. || !other->isPlaying() // Not playing so not audible anyways.
  765. || other->getPosition() == 0 ) // Not yet started playing.
  766. && other->_releaseVoice() )
  767. break;
  768. }
  769. }
  770. // Ok try to assign a voice once again!
  771. if( sound->_allocVoice( mDevice ) )
  772. continue;
  773. // If the source still doesn't have a buffer... well
  774. // tough cookies. It just cannot be heard yet, maybe
  775. // it can in the next update.
  776. mStatNumCulled ++;
  777. }
  778. // Update the voice count stat.
  779. mStatNumVoices = mDevice->getVoiceCount();
  780. }
  781. //-----------------------------------------------------------------------------
  782. void SFXSystem::_assignVoice( SFXSound* sound )
  783. {
  784. if( !mDevice )
  785. return;
  786. // Make sure all properties are up-to-date.
  787. sound->_update();
  788. // If voices are managed by the device, just let the sound
  789. // allocate a voice on it. Otherwise, do a voice allocation pass
  790. // on all our active sounds.
  791. if( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement )
  792. sound->_allocVoice( mDevice );
  793. else
  794. _assignVoices();
  795. // Update the voice count stat.
  796. mStatNumVoices = mDevice->getVoiceCount();
  797. }
  798. //-----------------------------------------------------------------------------
  799. void SFXSystem::setDistanceModel( SFXDistanceModel model )
  800. {
  801. const bool changed = ( model != mDistanceModel );
  802. mDistanceModel = model;
  803. if( mDevice && changed )
  804. mDevice->setDistanceModel( model );
  805. }
  806. //-----------------------------------------------------------------------------
  807. void SFXSystem::setDopplerFactor( F32 factor )
  808. {
  809. const bool changed = ( factor != mDopplerFactor );
  810. mDopplerFactor = factor;
  811. if( mDevice && changed )
  812. mDevice->setDopplerFactor( factor );
  813. }
  814. //-----------------------------------------------------------------------------
  815. void SFXSystem::setRolloffFactor( F32 factor )
  816. {
  817. const bool changed = ( factor != mRolloffFactor );
  818. mRolloffFactor = factor;
  819. if( mDevice && changed )
  820. mDevice->setRolloffFactor( factor );
  821. }
  822. //-----------------------------------------------------------------------------
  823. void SFXSystem::setReverb( const SFXReverbProperties& reverb )
  824. {
  825. mReverb = reverb;
  826. // Allow the plugins to adjust the reverb.
  827. for( U32 i = 0; i < mPlugins.size(); ++ i )
  828. mPlugins[ i ]->filterReverb( mReverb );
  829. // Pass it on to the device.
  830. if( mDevice )
  831. mDevice->setReverb( mReverb );
  832. }
  833. //-----------------------------------------------------------------------------
  834. void SFXSystem::setNumListeners( U32 num )
  835. {
  836. // If we are set to a single listener, just accept this as
  837. // we always support this no matter what.
  838. if( num == 1 )
  839. {
  840. mListeners.setSize( 1 );
  841. if( mDevice )
  842. mDevice->setNumListeners( 1 );
  843. return;
  844. }
  845. // If setting to multiple listeners, make sure that the device
  846. // both supports multiple listeners and implements its own voice
  847. // management (as our voice virtualization does not work with more
  848. // than a single listener).
  849. if( !mDevice || !( mDevice->getCaps() & SFXDevice::CAPS_MultiListener )
  850. || !( mDevice->getCaps() & SFXDevice::CAPS_VoiceManagement ) )
  851. {
  852. Con::errorf( "SFXSystem::setNumListeners() - multiple listeners not supported on current configuration" );
  853. return;
  854. }
  855. mListeners.setSize( num );
  856. if( mDevice )
  857. mDevice->setNumListeners( num );
  858. }
  859. //-----------------------------------------------------------------------------
  860. void SFXSystem::setListener( U32 index, const MatrixF& transform, const Point3F& velocity )
  861. {
  862. if( index >= mListeners.size() )
  863. return;
  864. mListeners[ index ] = SFXListenerProperties( transform, velocity );
  865. if( mDevice )
  866. mDevice->setListener( index, mListeners[ index ] );
  867. }
  868. //-----------------------------------------------------------------------------
  869. void SFXSystem::notifyDescriptionChanged( SFXDescription* description )
  870. {
  871. SimSet* set = Sim::getSFXSourceSet();
  872. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  873. {
  874. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  875. if( source && source->getDescription() == description )
  876. source->notifyDescriptionChanged();
  877. }
  878. }
  879. //-----------------------------------------------------------------------------
  880. void SFXSystem::notifyTrackChanged( SFXTrack* track )
  881. {
  882. SimSet* set = Sim::getSFXSourceSet();
  883. for( SimSet::iterator iter = set->begin(); iter != set->end(); ++ iter )
  884. {
  885. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  886. if( source && source->getTrack() == track )
  887. source->notifyTrackChanged();
  888. }
  889. }
  890. //-----------------------------------------------------------------------------
  891. void SFXSystem::dumpSources( StringBuilder* toString, bool excludeGroups )
  892. {
  893. SimSet* sources = Sim::getSFXSourceSet();
  894. if( !sources )
  895. return;
  896. bool isFirst = true;
  897. for( SimSet::iterator iter = sources->begin(); iter != sources->end(); ++ iter )
  898. {
  899. SFXSource* source = dynamic_cast< SFXSource* >( *iter );
  900. if( !source )
  901. continue;
  902. bool isGroup = typeid( *source ) == typeid( SFXSource );
  903. if( isGroup && excludeGroups )
  904. continue;
  905. bool isPlayOnce = false;
  906. for( U32 j = 0; j < mPlayOnceSources.size(); ++ j )
  907. if( mPlayOnceSources[ j ] == source )
  908. {
  909. isPlayOnce = true;
  910. break;
  911. }
  912. SFXSource* sourceGroup = source->getSourceGroup();
  913. SFXSound* sound = dynamic_cast< SFXSound* >( source );
  914. SFXController* controller = dynamic_cast< SFXController* >( source );
  915. if( toString )
  916. toString->format( "%s%5i: type=%s, status=%s, blocked=%s, volume=%.2f, priority=%.2f, virtual=%s, looping=%s, 3d=%s, group=%s, playtime=%.2f, playOnce=%s, streaming=%s, hasVoice=%s, track=%s",
  917. ( isFirst ? "" : "\n" ),
  918. source->getId(),
  919. ( isGroup ? "group" : sound ? "sound" : controller ? "list" : "other" ),
  920. source->isPlaying()
  921. ? "playing"
  922. : source->isPaused()
  923. ? "paused"
  924. : source->isStopped()
  925. ? "stopped"
  926. : "unknown",
  927. ( sound && sound->isBlocked() ? "1" : "0" ),
  928. source->getAttenuatedVolume(),
  929. source->getEffectivePriority(),
  930. ( sound && sound->isVirtualized() ? "1" : "0" ),
  931. ( sound && sound->isLooping() ) ? "1" : "0",
  932. source->getDescription()->mIs3D ? "1" : "0",
  933. sourceGroup ? sourceGroup->getName() : "",
  934. source->getElapsedPlayTimeCurrentCycle(),
  935. isPlayOnce ? "1" : "0",
  936. ( sound && sound->isStreaming() ? "1" : "0" ),
  937. ( sound && sound->hasVoice() ? "1" : "0" ),
  938. source->getTrack() ? source->getTrack()->getName() : ""
  939. );
  940. else
  941. Con::printf( "%5i: type=%s, status=%s, blocked=%s, volume=%.2f, priority=%.2f, virtual=%s, looping=%s, 3d=%s, group=%s, playtime=%.2f, playOnce=%s, streaming=%s, hasVoice=%s, track=%s",
  942. source->getId(),
  943. ( isGroup ? "group" : sound ? "sound" : controller ? "list" : "other" ),
  944. source->isPlaying()
  945. ? "playing"
  946. : source->isPaused()
  947. ? "paused"
  948. : source->isStopped()
  949. ? "stopped"
  950. : "unknown",
  951. ( sound && sound->isBlocked() ? "1" : "0" ),
  952. source->getAttenuatedVolume(),
  953. source->getEffectivePriority(),
  954. ( sound && sound->isVirtualized() ? "1" : "0" ),
  955. ( sound && sound->isLooping() ) ? "1" : "0",
  956. source->getDescription()->mIs3D ? "1" : "0",
  957. sourceGroup ? sourceGroup->getName() : "",
  958. source->getElapsedPlayTimeCurrentCycle(),
  959. isPlayOnce ? "1" : "0",
  960. ( sound && sound->isStreaming() ? "1" : "0" ),
  961. ( sound && sound->hasVoice() ? "1" : "0" ),
  962. source->getTrack() ? source->getTrack()->getName() : ""
  963. );
  964. isFirst = false;
  965. }
  966. }
  967. //=============================================================================
  968. // Console Functions.
  969. //=============================================================================
  970. // MARK: ---- Console Functions ----
  971. //-----------------------------------------------------------------------------
  972. DefineEngineFunction( sfxGetAvailableDevices, const char*, (),,
  973. "Get a list of all available sound devices.\n"
  974. "The return value will be a newline-separated list of entries where each line describes one available sound "
  975. "device. Each such line will have the following format:"
  976. "@verbatim\n"
  977. "provider TAB device TAB hasHardware TAB numMaxBuffers\n"
  978. "@endverbatim\n"
  979. "- provider: The name of the device provider (e.g. \"OpenAL\").\n"
  980. "- device: The name of the device as returned by the device layer.\n"
  981. "- hasHardware: Whether the device supports hardware mixing or not.\n"
  982. "- numMaxBuffers: The maximum number of concurrent voices supported by the device's mixer. If this limit "
  983. "limit is exceeded, i.e. if there are more active sounds playing at any one time, then voice virtualization "
  984. "will start culling voices and put them into virtualized playback mode. Voice virtualization may or may not "
  985. "be provided by the device itself; if not provided by the device, it will be provided by Torque's sound system.\n\n"
  986. "@return A newline-separated list of information about all available sound devices.\n"
  987. "@see sfxCreateDevice\n"
  988. "@see sfxGetDeviceInfo\n\n"
  989. "@see $SFX::DEVICE_INFO_PROVIDER\n\n"
  990. "@see $SFX::DEVICE_INFO_NAME\n\n"
  991. "@see $SFX::DEVICE_INFO_USEHARDWARE\n\n"
  992. "@see $SFX::DEVICE_INFO_MAXBUFFERS\n\n"
  993. "@ref SFX_devices\n"
  994. "@ingroup SFX" )
  995. {
  996. const S32 bufferSize = 2048;
  997. char* deviceList = Con::getReturnBuffer( bufferSize );
  998. S32 len = bufferSize;
  999. char *ptr = deviceList;
  1000. *ptr = 0;
  1001. SFXProvider* provider = SFXProvider::getFirstProvider();
  1002. while ( provider )
  1003. {
  1004. // List the devices in this provider.
  1005. const SFXDeviceInfoVector& deviceInfo = provider->getDeviceInfo();
  1006. for ( S32 d=0; d < deviceInfo.size(); d++ )
  1007. {
  1008. const SFXDeviceInfo* info = deviceInfo[d];
  1009. const char *providerName = provider->getName().c_str();
  1010. char *infoName = (char*)info->name.c_str();
  1011. dSprintf(ptr, len, "%s\t%s\t%s\t%i\n", providerName, infoName, info->hasHardware ? "1" : "0", info->maxBuffers);
  1012. ptr += dStrlen(ptr);
  1013. len = bufferSize - (ptr - deviceList);
  1014. if (len <= 0)
  1015. return deviceList;
  1016. }
  1017. provider = provider->getNextProvider();
  1018. }
  1019. return deviceList;
  1020. }
  1021. //-----------------------------------------------------------------------------
  1022. DefineEngineFunction( sfxCreateDevice, bool, ( const char* provider, const char* device, bool useHardware, S32 maxBuffers ),,
  1023. "Try to create a new sound device using the given properties.\n"
  1024. "If a sound device is currently initialized, it will be uninitialized first. However, be aware that in this case, "
  1025. "if this function fails, it will not restore the previously active device but rather leave the sound system in an "
  1026. "uninitialized state.\n\n"
  1027. "Sounds that are already playing while the new device is created will be temporarily transitioned to virtualized "
  1028. "playback and then resume normal playback once the device has been created.\n\n"
  1029. "In the core scripts, sound is automatically set up during startup in the sfxStartup() function.\n\n"
  1030. "@param provider The name of the device provider as returned by sfxGetAvailableDevices().\n"
  1031. "@param device The name of the device as returned by sfxGetAvailableDevices().\n"
  1032. "@param useHardware Whether to enabled hardware mixing on the device or not. Only relevant if supported by the given device.\n"
  1033. "@param maxBuffers The maximum number of concurrent voices for this device to use or -1 for the device to pick its own reasonable default."
  1034. "@return True if the initialization was successful, false if not.\n"
  1035. "@note This function must be called before any of the sound playback functions can be used.\n"
  1036. "@see sfxGetAvailableDevices\n"
  1037. "@see sfxGetDeviceInfo\n"
  1038. "@see sfxDeleteDevice\n\n"
  1039. "@ref SFX_devices\n"
  1040. "@ingroup SFX" )
  1041. {
  1042. return SFX->createDevice( provider, device, useHardware, maxBuffers, true );
  1043. }
  1044. //-----------------------------------------------------------------------------
  1045. DefineEngineFunction( sfxDeleteDevice, void, (),,
  1046. "Delete the currently active sound device and release all its resources.\n"
  1047. "SFXSources that are still playing will be transitioned to virtualized playback mode. "
  1048. "When creating a new device, they will automatically transition back to normal playback.\n\n"
  1049. "In the core scripts, this is done automatically for you during shutdown in the sfxShutdown() function.\n\n"
  1050. "@see sfxCreateDevice\n\n"
  1051. "@ref SFX_devices\n"
  1052. "@ingroup SFX" )
  1053. {
  1054. SFX->deleteDevice();
  1055. }
  1056. //-----------------------------------------------------------------------------
  1057. DefineEngineFunction( sfxGetDeviceInfo, const char*, (),,
  1058. "Return information about the currently active sound device.\n"
  1059. "The return value is a tab-delimited string of the following format:\n"
  1060. "@verbatim\n"
  1061. "provider TAB device TAB hasHardware TAB numMaxBuffers TAB caps\n"
  1062. "@endverbatim\n"
  1063. "- provider: The name of the device provider (e.g. \"OpenALD\").\n"
  1064. "- device: The name of the device as returned by the device layer.\n"
  1065. "- hasHardware: Whether the device supports hardware mixing or not.\n"
  1066. "- numMaxBuffers: The maximum number of concurrent voices supported by the device's mixer. If this limit "
  1067. "limit is exceeded, i.e. if there are more active sounds playing at any one time, then voice virtualization "
  1068. "will start culling voices and put them into virtualized playback mode. Voice virtualization may or may not "
  1069. "be provided by the device itself; if not provided by the device, it will be provided by Torque's sound system.\n"
  1070. "- caps: A bitfield of capability flags.\n\n"
  1071. "@return A tab-separated list of properties of the currently active sound device or the empty string if no sound device has been initialized.\n"
  1072. "@see sfxCreateDevice\n"
  1073. "@see sfxGetAvailableDevices\n\n"
  1074. "@see $SFX::DEVICE_INFO_PROVIDER\n\n"
  1075. "@see $SFX::DEVICE_INFO_NAME\n\n"
  1076. "@see $SFX::DEVICE_INFO_USEHARDWARE\n\n"
  1077. "@see $SFX::DEVICE_INFO_MAXBUFFERS\n\n"
  1078. "@see $SFX::DEVICE_INFO_CAPS\n\n"
  1079. "@see $SFX::DEVICE_CAPS_REVERB\n\n"
  1080. "@see $SFX::DEVICE_CAPS_VOICEMANAGEMENT\n\n"
  1081. "@see $SFX::DEVICE_CAPS_OCCLUSION\n\n"
  1082. "@see $SFX::DEVICE_CAPS_DSPEFFECTS\n\n"
  1083. "@see $SFX::DEVICE_CAPS_MULTILISTENER\n\n"
  1084. "@ref SFX_devices\n"
  1085. "@ingroup SFX" )
  1086. {
  1087. String deviceInfo = SFX->getDeviceInfoString();
  1088. if( deviceInfo.isEmpty() )
  1089. return "";
  1090. return Con::getReturnBuffer( deviceInfo );
  1091. }
  1092. //-----------------------------------------------------------------------------
  1093. static ConsoleDocFragment _sfxCreateSource1(
  1094. "@brief Create a new source that plays the given track.\n\n"
  1095. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1096. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1097. "Call delete() to release the source object.\n\n"
  1098. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1099. "@param track The track the source should play.\n"
  1100. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1101. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1102. "does not support the type. \n\n"
  1103. "@tsexample\n"
  1104. "// Create and play a source from a pre-existing profile:\n"
  1105. "%source = sfxCreateSource( SoundFileProfile );\n"
  1106. "%source.play();\n"
  1107. "@endtsexample\n\n"
  1108. "@ingroup SFX",
  1109. NULL,
  1110. "SFXSource sfxCreateSource( SFXTrack track );" );
  1111. static ConsoleDocFragment _sfxCreateSource2(
  1112. "@brief Create a new source that plays the given track and position its 3D sounds source at the given coordinates (if it is a 3D sound).\n\n"
  1113. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1114. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1115. "Call delete() to release the source object.\n\n"
  1116. "This function will automatically create the right SFXSource type for the given SFXTrack.\n\n"
  1117. "@param track The track the source should play.\n"
  1118. "@param x The X coordinate of the 3D sound position.\n"
  1119. "@param y The Y coordinate of the 3D sound position.\n"
  1120. "@param z The Z coordinate of the 3D sound position.\n"
  1121. "@return A new SFXSource for playback of the given track or 0 if no source could be created from the given track.\n\n"
  1122. "@note Trying to create a source for a device-specific track type will fail if the currently selected device "
  1123. "does not support the type. \n\n"
  1124. "@tsexample\n"
  1125. "// Create and play a source from a pre-existing profile and position it at (100, 200, 300):\n"
  1126. "%source = sfxCreateSource( SoundFileProfile, 100, 200, 300 );\n"
  1127. "%source.play();\n"
  1128. "@endtsexample\n\n"
  1129. "@ingroup SFX",
  1130. NULL,
  1131. "SFXSource sfxCreateSource( SFXTrack track, float x, float y, float z );" );
  1132. static ConsoleDocFragment _sfxCreateSource3(
  1133. "@brief Create a temporary SFXProfile from the given @a description and @a filename and then create and return a new source that plays the profile.\n\n"
  1134. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1135. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1136. "Call delete() to release the source object.\n\n"
  1137. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1138. "@param filename Path to the sound file to play.\n"
  1139. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1140. "@tsexample\n"
  1141. "// Create a source for a music track:\n"
  1142. "%source = sfxCreateSource( AudioMusicLoop2D, \"art/sound/backgroundMusic\" );\n"
  1143. "%source.play();\n"
  1144. "@endtsexample\n\n"
  1145. "@see SFXProfile\n\n"
  1146. "@ingroup SFX",
  1147. NULL,
  1148. "SFXSound sfxCreateSource( SFXDescription description, string filename );" );
  1149. static ConsoleDocFragment _sfxCreateSource4(
  1150. "@brief Create a temporary SFXProfile from the given @a description and @a filename and then create and return a new source that plays the profile. "
  1151. "Position the sound source at the given coordinates (if it is a 3D sound).\n\n"
  1152. "The source will be returned in stopped state. Call SFXSource::play() to start playback.\n\n"
  1153. "In contrast to play-once sources, the source object will not be automatically deleted once playback stops. "
  1154. "Call delete() to release the source object.\n\n"
  1155. "@param description The description to use for setting up the temporary SFXProfile.\n"
  1156. "@param filename Path to the sound file to play.\n"
  1157. "@param x The X coordinate of the 3D sound position.\n"
  1158. "@param y The Y coordinate of the 3D sound position.\n"
  1159. "@param z The Z coordinate of the 3D sound position.\n"
  1160. "@return A new SFXSource for playback of the given track or 0 if no source or no temporary profile could be created.\n\n"
  1161. "@tsexample\n"
  1162. "// Create a source for a music track and position it at (100, 200, 300):\n"
  1163. "%source = sfxCreateSource( AudioMusicLoop3D, \"art/sound/backgroundMusic\", 100, 200, 300 );\n"
  1164. "%source.play();\n"
  1165. "@endtsexample\n\n"
  1166. "@see SFXProfile\n\n"
  1167. "@ingroup SFX",
  1168. NULL,
  1169. "SFXSound sfxCreateSource( SFXDescription description, string filename, float x, float y, float z );" );
  1170. DefineEngineFunction( sfxCreateSource, S32, ( const char * sfxType, const char * arg0, const char * arg1, const char * arg2, const char * arg3 ), ("", "", "", ""),
  1171. "( SFXTrack track | ( SFXDescription description, string filename ) [, float x, float y, float z ] ) "
  1172. "Creates a new paused sound source using a profile or a description "
  1173. "and filename. The return value is the source which must be "
  1174. "released by delete().\n"
  1175. "@hide" )
  1176. {
  1177. SFXDescription* description = NULL;
  1178. SFXTrack* track = dynamic_cast< SFXTrack* >( Sim::findObject( sfxType ) );
  1179. if ( !track )
  1180. {
  1181. description = dynamic_cast< SFXDescription* >( Sim::findObject( sfxType ) );
  1182. if ( !description )
  1183. {
  1184. Con::printf( "Unable to locate sound track/description '%s'", sfxType );
  1185. return 0;
  1186. }
  1187. }
  1188. SFXSource* source = NULL;
  1189. if ( track )
  1190. {
  1191. // In this overloaded use of the function, arg0..arg2 are x, y, and z.
  1192. if ( String::isEmpty(arg0) )
  1193. {
  1194. source = SFX->createSource( track );
  1195. }
  1196. else
  1197. {
  1198. MatrixF transform;
  1199. transform.set( EulerF(0,0,0), Point3F( dAtof(arg0), dAtof(arg1), dAtof(arg2)) );
  1200. source = SFX->createSource( track, &transform );
  1201. }
  1202. }
  1203. else if ( description )
  1204. {
  1205. // In this use, arg0 is the filename, and arg1..arg3 are x, y, and z.
  1206. SFXProfile* tempProfile = new SFXProfile( description, StringTable->insert( arg0), true );
  1207. if( !tempProfile->registerObject() )
  1208. {
  1209. Con::errorf( "sfxCreateSource - unable to create profile" );
  1210. delete tempProfile;
  1211. }
  1212. else
  1213. {
  1214. if ( String::isEmpty(arg1) )
  1215. {
  1216. source = SFX->createSource( tempProfile );
  1217. }
  1218. else
  1219. {
  1220. MatrixF transform;
  1221. transform.set(EulerF(0,0,0), Point3F( dAtof(arg1), dAtof(arg2), dAtof(arg3) ));
  1222. source = SFX->createSource( tempProfile, &transform );
  1223. }
  1224. tempProfile->setAutoDelete( true );
  1225. }
  1226. }
  1227. if ( source )
  1228. return source->getId();
  1229. return 0;
  1230. }
  1231. //-----------------------------------------------------------------------------
  1232. static ConsoleDocFragment _sfxPlay1(
  1233. "@brief Start playback of the given source.\n\n"
  1234. "This is the same as calling SFXSource::play() directly.\n\n"
  1235. "@param source The source to start playing.\n\n"
  1236. "@return @a source.\n\n"
  1237. "@tsexample\n"
  1238. "// Create and play a source from a pre-existing profile:\n"
  1239. "%source = sfxCreateSource( SoundFileProfile );\n"
  1240. "%source.play();\n"
  1241. "@endtsexample\n\n"
  1242. "@ingroup SFX",
  1243. NULL,
  1244. "SFXSource sfxPlay( SFXSource source );" );
  1245. static ConsoleDocFragment _sfxPlay2(
  1246. "@brief Create a new play-once source for the given @a track and start playback of the source.\n\n"
  1247. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1248. "@param track The sound datablock to play.\n\n"
  1249. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1250. "@ref SFXSource_playonce\n\n"
  1251. "@ingroup SFX",
  1252. NULL,
  1253. "void sfxPlay( SFXTrack track );" );
  1254. static ConsoleDocFragment _sfxPlay3(
  1255. "@brief Create a new play-once source for the given @a track, position its 3D sound at the given coordinates (if the track's description "
  1256. "is set up for 3D sound) and start playback of the source.\n\n"
  1257. "This is equivalent to calling sfxCreateSource() on @track and SFXSource::play() on the resulting source.\n\n"
  1258. "@param track The sound datablock to play.\n\n"
  1259. "@param x The X coordinate of the 3D sound position.\n"
  1260. "@param y The Y coordinate of the 3D sound position.\n"
  1261. "@param z The Z coordinate of the 3D sound position.\n"
  1262. "@return The newly created play-once source or 0 if the creation failed.\n\n"
  1263. "@ref SFXSource_playonce\n\n"
  1264. "@ingroup SFX",
  1265. NULL,
  1266. "void sfxPlay( SFXTrack track, float x, float y, float z );" );
  1267. DefineEngineFunction( sfxPlay, S32, ( const char * trackName, const char * pointOrX, const char * y, const char * z ), ( "", "", ""),
  1268. "Start playing the given source or create a new source for the given track and play it.\n"
  1269. "@hide" )
  1270. {
  1271. if ( String::isEmpty(pointOrX) )
  1272. {
  1273. SFXSource* source = dynamic_cast<SFXSource*>( Sim::findObject( trackName ) );
  1274. if ( source )
  1275. {
  1276. source->play();
  1277. return source->getId();
  1278. }
  1279. }
  1280. SFXTrack* track = dynamic_cast<SFXTrack*>( Sim::findObject( trackName ) );
  1281. if ( !track )
  1282. {
  1283. Con::printf( "Unable to locate sfx track '%s'", trackName );
  1284. return 0;
  1285. }
  1286. Point3F pos(0.f, 0.f, 0.f);
  1287. if ( !String::isEmpty( pointOrX ) && String::isEmpty( y ) && String::isEmpty( z ) )
  1288. {
  1289. dSscanf( pointOrX, "%g %g %g", &pos.x, &pos.y, &pos.z );
  1290. }
  1291. else if( !String::isEmpty( pointOrX ) && !String::isEmpty( y ) && !String::isEmpty( z ) )
  1292. pos.set( dAtof(pointOrX), dAtof(y), dAtof(z) );
  1293. MatrixF transform;
  1294. transform.set( EulerF(0,0,0), pos );
  1295. SFXSource* source = SFX->playOnce( track, &transform );
  1296. if ( source )
  1297. return source->getId();
  1298. return 0;
  1299. }
  1300. //-----------------------------------------------------------------------------
  1301. static ConsoleDocFragment _sPlayOnce1(
  1302. "@brief Create a play-once source for the given @a asset.\n\n"
  1303. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1304. "@param track The sound datablock.\n"
  1305. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1306. "@ref SFXSource_playonce\n\n"
  1307. "@ingroup SFX",
  1308. NULL,
  1309. "SFXSource sfxPlayOnce( StringTableEntry assetID );"
  1310. );
  1311. static ConsoleDocFragment _sPlayOnce2(
  1312. "@brief Create a play-once source for the given given @a asset and position the source's 3D sound at the given coordinates "
  1313. "only if the asset is set up for 3D sound).\n\n"
  1314. "Once playback has finished, the source will be automatically deleted in the next sound system update.\n"
  1315. "@param assetId The sound asset.\n"
  1316. "@param x The X coordinate of the 3D sound position.\n"
  1317. "@param y The Y coordinate of the 3D sound position.\n"
  1318. "@param z The Z coordinate of the 3D sound position.\n"
  1319. "@param fadeInTime If >=0, this overrides the SFXDescription::fadeInTime value on the asset's definition.\n"
  1320. "@return A newly created temporary source in \"Playing\" state or 0 if the operation failed.\n\n"
  1321. "@tsexample\n"
  1322. "// Immediately start playing the given asset. Fade it in to full volume over 5 seconds.\n"
  1323. "sfxPlayOnce( ExampleModule:MusicTrack, 0, 0, 0, 5.f );\n"
  1324. "@endtsexample\n\n"
  1325. "@ref SFXSource_playonce\n\n"
  1326. "@ingroup SFX",
  1327. NULL,
  1328. "SFXSource sfxPlayOnce( StringTableEntry assetID, float x, float y, float z, float fadeInTime=-1 );"
  1329. );
  1330. DefineEngineFunction( sfxPlayOnce, S32, (StringTableEntry assetId, const char* arg0, const char * arg1, const char * arg2, const char * arg3 ), (StringTable->EmptyString(), "", "", "", "-1.0f"),
  1331. "SFXSource sfxPlayOnce( ( SFXTrack track | SFXDescription description, string filename ) [, float x, float y, float z, float fadeInTime=-1 ] ) "
  1332. "Create a new play-once source for the given profile or description+filename and start playback of the source.\n"
  1333. "@hide" )
  1334. {
  1335. if (assetId == StringTable->EmptyString())
  1336. {
  1337. Con::errorf( "sfxPlayOnce - Must Define a sound asset");
  1338. return 0;
  1339. }
  1340. SFXSource* source = NULL;
  1341. if (AssetDatabase.isDeclaredAsset(assetId))
  1342. {
  1343. AssetPtr<SoundAsset> tempSoundAsset;
  1344. tempSoundAsset = assetId;
  1345. if (String::isEmpty(arg0) || !tempSoundAsset->is3D())
  1346. {
  1347. source = SFX->playOnce(tempSoundAsset->getSfxProfile());
  1348. }
  1349. else
  1350. {
  1351. MatrixF transform;
  1352. transform.set(EulerF(0, 0, 0), Point3F(dAtof(arg0), dAtof(arg1), dAtof(arg2)));
  1353. source = SFX->playOnce(tempSoundAsset->getSfxProfile(), &transform, NULL, dAtof(arg3));
  1354. }
  1355. }
  1356. else
  1357. {
  1358. Con::errorf("sfxPlayOnce - Could not locate assetId '%s'", assetId);
  1359. return 0;
  1360. }
  1361. if( !source )
  1362. return 0;
  1363. return source->getId();
  1364. }
  1365. //-----------------------------------------------------------------------------
  1366. DefineEngineFunction( sfxStop, void, ( SFXSource* source ),,
  1367. "Stop playback of the given @a source.\n"
  1368. "This is equivalent to calling SFXSource::stop().\n\n"
  1369. "@param source The source to put into stopped state.\n\n"
  1370. "@ingroup SFX" )
  1371. {
  1372. if( source )
  1373. source->stop();
  1374. }
  1375. //-----------------------------------------------------------------------------
  1376. DefineEngineFunction( sfxStopAndDelete, void, ( SFXSource* source ),,
  1377. "Stop playback of the given @a source (if it is not already stopped) and delete the @a source.\n\n"
  1378. "The advantage of this function over directly calling delete() is that it will correctly "
  1379. "handle volume fades that may be configured on the source. Whereas calling delete() would immediately "
  1380. "stop playback and delete the source, this functionality will wait for the fade-out to play and only then "
  1381. "stop the source and delete it.\n\n"
  1382. "@param source A sound source.\n\n"
  1383. "@ref SFXSource_fades\n\n"
  1384. "@ingroup SFX" )
  1385. {
  1386. if( source )
  1387. SFX->stopAndDeleteSource( source );
  1388. }
  1389. //-----------------------------------------------------------------------------
  1390. DefineEngineFunction( sfxDeleteWhenStopped, void, ( SFXSource* source ),,
  1391. "Mark the given @a source for deletion as soon as it moves into stopped state.\n\n"
  1392. "This function will retroactively turn the given @a source into a play-once source (see @ref SFXSource_playonce).\n\n"
  1393. "@param source A sound source.\n\n"
  1394. "@ingroup SFX" )
  1395. {
  1396. if( source )
  1397. SFX->deleteWhenStopped( source );
  1398. }
  1399. //-----------------------------------------------------------------------------
  1400. DefineEngineFunction( sfxGetDistanceModel, SFXDistanceModel, (),,
  1401. "Get the falloff curve type currently being applied to 3D sounds.\n\n"
  1402. "@return The current distance model type.\n\n"
  1403. "@ref SFXSource_volume\n\n"
  1404. "@ref SFX_3d\n\n"
  1405. "@ingroup SFX" )
  1406. {
  1407. return SFX->getDistanceModel();
  1408. }
  1409. //-----------------------------------------------------------------------------
  1410. DefineEngineFunction( sfxSetDistanceModel, void, ( SFXDistanceModel model ),,
  1411. "Set the falloff curve type to use for distance-based volume attenuation of 3D sounds.\n\n"
  1412. "@param model The distance model to use for 3D sound.\n\n"
  1413. "@note This setting takes effect globally and is applied to all 3D sounds.\n\n"
  1414. "@ingroup SFX" )
  1415. {
  1416. SFX->setDistanceModel( model );
  1417. }
  1418. //-----------------------------------------------------------------------------
  1419. DefineEngineFunction( sfxGetDopplerFactor, F32, (),,
  1420. "Get the current global doppler effect setting.\n\n"
  1421. "@return The current global doppler effect scale factor (>=0).\n\n"
  1422. "@see sfxSetDopplerFactor\n\n"
  1423. "@ref SFXSource_doppler\n\n"
  1424. "@ingroup SFX" )
  1425. {
  1426. return SFX->getDopplerFactor();
  1427. }
  1428. //-----------------------------------------------------------------------------
  1429. DefineEngineFunction( sfxSetDopplerFactor, void, ( F32 value ),,
  1430. "Set the global doppler effect scale factor.\n"
  1431. "@param value The new doppler shift scale factor.\n"
  1432. "@pre @a value must be >= 0.\n"
  1433. "@see sfxGetDopplerFactor\n\n"
  1434. "@ref SFXSource_doppler\n\n"
  1435. "@ingroup SFX" )
  1436. {
  1437. if( value < 0.0f )
  1438. {
  1439. Con::errorf( "sfxSetDopplerFactor - factor must be >0" );
  1440. return;
  1441. }
  1442. SFX->setDopplerFactor( value );
  1443. }
  1444. //-----------------------------------------------------------------------------
  1445. DefineEngineFunction( sfxGetRolloffFactor, F32, (),,
  1446. "Get the current global scale factor applied to volume attenuation of 3D sounds in the logarithmic model.\n"
  1447. "@return The current scale factor for logarithmic 3D sound falloff curves.\n\n"
  1448. "@see sfxGetDistanceModel\n"
  1449. "@see SFXDistanceModel\n\n"
  1450. "@ref SFXSource_volume\n"
  1451. "@ref SFX_3d\n"
  1452. "@ingroup SFX" )
  1453. {
  1454. return SFX->getRolloffFactor();
  1455. }
  1456. //-----------------------------------------------------------------------------
  1457. DefineEngineFunction( sfxSetRolloffFactor, void, ( F32 value ),,
  1458. "Set the global scale factor to apply to volume attenuation of 3D sounds in the logarithmic model.\n"
  1459. "@param value The new scale factor for logarithmic 3D sound falloff curves.\n\n"
  1460. "@pre @a value must be > 0.\n"
  1461. "@note This function has no effect if the currently distance model is set to SFXDistanceModel::Linear.\n\n"
  1462. "@see sfxGetDistanceModel\n"
  1463. "@see SFXDistanceModel\n\n"
  1464. "@ref SFXSource_volume\n"
  1465. "@ref SFX_3d\n"
  1466. "@ingroup SFX" )
  1467. {
  1468. if( value <= 0.0f )
  1469. {
  1470. Con::errorf( "sfxSetRolloffFactor - factor must be >0" );
  1471. return;
  1472. }
  1473. SFX->setRolloffFactor( value );
  1474. }
  1475. //-----------------------------------------------------------------------------
  1476. DefineEngineFunction( sfxDumpSources, void, ( bool includeGroups ), ( false ),
  1477. "Dump information about all current SFXSource instances to the console.\n"
  1478. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1479. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1480. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1481. "@see SFXSource\n"
  1482. "@see sfxDumpSourcesToString\n"
  1483. "@ingroup SFX" )
  1484. {
  1485. SFX->dumpSources( NULL, !includeGroups );
  1486. }
  1487. //-----------------------------------------------------------------------------
  1488. DefineEngineFunction( sfxDumpSourcesToString, const char*, ( bool includeGroups ), ( false ),
  1489. "Dump information about all current SFXSource instances to a string.\n"
  1490. "The dump includes information about the playback status for each source, volume levels, virtualization, etc.\n"
  1491. "@param includeGroups If true, direct instances of SFXSources (which represent logical sound groups) will be included. "
  1492. "Otherwise only instances of subclasses of SFXSources are included in the dump.\n"
  1493. "@return A string containing a dump of information about all currently instantiated SFXSources.\n"
  1494. "@see SFXSource\n"
  1495. "@see sfxDumpSources\n"
  1496. "@ingroup SFX" )
  1497. {
  1498. StringBuilder str;
  1499. SFX->dumpSources( &str, !includeGroups );
  1500. return Con::getReturnBuffer( str );
  1501. }