ClientCommandManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. * ClientCommandManager.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 "ClientCommandManager.h"
  12. #include "Client.h"
  13. #include "adventureMap/CInGameConsole.h"
  14. #include "CPlayerInterface.h"
  15. #include "PlayerLocalState.h"
  16. #include "CServerHandler.h"
  17. #include "gui/CGuiHandler.h"
  18. #include "gui/WindowHandler.h"
  19. #include "render/IRenderHandler.h"
  20. #include "ClientNetPackVisitors.h"
  21. #include "../lib/CConfigHandler.h"
  22. #include "../lib/gameState/CGameState.h"
  23. #include "../lib/CPlayerState.h"
  24. #include "../lib/constants/StringConstants.h"
  25. #include "../lib/campaign/CampaignHandler.h"
  26. #include "../lib/mapping/CMapService.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "windows/CCastleInterface.h"
  29. #include "../lib/mapObjects/CGHeroInstance.h"
  30. #include "render/CAnimation.h"
  31. #include "../CCallback.h"
  32. #include "../lib/texts/CGeneralTextHandler.h"
  33. #include "../lib/filesystem/Filesystem.h"
  34. #include "../lib/modding/CModHandler.h"
  35. #include "../lib/modding/ContentTypeHandler.h"
  36. #include "../lib/modding/ModUtility.h"
  37. #include "../lib/CHeroHandler.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/logging/VisualLogger.h"
  40. #include "../lib/serializer/Connection.h"
  41. #ifdef SCRIPTING_ENABLED
  42. #include "../lib/ScriptHandler.h"
  43. #endif
  44. void ClientCommandManager::handleQuitCommand()
  45. {
  46. exit(EXIT_SUCCESS);
  47. }
  48. void ClientCommandManager::handleSaveCommand(std::istringstream & singleWordBuffer)
  49. {
  50. if(!CSH->client)
  51. {
  52. printCommandMessage("Game is not in playing state");
  53. return;
  54. }
  55. std::string saveFilename;
  56. singleWordBuffer >> saveFilename;
  57. CSH->client->save(saveFilename);
  58. printCommandMessage("Game saved as: " + saveFilename);
  59. }
  60. void ClientCommandManager::handleLoadCommand(std::istringstream& singleWordBuffer)
  61. {
  62. // TODO: this code should end the running game and manage to call startGame instead
  63. //std::string fname;
  64. //singleWordBuffer >> fname;
  65. //CSH->client->loadGame(fname);
  66. }
  67. void ClientCommandManager::handleGoSoloCommand()
  68. {
  69. Settings session = settings.write["session"];
  70. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  71. if(!CSH->client)
  72. {
  73. printCommandMessage("Game is not in playing state");
  74. return;
  75. }
  76. if(session["aiSolo"].Bool())
  77. {
  78. // unlikely it will work but just in case to be consistent
  79. for(auto & color : CSH->getAllClientPlayers(CSH->logicConnection->connectionID))
  80. {
  81. if(color.isValidPlayer() && CSH->client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  82. {
  83. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  84. }
  85. }
  86. }
  87. else
  88. {
  89. PlayerColor currentColor = LOCPLINT->playerID;
  90. CSH->client->removeGUI();
  91. for(auto & color : CSH->getAllClientPlayers(CSH->logicConnection->connectionID))
  92. {
  93. if(color.isValidPlayer() && CSH->client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  94. {
  95. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(color), false, false);
  96. printCommandMessage("Player " + color.toString() + " will be lead by " + AiToGive, ELogLevel::INFO);
  97. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  98. }
  99. }
  100. GH.windows().totalRedraw();
  101. giveTurn(currentColor);
  102. }
  103. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  104. }
  105. void ClientCommandManager::handleAutoskipCommand()
  106. {
  107. Settings session = settings.write["session"];
  108. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  109. }
  110. void ClientCommandManager::handleControlaiCommand(std::istringstream& singleWordBuffer)
  111. {
  112. std::string colorName;
  113. singleWordBuffer >> colorName;
  114. boost::to_lower(colorName);
  115. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  116. if(!CSH->client)
  117. {
  118. printCommandMessage("Game is not in playing state");
  119. return;
  120. }
  121. PlayerColor color;
  122. if(LOCPLINT)
  123. color = LOCPLINT->playerID;
  124. for(auto & elem : CSH->client->gameState()->players)
  125. {
  126. if(!elem.first.isValidPlayer()
  127. || elem.second.human
  128. || (colorName.length() && elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  129. {
  130. continue;
  131. }
  132. CSH->client->removeGUI();
  133. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  134. }
  135. GH.windows().totalRedraw();
  136. if(color != PlayerColor::NEUTRAL)
  137. giveTurn(color);
  138. }
  139. void ClientCommandManager::handleSetBattleAICommand(std::istringstream& singleWordBuffer)
  140. {
  141. std::string aiName;
  142. singleWordBuffer >> aiName;
  143. printCommandMessage("Will try loading that AI to see if it is correct name...\n");
  144. try
  145. {
  146. if(auto ai = CDynLibHandler::getNewBattleAI(aiName)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  147. {
  148. Settings neutralAI = settings.write["server"]["neutralAI"];
  149. neutralAI->String() = aiName;
  150. printCommandMessage("Setting changed, from now the battle ai will be " + aiName + "!\n");
  151. }
  152. }
  153. catch(std::exception &e)
  154. {
  155. printCommandMessage("Failed opening " + aiName + ": " + e.what(), ELogLevel::WARN);
  156. printCommandMessage("Setting not changed, AI not found or invalid!", ELogLevel::WARN);
  157. }
  158. }
  159. void ClientCommandManager::handleRedrawCommand()
  160. {
  161. GH.windows().totalRedraw();
  162. }
  163. void ClientCommandManager::handleTranslateGameCommand()
  164. {
  165. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  166. VLC->generaltexth->exportAllTexts(textsByMod);
  167. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "translation";
  168. boost::filesystem::create_directories(outPath);
  169. for(const auto & modEntry : textsByMod)
  170. {
  171. JsonNode output;
  172. for(const auto & stringEntry : modEntry.second)
  173. {
  174. if(boost::algorithm::starts_with(stringEntry.first, "map."))
  175. continue;
  176. if(boost::algorithm::starts_with(stringEntry.first, "campaign."))
  177. continue;
  178. output[stringEntry.first].String() = stringEntry.second;
  179. }
  180. if (!output.isNull())
  181. {
  182. const boost::filesystem::path filePath = outPath / (modEntry.first + ".json");
  183. std::ofstream file(filePath.c_str());
  184. file << output.toString();
  185. }
  186. }
  187. printCommandMessage("Translation export complete");
  188. }
  189. void ClientCommandManager::handleTranslateMapsCommand()
  190. {
  191. CMapService mapService;
  192. printCommandMessage("Searching for available maps");
  193. std::unordered_set<ResourcePath> mapList = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  194. {
  195. return ident.getType() == EResType::MAP;
  196. });
  197. std::vector<std::unique_ptr<CMap>> loadedMaps;
  198. std::vector<std::shared_ptr<CampaignState>> loadedCampaigns;
  199. printCommandMessage("Loading maps for export");
  200. for (auto const & mapName : mapList)
  201. {
  202. try
  203. {
  204. // load and drop loaded map - we only need loader to run over all maps
  205. loadedMaps.push_back(mapService.loadMap(mapName, nullptr));
  206. }
  207. catch(std::exception & e)
  208. {
  209. logGlobal->warn("Map %s is invalid. Message: %s", mapName.getName(), e.what());
  210. }
  211. }
  212. printCommandMessage("Searching for available campaigns");
  213. std::unordered_set<ResourcePath> campaignList = CResourceHandler::get()->getFilteredFiles([&](const ResourcePath & ident)
  214. {
  215. return ident.getType() == EResType::CAMPAIGN;
  216. });
  217. logGlobal->info("Loading campaigns for export");
  218. for (auto const & campaignName : campaignList)
  219. {
  220. loadedCampaigns.push_back(CampaignHandler::getCampaign(campaignName.getName()));
  221. for (auto const & part : loadedCampaigns.back()->allScenarios())
  222. loadedCampaigns.back()->getMap(part, nullptr);
  223. }
  224. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  225. VLC->generaltexth->exportAllTexts(textsByMod);
  226. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "translation";
  227. boost::filesystem::create_directories(outPath);
  228. for(const auto & modEntry : textsByMod)
  229. {
  230. JsonNode output;
  231. for(const auto & stringEntry : modEntry.second)
  232. {
  233. if(boost::algorithm::starts_with(stringEntry.first, "map."))
  234. output[stringEntry.first].String() = stringEntry.second;
  235. if(boost::algorithm::starts_with(stringEntry.first, "campaign."))
  236. output[stringEntry.first].String() = stringEntry.second;
  237. }
  238. if (!output.isNull())
  239. {
  240. const boost::filesystem::path filePath = outPath / (modEntry.first + ".json");
  241. std::ofstream file(filePath.c_str());
  242. file << output.toString();
  243. }
  244. }
  245. printCommandMessage("Translation export complete");
  246. }
  247. void ClientCommandManager::handleGetConfigCommand()
  248. {
  249. printCommandMessage("Command accepted.\t");
  250. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "configuration";
  251. boost::filesystem::create_directories(outPath);
  252. const std::vector<std::string> contentNames = { "heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills" };
  253. for(auto contentName : contentNames)
  254. {
  255. auto const & handler = *VLC->modh->content;
  256. auto const & content = handler[contentName];
  257. auto contentOutPath = outPath / contentName;
  258. boost::filesystem::create_directories(contentOutPath);
  259. for(auto& iter : content.modData)
  260. {
  261. const JsonNode& modData = iter.second.modData;
  262. for(auto& nameAndObject : modData.Struct())
  263. {
  264. const JsonNode& object = nameAndObject.second;
  265. std::string name = ModUtility::makeFullIdentifier(object.getModScope(), contentName, nameAndObject.first);
  266. boost::algorithm::replace_all(name, ":", "_");
  267. const boost::filesystem::path filePath = contentOutPath / (name + ".json");
  268. std::ofstream file(filePath.c_str());
  269. file << object.toString();
  270. }
  271. }
  272. }
  273. printCommandMessage("\rExtracting done :)\n");
  274. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  275. }
  276. void ClientCommandManager::handleGetScriptsCommand()
  277. {
  278. #if SCRIPTING_ENABLED
  279. printCommandMessage("Command accepted.\t");
  280. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "scripts";
  281. boost::filesystem::create_directories(outPath);
  282. for(const auto & kv : VLC->scriptHandler->objects)
  283. {
  284. std::string name = kv.first;
  285. boost::algorithm::replace_all(name,":","_");
  286. const scripting::ScriptImpl * script = kv.second.get();
  287. boost::filesystem::path filePath = outPath / (name + ".lua");
  288. std::ofstream file(filePath.c_str());
  289. file << script->getSource();
  290. }
  291. printCommandMessage("\rExtracting done :)\n");
  292. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  293. #endif
  294. }
  295. void ClientCommandManager::handleGetTextCommand()
  296. {
  297. printCommandMessage("Command accepted.\t");
  298. const boost::filesystem::path outPath =
  299. VCMIDirs::get().userExtractedPath();
  300. auto list =
  301. CResourceHandler::get()->getFilteredFiles([](const ResourcePath & ident)
  302. {
  303. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  304. });
  305. for (auto & filename : list)
  306. {
  307. const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT");
  308. boost::filesystem::create_directories(filePath.parent_path());
  309. std::ofstream file(filePath.c_str());
  310. auto text = CResourceHandler::get()->load(filename)->readAll();
  311. file.write((char*)text.first.get(), text.second);
  312. }
  313. printCommandMessage("\rExtracting done :)\n");
  314. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  315. }
  316. void ClientCommandManager::handleDef2bmpCommand(std::istringstream& singleWordBuffer)
  317. {
  318. std::string URI;
  319. singleWordBuffer >> URI;
  320. auto anim = GH.renderHandler().loadAnimation(AnimationPath::builtin(URI), EImageBlitMode::ALPHA);
  321. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  322. }
  323. void ClientCommandManager::handleExtractCommand(std::istringstream& singleWordBuffer)
  324. {
  325. std::string URI;
  326. singleWordBuffer >> URI;
  327. if(CResourceHandler::get()->existsResource(ResourcePath(URI)))
  328. {
  329. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  330. auto data = CResourceHandler::get()->load(ResourcePath(URI))->readAll();
  331. boost::filesystem::create_directories(outPath.parent_path());
  332. std::ofstream outFile(outPath.c_str(), std::ofstream::binary);
  333. outFile.write((char*)data.first.get(), data.second);
  334. }
  335. else
  336. printCommandMessage("File not found!", ELogLevel::ERROR);
  337. }
  338. void ClientCommandManager::handleBonusesCommand(std::istringstream & singleWordBuffer)
  339. {
  340. if(currentCallFromIngameConsole)
  341. {
  342. printCommandMessage("Output for this command is too large for ingame chat! Please run it from client console.\n");
  343. return;
  344. }
  345. std::string outputFormat;
  346. singleWordBuffer >> outputFormat;
  347. auto format = [outputFormat](const BonusList & b) -> std::string
  348. {
  349. if(outputFormat == "json")
  350. return b.toJsonNode().toCompactString();
  351. std::ostringstream ss;
  352. ss << b;
  353. return ss.str();
  354. };
  355. printCommandMessage("Bonuses of " + LOCPLINT->localState->getCurrentArmy()->getObjectName() + "\n");
  356. printCommandMessage(format(*LOCPLINT->localState->getCurrentArmy()->getAllBonuses(Selector::all, Selector::all)) + "\n");
  357. printCommandMessage("\nInherited bonuses:\n");
  358. TCNodes parents;
  359. LOCPLINT->localState->getCurrentArmy()->getParents(parents);
  360. for(const CBonusSystemNode *parent : parents)
  361. {
  362. printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n");
  363. }
  364. }
  365. void ClientCommandManager::handleTellCommand(std::istringstream& singleWordBuffer)
  366. {
  367. std::string what;
  368. int id1;
  369. int id2;
  370. singleWordBuffer >> what >> id1 >> id2;
  371. if(what == "hs")
  372. {
  373. for(const CGHeroInstance* h : LOCPLINT->cb->getHeroesInfo())
  374. if(h->type->getIndex() == id1)
  375. if(const CArtifactInstance* a = h->getArt(ArtifactPosition(id2)))
  376. printCommandMessage(a->nodeName());
  377. }
  378. }
  379. void ClientCommandManager::handleMpCommand()
  380. {
  381. if(const CGHeroInstance* h = LOCPLINT->localState->getCurrentHero())
  382. printCommandMessage(std::to_string(h->movementPointsRemaining()) + "; max: " + std::to_string(h->movementPointsLimit(true)) + "/" + std::to_string(h->movementPointsLimit(false)) + "\n");
  383. }
  384. void ClientCommandManager::handleSetCommand(std::istringstream& singleWordBuffer)
  385. {
  386. std::string what;
  387. std::string value;
  388. singleWordBuffer >> what;
  389. Settings config = settings.write["session"][what];
  390. singleWordBuffer >> value;
  391. if(value == "on")
  392. {
  393. config->Bool() = true;
  394. printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO);
  395. }
  396. else if(value == "off")
  397. {
  398. config->Bool() = false;
  399. printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO);
  400. }
  401. }
  402. void ClientCommandManager::handleCrashCommand()
  403. {
  404. int* ptr = nullptr;
  405. *ptr = 666;
  406. //disaster!
  407. }
  408. void ClientCommandManager::handleVsLog(std::istringstream & singleWordBuffer)
  409. {
  410. std::string key;
  411. singleWordBuffer >> key;
  412. logVisual->setKey(key);
  413. }
  414. void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
  415. {
  416. switch(messageType)
  417. {
  418. case ELogLevel::NOT_SET:
  419. std::cout << commandMessage;
  420. break;
  421. case ELogLevel::TRACE:
  422. logGlobal->trace(commandMessage);
  423. break;
  424. case ELogLevel::DEBUG:
  425. logGlobal->debug(commandMessage);
  426. break;
  427. case ELogLevel::INFO:
  428. logGlobal->info(commandMessage);
  429. break;
  430. case ELogLevel::WARN:
  431. logGlobal->warn(commandMessage);
  432. break;
  433. case ELogLevel::ERROR:
  434. logGlobal->error(commandMessage);
  435. break;
  436. default:
  437. std::cout << commandMessage;
  438. break;
  439. }
  440. if(currentCallFromIngameConsole)
  441. {
  442. boost::mutex::scoped_lock interfaceLock(GH.interfaceMutex);
  443. if(LOCPLINT && LOCPLINT->cingconsole)
  444. {
  445. LOCPLINT->cingconsole->addMessage("", "System", commandMessage);
  446. }
  447. }
  448. }
  449. void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier)
  450. {
  451. PlayerStartsTurn yt;
  452. yt.player = colorIdentifier;
  453. yt.queryID = QueryID::NONE;
  454. ApplyClientNetPackVisitor visitor(*CSH->client, *CSH->client->gameState());
  455. yt.visit(visitor);
  456. }
  457. void ClientCommandManager::processCommand(const std::string & message, bool calledFromIngameConsole)
  458. {
  459. // split the message into individual words
  460. std::istringstream singleWordBuffer;
  461. singleWordBuffer.str(message);
  462. // get command name, to be used for single word commands
  463. std::string commandName;
  464. singleWordBuffer >> commandName;
  465. currentCallFromIngameConsole = calledFromIngameConsole;
  466. if(message == std::string("die, fool"))
  467. handleQuitCommand();
  468. else if(commandName == "save")
  469. handleSaveCommand(singleWordBuffer);
  470. else if(commandName=="load")
  471. handleLoadCommand(singleWordBuffer); // not implemented
  472. else if(commandName == "gosolo")
  473. handleGoSoloCommand();
  474. else if(commandName == "autoskip")
  475. handleAutoskipCommand();
  476. else if(commandName == "controlai")
  477. handleControlaiCommand(singleWordBuffer);
  478. else if(commandName == "setBattleAI")
  479. handleSetBattleAICommand(singleWordBuffer);
  480. else if(commandName == "redraw")
  481. handleRedrawCommand();
  482. else if(message=="translate" || message=="translate game")
  483. handleTranslateGameCommand();
  484. else if(message=="translate maps")
  485. handleTranslateMapsCommand();
  486. else if(message=="get config")
  487. handleGetConfigCommand();
  488. else if(message=="get scripts")
  489. handleGetScriptsCommand();
  490. else if(message=="get txt")
  491. handleGetTextCommand();
  492. else if(commandName == "def2bmp")
  493. handleDef2bmpCommand(singleWordBuffer);
  494. else if(commandName == "extract")
  495. handleExtractCommand(singleWordBuffer);
  496. else if(commandName == "bonuses")
  497. handleBonusesCommand(singleWordBuffer);
  498. else if(commandName == "tell")
  499. handleTellCommand(singleWordBuffer);
  500. else if(commandName == "mp" && LOCPLINT)
  501. handleMpCommand();
  502. else if (commandName == "set")
  503. handleSetCommand(singleWordBuffer);
  504. else if(commandName == "crash")
  505. handleCrashCommand();
  506. else if(commandName == "vslog")
  507. handleVsLog(singleWordBuffer);
  508. else
  509. {
  510. if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise
  511. printCommandMessage("Command not found :(", ELogLevel::ERROR);
  512. }
  513. }