CMainMenu.cpp 17 KB

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