ClientCommandManager.cpp 15 KB

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