CCallback.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. * CCallback.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 "CCallback.h"
  12. #include "lib/CCreatureHandler.h"
  13. #include "lib/gameState/CGameState.h"
  14. #include "client/CPlayerInterface.h"
  15. #include "client/Client.h"
  16. #include "lib/mapping/CMap.h"
  17. #include "lib/mapObjects/CGHeroInstance.h"
  18. #include "lib/mapObjects/CGTownInstance.h"
  19. #include "lib/texts/CGeneralTextHandler.h"
  20. #include "lib/CHeroHandler.h"
  21. #include "lib/CArtHandler.h"
  22. #include "lib/GameConstants.h"
  23. #include "lib/CPlayerState.h"
  24. #include "lib/UnlockGuard.h"
  25. #include "lib/battle/BattleInfo.h"
  26. #include "lib/networkPacks/PacksForServer.h"
  27. bool CCallback::teleportHero(const CGHeroInstance *who, const CGTownInstance *where)
  28. {
  29. CastleTeleportHero pack(who->id, where->id, 1);
  30. sendRequest(&pack);
  31. return true;
  32. }
  33. void CCallback::moveHero(const CGHeroInstance *h, const int3 & destination, bool transit)
  34. {
  35. MoveHero pack({destination}, h->id, transit);
  36. sendRequest(&pack);
  37. }
  38. void CCallback::moveHero(const CGHeroInstance *h, const std::vector<int3> & path, bool transit)
  39. {
  40. MoveHero pack(path, h->id, transit);
  41. sendRequest(&pack);
  42. }
  43. int CCallback::selectionMade(int selection, QueryID queryID)
  44. {
  45. return sendQueryReply(selection, queryID);
  46. }
  47. int CCallback::sendQueryReply(std::optional<int32_t> reply, QueryID queryID)
  48. {
  49. ASSERT_IF_CALLED_WITH_PLAYER
  50. if(queryID == QueryID(-1))
  51. {
  52. logGlobal->error("Cannot answer the query -1!");
  53. return -1;
  54. }
  55. QueryReply pack(queryID, reply);
  56. pack.player = *player;
  57. return sendRequest(&pack);
  58. }
  59. void CCallback::recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level)
  60. {
  61. // TODO exception for neutral dwellings shouldn't be hardcoded
  62. if(player != obj->tempOwner && obj->ID != Obj::WAR_MACHINE_FACTORY && obj->ID != Obj::REFUGEE_CAMP)
  63. return;
  64. RecruitCreatures pack(obj->id, dst->id, ID, amount, level);
  65. sendRequest(&pack);
  66. }
  67. bool CCallback::dismissCreature(const CArmedInstance *obj, SlotID stackPos)
  68. {
  69. if((player && obj->tempOwner != player) || (obj->stacksCount()<2 && obj->needsLastStack()))
  70. return false;
  71. DisbandCreature pack(stackPos,obj->id);
  72. sendRequest(&pack);
  73. return true;
  74. }
  75. bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID)
  76. {
  77. UpgradeCreature pack(stackPos,obj->id,newID);
  78. sendRequest(&pack);
  79. return false;
  80. }
  81. void CCallback::endTurn()
  82. {
  83. logGlobal->trace("Player %d ended his turn.", player->getNum());
  84. EndTurn pack;
  85. sendRequest(&pack);
  86. }
  87. int CCallback::swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  88. {
  89. ArrangeStacks pack(1,p1,p2,s1->id,s2->id,0);
  90. sendRequest(&pack);
  91. return 0;
  92. }
  93. int CCallback::mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  94. {
  95. ArrangeStacks pack(2,p1,p2,s1->id,s2->id,0);
  96. sendRequest(&pack);
  97. return 0;
  98. }
  99. int CCallback::splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)
  100. {
  101. ArrangeStacks pack(3,p1,p2,s1->id,s2->id,val);
  102. sendRequest(&pack);
  103. return 0;
  104. }
  105. int CCallback::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  106. {
  107. BulkMoveArmy pack(srcArmy, destArmy, srcSlot);
  108. sendRequest(&pack);
  109. return 0;
  110. }
  111. int CCallback::bulkSplitStack(ObjectInstanceID armyId, SlotID srcSlot, int howMany)
  112. {
  113. BulkSplitStack pack(armyId, srcSlot, howMany);
  114. sendRequest(&pack);
  115. return 0;
  116. }
  117. int CCallback::bulkSmartSplitStack(ObjectInstanceID armyId, SlotID srcSlot)
  118. {
  119. BulkSmartSplitStack pack(armyId, srcSlot);
  120. sendRequest(&pack);
  121. return 0;
  122. }
  123. int CCallback::bulkMergeStacks(ObjectInstanceID armyId, SlotID srcSlot)
  124. {
  125. BulkMergeStacks pack(armyId, srcSlot);
  126. sendRequest(&pack);
  127. return 0;
  128. }
  129. bool CCallback::dismissHero(const CGHeroInstance *hero)
  130. {
  131. if(player!=hero->tempOwner) return false;
  132. DismissHero pack(hero->id);
  133. sendRequest(&pack);
  134. return true;
  135. }
  136. bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)
  137. {
  138. ExchangeArtifacts ea;
  139. ea.src = l1;
  140. ea.dst = l2;
  141. sendRequest(&ea);
  142. return true;
  143. }
  144. /**
  145. * Assembles or disassembles a combination artifact.
  146. * @param hero Hero holding the artifact(s).
  147. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  148. * @param assemble True for assembly operation, false for disassembly.
  149. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  150. * artifact to assemble to. Otherwise it's not used.
  151. */
  152. void CCallback::assembleArtifacts(const ObjectInstanceID & heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  153. {
  154. AssembleArtifacts aa(heroID, artifactSlot, assemble, assembleTo);
  155. sendRequest(&aa);
  156. }
  157. void CCallback::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap, bool equipped, bool backpack)
  158. {
  159. BulkExchangeArtifacts bma(srcHero, dstHero, swap, equipped, backpack);
  160. sendRequest(&bma);
  161. }
  162. void CCallback::scrollBackpackArtifacts(ObjectInstanceID hero, bool left)
  163. {
  164. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SCROLL_RIGHT);
  165. if(left)
  166. mba.cmd = ManageBackpackArtifacts::ManageCmd::SCROLL_LEFT;
  167. sendRequest(&mba);
  168. }
  169. void CCallback::manageHeroCostume(ObjectInstanceID hero, size_t costumeIndex, bool saveCostume)
  170. {
  171. ManageEquippedArtifacts mea(hero, costumeIndex, saveCostume);
  172. sendRequest(&mea);
  173. }
  174. void CCallback::eraseArtifactByClient(const ArtifactLocation & al)
  175. {
  176. EraseArtifactByClient ea(al);
  177. sendRequest(&ea);
  178. }
  179. bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
  180. {
  181. if(town->tempOwner!=player)
  182. return false;
  183. if(canBuildStructure(town, buildingID) != EBuildingState::ALLOWED)
  184. return false;
  185. BuildStructure pack(town->id,buildingID);
  186. sendRequest(&pack);
  187. return true;
  188. }
  189. bool CCallback::triggerTownSpecialBuildingAction(const CGTownInstance *town, BuildingSubID::EBuildingSubID subBuildingID)
  190. {
  191. if(town->tempOwner!=player)
  192. return false;
  193. TriggerTownSpecialBuildingAction pack(town->id, subBuildingID);
  194. sendRequest(&pack);
  195. return true;
  196. }
  197. void CBattleCallback::battleMakeSpellAction(const BattleID & battleID, const BattleAction & action)
  198. {
  199. assert(action.actionType == EActionType::HERO_SPELL);
  200. MakeAction mca(action);
  201. mca.battleID = battleID;
  202. sendRequest(&mca);
  203. }
  204. int CBattleCallback::sendRequest(const CPackForServer * request)
  205. {
  206. int requestID = cl->sendRequest(request, *getPlayerID());
  207. if(waitTillRealize)
  208. {
  209. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  210. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(CGameState::mutex, unlockGsWhenWaiting);
  211. CClient::waitingRequest.waitWhileContains(requestID);
  212. }
  213. boost::this_thread::interruption_point();
  214. return requestID;
  215. }
  216. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  217. {
  218. if(town->tempOwner == *player || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
  219. {
  220. GarrisonHeroSwap pack(town->id);
  221. sendRequest(&pack);
  222. }
  223. }
  224. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  225. {
  226. if(hero->tempOwner != *player) return;
  227. BuyArtifact pack(hero->id,aid);
  228. sendRequest(&pack);
  229. }
  230. void CCallback::trade(const IMarket * market, EMarketMode mode, TradeItemSell id1, TradeItemBuy id2, ui32 val1, const CGHeroInstance * hero)
  231. {
  232. trade(market, mode, std::vector(1, id1), std::vector(1, id2), std::vector(1, val1), hero);
  233. }
  234. void CCallback::trade(const IMarket * market, EMarketMode mode, const std::vector<TradeItemSell> & id1, const std::vector<TradeItemBuy> & id2, const std::vector<ui32> & val1, const CGHeroInstance * hero)
  235. {
  236. TradeOnMarketplace pack;
  237. pack.marketId = dynamic_cast<const CGObjectInstance *>(market)->id;
  238. pack.heroId = hero ? hero->id : ObjectInstanceID();
  239. pack.mode = mode;
  240. pack.r1 = id1;
  241. pack.r2 = id2;
  242. pack.val = val1;
  243. sendRequest(&pack);
  244. }
  245. void CCallback::setFormation(const CGHeroInstance * hero, EArmyFormation mode)
  246. {
  247. SetFormation pack(hero->id, mode);
  248. sendRequest(&pack);
  249. }
  250. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero)
  251. {
  252. assert(townOrTavern);
  253. assert(hero);
  254. HireHero pack(hero->getHeroType(), townOrTavern->id, nextHero);
  255. pack.player = *player;
  256. sendRequest(&pack);
  257. }
  258. void CCallback::save( const std::string &fname )
  259. {
  260. cl->save(fname);
  261. }
  262. void CCallback::gamePause(bool pause)
  263. {
  264. if(pause)
  265. {
  266. GamePause pack;
  267. pack.player = *player;
  268. sendRequest(&pack);
  269. }
  270. else
  271. {
  272. sendQueryReply(0, QueryID::CLIENT);
  273. }
  274. }
  275. void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
  276. {
  277. ASSERT_IF_CALLED_WITH_PLAYER
  278. PlayerMessage pm(mess, currentObject? currentObject->id : ObjectInstanceID(-1));
  279. if(player)
  280. pm.player = *player;
  281. sendRequest(&pm);
  282. }
  283. void CCallback::buildBoat( const IShipyard *obj )
  284. {
  285. BuildBoat bb;
  286. bb.objid = dynamic_cast<const CGObjectInstance*>(obj)->id;
  287. sendRequest(&bb);
  288. }
  289. CCallback::CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C)
  290. : CBattleCallback(Player, C)
  291. {
  292. gs = GS;
  293. waitTillRealize = false;
  294. unlockGsWhenWaiting = false;
  295. }
  296. CCallback::~CCallback() = default;
  297. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  298. {
  299. //bidirectional
  300. return gs->map->canMoveBetween(a, b);
  301. }
  302. std::shared_ptr<const CPathsInfo> CCallback::getPathsInfo(const CGHeroInstance * h)
  303. {
  304. return cl->getPathsInfo(h);
  305. }
  306. std::optional<PlayerColor> CCallback::getPlayerID() const
  307. {
  308. return CBattleCallback::getPlayerID();
  309. }
  310. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  311. {
  312. if (!gs->map->isInTheMap(tile))
  313. return int3(-1,-1,-1);
  314. return gs->map->guardingCreaturePositions[tile.z][tile.x][tile.y];
  315. }
  316. void CCallback::dig( const CGObjectInstance *hero )
  317. {
  318. DigWithHero dwh;
  319. dwh.id = hero->id;
  320. sendRequest(&dwh);
  321. }
  322. void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
  323. {
  324. CastAdvSpell cas;
  325. cas.hid = hero->id;
  326. cas.sid = spellID;
  327. cas.pos = pos;
  328. sendRequest(&cas);
  329. }
  330. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  331. {
  332. if(s1->getCreature(p1) == s2->getCreature(p2))
  333. return mergeStacks(s1, s2, p1, p2);
  334. else
  335. return swapCreatures(s1, s2, p1, p2);
  336. }
  337. void CCallback::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  338. {
  339. cl->additionalBattleInts[*player].push_back(battleEvents);
  340. }
  341. void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  342. {
  343. cl->additionalBattleInts[*player] -= battleEvents;
  344. }
  345. CBattleCallback::CBattleCallback(std::optional<PlayerColor> player, CClient * C):
  346. cl(C),
  347. player(player)
  348. {
  349. }
  350. void CBattleCallback::battleMakeUnitAction(const BattleID & battleID, const BattleAction & action)
  351. {
  352. assert(!cl->gs->getBattle(battleID)->tacticDistance);
  353. MakeAction ma;
  354. ma.ba = action;
  355. ma.battleID = battleID;
  356. sendRequest(&ma);
  357. }
  358. void CBattleCallback::battleMakeTacticAction(const BattleID & battleID, const BattleAction & action )
  359. {
  360. assert(cl->gs->getBattle(battleID)->tacticDistance);
  361. MakeAction ma;
  362. ma.ba = action;
  363. ma.battleID = battleID;
  364. sendRequest(&ma);
  365. }
  366. std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  367. {
  368. return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleID, battleState);
  369. }
  370. std::shared_ptr<CPlayerBattleCallback> CBattleCallback::getBattle(const BattleID & battleID)
  371. {
  372. if (activeBattles.count(battleID))
  373. return activeBattles.at(battleID);
  374. throw std::runtime_error("Failed to find battle " + std::to_string(battleID.getNum()) + " of player " + player->toString() + ". Number of ongoing battles: " + std::to_string(activeBattles.size()));
  375. }
  376. std::optional<PlayerColor> CBattleCallback::getPlayerID() const
  377. {
  378. return player;
  379. }
  380. void CBattleCallback::onBattleStarted(const IBattleInfo * info)
  381. {
  382. if (activeBattles.count(info->getBattleID()) > 0)
  383. throw std::runtime_error("Player " + player->toString() + " is already engaged in battle " + std::to_string(info->getBattleID().getNum()));
  384. logGlobal->debug("Battle %d started for player %s", info->getBattleID(), player->toString());
  385. activeBattles[info->getBattleID()] = std::make_shared<CPlayerBattleCallback>(info, *getPlayerID());
  386. }
  387. void CBattleCallback::onBattleEnded(const BattleID & battleID)
  388. {
  389. if (activeBattles.count(battleID) == 0)
  390. throw std::runtime_error("Player " + player->toString() + " is not engaged in battle " + std::to_string(battleID.getNum()));
  391. logGlobal->debug("Battle %d ended for player %s", battleID, player->toString());
  392. activeBattles.erase(battleID);
  393. }