AIGateway.cpp 47 KB

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