VCAI.cpp 82 KB

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