ClientCommandManager.cpp 17 KB

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