VCAI.cpp 92 KB

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