VCAI.cpp 81 KB

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