CMusicHandler.cpp 13 KB

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