ClientCommandManager.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 "GameEngine.h"
  18. #include "GameInstance.h"
  19. #include "gui/WindowHandler.h"
  20. #include "render/IRenderHandler.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/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(!GAME->server().client)
  51. {
  52. printCommandMessage("Game is not in playing state");
  53. return;
  54. }
  55. std::string saveFilename;
  56. singleWordBuffer >> saveFilename;
  57. GAME->server().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. //GAME->server().client->loadGame(fname);
  66. }
  67. void ClientCommandManager::handleGoSoloCommand()
  68. {
  69. Settings session = settings.write["session"];
  70. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  71. if(!GAME->server().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 : GAME->server().getAllClientPlayers(GAME->server().logicConnection->connectionID))
  80. {
  81. if(color.isValidPlayer() && GAME->server().client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  82. {
  83. GAME->server().client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  84. }
  85. }
  86. }
  87. else
  88. {
  89. PlayerColor currentColor = GAME->interface()->playerID;
  90. GAME->server().client->removeGUI();
  91. for(auto & color : GAME->server().getAllClientPlayers(GAME->server().logicConnection->connectionID))
  92. {
  93. if(color.isValidPlayer() && GAME->server().client->getStartInfo()->playerInfos.at(color).isControlledByHuman())
  94. {
  95. auto AiToGive = GAME->server().client->aiNameForPlayer(*GAME->server().client->getPlayerSettings(color), false, false);
  96. printCommandMessage("Player " + color.toString() + " will be lead by " + AiToGive, ELogLevel::INFO);
  97. GAME->server().client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  98. }
  99. }
  100. ENGINE->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. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  116. if(!GAME->server().client)
  117. {
  118. printCommandMessage("Game is not in playing state");
  119. return;
  120. }
  121. PlayerColor color;
  122. if(GAME->interface())
  123. color = GAME->interface()->playerID;
  124. for(auto & elem : GAME->server().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. GAME->server().client->removeGUI();
  133. GAME->server().client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  134. }
  135. ENGINE->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. ENGINE->windows().totalRedraw();
  162. }
  163. void ClientCommandManager::handleTranslateGameCommand(bool onlyMissing)
  164. {
  165. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  166. LIBRARY->generaltexth->exportAllTexts(textsByMod, onlyMissing);
  167. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / ( onlyMissing ? "translationMissing" : "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. try
  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. catch(std::exception & e)
  227. {
  228. logGlobal->warn("Campaign %s is invalid. Message: %s", campaignName.getName(), e.what());
  229. }
  230. }
  231. std::map<std::string, std::map<std::string, std::string>> textsByMod;
  232. LIBRARY->generaltexth->exportAllTexts(textsByMod, false);
  233. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "translation";
  234. boost::filesystem::create_directories(outPath);
  235. for(const auto & modEntry : textsByMod)
  236. {
  237. JsonNode output;
  238. for(const auto & stringEntry : modEntry.second)
  239. {
  240. if(boost::algorithm::starts_with(stringEntry.first, "map."))
  241. output[stringEntry.first].String() = stringEntry.second;
  242. if(boost::algorithm::starts_with(stringEntry.first, "campaign."))
  243. output[stringEntry.first].String() = stringEntry.second;
  244. }
  245. if (!output.isNull())
  246. {
  247. const boost::filesystem::path filePath = outPath / (modEntry.first + ".json");
  248. std::ofstream file(filePath.c_str());
  249. file << output.toString();
  250. }
  251. }
  252. printCommandMessage("Translation export complete");
  253. }
  254. void ClientCommandManager::handleGetConfigCommand()
  255. {
  256. printCommandMessage("Command accepted.\t");
  257. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "configuration";
  258. boost::filesystem::create_directories(outPath);
  259. const std::vector<std::string> contentNames = { "heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills" };
  260. for(auto contentName : contentNames)
  261. {
  262. auto const & handler = *LIBRARY->modh->content;
  263. auto const & content = handler[contentName];
  264. auto contentOutPath = outPath / contentName;
  265. boost::filesystem::create_directories(contentOutPath);
  266. for(auto& iter : content.modData)
  267. {
  268. const JsonNode& modData = iter.second.modData;
  269. for(auto& nameAndObject : modData.Struct())
  270. {
  271. const JsonNode& object = nameAndObject.second;
  272. std::string name = ModUtility::makeFullIdentifier(object.getModScope(), contentName, nameAndObject.first);
  273. boost::algorithm::replace_all(name, ":", "_");
  274. const boost::filesystem::path filePath = contentOutPath / (name + ".json");
  275. std::ofstream file(filePath.c_str());
  276. file << object.toString();
  277. }
  278. }
  279. }
  280. printCommandMessage("\rExtracting done :)\n");
  281. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  282. }
  283. void ClientCommandManager::handleGetScriptsCommand()
  284. {
  285. #if SCRIPTING_ENABLED
  286. printCommandMessage("Command accepted.\t");
  287. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / "scripts";
  288. boost::filesystem::create_directories(outPath);
  289. for(const auto & kv : LIBRARY->scriptHandler->objects)
  290. {
  291. std::string name = kv.first;
  292. boost::algorithm::replace_all(name,":","_");
  293. const scripting::ScriptImpl * script = kv.second.get();
  294. boost::filesystem::path filePath = outPath / (name + ".lua");
  295. std::ofstream file(filePath.c_str());
  296. file << script->getSource();
  297. }
  298. printCommandMessage("\rExtracting done :)\n");
  299. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  300. #endif
  301. }
  302. void ClientCommandManager::handleGetTextCommand()
  303. {
  304. printCommandMessage("Command accepted.\t");
  305. const boost::filesystem::path outPath =
  306. VCMIDirs::get().userExtractedPath();
  307. auto list =
  308. CResourceHandler::get()->getFilteredFiles([](const ResourcePath & ident)
  309. {
  310. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  311. });
  312. for (auto & filename : list)
  313. {
  314. const boost::filesystem::path filePath = outPath / (filename.getName() + ".TXT");
  315. boost::filesystem::create_directories(filePath.parent_path());
  316. std::ofstream file(filePath.c_str());
  317. auto text = CResourceHandler::get()->load(filename)->readAll();
  318. file.write((char*)text.first.get(), text.second);
  319. }
  320. printCommandMessage("\rExtracting done :)\n");
  321. printCommandMessage("Extracted files can be found in " + outPath.string() + " directory\n");
  322. }
  323. void ClientCommandManager::handleDef2bmpCommand(std::istringstream& singleWordBuffer)
  324. {
  325. std::string URI;
  326. singleWordBuffer >> URI;
  327. auto anim = ENGINE->renderHandler().loadAnimation(AnimationPath::builtin(URI), EImageBlitMode::SIMPLE);
  328. anim->exportBitmaps(VCMIDirs::get().userExtractedPath());
  329. }
  330. void ClientCommandManager::handleExtractCommand(std::istringstream& singleWordBuffer)
  331. {
  332. std::string URI;
  333. singleWordBuffer >> URI;
  334. if(CResourceHandler::get()->existsResource(ResourcePath(URI)))
  335. {
  336. const boost::filesystem::path outPath = VCMIDirs::get().userExtractedPath() / URI;
  337. auto data = CResourceHandler::get()->load(ResourcePath(URI))->readAll();
  338. boost::filesystem::create_directories(outPath.parent_path());
  339. std::ofstream outFile(outPath.c_str(), std::ofstream::binary);
  340. outFile.write((char*)data.first.get(), data.second);
  341. }
  342. else
  343. printCommandMessage("File not found!", ELogLevel::ERROR);
  344. }
  345. void ClientCommandManager::handleBonusesCommand(std::istringstream & singleWordBuffer)
  346. {
  347. if(currentCallFromIngameConsole)
  348. {
  349. printCommandMessage("Output for this command is too large for ingame chat! Please run it from client console.\n");
  350. return;
  351. }
  352. std::string outputFormat;
  353. singleWordBuffer >> outputFormat;
  354. auto format = [outputFormat](const BonusList & b) -> std::string
  355. {
  356. if(outputFormat == "json")
  357. return b.toJsonNode().toCompactString();
  358. std::ostringstream ss;
  359. ss << b;
  360. return ss.str();
  361. };
  362. printCommandMessage("Bonuses of " + GAME->interface()->localState->getCurrentArmy()->getObjectName() + "\n");
  363. printCommandMessage(format(*GAME->interface()->localState->getCurrentArmy()->getAllBonuses(Selector::all, Selector::all)) + "\n");
  364. printCommandMessage("\nInherited bonuses:\n");
  365. TCNodes parents;
  366. GAME->interface()->localState->getCurrentArmy()->getParents(parents);
  367. for(const CBonusSystemNode *parent : parents)
  368. {
  369. printCommandMessage(std::string("\nBonuses from ") + typeid(*parent).name() + "\n" + format(*parent->getAllBonuses(Selector::all, Selector::all)) + "\n");
  370. }
  371. }
  372. void ClientCommandManager::handleTellCommand(std::istringstream& singleWordBuffer)
  373. {
  374. std::string what;
  375. int id1;
  376. int id2;
  377. singleWordBuffer >> what >> id1 >> id2;
  378. if(what == "hs")
  379. {
  380. for(const CGHeroInstance* h : GAME->interface()->cb->getHeroesInfo())
  381. if(h->getHeroTypeID().getNum() == id1)
  382. if(const CArtifactInstance* a = h->getArt(ArtifactPosition(id2)))
  383. printCommandMessage(a->nodeName());
  384. }
  385. }
  386. void ClientCommandManager::handleMpCommand()
  387. {
  388. if(const CGHeroInstance* h = GAME->interface()->localState->getCurrentHero())
  389. printCommandMessage(std::to_string(h->movementPointsRemaining()) + "; max: " + std::to_string(h->movementPointsLimit(true)) + "/" + std::to_string(h->movementPointsLimit(false)) + "\n");
  390. }
  391. void ClientCommandManager::handleSetCommand(std::istringstream& singleWordBuffer)
  392. {
  393. std::string what;
  394. std::string value;
  395. singleWordBuffer >> what;
  396. Settings config = settings.write["session"][what];
  397. singleWordBuffer >> value;
  398. if(value == "on")
  399. {
  400. config->Bool() = true;
  401. printCommandMessage("Option " + what + " enabled!", ELogLevel::INFO);
  402. }
  403. else if(value == "off")
  404. {
  405. config->Bool() = false;
  406. printCommandMessage("Option " + what + " disabled!", ELogLevel::INFO);
  407. }
  408. }
  409. void ClientCommandManager::handleCrashCommand()
  410. {
  411. int* ptr = nullptr;
  412. *ptr = 666;
  413. //disaster!
  414. }
  415. void ClientCommandManager::handleVsLog(std::istringstream & singleWordBuffer)
  416. {
  417. std::string key;
  418. singleWordBuffer >> key;
  419. logVisual->setKey(key);
  420. }
  421. void ClientCommandManager::handleGenerateAssets()
  422. {
  423. ENGINE->renderHandler().exportGeneratedAssets();
  424. printCommandMessage("All assets generated");
  425. }
  426. void ClientCommandManager::printCommandMessage(const std::string &commandMessage, ELogLevel::ELogLevel messageType)
  427. {
  428. switch(messageType)
  429. {
  430. case ELogLevel::NOT_SET:
  431. std::cout << commandMessage;
  432. break;
  433. case ELogLevel::TRACE:
  434. logGlobal->trace(commandMessage);
  435. break;
  436. case ELogLevel::DEBUG:
  437. logGlobal->debug(commandMessage);
  438. break;
  439. case ELogLevel::INFO:
  440. logGlobal->info(commandMessage);
  441. break;
  442. case ELogLevel::WARN:
  443. logGlobal->warn(commandMessage);
  444. break;
  445. case ELogLevel::ERROR:
  446. logGlobal->error(commandMessage);
  447. break;
  448. default:
  449. std::cout << commandMessage;
  450. break;
  451. }
  452. if(currentCallFromIngameConsole)
  453. {
  454. std::scoped_lock interfaceLock(ENGINE->interfaceMutex);
  455. if(GAME->interface() && GAME->interface()->cingconsole)
  456. {
  457. GAME->interface()->cingconsole->addMessage("", "System", commandMessage);
  458. }
  459. }
  460. }
  461. void ClientCommandManager::giveTurn(const PlayerColor &colorIdentifier)
  462. {
  463. PlayerStartsTurn yt;
  464. yt.player = colorIdentifier;
  465. yt.queryID = QueryID::NONE;
  466. ApplyClientNetPackVisitor visitor(*GAME->server().client, *GAME->server().client->gameState());
  467. yt.visit(visitor);
  468. }
  469. void ClientCommandManager::processCommand(const std::string & message, bool calledFromIngameConsole)
  470. {
  471. // split the message into individual words
  472. std::istringstream singleWordBuffer;
  473. singleWordBuffer.str(message);
  474. // get command name, to be used for single word commands
  475. std::string commandName;
  476. singleWordBuffer >> commandName;
  477. currentCallFromIngameConsole = calledFromIngameConsole;
  478. if(message == std::string("die, fool"))
  479. handleQuitCommand();
  480. else if(commandName == "save")
  481. handleSaveCommand(singleWordBuffer);
  482. else if(commandName=="load")
  483. handleLoadCommand(singleWordBuffer); // not implemented
  484. else if(commandName == "gosolo")
  485. handleGoSoloCommand();
  486. else if(commandName == "autoskip")
  487. handleAutoskipCommand();
  488. else if(commandName == "controlai")
  489. handleControlaiCommand(singleWordBuffer);
  490. else if(commandName == "setBattleAI")
  491. handleSetBattleAICommand(singleWordBuffer);
  492. else if(commandName == "redraw")
  493. handleRedrawCommand();
  494. else if(message=="translate" || message=="translate game")
  495. handleTranslateGameCommand(false);
  496. else if(message=="translate missing")
  497. handleTranslateGameCommand(true);
  498. else if(message=="translate maps")
  499. handleTranslateMapsCommand();
  500. else if(message=="get config")
  501. handleGetConfigCommand();
  502. else if(message=="get scripts")
  503. handleGetScriptsCommand();
  504. else if(message=="get txt")
  505. handleGetTextCommand();
  506. else if(commandName == "def2bmp")
  507. handleDef2bmpCommand(singleWordBuffer);
  508. else if(commandName == "extract")
  509. handleExtractCommand(singleWordBuffer);
  510. else if(commandName == "bonuses")
  511. handleBonusesCommand(singleWordBuffer);
  512. else if(commandName == "tell")
  513. handleTellCommand(singleWordBuffer);
  514. else if(commandName == "mp" && GAME->interface())
  515. handleMpCommand();
  516. else if (commandName == "set")
  517. handleSetCommand(singleWordBuffer);
  518. else if(commandName == "crash")
  519. handleCrashCommand();
  520. else if(commandName == "vslog")
  521. handleVsLog(singleWordBuffer);
  522. else if(message=="generate assets")
  523. handleGenerateAssets();
  524. else
  525. {
  526. if (!commandName.empty() && !vstd::iswithin(commandName[0], 0, ' ')) // filter-out debugger/IDE noise
  527. printCommandMessage("Command not found :(", ELogLevel::ERROR);
  528. }
  529. }