CCallback.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. void CBattleCallback::battleMakeSpellAction(const BattleID & battleID, const BattleAction & action)
  190. {
  191. assert(action.actionType == EActionType::HERO_SPELL);
  192. MakeAction mca(action);
  193. mca.battleID = battleID;
  194. sendRequest(&mca);
  195. }
  196. int CBattleCallback::sendRequest(const CPackForServer * request)
  197. {
  198. int requestID = cl->sendRequest(request, *getPlayerID());
  199. if(waitTillRealize)
  200. {
  201. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  202. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(CGameState::mutex, unlockGsWhenWaiting);
  203. CClient::waitingRequest.waitWhileContains(requestID);
  204. }
  205. boost::this_thread::interruption_point();
  206. return requestID;
  207. }
  208. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  209. {
  210. if(town->tempOwner == *player || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
  211. {
  212. GarrisonHeroSwap pack(town->id);
  213. sendRequest(&pack);
  214. }
  215. }
  216. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  217. {
  218. if(hero->tempOwner != *player) return;
  219. BuyArtifact pack(hero->id,aid);
  220. sendRequest(&pack);
  221. }
  222. void CCallback::trade(const IMarket * market, EMarketMode mode, TradeItemSell id1, TradeItemBuy id2, ui32 val1, const CGHeroInstance * hero)
  223. {
  224. trade(market, mode, std::vector(1, id1), std::vector(1, id2), std::vector(1, val1), hero);
  225. }
  226. 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)
  227. {
  228. TradeOnMarketplace pack;
  229. pack.marketId = dynamic_cast<const CGObjectInstance *>(market)->id;
  230. pack.heroId = hero ? hero->id : ObjectInstanceID();
  231. pack.mode = mode;
  232. pack.r1 = id1;
  233. pack.r2 = id2;
  234. pack.val = val1;
  235. sendRequest(&pack);
  236. }
  237. void CCallback::setFormation(const CGHeroInstance * hero, EArmyFormation mode)
  238. {
  239. SetFormation pack(hero->id, mode);
  240. sendRequest(&pack);
  241. }
  242. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero)
  243. {
  244. assert(townOrTavern);
  245. assert(hero);
  246. HireHero pack(hero->getHeroType(), townOrTavern->id, nextHero);
  247. pack.player = *player;
  248. sendRequest(&pack);
  249. }
  250. void CCallback::save( const std::string &fname )
  251. {
  252. cl->save(fname);
  253. }
  254. void CCallback::gamePause(bool pause)
  255. {
  256. if(pause)
  257. {
  258. GamePause pack;
  259. pack.player = *player;
  260. sendRequest(&pack);
  261. }
  262. else
  263. {
  264. sendQueryReply(0, QueryID::CLIENT);
  265. }
  266. }
  267. void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
  268. {
  269. ASSERT_IF_CALLED_WITH_PLAYER
  270. PlayerMessage pm(mess, currentObject? currentObject->id : ObjectInstanceID(-1));
  271. if(player)
  272. pm.player = *player;
  273. sendRequest(&pm);
  274. }
  275. void CCallback::buildBoat( const IShipyard *obj )
  276. {
  277. BuildBoat bb;
  278. bb.objid = dynamic_cast<const CGObjectInstance*>(obj)->id;
  279. sendRequest(&bb);
  280. }
  281. CCallback::CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C)
  282. : CBattleCallback(Player, C)
  283. {
  284. gs = GS;
  285. waitTillRealize = false;
  286. unlockGsWhenWaiting = false;
  287. }
  288. CCallback::~CCallback() = default;
  289. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  290. {
  291. //bidirectional
  292. return gs->map->canMoveBetween(a, b);
  293. }
  294. std::shared_ptr<const CPathsInfo> CCallback::getPathsInfo(const CGHeroInstance * h)
  295. {
  296. return cl->getPathsInfo(h);
  297. }
  298. std::optional<PlayerColor> CCallback::getPlayerID() const
  299. {
  300. return CBattleCallback::getPlayerID();
  301. }
  302. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  303. {
  304. if (!gs->map->isInTheMap(tile))
  305. return int3(-1,-1,-1);
  306. return gs->map->guardingCreaturePositions[tile.z][tile.x][tile.y];
  307. }
  308. void CCallback::dig( const CGObjectInstance *hero )
  309. {
  310. DigWithHero dwh;
  311. dwh.id = hero->id;
  312. sendRequest(&dwh);
  313. }
  314. void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
  315. {
  316. CastAdvSpell cas;
  317. cas.hid = hero->id;
  318. cas.sid = spellID;
  319. cas.pos = pos;
  320. sendRequest(&cas);
  321. }
  322. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  323. {
  324. if(s1->getCreature(p1) == s2->getCreature(p2))
  325. return mergeStacks(s1, s2, p1, p2);
  326. else
  327. return swapCreatures(s1, s2, p1, p2);
  328. }
  329. void CCallback::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  330. {
  331. cl->additionalBattleInts[*player].push_back(battleEvents);
  332. }
  333. void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  334. {
  335. cl->additionalBattleInts[*player] -= battleEvents;
  336. }
  337. CBattleCallback::CBattleCallback(std::optional<PlayerColor> player, CClient * C):
  338. cl(C),
  339. player(player)
  340. {
  341. }
  342. void CBattleCallback::battleMakeUnitAction(const BattleID & battleID, const BattleAction & action)
  343. {
  344. assert(!cl->gs->getBattle(battleID)->tacticDistance);
  345. MakeAction ma;
  346. ma.ba = action;
  347. ma.battleID = battleID;
  348. sendRequest(&ma);
  349. }
  350. void CBattleCallback::battleMakeTacticAction(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. std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  359. {
  360. return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleID, battleState);
  361. }
  362. std::shared_ptr<CPlayerBattleCallback> CBattleCallback::getBattle(const BattleID & battleID)
  363. {
  364. if (activeBattles.count(battleID))
  365. return activeBattles.at(battleID);
  366. 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()));
  367. }
  368. std::optional<PlayerColor> CBattleCallback::getPlayerID() const
  369. {
  370. return player;
  371. }
  372. void CBattleCallback::onBattleStarted(const IBattleInfo * info)
  373. {
  374. if (activeBattles.count(info->getBattleID()) > 0)
  375. throw std::runtime_error("Player " + player->toString() + " is already engaged in battle " + std::to_string(info->getBattleID().getNum()));
  376. logGlobal->debug("Battle %d started for player %s", info->getBattleID(), player->toString());
  377. activeBattles[info->getBattleID()] = std::make_shared<CPlayerBattleCallback>(info, *getPlayerID());
  378. }
  379. void CBattleCallback::onBattleEnded(const BattleID & battleID)
  380. {
  381. if (activeBattles.count(battleID) == 0)
  382. throw std::runtime_error("Player " + player->toString() + " is not engaged in battle " + std::to_string(battleID.getNum()));
  383. logGlobal->debug("Battle %d ended for player %s", battleID, player->toString());
  384. activeBattles.erase(battleID);
  385. }