CMusicHandler.cpp 14 KB

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