CVCMIServer.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  1. /*
  2. * CVCMIServer.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 "CVCMIServer.h"
  12. #include "CGameHandler.h"
  13. #include "GlobalLobbyProcessor.h"
  14. #include "LobbyNetPackVisitors.h"
  15. #include "processors/PlayerMessageProcessor.h"
  16. #include "../lib/CPlayerState.h"
  17. #include "../lib/campaign/CampaignState.h"
  18. #include "../lib/entities/hero/CHeroHandler.h"
  19. #include "../lib/entities/hero/CHeroClass.h"
  20. #include "../lib/gameState/CGameState.h"
  21. #include "../lib/mapping/CMapDefines.h"
  22. #include "../lib/mapping/CMapInfo.h"
  23. #include "../lib/mapping/CMapHeader.h"
  24. #include "../lib/rmg/CMapGenOptions.h"
  25. #include "../lib/serializer/CMemorySerializer.h"
  26. #include "../lib/serializer/Connection.h"
  27. #include "../lib/texts/CGeneralTextHandler.h"
  28. // UUID generation
  29. #include <boost/uuid/uuid.hpp>
  30. #include <boost/uuid/uuid_io.hpp>
  31. #include <boost/uuid/uuid_generators.hpp>
  32. #include <boost/program_options.hpp>
  33. class CVCMIServerPackVisitor : public VCMI_LIB_WRAP_NAMESPACE(ICPackVisitor)
  34. {
  35. private:
  36. CVCMIServer & handler;
  37. std::shared_ptr<CGameHandler> gh;
  38. public:
  39. CVCMIServerPackVisitor(CVCMIServer & handler, std::shared_ptr<CGameHandler> gh)
  40. :handler(handler), gh(gh)
  41. {
  42. }
  43. bool callTyped() override { return false; }
  44. void visitForLobby(CPackForLobby & packForLobby) override
  45. {
  46. handler.handleReceivedPack(packForLobby);
  47. }
  48. void visitForServer(CPackForServer & serverPack) override
  49. {
  50. if (gh)
  51. gh->handleReceivedPack(serverPack);
  52. else
  53. logNetwork->error("Received pack for game server while in lobby!");
  54. }
  55. void visitForClient(CPackForClient & clientPack) override
  56. {
  57. }
  58. };
  59. CVCMIServer::CVCMIServer(uint16_t port, bool runByClient)
  60. : currentClientId(1)
  61. , currentPlayerId(1)
  62. , port(port)
  63. , runByClient(runByClient)
  64. {
  65. uuid = boost::uuids::to_string(boost::uuids::random_generator()());
  66. logNetwork->trace("CVCMIServer created! UUID: %s", uuid);
  67. networkHandler = INetworkHandler::createHandler();
  68. }
  69. CVCMIServer::~CVCMIServer() = default;
  70. uint16_t CVCMIServer::prepare(bool connectToLobby) {
  71. if(connectToLobby) {
  72. lobbyProcessor = std::make_unique<GlobalLobbyProcessor>(*this);
  73. return 0;
  74. } else {
  75. return startAcceptingIncomingConnections();
  76. }
  77. }
  78. uint16_t CVCMIServer::startAcceptingIncomingConnections()
  79. {
  80. port
  81. ? logNetwork->info("Port %d will be used", port)
  82. : logNetwork->info("Randomly assigned port will be used");
  83. // config port may be 0 => srvport will contain the OS-assigned port value
  84. networkServer = networkHandler->createServerTCP(*this);
  85. auto srvport = networkServer->start(port);
  86. logNetwork->info("Listening for connections at port %d", srvport);
  87. return srvport;
  88. }
  89. void CVCMIServer::onNewConnection(const std::shared_ptr<INetworkConnection> & connection)
  90. {
  91. if(getState() == EServerState::LOBBY)
  92. {
  93. activeConnections.push_back(std::make_shared<CConnection>(connection));
  94. activeConnections.back()->enterLobbyConnectionMode();
  95. }
  96. else
  97. {
  98. // TODO: reconnection support
  99. connection->close();
  100. }
  101. }
  102. void CVCMIServer::onPacketReceived(const std::shared_ptr<INetworkConnection> & connection, const std::vector<std::byte> & message)
  103. {
  104. std::shared_ptr<CConnection> c = findConnection(connection);
  105. if (c == nullptr)
  106. throw std::out_of_range("Unknown connection received in CVCMIServer::findConnection");
  107. auto pack = c->retrievePack(message);
  108. pack->c = c;
  109. CVCMIServerPackVisitor visitor(*this, this->gh);
  110. pack->visit(visitor);
  111. }
  112. void CVCMIServer::setState(EServerState value)
  113. {
  114. if (value == EServerState::SHUTDOWN && state == EServerState::SHUTDOWN)
  115. logGlobal->warn("Attempt to shutdown already shutdown server!");
  116. // do not attempt to restart dying server
  117. assert(state != EServerState::SHUTDOWN || state == value);
  118. state = value;
  119. if (state == EServerState::SHUTDOWN)
  120. networkHandler->stop();
  121. }
  122. EServerState CVCMIServer::getState() const
  123. {
  124. return state;
  125. }
  126. std::shared_ptr<CConnection> CVCMIServer::findConnection(const std::shared_ptr<INetworkConnection> & netConnection)
  127. {
  128. for(const auto & gameConnection : activeConnections)
  129. {
  130. if (gameConnection->isMyConnection(netConnection))
  131. return gameConnection;
  132. }
  133. return nullptr;
  134. }
  135. bool CVCMIServer::wasStartedByClient() const
  136. {
  137. return runByClient;
  138. }
  139. void CVCMIServer::run()
  140. {
  141. networkHandler->run();
  142. }
  143. void CVCMIServer::onTimer()
  144. {
  145. // we might receive onTimer call after transitioning from GAMEPLAY to LOBBY state, e.g. on game restart
  146. if (getState() != EServerState::GAMEPLAY)
  147. return;
  148. static const auto serverUpdateInterval = std::chrono::milliseconds(100);
  149. auto timeNow = std::chrono::steady_clock::now();
  150. auto timePassedBefore = lastTimerUpdateTime - gameplayStartTime;
  151. auto timePassedNow = timeNow - gameplayStartTime;
  152. lastTimerUpdateTime = timeNow;
  153. auto msPassedBefore = std::chrono::duration_cast<std::chrono::milliseconds>(timePassedBefore);
  154. auto msPassedNow = std::chrono::duration_cast<std::chrono::milliseconds>(timePassedNow);
  155. auto msDelta = msPassedNow - msPassedBefore;
  156. if (msDelta.count())
  157. gh->tick(msDelta.count());
  158. networkHandler->createTimer(*this, serverUpdateInterval);
  159. }
  160. void CVCMIServer::prepareToRestart()
  161. {
  162. if(getState() != EServerState::GAMEPLAY)
  163. {
  164. assert(0);
  165. return;
  166. }
  167. * si = * gh->gs->initialOpts;
  168. setState(EServerState::LOBBY);
  169. if (si->campState)
  170. {
  171. assert(si->campState->currentScenario().has_value());
  172. campaignMap = si->campState->currentScenario().value_or(CampaignScenarioID(0));
  173. campaignBonus = si->campState->getBonusID(campaignMap).value_or(-1);
  174. }
  175. for(auto activeConnection : activeConnections)
  176. activeConnection->enterLobbyConnectionMode();
  177. gh = nullptr;
  178. }
  179. bool CVCMIServer::prepareToStartGame()
  180. {
  181. Load::ProgressAccumulator progressTracking;
  182. Load::Progress current(1);
  183. progressTracking.include(current);
  184. if (lobbyProcessor)
  185. lobbyProcessor->sendGameStarted();
  186. auto progressTrackingThread = boost::thread([this, &progressTracking]()
  187. {
  188. auto currentProgress = std::numeric_limits<Load::Type>::max();
  189. while(!progressTracking.finished())
  190. {
  191. if(progressTracking.get() != currentProgress)
  192. {
  193. //FIXME: UNGUARDED MULTITHREADED ACCESS!!!
  194. currentProgress = progressTracking.get();
  195. LobbyLoadProgress loadProgress;
  196. loadProgress.progress = currentProgress;
  197. announcePack(loadProgress);
  198. }
  199. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  200. }
  201. });
  202. gh = std::make_shared<CGameHandler>(this);
  203. switch(si->mode)
  204. {
  205. case EStartMode::CAMPAIGN:
  206. logNetwork->info("Preparing to start new campaign");
  207. si->startTime = std::time(nullptr);
  208. si->fileURI = mi->fileURI;
  209. si->campState->setCurrentMap(campaignMap);
  210. si->campState->setCurrentMapBonus(campaignBonus);
  211. gh->init(si.get(), progressTracking);
  212. break;
  213. case EStartMode::NEW_GAME:
  214. logNetwork->info("Preparing to start new game");
  215. si->startTime = std::time(nullptr);
  216. si->fileURI = mi->fileURI;
  217. gh->init(si.get(), progressTracking);
  218. break;
  219. case EStartMode::LOAD_GAME:
  220. logNetwork->info("Preparing to start loaded game");
  221. if(!gh->load(si->mapname))
  222. {
  223. current.finish();
  224. progressTrackingThread.join();
  225. return false;
  226. }
  227. break;
  228. default:
  229. logNetwork->error("Wrong mode in StartInfo!");
  230. assert(0);
  231. break;
  232. }
  233. current.finish();
  234. progressTrackingThread.join();
  235. return true;
  236. }
  237. void CVCMIServer::startGameImmediately()
  238. {
  239. for(auto activeConnection : activeConnections)
  240. activeConnection->enterGameplayConnectionMode(gh->gs);
  241. gh->start(si->mode == EStartMode::LOAD_GAME);
  242. setState(EServerState::GAMEPLAY);
  243. lastTimerUpdateTime = gameplayStartTime = std::chrono::steady_clock::now();
  244. onTimer();
  245. multiplayerWelcomeMessage();
  246. }
  247. void CVCMIServer::onDisconnected(const std::shared_ptr<INetworkConnection> & connection, const std::string & errorMessage)
  248. {
  249. logNetwork->error("Network error receiving a pack. Connection has been closed");
  250. std::shared_ptr<CConnection> c = findConnection(connection);
  251. // player may have already disconnected via clientDisconnected call
  252. if (c)
  253. {
  254. LobbyClientDisconnected lcd;
  255. lcd.c = c;
  256. lcd.clientId = c->connectionID;
  257. handleReceivedPack(lcd);
  258. }
  259. }
  260. void CVCMIServer::handleReceivedPack(CPackForLobby & pack)
  261. {
  262. ClientPermissionsCheckerNetPackVisitor checker(*this);
  263. pack.visit(checker);
  264. if(checker.getResult())
  265. {
  266. ApplyOnServerNetPackVisitor applier(*this);
  267. pack.visit(applier);
  268. if (applier.getResult())
  269. announcePack(pack);
  270. }
  271. }
  272. void CVCMIServer::announcePack(CPackForLobby & pack)
  273. {
  274. for(auto activeConnection : activeConnections)
  275. {
  276. // FIXME: we need to avoid sending something to client that not yet get answer for LobbyClientConnected
  277. // Until UUID set we only pass LobbyClientConnected to this client
  278. //if(c->uuid == uuid && !dynamic_cast<LobbyClientConnected *>(pack.get()))
  279. // continue;
  280. activeConnection->sendPack(pack);
  281. }
  282. ApplyOnServerAfterAnnounceNetPackVisitor applier(*this);
  283. pack.visit(applier);
  284. }
  285. void CVCMIServer::announceMessage(const MetaString & txt)
  286. {
  287. logNetwork->info("Show message: %s", txt.toString());
  288. LobbyShowMessage cm;
  289. cm.message = txt;
  290. announcePack(cm);
  291. }
  292. void CVCMIServer::announceMessage(const std::string & txt)
  293. {
  294. MetaString str;
  295. str.appendRawString(txt);
  296. announceMessage(str);
  297. }
  298. void CVCMIServer::announceTxt(const MetaString & txt, const std::string & playerName)
  299. {
  300. logNetwork->info("%s says: %s", playerName, txt.toString());
  301. LobbyChatMessage cm;
  302. cm.playerName = playerName;
  303. cm.message = txt;
  304. announcePack(cm);
  305. }
  306. void CVCMIServer::announceTxt(const std::string & txt, const std::string & playerName)
  307. {
  308. MetaString str;
  309. str.appendRawString(txt);
  310. announceTxt(str, playerName);
  311. }
  312. bool CVCMIServer::passHost(int toConnectionId)
  313. {
  314. for(auto activeConnection : activeConnections)
  315. {
  316. if(isClientHost(activeConnection->connectionID))
  317. continue;
  318. if(activeConnection->connectionID != toConnectionId)
  319. continue;
  320. hostClientId = activeConnection->connectionID;
  321. announceTxt(boost::str(boost::format("Pass host to connection %d") % toConnectionId));
  322. return true;
  323. }
  324. return false;
  325. }
  326. void CVCMIServer::clientConnected(std::shared_ptr<CConnection> c, std::vector<std::string> & names, const std::string & uuid, EStartMode mode)
  327. {
  328. assert(getState() == EServerState::LOBBY);
  329. c->connectionID = currentClientId++;
  330. if(hostClientId == -1)
  331. {
  332. hostClientId = c->connectionID;
  333. si->mode = mode;
  334. }
  335. logNetwork->info("Connection with client %d established. UUID: %s", c->connectionID, c->uuid);
  336. for(auto & name : names)
  337. {
  338. logNetwork->info("Client %d player: %s", c->connectionID, name);
  339. ui8 id = currentPlayerId++;
  340. ClientPlayer cp;
  341. cp.connection = c->connectionID;
  342. cp.name = name;
  343. playerNames.insert(std::make_pair(id, cp));
  344. announceTxt(boost::str(boost::format("%s (pid %d cid %d) joins the game") % name % id % c->connectionID));
  345. //put new player in first slot with AI
  346. for(auto & elem : si->playerInfos)
  347. {
  348. if(elem.second.isControlledByAI() && !elem.second.compOnly)
  349. {
  350. setPlayerConnectedId(elem.second, id);
  351. break;
  352. }
  353. }
  354. }
  355. }
  356. void CVCMIServer::clientDisconnected(std::shared_ptr<CConnection> connection)
  357. {
  358. assert(vstd::contains(activeConnections, connection));
  359. logGlobal->trace("Received disconnection request");
  360. vstd::erase(activeConnections, connection);
  361. if(activeConnections.empty() || hostClientId == connection->connectionID)
  362. {
  363. setState(EServerState::SHUTDOWN);
  364. return;
  365. }
  366. if(gh && getState() == EServerState::GAMEPLAY)
  367. {
  368. gh->handleClientDisconnection(connection);
  369. }
  370. // PlayerReinitInterface startAiPack;
  371. // startAiPack.playerConnectionId = PlayerSettings::PLAYER_AI;
  372. //
  373. // for(auto it = playerNames.begin(); it != playerNames.end();)
  374. // {
  375. // if(it->second.connection != c->connectionID)
  376. // {
  377. // ++it;
  378. // continue;
  379. // }
  380. //
  381. // int id = it->first;
  382. // std::string playerLeftMsgText = boost::str(boost::format("%s (pid %d cid %d) left the game") % id % playerNames[id].name % c->connectionID);
  383. // announceTxt(playerLeftMsgText); //send lobby text, it will be ignored for non-lobby clients
  384. // auto * playerSettings = si->getPlayersSettings(id);
  385. // if(!playerSettings)
  386. // {
  387. // ++it;
  388. // continue;
  389. // }
  390. //
  391. // it = playerNames.erase(it);
  392. // setPlayerConnectedId(*playerSettings, PlayerSettings::PLAYER_AI);
  393. //
  394. // if(gh && si && state == EServerState::GAMEPLAY)
  395. // {
  396. // gh->playerMessages->broadcastMessage(playerSettings->color, playerLeftMsgText);
  397. // // gh->connections[playerSettings->color].insert(hostClient);
  398. // startAiPack.players.push_back(playerSettings->color);
  399. // }
  400. // }
  401. //
  402. // if(!startAiPack.players.empty())
  403. // gh->sendAndApply(startAiPack);
  404. }
  405. void CVCMIServer::reconnectPlayer(int connId)
  406. {
  407. PlayerReinitInterface startAiPack;
  408. startAiPack.playerConnectionId = connId;
  409. if(gh && si && getState() == EServerState::GAMEPLAY)
  410. {
  411. for(auto it = playerNames.begin(); it != playerNames.end(); ++it)
  412. {
  413. if(it->second.connection != connId)
  414. continue;
  415. int id = it->first;
  416. auto * playerSettings = si->getPlayersSettings(id);
  417. if(!playerSettings)
  418. continue;
  419. std::string messageText = boost::str(boost::format("%s (cid %d) is connected") % playerSettings->name % connId);
  420. gh->playerMessages->broadcastMessage(playerSettings->color, messageText);
  421. startAiPack.players.push_back(playerSettings->color);
  422. }
  423. if(!startAiPack.players.empty())
  424. gh->sendAndApply(startAiPack);
  425. }
  426. }
  427. void CVCMIServer::setPlayerConnectedId(PlayerSettings & pset, ui8 player) const
  428. {
  429. if(vstd::contains(playerNames, player))
  430. pset.name = playerNames.find(player)->second.name;
  431. else
  432. pset.name = VLC->generaltexth->allTexts[468]; //Computer
  433. pset.connectedPlayerIDs.clear();
  434. if(player != PlayerSettings::PLAYER_AI)
  435. pset.connectedPlayerIDs.insert(player);
  436. }
  437. void CVCMIServer::updateStartInfoOnMapChange(std::shared_ptr<CMapInfo> mapInfo, std::shared_ptr<CMapGenOptions> mapGenOpts)
  438. {
  439. mi = mapInfo;
  440. if(!mi)
  441. return;
  442. auto namesIt = playerNames.cbegin();
  443. si->playerInfos.clear();
  444. if(mi->scenarioOptionsOfSave)
  445. {
  446. si = CMemorySerializer::deepCopy(*mi->scenarioOptionsOfSave);
  447. si->mode = EStartMode::LOAD_GAME;
  448. if(si->campState)
  449. campaignMap = si->campState->currentScenario().value();
  450. for(auto & ps : si->playerInfos)
  451. {
  452. if(!ps.second.compOnly && ps.second.connectedPlayerIDs.size() && namesIt != playerNames.cend())
  453. {
  454. setPlayerConnectedId(ps.second, namesIt++->first);
  455. }
  456. else
  457. {
  458. setPlayerConnectedId(ps.second, PlayerSettings::PLAYER_AI);
  459. }
  460. }
  461. }
  462. else if(si->mode == EStartMode::NEW_GAME || si->mode == EStartMode::CAMPAIGN)
  463. {
  464. if(mi->campaign)
  465. return;
  466. for(int i = 0; i < mi->mapHeader->players.size(); i++)
  467. {
  468. const PlayerInfo & pinfo = mi->mapHeader->players[i];
  469. //neither computer nor human can play - no player
  470. if(!(pinfo.canHumanPlay || pinfo.canComputerPlay))
  471. continue;
  472. PlayerSettings & pset = si->playerInfos[PlayerColor(i)];
  473. pset.color = PlayerColor(i);
  474. if(pinfo.canHumanPlay && namesIt != playerNames.cend())
  475. {
  476. setPlayerConnectedId(pset, namesIt++->first);
  477. }
  478. else
  479. {
  480. setPlayerConnectedId(pset, PlayerSettings::PLAYER_AI);
  481. if(!pinfo.canHumanPlay)
  482. {
  483. pset.compOnly = true;
  484. }
  485. }
  486. pset.castle = pinfo.defaultCastle();
  487. pset.hero = pinfo.defaultHero();
  488. if(pset.hero != HeroTypeID::RANDOM && pinfo.hasCustomMainHero())
  489. {
  490. pset.hero = pinfo.mainCustomHeroId;
  491. pset.heroNameTextId = pinfo.mainCustomHeroNameTextId;
  492. pset.heroPortrait = pinfo.mainCustomHeroPortrait;
  493. }
  494. }
  495. if(mi->isRandomMap && mapGenOpts)
  496. si->mapGenOptions = std::shared_ptr<CMapGenOptions>(mapGenOpts);
  497. else
  498. si->mapGenOptions.reset();
  499. }
  500. if (lobbyProcessor)
  501. {
  502. std::string roomDescription;
  503. if (si->mapGenOptions)
  504. {
  505. if (si->mapGenOptions->getMapTemplate())
  506. roomDescription = si->mapGenOptions->getMapTemplate()->getName();
  507. // else - no template selected.
  508. // TODO: handle this somehow?
  509. }
  510. else
  511. roomDescription = mi->getNameTranslated();
  512. lobbyProcessor->sendChangeRoomDescription(roomDescription);
  513. }
  514. si->mapname = mi->fileURI;
  515. }
  516. void CVCMIServer::updateAndPropagateLobbyState()
  517. {
  518. // Update player settings for RMG
  519. // TODO: find appropriate location for this code
  520. if(si->mapGenOptions && si->mode == EStartMode::NEW_GAME)
  521. {
  522. for(const auto & psetPair : si->playerInfos)
  523. {
  524. const auto & pset = psetPair.second;
  525. si->mapGenOptions->setStartingTownForPlayer(pset.color, pset.castle);
  526. si->mapGenOptions->setStartingHeroForPlayer(pset.color, pset.hero);
  527. if(pset.isControlledByHuman())
  528. {
  529. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::HUMAN);
  530. }
  531. else
  532. {
  533. si->mapGenOptions->setPlayerTypeForStandardPlayer(pset.color, EPlayerType::AI);
  534. }
  535. }
  536. }
  537. LobbyUpdateState lus;
  538. lus.state = *this;
  539. announcePack(lus);
  540. }
  541. void CVCMIServer::setPlayer(PlayerColor clickedColor)
  542. {
  543. struct PlayerToRestore
  544. {
  545. PlayerColor color;
  546. int id;
  547. void reset() { id = -1; color = PlayerColor::CANNOT_DETERMINE; }
  548. PlayerToRestore(){ reset(); }
  549. } playerToRestore;
  550. PlayerSettings & clicked = si->playerInfos[clickedColor];
  551. //identify clicked player
  552. int clickedNameID = 0; //number of player - zero means AI, assume it initially
  553. if(clicked.isControlledByHuman())
  554. clickedNameID = *(clicked.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  555. if(clickedNameID > 0 && playerToRestore.id == clickedNameID) //player to restore is about to being replaced -> put him back to the old place
  556. {
  557. PlayerSettings & restPos = si->playerInfos[playerToRestore.color];
  558. setPlayerConnectedId(restPos, playerToRestore.id);
  559. playerToRestore.reset();
  560. }
  561. int newPlayer; //which player will take clicked position
  562. //who will be put here?
  563. if(!clickedNameID) //AI player clicked -> if possible replace computer with unallocated player
  564. {
  565. newPlayer = getIdOfFirstUnallocatedPlayer();
  566. if(!newPlayer) //no "free" player -> get just first one
  567. newPlayer = playerNames.begin()->first;
  568. }
  569. else //human clicked -> take next
  570. {
  571. auto i = playerNames.find(clickedNameID); //clicked one
  572. i++; //player AFTER clicked one
  573. if(i != playerNames.end())
  574. newPlayer = i->first;
  575. else
  576. newPlayer = 0; //AI if we scrolled through all players
  577. }
  578. setPlayerConnectedId(clicked, newPlayer); //put player
  579. //if that player was somewhere else, we need to replace him with computer
  580. if(newPlayer) //not AI
  581. {
  582. for(auto i = si->playerInfos.begin(); i != si->playerInfos.end(); i++)
  583. {
  584. int curNameID = *(i->second.connectedPlayerIDs.begin());
  585. if(i->first != clickedColor && curNameID == newPlayer)
  586. {
  587. assert(i->second.connectedPlayerIDs.size());
  588. playerToRestore.color = i->first;
  589. playerToRestore.id = newPlayer;
  590. setPlayerConnectedId(i->second, PlayerSettings::PLAYER_AI); //set computer
  591. break;
  592. }
  593. }
  594. }
  595. }
  596. void CVCMIServer::setPlayerName(PlayerColor color, std::string name)
  597. {
  598. if(color == PlayerColor::CANNOT_DETERMINE)
  599. return;
  600. PlayerSettings & player = si->playerInfos.at(color);
  601. if(!player.isControlledByHuman())
  602. return;
  603. if(player.connectedPlayerIDs.empty())
  604. return;
  605. int nameID = *(player.connectedPlayerIDs.begin()); //if not AI - set appropriate ID
  606. playerNames[nameID].name = name;
  607. setPlayerConnectedId(player, nameID);
  608. }
  609. void CVCMIServer::setPlayerHandicap(PlayerColor color, Handicap handicap)
  610. {
  611. if(color == PlayerColor::CANNOT_DETERMINE)
  612. return;
  613. si->playerInfos[color].handicap = handicap;
  614. int humanPlayer = 0;
  615. for (const auto & pi : si->playerInfos)
  616. if(pi.second.isControlledByHuman())
  617. humanPlayer++;
  618. if(humanPlayer < 2) // Singleplayer
  619. return;
  620. MetaString str;
  621. str.appendTextID("vcmi.lobby.handicap");
  622. str.appendRawString(" ");
  623. str.appendName(color);
  624. str.appendRawString(":");
  625. if(handicap.startBonus.empty() && handicap.percentIncome == 100 && handicap.percentGrowth == 100)
  626. {
  627. str.appendRawString(" ");
  628. str.appendTextID("core.genrltxt.523");
  629. announceTxt(str);
  630. return;
  631. }
  632. for(auto & res : EGameResID::ALL_RESOURCES())
  633. if(handicap.startBonus[res] != 0)
  634. {
  635. str.appendRawString(" ");
  636. str.appendName(res);
  637. str.appendRawString(":");
  638. str.appendRawString(std::to_string(handicap.startBonus[res]));
  639. }
  640. if(handicap.percentIncome != 100)
  641. {
  642. str.appendRawString(" ");
  643. str.appendTextID("core.jktext.32");
  644. str.appendRawString(":");
  645. str.appendRawString(std::to_string(handicap.percentIncome) + "%");
  646. }
  647. if(handicap.percentGrowth != 100)
  648. {
  649. str.appendRawString(" ");
  650. str.appendTextID("core.genrltxt.194");
  651. str.appendRawString(":");
  652. str.appendRawString(std::to_string(handicap.percentGrowth) + "%");
  653. }
  654. announceTxt(str);
  655. }
  656. void CVCMIServer::optionNextCastle(PlayerColor player, int dir)
  657. {
  658. PlayerSettings & s = si->playerInfos[player];
  659. FactionID & cur = s.castle;
  660. auto & allowed = getPlayerInfo(player).allowedFactions;
  661. const bool allowRandomTown = getPlayerInfo(player).isFactionRandom;
  662. if(cur == FactionID::NONE) //no change
  663. return;
  664. if(cur == FactionID::RANDOM) //first/last available
  665. {
  666. if(dir > 0)
  667. cur = *allowed.begin(); //id of first town
  668. else
  669. cur = *allowed.rbegin(); //id of last town
  670. }
  671. else // next/previous available
  672. {
  673. if((cur == *allowed.begin() && dir < 0) || (cur == *allowed.rbegin() && dir > 0))
  674. {
  675. if(allowRandomTown)
  676. {
  677. cur = FactionID::RANDOM;
  678. }
  679. else
  680. {
  681. if(dir > 0)
  682. cur = *allowed.begin();
  683. else
  684. cur = *allowed.rbegin();
  685. }
  686. }
  687. else
  688. {
  689. assert(dir >= -1 && dir <= 1); //othervice std::advance may go out of range
  690. auto iter = allowed.find(cur);
  691. std::advance(iter, dir);
  692. cur = *iter;
  693. }
  694. }
  695. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  696. {
  697. s.hero = HeroTypeID::RANDOM;
  698. }
  699. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  700. s.bonus = PlayerStartingBonus::RANDOM;
  701. }
  702. void CVCMIServer::optionSetCastle(PlayerColor player, FactionID id)
  703. {
  704. PlayerSettings & s = si->playerInfos[player];
  705. FactionID & cur = s.castle;
  706. auto & allowed = getPlayerInfo(player).allowedFactions;
  707. if(cur == FactionID::NONE) //no change
  708. return;
  709. if(allowed.find(id) == allowed.end() && id != FactionID::RANDOM) // valid id
  710. return;
  711. cur = static_cast<FactionID>(id);
  712. if(s.hero.isValid() && !getPlayerInfo(player).hasCustomMainHero()) // remove hero unless it set to fixed one in map editor
  713. {
  714. s.hero = HeroTypeID::RANDOM;
  715. }
  716. if(!cur.isValid() && s.bonus == PlayerStartingBonus::RESOURCE)
  717. s.bonus = PlayerStartingBonus::RANDOM;
  718. }
  719. void CVCMIServer::setCampaignMap(CampaignScenarioID mapId)
  720. {
  721. campaignMap = mapId;
  722. si->difficulty = si->campState->scenario(mapId).difficulty;
  723. campaignBonus = -1;
  724. updateStartInfoOnMapChange(si->campState->getMapInfo(mapId));
  725. }
  726. void CVCMIServer::setCampaignBonus(int bonusId)
  727. {
  728. campaignBonus = bonusId;
  729. const CampaignScenario & scenario = si->campState->scenario(campaignMap);
  730. const std::vector<CampaignBonus> & bonDescs = scenario.travelOptions.bonusesToChoose;
  731. if(bonDescs[bonusId].type == CampaignBonusType::HERO)
  732. {
  733. for(auto & elem : si->playerInfos)
  734. {
  735. if(elem.first == PlayerColor(bonDescs[bonusId].info1))
  736. setPlayerConnectedId(elem.second, 1);
  737. else
  738. setPlayerConnectedId(elem.second, PlayerSettings::PLAYER_AI);
  739. }
  740. }
  741. }
  742. void CVCMIServer::optionNextHero(PlayerColor player, int dir)
  743. {
  744. PlayerSettings & s = si->playerInfos[player];
  745. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  746. return;
  747. if(s.hero == HeroTypeID::RANDOM) // first/last available
  748. {
  749. if (dir > 0)
  750. s.hero = nextAllowedHero(player, HeroTypeID(-1), dir);
  751. else
  752. s.hero = nextAllowedHero(player, HeroTypeID(VLC->heroh->size()), dir);
  753. }
  754. else
  755. {
  756. s.hero = nextAllowedHero(player, s.hero, dir);
  757. }
  758. }
  759. void CVCMIServer::optionSetHero(PlayerColor player, HeroTypeID id)
  760. {
  761. PlayerSettings & s = si->playerInfos[player];
  762. if(!s.castle.isValid() || s.hero == HeroTypeID::NONE)
  763. return;
  764. if(id == HeroTypeID::RANDOM)
  765. {
  766. s.hero = HeroTypeID::RANDOM;
  767. }
  768. if(canUseThisHero(player, id))
  769. s.hero = static_cast<HeroTypeID>(id);
  770. }
  771. HeroTypeID CVCMIServer::nextAllowedHero(PlayerColor player, HeroTypeID initial, int direction)
  772. {
  773. HeroTypeID first(initial.getNum() + direction);
  774. if(direction > 0)
  775. {
  776. for (auto i = first; i.getNum() < VLC->heroh->size(); ++i)
  777. if(canUseThisHero(player, i))
  778. return i;
  779. }
  780. else
  781. {
  782. for (auto i = first; i.getNum() >= 0; --i)
  783. if(canUseThisHero(player, i))
  784. return i;
  785. }
  786. return HeroTypeID::RANDOM;
  787. }
  788. void CVCMIServer::optionNextBonus(PlayerColor player, int dir)
  789. {
  790. PlayerSettings & s = si->playerInfos[player];
  791. PlayerStartingBonus & ret = s.bonus = static_cast<PlayerStartingBonus>(static_cast<int>(s.bonus) + dir);
  792. if(s.hero == HeroTypeID::NONE &&
  793. !getPlayerInfo(player).heroesNames.size() &&
  794. ret == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  795. {
  796. if(dir < 0)
  797. ret = PlayerStartingBonus::RANDOM;
  798. else
  799. ret = PlayerStartingBonus::GOLD;
  800. }
  801. if(ret > PlayerStartingBonus::RESOURCE)
  802. ret = PlayerStartingBonus::RANDOM;
  803. if(ret < PlayerStartingBonus::RANDOM)
  804. ret = PlayerStartingBonus::RESOURCE;
  805. if(s.castle == FactionID::RANDOM && ret == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  806. {
  807. if(dir < 0)
  808. ret = PlayerStartingBonus::GOLD;
  809. else
  810. ret = PlayerStartingBonus::RANDOM;
  811. }
  812. }
  813. void CVCMIServer::optionSetBonus(PlayerColor player, PlayerStartingBonus id)
  814. {
  815. PlayerSettings & s = si->playerInfos[player];
  816. if(s.hero == HeroTypeID::NONE &&
  817. !getPlayerInfo(player).heroesNames.size() &&
  818. id == PlayerStartingBonus::ARTIFACT) //no hero - can't be artifact
  819. return;
  820. if(id > PlayerStartingBonus::RESOURCE)
  821. return;
  822. if(id < PlayerStartingBonus::RANDOM)
  823. return;
  824. if(s.castle == FactionID::RANDOM && id == PlayerStartingBonus::RESOURCE) //random castle - can't be resource
  825. return;
  826. s.bonus = id;
  827. }
  828. bool CVCMIServer::canUseThisHero(PlayerColor player, HeroTypeID ID)
  829. {
  830. return VLC->heroh->size() > ID
  831. && si->playerInfos[player].castle == VLC->heroh->objects[ID]->heroClass->faction
  832. && !vstd::contains(getUsedHeroes(), ID)
  833. && mi->mapHeader->allowedHeroes.count(ID);
  834. }
  835. std::vector<HeroTypeID> CVCMIServer::getUsedHeroes()
  836. {
  837. std::vector<HeroTypeID> heroIds;
  838. for(auto & p : si->playerInfos)
  839. {
  840. const auto & heroes = getPlayerInfo(p.first).heroesNames;
  841. for(auto & hero : heroes)
  842. if(hero.heroId >= 0) //in VCMI map format heroId = -1 means random hero
  843. heroIds.push_back(hero.heroId);
  844. if(p.second.hero != HeroTypeID::RANDOM)
  845. heroIds.push_back(p.second.hero);
  846. }
  847. return heroIds;
  848. }
  849. ui8 CVCMIServer::getIdOfFirstUnallocatedPlayer() const
  850. {
  851. for(auto i = playerNames.cbegin(); i != playerNames.cend(); i++)
  852. {
  853. if(!si->getPlayersSettings(i->first))
  854. return i->first;
  855. }
  856. return 0;
  857. }
  858. void CVCMIServer::multiplayerWelcomeMessage()
  859. {
  860. int humanPlayer = 0;
  861. for (const auto & pi : si->playerInfos)
  862. if(pi.second.isControlledByHuman())
  863. humanPlayer++;
  864. if(humanPlayer < 2) // Singleplayer
  865. return;
  866. gh->playerMessages->broadcastSystemMessage("Use '!help' to list available commands");
  867. for (const auto & pi : si->playerInfos)
  868. if(!pi.second.handicap.startBonus.empty() || pi.second.handicap.percentIncome != 100 || pi.second.handicap.percentGrowth != 100)
  869. {
  870. MetaString str;
  871. str.appendTextID("vcmi.lobby.handicap");
  872. str.appendRawString(" ");
  873. str.appendName(pi.first);
  874. str.appendRawString(":");
  875. for(auto & res : EGameResID::ALL_RESOURCES())
  876. if(pi.second.handicap.startBonus[res] != 0)
  877. {
  878. str.appendRawString(" ");
  879. str.appendName(res);
  880. str.appendRawString(":");
  881. str.appendRawString(std::to_string(pi.second.handicap.startBonus[res]));
  882. }
  883. if(pi.second.handicap.percentIncome != 100)
  884. {
  885. str.appendRawString(" ");
  886. str.appendTextID("core.jktext.32");
  887. str.appendRawString(":");
  888. str.appendRawString(std::to_string(pi.second.handicap.percentIncome) + "%");
  889. }
  890. if(pi.second.handicap.percentGrowth != 100)
  891. {
  892. str.appendRawString(" ");
  893. str.appendTextID("core.genrltxt.194");
  894. str.appendRawString(":");
  895. str.appendRawString(std::to_string(pi.second.handicap.percentGrowth) + "%");
  896. }
  897. gh->playerMessages->broadcastSystemMessage(str);
  898. }
  899. std::vector<std::string> optionIds;
  900. if(si->extraOptionsInfo.cheatsAllowed)
  901. optionIds.emplace_back("vcmi.optionsTab.cheatAllowed.hover");
  902. if(si->extraOptionsInfo.unlimitedReplay)
  903. optionIds.emplace_back("vcmi.optionsTab.unlimitedReplay.hover");
  904. if(!optionIds.size()) // No settings to publish
  905. return;
  906. MetaString str;
  907. str.appendTextID("vcmi.optionsTab.extraOptions.hover");
  908. str.appendRawString(": ");
  909. for(int i = 0; i < optionIds.size(); i++)
  910. {
  911. str.appendTextID(optionIds[i]);
  912. if(i < optionIds.size() - 1)
  913. str.appendRawString(", ");
  914. }
  915. gh->playerMessages->broadcastSystemMessage(str);
  916. }
  917. INetworkHandler & CVCMIServer::getNetworkHandler()
  918. {
  919. return *networkHandler;
  920. }