PlayerMessageProcessor.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /*
  2. * CGameHandler.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 "PlayerMessageProcessor.h"
  12. #include "CGameHandler.h"
  13. #include "CVCMIServer.h"
  14. #include "../lib/serializer/Connection.h"
  15. #include "../lib/CGeneralTextHandler.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CPlayerState.h"
  18. #include "../lib/GameConstants.h"
  19. #include "../lib/NetPacks.h"
  20. #include "../lib/StartInfo.h"
  21. #include "../lib/gameState/CGameState.h"
  22. #include "../lib/mapObjects/CGTownInstance.h"
  23. #include "../lib/modding/IdentifierStorage.h"
  24. #include "../lib/modding/ModScope.h"
  25. PlayerMessageProcessor::PlayerMessageProcessor()
  26. :gameHandler(nullptr)
  27. {
  28. }
  29. PlayerMessageProcessor::PlayerMessageProcessor(CGameHandler * gameHandler)
  30. :gameHandler(gameHandler)
  31. {
  32. }
  33. void PlayerMessageProcessor::playerMessage(PlayerColor player, const std::string &message, ObjectInstanceID currObj)
  34. {
  35. if (handleHostCommand(player, message))
  36. return;
  37. if (handleCheatCode(message, player, currObj))
  38. {
  39. if(!gameHandler->getPlayerSettings(player)->isControlledByAI())
  40. broadcastSystemMessage(VLC->generaltexth->allTexts[260]);
  41. if(!player.isSpectator())
  42. gameHandler->checkVictoryLossConditionsForPlayer(player);//Player enter win code or got required art\creature
  43. return;
  44. }
  45. broadcastMessage(player, message);
  46. }
  47. bool PlayerMessageProcessor::handleHostCommand(PlayerColor player, const std::string &message)
  48. {
  49. std::vector<std::string> words;
  50. boost::split(words, message, boost::is_any_of(" "));
  51. bool isHost = false;
  52. for(auto & c : gameHandler->connections[player])
  53. if(gameHandler->gameLobby()->isClientHost(c->connectionID))
  54. isHost = true;
  55. if(!isHost || words.size() < 2 || words[0] != "game")
  56. return false;
  57. if(words[1] == "exit" || words[1] == "quit" || words[1] == "end")
  58. {
  59. broadcastSystemMessage("game was terminated");
  60. gameHandler->gameLobby()->state = EServerState::SHUTDOWN;
  61. return true;
  62. }
  63. if(words.size() == 3 && words[1] == "save")
  64. {
  65. gameHandler->save("Saves/" + words[2]);
  66. broadcastSystemMessage("game saved as " + words[2]);
  67. return true;
  68. }
  69. if(words.size() == 3 && words[1] == "kick")
  70. {
  71. auto playername = words[2];
  72. PlayerColor playerToKick(PlayerColor::CANNOT_DETERMINE);
  73. if(std::all_of(playername.begin(), playername.end(), ::isdigit))
  74. playerToKick = PlayerColor(std::stoi(playername));
  75. else
  76. {
  77. for(auto & c : gameHandler->connections)
  78. {
  79. if(c.first.getStr(false) == playername)
  80. playerToKick = c.first;
  81. }
  82. }
  83. if(playerToKick != PlayerColor::CANNOT_DETERMINE)
  84. {
  85. PlayerCheated pc;
  86. pc.player = playerToKick;
  87. pc.losingCheatCode = true;
  88. gameHandler->sendAndApply(&pc);
  89. gameHandler->checkVictoryLossConditionsForPlayer(playerToKick);
  90. }
  91. return true;
  92. }
  93. if(words.size() == 2 && words[1] == "cheaters")
  94. {
  95. if (cheaters.empty())
  96. broadcastSystemMessage("No cheaters registered!");
  97. for (auto const & entry : cheaters)
  98. broadcastSystemMessage("Player " + entry.getStr() + " is cheater!");
  99. return true;
  100. }
  101. return false;
  102. }
  103. void PlayerMessageProcessor::cheatGiveSpells(PlayerColor player, const CGHeroInstance * hero)
  104. {
  105. if (!hero)
  106. return;
  107. ///Give hero spellbook
  108. if (!hero->hasSpellbook())
  109. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  110. ///Give all spells with bonus (to allow banned spells)
  111. GiveBonus giveBonus(GiveBonus::ETarget::HERO);
  112. giveBonus.id = hero->id.getNum();
  113. giveBonus.bonus = Bonus(BonusDuration::PERMANENT, BonusType::SPELLS_OF_LEVEL, BonusSource::OTHER, 0, 0);
  114. //start with level 0 to skip abilities
  115. for (int level = 1; level <= GameConstants::SPELL_LEVELS; level++)
  116. {
  117. giveBonus.bonus.subtype = level;
  118. gameHandler->sendAndApply(&giveBonus);
  119. }
  120. ///Give mana
  121. SetMana sm;
  122. sm.hid = hero->id;
  123. sm.val = 999;
  124. sm.absolute = true;
  125. gameHandler->sendAndApply(&sm);
  126. }
  127. void PlayerMessageProcessor::cheatBuildTown(PlayerColor player, const CGTownInstance * town)
  128. {
  129. if (!town)
  130. return;
  131. for (auto & build : town->town->buildings)
  132. {
  133. if (!town->hasBuilt(build.first)
  134. && !build.second->getNameTranslated().empty()
  135. && build.first != BuildingID::SHIP)
  136. {
  137. gameHandler->buildStructure(town->id, build.first, true);
  138. }
  139. }
  140. }
  141. void PlayerMessageProcessor::cheatGiveArmy(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  142. {
  143. if (!hero)
  144. return;
  145. std::string creatureIdentifier = words.empty() ? "archangel" : words[0];
  146. std::optional<int> amountPerSlot;
  147. try
  148. {
  149. amountPerSlot = std::stol(words.at(1));
  150. }
  151. catch(std::logic_error&)
  152. {
  153. }
  154. std::optional<int32_t> creatureId = VLC->identifiers()->getIdentifier(ModScope::scopeGame(), "creature", creatureIdentifier, false);
  155. if(creatureId.has_value())
  156. {
  157. const auto * creature = CreatureID(creatureId.value()).toCreature();
  158. for (int i = 0; i < GameConstants::ARMY_SIZE; i++)
  159. {
  160. if (!hero->hasStackAtSlot(SlotID(i)))
  161. {
  162. if (amountPerSlot.has_value())
  163. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, *amountPerSlot);
  164. else
  165. gameHandler->insertNewStack(StackLocation(hero, SlotID(i)), creature, 5 * std::pow(10, i));
  166. }
  167. }
  168. }
  169. }
  170. void PlayerMessageProcessor::cheatGiveMachines(PlayerColor player, const CGHeroInstance * hero)
  171. {
  172. if (!hero)
  173. return;
  174. if (!hero->getArt(ArtifactPosition::MACH1))
  175. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::BALLISTA], ArtifactPosition::MACH1);
  176. if (!hero->getArt(ArtifactPosition::MACH2))
  177. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::AMMO_CART], ArtifactPosition::MACH2);
  178. if (!hero->getArt(ArtifactPosition::MACH3))
  179. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::FIRST_AID_TENT], ArtifactPosition::MACH3);
  180. }
  181. void PlayerMessageProcessor::cheatGiveArtifacts(PlayerColor player, const CGHeroInstance * hero)
  182. {
  183. if (!hero)
  184. return;
  185. for(int g = 7; g < VLC->arth->objects.size(); ++g) //including artifacts from mods
  186. {
  187. if(VLC->arth->objects[g]->canBePutAt(hero))
  188. gameHandler->giveHeroNewArtifact(hero, VLC->arth->objects[g], ArtifactPosition::FIRST_AVAILABLE);
  189. }
  190. }
  191. void PlayerMessageProcessor::cheatLevelup(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  192. {
  193. if (!hero)
  194. return;
  195. int levelsToGain;
  196. try
  197. {
  198. levelsToGain = std::stol(words.at(0));
  199. }
  200. catch(std::logic_error&)
  201. {
  202. levelsToGain = 1;
  203. }
  204. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, VLC->heroh->reqExp(hero->level + levelsToGain) - VLC->heroh->reqExp(hero->level));
  205. }
  206. void PlayerMessageProcessor::cheatExperience(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  207. {
  208. if (!hero)
  209. return;
  210. int expAmountProcessed;
  211. try
  212. {
  213. expAmountProcessed = std::stol(words.at(0));
  214. }
  215. catch(std::logic_error&)
  216. {
  217. expAmountProcessed = 10000;
  218. }
  219. gameHandler->changePrimSkill(hero, PrimarySkill::EXPERIENCE, expAmountProcessed);
  220. }
  221. void PlayerMessageProcessor::cheatMovement(PlayerColor player, const CGHeroInstance * hero, std::vector<std::string> words)
  222. {
  223. if (!hero)
  224. return;
  225. SetMovePoints smp;
  226. smp.hid = hero->id;
  227. try
  228. {
  229. smp.val = std::stol(words.at(0));;
  230. }
  231. catch(std::logic_error&)
  232. {
  233. smp.val = 1000000;
  234. }
  235. gameHandler->sendAndApply(&smp);
  236. GiveBonus gb(GiveBonus::ETarget::HERO);
  237. gb.bonus.type = BonusType::FREE_SHIP_BOARDING;
  238. gb.bonus.duration = BonusDuration::ONE_DAY;
  239. gb.bonus.source = BonusSource::OTHER;
  240. gb.id = hero->id.getNum();
  241. gameHandler->giveHeroBonus(&gb);
  242. }
  243. void PlayerMessageProcessor::cheatResources(PlayerColor player, std::vector<std::string> words)
  244. {
  245. int baseResourceAmount;
  246. try
  247. {
  248. baseResourceAmount = std::stol(words.at(0));;
  249. }
  250. catch(std::logic_error&)
  251. {
  252. baseResourceAmount = 100;
  253. }
  254. TResources resources;
  255. resources[EGameResID::GOLD] = baseResourceAmount * 1000;
  256. for (GameResID i = EGameResID::WOOD; i < EGameResID::GOLD; ++i)
  257. resources[i] = baseResourceAmount;
  258. gameHandler->giveResources(player, resources);
  259. }
  260. void PlayerMessageProcessor::cheatVictory(PlayerColor player)
  261. {
  262. PlayerCheated pc;
  263. pc.player = player;
  264. pc.winningCheatCode = true;
  265. gameHandler->sendAndApply(&pc);
  266. }
  267. void PlayerMessageProcessor::cheatDefeat(PlayerColor player)
  268. {
  269. PlayerCheated pc;
  270. pc.player = player;
  271. pc.losingCheatCode = true;
  272. gameHandler->sendAndApply(&pc);
  273. }
  274. void PlayerMessageProcessor::cheatMapReveal(PlayerColor player, bool reveal)
  275. {
  276. FoWChange fc;
  277. fc.mode = reveal;
  278. fc.player = player;
  279. const auto & fowMap = gameHandler->gameState()->getPlayerTeam(player)->fogOfWarMap;
  280. const auto & mapSize = gameHandler->gameState()->getMapSize();
  281. auto hlp_tab = new int3[mapSize.x * mapSize.y * mapSize.z];
  282. int lastUnc = 0;
  283. for(int z = 0; z < mapSize.z; z++)
  284. for(int x = 0; x < mapSize.x; x++)
  285. for(int y = 0; y < mapSize.y; y++)
  286. if(!(*fowMap)[z][x][y] || !fc.mode)
  287. hlp_tab[lastUnc++] = int3(x, y, z);
  288. fc.tiles.insert(hlp_tab, hlp_tab + lastUnc);
  289. delete [] hlp_tab;
  290. gameHandler->sendAndApply(&fc);
  291. }
  292. bool PlayerMessageProcessor::handleCheatCode(const std::string & cheat, PlayerColor player, ObjectInstanceID currObj)
  293. {
  294. std::vector<std::string> words;
  295. boost::split(words, cheat, boost::is_any_of("\t\r\n "));
  296. if (words.empty())
  297. return false;
  298. //Make cheat name case-insensitive, but keep words/parameters (e.g. creature name) as it
  299. std::string cheatName = boost::to_lower_copy(words[0]);
  300. words.erase(words.begin());
  301. std::vector<std::string> townTargetedCheats = { "vcmiarmenelos", "vcmibuild", "nwczion" };
  302. std::vector<std::string> playerTargetedCheats = {
  303. "vcmiformenos", "vcmiresources", "nwctheconstruct",
  304. "vcmimelkor", "vcmilose", "nwcbluepill",
  305. "vcmisilmaril", "vcmiwin", "nwcredpill",
  306. "vcmieagles", "vcmimap", "nwcwhatisthematrix",
  307. "vcmiungoliant", "vcmihidemap", "nwcignoranceisbliss"
  308. };
  309. std::vector<std::string> heroTargetedCheats = {
  310. "vcmiainur", "vcmiarchangel", "nwctrinity",
  311. "vcmiangband", "vcmiblackknight", "nwcagents",
  312. "vcmiglaurung", "vcmicrystal", "vcmiazure",
  313. "vcmifaerie", "vcmiarmy", "vcminissi",
  314. "vcmiistari", "vcmispells", "nwcthereisnospoon",
  315. "vcminoldor", "vcmimachines", "nwclotsofguns",
  316. "vcmiglorfindel", "vcmilevel", "nwcneo",
  317. "vcminahar", "vcmimove", "nwcnebuchadnezzar",
  318. "vcmiforgeofnoldorking", "vcmiartifacts",
  319. "vcmiolorin", "vcmiexp",
  320. };
  321. if (!vstd::contains(townTargetedCheats, cheatName) && !vstd::contains(playerTargetedCheats, cheatName) && !vstd::contains(heroTargetedCheats, cheatName))
  322. return false;
  323. bool playerTargetedCheat = false;
  324. for (const auto & i : gameHandler->gameState()->players)
  325. {
  326. if (words.empty())
  327. break;
  328. if (i.first == PlayerColor::NEUTRAL)
  329. continue;
  330. if (words.front() == "ai" && i.second.human)
  331. continue;
  332. if (words.front() != "all" && words.front() != i.first.getStr())
  333. continue;
  334. std::vector<std::string> parameters = words;
  335. cheaters.insert(i.first);
  336. playerTargetedCheat = true;
  337. parameters.erase(parameters.begin());
  338. if (vstd::contains(playerTargetedCheats, cheatName))
  339. executeCheatCode(cheatName, i.first, ObjectInstanceID::NONE, parameters);
  340. if (vstd::contains(townTargetedCheats, cheatName))
  341. for (const auto & t : i.second.towns)
  342. executeCheatCode(cheatName, i.first, t->id, parameters);
  343. if (vstd::contains(heroTargetedCheats, cheatName))
  344. for (const auto & h : i.second.heroes)
  345. executeCheatCode(cheatName, i.first, h->id, parameters);
  346. }
  347. if (!playerTargetedCheat)
  348. executeCheatCode(cheatName, player, currObj, words);
  349. cheaters.insert(player);
  350. return true;
  351. }
  352. void PlayerMessageProcessor::executeCheatCode(const std::string & cheatName, PlayerColor player, ObjectInstanceID currObj, const std::vector<std::string> & words)
  353. {
  354. const CGHeroInstance * hero = gameHandler->getHero(currObj);
  355. const CGTownInstance * town = gameHandler->getTown(currObj);
  356. if (!town && hero)
  357. town = hero->visitedTown;
  358. const auto & doCheatGiveSpells = [&]() { cheatGiveSpells(player, hero); };
  359. const auto & doCheatBuildTown = [&]() { cheatBuildTown(player, town); };
  360. const auto & doCheatGiveArmyCustom = [&]() { cheatGiveArmy(player, hero, words); };
  361. const auto & doCheatGiveArmyFixed = [&](std::vector<std::string> customWords) { cheatGiveArmy(player, hero, customWords); };
  362. const auto & doCheatGiveMachines = [&]() { cheatGiveMachines(player, hero); };
  363. const auto & doCheatGiveArtifacts = [&]() { cheatGiveArtifacts(player, hero); };
  364. const auto & doCheatLevelup = [&]() { cheatLevelup(player, hero, words); };
  365. const auto & doCheatExperience = [&]() { cheatExperience(player, hero, words); };
  366. const auto & doCheatMovement = [&]() { cheatMovement(player, hero, words); };
  367. const auto & doCheatResources = [&]() { cheatResources(player, words); };
  368. const auto & doCheatVictory = [&]() { cheatVictory(player); };
  369. const auto & doCheatDefeat = [&]() { cheatDefeat(player); };
  370. const auto & doCheatMapReveal = [&]() { cheatMapReveal(player, true); };
  371. const auto & doCheatMapHide = [&]() { cheatMapReveal(player, false); };
  372. // Unimplemented H3 cheats:
  373. // nwcfollowthewhiterabbit - The currently selected hero permanently gains maximum luck.
  374. // nwcmorpheus - The currently selected hero permanently gains maximum morale.
  375. // nwcoracle - The puzzle map is permanently revealed.
  376. // nwcphisherprice - Changes and brightens the game colors.
  377. std::map<std::string, std::function<void()>> callbacks = {
  378. {"vcmiainur", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  379. {"nwctrinity", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  380. {"vcmiangband", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  381. {"vcmiglaurung", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  382. {"vcmiarchangel", [&] () {doCheatGiveArmyFixed({ "archangel", "5" });} },
  383. {"nwcagents", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  384. {"vcmiblackknight", [&] () {doCheatGiveArmyFixed({ "blackKnight", "10" });} },
  385. {"vcmicrystal", [&] () {doCheatGiveArmyFixed({ "crystalDragon", "5000" });} },
  386. {"vcmiazure", [&] () {doCheatGiveArmyFixed({ "azureDragon", "5000" });} },
  387. {"vcmifaerie", [&] () {doCheatGiveArmyFixed({ "fairieDragon", "5000" });} },
  388. {"vcmiarmy", doCheatGiveArmyCustom },
  389. {"vcminissi", doCheatGiveArmyCustom },
  390. {"vcmiistari", doCheatGiveSpells },
  391. {"vcmispells", doCheatGiveSpells },
  392. {"nwcthereisnospoon", doCheatGiveSpells },
  393. {"vcmiarmenelos", doCheatBuildTown },
  394. {"vcmibuild", doCheatBuildTown },
  395. {"nwczion", doCheatBuildTown },
  396. {"vcminoldor", doCheatGiveMachines },
  397. {"vcmimachines", doCheatGiveMachines },
  398. {"nwclotsofguns", doCheatGiveMachines },
  399. {"vcmiforgeofnoldorking", doCheatGiveArtifacts },
  400. {"vcmiartifacts", doCheatGiveArtifacts },
  401. {"vcmiglorfindel", doCheatLevelup },
  402. {"vcmilevel", doCheatLevelup },
  403. {"nwcneo", doCheatLevelup },
  404. {"vcmiolorin", doCheatExperience },
  405. {"vcmiexp", doCheatExperience },
  406. {"vcminahar", doCheatMovement },
  407. {"vcmimove", doCheatMovement },
  408. {"nwcnebuchadnezzar", doCheatMovement },
  409. {"vcmiformenos", doCheatResources },
  410. {"vcmiresources", doCheatResources },
  411. {"nwctheconstruct", doCheatResources },
  412. {"nwcbluepill", doCheatDefeat },
  413. {"vcmimelkor", doCheatDefeat },
  414. {"vcmilose", doCheatDefeat },
  415. {"nwcredpill", doCheatVictory },
  416. {"vcmisilmaril", doCheatVictory },
  417. {"vcmiwin", doCheatVictory },
  418. {"nwcwhatisthematrix", doCheatMapReveal },
  419. {"vcmieagles", doCheatMapReveal },
  420. {"vcmimap", doCheatMapReveal },
  421. {"vcmiungoliant", doCheatMapHide },
  422. {"vcmihidemap", doCheatMapHide },
  423. {"nwcignoranceisbliss", doCheatMapHide },
  424. };
  425. assert(callbacks.count(cheatName));
  426. if (callbacks.count(cheatName))
  427. callbacks.at(cheatName)();
  428. }
  429. void PlayerMessageProcessor::sendSystemMessage(std::shared_ptr<CConnection> connection, const std::string & message)
  430. {
  431. SystemMessage sm;
  432. sm.text = message;
  433. connection->sendPack(&sm);
  434. }
  435. void PlayerMessageProcessor::broadcastSystemMessage(const std::string & message)
  436. {
  437. SystemMessage sm;
  438. sm.text = message;
  439. gameHandler->sendToAllClients(&sm);
  440. }
  441. void PlayerMessageProcessor::broadcastMessage(PlayerColor playerSender, const std::string & message)
  442. {
  443. PlayerMessageClient temp_message(playerSender, message);
  444. gameHandler->sendAndApply(&temp_message);
  445. }