ClientCommandManager.cpp 14 KB

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