CMusicHandler.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. #include "../stdafx.h"
  2. #include <sstream>
  3. #include <boost/assign/std/vector.hpp>
  4. #include <boost/assign/list_of.hpp>
  5. #include <boost/bimap.hpp>
  6. #include <SDL_mixer.h>
  7. #include "CSndHandler.h"
  8. #include "CMusicHandler.h"
  9. #include "../lib/CCreatureHandler.h"
  10. #include "../lib/CSpellHandler.h"
  11. #include "../client/CGameInfo.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(unsigned int percent)
  52. {
  53. if (percent > 100)
  54. percent = 100;
  55. volume = percent;
  56. }
  57. CSoundHandler::CSoundHandler()
  58. {
  59. // Map sound names
  60. #define VCMI_SOUND_NAME(x) ( soundBase::x,
  61. #define VCMI_SOUND_FILE(y) #y )
  62. sounds = boost::assign::list_of<boost::bimap<soundBase::soundID, std::string>::relation>
  63. VCMI_SOUND_LIST;
  64. #undef VCMI_SOUND_NAME
  65. #undef VCMI_SOUND_FILE
  66. // Vectors for helper(s)
  67. pickupSounds += soundBase::pickup01, soundBase::pickup02, soundBase::pickup03,
  68. soundBase::pickup04, soundBase::pickup05, soundBase::pickup06, soundBase::pickup07;
  69. horseSounds += // must be the same order as terrains (see EterrainType);
  70. soundBase::horseDirt, soundBase::horseSand, soundBase::horseGrass,
  71. soundBase::horseSnow, soundBase::horseSwamp, soundBase::horseRough,
  72. soundBase::horseSubterranean, soundBase::horseLava,
  73. soundBase::horseWater, soundBase::horseRock;
  74. battleIntroSounds += soundBase::battle00, soundBase::battle01,
  75. soundBase::battle02, soundBase::battle03, soundBase::battle04,
  76. soundBase::battle05, soundBase::battle06, soundBase::battle07;
  77. };
  78. void CSoundHandler::init()
  79. {
  80. CAudioBase::init();
  81. if (initialized)
  82. {
  83. // Load sounds
  84. sndh.add_file(std::string(DATA_DIR "/Data/Heroes3.snd"));
  85. sndh.add_file(std::string(DATA_DIR "/Data/Heroes3-cd2.snd"));
  86. sndh.add_file(std::string(DATA_DIR "/Data/H3ab_ahd.snd"));
  87. Mix_ChannelFinished(soundFinishedCallbackC);
  88. }
  89. }
  90. void CSoundHandler::release()
  91. {
  92. if (initialized)
  93. {
  94. Mix_HaltChannel(-1);
  95. std::map<soundBase::soundID, Mix_Chunk *>::iterator it;
  96. for (it=soundChunks.begin(); it != soundChunks.end(); it++)
  97. {
  98. if (it->second)
  99. Mix_FreeChunk(it->second);
  100. }
  101. }
  102. CAudioBase::release();
  103. }
  104. // Allocate an SDL chunk and cache it.
  105. Mix_Chunk *CSoundHandler::GetSoundChunk(soundBase::soundID soundID)
  106. {
  107. // Find its name
  108. boost::bimap<soundBase::soundID, std::string>::left_iterator it;
  109. it = sounds.left.find(soundID);
  110. if (it == sounds.left.end())
  111. return NULL;
  112. // Load and insert
  113. int size;
  114. const char *data = sndh.extract(it->second, size);
  115. if (!data)
  116. return NULL;
  117. SDL_RWops *ops = SDL_RWFromConstMem(data, size);
  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(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.txt" << std::endl;
  141. std::ifstream ifs(DATA_DIR "/config/cr_sounds.txt");
  142. std::string line;
  143. CBattleSounds.resize(creatures.size());
  144. while(getline(ifs, line))
  145. {
  146. std::string cname="", attack="", defend="", killed="", move="",
  147. shoot="", wince="", ext1="", ext2="";
  148. std::istringstream str(line);
  149. str >> cname >> attack >> defend >> killed >> move >> shoot >> wince >> ext1 >> ext2;
  150. if (!line.size() || cname[0] == '#')
  151. // That's a comment. Discard.
  152. continue;
  153. if (str.good() || (str.eof() && wince != ""))
  154. {
  155. int id = -1;
  156. bmap<std::string,int>::const_iterator i = CGI->creh->nameToID.find(cname);
  157. if(i != CGI->creh->nameToID.end())
  158. id = i->second;
  159. else
  160. {
  161. tlog1 << "Sound info for an unknown creature: " << cname << std::endl;
  162. continue;
  163. }
  164. if (CBattleSounds[id].killed != soundBase::invalid)
  165. tlog1 << "Creature << " << cname << " already has sounds" << std::endl;
  166. CBattleSounds[id].attack = getSoundID(attack);
  167. CBattleSounds[id].defend = getSoundID(defend);
  168. CBattleSounds[id].killed = getSoundID(killed);
  169. CBattleSounds[id].move = getSoundID(move);
  170. CBattleSounds[id].shoot = getSoundID(shoot);
  171. CBattleSounds[id].wince = getSoundID(wince);
  172. CBattleSounds[id].ext1 = getSoundID(ext1);
  173. CBattleSounds[id].ext2 = getSoundID(ext2);
  174. // Special creatures
  175. if (id == 55 || // Archdevil
  176. id == 62 || // Vampire
  177. id == 62) // Vampire Lord
  178. {
  179. CBattleSounds[id].startMoving = CBattleSounds[id].ext1;
  180. CBattleSounds[id].endMoving = CBattleSounds[id].ext2;
  181. }
  182. }
  183. }
  184. ifs.close();
  185. ifs.clear();
  186. //commented to avoid spurious warnings
  187. /*
  188. // Find creatures without sounds
  189. for(unsigned int i=0;i<creatures.size();i++)
  190. {
  191. // Note: this will exclude war machines, but it's better
  192. // than nothing.
  193. if (vstd::contains(CGI->creh->notUsedMonsters, i))
  194. continue;
  195. CCreature &c = creatures[i];
  196. if (c.sounds.killed == soundBase::invalid)
  197. tlog1 << "creature " << c.idNumber << " doesn't have sounds" << std::endl;
  198. }*/
  199. }
  200. void CSoundHandler::initSpellsSounds(const std::vector< ConstTransitivePtr<CSpell> > &spells)
  201. {
  202. tlog5 << "\t\tReading config/sp_sounds.txt" << std::endl;
  203. std::ifstream ifs(DATA_DIR "/config/sp_sounds.txt");
  204. std::string line;
  205. while(getline(ifs, line))
  206. {
  207. int spellid;
  208. std::string soundfile="";
  209. std::istringstream str(line);
  210. str >> spellid >> soundfile;
  211. if (str.good() || (str.eof() && soundfile != ""))
  212. {
  213. const CSpell *s = CGI->spellh->spells[spellid];
  214. if (vstd::contains(spellSounds, s))
  215. {
  216. tlog1 << "Spell << " << spellid << " already has a sound" << std::endl;
  217. }
  218. spellSounds[s] = getSoundID(soundfile);
  219. }
  220. }
  221. ifs.close();
  222. ifs.clear();
  223. }
  224. // Plays a sound, and return its channel so we can fade it out later
  225. int CSoundHandler::playSound(soundBase::soundID soundID, int repeats)
  226. {
  227. if (!initialized)
  228. return -1;
  229. int channel;
  230. Mix_Chunk *chunk = GetSoundChunk(soundID);
  231. if (chunk)
  232. {
  233. channel = Mix_PlayChannel(-1, chunk, repeats);
  234. if (channel == -1)
  235. tlog1 << "Unable to play sound file " << soundID << " , error " << Mix_GetError() << std::endl;
  236. else
  237. callbacks[channel];//insert empty callback
  238. }
  239. else
  240. {
  241. channel = -1;
  242. }
  243. return channel;
  244. }
  245. // Helper. Randomly select a sound from an array and play it
  246. int CSoundHandler::playSoundFromSet(std::vector<soundBase::soundID> &sound_vec)
  247. {
  248. return playSound(sound_vec[rand() % sound_vec.size()]);
  249. }
  250. void CSoundHandler::stopSound( int handler )
  251. {
  252. if (initialized && handler != -1)
  253. Mix_HaltChannel(handler);
  254. }
  255. // Sets the sound volume, from 0 (mute) to 100
  256. void CSoundHandler::setVolume(unsigned int percent)
  257. {
  258. CAudioBase::setVolume(percent);
  259. if (initialized)
  260. Mix_Volume(-1, (MIX_MAX_VOLUME * volume)/100);
  261. }
  262. void CSoundHandler::setCallback(int channel, boost::function<void()> function)
  263. {
  264. std::map<int, boost::function<void()> >::iterator iter;
  265. iter = callbacks.find(channel);
  266. //channel not found. It may have finished so fire callback now
  267. if(iter == callbacks.end())
  268. function();
  269. else
  270. iter->second = function;
  271. }
  272. void CSoundHandler::soundFinishedCallback(int channel)
  273. {
  274. std::map<int, boost::function<void()> >::iterator iter;
  275. iter = callbacks.find(channel);
  276. assert(iter != callbacks.end());
  277. if (iter->second)
  278. iter->second();
  279. callbacks.erase(iter);
  280. }
  281. CMusicHandler::CMusicHandler()
  282. {
  283. // Map music IDs
  284. #define VCMI_MUSIC_ID(x) ( musicBase::x ,
  285. #define VCMI_MUSIC_FILE(y) y )
  286. musics = map_list_of
  287. VCMI_MUSIC_LIST;
  288. #undef VCMI_MUSIC_NAME
  289. #undef VCMI_MUSIC_FILE
  290. // Vectors for helper
  291. battleMusics += musicBase::combat1, musicBase::combat2,
  292. musicBase::combat3, musicBase::combat4;
  293. townMusics += musicBase::castleTown, musicBase::rampartTown,
  294. musicBase::towerTown, musicBase::infernoTown,
  295. musicBase::necroTown, musicBase::dungeonTown,
  296. musicBase::strongHoldTown, musicBase::fortressTown,
  297. musicBase::elemTown;
  298. terrainMusics += musicBase::dirt, musicBase::sand, musicBase::grass,
  299. musicBase::snow, musicBase::swamp, musicBase::rough,
  300. musicBase::underground, musicBase::lava,musicBase::water;
  301. }
  302. void CMusicHandler::init()
  303. {
  304. CAudioBase::init();
  305. if (initialized)
  306. Mix_HookMusicFinished(musicFinishedCallbackC);
  307. }
  308. void CMusicHandler::release()
  309. {
  310. if (initialized)
  311. {
  312. boost::mutex::scoped_lock guard(musicMutex);
  313. Mix_HookMusicFinished(NULL);
  314. current.reset();
  315. next.reset();
  316. }
  317. CAudioBase::release();
  318. }
  319. // Plays a music
  320. // loop: -1 always repeats, 0=do not play, 1+=number of loops
  321. void CMusicHandler::playMusic(musicBase::musicID musicID, int loop)
  322. {
  323. if (current.get() != NULL && *current == musicID)
  324. return;
  325. queueNext(new MusicEntry(this, musicID, loop));
  326. }
  327. // Helper. Randomly plays tracks from music_vec
  328. void CMusicHandler::playMusicFromSet(std::vector<musicBase::musicID> &music_vec, int loop)
  329. {
  330. if (current.get() != NULL && *current == music_vec)
  331. return;
  332. queueNext(new MusicEntry(this, music_vec, loop));
  333. }
  334. void CMusicHandler::queueNext(MusicEntry *queued)
  335. {
  336. if (!initialized)
  337. return;
  338. boost::mutex::scoped_lock guard(musicMutex);
  339. next.reset(queued);
  340. if (current.get() != NULL)
  341. {
  342. current->stop(1000);
  343. }
  344. else
  345. {
  346. current = next;
  347. current->play();
  348. }
  349. }
  350. // Stop and free the current music
  351. void CMusicHandler::stopMusic(int fade_ms)
  352. {
  353. if (!initialized)
  354. return;
  355. boost::mutex::scoped_lock guard(musicMutex);
  356. if (current.get() != NULL)
  357. current->stop(fade_ms);
  358. next.reset();
  359. }
  360. // Sets the music volume, from 0 (mute) to 100
  361. void CMusicHandler::setVolume(unsigned int percent)
  362. {
  363. CAudioBase::setVolume(percent);
  364. if (initialized)
  365. Mix_VolumeMusic((MIX_MAX_VOLUME * volume)/100);
  366. }
  367. // Called by SDL when a music finished.
  368. void CMusicHandler::musicFinishedCallback(void)
  369. {
  370. boost::mutex::scoped_lock guard(musicMutex);
  371. if (current.get() != NULL)
  372. {
  373. //return if current music still not finished
  374. if (current->play())
  375. return;
  376. else
  377. current.reset();
  378. }
  379. if (current.get() == NULL && next.get() != NULL)
  380. {
  381. current = next;
  382. current->play();
  383. }
  384. }
  385. MusicEntry::MusicEntry(CMusicHandler *_owner, musicBase::musicID _musicID, int _loopCount):
  386. owner(_owner),
  387. music(NULL),
  388. loopCount(_loopCount)
  389. {
  390. load(_musicID);
  391. }
  392. MusicEntry::MusicEntry(CMusicHandler *_owner, std::vector<musicBase::musicID> &_musicVec, int _loopCount):
  393. currentID(musicBase::music_todo),
  394. owner(_owner),
  395. music(NULL),
  396. loopCount(_loopCount),
  397. musicVec(_musicVec)
  398. {
  399. //In this case music will be loaded only on playing - no need to call load() here
  400. }
  401. MusicEntry::~MusicEntry()
  402. {
  403. tlog5<<"Del-ing music file "<<filename<<"\n";
  404. if (music)
  405. Mix_FreeMusic(music);
  406. }
  407. void MusicEntry::load(musicBase::musicID ID)
  408. {
  409. currentID = ID;
  410. filename = DATA_DIR "/Mp3/";
  411. filename += owner->musics[ID];
  412. tlog5<<"Loading music file "<<filename<<"\n";
  413. if (music)
  414. Mix_FreeMusic(music);
  415. music = Mix_LoadMUS(filename.c_str());
  416. #ifdef _WIN32
  417. //The assertion will fail if old MSVC libraries pack .dll is used
  418. assert(Mix_GetMusicType(music) == MUS_MP3_MAD);
  419. #endif
  420. }
  421. bool MusicEntry::play()
  422. {
  423. tlog5<<"Playing music file "<<filename<<"\n";
  424. if (loopCount == 0)
  425. return false;
  426. if (loopCount > 0)
  427. loopCount--;
  428. if (!musicVec.empty())
  429. load(musicVec.at(rand() % musicVec.size()));
  430. if(Mix_PlayMusic(music, 1) == -1)
  431. {
  432. tlog1 << "Unable to play music (" << Mix_GetError() << ")" << std::endl;
  433. return false;
  434. }
  435. return true;
  436. }
  437. void MusicEntry::stop(int fade_ms)
  438. {
  439. tlog5<<"Stoping music file "<<filename<<"\n";
  440. loopCount = 0;
  441. Mix_FadeOutMusic(fade_ms);
  442. }
  443. bool MusicEntry::operator == (musicBase::musicID _musicID) const
  444. {
  445. return musicVec.empty() && currentID == _musicID;
  446. }
  447. bool MusicEntry::operator == (std::vector<musicBase::musicID> &_musicVec) const
  448. {
  449. return musicVec == _musicVec;
  450. }