VCAI.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919
  1. /*
  2. * VCAI.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 "VCAI.h"
  12. #include "FuzzyHelper.h"
  13. #include "ResourceManager.h"
  14. #include "BuildingManager.h"
  15. #include "Goals/Goals.h"
  16. #include "Goals/CompleteQuest.h"
  17. #include "../../lib/AsyncRunner.h"
  18. #include "../../lib/CThreadHelper.h"
  19. #include "../../lib/UnlockGuard.h"
  20. #include "../../lib/StartInfo.h"
  21. #include "../../lib/battle/CPlayerBattleCallback.h"
  22. #include "../../lib/mapObjects/MapObjects.h"
  23. #include "../../lib/mapObjects/ObjectTemplate.h"
  24. #include "../../lib/CConfigHandler.h"
  25. #include "../../lib/IGameSettings.h"
  26. #include "../../lib/gameState/CGameState.h"
  27. #include "../../lib/gameState/UpgradeInfo.h"
  28. #include "../../lib/bonuses/Limiters.h"
  29. #include "../../lib/bonuses/Updaters.h"
  30. #include "../../lib/bonuses/Propagators.h"
  31. #include "../../lib/entities/artifact/ArtifactUtils.h"
  32. #include "../../lib/entities/artifact/CArtifact.h"
  33. #include "../../lib/entities/building/CBuilding.h"
  34. #include "../../lib/mapObjects/CQuest.h"
  35. #include "../../lib/networkPacks/PacksForClient.h"
  36. #include "../../lib/networkPacks/PacksForClientBattle.h"
  37. #include "../../lib/networkPacks/PacksForServer.h"
  38. #include "../../lib/serializer/CTypeList.h"
  39. #include "../../lib/pathfinder/PathfinderCache.h"
  40. #include "../../lib/pathfinder/PathfinderOptions.h"
  41. #include "AIhelper.h"
  42. extern FuzzyHelper * fh;
  43. const double SAFE_ATTACK_CONSTANT = 1.5;
  44. //one thread may be turn of AI and another will be handling a side effect for AI2
  45. thread_local CCallback * cb = nullptr;
  46. thread_local VCAI * ai = nullptr;
  47. //std::map<int, std::map<int, int> > HeroView::infosCount;
  48. //helper RAII to manage global ai/cb ptrs
  49. struct SetGlobalState
  50. {
  51. SetGlobalState(VCAI * AI)
  52. {
  53. assert(!ai);
  54. assert(!cb);
  55. ai = AI;
  56. cb = AI->myCb.get();
  57. }
  58. ~SetGlobalState()
  59. {
  60. //TODO: how to handle rm? shouldn't be called after ai is destroyed, hopefully
  61. //TODO: to ensure that, make rm unique_ptr
  62. ai = nullptr;
  63. cb = nullptr;
  64. }
  65. };
  66. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai)
  67. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  68. #define MAKING_TURN SET_GLOBAL_STATE(this)
  69. VCAI::VCAI()
  70. {
  71. LOG_TRACE(logAi);
  72. asyncTasks = std::make_unique<AsyncRunner>();
  73. destinationTeleport = ObjectInstanceID();
  74. destinationTeleportPos = int3(-1);
  75. ah = new AIhelper();
  76. ah->setAI(this);
  77. }
  78. VCAI::~VCAI()
  79. {
  80. delete ah;
  81. LOG_TRACE(logAi);
  82. finish();
  83. }
  84. void VCAI::availableCreaturesChanged(const CGDwelling * town)
  85. {
  86. LOG_TRACE(logAi);
  87. NET_EVENT_HANDLER;
  88. }
  89. void VCAI::heroMoved(const TryMoveHero & details, bool verbose)
  90. {
  91. LOG_TRACE(logAi);
  92. NET_EVENT_HANDLER;
  93. //enemy hero may have left visible area
  94. validateObject(details.id);
  95. auto hero = cb->getHero(details.id);
  96. const int3 from = hero ? hero->convertToVisitablePos(details.start) : (details.start - int3(0,1,0));
  97. const int3 to = hero ? hero->convertToVisitablePos(details.end) : (details.end - int3(0,1,0));
  98. const CGObjectInstance * o1 = vstd::frontOrNull(cb->getVisitableObjs(from, verbose));
  99. const CGObjectInstance * o2 = vstd::frontOrNull(cb->getVisitableObjs(to, verbose));
  100. if(details.result == TryMoveHero::TELEPORTATION)
  101. {
  102. auto t1 = dynamic_cast<const CGTeleport *>(o1);
  103. auto t2 = dynamic_cast<const CGTeleport *>(o2);
  104. if(t1 && t2)
  105. {
  106. if(cb->isTeleportChannelBidirectional(t1->channel))
  107. {
  108. 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
  109. {
  110. knownSubterraneanGates[o1] = o2;
  111. knownSubterraneanGates[o2] = o1;
  112. logAi->debug("Found a pair of subterranean gates between %s and %s!", from.toString(), to.toString());
  113. }
  114. }
  115. }
  116. //FIXME: teleports are not correctly visited
  117. unreserveObject(hero, t1);
  118. unreserveObject(hero, t2);
  119. }
  120. else if(details.result == TryMoveHero::EMBARK && hero)
  121. {
  122. //make sure AI not attempt to visit used boat
  123. validateObject(hero->getBoat());
  124. }
  125. else if(details.result == TryMoveHero::DISEMBARK && o1)
  126. {
  127. auto boat = dynamic_cast<const CGBoat *>(o1);
  128. if(boat)
  129. addVisitableObj(boat);
  130. }
  131. }
  132. void VCAI::heroInGarrisonChange(const CGTownInstance * town)
  133. {
  134. LOG_TRACE(logAi);
  135. NET_EVENT_HANDLER;
  136. }
  137. void VCAI::centerView(int3 pos, int focusTime)
  138. {
  139. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  140. NET_EVENT_HANDLER;
  141. }
  142. void VCAI::artifactMoved(const ArtifactLocation & src, const ArtifactLocation & dst)
  143. {
  144. LOG_TRACE(logAi);
  145. NET_EVENT_HANDLER;
  146. }
  147. void VCAI::artifactAssembled(const ArtifactLocation & al)
  148. {
  149. LOG_TRACE(logAi);
  150. NET_EVENT_HANDLER;
  151. }
  152. void VCAI::showTavernWindow(const CGObjectInstance * object, const CGHeroInstance * visitor, QueryID queryID)
  153. {
  154. LOG_TRACE(logAi);
  155. NET_EVENT_HANDLER;
  156. status.addQuery(queryID, "TavernWindow");
  157. executeActionAsync("showTavernWindow", [this, queryID](){ answerQuery(queryID, 0); });
  158. }
  159. void VCAI::showThievesGuildWindow(const CGObjectInstance * obj)
  160. {
  161. LOG_TRACE(logAi);
  162. NET_EVENT_HANDLER;
  163. }
  164. void VCAI::playerBlocked(int reason, bool start)
  165. {
  166. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  167. NET_EVENT_HANDLER;
  168. if(start && reason == PlayerBlocked::UPCOMING_BATTLE)
  169. status.setBattle(UPCOMING_BATTLE);
  170. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  171. status.setMove(start);
  172. }
  173. void VCAI::showPuzzleMap()
  174. {
  175. LOG_TRACE(logAi);
  176. NET_EVENT_HANDLER;
  177. }
  178. void VCAI::showShipyardDialog(const IShipyard * obj)
  179. {
  180. LOG_TRACE(logAi);
  181. NET_EVENT_HANDLER;
  182. }
  183. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  184. {
  185. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult.messageToSelf.toString());
  186. NET_EVENT_HANDLER;
  187. logAi->debug("Player %d (%s): I heard that player %d (%s) %s.", playerID, playerID.toString(), player, player.toString(), (victoryLossCheckResult.victory() ? "won" : "lost"));
  188. if(player == playerID)
  189. {
  190. if(victoryLossCheckResult.victory())
  191. {
  192. logAi->debug("VCAI: I won! Incredible!");
  193. logAi->debug("Turn nr %d", myCb->getDate());
  194. }
  195. else
  196. {
  197. logAi->debug("VCAI: Player %d (%s) lost. It's me. What a disappointment! :(", player, player.toString());
  198. }
  199. makingTurnInterrupption.interruptThread();
  200. }
  201. }
  202. void VCAI::artifactPut(const ArtifactLocation & al)
  203. {
  204. LOG_TRACE(logAi);
  205. NET_EVENT_HANDLER;
  206. }
  207. void VCAI::artifactRemoved(const ArtifactLocation & al)
  208. {
  209. LOG_TRACE(logAi);
  210. NET_EVENT_HANDLER;
  211. }
  212. void VCAI::artifactDisassembled(const ArtifactLocation & al)
  213. {
  214. LOG_TRACE(logAi);
  215. NET_EVENT_HANDLER;
  216. }
  217. void VCAI::heroVisit(const CGHeroInstance * visitor, const CGObjectInstance * visitedObj, bool start)
  218. {
  219. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->getObjectName() : std::string("n/a")));
  220. NET_EVENT_HANDLER;
  221. if(start && visitedObj) //we can end visit with null object, anyway
  222. {
  223. markObjectVisited(visitedObj);
  224. unreserveObject(visitor, visitedObj);
  225. completeGoal(sptr(Goals::VisitObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  226. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  227. if (visitedObj->ID == Obj::HERO)
  228. {
  229. visitedHeroes[visitor].insert(HeroPtr(dynamic_cast<const CGHeroInstance *>(visitedObj)));
  230. }
  231. }
  232. status.heroVisit(visitedObj, start);
  233. }
  234. void VCAI::availableArtifactsChanged(const CGBlackMarket * bm)
  235. {
  236. LOG_TRACE(logAi);
  237. NET_EVENT_HANDLER;
  238. }
  239. void VCAI::heroVisitsTown(const CGHeroInstance * hero, const CGTownInstance * town)
  240. {
  241. LOG_TRACE(logAi);
  242. NET_EVENT_HANDLER;
  243. //buildArmyIn(town);
  244. //moveCreaturesToHero(town);
  245. }
  246. void VCAI::tileHidden(const std::unordered_set<int3> & pos)
  247. {
  248. LOG_TRACE(logAi);
  249. NET_EVENT_HANDLER;
  250. validateVisitableObjs();
  251. clearPathsInfo();
  252. }
  253. void VCAI::tileRevealed(const std::unordered_set<int3> & pos)
  254. {
  255. LOG_TRACE(logAi);
  256. NET_EVENT_HANDLER;
  257. for(int3 tile : pos)
  258. {
  259. for(const CGObjectInstance * obj : myCb->getVisitableObjs(tile))
  260. addVisitableObj(obj);
  261. }
  262. clearPathsInfo();
  263. }
  264. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  265. {
  266. LOG_TRACE(logAi);
  267. NET_EVENT_HANDLER;
  268. auto firstHero = cb->getHero(hero1);
  269. auto secondHero = cb->getHero(hero2);
  270. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s (%d) and %s (%d)") % firstHero->getNameTranslated() % firstHero->tempOwner % secondHero->getNameTranslated() % secondHero->tempOwner));
  271. executeActionAsync("heroExchangeStarted", [this, firstHero, secondHero, query]()
  272. {
  273. float goalpriority1 = 0;
  274. float goalpriority2 = 0;
  275. auto firstGoal = getGoal(firstHero);
  276. if(firstGoal->goalType == Goals::GATHER_ARMY)
  277. goalpriority1 = firstGoal->priority;
  278. auto secondGoal = getGoal(secondHero);
  279. if(secondGoal->goalType == Goals::GATHER_ARMY)
  280. goalpriority2 = secondGoal->priority;
  281. auto transferFrom2to1 = [this](const CGHeroInstance * h1, const CGHeroInstance * h2) -> void
  282. {
  283. this->pickBestCreatures(h1, h2);
  284. this->pickBestArtifacts(h1, h2);
  285. };
  286. //Do not attempt army or artifacts exchange if we visited ally player
  287. //Visits can still be useful if hero have skills like Scholar
  288. if(firstHero->tempOwner != secondHero->tempOwner)
  289. {
  290. logAi->debug("Heroes owned by different players. Do not exchange army or artifacts.");
  291. }
  292. else if(goalpriority1 > goalpriority2)
  293. {
  294. transferFrom2to1(firstHero, secondHero);
  295. }
  296. else if(goalpriority1 < goalpriority2)
  297. {
  298. transferFrom2to1(secondHero, firstHero);
  299. }
  300. else //regular criteria
  301. {
  302. if(firstHero->getFightingStrength() > secondHero->getFightingStrength() && ah->canGetArmy(firstHero, secondHero))
  303. transferFrom2to1(firstHero, secondHero);
  304. else if(ah->canGetArmy(secondHero, firstHero))
  305. transferFrom2to1(secondHero, firstHero);
  306. }
  307. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  308. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  309. answerQuery(query, 0);
  310. });
  311. }
  312. void VCAI::heroExperienceChanged(const CGHeroInstance * hero, si64 val)
  313. {
  314. LOG_TRACE_PARAMS(logAi, "val '%i'", val);
  315. NET_EVENT_HANDLER;
  316. }
  317. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, PrimarySkill which, si64 val)
  318. {
  319. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which.getNum() % val);
  320. NET_EVENT_HANDLER;
  321. }
  322. void VCAI::showRecruitmentDialog(const CGDwelling * dwelling, const CArmedInstance * dst, int level, QueryID queryID)
  323. {
  324. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  325. NET_EVENT_HANDLER;
  326. status.addQuery(queryID, "RecruitmentDialog");
  327. executeActionAsync("showRecruitmentDialog", [this, dwelling, dst, queryID](){
  328. recruitCreatures(dwelling, dst);
  329. checkHeroArmy(dynamic_cast<const CGHeroInstance*>(dst));
  330. answerQuery(queryID, 0);
  331. });
  332. }
  333. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  334. {
  335. LOG_TRACE(logAi);
  336. NET_EVENT_HANDLER;
  337. }
  338. void VCAI::garrisonsChanged(ObjectInstanceID id1, ObjectInstanceID id2)
  339. {
  340. LOG_TRACE(logAi);
  341. NET_EVENT_HANDLER;
  342. }
  343. void VCAI::newObject(const CGObjectInstance * obj)
  344. {
  345. LOG_TRACE(logAi);
  346. NET_EVENT_HANDLER;
  347. if(obj->isVisitable())
  348. addVisitableObj(obj);
  349. }
  350. //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
  351. //see: RemoveObject::applyFirstCl, to keep AI "not cheating" do not use advantage of this and use this function just to prevent crashes
  352. void VCAI::objectRemoved(const CGObjectInstance * obj, const PlayerColor & initiator)
  353. {
  354. LOG_TRACE(logAi);
  355. NET_EVENT_HANDLER;
  356. vstd::erase_if_present(visitableObjs, obj);
  357. vstd::erase_if_present(alreadyVisited, obj);
  358. for(auto h : cb->getHeroesInfo())
  359. unreserveObject(h, obj);
  360. std::function<bool(const Goals::TSubgoal &)> checkRemovalValidity = [&](const Goals::TSubgoal & x) -> bool
  361. {
  362. if((x->goalType == Goals::VISIT_OBJ) && (x->objid == obj->id.getNum()))
  363. return true;
  364. else if(x->parent && checkRemovalValidity(x->parent)) //repeat this lambda check recursively on parent goal
  365. return true;
  366. else
  367. return false;
  368. };
  369. //clear VCAI / main loop caches
  370. vstd::erase_if(lockedHeroes, [&](const std::pair<HeroPtr, Goals::TSubgoal> & x) -> bool
  371. {
  372. return checkRemovalValidity(x.second);
  373. });
  374. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  375. {
  376. return checkRemovalValidity(x.first);
  377. });
  378. vstd::erase_if(basicGoals, checkRemovalValidity);
  379. vstd::erase_if(goalsToAdd, checkRemovalValidity);
  380. vstd::erase_if(goalsToRemove, checkRemovalValidity);
  381. for(auto goal : ultimateGoalsFromBasic)
  382. vstd::erase_if(goal.second, checkRemovalValidity);
  383. //clear resource manager goal cache
  384. ah->removeOutdatedObjectives(checkRemovalValidity);
  385. //TODO: Find better way to handle hero boat removal
  386. if(auto hero = dynamic_cast<const CGHeroInstance *>(obj))
  387. {
  388. if(hero->inBoat())
  389. {
  390. vstd::erase_if_present(visitableObjs, hero->getBoat());
  391. vstd::erase_if_present(alreadyVisited, hero->getBoat());
  392. for(auto h : cb->getHeroesInfo())
  393. unreserveObject(h, hero->getBoat());
  394. }
  395. }
  396. //TODO
  397. //there are other places where CGObjectinstance ptrs are stored...
  398. //
  399. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  400. {
  401. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  402. }
  403. }
  404. void VCAI::showHillFortWindow(const CGObjectInstance * object, const CGHeroInstance * visitor)
  405. {
  406. LOG_TRACE(logAi);
  407. NET_EVENT_HANDLER;
  408. executeActionAsync("showHillFortWindow", [visitor]()
  409. {
  410. makePossibleUpgrades(visitor);
  411. });
  412. }
  413. void VCAI::playerBonusChanged(const Bonus & bonus, bool gain)
  414. {
  415. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  416. NET_EVENT_HANDLER;
  417. }
  418. void VCAI::heroCreated(const CGHeroInstance * h)
  419. {
  420. LOG_TRACE(logAi);
  421. if(h->getVisitedTown())
  422. townVisitsThisWeek[HeroPtr(h)].insert(h->getVisitedTown());
  423. NET_EVENT_HANDLER;
  424. }
  425. void VCAI::advmapSpellCast(const CGHeroInstance * caster, SpellID spellID)
  426. {
  427. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  428. NET_EVENT_HANDLER;
  429. }
  430. void VCAI::showInfoDialog(EInfoWindowMode type, const std::string & text, const std::vector<Component> & components, int soundID)
  431. {
  432. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  433. NET_EVENT_HANDLER;
  434. }
  435. void VCAI::requestRealized(PackageApplied * pa)
  436. {
  437. LOG_TRACE(logAi);
  438. NET_EVENT_HANDLER;
  439. if(status.haveTurn())
  440. {
  441. if(pa->packType == CTypeList::getInstance().getTypeID<EndTurn>(nullptr))
  442. {
  443. if(pa->result)
  444. status.madeTurn();
  445. }
  446. }
  447. if(pa->packType == CTypeList::getInstance().getTypeID<QueryReply>(nullptr))
  448. {
  449. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  450. }
  451. }
  452. void VCAI::receivedResource()
  453. {
  454. LOG_TRACE(logAi);
  455. NET_EVENT_HANDLER;
  456. }
  457. void VCAI::showUniversityWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  458. {
  459. LOG_TRACE(logAi);
  460. NET_EVENT_HANDLER;
  461. status.addQuery(queryID, "UniversityWindow");
  462. executeActionAsync("showUniversityWindow", [this, queryID](){ answerQuery(queryID, 0); });
  463. }
  464. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  465. {
  466. LOG_TRACE(logAi);
  467. NET_EVENT_HANDLER;
  468. }
  469. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  470. {
  471. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  472. NET_EVENT_HANDLER;
  473. }
  474. void VCAI::battleResultsApplied()
  475. {
  476. LOG_TRACE(logAi);
  477. NET_EVENT_HANDLER;
  478. assert(status.getBattle() == ENDING_BATTLE);
  479. status.setBattle(NO_BATTLE);
  480. }
  481. void VCAI::beforeObjectPropertyChanged(const SetObjectProperty * sop)
  482. {
  483. }
  484. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  485. {
  486. LOG_TRACE(logAi);
  487. NET_EVENT_HANDLER;
  488. if(sop->what == ObjProperty::OWNER)
  489. {
  490. if(myCb->getPlayerRelations(playerID, sop->identifier.as<PlayerColor>()) == PlayerRelations::ENEMIES)
  491. {
  492. //we want to visit objects owned by oppponents
  493. auto obj = myCb->getObj(sop->id, false);
  494. if(obj)
  495. {
  496. addVisitableObj(obj); // TODO: Remove once save compatibility broken. In past owned objects were removed from this set
  497. vstd::erase_if_present(alreadyVisited, obj);
  498. }
  499. }
  500. }
  501. }
  502. void VCAI::buildChanged(const CGTownInstance * town, BuildingID buildingID, int what)
  503. {
  504. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  505. NET_EVENT_HANDLER;
  506. if(town->getOwner() == playerID && what == 1) //built
  507. completeGoal(sptr(Goals::BuildThis(buildingID, town)));
  508. }
  509. void VCAI::heroBonusChanged(const CGHeroInstance * hero, const Bonus & bonus, bool gain)
  510. {
  511. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  512. NET_EVENT_HANDLER;
  513. }
  514. void VCAI::showMarketWindow(const IMarket * market, const CGHeroInstance * visitor, QueryID queryID)
  515. {
  516. LOG_TRACE(logAi);
  517. NET_EVENT_HANDLER;
  518. status.addQuery(queryID, "MarketWindow");
  519. executeActionAsync("showMarketWindow", [this, queryID](){ answerQuery(queryID, 0); });
  520. }
  521. void VCAI::showWorldViewEx(const std::vector<ObjectPosInfo> & objectPositions, bool showTerrain)
  522. {
  523. //TODO: AI support for ViewXXX spell
  524. LOG_TRACE(logAi);
  525. NET_EVENT_HANDLER;
  526. }
  527. void VCAI::initGameInterface(std::shared_ptr<Environment> ENV, std::shared_ptr<CCallback> CB)
  528. {
  529. LOG_TRACE(logAi);
  530. env = ENV;
  531. myCb = CB;
  532. cbc = CB;
  533. ah->init(CB.get());
  534. NET_EVENT_HANDLER; //sets ah->rm->cb
  535. playerID = *myCb->getPlayerID();
  536. myCb->waitTillRealize = true;
  537. pathfinderCache = std::make_unique<PathfinderCache>(myCb.get(), PathfinderOptions(*myCb));
  538. if(!fh)
  539. fh = new FuzzyHelper();
  540. retrieveVisitableObjs();
  541. }
  542. std::shared_ptr<const CPathsInfo> VCAI::getPathsInfo(const CGHeroInstance * h) const
  543. {
  544. return pathfinderCache->getPathsInfo(h);
  545. }
  546. void VCAI::invalidatePaths()
  547. {
  548. pathfinderCache->invalidatePaths();
  549. }
  550. void VCAI::yourTurn(QueryID queryID)
  551. {
  552. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  553. NET_EVENT_HANDLER;
  554. status.addQuery(queryID, "YourTurn");
  555. executeActionAsync("yourTurn", [this, queryID](){ answerQuery(queryID, 0); });
  556. status.startedTurn();
  557. makingTurnInterrupption.reset();
  558. asyncTasks->run([this]()
  559. {
  560. ScopedThreadName guard("VCAI::makingTurn");
  561. makeTurn();
  562. });
  563. }
  564. void VCAI::heroGotLevel(const CGHeroInstance * hero, PrimarySkill pskill, std::vector<SecondarySkill> & skills, QueryID queryID)
  565. {
  566. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  567. NET_EVENT_HANDLER;
  568. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->getNameTranslated() % hero->level));
  569. executeActionAsync("heroGotLevel", [this, queryID](){ answerQuery(queryID, 0); });
  570. }
  571. void VCAI::commanderGotLevel(const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  572. {
  573. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  574. NET_EVENT_HANDLER;
  575. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->getArmy()->nodeName() % static_cast<int>(commander->level)));
  576. executeActionAsync("commanderGotLevel", [this, queryID](){ answerQuery(queryID, 0); });
  577. }
  578. void VCAI::showBlockingDialog(const std::string & text, const std::vector<Component> & components, QueryID askID, const int soundID, bool selection, bool cancel, bool safeToAutoaccept)
  579. {
  580. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i', autoaccept '%i'", text % askID % soundID % selection % cancel % safeToAutoaccept);
  581. NET_EVENT_HANDLER;
  582. int sel = 0;
  583. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  584. % components.size() % text));
  585. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  586. sel = static_cast<int>(components.size());
  587. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  588. sel = 1;
  589. executeActionAsync("showBlockingDialog", [this, askID, sel]()
  590. {
  591. answerQuery(askID, sel);
  592. });
  593. }
  594. void VCAI::showTeleportDialog(const CGHeroInstance * hero, TeleportChannelID channel, TTeleportExitsList exits, bool impassable, QueryID askID)
  595. {
  596. // LOG_TRACE_PARAMS(logAi, "askID '%i', exits '%s'", askID % exits);
  597. NET_EVENT_HANDLER;
  598. status.addQuery(askID, boost::str(boost::format("Teleport dialog query with %d exits")
  599. % exits.size()));
  600. int chosenExit = -1;
  601. if(impassable)
  602. {
  603. knownTeleportChannels[channel]->passability = TeleportChannel::IMPASSABLE;
  604. }
  605. else if(destinationTeleport != ObjectInstanceID() && destinationTeleportPos.isValid())
  606. {
  607. auto neededExit = std::make_pair(destinationTeleport, destinationTeleportPos);
  608. if(destinationTeleport != ObjectInstanceID() && vstd::contains(exits, neededExit))
  609. chosenExit = vstd::find_pos(exits, neededExit);
  610. }
  611. for(auto exit : exits)
  612. {
  613. if(status.channelProbing() && exit.first == destinationTeleport)
  614. {
  615. chosenExit = vstd::find_pos(exits, exit);
  616. break;
  617. }
  618. else
  619. {
  620. // TODO: Implement checking if visiting that teleport will uncovert any FoW
  621. // So far this is the best option to handle decision about probing
  622. auto obj = cb->getObj(exit.first, false);
  623. if(obj == nullptr && !vstd::contains(teleportChannelProbingList, exit.first))
  624. {
  625. if(exit.first != destinationTeleport)
  626. teleportChannelProbingList.push_back(exit.first);
  627. }
  628. }
  629. }
  630. executeActionAsync("showTeleportDialog", [this, askID, chosenExit]()
  631. {
  632. answerQuery(askID, chosenExit);
  633. });
  634. }
  635. void VCAI::showGarrisonDialog(const CArmedInstance * up, const CGHeroInstance * down, bool removableUnits, QueryID queryID)
  636. {
  637. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  638. NET_EVENT_HANDLER;
  639. std::string s1 = up ? up->nodeName() : "NONE";
  640. std::string s2 = down ? down->nodeName() : "NONE";
  641. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  642. //you can't request action from action-response thread
  643. executeActionAsync("showGarrisonDialog", [this, down, up, removableUnits, queryID]()
  644. {
  645. if(removableUnits && !cb->getStartInfo()->restrictedGarrisonsForAI())
  646. pickBestCreatures(down, up);
  647. answerQuery(queryID, 0);
  648. });
  649. }
  650. void VCAI::showMapObjectSelectDialog(QueryID askID, const Component & icon, const MetaString & title, const MetaString & description, const std::vector<ObjectInstanceID> & objects)
  651. {
  652. NET_EVENT_HANDLER;
  653. status.addQuery(askID, "Map object select query");
  654. executeActionAsync("showMapObjectSelectDialog", [this, askID](){ answerQuery(askID, selectedObject.getNum()); });
  655. }
  656. void makePossibleUpgrades(const CArmedInstance * obj)
  657. {
  658. if(!obj)
  659. return;
  660. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  661. {
  662. if(const CStackInstance * s = obj->getStackPtr(SlotID(i)))
  663. {
  664. UpgradeInfo upgradeInfo(s->getId());
  665. do
  666. {
  667. cb->fillUpgradeInfo(obj, SlotID(i), upgradeInfo);
  668. if(upgradeInfo.hasUpgrades())
  669. {
  670. // creature at given slot might have alternative upgrades, pick best one
  671. CreatureID upgID = *vstd::maxElementByFun(upgradeInfo.getAvailableUpgrades(), [](const CreatureID & id)
  672. {
  673. return id.toCreature()->getAIValue();
  674. });
  675. if(cb->getResourceAmount().canAfford(upgradeInfo.getUpgradeCostsFor(upgID) * s->getCount()))
  676. {
  677. cb->upgradeCreature(obj, SlotID(i), upgID);
  678. logAi->debug("Upgraded %d %s to %s", s->getCount(), upgradeInfo.oldID.toCreature()->getNamePluralTranslated(),
  679. upgradeInfo.getUpgrade().toCreature()->getNamePluralTranslated());
  680. }
  681. else
  682. break;
  683. }
  684. }
  685. while(upgradeInfo.hasUpgrades());
  686. }
  687. }
  688. }
  689. void VCAI::makeTurn()
  690. {
  691. MAKING_TURN;
  692. auto day = cb->getDate(Date::DAY);
  693. logAi->info("Player %d (%s) starting turn, day %d", playerID, playerID.toString(), day);
  694. std::shared_lock gsLock(CGameState::mutex);
  695. setThreadName("VCAI::makeTurn");
  696. switch(cb->getDate(Date::DAY_OF_WEEK))
  697. {
  698. case 1:
  699. {
  700. townVisitsThisWeek.clear();
  701. std::vector<const CGObjectInstance *> objs;
  702. retrieveVisitableObjs(objs, true);
  703. for(const CGObjectInstance * obj : objs)
  704. {
  705. if(isWeeklyRevisitable(obj))
  706. {
  707. addVisitableObj(obj);
  708. vstd::erase_if_present(alreadyVisited, obj);
  709. }
  710. }
  711. break;
  712. }
  713. }
  714. markHeroAbleToExplore(primaryHero());
  715. visitedHeroes.clear();
  716. try
  717. {
  718. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  719. for (const CGTownInstance * t : cb->getTownsInfo())
  720. moveCreaturesToHero(t);
  721. mainLoop();
  722. /*Below function is also responsible for hero movement via internal wander function. By design it is separate logic for heroes that have nothing to do.
  723. Heroes that were not picked by striveToGoal(sptr(Goals::Win())); recently (so they do not have new goals and cannot continue/reevaluate previously locked goals) will do logic in wander().*/
  724. performTypicalActions();
  725. //for debug purpose
  726. for (auto h : cb->getHeroesInfo())
  727. {
  728. if (h->movementPointsRemaining())
  729. logAi->info("Hero %s has %d MP left", h->getNameTranslated(), h->movementPointsRemaining());
  730. }
  731. }
  732. catch (const TerminationRequestedException &)
  733. {
  734. logAi->debug("Making turn thread has been interrupted. We'll end without calling endTurn.");
  735. return;
  736. }
  737. catch (std::exception & e)
  738. {
  739. logAi->debug("Making turn thread has caught an exception: %s", e.what());
  740. }
  741. endTurn();
  742. }
  743. std::vector<HeroPtr> VCAI::getMyHeroes() const
  744. {
  745. std::vector<HeroPtr> ret;
  746. for(auto h : cb->getHeroesInfo())
  747. {
  748. ret.push_back(h);
  749. }
  750. return ret;
  751. }
  752. void VCAI::mainLoop()
  753. {
  754. std::vector<Goals::TSubgoal> elementarGoals; //no duplicates allowed (operator ==)
  755. basicGoals.clear();
  756. validateVisitableObjs();
  757. //get all potential and saved goals
  758. //TODO: not lose
  759. basicGoals.push_back(sptr(Goals::Win()));
  760. for (auto goalPair : lockedHeroes)
  761. {
  762. fh->setPriority(goalPair.second); //re-evaluate, as heroes moved in the meantime
  763. basicGoals.push_back(goalPair.second);
  764. }
  765. if (ah->hasTasksLeft())
  766. basicGoals.push_back(ah->whatToDo());
  767. for (auto quest : myCb->getMyQuests())
  768. {
  769. basicGoals.push_back(sptr(Goals::CompleteQuest(quest)));
  770. }
  771. basicGoals.push_back(sptr(Goals::Build()));
  772. invalidPathHeroes.clear();
  773. for (int pass = 0; pass< 30 && basicGoals.size(); pass++)
  774. {
  775. vstd::removeDuplicates(basicGoals); //TODO: container which does this automagically without has would be nice
  776. goalsToAdd.clear();
  777. goalsToRemove.clear();
  778. elementarGoals.clear();
  779. ultimateGoalsFromBasic.clear();
  780. ah->updatePaths(getMyHeroes());
  781. logAi->debug("Main loop: decomposing %i basic goals", basicGoals.size());
  782. for (auto basicGoal : basicGoals)
  783. {
  784. logAi->debug("Main loop: decomposing basic goal %s", basicGoal->name());
  785. auto goalToDecompose = basicGoal;
  786. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  787. int maxAbstractGoals = 10;
  788. while (!elementarGoal->isElementar && maxAbstractGoals)
  789. {
  790. try
  791. {
  792. elementarGoal = decomposeGoal(goalToDecompose);
  793. }
  794. catch (goalFulfilledException & e)
  795. {
  796. //it is impossible to continue some goals (like exploration, for example)
  797. //complete abstract goal for now, but maybe main goal finds another path
  798. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  799. completeGoal(e.goal); //put in goalsToRemove
  800. break;
  801. }
  802. catch(cannotFulfillGoalException & e)
  803. {
  804. //it is impossible to continue some goals (like exploration, for example)
  805. //complete abstract goal for now, but maybe main goal finds another path
  806. goalsToRemove.push_back(basicGoal);
  807. logAi->debug("Goal %s decomposition failed: %s", goalToDecompose->name(), e.what());
  808. break;
  809. }
  810. catch (std::exception & e) //decomposition failed, which means we can't decompose entire tree
  811. {
  812. goalsToRemove.push_back(basicGoal);
  813. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  814. break;
  815. }
  816. if (elementarGoal->isAbstract) //we can decompose it further
  817. {
  818. goalsToAdd.push_back(elementarGoal);
  819. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  820. goalToDecompose = elementarGoal;
  821. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  822. maxAbstractGoals--;
  823. }
  824. else if (elementarGoal->isElementar) //should be
  825. {
  826. logAi->debug("Found elementar goal %s", elementarGoal->name());
  827. elementarGoals.push_back(elementarGoal);
  828. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  829. break;
  830. }
  831. else //should never be here
  832. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  833. }
  834. }
  835. logAi->trace("Main loop: selecting best elementar goal");
  836. //now choose one elementar goal to realize
  837. Goals::TGoalVec possibleGoals(elementarGoals.begin(), elementarGoals.end()); //copy to vector
  838. Goals::TSubgoal goalToRealize = sptr(Goals::Invalid());
  839. while (possibleGoals.size())
  840. {
  841. //allow assign goals to heroes with 0 movement, but don't realize them
  842. //maybe there are better ones left
  843. auto bestGoal = fh->chooseSolution(possibleGoals);
  844. if (bestGoal->hero) //lock this hero to fulfill goal
  845. {
  846. setGoal(bestGoal->hero, bestGoal);
  847. if (!bestGoal->hero->movementPointsRemaining() || vstd::contains(invalidPathHeroes, bestGoal->hero))
  848. {
  849. if (!vstd::erase_if_present(possibleGoals, bestGoal))
  850. {
  851. logAi->error("erase_if_preset failed? Something very wrong!");
  852. break;
  853. }
  854. continue; //chose next from the list
  855. }
  856. }
  857. goalToRealize = bestGoal; //we found our goal to execute
  858. break;
  859. }
  860. //realize best goal
  861. if (!goalToRealize->invalid())
  862. {
  863. logAi->debug("Trying to realize %s (value %2.3f)", goalToRealize->name(), goalToRealize->priority);
  864. try
  865. {
  866. makingTurnInterrupption.interruptionPoint();
  867. goalToRealize->accept(this); //visitor pattern
  868. makingTurnInterrupption.interruptionPoint();
  869. }
  870. catch (const TerminationRequestedException &)
  871. {
  872. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  873. throw; //rethrow, we want to truly end this thread
  874. }
  875. catch (const goalFulfilledException & e)
  876. {
  877. //the sub-goal was completed successfully
  878. completeGoal(e.goal);
  879. //local goal was also completed?
  880. completeGoal(goalToRealize);
  881. // remove abstract visit tile if we completed the elementar one
  882. vstd::erase_if_present(goalsToAdd, goalToRealize);
  883. }
  884. catch (const std::exception & e)
  885. {
  886. logAi->debug("Failed to realize subgoal of type %s, I will stop.", goalToRealize->name());
  887. logAi->debug("The error message was: %s", e.what());
  888. //erase base goal if we failed to execute decomposed goal
  889. for (auto basicGoal : ultimateGoalsFromBasic[goalToRealize])
  890. goalsToRemove.push_back(basicGoal);
  891. // sometimes resource manager contains an elementar goal which is not able to execute anymore and just fails each turn.
  892. ai->ah->notifyGoalCompleted(goalToRealize);
  893. //we failed to realize best goal, but maybe others are still possible?
  894. }
  895. //remove goals we couldn't decompose
  896. for (auto goal : goalsToRemove)
  897. vstd::erase_if_present(basicGoals, goal);
  898. //add abstract goals
  899. boost::sort(goalsToAdd, [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  900. {
  901. return lhs->priority > rhs->priority; //highest priority at the beginning
  902. });
  903. //max number of goals = 10
  904. int i = 0;
  905. while (basicGoals.size() < 10 && goalsToAdd.size() > i)
  906. {
  907. if (!vstd::contains(basicGoals, goalsToAdd[i])) //don't add duplicates
  908. basicGoals.push_back(goalsToAdd[i]);
  909. i++;
  910. }
  911. }
  912. else //no elementar goals possible
  913. {
  914. logAi->debug("Goal decomposition exhausted");
  915. break;
  916. }
  917. }
  918. }
  919. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  920. {
  921. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->getNameTranslated() % obj->getObjectName() % obj->anchorPos().toString());
  922. switch(obj->ID)
  923. {
  924. case Obj::TOWN:
  925. moveCreaturesToHero(dynamic_cast<const CGTownInstance *>(obj));
  926. if(h->getVisitedTown()) //we are inside, not just attacking
  927. {
  928. townVisitsThisWeek[h].insert(h->getVisitedTown());
  929. if(!h->hasSpellbook() && ah->freeGold() >= GameConstants::SPELLBOOK_GOLD_COST)
  930. {
  931. if(h->getVisitedTown()->hasBuilt(BuildingID::MAGES_GUILD_1))
  932. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  933. }
  934. }
  935. break;
  936. }
  937. completeGoal(sptr(Goals::VisitObj(obj->id.getNum()).sethero(h)));
  938. }
  939. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  940. {
  941. if(t->getVisitingHero() && t->armedGarrison() && t->getVisitingHero()->tempOwner == t->tempOwner)
  942. {
  943. pickBestCreatures(t->getVisitingHero(), t);
  944. }
  945. }
  946. void VCAI::pickBestCreatures(const CArmedInstance * destinationArmy, const CArmedInstance * source)
  947. {
  948. const CArmedInstance * armies[] = {destinationArmy, source};
  949. auto bestArmy = ah->getSortedSlots(destinationArmy, source);
  950. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  951. for(SlotID i = SlotID(0); i.getNum() < bestArmy.size() && i.validSlot(); i.advance(1)) //i-th strongest creature type will go to i-th slot
  952. {
  953. const CCreature * targetCreature = bestArmy[i.getNum()].creature;
  954. for(auto armyPtr : armies)
  955. {
  956. for(SlotID j = SlotID(0); j.validSlot(); j.advance(1))
  957. {
  958. if(armyPtr->getCreature(j) == targetCreature && (i != j || armyPtr != destinationArmy)) //it's a searched creature not in dst SLOT
  959. {
  960. //can't take away last creature without split. generate a new stack with 1 creature which is weak but fast
  961. if(armyPtr == source
  962. && source->needsLastStack()
  963. && source->stacksCount() == 1
  964. && (!destinationArmy->hasStackAtSlot(i) || destinationArmy->getCreature(i) == targetCreature))
  965. {
  966. auto weakest = ah->getWeakestCreature(bestArmy);
  967. if(weakest->creature == targetCreature)
  968. {
  969. if(1 == source->getStackCount(j))
  970. break;
  971. // move all except 1 of weakest creature from source to destination
  972. cb->splitStack(
  973. source,
  974. destinationArmy,
  975. j,
  976. destinationArmy->getSlotFor(targetCreature),
  977. destinationArmy->getStackCount(i) + source->getStackCount(j) - 1);
  978. break;
  979. }
  980. else
  981. {
  982. // Source last stack is not weakest. Move 1 of weakest creature from destination to source
  983. cb->splitStack(
  984. destinationArmy,
  985. source,
  986. destinationArmy->getSlotFor(weakest->creature),
  987. source->getFreeSlot(),
  988. 1);
  989. }
  990. }
  991. cb->mergeOrSwapStacks(armyPtr, destinationArmy, j, i);
  992. }
  993. }
  994. }
  995. }
  996. //TODO - having now strongest possible army, we may want to think about arranging stacks
  997. auto hero = dynamic_cast<const CGHeroInstance *>(destinationArmy);
  998. if(hero)
  999. checkHeroArmy(hero);
  1000. }
  1001. void VCAI::pickBestArtifacts(const CGHeroInstance * h, const CGHeroInstance * other)
  1002. {
  1003. auto equipBest = [](const CGHeroInstance * h, const CGHeroInstance * otherh, bool giveStuffToFirstHero) -> void
  1004. {
  1005. bool changeMade = false;
  1006. do
  1007. {
  1008. changeMade = false;
  1009. //we collect gear always in same order
  1010. std::vector<ArtifactLocation> allArtifacts;
  1011. if(giveStuffToFirstHero)
  1012. {
  1013. for(auto p : h->artifactsWorn)
  1014. {
  1015. if(p.second.getArt())
  1016. allArtifacts.push_back(ArtifactLocation(h->id, p.first));
  1017. }
  1018. }
  1019. for(auto slot : h->artifactsInBackpack)
  1020. allArtifacts.push_back(ArtifactLocation(h->id, h->getArtPos(slot.getArt())));
  1021. if(otherh)
  1022. {
  1023. for(auto p : otherh->artifactsWorn)
  1024. {
  1025. if(p.second.getArt())
  1026. allArtifacts.push_back(ArtifactLocation(otherh->id, p.first));
  1027. }
  1028. for(auto slot : otherh->artifactsInBackpack)
  1029. allArtifacts.push_back(ArtifactLocation(otherh->id, otherh->getArtPos(slot.getArt())));
  1030. }
  1031. //we give stuff to one hero or another, depending on giveStuffToFirstHero
  1032. const CGHeroInstance * target = nullptr;
  1033. if(giveStuffToFirstHero || !otherh)
  1034. target = h;
  1035. else
  1036. target = otherh;
  1037. for(auto location : allArtifacts)
  1038. {
  1039. if(location.slot == ArtifactPosition::MACH4 || location.slot == ArtifactPosition::SPELLBOOK)
  1040. continue; // don't attempt to move catapult and spellbook
  1041. if(location.artHolder == target->id && ArtifactUtils::isSlotEquipment(location.slot))
  1042. continue; //don't reequip artifact we already wear
  1043. auto s = cb->getHero(location.artHolder)->getSlot(location.slot);
  1044. if(!s || s->locked) //we can't move locks
  1045. continue;
  1046. auto artifact = s->getArt();
  1047. if(!artifact)
  1048. continue;
  1049. //FIXME: why are the above possible to be null?
  1050. bool emptySlotFound = false;
  1051. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1052. {
  1053. if(target->isPositionFree(slot) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1054. {
  1055. ArtifactLocation destLocation(target->id, slot);
  1056. cb->swapArtifacts(location, destLocation); //just put into empty slot
  1057. emptySlotFound = true;
  1058. changeMade = true;
  1059. break;
  1060. }
  1061. }
  1062. if(!emptySlotFound) //try to put that atifact in already occupied slot
  1063. {
  1064. for(auto slot : artifact->getType()->getPossibleSlots().at(target->bearerType()))
  1065. {
  1066. auto otherSlot = target->getSlot(slot);
  1067. if(otherSlot && otherSlot->getArt()) //we need to exchange artifact for better one
  1068. {
  1069. //if that artifact is better than what we have, pick it
  1070. if(compareArtifacts(artifact, otherSlot->getArt()) && artifact->canBePutAt(target, slot, true)) //combined artifacts are not always allowed to move
  1071. {
  1072. ArtifactLocation destLocation(target->id, slot);
  1073. cb->swapArtifacts(location, ArtifactLocation(target->id, target->getArtPos(otherSlot->getArt())));
  1074. changeMade = true;
  1075. break;
  1076. }
  1077. }
  1078. }
  1079. }
  1080. if(changeMade)
  1081. break; //start evaluating artifacts from scratch
  1082. }
  1083. }
  1084. while(changeMade);
  1085. };
  1086. equipBest(h, other, true);
  1087. if(other)
  1088. equipBest(h, other, false);
  1089. }
  1090. void VCAI::recruitCreatures(const CGDwelling * d, const CArmedInstance * recruiter)
  1091. {
  1092. //now used only for visited dwellings / towns, not BuyArmy goal
  1093. for(int i = 0; i < d->creatures.size(); i++)
  1094. {
  1095. if(!d->creatures[i].second.size())
  1096. continue;
  1097. int count = d->creatures[i].first;
  1098. CreatureID creID = d->creatures[i].second.back();
  1099. vstd::amin(count, ah->freeResources() / LIBRARY->creatures()->getById(creID)->getFullRecruitCost());
  1100. if(count > 0)
  1101. cb->recruitCreatures(d, recruiter, creID, count, i);
  1102. }
  1103. }
  1104. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, std::optional<float> movementCostLimit)
  1105. {
  1106. int3 op = obj->visitablePos();
  1107. auto paths = ah->getPathsToTile(h, op);
  1108. for(const auto & path : paths)
  1109. {
  1110. if(movementCostLimit && movementCostLimit.value() < path.movementCost())
  1111. return false;
  1112. if(isGoodForVisit(obj, h, path))
  1113. return true;
  1114. }
  1115. return false;
  1116. }
  1117. bool VCAI::isGoodForVisit(const CGObjectInstance * obj, HeroPtr h, const AIPath & path) const
  1118. {
  1119. const int3 pos = obj->visitablePos();
  1120. const int3 targetPos = path.firstTileToGet();
  1121. if (!targetPos.isValid())
  1122. return false;
  1123. if (!isTileNotReserved(h.get(), targetPos))
  1124. return false;
  1125. if (obj->wasVisited(playerID))
  1126. return false;
  1127. if (cb->getPlayerRelations(playerID, obj->tempOwner) != PlayerRelations::ENEMIES && !isWeeklyRevisitable(obj))
  1128. return false; // Otherwise we flag or get weekly resources / creatures
  1129. if (!isSafeToVisit(h, pos))
  1130. return false;
  1131. if (!shouldVisit(h, obj))
  1132. return false;
  1133. if (vstd::contains(alreadyVisited, obj))
  1134. return false;
  1135. if (vstd::contains(reservedObjs, obj))
  1136. return false;
  1137. // TODO: looks extra if we already have AIPath
  1138. //if (!isAccessibleForHero(targetPos, h))
  1139. // return false;
  1140. const CGObjectInstance * topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1141. //we don't try visiting object on which allied or owned hero stands
  1142. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1143. return !(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES); //all of the following is met
  1144. }
  1145. bool VCAI::isTileNotReserved(const CGHeroInstance * h, int3 t) const
  1146. {
  1147. if(t.isValid())
  1148. {
  1149. auto obj = cb->getTopObj(t);
  1150. if(obj && vstd::contains(ai->reservedObjs, obj)
  1151. && vstd::contains(reservedHeroesMap, h)
  1152. && !vstd::contains(reservedHeroesMap.at(h), obj))
  1153. return false; //do not capture object reserved by another hero
  1154. else
  1155. return true;
  1156. }
  1157. else
  1158. {
  1159. return false;
  1160. }
  1161. }
  1162. bool VCAI::canRecruitAnyHero(const CGTownInstance * t) const
  1163. {
  1164. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1165. if(!t)
  1166. t = findTownWithTavern();
  1167. if(!t)
  1168. return false;
  1169. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST) //TODO: use ResourceManager
  1170. return false;
  1171. if(cb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  1172. return false;
  1173. if(!cb->getAvailableHeroes(t).size())
  1174. return false;
  1175. return true;
  1176. }
  1177. void VCAI::wander(HeroPtr h)
  1178. {
  1179. auto visitTownIfAny = [this](HeroPtr h) -> bool
  1180. {
  1181. if (h->getVisitedTown())
  1182. {
  1183. townVisitsThisWeek[h].insert(h->getVisitedTown());
  1184. buildArmyIn(h->getVisitedTown());
  1185. return true;
  1186. }
  1187. return false;
  1188. };
  1189. //unclaim objects that are now dangerous for us
  1190. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1191. for(auto obj : reservedObjsSetCopy)
  1192. {
  1193. if(!isSafeToVisit(h, obj->visitablePos()))
  1194. unreserveObject(h, obj);
  1195. }
  1196. TimeCheck tc("looking for wander destination");
  1197. for(int k = 0; k < 10 && h->movementPointsRemaining(); k++)
  1198. {
  1199. validateVisitableObjs();
  1200. ah->updatePaths(getMyHeroes());
  1201. std::vector<ObjectIdRef> dests;
  1202. //also visit our reserved objects - but they are not prioritized to avoid running back and forth
  1203. vstd::copy_if(reservedHeroesMap[h], std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1204. {
  1205. return ah->isTileAccessible(h, obj->visitablePos());
  1206. });
  1207. int pass = 0;
  1208. std::vector<std::optional<float>> distanceLimits = {1.0, 2.0, std::nullopt};
  1209. while(!dests.size() && pass < distanceLimits.size())
  1210. {
  1211. auto & distanceLimit = distanceLimits[pass];
  1212. logAi->debug("Looking for wander destination pass=%i, cost limit=%f", pass, distanceLimit.value_or(-1.0));
  1213. vstd::copy_if(visitableObjs, std::back_inserter(dests), [&](ObjectIdRef obj) -> bool
  1214. {
  1215. return isGoodForVisit(obj, h, distanceLimit);
  1216. });
  1217. pass++;
  1218. }
  1219. if(!dests.size())
  1220. {
  1221. logAi->debug("Looking for town destination");
  1222. if(cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1223. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1224. auto compareReinforcements = [&](const CGTownInstance * lhs, const CGTownInstance * rhs) -> bool
  1225. {
  1226. const CGHeroInstance * hptr = h.get();
  1227. auto r1 = ah->howManyReinforcementsCanGet(hptr, lhs);
  1228. auto r2 = ah->howManyReinforcementsCanGet(hptr, rhs);
  1229. if (r1 != r2)
  1230. return r1 < r2;
  1231. else
  1232. return ah->howManyReinforcementsCanBuy(hptr, lhs) < ah->howManyReinforcementsCanBuy(hptr, rhs);
  1233. };
  1234. std::vector<const CGTownInstance *> townsReachable;
  1235. std::vector<const CGTownInstance *> townsNotReachable;
  1236. for(const CGTownInstance * t : cb->getTownsInfo())
  1237. {
  1238. if(!t->getVisitingHero() && !vstd::contains(townVisitsThisWeek[h], t))
  1239. {
  1240. if(isAccessibleForHero(t->visitablePos(), h))
  1241. townsReachable.push_back(t);
  1242. else
  1243. townsNotReachable.push_back(t);
  1244. }
  1245. }
  1246. if(townsReachable.size()) //travel to town with largest garrison, or empty - better than nothing
  1247. {
  1248. dests.push_back(*boost::max_element(townsReachable, compareReinforcements));
  1249. }
  1250. else if(townsNotReachable.size())
  1251. {
  1252. //TODO pick the truly best
  1253. const CGTownInstance * t = *boost::max_element(townsNotReachable, compareReinforcements);
  1254. logAi->debug("%s can't reach any town, we'll try to make our way to %s at %s", h->getNameTranslated(), t->getNameTranslated(), t->visitablePos().toString());
  1255. int3 posBefore = h->visitablePos();
  1256. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h))); //TODO: drop "strive", add to mainLoop
  1257. //if out hero is stuck, we may need to request another hero to clear the way we see
  1258. if(posBefore == h->visitablePos() && h == primaryHero()) //hero can't move
  1259. {
  1260. if(canRecruitAnyHero(t))
  1261. recruitHero(t);
  1262. }
  1263. break;
  1264. }
  1265. else if(cb->getResourceAmount(EGameResID::GOLD) >= GameConstants::HERO_GOLD_COST)
  1266. {
  1267. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1268. vstd::erase_if(towns, [&](const CGTownInstance * t) -> bool
  1269. {
  1270. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1271. {
  1272. if(!t->getArmyStrength() || ah->howManyReinforcementsCanGet(h, t))
  1273. return true;
  1274. }
  1275. return false;
  1276. });
  1277. if (towns.size())
  1278. {
  1279. recruitHero(*boost::max_element(towns, compareArmyStrength));
  1280. }
  1281. break;
  1282. }
  1283. else
  1284. {
  1285. logAi->debug("Nowhere more to go...");
  1286. break;
  1287. }
  1288. }
  1289. //end of objs empty
  1290. if(dests.size()) //performance improvement
  1291. {
  1292. Goals::TGoalVec targetObjectGoals;
  1293. for(auto destination : dests)
  1294. {
  1295. vstd::concatenate(targetObjectGoals, ah->howToVisitObj(h, destination, false));
  1296. }
  1297. if(targetObjectGoals.size())
  1298. {
  1299. auto bestObjectGoal = fh->chooseSolution(targetObjectGoals);
  1300. //wander should not cause heroes to be reserved - they are always considered free
  1301. if(bestObjectGoal->goalType == Goals::VISIT_OBJ)
  1302. {
  1303. auto chosenObject = cb->getObjInstance(ObjectInstanceID(bestObjectGoal->objid));
  1304. if(chosenObject != nullptr)
  1305. logAi->debug("Of all %d destinations, object %s at pos=%s seems nice", dests.size(), chosenObject->getObjectName(), chosenObject->anchorPos().toString());
  1306. }
  1307. else
  1308. logAi->debug("Trying to realize goal of type %s as part of wandering.", bestObjectGoal->name());
  1309. try
  1310. {
  1311. decomposeGoal(bestObjectGoal)->accept(this);
  1312. }
  1313. catch(const goalFulfilledException & e)
  1314. {
  1315. if(e.goal->goalType == Goals::EGoals::VISIT_TILE || e.goal->goalType == Goals::EGoals::VISIT_OBJ)
  1316. continue;
  1317. throw;
  1318. }
  1319. }
  1320. else
  1321. {
  1322. logAi->debug("Nowhere more to go...");
  1323. break;
  1324. }
  1325. visitTownIfAny(h);
  1326. }
  1327. }
  1328. visitTownIfAny(h); //in case hero is just sitting in town
  1329. }
  1330. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1331. {
  1332. if(goal->invalid())
  1333. {
  1334. vstd::erase_if_present(lockedHeroes, h);
  1335. }
  1336. else
  1337. {
  1338. lockedHeroes[h] = goal;
  1339. goal->setisElementar(false); //Force always evaluate goals before realizing
  1340. }
  1341. }
  1342. void VCAI::evaluateGoal(HeroPtr h)
  1343. {
  1344. if(vstd::contains(lockedHeroes, h))
  1345. fh->setPriority(lockedHeroes[h]);
  1346. }
  1347. void VCAI::completeGoal(Goals::TSubgoal goal)
  1348. {
  1349. if (goal->goalType == Goals::WIN) //we can never complete this goal - unless we already won
  1350. return;
  1351. logAi->debug("Completing goal: %s", goal->name());
  1352. //notify Managers
  1353. ah->notifyGoalCompleted(goal);
  1354. //notify mainLoop()
  1355. goalsToRemove.push_back(goal); //will be removed from mainLoop() goals
  1356. for (auto basicGoal : basicGoals) //we could luckily fulfill any of our goals
  1357. {
  1358. if (basicGoal->fulfillsMe(goal))
  1359. goalsToRemove.push_back(basicGoal);
  1360. }
  1361. //unreserve heroes
  1362. if(const CGHeroInstance * h = goal->hero.get(true))
  1363. {
  1364. auto it = lockedHeroes.find(h);
  1365. if(it != lockedHeroes.end())
  1366. {
  1367. if(it->second == goal || it->second->fulfillsMe(goal)) //FIXME this is overspecified, fulfillsMe should be complete
  1368. {
  1369. logAi->debug(goal->completeMessage());
  1370. lockedHeroes.erase(it); //goal fulfilled, free hero
  1371. }
  1372. }
  1373. }
  1374. else //complete goal for all heroes maybe?
  1375. {
  1376. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1377. {
  1378. if(p.second == goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1379. {
  1380. logAi->debug(p.second->completeMessage());
  1381. return true;
  1382. }
  1383. return false;
  1384. });
  1385. }
  1386. }
  1387. void VCAI::battleStart(const BattleID & battleID, const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance * hero1, const CGHeroInstance * hero2, BattleSide side, bool replayAllowed)
  1388. {
  1389. NET_EVENT_HANDLER;
  1390. assert(!playerID.isValidPlayer() || status.getBattle() == UPCOMING_BATTLE);
  1391. status.setBattle(ONGOING_BATTLE);
  1392. 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
  1393. 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());
  1394. CAdventureAI::battleStart(battleID, army1, army2, tile, hero1, hero2, side, replayAllowed);
  1395. }
  1396. void VCAI::battleEnd(const BattleID & battleID, const BattleResult * br, QueryID queryID)
  1397. {
  1398. NET_EVENT_HANDLER;
  1399. assert(status.getBattle() == ONGOING_BATTLE);
  1400. status.setBattle(ENDING_BATTLE);
  1401. bool won = br->winner == myCb->getBattle(battleID)->battleGetMySide();
  1402. logAi->debug("Player %d (%s): I %s the %s!", playerID, playerID.toString(), (won ? "won" : "lost"), battlename);
  1403. battlename.clear();
  1404. CAdventureAI::battleEnd(battleID, br, queryID);
  1405. }
  1406. void VCAI::waitTillFree()
  1407. {
  1408. auto unlock = vstd::makeUnlockSharedGuard(CGameState::mutex);
  1409. status.waitTillFree();
  1410. }
  1411. void VCAI::markObjectVisited(const CGObjectInstance * obj)
  1412. {
  1413. if(!obj)
  1414. return;
  1415. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj)) //we may want to visit it with another hero
  1416. {
  1417. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_HERO) //we may want to visit it with another hero
  1418. return;
  1419. if (rewardable->configuration.getVisitMode() == Rewardable::VISIT_BONUS) //or another time
  1420. return;
  1421. }
  1422. if(obj->ID == Obj::MONSTER)
  1423. return;
  1424. alreadyVisited.insert(obj);
  1425. }
  1426. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance * obj)
  1427. {
  1428. reservedObjs.insert(obj);
  1429. reservedHeroesMap[h].insert(obj);
  1430. logAi->debug("reserved object id=%d; address=%p; name=%s", obj->id, obj, obj->getObjectName());
  1431. }
  1432. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance * obj)
  1433. {
  1434. vstd::erase_if_present(reservedObjs, obj); //unreserve objects
  1435. vstd::erase_if_present(reservedHeroesMap[h], obj);
  1436. }
  1437. void VCAI::markHeroUnableToExplore(HeroPtr h)
  1438. {
  1439. heroesUnableToExplore.insert(h);
  1440. }
  1441. void VCAI::markHeroAbleToExplore(HeroPtr h)
  1442. {
  1443. vstd::erase_if_present(heroesUnableToExplore, h);
  1444. }
  1445. bool VCAI::isAbleToExplore(HeroPtr h)
  1446. {
  1447. return !vstd::contains(heroesUnableToExplore, h);
  1448. }
  1449. void VCAI::clearPathsInfo()
  1450. {
  1451. heroesUnableToExplore.clear();
  1452. }
  1453. void VCAI::validateVisitableObjs()
  1454. {
  1455. std::string errorMsg;
  1456. auto shouldBeErased = [&](const CGObjectInstance * obj) -> bool
  1457. {
  1458. if(obj)
  1459. return !cb->getObj(obj->id, false); // no verbose output needed as we check object visibility
  1460. else
  1461. return true;
  1462. };
  1463. //errorMsg is captured by ref so lambda will take the new text
  1464. errorMsg = " shouldn't be on the visitable objects list!";
  1465. vstd::erase_if(visitableObjs, shouldBeErased);
  1466. //FIXME: how comes our own heroes become inaccessible?
  1467. vstd::erase_if(reservedHeroesMap, [](std::pair<HeroPtr, std::set<const CGObjectInstance *>> hp) -> bool
  1468. {
  1469. return !hp.first.get(true);
  1470. });
  1471. for(auto & p : reservedHeroesMap)
  1472. {
  1473. errorMsg = " shouldn't be on list for hero " + p.first->getNameTranslated() + "!";
  1474. vstd::erase_if(p.second, shouldBeErased);
  1475. }
  1476. errorMsg = " shouldn't be on the reserved objs list!";
  1477. vstd::erase_if(reservedObjs, shouldBeErased);
  1478. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1479. errorMsg = " shouldn't be on the already visited objs list!";
  1480. vstd::erase_if(alreadyVisited, shouldBeErased);
  1481. }
  1482. void VCAI::retrieveVisitableObjs(std::vector<const CGObjectInstance *> & out, bool includeOwned) const
  1483. {
  1484. foreach_tile_pos([&](const int3 & pos)
  1485. {
  1486. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1487. {
  1488. if(includeOwned || obj->tempOwner != playerID)
  1489. out.push_back(obj);
  1490. }
  1491. });
  1492. }
  1493. void VCAI::retrieveVisitableObjs()
  1494. {
  1495. foreach_tile_pos([&](const int3 & pos)
  1496. {
  1497. for(const CGObjectInstance * obj : myCb->getVisitableObjs(pos, false))
  1498. {
  1499. if(obj->tempOwner != playerID)
  1500. addVisitableObj(obj);
  1501. }
  1502. });
  1503. }
  1504. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1505. {
  1506. std::vector<const CGObjectInstance *> ret;
  1507. for(const CGObjectInstance * obj : visitableObjs)
  1508. {
  1509. if(obj->tempOwner == playerID)
  1510. ret.push_back(obj);
  1511. }
  1512. return ret;
  1513. }
  1514. void VCAI::addVisitableObj(const CGObjectInstance * obj)
  1515. {
  1516. if(obj->ID == Obj::EVENT)
  1517. return;
  1518. visitableObjs.insert(obj);
  1519. // All teleport objects seen automatically assigned to appropriate channels
  1520. auto teleportObj = dynamic_cast<const CGTeleport *>(obj);
  1521. if(teleportObj)
  1522. CGTeleport::addToChannel(knownTeleportChannels, teleportObj);
  1523. }
  1524. const CGObjectInstance * VCAI::lookForArt(ArtifactID aid) const
  1525. {
  1526. for(const CGObjectInstance * obj : ai->visitableObjs)
  1527. {
  1528. if(obj->ID == Obj::ARTIFACT && dynamic_cast<const CGArtifact *>(obj)->getArtifactType() == aid)
  1529. return obj;
  1530. }
  1531. return nullptr;
  1532. //TODO what if more than one artifact is available? return them all or some selection criteria
  1533. }
  1534. bool VCAI::isAccessible(const int3 & pos) const
  1535. {
  1536. //TODO precalculate for speed
  1537. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1538. {
  1539. if(isAccessibleForHero(pos, h))
  1540. return true;
  1541. }
  1542. return false;
  1543. }
  1544. HeroPtr VCAI::getHeroWithGrail() const
  1545. {
  1546. for(const CGHeroInstance * h : cb->getHeroesInfo())
  1547. {
  1548. if(h->hasArt(ArtifactID::GRAIL))
  1549. return h;
  1550. }
  1551. return nullptr;
  1552. }
  1553. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> & predicate)
  1554. {
  1555. //TODO smarter definition of unvisited
  1556. for(const CGObjectInstance * obj : visitableObjs)
  1557. {
  1558. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1559. return obj;
  1560. }
  1561. return nullptr;
  1562. }
  1563. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies) const
  1564. {
  1565. // Don't visit tile occupied by allied hero
  1566. if(!includeAllies)
  1567. {
  1568. for(auto obj : cb->getVisitableObjs(pos))
  1569. {
  1570. if(obj->ID == Obj::HERO && cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES)
  1571. {
  1572. if(obj != h.get())
  1573. return false;
  1574. }
  1575. }
  1576. }
  1577. return getPathsInfo(h.get())->getPathInfo(pos)->reachable();
  1578. }
  1579. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1580. {
  1581. //TODO: consider if blockVisit objects change something in our checks: AIUtility::isBlockVisitObj()
  1582. auto afterMovementCheck = [&]() -> void
  1583. {
  1584. waitTillFree(); //movement may cause battle or blocking dialog
  1585. if(!h)
  1586. {
  1587. lostHero(h);
  1588. teleportChannelProbingList.clear();
  1589. if(status.channelProbing()) // if hero lost during channel probing we need to switch this mode off
  1590. status.setChannelProbing(false);
  1591. throw cannotFulfillGoalException("Hero was lost!");
  1592. }
  1593. };
  1594. logAi->debug("Moving hero %s to tile %s", h->getNameTranslated(), dst.toString());
  1595. int3 startHpos = h->visitablePos();
  1596. bool ret = false;
  1597. if(startHpos == dst)
  1598. {
  1599. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1600. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1601. cb->moveHero(*h, h->convertFromVisitablePos(dst), false);
  1602. afterMovementCheck(); // TODO: is it feasible to hero get killed there if game work properly?
  1603. // If revisiting, teleport probing is never done, and so the entries into the list would remain unused and uncleared
  1604. teleportChannelProbingList.clear();
  1605. // not sure if AI can currently reconsider to attack bank while staying on it. Check issue 2084 on mantis for more information.
  1606. ret = true;
  1607. }
  1608. else
  1609. {
  1610. CGPath path;
  1611. getPathsInfo(h.get())->getPath(path, dst);
  1612. if(path.nodes.empty())
  1613. {
  1614. logAi->error("Hero %s cannot reach %s.", h->getNameTranslated(), dst.toString());
  1615. throw goalFulfilledException(sptr(Goals::VisitTile(dst).sethero(h)));
  1616. }
  1617. int i = (int)path.nodes.size() - 1;
  1618. auto getObj = [&](int3 coord, bool ignoreHero)
  1619. {
  1620. return cb->getObj(cb->getTile(coord)->topVisitableObj(ignoreHero));
  1621. };
  1622. auto isTeleportAction = [&](EPathNodeAction action) -> bool
  1623. {
  1624. if(action != EPathNodeAction::TELEPORT_NORMAL && action != EPathNodeAction::TELEPORT_BLOCKING_VISIT)
  1625. {
  1626. if(action != EPathNodeAction::TELEPORT_BATTLE)
  1627. {
  1628. return false;
  1629. }
  1630. }
  1631. return true;
  1632. };
  1633. auto getDestTeleportObj = [&](const CGObjectInstance * currentObject, const CGObjectInstance * nextObjectTop, const CGObjectInstance * nextObject) -> const CGObjectInstance *
  1634. {
  1635. if(CGTeleport::isConnected(currentObject, nextObjectTop))
  1636. return nextObjectTop;
  1637. if(nextObjectTop && nextObjectTop->ID == Obj::HERO)
  1638. {
  1639. if(CGTeleport::isConnected(currentObject, nextObject))
  1640. return nextObject;
  1641. }
  1642. return nullptr;
  1643. };
  1644. auto doMovement = [&](int3 dst, bool transit)
  1645. {
  1646. cb->moveHero(*h, h->convertFromVisitablePos(dst), transit);
  1647. };
  1648. auto doTeleportMovement = [&](ObjectInstanceID exitId, int3 exitPos)
  1649. {
  1650. destinationTeleport = exitId;
  1651. if(exitPos.isValid())
  1652. destinationTeleportPos = exitPos;
  1653. cb->moveHero(*h, h->pos, false);
  1654. destinationTeleport = ObjectInstanceID();
  1655. destinationTeleportPos = int3(-1);
  1656. afterMovementCheck();
  1657. };
  1658. auto doChannelProbing = [&]() -> void
  1659. {
  1660. auto currentPos = h->visitablePos();
  1661. auto currentExit = getObj(currentPos, true)->id;
  1662. status.setChannelProbing(true);
  1663. for(auto exit : teleportChannelProbingList)
  1664. doTeleportMovement(exit, int3(-1));
  1665. teleportChannelProbingList.clear();
  1666. status.setChannelProbing(false);
  1667. doTeleportMovement(currentExit, currentPos);
  1668. };
  1669. for(; i > 0; i--)
  1670. {
  1671. int3 currentCoord = path.nodes[i].coord;
  1672. int3 nextCoord = path.nodes[i - 1].coord;
  1673. auto currentObject = getObj(currentCoord, currentCoord == h->visitablePos());
  1674. auto nextObjectTop = getObj(nextCoord, false);
  1675. auto nextObject = getObj(nextCoord, true);
  1676. auto destTeleportObj = getDestTeleportObj(currentObject, nextObjectTop, nextObject);
  1677. if(isTeleportAction(path.nodes[i - 1].action) && destTeleportObj != nullptr)
  1678. {
  1679. //we use special login if hero standing on teleporter it's mean we need
  1680. doTeleportMovement(destTeleportObj->id, nextCoord);
  1681. if(teleportChannelProbingList.size())
  1682. doChannelProbing();
  1683. markObjectVisited(destTeleportObj); //FIXME: Monoliths are not correctly visited
  1684. continue;
  1685. }
  1686. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1687. if(path.nodes[i - 1].turns)
  1688. {
  1689. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1690. break;
  1691. }
  1692. int3 endpos = path.nodes[i - 1].coord;
  1693. if(endpos == h->visitablePos())
  1694. continue;
  1695. bool isConnected = false;
  1696. bool isNextObjectTeleport = false;
  1697. // Check there is node after next one; otherwise transit is pointless
  1698. if(i - 2 >= 0)
  1699. {
  1700. isConnected = CGTeleport::isConnected(nextObjectTop, getObj(path.nodes[i - 2].coord, false));
  1701. isNextObjectTeleport = CGTeleport::isTeleport(nextObjectTop);
  1702. }
  1703. if(isConnected || isNextObjectTeleport)
  1704. {
  1705. // Hero should be able to go through object if it's allow transit
  1706. doMovement(endpos, true);
  1707. }
  1708. else if(path.nodes[i - 1].layer == EPathfindingLayer::AIR)
  1709. {
  1710. doMovement(endpos, true);
  1711. }
  1712. else
  1713. {
  1714. doMovement(endpos, false);
  1715. }
  1716. afterMovementCheck();
  1717. if(teleportChannelProbingList.size())
  1718. doChannelProbing();
  1719. }
  1720. if(path.nodes[0].action == EPathNodeAction::BLOCKING_VISIT)
  1721. {
  1722. ret = h && i == 0; // when we take resource we do not reach its position. We even might not move
  1723. }
  1724. }
  1725. if(h)
  1726. {
  1727. if(auto visitedObject = vstd::frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1728. {
  1729. if(visitedObject != *h)
  1730. performObjectInteraction(visitedObject, h);
  1731. }
  1732. }
  1733. if(h) //we could have lost hero after last move
  1734. {
  1735. completeGoal(sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1736. completeGoal(sptr(Goals::ClearWayTo(dst).sethero(h)));
  1737. ret = ret || (dst == h->visitablePos());
  1738. if(!ret) //reserve object we are heading towards
  1739. {
  1740. auto obj = vstd::frontOrNull(cb->getVisitableObjs(dst));
  1741. if(obj && obj != *h)
  1742. reserveObject(h, obj);
  1743. }
  1744. if(startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1745. {
  1746. vstd::erase_if_present(lockedHeroes, h); //hero seemingly is confused or has only 95mp which is not enough to move
  1747. invalidPathHeroes.insert(h);
  1748. throw cannotFulfillGoalException("Invalid path found!");
  1749. }
  1750. evaluateGoal(h); //new hero position means new game situation
  1751. logAi->debug("Hero %s moved from %s to %s. Returning %d.", h->getNameTranslated(), startHpos.toString(), h->visitablePos().toString(), ret);
  1752. }
  1753. return ret;
  1754. }
  1755. void VCAI::buildStructure(const CGTownInstance * t, BuildingID building)
  1756. {
  1757. auto name = t->getTown()->buildings.at(building)->getNameTranslated();
  1758. logAi->debug("Player %d will build %s in town of %s at %s", ai->playerID, name, t->getNameTranslated(), t->anchorPos().toString());
  1759. cb->buildBuilding(t, building); //just do this;
  1760. }
  1761. void VCAI::tryRealize(Goals::Explore & g)
  1762. {
  1763. throw cannotFulfillGoalException("EXPLORE is not an elementar goal!");
  1764. }
  1765. void VCAI::tryRealize(Goals::RecruitHero & g)
  1766. {
  1767. if(cb->getResourceAmount(EGameResID::GOLD) < GameConstants::HERO_GOLD_COST)
  1768. throw cannotFulfillGoalException("Not enough gold to recruit hero!");
  1769. if(const CGTownInstance * t = findTownWithTavern())
  1770. {
  1771. recruitHero(t, true);
  1772. //TODO try to free way to blocked town
  1773. //TODO: adventure map tavern or prison?
  1774. }
  1775. else
  1776. {
  1777. throw cannotFulfillGoalException("No town to recruit hero!");
  1778. }
  1779. }
  1780. void VCAI::tryRealize(Goals::VisitTile & g)
  1781. {
  1782. if(!g.hero->movementPointsRemaining())
  1783. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1784. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1785. {
  1786. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1787. throw goalFulfilledException(sptr(g));
  1788. }
  1789. if(ai->moveHeroToTile(g.tile, g.hero.get()))
  1790. {
  1791. throw goalFulfilledException(sptr(g));
  1792. }
  1793. }
  1794. void VCAI::tryRealize(Goals::VisitObj & g)
  1795. {
  1796. auto position = g.tile;
  1797. if(!g.hero->movementPointsRemaining())
  1798. throw cannotFulfillGoalException("Cannot visit object: hero is out of MPs!");
  1799. if(position == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1800. {
  1801. logAi->warn("Why do I want to move hero %s to tile %s? Already standing on that tile! ", g.hero->getNameTranslated(), g.tile.toString());
  1802. throw goalFulfilledException(sptr(g));
  1803. }
  1804. if(ai->moveHeroToTile(position, g.hero.get()))
  1805. {
  1806. throw goalFulfilledException(sptr(g));
  1807. }
  1808. }
  1809. void VCAI::tryRealize(Goals::VisitHero & g)
  1810. {
  1811. if(!g.hero->movementPointsRemaining())
  1812. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1813. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1814. if(obj)
  1815. {
  1816. if(ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1817. {
  1818. throw goalFulfilledException(sptr(g));
  1819. }
  1820. }
  1821. else
  1822. {
  1823. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1824. }
  1825. }
  1826. void VCAI::tryRealize(Goals::BuildThis & g)
  1827. {
  1828. auto b = BuildingID(g.bid);
  1829. auto t = g.town;
  1830. if (t)
  1831. {
  1832. if (cb->canBuildStructure(t, b) == EBuildingState::ALLOWED)
  1833. {
  1834. logAi->debug("Player %d will build %s in town of %s at %s",
  1835. playerID, t->getTown()->buildings.at(b)->getNameTranslated(), t->getNameTranslated(), t->anchorPos().toString());
  1836. cb->buildBuilding(t, b);
  1837. throw goalFulfilledException(sptr(g));
  1838. }
  1839. }
  1840. throw cannotFulfillGoalException("Cannot build a given structure!");
  1841. }
  1842. void VCAI::tryRealize(Goals::DigAtTile & g)
  1843. {
  1844. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1845. if(g.hero->diggingStatus() == EDiggingStatus::CAN_DIG)
  1846. {
  1847. cb->dig(g.hero.get());
  1848. completeGoal(sptr(g)); // finished digging
  1849. }
  1850. else
  1851. {
  1852. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1853. throw cannotFulfillGoalException("A hero can't dig!\n");
  1854. }
  1855. }
  1856. void VCAI::tryRealize(Goals::Trade & g) //trade
  1857. {
  1858. if(ah->freeResources()[g.resID] >= g.value) //goal is already fulfilled. Why we need this check, anyway?
  1859. throw goalFulfilledException(sptr(g));
  1860. int acquiredResources = 0;
  1861. if(const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1862. {
  1863. if(const auto * m = dynamic_cast<const IMarket*>(obj))
  1864. {
  1865. auto freeRes = ah->freeResources(); //trade only resources which are not reserved
  1866. for(auto it = ResourceSet::nziterator(freeRes); it.valid(); it++)
  1867. {
  1868. auto res = it->resType;
  1869. if(res.getNum() == g.resID) //sell any other resource
  1870. continue;
  1871. int toGive;
  1872. int toGet;
  1873. m->getOffer(res.getNum(), g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1874. toGive = static_cast<int>(toGive * (it->resVal / toGive)); //round down
  1875. //TODO trade only as much as needed
  1876. if (toGive) //don't try to sell 0 resources
  1877. {
  1878. cb->trade(m->getObjInstanceID(), EMarketMode::RESOURCE_RESOURCE, res, GameResID(g.resID), toGive);
  1879. acquiredResources = static_cast<int>(toGet * (it->resVal / toGive));
  1880. logAi->debug("Traded %d of %s for %d of %s at %s", toGive, res, acquiredResources, g.resID, obj->getObjectName());
  1881. }
  1882. if (ah->freeResources()[g.resID] >= g.value)
  1883. throw goalFulfilledException(sptr(g)); //we traded all we needed
  1884. }
  1885. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1886. }
  1887. else
  1888. {
  1889. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1890. }
  1891. }
  1892. else
  1893. {
  1894. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1895. }
  1896. }
  1897. void VCAI::tryRealize(Goals::BuyArmy & g)
  1898. {
  1899. auto t = g.town;
  1900. ui64 valueBought = 0;
  1901. //buy the stacks with largest AI value
  1902. makePossibleUpgrades(t);
  1903. while (valueBought < g.value)
  1904. {
  1905. auto res = ah->allResources();
  1906. std::vector<creInfo> creaturesInDwellings;
  1907. for (int i = 0; i < t->creatures.size(); i++)
  1908. {
  1909. auto ci = infoFromDC(t->creatures[i]);
  1910. if(!ci.count
  1911. || ci.creID == CreatureID::NONE
  1912. || (g.objid != -1 && ci.creID.getNum() != g.objid)
  1913. || t->getUpperArmy()->getSlotFor(ci.creID) == SlotID())
  1914. continue;
  1915. vstd::amin(ci.count, res / ci.cre->getFullRecruitCost()); //max count we can afford
  1916. if(!ci.count)
  1917. continue;
  1918. ci.level = i; //this is important for Dungeon Summoning Portal
  1919. creaturesInDwellings.push_back(ci);
  1920. }
  1921. if (creaturesInDwellings.empty())
  1922. throw cannotFulfillGoalException("Can't buy any more creatures!");
  1923. creInfo ci =
  1924. *boost::max_element(creaturesInDwellings, [](const creInfo & lhs, const creInfo & rhs)
  1925. {
  1926. //max value of creatures we can buy with our res
  1927. int value1 = lhs.cre->getAIValue() * lhs.count;
  1928. int value2 = rhs.cre->getAIValue() * rhs.count;
  1929. return value1 < value2;
  1930. });
  1931. cb->recruitCreatures(t, t->getUpperArmy(), ci.creID, ci.count, ci.level);
  1932. valueBought += ci.count * ci.cre->getAIValue();
  1933. }
  1934. throw goalFulfilledException(sptr(g)); //we bought as many creatures as we wanted
  1935. }
  1936. void VCAI::tryRealize(Goals::Invalid & g)
  1937. {
  1938. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1939. }
  1940. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1941. {
  1942. logAi->debug("Attempting realizing goal with code %s", g.name());
  1943. throw cannotFulfillGoalException("Unknown type of goal !");
  1944. }
  1945. const CGTownInstance * VCAI::findTownWithTavern() const
  1946. {
  1947. for(const CGTownInstance * t : cb->getTownsInfo())
  1948. if(t->hasBuilt(BuildingID::TAVERN) && !t->getVisitingHero())
  1949. return t;
  1950. return nullptr;
  1951. }
  1952. Goals::TSubgoal VCAI::getGoal(HeroPtr h) const
  1953. {
  1954. auto it = lockedHeroes.find(h);
  1955. if(it != lockedHeroes.end())
  1956. return it->second;
  1957. else
  1958. return sptr(Goals::Invalid());
  1959. }
  1960. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1961. {
  1962. std::vector<HeroPtr> ret;
  1963. for(auto h : cb->getHeroesInfo())
  1964. {
  1965. //&& !vstd::contains(lockedHeroes, h)
  1966. //at this point we assume heroes exhausted their locked goals
  1967. if(canAct(h))
  1968. ret.push_back(h);
  1969. }
  1970. return ret;
  1971. }
  1972. bool VCAI::canAct(HeroPtr h) const
  1973. {
  1974. auto mission = lockedHeroes.find(h);
  1975. if(mission != lockedHeroes.end())
  1976. {
  1977. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1978. if(mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1979. return false;
  1980. }
  1981. return h->movementPointsRemaining();
  1982. }
  1983. HeroPtr VCAI::primaryHero() const
  1984. {
  1985. auto hs = cb->getHeroesInfo();
  1986. if (hs.empty())
  1987. return nullptr;
  1988. else
  1989. return *boost::max_element(hs, compareHeroStrength);
  1990. }
  1991. void VCAI::endTurn()
  1992. {
  1993. logAi->info("Player %d (%s) ends turn", playerID, playerID.toString());
  1994. if(!status.haveTurn())
  1995. {
  1996. logAi->error("Not having turn at the end of turn???");
  1997. }
  1998. logAi->debug("Resources at the end of turn: %s", cb->getResourceAmount().toString());
  1999. do
  2000. {
  2001. cb->endTurn();
  2002. }
  2003. 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
  2004. logGlobal->info("Player %d (%s) ended turn", playerID, playerID.toString());
  2005. }
  2006. void VCAI::striveToGoal(Goals::TSubgoal basicGoal)
  2007. {
  2008. //TODO: this function is deprecated and should be dropped altogether
  2009. auto goalToDecompose = basicGoal;
  2010. Goals::TSubgoal elementarGoal = sptr(Goals::Invalid());
  2011. int maxAbstractGoals = 10;
  2012. while (!elementarGoal->isElementar && maxAbstractGoals)
  2013. {
  2014. try
  2015. {
  2016. elementarGoal = decomposeGoal(goalToDecompose);
  2017. }
  2018. catch (goalFulfilledException & e)
  2019. {
  2020. //it is impossible to continue some goals (like exploration, for example)
  2021. completeGoal(e.goal); //put in goalsToRemove
  2022. logAi->debug("Goal %s decomposition failed: goal was completed as much as possible", e.goal->name());
  2023. return;
  2024. }
  2025. catch (std::exception & e)
  2026. {
  2027. goalsToRemove.push_back(basicGoal);
  2028. logAi->debug("Goal %s decomposition failed: %s", basicGoal->name(), e.what());
  2029. return;
  2030. }
  2031. if (elementarGoal->isAbstract) //we can decompose it further
  2032. {
  2033. goalsToAdd.push_back(elementarGoal);
  2034. //decompose further now - this is necesssary if we can't add over 10 goals in the pool
  2035. goalToDecompose = elementarGoal;
  2036. //there is a risk of infinite abstract goal loop, though it indicates failed logic
  2037. maxAbstractGoals--;
  2038. }
  2039. else if (elementarGoal->isElementar) //should be
  2040. {
  2041. logAi->debug("Found elementar goal %s", elementarGoal->name());
  2042. ultimateGoalsFromBasic[elementarGoal].push_back(goalToDecompose); //TODO: how about indirect basicGoal?
  2043. break;
  2044. }
  2045. else //should never be here
  2046. throw cannotFulfillGoalException("Goal %s is neither abstract nor elementar!" + basicGoal->name());
  2047. }
  2048. //realize best goal
  2049. if (!elementarGoal->invalid())
  2050. {
  2051. logAi->debug("Trying to realize %s (value %2.3f)", elementarGoal->name(), elementarGoal->priority);
  2052. try
  2053. {
  2054. makingTurnInterrupption.interruptionPoint();
  2055. elementarGoal->accept(this); //visitor pattern
  2056. makingTurnInterrupption.interruptionPoint();
  2057. }
  2058. catch (const TerminationRequestedException &)
  2059. {
  2060. logAi->debug("Player %d: Making turn thread received an interruption!", playerID);
  2061. throw; //rethrow, we want to truly end this thread
  2062. }
  2063. catch (const goalFulfilledException & e)
  2064. {
  2065. //the sub-goal was completed successfully
  2066. completeGoal(e.goal);
  2067. //local goal was also completed
  2068. completeGoal(elementarGoal);
  2069. }
  2070. catch (const std::exception & e)
  2071. {
  2072. logAi->debug("Failed to realize subgoal of type %s, I will stop.", elementarGoal->name());
  2073. logAi->debug("The error message was: %s", e.what());
  2074. //erase base goal if we failed to execute decomposed goal
  2075. for (auto basicGoalToRemove : ultimateGoalsFromBasic[elementarGoal])
  2076. goalsToRemove.push_back(basicGoalToRemove);
  2077. }
  2078. }
  2079. }
  2080. Goals::TSubgoal VCAI::decomposeGoal(Goals::TSubgoal ultimateGoal)
  2081. {
  2082. if(ultimateGoal->isElementar)
  2083. {
  2084. logAi->warn("Trying to decompose elementar goal %s", ultimateGoal->name());
  2085. return ultimateGoal;
  2086. }
  2087. const int searchDepth = 30;
  2088. Goals::TSubgoal goal = ultimateGoal;
  2089. logAi->debug("Decomposing goal %s", ultimateGoal->name());
  2090. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  2091. while (maxGoals)
  2092. {
  2093. makingTurnInterrupption.interruptionPoint();
  2094. goal = goal->whatToDoToAchieve(); //may throw if decomposition fails
  2095. --maxGoals;
  2096. if (goal == ultimateGoal) //compare objects by value
  2097. if (goal->isElementar == ultimateGoal->isElementar)
  2098. throw cannotFulfillGoalException((boost::format("Goal dependency loop detected for %s!")
  2099. % ultimateGoal->name()).str());
  2100. if (goal->isAbstract || goal->isElementar)
  2101. return goal;
  2102. else
  2103. logAi->debug("Considering: %s", goal->name());
  2104. }
  2105. throw cannotFulfillGoalException("Too many subgoals, don't know what to do");
  2106. }
  2107. void VCAI::performTypicalActions()
  2108. {
  2109. for(auto h : getUnblockedHeroes())
  2110. {
  2111. if(!h) //hero might be lost. getUnblockedHeroes() called once on start of turn
  2112. continue;
  2113. logAi->debug("Hero %s started wandering, MP=%d", h->getNameTranslated(), h->movementPointsRemaining());
  2114. makePossibleUpgrades(*h);
  2115. pickBestArtifacts(*h);
  2116. try
  2117. {
  2118. wander(h);
  2119. }
  2120. catch(std::exception & e)
  2121. {
  2122. logAi->debug("Cannot use this hero anymore, received exception: %s", e.what());
  2123. continue;
  2124. }
  2125. }
  2126. }
  2127. void VCAI::buildArmyIn(const CGTownInstance * t)
  2128. {
  2129. makePossibleUpgrades(t->getVisitingHero());
  2130. makePossibleUpgrades(t);
  2131. recruitCreatures(t, t->getUpperArmy());
  2132. moveCreaturesToHero(t);
  2133. }
  2134. void VCAI::checkHeroArmy(HeroPtr h)
  2135. {
  2136. auto it = lockedHeroes.find(h);
  2137. if(it != lockedHeroes.end())
  2138. {
  2139. if(it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2140. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2141. }
  2142. }
  2143. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2144. {
  2145. logAi->debug("Trying to recruit a hero in %s at %s", t->getNameTranslated(), t->visitablePos().toString());
  2146. auto heroes = cb->getAvailableHeroes(t);
  2147. if(heroes.size())
  2148. {
  2149. auto hero = heroes[0];
  2150. if(heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2151. {
  2152. if(heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2153. hero = heroes[1];
  2154. }
  2155. cb->recruitHero(t, hero);
  2156. throw goalFulfilledException(sptr(Goals::RecruitHero().settown(t)));
  2157. }
  2158. else if(throwing)
  2159. {
  2160. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2161. }
  2162. }
  2163. void VCAI::finish()
  2164. {
  2165. makingTurnInterrupption.interruptThread();
  2166. if (asyncTasks)
  2167. {
  2168. asyncTasks->wait();
  2169. asyncTasks.reset();
  2170. }
  2171. }
  2172. void VCAI::executeActionAsync(const std::string & description, const std::function<void()> & whatToDo)
  2173. {
  2174. if (!asyncTasks)
  2175. throw std::runtime_error("Attempt to execute task on shut down AI state!");
  2176. asyncTasks->run([this, description, whatToDo]()
  2177. {
  2178. ScopedThreadName guard("VCAI::" + description);
  2179. SET_GLOBAL_STATE(this);
  2180. std::shared_lock gsLock(CGameState::mutex);
  2181. whatToDo();
  2182. });
  2183. }
  2184. void VCAI::lostHero(HeroPtr h)
  2185. {
  2186. logAi->debug("I lost my hero %s. It's best to forget and move on.", h.name);
  2187. vstd::erase_if_present(lockedHeroes, h);
  2188. for(auto obj : reservedHeroesMap[h])
  2189. {
  2190. vstd::erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2191. }
  2192. vstd::erase_if_present(reservedHeroesMap, h);
  2193. vstd::erase_if_present(visitedHeroes, h);
  2194. for (auto heroVec : visitedHeroes)
  2195. {
  2196. vstd::erase_if_present(heroVec.second, h);
  2197. }
  2198. //remove goals with removed hero assigned from main loop
  2199. vstd::erase_if(ultimateGoalsFromBasic, [&](const std::pair<Goals::TSubgoal, Goals::TGoalVec> & x) -> bool
  2200. {
  2201. if(x.first->hero == h)
  2202. return true;
  2203. else
  2204. return false;
  2205. });
  2206. auto removedHeroGoalPredicate = [&](const Goals::TSubgoal & x) ->bool
  2207. {
  2208. if(x->hero == h)
  2209. return true;
  2210. else
  2211. return false;
  2212. };
  2213. vstd::erase_if(basicGoals, removedHeroGoalPredicate);
  2214. vstd::erase_if(goalsToAdd, removedHeroGoalPredicate);
  2215. vstd::erase_if(goalsToRemove, removedHeroGoalPredicate);
  2216. for(auto goal : ultimateGoalsFromBasic)
  2217. vstd::erase_if(goal.second, removedHeroGoalPredicate);
  2218. }
  2219. void VCAI::answerQuery(QueryID queryID, int selection)
  2220. {
  2221. logAi->debug("I'll answer the query %d giving the choice %d", queryID, selection);
  2222. if(queryID != QueryID(-1))
  2223. {
  2224. cb->selectionMade(selection, queryID);
  2225. }
  2226. else
  2227. {
  2228. logAi->debug("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2229. //do nothing
  2230. }
  2231. }
  2232. void VCAI::requestSent(const CPackForServer * pack, int requestID)
  2233. {
  2234. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2235. if(auto reply = dynamic_cast<const QueryReply *>(pack))
  2236. {
  2237. status.attemptedAnsweringQuery(reply->qid, requestID);
  2238. }
  2239. }
  2240. std::string VCAI::getBattleAIName() const
  2241. {
  2242. if(settings["server"]["enemyAI"].getType() == JsonNode::JsonType::DATA_STRING)
  2243. return settings["server"]["enemyAI"].String();
  2244. else
  2245. return "BattleAI";
  2246. }
  2247. void VCAI::validateObject(const CGObjectInstance * obj)
  2248. {
  2249. validateObject(obj->id);
  2250. }
  2251. void VCAI::validateObject(ObjectIdRef obj)
  2252. {
  2253. auto matchesId = [&](const CGObjectInstance * hlpObj) -> bool
  2254. {
  2255. return hlpObj->id == obj.id;
  2256. };
  2257. if(!obj)
  2258. {
  2259. vstd::erase_if(visitableObjs, matchesId);
  2260. for(auto & p : reservedHeroesMap)
  2261. vstd::erase_if(p.second, matchesId);
  2262. vstd::erase_if(reservedObjs, matchesId);
  2263. }
  2264. }
  2265. AIStatus::AIStatus()
  2266. {
  2267. battle = NO_BATTLE;
  2268. havingTurn = false;
  2269. ongoingHeroMovement = false;
  2270. ongoingChannelProbing = false;
  2271. }
  2272. AIStatus::~AIStatus()
  2273. {
  2274. }
  2275. void AIStatus::setBattle(BattleState BS)
  2276. {
  2277. std::unique_lock<std::mutex> lock(mx);
  2278. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2279. battle = BS;
  2280. cv.notify_all();
  2281. }
  2282. BattleState AIStatus::getBattle()
  2283. {
  2284. std::unique_lock<std::mutex> lock(mx);
  2285. return battle;
  2286. }
  2287. void AIStatus::addQuery(QueryID ID, std::string description)
  2288. {
  2289. if(ID == QueryID(-1))
  2290. {
  2291. logAi->debug("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID, description);
  2292. return;
  2293. }
  2294. assert(ID.getNum() >= 0);
  2295. std::unique_lock<std::mutex> lock(mx);
  2296. assert(!vstd::contains(remainingQueries, ID));
  2297. remainingQueries[ID] = description;
  2298. cv.notify_all();
  2299. logAi->debug("Adding query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2300. }
  2301. void AIStatus::removeQuery(QueryID ID)
  2302. {
  2303. std::unique_lock<std::mutex> lock(mx);
  2304. assert(vstd::contains(remainingQueries, ID));
  2305. std::string description = remainingQueries[ID];
  2306. remainingQueries.erase(ID);
  2307. cv.notify_all();
  2308. logAi->debug("Removing query %d - %s. Total queries count: %d", ID, description, remainingQueries.size());
  2309. }
  2310. int AIStatus::getQueriesCount()
  2311. {
  2312. std::unique_lock<std::mutex> lock(mx);
  2313. return static_cast<int>(remainingQueries.size());
  2314. }
  2315. void AIStatus::startedTurn()
  2316. {
  2317. std::unique_lock<std::mutex> lock(mx);
  2318. havingTurn = true;
  2319. cv.notify_all();
  2320. }
  2321. void AIStatus::madeTurn()
  2322. {
  2323. std::unique_lock<std::mutex> lock(mx);
  2324. havingTurn = false;
  2325. cv.notify_all();
  2326. }
  2327. void AIStatus::waitTillFree()
  2328. {
  2329. std::unique_lock<std::mutex> lock(mx);
  2330. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2331. cv.wait_for(lock, std::chrono::milliseconds(100));
  2332. }
  2333. bool AIStatus::haveTurn()
  2334. {
  2335. std::unique_lock<std::mutex> lock(mx);
  2336. return havingTurn;
  2337. }
  2338. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2339. {
  2340. std::unique_lock<std::mutex> lock(mx);
  2341. assert(vstd::contains(remainingQueries, queryID));
  2342. std::string description = remainingQueries[queryID];
  2343. logAi->debug("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID, description, answerRequestID);
  2344. requestToQueryID[answerRequestID] = queryID;
  2345. }
  2346. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2347. {
  2348. QueryID query;
  2349. {
  2350. std::unique_lock<std::mutex> lock(mx);
  2351. assert(vstd::contains(requestToQueryID, answerRequestID));
  2352. query = requestToQueryID[answerRequestID];
  2353. assert(vstd::contains(remainingQueries, query));
  2354. requestToQueryID.erase(answerRequestID);
  2355. }
  2356. if(result)
  2357. {
  2358. removeQuery(query);
  2359. }
  2360. else
  2361. {
  2362. logAi->error("Something went really wrong, failed to answer query %d : %s", query.getNum(), remainingQueries[query]);
  2363. //TODO safely retry
  2364. }
  2365. }
  2366. void AIStatus::heroVisit(const CGObjectInstance * obj, bool started)
  2367. {
  2368. std::unique_lock<std::mutex> lock(mx);
  2369. if(started)
  2370. {
  2371. objectsBeingVisited.push_back(obj);
  2372. }
  2373. else
  2374. {
  2375. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2376. // causing visit to hero on the other side.
  2377. // However, we are guaranteed that start/end visit notification maintain stack order.
  2378. assert(!objectsBeingVisited.empty());
  2379. objectsBeingVisited.pop_back();
  2380. }
  2381. cv.notify_all();
  2382. }
  2383. void AIStatus::setMove(bool ongoing)
  2384. {
  2385. std::unique_lock<std::mutex> lock(mx);
  2386. ongoingHeroMovement = ongoing;
  2387. cv.notify_all();
  2388. }
  2389. void AIStatus::setChannelProbing(bool ongoing)
  2390. {
  2391. std::unique_lock<std::mutex> lock(mx);
  2392. ongoingChannelProbing = ongoing;
  2393. cv.notify_all();
  2394. }
  2395. bool AIStatus::channelProbing()
  2396. {
  2397. return ongoingChannelProbing;
  2398. }
  2399. bool isWeeklyRevisitable(const CGObjectInstance * obj)
  2400. {
  2401. //TODO: allow polling of remaining creatures in dwelling
  2402. if(const auto * rewardable = dynamic_cast<const CRewardableObject *>(obj))
  2403. return rewardable->configuration.getResetDuration() == 7;
  2404. if(dynamic_cast<const CGDwelling *>(obj))
  2405. return true;
  2406. switch(obj->ID)
  2407. {
  2408. case Obj::STABLES:
  2409. case Obj::MAGIC_WELL:
  2410. case Obj::HILL_FORT:
  2411. return true;
  2412. case Obj::BORDER_GATE:
  2413. case Obj::BORDERGUARD:
  2414. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID); //FIXME: they could be revisited sooner than in a week
  2415. }
  2416. return false;
  2417. }
  2418. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2419. {
  2420. switch(obj->ID)
  2421. {
  2422. case Obj::TOWN:
  2423. case Obj::HERO: //never visit our heroes at random
  2424. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2425. case Obj::BORDER_GATE:
  2426. {
  2427. for(auto q : ai->myCb->getMyQuests())
  2428. {
  2429. if(q.getObject(cb) == obj)
  2430. {
  2431. return false; // do not visit guards or gates when wandering
  2432. }
  2433. }
  2434. return true; //we don't have this quest yet
  2435. }
  2436. case Obj::BORDERGUARD: //open borderguard if possible
  2437. return (dynamic_cast<const CGKeys *>(obj))->wasMyColorVisited(ai->playerID);
  2438. case Obj::SEER_HUT:
  2439. case Obj::QUEST_GUARD:
  2440. {
  2441. for(auto q : ai->myCb->getMyQuests())
  2442. {
  2443. if(q.getObject(cb) == obj)
  2444. {
  2445. if(q.getQuest(cb)->checkQuest(h.h))
  2446. return true; //we completed the quest
  2447. else
  2448. return false; //we can't complete this quest
  2449. }
  2450. }
  2451. return true; //we don't have this quest yet
  2452. }
  2453. case Obj::CREATURE_GENERATOR1:
  2454. {
  2455. if(obj->tempOwner != h->tempOwner)
  2456. return true; //flag just in case
  2457. bool canRecruitCreatures = false;
  2458. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2459. for(auto level : d->creatures)
  2460. {
  2461. for(auto c : level.second)
  2462. {
  2463. if(h->getSlotFor(CreatureID(c)) != SlotID())
  2464. canRecruitCreatures = true;
  2465. }
  2466. }
  2467. return canRecruitCreatures;
  2468. }
  2469. case Obj::HILL_FORT:
  2470. {
  2471. for(const auto & slot : h->Slots())
  2472. {
  2473. if(slot.second->getType()->hasUpgrades())
  2474. return true; //TODO: check price?
  2475. }
  2476. return false;
  2477. }
  2478. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2479. case Obj::MONOLITH_ONE_WAY_EXIT:
  2480. case Obj::MONOLITH_TWO_WAY:
  2481. case Obj::WHIRLPOOL:
  2482. return false;
  2483. case Obj::SCHOOL_OF_MAGIC:
  2484. case Obj::SCHOOL_OF_WAR:
  2485. {
  2486. if (ai->ah->freeGold() < 1000)
  2487. return false;
  2488. break;
  2489. }
  2490. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2491. if(h->level < 12)
  2492. return false;
  2493. break;
  2494. case Obj::TREE_OF_KNOWLEDGE:
  2495. {
  2496. TResources myRes = ai->ah->freeResources();
  2497. if(myRes[EGameResID::GOLD] < 2000 || myRes[EGameResID::GEMS] < 10)
  2498. return false;
  2499. break;
  2500. }
  2501. case Obj::MAGIC_WELL:
  2502. return h->mana < h->manaLimit();
  2503. case Obj::PRISON:
  2504. return ai->myCb->getHeroesInfo().size() < cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP);
  2505. case Obj::TAVERN:
  2506. {
  2507. //TODO: make AI actually recruit heroes
  2508. //TODO: only on request
  2509. if(ai->myCb->getHeroesInfo().size() >= cb->getSettings().getInteger(EGameSettings::HEROES_PER_PLAYER_ON_MAP_CAP))
  2510. return false;
  2511. else if(ai->ah->freeGold() < GameConstants::HERO_GOLD_COST)
  2512. return false;
  2513. break;
  2514. }
  2515. case Obj::BOAT:
  2516. return false;
  2517. //Boats are handled by pathfinder
  2518. case Obj::EYE_OF_MAGI:
  2519. return false; //this object is useless to visit, but could be visited indefinitely
  2520. }
  2521. if(obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2522. return false;
  2523. return true;
  2524. }
  2525. std::optional<BattleAction> VCAI::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  2526. {
  2527. return std::nullopt;
  2528. }