PlayerMessageProcessor.cpp 17 KB

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