ClientCommandManager.cpp 15 KB

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