VCAI.cpp 88 KB

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