CVCMIServer.cpp 30 KB

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