VCAI.cpp 82 KB

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