CMusicHandler.cpp 13 KB

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