CVCMIServer.cpp 31 KB

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