ClientCommandManager.cpp 17 KB

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