CVCMIServer.cpp 30 KB

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