ClientCommandManager.cpp 14 KB

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