VCAI.cpp 98 KB

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