CVCMIServer.cpp 31 KB

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