AIGateway.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. /*
  2. * AIGateway.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 "../../lib/UnlockGuard.h"
  12. #include "../../lib/mapObjects/MapObjects.h"
  13. #include "../../lib/mapObjects/ObjectTemplate.h"
  14. #include "../../lib/CConfigHandler.h"
  15. #include "../../lib/CHeroHandler.h"
  16. #include "../../lib/GameSettings.h"
  17. #include "../../lib/CGameState.h"
  18. #include "../../lib/NetPacks.h"
  19. #include "../../lib/serializer/CTypeList.h"
  20. #include "../../lib/serializer/BinarySerializer.h"
  21. #include "../../lib/serializer/BinaryDeserializer.h"
  22. #include "../../lib/battle/BattleStateInfoForRetreat.h"
  23. #include "AIGateway.h"
  24. #include "Goals/Goals.h"
  25. namespace NKAI
  26. {
  27. // our to enemy strength ratio constants
  28. const float SAFE_ATTACK_CONSTANT = 1.2f;
  29. const float RETREAT_THRESHOLD = 0.3f;
  30. const double RETREAT_ABSOLUTE_THRESHOLD = 10000.;
  31. //one thread may be turn of AI and another will be handling a side effect for AI2
  32. boost::thread_specific_ptr<CCallback> cb;
  33. boost::thread_specific_ptr<AIGateway> ai;
  34. //helper RAII to manage global ai/cb ptrs
  35. struct SetGlobalState
  36. {
  37. SetGlobalState(AIGateway * AI)
  38. {
  39. assert(!ai.get());
  40. assert(!cb.get());
  41. ai.reset(AI);
  42. cb.reset(AI->myCb.get());
  43. }
  44. ~SetGlobalState()
  45. {
  46. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  47. //TODO: to ensure that, make rm unique_ptr
  48. ai.release();
  49. cb.release();
  50. }
  51. };
  52. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  53. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  54. #define MAKING_TURN SET_GLOBAL_STATE(this)
  55. AIGateway::AIGateway()
  56. {
  57. LOG_TRACE(logAi);
  58. makingTurn = nullptr;
  59. destinationTeleport = ObjectInstanceID();
  60. destinationTeleportPos = int3(-1);
  61. nullkiller.reset(new Nullkiller());
  62. }
  63. AIGateway::~AIGateway()
  64. {
  65. LOG_TRACE(logAi);
  66. finish();
  67. nullkiller.reset();
  68. }
  69. void AIGateway::availableCreaturesChanged(const CGDwelling * town)
  70. {
  71. LOG_TRACE(logAi);
  72. NET_EVENT_HANDLER;
  73. }
  74. void AIGateway::heroMoved(const TryMoveHero & details, bool verbose)
  75. {
  76. LOG_TRACE(logAi);
  77. NET_EVENT_HANDLER;
  78. validateObject(details.id); //enemy hero may have left visible area
  79. auto hero = cb->getHero(details.id);
  80. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));;
  81. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  82. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  83. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  84. if(details.result == TryMoveHero::TELEPORTATION)
  85. {
  86. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  87. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  88. if(t1 && t2)
  89. {
  90. if(cb->isTeleportChannelBidirectional(t1->channel))
  91. {
  92. if(o1->ID == Obj::SUBTERRANEAN_GATE && o1->ID == o2->ID) // We need to only add subterranean gates in knownSubterraneanGates. Used for features not yet ported to use teleport channels
  93. {
  94. nullkiller->memory->addSubterraneanGate(o1, o2);
  95. }
  96. }
  97. }
  98. }
  99. else if(details.result == TryMoveHero::EMBARK && hero)
  100. {
  101. //make sure AI not attempt to visit used boat
  102. validateObject(hero->boat);
  103. }
  104. else if(details.result == TryMoveHero::DISEMBARK && o1)
  105. {
  106. auto boat = dynamic_cast<const CGBoat *>(o1);
  107. if(boat)
  108. addVisitableObj(boat);
  109. }
  110. }
  111. void AIGateway::heroInGarrisonChange(const CGTownInstance * town)
  112. {
  113. LOG_TRACE(logAi);
  114. NET_EVENT_HANDLER;
  115. }
  116. void AIGateway::centerView(int3 pos, int focusTime)
  117. {
  118. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  119. NET_EVENT_HANDLER;
  120. }
  121. void AIGateway::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  122. {
  123. LOG_TRACE(logAi);
  124. NET_EVENT_HANDLER;
  125. }
  126. void AIGateway::artifactAssembled(const ArtifactLocation & al)
  127. {
  128. LOG_TRACE(logAi);
  129. NET_EVENT_HANDLER;
  130. }
  131. void AIGateway::showTavernWindow(const CGObjectInstance * townOrTavern)
  132. {
  133. LOG_TRACE(logAi);
  134. NET_EVENT_HANDLER;
  135. }
  136. void AIGateway::showThievesGuildWindow(const CGObjectInstance * obj)
  137. {
  138. LOG_TRACE(logAi);
  139. NET_EVENT_HANDLER;
  140. }
  141. void AIGateway::playerBlocked(int reason, bool start)
  142. {
  143. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  144. NET_EVENT_HANDLER;
  145. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  146. status.setBattle(UPCOMING_BATTLE);
  147. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  148. status.setMove(start);
  149. }
  150. void AIGateway::showPuzzleMap()
  151. {
  152. LOG_TRACE(logAi);
  153. NET_EVENT_HANDLER;
  154. }
  155. void AIGateway::showShipyardDialog(const IShipyard * obj)
  156. {
  157. LOG_TRACE(logAi);
  158. NET_EVENT_HANDLER;
  159. }
  160. void AIGateway::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  161. {
  162. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf);
  163. NET_EVENT_HANDLER;
  164. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.getStr(), player, player.getStr(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  165. // some whitespace to flush stream
  166. logAi->debug(std::string(200, ' '));
  167. if(player == playerID)
  168. {
  169. if(victoryLossCheckResult.victory())
  170. {
  171. logAi->debug("AIGateway: Player %d (%s) won. I won! Incredible!", player, player.getStr());
  172. logAi->debug("Turn nr %d", myCb->getDate());
  173. }
  174. else
  175. {
  176. logAi->debug("AIGateway: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.getStr());
  177. }
  178. // some whitespace to flush stream
  179. logAi->debug(std::string(200, ' '));
  180. finish();
  181. }
  182. }
  183. void AIGateway::artifactPut(const ArtifactLocation & al)
  184. {
  185. LOG_TRACE(logAi);
  186. NET_EVENT_HANDLER;
  187. }
  188. void AIGateway::artifactRemoved(const ArtifactLocation & al)
  189. {
  190. LOG_TRACE(logAi);
  191. NET_EVENT_HANDLER;
  192. }
  193. void AIGateway::artifactDisassembled(const ArtifactLocation & al)
  194. {
  195. LOG_TRACE(logAi);
  196. NET_EVENT_HANDLER;
  197. }
  198. void AIGateway::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  199. {
  200. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  201. NET_EVENT_HANDLER;
  202. if(start && visitedObj) //we can end visit with null object, anyway
  203. {
  204. nullkiller->memory->markObjectVisited(visitedObj);
  205. }
  206. status.heroVisit(visitedObj, start);
  207. }
  208. void AIGateway::availableArtifactsChanged(const CGBlackMarket * bm)
  209. {
  210. LOG_TRACE(logAi);
  211. NET_EVENT_HANDLER;
  212. }
  213. void AIGateway::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  214. {
  215. LOG_TRACE(logAi);
  216. NET_EVENT_HANDLER;
  217. }
  218. void AIGateway::tileHidden(const std::unordered_set<int3> & pos)
  219. {
  220. LOG_TRACE(logAi);
  221. NET_EVENT_HANDLER;
  222. nullkiller->memory->removeInvisibleObjects(myCb.get());
  223. }
  224. void AIGateway::tileRevealed(const std::unordered_set<int3> & pos)
  225. {
  226. LOG_TRACE(logAi);
  227. NET_EVENT_HANDLER;
  228. for(int3 tile : pos)
  229. {
  230. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  231. addVisitableObj(obj);
  232. }
  233. }
  234. void AIGateway::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  235. {
  236. LOG_TRACE(logAi);
  237. NET_EVENT_HANDLER;
  238. auto firstHero = cb->getHero(hero1);
  239. auto secondHero = cb->getHero(hero2);
  240. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  241. requestActionASAP([=]()
  242. {
  243. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  244. {
  245. this->pickBestCreatures(h1, h2);
  246. this->pickBestArtifacts(h1, h2);
  247. };
  248. //Do not attempt army or artifacts exchange if we visited ally player
  249. //Visits can still be useful if hero have skills like Scholar
  250. if(firstHero->tempOwner != secondHero->tempOwner)
  251. {
  252. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  253. }
  254. else
  255. {
  256. if(nullkiller->isActive(firstHero))
  257. transferFrom2to1(secondHero, firstHero);
  258. else
  259. transferFrom2to1(firstHero, secondHero);
  260. }
  261. answerQuery(query, 0);
  262. });
  263. }
  264. void AIGateway::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  265. {
  266. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  267. NET_EVENT_HANDLER;
  268. }
  269. void AIGateway::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level)
  270. {
  271. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  272. NET_EVENT_HANDLER;
  273. }
  274. void AIGateway::heroMovePointsChanged(const CGHeroInstance * hero)
  275. {
  276. LOG_TRACE(logAi);
  277. NET_EVENT_HANDLER;
  278. }
  279. void AIGateway::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  280. {
  281. LOG_TRACE(logAi);
  282. NET_EVENT_HANDLER;
  283. }
  284. void AIGateway::newObject(const CGObjectInstance * obj)
  285. {
  286. LOG_TRACE(logAi);
  287. NET_EVENT_HANDLER;
  288. if(obj->isVisitable())
  289. addVisitableObj(obj);
  290. }
  291. //to prevent AI from accessing objects that got deleted while they became invisible (Cover of Darkness, enemy hero moved etc.) below code allows AI to know deletion of objects out of sight
  292. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  293. void AIGateway::objectRemoved(const CGObjectInstance * obj)
  294. {
  295. LOG_TRACE(logAi);
  296. NET_EVENT_HANDLER;
  297. if(!nullkiller) // crash protection
  298. return;
  299. nullkiller->memory->removeFromMemory(obj);
  300. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  301. {
  302. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  303. }
  304. if(obj->ID == Obj::HERO && cb->getPlayerRelations(obj->tempOwner, playerID) == PlayerRelations::ENEMIES)
  305. {
  306. nullkiller->dangerHitMap->reset();
  307. }
  308. }
  309. void AIGateway::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  310. {
  311. LOG_TRACE(logAi);
  312. NET_EVENT_HANDLER;
  313. }
  314. void AIGateway::playerBonusChanged(const Bonus & bonus, bool gain)
  315. {
  316. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  317. NET_EVENT_HANDLER;
  318. }
  319. void AIGateway::heroCreated(const CGHeroInstance * h)
  320. {
  321. LOG_TRACE(logAi);
  322. NET_EVENT_HANDLER;
  323. }
  324. void AIGateway::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  325. {
  326. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  327. NET_EVENT_HANDLER;
  328. }
  329. void AIGateway::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  330. {
  331. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  332. NET_EVENT_HANDLER;
  333. }
  334. void AIGateway::requestRealized(PackageApplied * pa)
  335. {
  336. LOG_TRACE(logAi);
  337. NET_EVENT_HANDLER;
  338. if(status.haveTurn())
  339. {
  340. if(pa->packType == typeList.getTypeID<EndTurn>())
  341. {
  342. if(pa->result)
  343. status.madeTurn();
  344. }
  345. }
  346. if(pa->packType == typeList.getTypeID<QueryReply>())
  347. {
  348. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  349. }
  350. }
  351. void AIGateway::receivedResource()
  352. {
  353. LOG_TRACE(logAi);
  354. NET_EVENT_HANDLER;
  355. }
  356. void AIGateway::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor)
  357. {
  358. LOG_TRACE(logAi);
  359. NET_EVENT_HANDLER;
  360. }
  361. void AIGateway::heroManaPointsChanged(const CGHeroInstance * hero)
  362. {
  363. LOG_TRACE(logAi);
  364. NET_EVENT_HANDLER;
  365. }
  366. void AIGateway::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  367. {
  368. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  369. NET_EVENT_HANDLER;
  370. }
  371. void AIGateway::battleResultsApplied()
  372. {
  373. LOG_TRACE(logAi);
  374. NET_EVENT_HANDLER;
  375. assert(status.getBattle() == ENDING_BATTLE);
  376. status.setBattle(NO_BATTLE);
  377. }
  378. void AIGateway::objectPropertyChanged(const SetObjectProperty * sop)
  379. {
  380. LOG_TRACE(logAi);
  381. NET_EVENT_HANDLER;
  382. if(sop->what == ObjProperty::OWNER)
  383. {
  384. auto relations = myCb->getPlayerRelations(playerID, (PlayerColor)sop->val);
  385. auto obj = myCb->getObj(sop->id, false);
  386. if(!nullkiller) // crash protection
  387. return;
  388. if(obj)
  389. {
  390. if(relations == PlayerRelations::ENEMIES)
  391. {
  392. //we want to visit objects owned by oppponents
  393. //addVisitableObj(obj); // TODO: Remove once save compatability broken. In past owned objects were removed from this set
  394. nullkiller->memory->markObjectUnvisited(obj);
  395. }
  396. else if(relations == PlayerRelations::SAME_PLAYER && obj->ID == Obj::TOWN)
  397. {
  398. // reevaluate defence for a new town
  399. nullkiller->dangerHitMap->reset();
  400. }
  401. }
  402. }
  403. }
  404. void AIGateway::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  405. {
  406. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  407. NET_EVENT_HANDLER;
  408. }
  409. void AIGateway::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  410. {
  411. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  412. NET_EVENT_HANDLER;
  413. }
  414. void AIGateway::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor)
  415. {
  416. LOG_TRACE(logAi);
  417. NET_EVENT_HANDLER;
  418. }
  419. void AIGateway::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  420. {
  421. //TODO: AI support for ViewXXX spell
  422. LOG_TRACE(logAi);
  423. NET_EVENT_HANDLER;
  424. }
  425. std::optional<BattleAction> AIGateway::makeSurrenderRetreatDecision(const BattleStateInfoForRetreat & battleState)
  426. {
  427. LOG_TRACE(logAi);
  428. NET_EVENT_HANDLER;
  429. double ourStrength = battleState.getOurStrength();
  430. double fightRatio = ourStrength / (double)battleState.getEnemyStrength();
  431. // if we have no towns - things are already bad, so retreat is not an option.
  432. if(cb->getTownsInfo().size() && ourStrength < RETREAT_ABSOLUTE_THRESHOLD && fightRatio < RETREAT_THRESHOLD && battleState.canFlee)
  433. {
  434. return BattleAction::makeRetreat(battleState.ourSide);
  435. }
  436. return std::nullopt;
  437. }
  438. void AIGateway::initGameInterface(std::shared_ptr<Environment> env, std::shared_ptr<CCallback> CB)
  439. {
  440. LOG_TRACE(logAi);
  441. myCb = CB;
  442. cbc = CB;
  443. NET_EVENT_HANDLER;
  444. playerID = *myCb->getMyColor();
  445. myCb->waitTillRealize = true;
  446. myCb->unlockGsWhenWaiting = true;
  447. nullkiller->init(CB, playerID);
  448. retrieveVisitableObjs();
  449. }
  450. void AIGateway::yourTurn()
  451. {
  452. LOG_TRACE(logAi);
  453. NET_EVENT_HANDLER;
  454. status.startedTurn();
  455. makingTurn = std::make_unique<boost::thread>(&AIGateway::makeTurn, this);
  456. }
  457. void AIGateway::heroGotLevel(const CGHeroInstance * hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  458. {
  459. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  460. NET_EVENT_HANDLER;
  461. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  462. HeroPtr hPtr = hero;
  463. requestActionASAP([=]()
  464. {
  465. if(hPtr.validAndSet())
  466. {
  467. nullkiller->heroManager->update();
  468. answerQuery(queryID, nullkiller->heroManager->selectBestSkill(hPtr, skills));
  469. }
  470. });
  471. }
  472. void AIGateway::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  473. {
  474. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  475. NET_EVENT_HANDLER;
  476. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  477. requestActionASAP([=](){ answerQuery(queryID, 0); });
  478. }
  479. void AIGateway::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel)
  480. {
  481. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  482. NET_EVENT_HANDLER;
  483. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  484. % components.size() % text));
  485. auto hero = nullkiller->getActiveHero();
  486. auto target = nullkiller->getTargetTile();
  487. if(!selection && cancel)
  488. {
  489. requestActionASAP([=]()
  490. {
  491. //yes&no -> always answer yes, we are a brave AI :)
  492. bool answer = true;
  493. auto objects = cb->getVisitableObjs(target);
  494. if(hero.validAndSet() && target.valid() && objects.size())
  495. {
  496. auto topObj = objects.front()->id == hero->id ? objects.back() : objects.front();
  497. auto objType = topObj->ID; // top object should be our hero
  498. auto goalObjectID = nullkiller->getTargetObject();
  499. auto ratio = (float)nullkiller->dangerEvaluator->evaluateDanger(target, hero.get()) / (float)hero->getTotalStrength();
  500. answer = topObj->id == goalObjectID; // no if we do not aim to visit this object
  501. logAi->trace("Query hook: %s(%s) by %s danger ratio %f", target.toString(), topObj->getObjectName(), hero.name, ratio);
  502. if(cb->getObj(goalObjectID, false))
  503. {
  504. logAi->trace("AI expected %s", cb->getObj(goalObjectID, false)->getObjectName());
  505. }
  506. if(objType == Obj::BORDERGUARD || objType == Obj::QUEST_GUARD)
  507. {
  508. answer = true;
  509. }
  510. else if(objType == Obj::ARTIFACT || objType == Obj::RESOURCE)
  511. {
  512. bool dangerUnknown = ratio == 0;
  513. bool dangerTooHigh = ratio > (1 / SAFE_ATTACK_CONSTANT);
  514. answer = !dangerUnknown && !dangerTooHigh;
  515. }
  516. }
  517. answerQuery(askID, answer ? 1 : 0);
  518. });
  519. return;
  520. }
  521. requestActionASAP([=]()
  522. {
  523. int sel = 0;
  524. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  525. sel = components.size();
  526. // TODO: Find better way to understand it is Chest of Treasures
  527. if(hero.validAndSet()
  528. && components.size() == 2
  529. && components.front().id == Component::EComponentType::RESOURCE
  530. && (nullkiller->heroManager->getHeroRole(hero) != HeroRole::MAIN
  531. || nullkiller->buildAnalyzer->getGoldPreasure() > MAX_GOLD_PEASURE))
  532. {
  533. sel = 1; // for now lets pick gold from a chest.
  534. }
  535. answerQuery(askID, sel);
  536. });
  537. }
  538. void AIGateway::showTeleportDialog(TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  539. {
  540. NET_EVENT_HANDLER;
  541. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits") % exits.size()));
  542. int choosenExit = -1;
  543. if(impassable)
  544. {
  545. nullkiller->memory->knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  546. }
  547. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.valid())
  548. {
  549. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  550. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  551. choosenExit = vstd::find_pos(exits, neededExit);
  552. }
  553. for(auto exit : exits)
  554. {
  555. if(status.channelProbing() && exit.first == destinationTeleport)
  556. {
  557. choosenExit = vstd::find_pos(exits, exit);
  558. break;
  559. }
  560. else
  561. {
  562. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  563. // So far this is the best option to handle decision about probing
  564. auto obj = cb->getObj(exit.first, false);
  565. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  566. {
  567. if(exit.first != destinationTeleport)
  568. teleportChannelProbingList.push_back(exit.first);
  569. }
  570. }
  571. }
  572. requestActionASAP([=]()
  573. {
  574. answerQuery(askID, choosenExit);
  575. });
  576. }
  577. void AIGateway::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  578. {
  579. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  580. NET_EVENT_HANDLER;
  581. std::string s1 = up ? up->nodeName() : "NONE";
  582. std::string s2 = down ? down->nodeName() : "NONE";
  583. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  584. //you can't request action from action-response thread
  585. requestActionASAP([=]()
  586. {
  587. if(removableUnits)
  588. pickBestCreatures(down, up);
  589. answerQuery(queryID, 0);
  590. });
  591. }
  592. void AIGateway::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  593. {
  594. NET_EVENT_HANDLER;
  595. status.addQuery(askID, "Map object select query");
  596. requestActionASAP([=](){ answerQuery(askID, selectedObject.getNum()); });
  597. }
  598. void AIGateway::saveGame(BinarySerializer & h, const int version)
  599. {
  600. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  601. NET_EVENT_HANDLER;
  602. nullkiller->memory->removeInvisibleObjects(myCb.get());
  603. CAdventureAI::saveGame(h, version);
  604. serializeInternal(h, version);
  605. }
  606. void AIGateway::loadGame(BinaryDeserializer & h, const int version)
  607. {
  608. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  609. //NET_EVENT_HANDLER;
  610. #if 0
  611. //disabled due to issue 2890
  612. registerGoals(h);
  613. #endif // 0
  614. CAdventureAI::loadGame(h, version);
  615. serializeInternal(h, version);
  616. }
  617. bool AIGateway::makePossibleUpgrades(const CArmedInstance * obj)
  618. {
  619. if(!obj)
  620. return false;
  621. bool upgraded = false;
  622. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  623. {
  624. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  625. {
  626. UpgradeInfo ui;
  627. myCb->fillUpgradeInfo(obj, SlotID(i), ui);
  628. if(ui.oldID >= 0 && nullkiller->getFreeResources().canAfford(ui.cost[0] * s->count))
  629. {
  630. myCb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  631. upgraded = true;
  632. logAi->debug("Upgraded %d %s to %s", s->count, ui.oldID.toCreature()->getNamePluralTranslated(), ui.newID[0].toCreature()->getNamePluralTranslated());
  633. }
  634. }
  635. }
  636. return upgraded;
  637. }
  638. void AIGateway::makeTurn()
  639. {
  640. MAKING_TURN;
  641. auto day = cb->getDate(Date::EDateType::DAY);
  642. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.getStr(), day);
  643. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  644. setThreadName("AIGateway::makeTurn");
  645. if(cb->getDate(Date::DAY_OF_WEEK) == 1)
  646. {
  647. std::vector<const CGObjectInstance *> objs;
  648. retrieveVisitableObjs(objs, true);
  649. for(const CGObjectInstance * obj : objs)
  650. {
  651. if(isWeeklyRevisitable(obj))
  652. {
  653. addVisitableObj(obj);
  654. nullkiller->memory->markObjectUnvisited(obj);
  655. }
  656. }
  657. }
  658. cb->sendMessage("vcmieagles");
  659. if(cb->getDate(Date::DAY) == 1)
  660. {
  661. retrieveVisitableObjs();
  662. }
  663. #if NKAI_TRACE_LEVEL == 0
  664. try
  665. {
  666. #endif
  667. nullkiller->makeTurn();
  668. //for debug purpose
  669. for (auto h : cb->getHeroesInfo())
  670. {
  671. if (h->movement)
  672. logAi->warn("Hero %s has %d MP left", h->getNameTranslated(), h->movement);
  673. }
  674. #if NKAI_TRACE_LEVEL == 0
  675. }
  676. catch (boost::thread_interrupted & e)
  677. {
  678. (void)e;
  679. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  680. return;
  681. }
  682. catch (std::exception & e)
  683. {
  684. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  685. }
  686. #endif
  687. endTurn();
  688. }
  689. void AIGateway::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  690. {
  691. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->pos.toString());
  692. switch(obj->ID)
  693. {
  694. case Obj::CREATURE_GENERATOR1:
  695. recruitCreatures(dynamic_cast<const CGDwelling *>(obj), h.get());
  696. break;
  697. case Obj::TOWN:
  698. if(h->visitedTown) //we are inside, not just attacking
  699. {
  700. makePossibleUpgrades(h.get());
  701. if(!h->visitedTown->garrisonHero || !nullkiller->isHeroLocked(h->visitedTown->garrisonHero))
  702. moveCreaturesToHero(h->visitedTown);
  703. if(nullkiller->heroManager->getHeroRole(h) == HeroRole::MAIN && !h->hasSpellbook()
  704. && nullkiller->getFreeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  705. {
  706. if(h->visitedTown->hasBuilt(BuildingID::MAGES_GUILD_1))
  707. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  708. }
  709. }
  710. break;
  711. case Obj::HILL_FORT:
  712. makePossibleUpgrades(h.get());
  713. break;
  714. }
  715. }
  716. void AIGateway::moveCreaturesToHero(const CGTownInstance * t)
  717. {
  718. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  719. {
  720. pickBestCreatures(t->visitingHero, t->getUpperArmy());
  721. }
  722. }
  723. void AIGateway::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  724. {
  725. const CArmedInstance * armies[] = {destinationArmy, source};
  726. auto bestArmy = nullkiller->armyManager->getBestArmy(destinationArmy, destinationArmy, source);
  727. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  728. for(SlotID i = SlotID(0); i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  729. {
  730. if(i.getNum() >= bestArmy.size())
  731. {
  732. if(destinationArmy->hasStackAtSlot(i))
  733. {
  734. auto creature = destinationArmy->getCreature(i);
  735. auto targetSlot = source->getSlotFor(creature);
  736. if(targetSlot.validSlot())
  737. {
  738. // remove unwanted creatures
  739. cb->mergeOrSwapStacks(destinationArmy, source, i, targetSlot);
  740. }
  741. else if(destinationArmy->getStack(i).getPower() < destinationArmy->getArmyStrength() / 100)
  742. {
  743. // dismiss creatures if the amount is small
  744. cb->dismissCreature(destinationArmy, i);
  745. }
  746. }
  747. continue;
  748. }
  749. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  750. for(auto armyPtr : armies)
  751. {
  752. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  753. {
  754. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  755. {
  756. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  757. if(armyPtr == source
  758. && source->needsLastStack()
  759. && source->stacksCount() == 1
  760. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  761. {
  762. auto weakest = nullkiller->armyManager->getWeakestCreature(bestArmy);
  763. if(weakest->creature == targetCreature)
  764. {
  765. if(1 == source->getStackCount(j))
  766. break;
  767. // move all except 1 of weakest creature from source to destination
  768. cb->splitStack(
  769. source,
  770. destinationArmy,
  771. j,
  772. destinationArmy->getSlotFor(targetCreature),
  773. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  774. break;
  775. }
  776. else
  777. {
  778. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  779. cb->splitStack(
  780. destinationArmy,
  781. source,
  782. destinationArmy->getSlotFor(weakest->creature),
  783. source->getFreeSlot(),
  784. 1);
  785. }
  786. }
  787. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  788. }
  789. }
  790. }
  791. }
  792. //TODO - having now strongest possible army, we may want to think about arranging stacks
  793. }
  794. void AIGateway::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  795. {
  796. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  797. {
  798. bool changeMade = false;
  799. do
  800. {
  801. changeMade = false;
  802. //we collect gear always in same order
  803. std::vector<ArtifactLocation> allArtifacts;
  804. if(giveStuffToFirstHero)
  805. {
  806. for(auto p : h->artifactsWorn)
  807. {
  808. if(p.second.artifact)
  809. allArtifacts.push_back(ArtifactLocation(h, p.first));
  810. }
  811. }
  812. for(auto slot : h->artifactsInBackpack)
  813. allArtifacts.push_back(ArtifactLocation(h, h->getArtPos(slot.artifact)));
  814. if(otherh)
  815. {
  816. for(auto p : otherh->artifactsWorn)
  817. {
  818. if(p.second.artifact)
  819. allArtifacts.push_back(ArtifactLocation(otherh, p.first));
  820. }
  821. for(auto slot : otherh->artifactsInBackpack)
  822. allArtifacts.push_back(ArtifactLocation(otherh, otherh->getArtPos(slot.artifact)));
  823. }
  824. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  825. const CGHeroInstance * target = nullptr;
  826. if(giveStuffToFirstHero || !otherh)
  827. target = h;
  828. else
  829. target = otherh;
  830. for(auto location : allArtifacts)
  831. {
  832. if(location.relatedObj() == target && location.slot < ArtifactPosition::AFTER_LAST)
  833. continue; //don't reequip artifact we already wear
  834. if(location.slot == ArtifactPosition::MACH4) // don't attempt to move catapult
  835. continue;
  836. auto s = location.getSlot();
  837. if(!s || s->locked) //we can't move locks
  838. continue;
  839. auto artifact = s->artifact;
  840. if(!artifact)
  841. continue;
  842. //FIXME: why are the above possible to be null?
  843. bool emptySlotFound = false;
  844. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  845. {
  846. ArtifactLocation destLocation(target, slot);
  847. if(target->isPositionFree(slot) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  848. {
  849. cb->swapArtifacts(location, destLocation); //just put into empty slot
  850. emptySlotFound = true;
  851. changeMade = true;
  852. break;
  853. }
  854. }
  855. if(!emptySlotFound) //try to put that atifact in already occupied slot
  856. {
  857. for(auto slot : artifact->artType->possibleSlots.at(target->bearerType()))
  858. {
  859. auto otherSlot = target->getSlot(slot);
  860. if(otherSlot && otherSlot->artifact) //we need to exchange artifact for better one
  861. {
  862. ArtifactLocation destLocation(target, slot);
  863. //if that artifact is better than what we have, pick it
  864. if(compareArtifacts(artifact, otherSlot->artifact) && artifact->canBePutAt(destLocation, true)) //combined artifacts are not always allowed to move
  865. {
  866. cb->swapArtifacts(location, ArtifactLocation(target, target->getArtPos(otherSlot->artifact)));
  867. changeMade = true;
  868. break;
  869. }
  870. }
  871. }
  872. }
  873. if(changeMade)
  874. break; //start evaluating artifacts from scratch
  875. }
  876. }
  877. while(changeMade);
  878. };
  879. equipBest(h, other, true);
  880. if(other)
  881. equipBest(h, other, false);
  882. }
  883. void AIGateway::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  884. {
  885. //now used only for visited dwellings / towns, not BuyArmy goal
  886. for(int i = 0; i < d->creatures.size(); i++)
  887. {
  888. if(!d->creatures[i].second.size())
  889. continue;
  890. int count = d->creatures[i].first;
  891. CreatureID creID = d->creatures[i].second.back();
  892. vstd::amin(count, cb->getResourceAmount() / creID.toCreature()->getFullRecruitCost());
  893. if(count > 0)
  894. cb->recruitCreatures(d, recruiter, creID, count, i);
  895. }
  896. }
  897. void AIGateway::battleStart(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool side)
  898. {
  899. NET_EVENT_HANDLER;
  900. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  901. status.setBattle(ONGOING_BATTLE);
  902. const CGObjectInstance * presumedEnemy = vstd::backOrNull(cb->getVisitableObjs(tile)); //may be nullptr in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  903. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->getNameTranslated() : "a army") % (presumedEnemy ? presumedEnemy->getObjectName() : "unknown enemy") % tile.toString());
  904. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  905. }
  906. void AIGateway::battleEnd(const BattleResult * br, QueryID queryID)
  907. {
  908. NET_EVENT_HANDLER;
  909. assert(status.getBattle() == ONGOING_BATTLE);
  910. status.setBattle(ENDING_BATTLE);
  911. bool won = br->winner == myCb->battleGetMySide();
  912. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.getStr(), (won ? "won" : "lost"), battlename);
  913. battlename.clear();
  914. status.addQuery(queryID, "Combat result dialog");
  915. const int confirmAction = 0;
  916. requestActionASAP([=]()
  917. {
  918. answerQuery(queryID, confirmAction);
  919. });
  920. CAdventureAI::battleEnd(br, queryID);
  921. }
  922. void AIGateway::waitTillFree()
  923. {
  924. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  925. status.waitTillFree();
  926. }
  927. void AIGateway::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  928. {
  929. foreach_tile_pos([&](const int3 & pos)
  930. {
  931. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  932. {
  933. if(includeOwned || obj->tempOwner != playerID)
  934. out.push_back(obj);
  935. }
  936. });
  937. }
  938. void AIGateway::retrieveVisitableObjs()
  939. {
  940. foreach_tile_pos([&](const int3 & pos)
  941. {
  942. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  943. {
  944. if(obj->tempOwner != playerID)
  945. addVisitableObj(obj);
  946. }
  947. });
  948. }
  949. std::vector<const CGObjectInstance *> AIGateway::getFlaggedObjects() const
  950. {
  951. std::vector<const CGObjectInstance *> ret;
  952. for(const CGObjectInstance * obj : nullkiller->memory->visitableObjs)
  953. {
  954. if(obj->tempOwner == playerID)
  955. ret.push_back(obj);
  956. }
  957. return ret;
  958. }
  959. void AIGateway::addVisitableObj(const CGObjectInstance * obj)
  960. {
  961. if(obj->ID == Obj::EVENT)
  962. return;
  963. nullkiller->memory->addVisitableObject(obj);
  964. if(obj->ID == Obj::HERO && cb->getPlayerRelations(obj->tempOwner, playerID) == PlayerRelations::ENEMIES)
  965. {
  966. nullkiller->dangerHitMap->reset();
  967. }
  968. }
  969. bool AIGateway::moveHeroToTile(int3 dst, HeroPtr h)
  970. {
  971. if(h->inTownGarrison && h->visitedTown)
  972. {
  973. cb->swapGarrisonHero(h->visitedTown);
  974. moveCreaturesToHero(h->visitedTown);
  975. }
  976. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  977. auto afterMovementCheck = [&]() -> void
  978. {
  979. waitTillFree(); //movement may cause battle or blocking dialog
  980. if(!h)
  981. {
  982. lostHero(h);
  983. teleportChannelProbingList.clear();
  984. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  985. status.setChannelProbing(false);
  986. throw cannotFulfillGoalException("Hero was lost!");
  987. }
  988. };
  989. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  990. int3 startHpos = h->visitablePos();
  991. bool ret = false;
  992. if(startHpos == dst)
  993. {
  994. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  995. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  996. cb->moveHero(*h, h->convertFromVisitablePos(dst));
  997. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  998. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  999. teleportChannelProbingList.clear();
  1000. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1001. ret = true;
  1002. }
  1003. else
  1004. {
  1005. CGPath path;
  1006. cb->getPathsInfo(h.get())->getPath(path, dst);
  1007. if(path.nodes.empty())
  1008. {
  1009. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1010. return true;
  1011. }
  1012. int i = (int)path.nodes.size() - 1;
  1013. auto getObj = [&](int3 coord, bool ignoreHero)
  1014. {
  1015. auto tile = cb->getTile(coord, false);
  1016. assert(tile);
  1017. return tile->topVisitableObj(ignoreHero);
  1018. //return cb->getTile(coord,false)->topVisitableObj(ignoreHero);
  1019. };
  1020. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1021. {
  1022. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1023. {
  1024. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1025. {
  1026. return false;
  1027. }
  1028. }
  1029. return true;
  1030. };
  1031. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1032. {
  1033. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1034. return nextObjectTop;
  1035. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1036. {
  1037. if(CGTeleport::isConnected(currentObject, nextObject))
  1038. return nextObject;
  1039. }
  1040. return nullptr;
  1041. };
  1042. auto doMovement = [&](int3 dst, bool transit)
  1043. {
  1044. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1045. };
  1046. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1047. {
  1048. destinationTeleport = exitId;
  1049. if(exitPos.valid())
  1050. destinationTeleportPos = h->convertFromVisitablePos(exitPos);
  1051. cb->moveHero(*h, h->pos);
  1052. destinationTeleport = ObjectInstanceID();
  1053. destinationTeleportPos = int3(-1);
  1054. afterMovementCheck();
  1055. };
  1056. auto doChannelProbing = [&]() -> void
  1057. {
  1058. auto currentPos = h->visitablePos();
  1059. auto currentExit = getObj(currentPos, true)->id;
  1060. status.setChannelProbing(true);
  1061. for(auto exit : teleportChannelProbingList)
  1062. doTeleportMovement(exit, int3(-1));
  1063. teleportChannelProbingList.clear();
  1064. status.setChannelProbing(false);
  1065. doTeleportMovement(currentExit, currentPos);
  1066. };
  1067. for(; i > 0; i--)
  1068. {
  1069. int3 currentCoord = path.nodes[i].coord;
  1070. int3 nextCoord = path.nodes[i - 1].coord;
  1071. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1072. auto nextObjectTop = getObj(nextCoord, false);
  1073. auto nextObject = getObj(nextCoord, true);
  1074. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1075. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1076. {
  1077. //we use special login if hero standing on teleporter it's mean we need
  1078. doTeleportMovement(destTeleportObj->id, nextCoord);
  1079. if(teleportChannelProbingList.size())
  1080. doChannelProbing();
  1081. nullkiller->memory->markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1082. continue;
  1083. }
  1084. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1085. if(path.nodes[i - 1].turns)
  1086. {
  1087. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1088. return false;
  1089. }
  1090. int3 endpos = path.nodes[i - 1].coord;
  1091. if(endpos == h->visitablePos())
  1092. continue;
  1093. bool isConnected = false;
  1094. bool isNextObjectTeleport = false;
  1095. // Check there is node after next one; otherwise transit is pointless
  1096. if(i - 2 >= 0)
  1097. {
  1098. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1099. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1100. }
  1101. if(isConnected || isNextObjectTeleport)
  1102. {
  1103. // Hero should be able to go through object if it's allow transit
  1104. doMovement(endpos, true);
  1105. }
  1106. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1107. {
  1108. doMovement(endpos, true);
  1109. }
  1110. else
  1111. {
  1112. doMovement(endpos, false);
  1113. }
  1114. afterMovementCheck();
  1115. if(teleportChannelProbingList.size())
  1116. doChannelProbing();
  1117. }
  1118. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT || path.nodes[0].action == EPathNodeAction::BATTLE)
  1119. {
  1120. // when we take resource we do not reach its position. We even might not move
  1121. // also guarded town is not get visited automatically after capturing
  1122. ret = h && i == 0;
  1123. }
  1124. }
  1125. if(h)
  1126. {
  1127. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1128. {
  1129. if(visitedObject != *h)
  1130. {
  1131. performObjectInteraction(visitedObject, h);
  1132. ret = true;
  1133. }
  1134. }
  1135. }
  1136. if(h) //we could have lost hero after last move
  1137. {
  1138. ret = ret || (dst == h->visitablePos());
  1139. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1140. {
  1141. throw cannotFulfillGoalException("Invalid path found!");
  1142. }
  1143. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1144. }
  1145. return ret;
  1146. }
  1147. void AIGateway::buildStructure(const CGTownInstance * t, BuildingID building)
  1148. {
  1149. auto name = t->town->buildings.at(building)->getNameTranslated();
  1150. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->pos.toString());
  1151. cb->buildBuilding(t, building); //just do this;
  1152. }
  1153. void AIGateway::tryRealize(Goals::DigAtTile & g)
  1154. {
  1155. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1156. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1157. {
  1158. cb->dig(g.hero.get());
  1159. }
  1160. else
  1161. {
  1162. throw cannotFulfillGoalException("A hero can't dig!\n");
  1163. }
  1164. }
  1165. void AIGateway::tryRealize(Goals::Trade & g) //trade
  1166. {
  1167. if(cb->getResourceAmount(GameResID(g.resID)) >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1168. throw goalFulfilledException(sptr(g));
  1169. int accquiredResources = 0;
  1170. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1171. {
  1172. if(const IMarket * m = IMarket::castFrom(obj, false))
  1173. {
  1174. auto freeRes = cb->getResourceAmount(); //trade only resources which are not reserved
  1175. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1176. {
  1177. auto res = it->resType;
  1178. if(res.getNum() == g.resID) //sell any other resource
  1179. continue;
  1180. int toGive, toGet;
  1181. m->getOffer(res, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1182. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1183. //TODO trade only as much as needed
  1184. if (toGive) //don't try to sell 0 resources
  1185. {
  1186. cb->trade(m, EMarketMode::RESOURCE_RESOURCE, res, g.resID, toGive);
  1187. accquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1188. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, accquiredResources, g.resID, obj->getObjectName());
  1189. }
  1190. if (cb->getResourceAmount(GameResID(g.resID)))
  1191. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1192. }
  1193. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1194. }
  1195. else
  1196. {
  1197. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1198. }
  1199. }
  1200. else
  1201. {
  1202. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1203. }
  1204. }
  1205. void AIGateway::endTurn()
  1206. {
  1207. logAi->info("Player %d (%s) ends turn", playerID, playerID.getStr());
  1208. if(!status.haveTurn())
  1209. {
  1210. logAi->error("Not having turn at the end of turn???");
  1211. }
  1212. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1213. if(cb->getPlayerStatus(playerID) != EPlayerStatus::INGAME)
  1214. {
  1215. logAi->info("Ending turn is not needed because we already lost");
  1216. return;
  1217. }
  1218. do
  1219. {
  1220. cb->endTurn();
  1221. }
  1222. while(status.haveTurn()); //for some reasons, our request may fail -> stop requesting end of turn only after we've received a confirmation that it's over
  1223. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.getStr());
  1224. }
  1225. void AIGateway::buildArmyIn(const CGTownInstance * t)
  1226. {
  1227. makePossibleUpgrades(t->visitingHero);
  1228. makePossibleUpgrades(t);
  1229. recruitCreatures(t, t->getUpperArmy());
  1230. moveCreaturesToHero(t);
  1231. }
  1232. void AIGateway::finish()
  1233. {
  1234. //we want to lock to avoid multiple threads from calling makingTurn->join() at same time
  1235. boost::lock_guard<boost::mutex> multipleCleanupGuard(turnInterruptionMutex);
  1236. if(makingTurn)
  1237. {
  1238. makingTurn->interrupt();
  1239. makingTurn->join();
  1240. makingTurn.reset();
  1241. }
  1242. }
  1243. void AIGateway::requestActionASAP(std::function<void()> whatToDo)
  1244. {
  1245. boost::thread newThread([this, whatToDo]()
  1246. {
  1247. setThreadName("AIGateway::requestActionASAP::whatToDo");
  1248. SET_GLOBAL_STATE(this);
  1249. boost::shared_lock<boost::shared_mutex> gsLock(CGameState::mutex);
  1250. whatToDo();
  1251. });
  1252. }
  1253. void AIGateway::lostHero(HeroPtr h)
  1254. {
  1255. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  1256. }
  1257. void AIGateway::answerQuery(QueryID queryID, int selection)
  1258. {
  1259. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  1260. if(queryID != QueryID(-1))
  1261. {
  1262. cb->selectionMade(selection, queryID);
  1263. }
  1264. else
  1265. {
  1266. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  1267. //do nothing
  1268. }
  1269. }
  1270. void AIGateway::requestSent(const CPackForServer * pack, int requestID)
  1271. {
  1272. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  1273. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  1274. {
  1275. status.attemptedAnsweringQuery(reply->qid, requestID);
  1276. }
  1277. }
  1278. std::string AIGateway::getBattleAIName() const
  1279. {
  1280. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  1281. return settings["server"]["enemyAI"].String();
  1282. else
  1283. return "BattleAI";
  1284. }
  1285. void AIGateway::validateObject(const CGObjectInstance * obj)
  1286. {
  1287. validateObject(obj->id);
  1288. }
  1289. void AIGateway::validateObject(ObjectIdRef obj)
  1290. {
  1291. if(!obj)
  1292. {
  1293. nullkiller->memory->removeFromMemory(obj);
  1294. }
  1295. }
  1296. AIStatus::AIStatus()
  1297. {
  1298. battle = NO_BATTLE;
  1299. havingTurn = false;
  1300. ongoingHeroMovement = false;
  1301. ongoingChannelProbing = false;
  1302. }
  1303. AIStatus::~AIStatus()
  1304. {
  1305. }
  1306. void AIStatus::setBattle(BattleState BS)
  1307. {
  1308. boost::unique_lock<boost::mutex> lock(mx);
  1309. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  1310. battle = BS;
  1311. cv.notify_all();
  1312. }
  1313. BattleState AIStatus::getBattle()
  1314. {
  1315. boost::unique_lock<boost::mutex> lock(mx);
  1316. return battle;
  1317. }
  1318. void AIStatus::addQuery(QueryID ID, std::string description)
  1319. {
  1320. if(ID == QueryID(-1))
  1321. {
  1322. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  1323. return;
  1324. }
  1325. assert(ID.getNum() >= 0);
  1326. boost::unique_lock<boost::mutex> lock(mx);
  1327. assert(!vstd::contains(remainingQueries, ID));
  1328. remainingQueries[ID] = description;
  1329. cv.notify_all();
  1330. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1331. }
  1332. void AIStatus::removeQuery(QueryID ID)
  1333. {
  1334. boost::unique_lock<boost::mutex> lock(mx);
  1335. assert(vstd::contains(remainingQueries, ID));
  1336. std::string description = remainingQueries[ID];
  1337. remainingQueries.erase(ID);
  1338. cv.notify_all();
  1339. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  1340. }
  1341. int AIStatus::getQueriesCount()
  1342. {
  1343. boost::unique_lock<boost::mutex> lock(mx);
  1344. return static_cast<int>(remainingQueries.size());
  1345. }
  1346. void AIStatus::startedTurn()
  1347. {
  1348. boost::unique_lock<boost::mutex> lock(mx);
  1349. havingTurn = true;
  1350. cv.notify_all();
  1351. }
  1352. void AIStatus::madeTurn()
  1353. {
  1354. boost::unique_lock<boost::mutex> lock(mx);
  1355. havingTurn = false;
  1356. cv.notify_all();
  1357. }
  1358. void AIStatus::waitTillFree()
  1359. {
  1360. boost::unique_lock<boost::mutex> lock(mx);
  1361. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  1362. cv.timed_wait(lock, boost::posix_time::milliseconds(10));
  1363. }
  1364. bool AIStatus::haveTurn()
  1365. {
  1366. boost::unique_lock<boost::mutex> lock(mx);
  1367. return havingTurn;
  1368. }
  1369. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  1370. {
  1371. boost::unique_lock<boost::mutex> lock(mx);
  1372. assert(vstd::contains(remainingQueries, queryID));
  1373. std::string description = remainingQueries[queryID];
  1374. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  1375. requestToQueryID[answerRequestID] = queryID;
  1376. }
  1377. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  1378. {
  1379. assert(vstd::contains(requestToQueryID, answerRequestID));
  1380. QueryID query = requestToQueryID[answerRequestID];
  1381. assert(vstd::contains(remainingQueries, query));
  1382. requestToQueryID.erase(answerRequestID);
  1383. if(result)
  1384. {
  1385. removeQuery(query);
  1386. }
  1387. else
  1388. {
  1389. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  1390. //TODO safely retry
  1391. }
  1392. }
  1393. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  1394. {
  1395. boost::unique_lock<boost::mutex> lock(mx);
  1396. if(started)
  1397. {
  1398. objectsBeingVisited.push_back(obj);
  1399. }
  1400. else
  1401. {
  1402. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  1403. // causing visit to hero on the other side.
  1404. // However, we are guaranteed that start/end visit notification maintain stack order.
  1405. assert(!objectsBeingVisited.empty());
  1406. objectsBeingVisited.pop_back();
  1407. }
  1408. cv.notify_all();
  1409. }
  1410. void AIStatus::setMove(bool ongoing)
  1411. {
  1412. boost::unique_lock<boost::mutex> lock(mx);
  1413. ongoingHeroMovement = ongoing;
  1414. cv.notify_all();
  1415. }
  1416. void AIStatus::setChannelProbing(bool ongoing)
  1417. {
  1418. boost::unique_lock<boost::mutex> lock(mx);
  1419. ongoingChannelProbing = ongoing;
  1420. cv.notify_all();
  1421. }
  1422. bool AIStatus::channelProbing()
  1423. {
  1424. return ongoingChannelProbing;
  1425. }
  1426. }