ClientCommandManager.cpp 16 KB

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