CMainMenu.cpp 17 KB

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