ClientCommandManager.cpp 13 KB

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