ClientCommandManager.cpp 18 KB

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