VCAI.cpp 80 KB

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