CMusicHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. #include "StdInc.h"
  2. #include <boost/bimap.hpp>
  3. #include <SDL_mixer.h>
  4. #include "CSndHandler.h"
  5. #include "CMusicHandler.h"
  6. #include "../lib/CCreatureHandler.h"
  7. #include "../lib/CSpellHandler.h"
  8. #include "../client/CGameInfo.h"
  9. #include "../lib/JsonNode.h"
  10. #include "../lib/GameConstants.h"
  11. #include "../lib/Filesystem/CResourceLoader.h"
  12. /*
  13. * CMusicHandler.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. using namespace boost::assign;
  22. static boost::bimap<soundBase::soundID, std::string> sounds;
  23. // Not pretty, but there's only one music handler object in the game.
  24. static void soundFinishedCallbackC(int channel)
  25. {
  26. CCS->soundh->soundFinishedCallback(channel);
  27. }
  28. static void musicFinishedCallbackC(void)
  29. {
  30. CCS->musich->musicFinishedCallback();
  31. }
  32. void CAudioBase::init()
  33. {
  34. if (initialized)
  35. return;
  36. if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024)==-1)
  37. {
  38. tlog1 << "Mix_OpenAudio error: " << Mix_GetError() << std::endl;
  39. return;
  40. }
  41. initialized = true;
  42. }
  43. void CAudioBase::release()
  44. {
  45. if (initialized)
  46. {
  47. Mix_CloseAudio();
  48. initialized = false;
  49. }
  50. }
  51. void CAudioBase::setVolume(ui32 percent)
  52. {
  53. if (percent > 100)
  54. percent = 100;
  55. volume = percent;
  56. }
  57. void CSoundHandler::onVolumeChange(const JsonNode &volumeNode)
  58. {
  59. setVolume(volumeNode.Float());
  60. }
  61. CSoundHandler::CSoundHandler():
  62. listener(settings.listen["general"]["sound"])
  63. {
  64. listener(boost::bind(&CSoundHandler::onVolumeChange, this, _1));
  65. // Map sound names
  66. #define VCMI_SOUND_NAME(x) ( soundBase::x,
  67. #define VCMI_SOUND_FILE(y) #y )
  68. sounds = boost::assign::list_of<boost::bimap<soundBase::soundID, std::string>::relation>
  69. VCMI_SOUND_LIST;
  70. #undef VCMI_SOUND_NAME
  71. #undef VCMI_SOUND_FILE
  72. // Vectors for helper(s)
  73. pickupSounds += soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  74. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07;
  75. horseSounds += // must be the same order as terrains (see EterrainType);
  76. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  77. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  78. soundBase::horseSubterranean, soundBase::horseLava,
  79. soundBase::horseWater, soundBase::horseRock;
  80. battleIntroSounds += soundBase::battle00, soundBase::battle01,
  81. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  82. soundBase::battle05, soundBase::battle06, soundBase::battle07;
  83. };
  84. void CSoundHandler::init()
  85. {
  86. CAudioBase::init();
  87. if (initialized)
  88. {
  89. // Load sounds
  90. Mix_ChannelFinished(soundFinishedCallbackC);
  91. }
  92. }
  93. void CSoundHandler::release()
  94. {
  95. if (initialized)
  96. {
  97. Mix_HaltChannel(-1);
  98. std::map<soundBase::soundID, Mix_Chunk *>::iterator it;
  99. for (it=soundChunks.begin(); it != soundChunks.end(); it++)
  100. {
  101. if (it->second)
  102. Mix_FreeChunk(it->second);
  103. }
  104. }
  105. CAudioBase::release();
  106. }
  107. // Allocate an SDL chunk and cache it.
  108. Mix_Chunk *CSoundHandler::GetSoundChunk(soundBase::soundID soundID)
  109. {
  110. // Find its name
  111. boost::bimap<soundBase::soundID, std::string>::left_iterator it;
  112. it = sounds.left.find(soundID);
  113. if (it == sounds.left.end())
  114. return NULL;
  115. // Load and insert
  116. auto data = CResourceHandler::get()->loadData(ResourceID(std::string("SOUNDS/") + it->second, EResType::SOUND));
  117. SDL_RWops *ops = SDL_RWFromMem(data.first.release(), data.second);
  118. Mix_Chunk *chunk;
  119. chunk = Mix_LoadWAV_RW(ops, 1); // will free ops
  120. if (!chunk)
  121. {
  122. tlog1 << "Unable to mix sound" << it->second << "(" << Mix_GetError() << ")" << std::endl;
  123. return NULL;
  124. }
  125. soundChunks.insert(std::pair<soundBase::soundID, Mix_Chunk *>(soundID, chunk));
  126. return chunk;
  127. }
  128. // Get a soundID given a filename
  129. soundBase::soundID CSoundHandler::getSoundID(const std::string &fileName)
  130. {
  131. boost::bimap<soundBase::soundID, std::string>::right_iterator it;
  132. it = sounds.right.find(fileName);
  133. if (it == sounds.right.end())
  134. return soundBase::invalid;
  135. else
  136. return it->second;
  137. }
  138. void CSoundHandler::initCreaturesSounds(const std::vector<ConstTransitivePtr< CCreature> > &creatures)
  139. {
  140. tlog5 << "\t\tReading config/cr_sounds.json" << std::endl;
  141. const JsonNode config(ResourceID("config/cr_sounds.json"));
  142. CBattleSounds.resize(creatures.size());
  143. if (!config["creature_sounds"].isNull()) {
  144. BOOST_FOREACH(const JsonNode &node, config["creature_sounds"].Vector()) {
  145. const JsonNode *value;
  146. int id;
  147. value = &node["name"];
  148. bmap<std::string,int>::const_iterator i = CGI->creh->nameToID.find(value->String());
  149. if (i != CGI->creh->nameToID.end())
  150. id = i->second;
  151. else
  152. {
  153. tlog1 << "Sound info for an unknown creature: " << value->String() << std::endl;
  154. continue;
  155. }
  156. /* This is a bit ugly. Maybe we should use an array for
  157. * sound ids instead of separate variables and define
  158. * attack/defend/killed/... as indexes. */
  159. #define GET_SOUND_VALUE(value_name) do { value = &node[#value_name]; if (!value->isNull()) CBattleSounds[id].value_name = getSoundID(value->String()); } while(0)
  160. GET_SOUND_VALUE(attack);
  161. GET_SOUND_VALUE(defend);
  162. GET_SOUND_VALUE(killed);
  163. GET_SOUND_VALUE(move);
  164. GET_SOUND_VALUE(shoot);
  165. GET_SOUND_VALUE(wince);
  166. GET_SOUND_VALUE(ext1);
  167. GET_SOUND_VALUE(ext2);
  168. GET_SOUND_VALUE(startMoving);
  169. GET_SOUND_VALUE(endMoving);
  170. #undef GET_SOUND_VALUE
  171. }
  172. }
  173. //commented to avoid spurious warnings
  174. /*
  175. // Find creatures without sounds
  176. for(ui32 i=0;i<creatures.size();i++)
  177. {
  178. // Note: this will exclude war machines, but it's better
  179. // than nothing.
  180. if (vstd::contains(CGI->creh->notUsedMonsters, i))
  181. continue;
  182. CCreature &c = creatures[i];
  183. if (c.sounds.killed == soundBase::invalid)
  184. tlog1 << "creature " << c.idNumber << " doesn't have sounds" << std::endl;
  185. }*/
  186. }
  187. void CSoundHandler::initSpellsSounds(const std::vector< ConstTransitivePtr<CSpell> > &spells)
  188. {
  189. const JsonNode config(ResourceID("config/sp_sounds.json"));
  190. if (!config["spell_sounds"].isNull()) {
  191. BOOST_FOREACH(const JsonNode &node, config["spell_sounds"].Vector()) {
  192. int spellid = node["id"].Float();
  193. const CSpell *s = CGI->spellh->spells[spellid];
  194. if (vstd::contains(spellSounds, s))
  195. tlog1 << "Spell << " << spellid << " already has a sound" << std::endl;
  196. soundBase::soundID sound = getSoundID(node["soundfile"].String());
  197. if (sound == soundBase::invalid)
  198. tlog0 << "Error: invalid sound for id "<< spellid << "\n";
  199. spellSounds[s] = sound;
  200. }
  201. }
  202. }
  203. // Plays a sound, and return its channel so we can fade it out later
  204. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  205. {
  206. if (!initialized)
  207. return -1;
  208. int channel;
  209. Mix_Chunk *chunk = GetSoundChunk(soundID);
  210. if (chunk)
  211. {
  212. channel = Mix_PlayChannel(-1, chunk, repeats);
  213. if (channel == -1)
  214. tlog1 << "Unable to play sound file " << soundID << " , error " << Mix_GetError() << std::endl;
  215. else
  216. callbacks[channel];//insert empty callback
  217. }
  218. else
  219. {
  220. channel = -1;
  221. }
  222. return channel;
  223. }
  224. // Helper. Randomly select a sound from an array and play it
  225. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  226. {
  227. return playSound(sound_vec[rand() % sound_vec.size()]);
  228. }
  229. void CSoundHandler::stopSound( int handler )
  230. {
  231. if (initialized && handler != -1)
  232. Mix_HaltChannel(handler);
  233. }
  234. // Sets the sound volume, from 0 (mute) to 100
  235. void CSoundHandler::setVolume(ui32 percent)
  236. {
  237. CAudioBase::setVolume(percent);
  238. if (initialized)
  239. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  240. }
  241. void CSoundHandler::setCallback(int channel, boost::function<void()> function)
  242. {
  243. std::map<int, boost::function<void()> >::iterator iter;
  244. iter = callbacks.find(channel);
  245. //channel not found. It may have finished so fire callback now
  246. if(iter == callbacks.end())
  247. function();
  248. else
  249. iter->second = function;
  250. }
  251. void CSoundHandler::soundFinishedCallback(int channel)
  252. {
  253. std::map<int, boost::function<void()> >::iterator iter;
  254. iter = callbacks.find(channel);
  255. assert(iter != callbacks.end());
  256. if (iter->second)
  257. iter->second();
  258. callbacks.erase(iter);
  259. }
  260. void CMusicHandler::onVolumeChange(const JsonNode &volumeNode)
  261. {
  262. setVolume(volumeNode.Float());
  263. }
  264. CMusicHandler::CMusicHandler():
  265. listener(settings.listen["general"]["music"])
  266. {
  267. listener(boost::bind(&CMusicHandler::onVolumeChange, this, _1));
  268. // Map music IDs
  269. // Vectors for helper
  270. const std::string setEnemy[] = {"AITheme0", "AITheme1", "AITheme2"};
  271. const std::string setBattle[] = {"Combat01", "Combat02", "Combat03", "Combat04"};
  272. const std::string setTerrain[] = {"Dirt", "Sand", "Grass", "Snow", "Swamp", "Rough", "Underground", "Lava", "Water"};
  273. const std::string setTowns[] = {"CstleTown", "Rampart", "TowerTown", "InfernoTown",
  274. "NecroTown", "Dungeon", "Stronghold", "FortressTown", "ElemTown"};
  275. auto fillSet = [=](std::string setName, const std::string list[], size_t amount)
  276. {
  277. for (size_t i=0; i < amount; i++)
  278. addEntryToSet(setName, i, std::string("music/") + list[i]);
  279. };
  280. fillSet("enemy-turn", setEnemy, ARRAY_COUNT(setEnemy));
  281. fillSet("battle", setBattle, ARRAY_COUNT(setBattle));
  282. fillSet("terrain", setTerrain, ARRAY_COUNT(setTerrain));
  283. fillSet("town-theme", setTowns, ARRAY_COUNT(setTowns));
  284. }
  285. void CMusicHandler::addEntryToSet(std::string set, int musicID, std::string musicURI)
  286. {
  287. musicsSet[set][musicID] = musicURI;
  288. }
  289. void CMusicHandler::init()
  290. {
  291. CAudioBase::init();
  292. if (initialized)
  293. Mix_HookMusicFinished(musicFinishedCallbackC);
  294. }
  295. void CMusicHandler::release()
  296. {
  297. if (initialized)
  298. {
  299. boost::mutex::scoped_lock guard(musicMutex);
  300. Mix_HookMusicFinished(NULL);
  301. current.reset();
  302. next.reset();
  303. }
  304. CAudioBase::release();
  305. }
  306. void CMusicHandler::playMusic(std::string musicURI, bool loop)
  307. {
  308. if (current && current->isTrack( musicURI))
  309. return;
  310. queueNext(new MusicEntry(this, "", musicURI, loop));
  311. }
  312. void CMusicHandler::playMusicFromSet(std::string whichSet, bool loop)
  313. {
  314. auto selectedSet = musicsSet.find(whichSet);
  315. if (selectedSet == musicsSet.end())
  316. {
  317. tlog0 << "Error: playing music from non-existing set: " << whichSet << "\n";
  318. return;
  319. }
  320. if (current && current->isSet(whichSet))
  321. return;
  322. queueNext(new MusicEntry(this, whichSet, "", loop));
  323. }
  324. void CMusicHandler::playMusicFromSet(std::string whichSet, int entryID, bool loop)
  325. {
  326. auto selectedSet = musicsSet.find(whichSet);
  327. if (selectedSet == musicsSet.end())
  328. {
  329. tlog0 << "Error: playing music from non-existing set: " << whichSet << "\n";
  330. return;
  331. }
  332. auto selectedEntry = selectedSet->second.find(entryID);
  333. if (selectedEntry == selectedSet->second.end())
  334. {
  335. tlog0 << "Error: playing non-existing entry " << entryID << " from set: " << whichSet << "\n";
  336. return;
  337. }
  338. queueNext(new MusicEntry(this, "", selectedEntry->second, loop));
  339. }
  340. void CMusicHandler::queueNext(MusicEntry *queued)
  341. {
  342. if (!initialized)
  343. return;
  344. boost::mutex::scoped_lock guard(musicMutex);
  345. next.reset(queued);
  346. if (current.get() != NULL)
  347. {
  348. current->stop(1000);
  349. }
  350. else
  351. {
  352. current.reset(next.release());
  353. current->play();
  354. }
  355. }
  356. void CMusicHandler::stopMusic(int fade_ms)
  357. {
  358. if (!initialized)
  359. return;
  360. boost::mutex::scoped_lock guard(musicMutex);
  361. if (current.get() != NULL)
  362. current->stop(fade_ms);
  363. next.reset();
  364. }
  365. void CMusicHandler::setVolume(ui32 percent)
  366. {
  367. CAudioBase::setVolume(percent);
  368. if (initialized)
  369. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  370. }
  371. void CMusicHandler::musicFinishedCallback(void)
  372. {
  373. boost::mutex::scoped_lock guard(musicMutex);
  374. if (current.get() != NULL)
  375. {
  376. //return if current music still not finished
  377. if (current->play())
  378. return;
  379. else
  380. current.reset();
  381. }
  382. if (current.get() == NULL && next.get() != NULL)
  383. {
  384. current.reset(next.release());
  385. current->play();
  386. }
  387. }
  388. MusicEntry::MusicEntry(CMusicHandler *owner, std::string setName, std::string musicURI, bool looped):
  389. owner(owner),
  390. music(nullptr),
  391. looped(looped),
  392. setName(setName)
  393. {
  394. if (!musicURI.empty())
  395. load(musicURI);
  396. }
  397. MusicEntry::~MusicEntry()
  398. {
  399. tlog5<<"Del-ing music file "<<currentName<<"\n";
  400. if (music)
  401. Mix_FreeMusic(music);
  402. }
  403. void MusicEntry::load(std::string musicURI)
  404. {
  405. if (music)
  406. {
  407. tlog5<<"Del-ing music file "<<currentName<<"\n";
  408. Mix_FreeMusic(music);
  409. }
  410. currentName = musicURI;
  411. tlog5<<"Loading music file "<<musicURI<<"\n";
  412. music = Mix_LoadMUS(CResourceHandler::get()->getResourceName(ResourceID(musicURI, EResType::MUSIC)).c_str());
  413. if(!music)
  414. {
  415. tlog3 << "Warning: Cannot open " << currentName << ": " << Mix_GetError() << std::endl;
  416. return;
  417. }
  418. #ifdef _WIN32
  419. //The assertion will fail if old MSVC libraries pack .dll is used
  420. assert(Mix_GetMusicType(music) != MUS_MP3);
  421. #endif
  422. }
  423. bool MusicEntry::play()
  424. {
  425. if (!looped && music) //already played once - return
  426. return false;
  427. if (!setName.empty())
  428. {
  429. auto set = owner->musicsSet[setName];
  430. size_t entryID = rand() % set.size();
  431. auto iterator = set.begin();
  432. std::advance(iterator, entryID);
  433. load(iterator->second);
  434. }
  435. tlog5<<"Playing music file "<<currentName<<"\n";
  436. if(Mix_PlayMusic(music, 1) == -1)
  437. {
  438. tlog1 << "Unable to play music (" << Mix_GetError() << ")" << std::endl;
  439. return false;
  440. }
  441. return true;
  442. }
  443. void MusicEntry::stop(int fade_ms)
  444. {
  445. tlog5<<"Stoping music file "<<currentName<<"\n";
  446. looped = false;
  447. Mix_FadeOutMusic(fade_ms);
  448. }
  449. bool MusicEntry::isSet(std::string set)
  450. {
  451. return !setName.empty() && set == setName;
  452. }
  453. bool MusicEntry::isTrack(std::string track)
  454. {
  455. return setName.empty() && track == currentName;
  456. }