CMainMenu.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /*
  2. * CMainMenu.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CMainMenu.h"
  12. #include "CCampaignScreen.h"
  13. #include "CreditsScreen.h"
  14. #include "../lobby/CBonusSelection.h"
  15. #include "../lobby/CSelectionBase.h"
  16. #include "../lobby/CLobbyScreen.h"
  17. #include "../../lib/filesystem/Filesystem.h"
  18. #include "../../lib/filesystem/CCompressedStream.h"
  19. #include "../gui/CursorHandler.h"
  20. #include "../CGameInfo.h"
  21. #include "../../lib/CGeneralTextHandler.h"
  22. #include "../../lib/JsonNode.h"
  23. #include "../CMusicHandler.h"
  24. #include "../CVideoHandler.h"
  25. #include "../../lib/serializer/Connection.h"
  26. #include "../../lib/serializer/CTypeList.h"
  27. #include "../../lib/VCMIDirs.h"
  28. #include "../../lib/mapping/CMap.h"
  29. #include "../windows/GUIClasses.h"
  30. #include "../CPlayerInterface.h"
  31. #include "../../CCallback.h"
  32. #include "../Client.h"
  33. #include "../gui/CGuiHandler.h"
  34. #include "../widgets/CComponent.h"
  35. #include "../widgets/Buttons.h"
  36. #include "../widgets/MiscWidgets.h"
  37. #include "../widgets/ObjectLists.h"
  38. #include "../widgets/TextControls.h"
  39. #include "../windows/InfoWindows.h"
  40. #include "../CServerHandler.h"
  41. #include "../../lib/CStopWatch.h"
  42. #include "../../lib/NetPacksLobby.h"
  43. #include "../../lib/CThreadHelper.h"
  44. #include "../../lib/CConfigHandler.h"
  45. #include "../../lib/GameConstants.h"
  46. #include "../../lib/CRandomGenerator.h"
  47. #include "../../lib/CondSh.h"
  48. #include "../../lib/mapping/CCampaignHandler.h"
  49. #include <SDL_events.h>
  50. namespace fs = boost::filesystem;
  51. std::shared_ptr<CMainMenu> CMM;
  52. ISelectionScreenInfo * SEL;
  53. static void do_quit()
  54. {
  55. SDL_Event event;
  56. event.quit.type = SDL_QUIT;
  57. SDL_PushEvent(&event);
  58. }
  59. CMenuScreen::CMenuScreen(const JsonNode & configNode)
  60. : CWindowObject(BORDERED), config(configNode)
  61. {
  62. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  63. background = std::make_shared<CPicture>(config["background"].String());
  64. if(config["scalable"].Bool())
  65. background->scaleTo(Point(screen->w, screen->h));
  66. pos = background->center();
  67. for(const JsonNode & node : config["items"].Vector())
  68. menuNameToEntry.push_back(node["name"].String());
  69. for(const JsonNode & node : config["images"].Vector())
  70. images.push_back(CMainMenu::createPicture(node));
  71. //Hardcoded entry
  72. menuNameToEntry.push_back("credits");
  73. tabs = std::make_shared<CTabbedInt>(std::bind(&CMenuScreen::createTab, this, _1));
  74. tabs->type |= REDRAW_PARENT;
  75. }
  76. std::shared_ptr<CIntObject> CMenuScreen::createTab(size_t index)
  77. {
  78. if(config["items"].Vector().size() == index)
  79. return std::make_shared<CreditsScreen>(this->pos);
  80. else
  81. return std::make_shared<CMenuEntry>(this, config["items"].Vector()[index]);
  82. }
  83. void CMenuScreen::show(SDL_Surface * to)
  84. {
  85. if(!config["video"].isNull())
  86. CCS->videoh->update((int)config["video"]["x"].Float() + pos.x, (int)config["video"]["y"].Float() + pos.y, to, true, false);
  87. CIntObject::show(to);
  88. }
  89. void CMenuScreen::activate()
  90. {
  91. CCS->musich->playMusic("Music/MainMenu", true, true);
  92. if(!config["video"].isNull())
  93. CCS->videoh->open(config["video"]["name"].String());
  94. CIntObject::activate();
  95. }
  96. void CMenuScreen::deactivate()
  97. {
  98. if(!config["video"].isNull())
  99. CCS->videoh->close();
  100. CIntObject::deactivate();
  101. }
  102. void CMenuScreen::switchToTab(size_t index)
  103. {
  104. tabs->setActive(index);
  105. }
  106. void CMenuScreen::switchToTab(std::string name)
  107. {
  108. switchToTab(vstd::find_pos(menuNameToEntry, name));
  109. }
  110. size_t CMenuScreen::getActiveTab() const
  111. {
  112. return tabs->getActive();
  113. }
  114. //funciton for std::string -> std::function conversion for main menu
  115. static std::function<void()> genCommand(CMenuScreen * menu, std::vector<std::string> menuType, const std::string & string)
  116. {
  117. static const std::vector<std::string> commandType = {"to", "campaigns", "start", "load", "exit", "highscores"};
  118. static const std::vector<std::string> gameType = {"single", "multi", "campaign", "tutorial"};
  119. std::list<std::string> commands;
  120. boost::split(commands, string, boost::is_any_of("\t "));
  121. if(!commands.empty())
  122. {
  123. size_t index = std::find(commandType.begin(), commandType.end(), commands.front()) - commandType.begin();
  124. commands.pop_front();
  125. if(index > 3 || !commands.empty())
  126. {
  127. switch(index)
  128. {
  129. case 0: //to - switch to another tab, if such tab exists
  130. {
  131. size_t index2 = std::find(menuType.begin(), menuType.end(), commands.front()) - menuType.begin();
  132. if(index2 != menuType.size())
  133. return std::bind((void(CMenuScreen::*)(size_t))&CMenuScreen::switchToTab, menu, index2);
  134. break;
  135. }
  136. case 1: //open campaign selection window
  137. {
  138. return std::bind(&CMainMenu::openCampaignScreen, CMM, commands.front());
  139. break;
  140. }
  141. case 2: //start
  142. {
  143. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  144. {
  145. case 0:
  146. return std::bind(CMainMenu::openLobby, ESelectionScreen::newGame, true, nullptr, ELoadMode::NONE);
  147. case 1:
  148. return []() { GH.pushIntT<CMultiMode>(ESelectionScreen::newGame); };
  149. case 2:
  150. return std::bind(CMainMenu::openLobby, ESelectionScreen::campaignList, true, nullptr, ELoadMode::NONE);
  151. case 3:
  152. return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  153. }
  154. break;
  155. }
  156. case 3: //load
  157. {
  158. switch(std::find(gameType.begin(), gameType.end(), commands.front()) - gameType.begin())
  159. {
  160. case 0:
  161. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::SINGLE);
  162. case 1:
  163. return []() { GH.pushIntT<CMultiMode>(ESelectionScreen::loadGame); };
  164. case 2:
  165. return std::bind(CMainMenu::openLobby, ESelectionScreen::loadGame, true, nullptr, ELoadMode::CAMPAIGN);
  166. case 3:
  167. return std::bind(CInfoWindow::showInfoDialog, "Sorry, tutorial is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  168. }
  169. }
  170. break;
  171. case 4: //exit
  172. {
  173. return std::bind(CInfoWindow::showYesNoDialog, CGI->generaltexth->allTexts[69], std::vector<std::shared_ptr<CComponent>>(), do_quit, 0, PlayerColor(1));
  174. }
  175. break;
  176. case 5: //highscores
  177. {
  178. return std::bind(CInfoWindow::showInfoDialog, "Sorry, high scores menu is not implemented yet\n", std::vector<std::shared_ptr<CComponent>>(), PlayerColor(1));
  179. }
  180. }
  181. }
  182. }
  183. logGlobal->error("Failed to parse command: %s", string);
  184. return std::function<void()>();
  185. }
  186. std::shared_ptr<CButton> CMenuEntry::createButton(CMenuScreen * parent, const JsonNode & button)
  187. {
  188. std::function<void()> command = genCommand(parent, parent->menuNameToEntry, button["command"].String());
  189. std::pair<std::string, std::string> help;
  190. if(!button["help"].isNull() && button["help"].Float() > 0)
  191. help = CGI->generaltexth->zelp[(size_t)button["help"].Float()];
  192. int posx = static_cast<int>(button["x"].Float());
  193. if(posx < 0)
  194. posx = pos.w + posx;
  195. int posy = static_cast<int>(button["y"].Float());
  196. if(posy < 0)
  197. posy = pos.h + posy;
  198. auto result = std::make_shared<CButton>(Point(posx, posy), button["name"].String(), help, command, (int)button["hotkey"].Float());
  199. if (button["center"].Bool())
  200. result->moveBy(Point(-result->pos.w/2, -result->pos.h/2));
  201. return result;
  202. }
  203. CMenuEntry::CMenuEntry(CMenuScreen * parent, const JsonNode & config)
  204. {
  205. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  206. type |= REDRAW_PARENT;
  207. pos = parent->pos;
  208. for(const JsonNode & node : config["images"].Vector())
  209. images.push_back(CMainMenu::createPicture(node));
  210. for(const JsonNode & node : config["buttons"].Vector())
  211. {
  212. buttons.push_back(createButton(parent, node));
  213. buttons.back()->hoverable = true;
  214. buttons.back()->type |= REDRAW_PARENT;
  215. }
  216. }
  217. CMainMenuConfig::CMainMenuConfig()
  218. : campaignSets(JsonNode(ResourceID("config/campaignSets.json"))), config(JsonNode(ResourceID("config/mainmenu.json")))
  219. {
  220. }
  221. CMainMenuConfig & CMainMenuConfig::get()
  222. {
  223. static CMainMenuConfig config;
  224. return config;
  225. }
  226. const JsonNode & CMainMenuConfig::getConfig() const
  227. {
  228. return config;
  229. }
  230. const JsonNode & CMainMenuConfig::getCampaigns() const
  231. {
  232. return campaignSets;
  233. }
  234. CMainMenu::CMainMenu()
  235. {
  236. pos.w = screen->w;
  237. pos.h = screen->h;
  238. GH.defActionsDef = 63;
  239. menu = std::make_shared<CMenuScreen>(CMainMenuConfig::get().getConfig()["window"]);
  240. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  241. backgroundAroundMenu = std::make_shared<CFilledTexture>("DIBOXBCK", pos);
  242. }
  243. CMainMenu::~CMainMenu()
  244. {
  245. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  246. if(GH.curInt == this)
  247. GH.curInt = nullptr;
  248. }
  249. void CMainMenu::update()
  250. {
  251. if(CMM != this->shared_from_this()) //don't update if you are not a main interface
  252. return;
  253. if(GH.listInt.empty())
  254. {
  255. GH.pushInt(CMM);
  256. GH.pushInt(menu);
  257. menu->switchToTab(menu->getActiveTab());
  258. }
  259. // Handles mouse and key input
  260. GH.updateTime();
  261. GH.handleEvents();
  262. // check for null othervice crash on finishing a campaign
  263. // /FIXME: find out why GH.listInt is empty to begin with
  264. if(GH.topInt())
  265. GH.topInt()->show(screen);
  266. }
  267. void CMainMenu::openLobby(ESelectionScreen screenType, bool host, const std::vector<std::string> * names, ELoadMode loadMode)
  268. {
  269. CSH->resetStateForLobby(screenType == ESelectionScreen::newGame ? StartInfo::NEW_GAME : StartInfo::LOAD_GAME, names);
  270. CSH->screenType = screenType;
  271. CSH->loadMode = loadMode;
  272. GH.pushIntT<CSimpleJoinScreen>(host);
  273. }
  274. void CMainMenu::openCampaignLobby(const std::string & campaignFileName)
  275. {
  276. auto ourCampaign = std::make_shared<CCampaignState>(CCampaignHandler::getCampaign(campaignFileName));
  277. openCampaignLobby(ourCampaign);
  278. }
  279. void CMainMenu::openCampaignLobby(std::shared_ptr<CCampaignState> campaign)
  280. {
  281. CSH->resetStateForLobby(StartInfo::CAMPAIGN);
  282. CSH->screenType = ESelectionScreen::campaignList;
  283. CSH->campaignStateToSend = campaign;
  284. GH.pushIntT<CSimpleJoinScreen>();
  285. }
  286. void CMainMenu::openCampaignScreen(std::string name)
  287. {
  288. if(vstd::contains(CMainMenuConfig::get().getCampaigns().Struct(), name))
  289. {
  290. GH.pushIntT<CCampaignScreen>(CMainMenuConfig::get().getCampaigns()[name]);
  291. return;
  292. }
  293. logGlobal->error("Unknown campaign set: %s", name);
  294. }
  295. std::shared_ptr<CMainMenu> CMainMenu::create()
  296. {
  297. if(!CMM)
  298. CMM = std::shared_ptr<CMainMenu>(new CMainMenu());
  299. GH.terminate_cond->setn(false);
  300. return CMM;
  301. }
  302. std::shared_ptr<CPicture> CMainMenu::createPicture(const JsonNode & config)
  303. {
  304. return std::make_shared<CPicture>(config["name"].String(), (int)config["x"].Float(), (int)config["y"].Float());
  305. }
  306. CMultiMode::CMultiMode(ESelectionScreen ScreenType)
  307. : screenType(ScreenType)
  308. {
  309. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  310. background = std::make_shared<CPicture>("MUPOPUP.bmp");
  311. pos = background->center(); //center, window has size of bg graphic
  312. picture = std::make_shared<CPicture>("MUMAP.bmp", 16, 77);
  313. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 465, 440, 18), 7, 465));
  314. playerName = std::make_shared<CTextInput>(Rect(19, 436, 334, 16), background->getSurface());
  315. playerName->setText(settings["general"]["playerName"].String());
  316. playerName->cb += std::bind(&CMultiMode::onNameChange, this, _1);
  317. buttonHotseat = std::make_shared<CButton>(Point(373, 78), "MUBHOT.DEF", CGI->generaltexth->zelp[266], std::bind(&CMultiMode::hostTCP, this));
  318. buttonHost = std::make_shared<CButton>(Point(373, 78 + 57 * 1), "MUBHOST.DEF", CButton::tooltip("Host TCP/IP game", ""), std::bind(&CMultiMode::hostTCP, this));
  319. buttonJoin = std::make_shared<CButton>(Point(373, 78 + 57 * 2), "MUBJOIN.DEF", CButton::tooltip("Join TCP/IP game", ""), std::bind(&CMultiMode::joinTCP, this));
  320. buttonCancel = std::make_shared<CButton>(Point(373, 424), "MUBCANC.DEF", CGI->generaltexth->zelp[288], [=](){ close();}, SDLK_ESCAPE);
  321. }
  322. void CMultiMode::hostTCP()
  323. {
  324. auto savedScreenType = screenType;
  325. close();
  326. GH.pushIntT<CMultiPlayers>(settings["general"]["playerName"].String(), savedScreenType, true, ELoadMode::MULTI);
  327. }
  328. void CMultiMode::joinTCP()
  329. {
  330. auto savedScreenType = screenType;
  331. close();
  332. GH.pushIntT<CMultiPlayers>(settings["general"]["playerName"].String(), savedScreenType, false, ELoadMode::MULTI);
  333. }
  334. void CMultiMode::onNameChange(std::string newText)
  335. {
  336. Settings name = settings.write["general"]["playerName"];
  337. name->String() = newText;
  338. }
  339. CMultiPlayers::CMultiPlayers(const std::string & firstPlayer, ESelectionScreen ScreenType, bool Host, ELoadMode LoadMode)
  340. : loadMode(LoadMode), screenType(ScreenType), host(Host)
  341. {
  342. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  343. background = std::make_shared<CPicture>("MUHOTSEA.bmp");
  344. pos = background->center(); //center, window has size of bg graphic
  345. std::string text = CGI->generaltexth->allTexts[446];
  346. boost::replace_all(text, "\t", "\n");
  347. textTitle = std::make_shared<CTextBox>(text, Rect(25, 20, 315, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE); //HOTSEAT Please enter names
  348. for(int i = 0; i < inputNames.size(); i++)
  349. {
  350. inputNames[i] = std::make_shared<CTextInput>(Rect(60, 85 + i * 30, 280, 16), background->getSurface());
  351. inputNames[i]->cb += std::bind(&CMultiPlayers::onChange, this, _1);
  352. }
  353. buttonOk = std::make_shared<CButton>(Point(95, 338), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CMultiPlayers::enterSelectionScreen, this), SDLK_RETURN);
  354. buttonCancel = std::make_shared<CButton>(Point(205, 338), "MUBCANC.DEF", CGI->generaltexth->zelp[561], [=](){ close();}, SDLK_ESCAPE);
  355. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 381, 348, 18), 7, 381));
  356. inputNames[0]->setText(firstPlayer, true);
  357. #ifndef VCMI_IOS
  358. inputNames[0]->giveFocus();
  359. #endif
  360. }
  361. void CMultiPlayers::onChange(std::string newText)
  362. {
  363. }
  364. void CMultiPlayers::enterSelectionScreen()
  365. {
  366. std::vector<std::string> names;
  367. for(auto name : inputNames)
  368. {
  369. if(name->getText().length())
  370. names.push_back(name->getText());
  371. }
  372. Settings name = settings.write["general"]["playerName"];
  373. name->String() = names[0];
  374. CMainMenu::openLobby(screenType, host, &names, loadMode);
  375. }
  376. CSimpleJoinScreen::CSimpleJoinScreen(bool host)
  377. {
  378. OBJ_CONSTRUCTION_CAPTURING_ALL_NO_DISPOSE;
  379. background = std::make_shared<CPicture>("MUDIALOG.bmp"); // address background
  380. pos = background->center(); //center, window has size of bg graphic (x,y = 396,278 w=232 h=212)
  381. textTitle = std::make_shared<CTextBox>("", Rect(20, 20, 205, 50), 0, FONT_BIG, ETextAlignment::CENTER, Colors::WHITE);
  382. inputAddress = std::make_shared<CTextInput>(Rect(25, 68, 175, 16), background->getSurface());
  383. inputPort = std::make_shared<CTextInput>(Rect(25, 115, 175, 16), background->getSurface());
  384. if(host && !settings["session"]["donotstartserver"].Bool())
  385. {
  386. textTitle->setText("Connecting...");
  387. boost::thread(&CSimpleJoinScreen::connectThread, this, "", 0);
  388. }
  389. else
  390. {
  391. textTitle->setText("Enter address:");
  392. inputAddress->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  393. inputPort->cb += std::bind(&CSimpleJoinScreen::onChange, this, _1);
  394. inputPort->filters += std::bind(&CTextInput::numberFilter, _1, _2, 0, 65535);
  395. buttonOk = std::make_shared<CButton>(Point(26, 142), "MUBCHCK.DEF", CGI->generaltexth->zelp[560], std::bind(&CSimpleJoinScreen::connectToServer, this), SDLK_RETURN);
  396. inputAddress->giveFocus();
  397. }
  398. inputAddress->setText(host ? CServerHandler::localhostAddress : CSH->getHostAddress(), true);
  399. inputPort->setText(boost::lexical_cast<std::string>(CSH->getHostPort()), true);
  400. buttonCancel = std::make_shared<CButton>(Point(142, 142), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), SDLK_ESCAPE);
  401. statusBar = CGStatusBar::create(std::make_shared<CPicture>(background->getSurface(), Rect(7, 186, 218, 18), 7, 186));
  402. }
  403. void CSimpleJoinScreen::connectToServer()
  404. {
  405. textTitle->setText("Connecting...");
  406. buttonOk->block(true);
  407. GH.stopTextInput();
  408. boost::thread(&CSimpleJoinScreen::connectThread, this, inputAddress->getText(), boost::lexical_cast<ui16>(inputPort->getText()));
  409. }
  410. void CSimpleJoinScreen::leaveScreen()
  411. {
  412. if(CSH->state == EClientState::CONNECTING)
  413. {
  414. textTitle->setText("Closing...");
  415. CSH->state = EClientState::CONNECTION_CANCELLED;
  416. }
  417. else if(GH.listInt.size() && GH.listInt.front().get() == this)
  418. {
  419. close();
  420. }
  421. }
  422. void CSimpleJoinScreen::onChange(const std::string & newText)
  423. {
  424. buttonOk->block(inputAddress->getText().empty() || inputPort->getText().empty());
  425. }
  426. void CSimpleJoinScreen::connectThread(const std::string addr, const ui16 port)
  427. {
  428. setThreadName("CSimpleJoinScreen::connectThread");
  429. if(!addr.length())
  430. CSH->startLocalServerAndConnect();
  431. else
  432. CSH->justConnectToServer(addr, port);
  433. if(GH.listInt.size() && GH.listInt.front().get() == this)
  434. {
  435. close();
  436. }
  437. }
  438. CLoadingScreen::CLoadingScreen(std::function<void()> loader)
  439. : CWindowObject(BORDERED, getBackground()), loadingThread(loader)
  440. {
  441. CCS->musich->stopMusic(5000);
  442. }
  443. CLoadingScreen::~CLoadingScreen()
  444. {
  445. loadingThread.join();
  446. }
  447. void CLoadingScreen::showAll(SDL_Surface * to)
  448. {
  449. //FIXME: filling screen with transparency? BLACK intended?
  450. //Rect rect(0, 0, to->w, to->h);
  451. //CSDL_Ext::fillRect(to, rect, Colors::TRANSPARENCY);
  452. CWindowObject::showAll(to);
  453. }
  454. std::string CLoadingScreen::getBackground()
  455. {
  456. const auto & conf = CMainMenuConfig::get().getConfig()["loading"].Vector();
  457. if(conf.empty())
  458. {
  459. return "loadbar";
  460. }
  461. else
  462. {
  463. return RandomGeneratorUtil::nextItem(conf, CRandomGenerator::getDefault())->String();
  464. }
  465. }