VCAI.cpp 91 KB

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