VCAI.cpp 89 KB

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