ClientCommandManager.cpp 13 KB

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