VCAI.cpp 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "../../lib/UnlockGuard.h"
  4. #include "../../lib/CObjectHandler.h"
  5. #include "../../lib/CConfigHandler.h"
  6. #define I_AM_ELEMENTAR return CGoal(*this).setisElementar(true)
  7. CLogger &aiLogger = tlog6;
  8. extern FuzzyHelper *fh;
  9. class CGVisitableOPW;
  10. const int ACTUAL_RESOURCE_COUNT = 7;
  11. const double SAFE_ATTACK_CONSTANT = 1.5;
  12. using namespace vstd;
  13. //one thread may be turn of AI and another will be handling a side effect for AI2
  14. boost::thread_specific_ptr<CCallback> cb;
  15. boost::thread_specific_ptr<VCAI> ai;
  16. //std::map<int, std::map<int, int> > HeroView::infosCount;
  17. // CCallback *cb;
  18. // VCAI *ai;
  19. //helper RAII to manage global ai/cb ptrs
  20. struct SetGlobalState
  21. {
  22. SetGlobalState(VCAI * AI)
  23. {
  24. assert(!ai.get());
  25. assert(!cb.get());
  26. ai.reset(AI);
  27. cb.reset(AI->myCb);
  28. }
  29. ~SetGlobalState()
  30. {
  31. ai.release();
  32. cb.release();
  33. }
  34. };
  35. template <typename Container>
  36. typename Container::value_type backOrNull(const Container &c) //returns last element of container or NULL if it is empty (to be used with containers of pointers)
  37. {
  38. if(c.size())
  39. return c.back();
  40. else
  41. return NULL;
  42. }
  43. template <typename Container>
  44. typename Container::value_type frontOrNull(const Container &c) //returns first element of container or NULL if it is empty (to be used with containers of pointers)
  45. {
  46. if(c.size())
  47. return c.front();
  48. else
  49. return NULL;
  50. }
  51. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  52. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  53. #define MAKING_TURN SET_GLOBAL_STATE(this)
  54. 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)
  55. const int HERO_GOLD_COST = 2500;
  56. const int ALLOWED_ROAMING_HEROES = 8;
  57. const int GOLD_MINE_PRODUCTION = 1000, WOOD_ORE_MINE_PRODUCTION = 2, RESOURCE_MINE_PRODUCTION = 1;
  58. std::string goalName(EGoals goalType)
  59. {
  60. switch (goalType)
  61. {
  62. case INVALID:
  63. return "INVALID";
  64. case WIN:
  65. return "WIN";
  66. case DO_NOT_LOSE:
  67. return "DO NOT LOOSE";
  68. case CONQUER:
  69. return "CONQUER";
  70. case BUILD:
  71. return "BUILD";
  72. case EXPLORE:
  73. return "EXPLORE";
  74. case GATHER_ARMY:
  75. return "GATHER ARMY";
  76. case BOOST_HERO:
  77. return "BOOST_HERO (unsupported)";
  78. case BUILD_STRUCTURE:
  79. return "BUILD STRUCTURE";
  80. case COLLECT_RES:
  81. return "COLLECT RESOURCE";
  82. case GET_OBJ:
  83. return "GET OBJECT";
  84. case FIND_OBJ:
  85. return "FIND OBJECT";
  86. case VISIT_HERO:
  87. return "VISIT HERO";
  88. case GET_ART_TYPE:
  89. return "GET ARTIFACT OF TYPE";
  90. case ISSUE_COMMAND:
  91. return "ISSUE COMMAND (unsupported)";
  92. case VISIT_TILE:
  93. return "VISIT TILE";
  94. case CLEAR_WAY_TO:
  95. return "CLEAR WAY TO";
  96. case DIG_AT_TILE:
  97. return "DIG AT TILE";
  98. default:
  99. return boost::lexical_cast<std::string>(goalType);
  100. }
  101. }
  102. bool compareHeroStrength(HeroPtr h1, HeroPtr h2)
  103. {
  104. return h1->getTotalStrength() < h2->getTotalStrength();
  105. }
  106. bool compareArmyStrength(const CArmedInstance *a1, const CArmedInstance *a2)
  107. {
  108. return a1->getArmyStrength() < a2->getArmyStrength();
  109. }
  110. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  111. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  112. struct AILogger
  113. {
  114. AILogger()
  115. {
  116. lvl = 0;
  117. }
  118. int lvl;
  119. struct Tab
  120. {
  121. Tab();
  122. ~Tab();
  123. };
  124. } logger;
  125. AILogger::Tab::Tab()
  126. {
  127. logger.lvl++;
  128. }
  129. AILogger::Tab::~Tab()
  130. {
  131. logger.lvl--;
  132. }
  133. struct TimeCheck
  134. {
  135. CStopWatch time;
  136. std::string txt;
  137. TimeCheck(crstring TXT) : txt(TXT)
  138. {
  139. }
  140. ~TimeCheck()
  141. {
  142. BNLOG("Time of %s was %d ms.", txt % time.getDiff());
  143. }
  144. };
  145. template<typename T>
  146. void removeDuplicates(std::vector<T> &vec)
  147. {
  148. boost::sort(vec);
  149. vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
  150. }
  151. struct AtScopeExit
  152. {
  153. boost::function<void()> foo;
  154. AtScopeExit(const boost::function<void()> &FOO) : foo(FOO)
  155. {}
  156. ~AtScopeExit()
  157. {
  158. foo();
  159. }
  160. };
  161. void foreach_tile_pos(boost::function<void(const int3& pos)> foo)
  162. {
  163. for(int i = 0; i < cb->getMapSize().x; i++)
  164. for(int j = 0; j < cb->getMapSize().y; j++)
  165. for(int k = 0; k < cb->getMapSize().z; k++)
  166. foo(int3(i,j,k));
  167. }
  168. void foreach_neighbour(const int3 &pos, boost::function<void(const int3& pos)> foo)
  169. {
  170. BOOST_FOREACH(const int3 &dir, dirs)
  171. {
  172. const int3 n = pos + dir;
  173. if(cb->isInTheMap(n))
  174. foo(pos+dir);
  175. }
  176. }
  177. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  178. {
  179. return vectors[pos.x][pos.y][pos.z];
  180. }
  181. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  182. {
  183. return vectors[pos.x][pos.y][pos.z];
  184. }
  185. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, boost::function<void(unsigned char &in)> foo)
  186. {
  187. for(auto i = vectors.begin(); i != vectors.end(); i++)
  188. for(auto j = i->begin(); j != i->end(); j++)
  189. for(auto z = j->begin(); z != j->end(); z++)
  190. foo(*z);
  191. }
  192. struct ObjInfo
  193. {
  194. int3 pos;
  195. std::string name;
  196. ObjInfo(){}
  197. ObjInfo(const CGObjectInstance *obj)
  198. {
  199. pos = obj->pos;
  200. name = obj->getHoverText();
  201. }
  202. };
  203. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  204. template <typename Container, typename Item>
  205. bool remove_if_present(Container &c, const Item &item)
  206. {
  207. auto i = std::find(c.begin(), c.end(), item);
  208. if (i != c.end())
  209. {
  210. c.erase(i);
  211. return true;
  212. }
  213. return false;
  214. }
  215. template <typename V, typename Item, typename Item2>
  216. bool remove_if_present(std::map<Item,V> & c, const Item2 &item)
  217. {
  218. auto i = c.find(item);
  219. if (i != c.end())
  220. {
  221. c.erase(i);
  222. return true;
  223. }
  224. return false;
  225. }
  226. template <typename Container, typename Pred>
  227. void erase(Container &c, Pred pred)
  228. {
  229. c.erase(boost::remove_if(c, pred), c.end());
  230. }
  231. bool isReachable(const CGObjectInstance *obj)
  232. {
  233. return cb->getPathInfo(obj->visitablePos())->turns < 255;
  234. }
  235. ui64 howManyReinforcementsCanGet(HeroPtr h, const CGTownInstance *t)
  236. {
  237. ui64 ret = 0;
  238. int freeHeroSlots = GameConstants::ARMY_SIZE - h->stacksCount();
  239. std::vector<const CStackInstance *> toMove;
  240. BOOST_FOREACH(auto const slot, t->Slots())
  241. {
  242. //can be merged woth another stack?
  243. TSlot dst = h->getSlotFor(slot.second->getCreatureID());
  244. if(h->hasStackAtSlot(dst))
  245. ret += t->getPower(slot.first);
  246. else
  247. toMove.push_back(slot.second);
  248. }
  249. boost::sort(toMove, [](const CStackInstance *lhs, const CStackInstance *rhs)
  250. {
  251. return lhs->getPower() < rhs->getPower();
  252. });
  253. BOOST_REVERSE_FOREACH(const CStackInstance *stack, toMove)
  254. {
  255. if(freeHeroSlots)
  256. {
  257. ret += stack->getPower();
  258. freeHeroSlots--;
  259. }
  260. else
  261. break;
  262. }
  263. return ret;
  264. }
  265. std::string strFromInt3(int3 pos)
  266. {
  267. std::ostringstream oss;
  268. oss << pos;
  269. return oss.str();
  270. }
  271. bool isCloser(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  272. {
  273. const CGPathNode *ln = cb->getPathInfo(lhs->visitablePos()), *rn = cb->getPathInfo(rhs->visitablePos());
  274. if(ln->turns != rn->turns)
  275. return ln->turns < rn->turns;
  276. return (ln->moveRemains > rn->moveRemains);
  277. };
  278. bool compareMovement(HeroPtr lhs, HeroPtr rhs)
  279. {
  280. return lhs->movement > rhs->movement;
  281. };
  282. ui64 evaluateDanger(const CGObjectInstance *obj);
  283. ui64 evaluateDanger(crint3 tile)
  284. {
  285. const TerrainTile *t = cb->getTile(tile, false);
  286. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  287. return 190000000; //MUCH
  288. ui64 objectDanger = 0, guardDanger = 0;
  289. auto visObjs = cb->getVisitableObjs(tile);
  290. if(visObjs.size())
  291. objectDanger = evaluateDanger(visObjs.back());
  292. int3 guardPos = cb->guardingCreaturePosition(tile);
  293. if(guardPos.x >= 0 && guardPos != tile)
  294. guardDanger = evaluateDanger(guardPos);
  295. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  296. return std::max(objectDanger, guardDanger);
  297. return 0;
  298. }
  299. ui64 evaluateDanger(crint3 tile, const CGHeroInstance *visitor)
  300. {
  301. const TerrainTile *t = cb->getTile(tile, false);
  302. if(!t) //we can know about guard but can't check its tile (the edge of fow)
  303. return 190000000; //MUCH
  304. ui64 objectDanger = 0, guardDanger = 0;
  305. if(const CGObjectInstance * dangerousObject = backOrNull(cb->getVisitableObjs(tile)))
  306. {
  307. objectDanger = evaluateDanger(dangerousObject); //unguarded objects can also be dangerous or unhandled
  308. if (objectDanger)
  309. {
  310. //TODO: don't downcast objects AI shouldnt know about!
  311. auto armedObj = dynamic_cast<const CArmedInstance*>(dangerousObject);
  312. if(armedObj)
  313. objectDanger *= fh->getTacticalAdvantage(visitor, armedObj); //this line tends to go infinite for allied towns (?)
  314. }
  315. }
  316. int3 guardPos = cb->guardingCreaturePosition(tile);
  317. if(guardPos.x >= 0 && guardPos != tile)
  318. guardDanger = evaluateDanger(guardPos, visitor);
  319. //TODO mozna odwiedzic blockvis nie ruszajac straznika
  320. return std::max(objectDanger, guardDanger);
  321. }
  322. ui64 evaluateDanger(const CGObjectInstance *obj)
  323. {
  324. if(obj->tempOwner < GameConstants::PLAYER_LIMIT && cb->getPlayerRelations(obj->tempOwner, ai->playerID)) //owned or allied objects don't pose any threat
  325. return 0;
  326. switch(obj->ID)
  327. {
  328. case Obj::HERO:
  329. {
  330. InfoAboutHero iah;
  331. cb->getHeroInfo(obj, iah);
  332. return iah.army.getStrength();
  333. }
  334. case Obj::TOWN:
  335. case Obj::GARRISON: case Obj::GARRISON2: //garrison
  336. {
  337. InfoAboutTown iat;
  338. cb->getTownInfo(obj, iat);
  339. return iat.army.getStrength();
  340. }
  341. case Obj::MONSTER:
  342. {
  343. //TODO!!!!!!!!
  344. const CGCreature *cre = dynamic_cast<const CGCreature*>(obj);
  345. return cre->getArmyStrength();
  346. }
  347. case Obj::CREATURE_GENERATOR1:
  348. {
  349. const CGDwelling *d = dynamic_cast<const CGDwelling*>(obj);
  350. return d->getArmyStrength();
  351. }
  352. case Obj::MINE:
  353. case Obj::ABANDONED_MINE:
  354. {
  355. const CArmedInstance * a = dynamic_cast<const CArmedInstance*>(obj);
  356. return a->getArmyStrength();
  357. }
  358. case Obj::CRYPT: //crypt
  359. case Obj::CREATURE_BANK: //crebank
  360. case Obj::DRAGON_UTOPIA:
  361. case Obj::SHIPWRECK: //shipwreck
  362. case Obj::DERELICT_SHIP: //derelict ship
  363. case Obj::PYRAMID:
  364. return fh->estimateBankDanger (VLC->objh->bankObjToIndex(obj));
  365. default:
  366. return 0;
  367. }
  368. }
  369. bool compareDanger(const CGObjectInstance *lhs, const CGObjectInstance *rhs)
  370. {
  371. return evaluateDanger(lhs) < evaluateDanger(rhs);
  372. }
  373. VCAI::VCAI(void)
  374. {
  375. LOG_ENTRY;
  376. myCb = NULL;
  377. makingTurn = NULL;
  378. }
  379. VCAI::~VCAI(void)
  380. {
  381. LOG_ENTRY;
  382. }
  383. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  384. {
  385. NET_EVENT_HANDLER;
  386. LOG_ENTRY;
  387. }
  388. void VCAI::heroMoved(const TryMoveHero & details)
  389. {
  390. NET_EVENT_HANDLER;
  391. LOG_ENTRY;
  392. if(details.result == TryMoveHero::TELEPORTATION)
  393. {
  394. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  395. to = CGHeroInstance::convertPosition(details.end, false);
  396. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  397. *o2 = frontOrNull(cb->getVisitableObjs(to));
  398. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  399. {
  400. knownSubterraneanGates[o1] = o2;
  401. knownSubterraneanGates[o2] = o1;
  402. BNLOG("Found a pair of subterranean gates between %s and %s!", from % to);
  403. }
  404. }
  405. }
  406. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  407. {
  408. NET_EVENT_HANDLER;
  409. LOG_ENTRY;
  410. }
  411. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  412. {
  413. NET_EVENT_HANDLER;
  414. LOG_ENTRY;
  415. }
  416. void VCAI::centerView(int3 pos, int focusTime)
  417. {
  418. NET_EVENT_HANDLER;
  419. LOG_ENTRY;
  420. }
  421. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  422. {
  423. NET_EVENT_HANDLER;
  424. LOG_ENTRY;
  425. }
  426. void VCAI::artifactAssembled(const ArtifactLocation &al)
  427. {
  428. NET_EVENT_HANDLER;
  429. LOG_ENTRY;
  430. }
  431. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  432. {
  433. NET_EVENT_HANDLER;
  434. LOG_ENTRY;
  435. }
  436. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  437. {
  438. NET_EVENT_HANDLER;
  439. LOG_ENTRY;
  440. }
  441. void VCAI::playerBlocked(int reason)
  442. {
  443. NET_EVENT_HANDLER;
  444. LOG_ENTRY;
  445. if (reason == PlayerBlocked::UPCOMING_BATTLE)
  446. status.setBattle(UPCOMING_BATTLE);
  447. }
  448. void VCAI::showPuzzleMap()
  449. {
  450. NET_EVENT_HANDLER;
  451. LOG_ENTRY;
  452. }
  453. void VCAI::showShipyardDialog(const IShipyard *obj)
  454. {
  455. NET_EVENT_HANDLER;
  456. LOG_ENTRY;
  457. }
  458. void VCAI::gameOver(ui8 player, bool victory)
  459. {
  460. NET_EVENT_HANDLER;
  461. LOG_ENTRY;
  462. BNLOG("Player %d: I heard that player %d %s.", playerID % (int)player % (victory ? "won" : "lost"));
  463. if(player == playerID)
  464. {
  465. if(victory)
  466. {
  467. tlog0 << "VCAI: I won! Incredible!\n";
  468. tlog0 << "Turn nr " << myCb->getDate() << std::endl;
  469. }
  470. else
  471. {
  472. tlog0 << "VCAI: Player " << (int)player << " lost. It's me. What a disappointment! :(\n";
  473. }
  474. // //let's make Impossible difficulty finally standing to its name :>
  475. // if(myCb->getStartInfo()->difficulty == 4 && !victory)
  476. // {
  477. // //play dirty: crash the whole engine to avoid lose
  478. // //that way AI is unbeatable!
  479. // *(int*)NULL = 666;
  480. // }
  481. // TODO - at least write some insults on stdout
  482. finish();
  483. }
  484. }
  485. void VCAI::artifactPut(const ArtifactLocation &al)
  486. {
  487. NET_EVENT_HANDLER;
  488. LOG_ENTRY;
  489. }
  490. void VCAI::artifactRemoved(const ArtifactLocation &al)
  491. {
  492. NET_EVENT_HANDLER;
  493. LOG_ENTRY;
  494. }
  495. void VCAI::stacksErased(const StackLocation &location)
  496. {
  497. NET_EVENT_HANDLER;
  498. LOG_ENTRY;
  499. }
  500. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  501. {
  502. NET_EVENT_HANDLER;
  503. LOG_ENTRY;
  504. }
  505. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  506. {
  507. NET_EVENT_HANDLER;
  508. LOG_ENTRY;
  509. if (start)
  510. {
  511. visitedObject = const_cast<CGObjectInstance *>(visitedObj); // remember the object and wait for return
  512. markObjectVisited (visitedObj);
  513. remove_if_present(reservedObjs, visitedObj); //unreserve objects
  514. remove_if_present(reservedHeroesMap[visitor], visitedObj);
  515. completeGoal (CGoal(GET_OBJ).sethero(visitor)); //we don't need to visit in anymore
  516. }
  517. }
  518. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= NULL*/)
  519. {
  520. NET_EVENT_HANDLER;
  521. LOG_ENTRY;
  522. }
  523. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  524. {
  525. NET_EVENT_HANDLER;
  526. LOG_ENTRY;
  527. //buildArmyIn(town);
  528. //moveCreaturesToHero(town);
  529. }
  530. void VCAI::tileHidden(const boost::unordered_set<int3, ShashInt3> &pos)
  531. {
  532. NET_EVENT_HANDLER;
  533. LOG_ENTRY;
  534. // BOOST_FOREACH(int3 tile, pos)
  535. // BOOST_FOREACH(const CGObjectInstance *obj, cb->getVisitableObjs(tile))
  536. // remove_if_present(visitableObjs, obj);
  537. visitableObjs.erase(boost::remove_if(visitableObjs, [&](const CGObjectInstance *obj){return !myCb->getObj(obj->id);}), visitableObjs.end());
  538. }
  539. void VCAI::tileRevealed(const boost::unordered_set<int3, ShashInt3> &pos)
  540. {
  541. NET_EVENT_HANDLER;
  542. LOG_ENTRY;
  543. BOOST_FOREACH(int3 tile, pos)
  544. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(tile))
  545. addVisitableObj(obj);
  546. }
  547. void VCAI::heroExchangeStarted(si32 hero1, si32 hero2)
  548. {
  549. NET_EVENT_HANDLER;
  550. LOG_ENTRY;
  551. auto firstHero = cb->getHero(hero1);
  552. auto secondHero = cb->getHero(hero2);
  553. requestActionASAP([=]()
  554. {
  555. if (firstHero->getHeroStrength() > secondHero->getHeroStrength() && canGetArmy (firstHero, secondHero))
  556. pickBestCreatures (firstHero, secondHero);
  557. else if (canGetArmy (secondHero, firstHero))
  558. pickBestCreatures (secondHero, firstHero);
  559. completeGoal(CGoal(VISIT_HERO).sethero(firstHero)); //TODO: what if we were visited by other hero in the meantime?
  560. completeGoal(CGoal(VISIT_HERO).sethero(secondHero));
  561. //TODO: exchange artifacts
  562. });
  563. }
  564. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  565. {
  566. NET_EVENT_HANDLER;
  567. LOG_ENTRY;
  568. }
  569. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  570. {
  571. NET_EVENT_HANDLER;
  572. LOG_ENTRY;
  573. }
  574. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  575. {
  576. NET_EVENT_HANDLER;
  577. LOG_ENTRY;
  578. }
  579. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  580. {
  581. NET_EVENT_HANDLER;
  582. LOG_ENTRY;
  583. }
  584. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  585. {
  586. NET_EVENT_HANDLER;
  587. LOG_ENTRY;
  588. }
  589. void VCAI::newObject(const CGObjectInstance * obj)
  590. {
  591. NET_EVENT_HANDLER;
  592. LOG_ENTRY;
  593. if(obj->isVisitable())
  594. addVisitableObj(obj);
  595. }
  596. void VCAI::objectRemoved(const CGObjectInstance *obj)
  597. {
  598. NET_EVENT_HANDLER;
  599. LOG_ENTRY;
  600. if(remove_if_present(visitableObjs, obj))
  601. assert(obj->isVisitable());
  602. BOOST_FOREACH(auto &p, reservedHeroesMap)
  603. remove_if_present(p.second, obj);
  604. //TODO
  605. //there are other places where CGObjectinstance ptrs are stored...
  606. //
  607. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  608. {
  609. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is killed just before actual deletion
  610. }
  611. }
  612. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  613. {
  614. NET_EVENT_HANDLER;
  615. LOG_ENTRY;
  616. requestActionASAP([=]()
  617. {
  618. makePossibleUpgrades(visitor);
  619. });
  620. }
  621. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  622. {
  623. NET_EVENT_HANDLER;
  624. LOG_ENTRY;
  625. }
  626. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  627. {
  628. NET_EVENT_HANDLER;
  629. LOG_ENTRY;
  630. }
  631. void VCAI::heroCreated(const CGHeroInstance*)
  632. {
  633. NET_EVENT_HANDLER;
  634. LOG_ENTRY;
  635. }
  636. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  637. {
  638. NET_EVENT_HANDLER;
  639. LOG_ENTRY;
  640. }
  641. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  642. {
  643. NET_EVENT_HANDLER;
  644. LOG_ENTRY;
  645. }
  646. void VCAI::requestRealized(PackageApplied *pa)
  647. {
  648. NET_EVENT_HANDLER;
  649. LOG_ENTRY;
  650. if(status.haveTurn())
  651. {
  652. if(pa->packType == typeList.getTypeID<EndTurn>())
  653. if(pa->result)
  654. status.madeTurn();
  655. }
  656. if(pa->packType == typeList.getTypeID<QueryReply>())
  657. {
  658. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  659. }
  660. }
  661. void VCAI::receivedResource(int type, int val)
  662. {
  663. NET_EVENT_HANDLER;
  664. LOG_ENTRY;
  665. }
  666. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  667. {
  668. NET_EVENT_HANDLER;
  669. LOG_ENTRY;
  670. }
  671. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  672. {
  673. NET_EVENT_HANDLER;
  674. LOG_ENTRY;
  675. }
  676. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  677. {
  678. NET_EVENT_HANDLER;
  679. LOG_ENTRY;
  680. }
  681. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  682. {
  683. NET_EVENT_HANDLER;
  684. LOG_ENTRY;
  685. }
  686. void VCAI::battleResultsApplied()
  687. {
  688. NET_EVENT_HANDLER;
  689. LOG_ENTRY;
  690. assert(status.getBattle() == ENDING_BATTLE);
  691. status.setBattle(NO_BATTLE);
  692. }
  693. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  694. {
  695. NET_EVENT_HANDLER;
  696. LOG_ENTRY;
  697. if(sop->what == ObjProperty::OWNER)
  698. {
  699. if(sop->val == playerID)
  700. remove_if_present(visitableObjs, myCb->getObj(sop->id));
  701. //TODO restore lost obj
  702. }
  703. }
  704. void VCAI::buildChanged(const CGTownInstance *town, int buildingID, int what)
  705. {
  706. NET_EVENT_HANDLER;
  707. LOG_ENTRY;
  708. }
  709. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  710. {
  711. NET_EVENT_HANDLER;
  712. LOG_ENTRY;
  713. }
  714. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  715. {
  716. NET_EVENT_HANDLER;
  717. LOG_ENTRY;
  718. }
  719. void VCAI::init(CCallback * CB)
  720. {
  721. myCb = CB;
  722. cbc = CB;
  723. NET_EVENT_HANDLER;
  724. LOG_ENTRY;
  725. playerID = myCb->getMyColor();
  726. myCb->waitTillRealize = true;
  727. myCb->unlockGsWhenWaiting = true;
  728. if(!fh)
  729. fh = new FuzzyHelper();
  730. retreiveVisitableObjs(visitableObjs);
  731. }
  732. void VCAI::yourTurn()
  733. {
  734. NET_EVENT_HANDLER;
  735. LOG_ENTRY;
  736. status.startedTurn();
  737. makingTurn = new boost::thread(&VCAI::makeTurn, this);
  738. }
  739. void VCAI::heroGotLevel(const CGHeroInstance *hero, int pskill, std::vector<ui16> &skills, int queryID)
  740. {
  741. NET_EVENT_HANDLER;
  742. LOG_ENTRY;
  743. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  744. requestActionASAP([=]{ answerQuery(queryID, 0); });
  745. }
  746. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, int queryID)
  747. {
  748. NET_EVENT_HANDLER;
  749. LOG_ENTRY;
  750. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  751. requestActionASAP([=]{ answerQuery(queryID, 0); });
  752. }
  753. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, ui32 askID, const int soundID, bool selection, bool cancel)
  754. {
  755. NET_EVENT_HANDLER;
  756. LOG_ENTRY;
  757. int sel = 0;
  758. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  759. % components.size() % text));
  760. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  761. sel = components.size();
  762. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  763. sel = 1;
  764. requestActionASAP([=]()
  765. {
  766. answerQuery(askID, sel);
  767. });
  768. }
  769. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, int queryID)
  770. {
  771. NET_EVENT_HANDLER;
  772. LOG_ENTRY;
  773. std::string s1 = up ? up->nodeName() : "NONE";
  774. std::string s2 = down ? down->nodeName() : "NONE";
  775. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  776. //you can't request action from action-response thread
  777. requestActionASAP([=]()
  778. {
  779. pickBestCreatures (down, up);
  780. answerQuery(queryID, 0);
  781. });
  782. }
  783. void VCAI::serialize(COSer<CSaveFile> &h, const int version)
  784. {
  785. NET_EVENT_HANDLER;
  786. LOG_ENTRY;
  787. }
  788. void VCAI::serialize(CISer<CLoadFile> &h, const int version)
  789. {
  790. NET_EVENT_HANDLER;
  791. LOG_ENTRY;
  792. }
  793. void makePossibleUpgrades(const CArmedInstance *obj)
  794. {
  795. if(!obj)
  796. return;
  797. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  798. {
  799. if(const CStackInstance *s = obj->getStackPtr(i))
  800. {
  801. UpgradeInfo ui;
  802. cb->getUpgradeInfo(obj, i, ui);
  803. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  804. {
  805. cb->upgradeCreature(obj, i, ui.newID[0]);
  806. }
  807. }
  808. }
  809. }
  810. void VCAI::makeTurn()
  811. {
  812. MAKING_TURN;
  813. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  814. setThreadName("VCAI::makeTurn");
  815. BNLOG("Player %d starting turn", playerID);
  816. INDENT;
  817. switch(cb->getDate(1))
  818. {
  819. case 1:
  820. {
  821. townVisitsThisWeek.clear();
  822. std::vector<const CGObjectInstance *> objs;
  823. retreiveVisitableObjs(objs, true);
  824. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  825. {
  826. if (isWeeklyRevisitable(obj))
  827. {
  828. if (!vstd::contains(visitableObjs, obj))
  829. visitableObjs.push_back(obj);
  830. auto o = std::find (alreadyVisited.begin(), alreadyVisited.end(), obj);
  831. if (o != alreadyVisited.end())
  832. alreadyVisited.erase(o);
  833. }
  834. }
  835. }
  836. break;
  837. case 7: //reconsider strategy
  838. {
  839. if(auto h = primaryHero()) //check if our primary hero can handle danger
  840. {
  841. ui64 totalDanger = 0;
  842. int dangerousObjects = 0;
  843. std::vector<const CGObjectInstance *> objs;
  844. retreiveVisitableObjs(objs, false);
  845. BOOST_FOREACH (auto obj, objs)
  846. {
  847. if (evaluateDanger(obj)) //potentilaly dnagerous
  848. {
  849. totalDanger += evaluateDanger(obj->visitablePos(), *h);
  850. ++dangerousObjects;
  851. }
  852. }
  853. ui64 averageDanger = totalDanger / std::max(dangerousObjects, 1);
  854. if (dangerousObjects && averageDanger > h->getHeroStrength())
  855. {
  856. setGoal (h, CGoal(GATHER_ARMY).sethero(h).setvalue(averageDanger * SAFE_ATTACK_CONSTANT).setisAbstract(true));
  857. }
  858. }
  859. }
  860. break;
  861. }
  862. if(cb->getSelectedHero())
  863. cb->recalculatePaths();
  864. makeTurnInternal();
  865. vstd::clear_pointer(makingTurn);
  866. return;
  867. }
  868. void VCAI::makeTurnInternal()
  869. {
  870. saving = 0;
  871. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  872. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  873. moveCreaturesToHero(t);
  874. try
  875. {
  876. //Pick objects reserved in previous turn - we expect only nerby objects there
  877. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  878. BOOST_FOREACH (auto hero, reservedHeroesCopy)
  879. {
  880. cb->setSelection(hero.first.get());
  881. boost::sort (hero.second, isCloser);
  882. BOOST_FOREACH (auto obj, hero.second)
  883. {
  884. striveToGoal (CGoal(VISIT_TILE).sethero(hero.first).settile(obj->visitablePos()));
  885. }
  886. }
  887. //now try to win
  888. striveToGoal(CGoal(WIN));
  889. //finally, continue our abstract long-term goals
  890. //heroes tend to die in the process and loose their goals, unsafe to iterate it
  891. std::vector<std::pair<HeroPtr, CGoal> > safeCopy;
  892. boost::copy(lockedHeroes, std::back_inserter(safeCopy));
  893. typedef std::pair<HeroPtr, CGoal> TItrType;
  894. auto lockedHeroesSorter = [](TItrType h1, TItrType h2) -> bool
  895. {
  896. return compareMovement (h1.first, h2.first);
  897. };
  898. boost::sort(safeCopy, lockedHeroesSorter);
  899. while (safeCopy.size()) //continue our goals
  900. {
  901. auto it = safeCopy.begin();
  902. if (it->first && it->first->tempOwner == playerID && vstd::contains(lockedHeroes, it->first)) //make sure hero still has his goal
  903. {
  904. cb->setSelection(*it->first);
  905. striveToGoal (it->second);
  906. }
  907. safeCopy.erase(it);
  908. }
  909. auto quests = myCb->getMyQuests();
  910. BOOST_FOREACH (auto quest, quests)
  911. {
  912. striveToQuest (quest);
  913. }
  914. striveToGoal(CGoal(BUILD)); //TODO: smarter building management
  915. }
  916. catch(boost::thread_interrupted &e)
  917. {
  918. tlog0 << "Making turn thread has been interrupted. We'll end without calling endTurn.\n";
  919. return;
  920. }
  921. catch(std::exception &e)
  922. {
  923. tlog0 << "Making turn thread has caught an exception: " << e.what() << "\n";
  924. }
  925. endTurn();
  926. }
  927. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  928. {
  929. int3 dst = obj->visitablePos();
  930. BNLOG("%s will try to visit %s at (%s)", h->name % obj->getHoverText() % strFromInt3(dst));
  931. return moveHeroToTile(dst, h);
  932. }
  933. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  934. {
  935. switch (obj->ID)
  936. {
  937. case Obj::CREATURE_GENERATOR1:
  938. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  939. checkHeroArmy (h);
  940. break;
  941. case Obj::TOWN:
  942. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  943. townVisitsThisWeek[h].push_back(h->visitedTown);
  944. break;
  945. break;
  946. }
  947. }
  948. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  949. {
  950. if(t->visitingHero && t->armedGarrison())
  951. {
  952. pickBestCreatures (t->visitingHero, t);
  953. }
  954. }
  955. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  956. { //TODO: merge with pickBestCreatures
  957. const CArmedInstance *armies[] = {army, source};
  958. int armySize = 0;
  959. //we calculate total strength for each creature type available in armies
  960. std::map<const CCreature*, int> creToPower;
  961. BOOST_FOREACH(auto armyPtr, armies)
  962. BOOST_FOREACH(auto &i, armyPtr->Slots())
  963. {
  964. ++armySize;//TODO: allow splitting stacks?
  965. creToPower[i.second->type] += i.second->getPower();
  966. }
  967. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  968. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  969. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  970. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  971. {
  972. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  973. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  974. {
  975. return lhs.second < rhs.second;
  976. });
  977. bestArmy.push_back(creIt->first);
  978. creToPower.erase(creIt);
  979. if(creToPower.empty())
  980. break;
  981. }
  982. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  983. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  984. {
  985. BOOST_FOREACH(auto armyPtr, armies)
  986. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  987. {
  988. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  989. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army)) //can't take away last creature
  990. return true; //at least one exchange will be performed
  991. }
  992. }
  993. return false;
  994. }
  995. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  996. {
  997. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  998. const CArmedInstance *armies[] = {army, source};
  999. int armySize = 0;
  1000. //we calculate total strength for each creature type available in armies
  1001. std::map<const CCreature*, int> creToPower;
  1002. BOOST_FOREACH(auto armyPtr, armies)
  1003. BOOST_FOREACH(auto &i, armyPtr->Slots())
  1004. {
  1005. ++armySize;//TODO: allow splitting stacks?
  1006. creToPower[i.second->type] += i.second->getPower();
  1007. }
  1008. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  1009. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  1010. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  1011. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  1012. {
  1013. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  1014. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  1015. {
  1016. return lhs.second < rhs.second;
  1017. });
  1018. bestArmy.push_back(creIt->first);
  1019. creToPower.erase(creIt);
  1020. if(creToPower.empty())
  1021. break;
  1022. }
  1023. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  1024. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  1025. {
  1026. BOOST_FOREACH(auto armyPtr, armies)
  1027. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  1028. {
  1029. if(armyPtr->getCreature(j) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst slot
  1030. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1 && armyPtr != army))
  1031. cb->mergeOrSwapStacks(armyPtr, army, j, i);
  1032. }
  1033. }
  1034. //TODO - having now strongest possible army, we may want to think about arranging stacks
  1035. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  1036. if (hero)
  1037. {
  1038. checkHeroArmy (hero);
  1039. }
  1040. }
  1041. void VCAI::recruitCreatures(const CGDwelling * d)
  1042. {
  1043. for(int i = 0; i < d->creatures.size(); i++)
  1044. {
  1045. if(!d->creatures[i].second.size())
  1046. continue;
  1047. int count = d->creatures[i].first;
  1048. int creID = d->creatures[i].second.back();
  1049. // const CCreature *c = VLC->creh->creatures[creID];
  1050. // if(containsSavedRes(c->cost))
  1051. // continue;
  1052. TResources myRes = cb->getResourceAmount();
  1053. myRes[Res::GOLD] -= GOLD_RESERVE;
  1054. amin(count, myRes / VLC->creh->creatures[creID]->cost);
  1055. if(count > 0)
  1056. cb->recruitCreatures(d, creID, count, i);
  1057. }
  1058. }
  1059. bool VCAI::tryBuildStructure(const CGTownInstance * t, int building, unsigned int maxDays)
  1060. {
  1061. if (!vstd::contains(t->town->buildings, building))
  1062. return false; // no such building in town
  1063. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  1064. return true;
  1065. std::set<int> toBuild = cb->getBuildingRequiments(t, building);
  1066. //erase all already built buildings
  1067. for (auto buildIter = toBuild.begin(); buildIter != toBuild.end();)
  1068. {
  1069. if (t->hasBuilt(*buildIter))
  1070. toBuild.erase(buildIter++);
  1071. else
  1072. buildIter++;
  1073. }
  1074. toBuild.insert(building);
  1075. BOOST_FOREACH(int buildID, toBuild)
  1076. {
  1077. int canBuild = cb->canBuildStructure(t, buildID);
  1078. if (canBuild == EBuildingState::HAVE_CAPITAL
  1079. || canBuild == EBuildingState::FORBIDDEN
  1080. || canBuild == EBuildingState::NO_WATER)
  1081. return false; //we won't be able to build this
  1082. }
  1083. if (maxDays && toBuild.size() > maxDays)
  1084. return false;
  1085. TResources currentRes = cb->getResourceAmount();
  1086. TResources income = estimateIncome();
  1087. //TODO: calculate if we have enough resources to build it in maxDays
  1088. BOOST_FOREACH(int buildID, toBuild)
  1089. {
  1090. const CBuilding *b = t->town->buildings[buildID];
  1091. int canBuild = cb->canBuildStructure(t, buildID);
  1092. if(canBuild == EBuildingState::ALLOWED)
  1093. {
  1094. if(!containsSavedRes(b->resources))
  1095. {
  1096. BNLOG("Player %d will build %s in town of %s at %s", playerID % b->Name() % t->name % t->pos);
  1097. cb->buildBuilding(t, buildID);
  1098. return true;
  1099. }
  1100. continue;
  1101. }
  1102. else if(canBuild == EBuildingState::NO_RESOURCES)
  1103. {
  1104. TResources cost = t->town->buildings[buildID]->resources;
  1105. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  1106. {
  1107. int diff = currentRes[i] - cost[i] + income[i];
  1108. if(diff < 0)
  1109. saving[i] = 1;
  1110. }
  1111. continue;
  1112. }
  1113. }
  1114. return false;
  1115. }
  1116. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  1117. {
  1118. BOOST_FOREACH(int building, buildList)
  1119. {
  1120. if(t->hasBuilt(building))
  1121. continue;
  1122. if (tryBuildStructure(t, building, maxDays))
  1123. return true;
  1124. }
  1125. return false; //Can't build anything
  1126. }
  1127. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<int> buildList, unsigned int maxDays)
  1128. {
  1129. BOOST_FOREACH(int building, buildList)
  1130. {
  1131. if(t->hasBuilt(building))
  1132. continue;
  1133. return tryBuildStructure(t, building, maxDays);
  1134. }
  1135. return false;//Nothing to build
  1136. }
  1137. void VCAI::buildStructure(const CGTownInstance * t)
  1138. {
  1139. using namespace EBuilding;
  1140. //TODO make *real* town development system
  1141. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  1142. //TODO: build resource silo, defences when needed
  1143. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  1144. //Set of buildings for different goals. Does not include any prerequisites.
  1145. const int essential[] = {TAVERN, TOWN_HALL};
  1146. const int goldSource[] = {TOWN_HALL, CITY_HALL, CAPITOL};
  1147. const int unitsSource[] = { 30, 31, 32, 33, 34, 35, 36};
  1148. const int unitsUpgrade[] = { 37, 38, 39, 40, 41, 42, 43};
  1149. const int unitGrowth[] = { FORT, CITADEL, CASTLE, HORDE_1, HORDE_1_UPGR, HORDE_2, HORDE_2_UPGR};
  1150. const int spells[] = {MAGES_GUILD_1, MAGES_GUILD_2, MAGES_GUILD_3, MAGES_GUILD_4, MAGES_GUILD_5};
  1151. const int extra[] = {RESOURCE_SILO, SPECIAL_1, SPECIAL_2, SPECIAL_3, SPECIAL_4, SHIPYARD}; // all remaining buildings
  1152. TResources currentRes = cb->getResourceAmount();
  1153. TResources income = estimateIncome();
  1154. if (tryBuildAnyStructure(t, std::vector<int>(essential, essential + ARRAY_COUNT(essential))))
  1155. return;
  1156. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  1157. if (currentRes[Res::GOLD] < income[Res::GOLD] * 6)
  1158. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1159. return;
  1160. if (cb->getDate(1) > 6)// last 2 days of week - try to focus on growth
  1161. {
  1162. if (tryBuildNextStructure(t, std::vector<int>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  1163. return;
  1164. }
  1165. // first in-game week or second half of any week: try build dwellings
  1166. if (cb->getDate(0) < 7 || cb->getDate(1) > 3)
  1167. if (tryBuildAnyStructure(t, std::vector<int>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(1)))
  1168. return;
  1169. //try to upgrade dwelling
  1170. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1171. {
  1172. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1173. {
  1174. if (tryBuildStructure(t, unitsUpgrade[i]))
  1175. return;
  1176. }
  1177. }
  1178. //remaining tasks
  1179. if (tryBuildNextStructure(t, std::vector<int>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1180. return;
  1181. if (tryBuildNextStructure(t, std::vector<int>(spells, spells + ARRAY_COUNT(spells))))
  1182. return;
  1183. if (tryBuildAnyStructure(t, std::vector<int>(extra, extra + ARRAY_COUNT(extra))))
  1184. return;
  1185. }
  1186. bool isSafeToVisit(HeroPtr h, crint3 tile)
  1187. {
  1188. const ui64 heroStrength = h->getTotalStrength(),
  1189. dangerStrength = evaluateDanger(tile, *h);
  1190. if(dangerStrength)
  1191. {
  1192. if(heroStrength / SAFE_ATTACK_CONSTANT > dangerStrength)
  1193. {
  1194. BNLOG("It's, safe for %s to visit tile %s", h->name % tile);
  1195. return true;
  1196. }
  1197. else
  1198. return false;
  1199. }
  1200. return true; //there's no danger
  1201. }
  1202. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1203. {
  1204. validateVisitableObjs();
  1205. std::vector<const CGObjectInstance *> possibleDestinations;
  1206. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1207. {
  1208. if(cb->getPathInfo(obj->visitablePos())->reachable() && !obj->wasVisited(playerID) &&
  1209. (obj->tempOwner != playerID || isWeeklyRevisitable(obj))) //flag or get weekly resources / creatures
  1210. possibleDestinations.push_back(obj);
  1211. }
  1212. boost::sort(possibleDestinations, isCloser);
  1213. possibleDestinations.erase(boost::remove_if(possibleDestinations, [&](const CGObjectInstance *obj) -> bool
  1214. {
  1215. const int3 pos = obj->visitablePos();
  1216. if(vstd::contains(alreadyVisited, obj))
  1217. return true;
  1218. if(!isSafeToVisit(h, pos))
  1219. return true;
  1220. if (!shouldVisit(h, obj))
  1221. return true;
  1222. if (vstd::contains(reservedObjs, obj)) //does checking for our own reserved objects make sense? here?
  1223. return true;
  1224. const CGObjectInstance *topObj = cb->getVisitableObjs(pos).back(); //it may be hero visiting this obj
  1225. //we don't try visiting object on which allied or owned hero stands
  1226. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1227. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != 0)
  1228. return true;
  1229. return false;
  1230. }),possibleDestinations.end());
  1231. return possibleDestinations;
  1232. }
  1233. void VCAI::wander(HeroPtr h)
  1234. {
  1235. while(1)
  1236. {
  1237. std::vector <ObjectIdRef> dests;
  1238. range::copy(reservedHeroesMap[h], std::back_inserter(dests));
  1239. if (!dests.size())
  1240. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1241. if(!dests.size())
  1242. {
  1243. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1244. {
  1245. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1246. };
  1247. std::vector<const CGTownInstance *> townsReachable;
  1248. std::vector<const CGTownInstance *> townsNotReachable;
  1249. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1250. {
  1251. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1252. {
  1253. if(isReachable(t))
  1254. townsReachable.push_back(t);
  1255. else
  1256. townsNotReachable.push_back(t);
  1257. }
  1258. }
  1259. if(townsReachable.size())
  1260. {
  1261. boost::sort(townsReachable, compareReinforcements);
  1262. dests.emplace_back(townsReachable.back());
  1263. }
  1264. else if(townsNotReachable.size())
  1265. {
  1266. boost::sort(townsNotReachable, compareReinforcements);
  1267. //TODO pick the truly best
  1268. const CGTownInstance *t = townsNotReachable.back();
  1269. BNLOG("%s can't reach any town, we'll try to make our way to %s at %s", h->name % t->name % t->visitablePos());
  1270. int3 pos1 = h->pos;
  1271. striveToGoal(CGoal(CLEAR_WAY_TO).settile(t->visitablePos()).sethero(h));
  1272. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1273. {
  1274. if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST && cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES && cb->getAvailableHeroes(t).size())
  1275. recruitHero(t);
  1276. }
  1277. break;
  1278. }
  1279. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1280. {
  1281. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1282. erase_if(towns, [](const CGTownInstance *t) -> bool
  1283. {
  1284. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1285. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1286. return true;
  1287. return false;
  1288. });
  1289. boost::sort(towns, compareArmyStrength);
  1290. if(towns.size())
  1291. recruitHero(towns.back());
  1292. break;
  1293. }
  1294. else
  1295. {
  1296. PNLOG("Nowhere more to go...\n");
  1297. break;
  1298. }
  1299. }
  1300. const ObjectIdRef&dest = dests.front();
  1301. if(!goVisitObj(dest, h))
  1302. {
  1303. if(!dest)
  1304. {
  1305. BNLOG("Visit attempt made the object (id=%d) gone...", dest.id);
  1306. }
  1307. else
  1308. {
  1309. BNLOG("Hero %s apparently used all MPs (%d left)\n", h->name % h->movement);
  1310. reserveObject(h, dest); //reserve that object - we predict it will be reached soon
  1311. //removed - do not forget abstract goal so easily
  1312. //setGoal(h, CGoal(VISIT_TILE).sethero(h).settile(dest->visitablePos()));
  1313. }
  1314. break;
  1315. }
  1316. if(h->visitedTown)
  1317. {
  1318. townVisitsThisWeek[h].push_back(h->visitedTown);
  1319. buildArmyIn(h->visitedTown);
  1320. break;
  1321. }
  1322. }
  1323. }
  1324. void VCAI::setGoal(HeroPtr h, const CGoal goal)
  1325. { //TODO: check for presence?
  1326. if (goal.goalType == EGoals::INVALID)
  1327. remove_if_present(lockedHeroes, h);
  1328. else
  1329. lockedHeroes[h] = CGoal(goal).setisElementar(false); //always evaluate goals before realizing
  1330. }
  1331. void VCAI::setGoal(HeroPtr h, EGoals goalType)
  1332. {
  1333. if (goalType == EGoals::INVALID)
  1334. remove_if_present(lockedHeroes, h);
  1335. else
  1336. lockedHeroes[h] = CGoal(goalType).setisElementar(false); //always evaluate goals before realizing;
  1337. }
  1338. void VCAI::completeGoal (const CGoal goal)
  1339. {
  1340. if (const CGHeroInstance * h = goal.hero.get(true))
  1341. {
  1342. auto it = lockedHeroes.find(h);
  1343. if (it != lockedHeroes.end())
  1344. if (it->second.goalType == goal.goalType)
  1345. lockedHeroes.erase(it); //goal fulfilled, free hero
  1346. }
  1347. }
  1348. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1349. {
  1350. NET_EVENT_HANDLER;
  1351. assert(playerID > GameConstants::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1352. status.setBattle(ONGOING_BATTLE);
  1353. const CGObjectInstance *presumedEnemy = backOrNull(cb->getVisitableObjs(tile)); //may be NULL in some very are cases -> eg. visited monolith and fighting with an enemy at the FoW covered exit
  1354. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1355. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1356. }
  1357. void VCAI::battleEnd(const BattleResult *br)
  1358. {
  1359. NET_EVENT_HANDLER;
  1360. assert(status.getBattle() == ONGOING_BATTLE);
  1361. status.setBattle(ENDING_BATTLE);
  1362. bool won = br->winner == myCb->battleGetMySide();
  1363. BNLOG("Player %d: I %s the %s!", playerID % (won ? "won" : "lost") % battlename);
  1364. battlename.clear();
  1365. CAdventureAI::battleEnd(br);
  1366. }
  1367. void VCAI::waitTillFree()
  1368. {
  1369. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1370. status.waitTillFree();
  1371. }
  1372. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1373. {
  1374. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1375. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1376. (obj->ID == Obj::MONSTER))
  1377. return;
  1378. alreadyVisited.push_back(obj);
  1379. }
  1380. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1381. {
  1382. reservedObjs.push_back(obj);
  1383. reservedHeroesMap[h].push_back(obj);
  1384. }
  1385. void VCAI::validateVisitableObjs()
  1386. {
  1387. std::vector<const CGObjectInstance *> hlp;
  1388. retreiveVisitableObjs(hlp, true);
  1389. start:
  1390. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1391. if(!vstd::contains(hlp, obj))
  1392. {
  1393. tlog1 << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << " shouldn't be on list!\n";
  1394. remove_if_present(visitableObjs, obj);
  1395. goto start;
  1396. }
  1397. }
  1398. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1399. {
  1400. foreach_tile_pos([&](const int3 &pos)
  1401. {
  1402. BOOST_FOREACH(const CGObjectInstance *obj, myCb->getVisitableObjs(pos, false))
  1403. {
  1404. if(includeOwned || obj->tempOwner != playerID)
  1405. out.push_back(obj);
  1406. }
  1407. });
  1408. }
  1409. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1410. {
  1411. std::vector<const CGObjectInstance *> ret;
  1412. retreiveVisitableObjs(ret, true);
  1413. erase_if(ret, [](const CGObjectInstance *obj)
  1414. {
  1415. return obj->tempOwner != ai->playerID;
  1416. });
  1417. return ret;
  1418. }
  1419. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1420. {
  1421. visitableObjs.push_back(obj);
  1422. helperObjInfo[obj] = ObjInfo(obj);
  1423. }
  1424. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1425. {
  1426. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  1427. {
  1428. if(obj->ID == 5 && obj->subID == aid)
  1429. return obj;
  1430. }
  1431. return NULL;
  1432. //TODO what if more than one artifact is available? return them all or some slection criteria
  1433. }
  1434. bool VCAI::isAccessible(const int3 &pos)
  1435. {
  1436. //TODO precalculate for speed
  1437. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1438. {
  1439. if(isAccessibleForHero(pos, h))
  1440. return true;
  1441. }
  1442. return false;
  1443. }
  1444. HeroPtr VCAI::getHeroWithGrail() const
  1445. {
  1446. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  1447. if(h->hasArt(2)) //grail
  1448. return h;
  1449. return NULL;
  1450. }
  1451. const CGObjectInstance * VCAI::getUnvisitedObj(const boost::function<bool(const CGObjectInstance *)> &predicate)
  1452. {
  1453. //TODO smarter definition of unvisited
  1454. BOOST_FOREACH(const CGObjectInstance *obj, visitableObjs)
  1455. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1456. return obj;
  1457. return NULL;
  1458. }
  1459. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1460. {
  1461. cb->setSelection(*h);
  1462. if (!includeAllies)
  1463. { //don't visit tile occupied by allied hero
  1464. BOOST_FOREACH (auto obj, cb->getVisitableObjs(pos))
  1465. {
  1466. if (obj->ID == Obj::HERO && obj->tempOwner == h->tempOwner && obj != h)
  1467. return false;
  1468. }
  1469. }
  1470. return cb->getPathInfo(pos)->reachable();
  1471. }
  1472. class cannotFulfillGoalException : public std::exception
  1473. {
  1474. std::string msg;
  1475. public:
  1476. explicit cannotFulfillGoalException(crstring _Message) : msg(_Message)
  1477. {
  1478. }
  1479. virtual ~cannotFulfillGoalException() throw ()
  1480. {
  1481. };
  1482. const char *what() const throw () OVERRIDE
  1483. {
  1484. return msg.c_str();
  1485. }
  1486. };
  1487. class goalFulfilledException : public std::exception
  1488. {
  1489. std::string msg;
  1490. public:
  1491. explicit goalFulfilledException(crstring _Message) : msg(_Message)
  1492. {
  1493. }
  1494. virtual ~goalFulfilledException() throw ()
  1495. {
  1496. };
  1497. const char *what() const throw () OVERRIDE
  1498. {
  1499. return msg.c_str();
  1500. }
  1501. };
  1502. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1503. {
  1504. visitedObject = NULL;
  1505. int3 startHpos = h->visitablePos();
  1506. bool ret = false;
  1507. if(startHpos == dst)
  1508. {
  1509. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1510. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1511. waitTillFree(); //movement may cause battle or blocking dialog
  1512. ret = true;
  1513. }
  1514. else
  1515. {
  1516. CGPath path;
  1517. cb->getPath2(dst, path);
  1518. if(path.nodes.empty())
  1519. {
  1520. tlog1 << "Hero " << h->name << " cannot reach " << dst << std::endl;
  1521. //setGoal(h, INVALID);
  1522. completeGoal (CGoal(VISIT_TILE).sethero(h));
  1523. cb->recalculatePaths();
  1524. throw std::runtime_error("Wrong move order!");
  1525. }
  1526. int i=path.nodes.size()-1;
  1527. for(; i>0; i--)
  1528. {
  1529. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1530. if(path.nodes[i-1].turns)
  1531. {
  1532. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1533. break;
  1534. }
  1535. int3 endpos = path.nodes[i-1].coord;
  1536. if(endpos == h->visitablePos())
  1537. //if (endpos == h->pos)
  1538. continue;
  1539. // if(i > 1)
  1540. // {
  1541. // int3 afterEndPos = path.nodes[i-2].coord;
  1542. // if(afterEndPos.z != endpos.z)
  1543. //
  1544. // }
  1545. //tlog0 << "Moving " << h->name << " from " << h->getPosition() << " to " << endpos << std::endl;
  1546. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1547. waitTillFree(); //movement may cause battle or blocking dialog
  1548. boost::this_thread::interruption_point();
  1549. if(!h) //we lost hero - remove all tasks assigned to him/her
  1550. {
  1551. lostHero(h);
  1552. //we need to throw, otherwise hero will be assigned to sth again
  1553. throw std::runtime_error("Hero was lost!");
  1554. break;
  1555. }
  1556. }
  1557. ret = !i;
  1558. }
  1559. if (visitedObject) //we step into something interesting
  1560. {
  1561. performObjectInteraction (visitedObject, h);
  1562. }
  1563. if(h) //we could have lost hero after last move
  1564. {
  1565. cb->recalculatePaths();
  1566. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1567. {
  1568. throw cannotFulfillGoalException("Invalid path found!");
  1569. }
  1570. }
  1571. BNLOG("Hero %s moved from %s to %s", h->name % startHpos % h->visitablePos());
  1572. return ret;
  1573. }
  1574. int howManyTilesWillBeDiscovered(const int3 &pos, int radious)
  1575. {
  1576. int ret = 0;
  1577. for(int x = pos.x - radious; x <= pos.x + radious; x++)
  1578. {
  1579. for(int y = pos.y - radious; y <= pos.y + radious; y++)
  1580. {
  1581. int3 npos = int3(x,y,pos.z);
  1582. if(cb->isInTheMap(npos) && pos.dist2d(npos) - 0.5 < radious && !cb->isVisible(npos))
  1583. {
  1584. ret++;
  1585. }
  1586. }
  1587. }
  1588. return ret;
  1589. }
  1590. int howManyTilesWillBeDiscovered(int radious, int3 pos, crint3 dir)
  1591. {
  1592. return howManyTilesWillBeDiscovered(pos + dir, radious);
  1593. }
  1594. void getVisibleNeighbours(const std::vector<int3> &tiles, std::vector<int3> &out)
  1595. {
  1596. BOOST_FOREACH(const int3 &tile, tiles)
  1597. {
  1598. foreach_neighbour(tile, [&](int3 neighbour)
  1599. {
  1600. if(cb->isVisible(neighbour))
  1601. out.push_back(neighbour);
  1602. });
  1603. }
  1604. }
  1605. void VCAI::tryRealize(CGoal g)
  1606. {
  1607. BNLOG("Attempting realizing goal with code %s", goalName(g.goalType));
  1608. switch(g.goalType)
  1609. {
  1610. case EXPLORE:
  1611. {
  1612. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1613. }
  1614. break;
  1615. case RECRUIT_HERO:
  1616. {
  1617. if(const CGTownInstance *t = findTownWithTavern())
  1618. {
  1619. //TODO co jesli nie ma dostepnego bohatera?
  1620. //TODO jezeli miasto jest zablokowane, sprobowac oczyscic wejscie
  1621. cb->recruitHero(t, cb->getAvailableHeroes(t)[0]);
  1622. }
  1623. //TODO karkolomna alternatywa - tawerna na mapie przygod lub wiezienie (nie wiem, czy warto?)
  1624. }
  1625. break;
  1626. case VISIT_TILE:
  1627. {
  1628. //cb->recalculatePaths();
  1629. if(!g.hero->movement)
  1630. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1631. //if(!g.isBlockedBorderGate(g.tile))
  1632. //{
  1633. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1634. {
  1635. throw goalFulfilledException("");
  1636. }
  1637. //}
  1638. //else
  1639. // throw cannotFulfillGoalException("There's a blocked gate!, we should never be here"); //CLEAR_WAY_TO should get keymaster tent
  1640. }
  1641. break;
  1642. case VISIT_HERO:
  1643. {
  1644. if(!g.hero->movement)
  1645. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1646. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1647. {
  1648. throw goalFulfilledException("");
  1649. }
  1650. }
  1651. break;
  1652. case BUILD_STRUCTURE:
  1653. {
  1654. const CGTownInstance *t = g.town;
  1655. if(!t && g.hero)
  1656. t = g.hero->visitedTown;
  1657. if(!t)
  1658. {
  1659. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1660. {
  1661. switch(cb->canBuildStructure(t, g.bid))
  1662. {
  1663. case EBuildingState::ALLOWED:
  1664. cb->buildBuilding(t, g.bid);
  1665. return;
  1666. default:
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. else if(cb->canBuildStructure(t, g.bid) == EBuildingState::ALLOWED)
  1672. {
  1673. cb->buildBuilding(t, g.bid);
  1674. return;
  1675. }
  1676. throw cannotFulfillGoalException("Cannot build a given structure!");
  1677. }
  1678. break;
  1679. case DIG_AT_TILE:
  1680. {
  1681. assert(g.hero->visitablePos() == g.tile);
  1682. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1683. {
  1684. cb->dig(g.hero.get());
  1685. setGoal(g.hero, INVALID); // finished digging
  1686. }
  1687. else
  1688. {
  1689. ai->lockedHeroes[g.hero] = g; //hero who tries to dig shouldn't do anything else
  1690. throw cannotFulfillGoalException("A hero can't dig!\n");
  1691. }
  1692. }
  1693. break;
  1694. case COLLECT_RES: //TODO: use piles and mines?
  1695. if(cb->getResourceAmount(g.resID) >= g.value)
  1696. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1697. if(const CGObjectInstance *obj = cb->getObj(g.objid, false))
  1698. {
  1699. if(const IMarket *m = IMarket::castFrom(obj, false))
  1700. {
  1701. for (int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  1702. {
  1703. if(i == g.resID) continue;
  1704. int toGive, toGet;
  1705. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1706. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1707. //TODO trade only as much as needed
  1708. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1709. if(cb->getResourceAmount(g.resID) >= g.value)
  1710. return;
  1711. }
  1712. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1713. }
  1714. else
  1715. {
  1716. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1717. }
  1718. }
  1719. else
  1720. {
  1721. saving[g.resID] = 1;
  1722. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1723. }
  1724. case CONQUER:
  1725. case GATHER_ARMY:
  1726. case BOOST_HERO:
  1727. // TODO: conquer??
  1728. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1729. case BUILD:
  1730. performTypicalActions(); //TODO: separate build and wander
  1731. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1732. case INVALID:
  1733. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1734. default:
  1735. throw cannotFulfillGoalException("Unknown type of goal !");
  1736. }
  1737. }
  1738. const CGTownInstance * VCAI::findTownWithTavern() const
  1739. {
  1740. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  1741. if(t->hasBuilt(EBuilding::TAVERN) && !t->visitingHero)
  1742. return t;
  1743. return NULL;
  1744. }
  1745. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1746. {
  1747. std::vector<HeroPtr> ret;
  1748. boost::copy(cb->getHeroesInfo(), std::back_inserter(ret));
  1749. BOOST_FOREACH(auto h, lockedHeroes)
  1750. {
  1751. //if (!h.second.invalid()) //we can use heroes without valid goal
  1752. if (h.second.goalType == DIG_AT_TILE || !h.first->movement) //experiment: use all heroes that have movement left, TODO: unlock heroes that couldn't realize their goals
  1753. remove_if_present(ret, h.first);
  1754. }
  1755. return ret;
  1756. }
  1757. HeroPtr VCAI::primaryHero() const
  1758. {
  1759. auto hs = cb->getHeroesInfo();
  1760. boost::sort(hs, compareHeroStrength);
  1761. if(hs.empty())
  1762. return NULL;
  1763. return hs.back();
  1764. }
  1765. void VCAI::endTurn()
  1766. {
  1767. tlog4 << "Player " << playerID << " ends turn\n";
  1768. if(!status.haveTurn())
  1769. {
  1770. tlog1 << "Not having turn at the end of turn???\n";
  1771. }
  1772. do
  1773. {
  1774. cb->endTurn();
  1775. } 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
  1776. tlog4 << "Player " << playerID << " ended turn\n";
  1777. }
  1778. void VCAI::striveToGoal(const CGoal &ultimateGoal)
  1779. {
  1780. if (ultimateGoal.invalid())
  1781. return;
  1782. CGoal abstractGoal;
  1783. while(1)
  1784. {
  1785. CGoal goal = ultimateGoal;
  1786. BNLOG("Striving to goal of type %s", goalName(ultimateGoal.goalType));
  1787. int maxGoals = 100; //preventing deadlock for mutually dependent goals
  1788. while(!goal.isElementar && !goal.isAbstract && maxGoals)
  1789. {
  1790. INDENT;
  1791. BNLOG("Considering goal %s", goalName(goal.goalType));
  1792. try
  1793. {
  1794. boost::this_thread::interruption_point();
  1795. goal = goal.whatToDoToAchieve();
  1796. --maxGoals;
  1797. }
  1798. catch(std::exception &e)
  1799. {
  1800. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1801. //setGoal (goal.hero, INVALID); //test: if we don't know how to realize goal, we should abandon it for now
  1802. return;
  1803. }
  1804. }
  1805. try
  1806. {
  1807. boost::this_thread::interruption_point();
  1808. if (goal.hero) //lock this hero to fulfill ultimate goal
  1809. {
  1810. if (maxGoals)
  1811. {
  1812. setGoal(goal.hero, goal);
  1813. }
  1814. else
  1815. {
  1816. setGoal(goal.hero, INVALID); // we seemingly don't know what to do with hero
  1817. }
  1818. }
  1819. if (goal.isAbstract)
  1820. {
  1821. abstractGoal = goal; //allow only one abstract goal per call
  1822. BNLOG("Choosing abstract goal %s", goalName(goal.goalType));
  1823. break;
  1824. }
  1825. else
  1826. tryRealize(goal);
  1827. boost::this_thread::interruption_point();
  1828. }
  1829. catch(boost::thread_interrupted &e)
  1830. {
  1831. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1832. throw; //rethrow, we want to truly end this thread
  1833. }
  1834. catch(goalFulfilledException &e)
  1835. {
  1836. completeGoal (goal);
  1837. if (maxGoals > 98) //completed goal was main goal
  1838. //TODO: find better condition
  1839. return;
  1840. }
  1841. catch(std::exception &e)
  1842. {
  1843. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1844. BNLOG("The error message was: %s", e.what());
  1845. break;
  1846. }
  1847. }
  1848. //TODO: save abstract goals not related to hero
  1849. if (!abstractGoal.invalid()) //try to realize our one goal
  1850. {
  1851. while (1)
  1852. {
  1853. CGoal goal = CGoal(abstractGoal).setisAbstract(false);
  1854. int maxGoals = 50;
  1855. while (!goal.isElementar && maxGoals) //find elementar goal and fulfill it
  1856. {
  1857. try
  1858. {
  1859. boost::this_thread::interruption_point();
  1860. goal = goal.whatToDoToAchieve();
  1861. --maxGoals;
  1862. }
  1863. catch(std::exception &e)
  1864. {
  1865. BNLOG("Goal %s decomposition failed: %s", goalName(goal.goalType) % e.what());
  1866. //setGoal (goal.hero, INVALID);
  1867. return;
  1868. }
  1869. }
  1870. try
  1871. {
  1872. boost::this_thread::interruption_point();
  1873. tryRealize(goal);
  1874. boost::this_thread::interruption_point();
  1875. }
  1876. catch(boost::thread_interrupted &e)
  1877. {
  1878. BNLOG("Player %d: Making turn thread received an interruption!", playerID);
  1879. throw; //rethrow, we want to truly end this thread
  1880. }
  1881. catch(goalFulfilledException &e)
  1882. {
  1883. completeGoal (goal);
  1884. if (maxGoals > 98) //completed goal was main goal
  1885. //TODO: find better condition
  1886. return;
  1887. }
  1888. catch(std::exception &e)
  1889. {
  1890. BNLOG("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.", goalName(goal.goalType) % goalName(ultimateGoal.goalType));
  1891. BNLOG("The error message was: %s", e.what());
  1892. break;
  1893. }
  1894. }
  1895. }
  1896. }
  1897. void VCAI::striveToQuest (const QuestInfo &q)
  1898. {
  1899. if (q.quest.progress < CQuest::COMPLETE)
  1900. {
  1901. MetaString ms;
  1902. q.quest.getRolloverText(ms, false);
  1903. BNLOG ("Trying to realize quest: %s", ms.toString());
  1904. auto heroes = cb->getHeroesInfo();
  1905. switch (q.quest.missionType)
  1906. {
  1907. case CQuest::MISSION_ART:
  1908. {
  1909. BOOST_FOREACH (auto hero, heroes) //TODO: remove duplicated code?
  1910. {
  1911. if (q.quest.checkQuest(hero))
  1912. {
  1913. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1914. return;
  1915. }
  1916. }
  1917. BOOST_FOREACH (auto art, q.quest.m5arts)
  1918. {
  1919. striveToGoal (CGoal(GET_ART_TYPE).setaid(art)); //TODO: transport?
  1920. }
  1921. break;
  1922. }
  1923. case CQuest::MISSION_HERO:
  1924. {
  1925. //striveToGoal (CGoal(RECRUIT_HERO));
  1926. BOOST_FOREACH (auto hero, heroes)
  1927. {
  1928. if (q.quest.checkQuest(hero))
  1929. {
  1930. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1931. return;
  1932. }
  1933. }
  1934. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::PRISON)); //rule of a thumb - quest heroes usually are locked in prisons
  1935. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1936. break;
  1937. }
  1938. case CQuest::MISSION_ARMY:
  1939. {
  1940. BOOST_FOREACH (auto hero, heroes)
  1941. {
  1942. if (q.quest.checkQuest(hero)) //veyr bad info - stacks can be split between multiple heroes :(
  1943. {
  1944. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1945. return;
  1946. }
  1947. }
  1948. BOOST_FOREACH (auto creature, q.quest.m6creatures)
  1949. {
  1950. striveToGoal (CGoal(GATHER_TROOPS).setobjid(creature.type->idNumber).setvalue(creature.count));
  1951. }
  1952. //TODO: exchange armies... oh my
  1953. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1954. break;
  1955. }
  1956. case CQuest::MISSION_RESOURCES:
  1957. {
  1958. if (heroes.size())
  1959. {
  1960. if (q.quest.checkQuest(heroes.front())) //it doesn't matter which hero it is
  1961. {
  1962. striveToGoal (CGoal(VISIT_TILE).settile(q.tile));
  1963. }
  1964. else
  1965. {
  1966. for (int i = 0; i < q.quest.m7resources.size(); ++i)
  1967. {
  1968. if (q.quest.m7resources[i])
  1969. striveToGoal (CGoal(COLLECT_RES).setresID(i).setvalue(q.quest.m7resources[i]));
  1970. }
  1971. }
  1972. }
  1973. else
  1974. striveToGoal (CGoal(RECRUIT_HERO)); //FIXME: checkQuest requires any hero belonging to player :(
  1975. break;
  1976. }
  1977. case CQuest::MISSION_KILL_HERO:
  1978. case CQuest::MISSION_KILL_CREATURE:
  1979. {
  1980. auto obj = cb->getObjByQuestIdentifier(q.quest.m13489val);
  1981. if (obj)
  1982. striveToGoal (CGoal(GET_OBJ).setobjid(obj->id));
  1983. else
  1984. striveToGoal (CGoal(VISIT_TILE).settile(q.tile)); //visit seer hut
  1985. break;
  1986. }
  1987. case CQuest::MISSION_PRIMARY_STAT:
  1988. {
  1989. auto heroes = cb->getHeroesInfo();
  1990. BOOST_FOREACH (auto hero, heroes)
  1991. {
  1992. if (q.quest.checkQuest(hero))
  1993. {
  1994. striveToGoal (CGoal(GET_OBJ).setobjid(q.obj->id).sethero(hero));
  1995. return;
  1996. }
  1997. }
  1998. for (int i = 0; i < q.quest.m2stats.size(); ++i)
  1999. {
  2000. BNLOG ("Don't know how to increase primary stat %d\n", i);
  2001. }
  2002. break;
  2003. }
  2004. case CQuest::MISSION_LEVEL:
  2005. {
  2006. auto heroes = cb->getHeroesInfo();
  2007. BOOST_FOREACH (auto hero, heroes)
  2008. {
  2009. if (q.quest.checkQuest(hero))
  2010. {
  2011. striveToGoal (CGoal(VISIT_TILE).settile(q.tile).sethero(hero)); //TODO: causes infinite loop :/
  2012. return;
  2013. }
  2014. }
  2015. BNLOG ("Don't know how to reach hero level %d\n", q.quest.m13489val);
  2016. break;
  2017. }
  2018. case CQuest::MISSION_PLAYER:
  2019. {
  2020. if (playerID != q.quest.m13489val)
  2021. BNLOG ("Can't be player of color %d\n", q.quest.m13489val);
  2022. break;
  2023. }
  2024. case CQuest::MISSION_KEYMASTER:
  2025. {
  2026. striveToGoal (CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(q.obj->subID));
  2027. break;
  2028. }
  2029. }
  2030. }
  2031. }
  2032. void VCAI::performTypicalActions()
  2033. {
  2034. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2035. {
  2036. BNLOG("Looking into %s", t->name);
  2037. buildStructure(t);
  2038. buildArmyIn(t);
  2039. if(!ai->primaryHero() ||
  2040. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  2041. {
  2042. recruitHero(t);
  2043. buildArmyIn(t);
  2044. }
  2045. }
  2046. BOOST_FOREACH(auto h, getUnblockedHeroes())
  2047. {
  2048. BNLOG("Looking into %s, MP=%d", h->name.c_str() % h->movement);
  2049. INDENT;
  2050. makePossibleUpgrades(*h);
  2051. cb->setSelection(*h);
  2052. try
  2053. {
  2054. wander(h);
  2055. }
  2056. catch(std::exception &e)
  2057. {
  2058. BNLOG("Cannot use this hero anymore, received exception: %s", e.what());
  2059. continue;
  2060. }
  2061. }
  2062. }
  2063. void VCAI::buildArmyIn(const CGTownInstance * t)
  2064. {
  2065. makePossibleUpgrades(t->visitingHero);
  2066. makePossibleUpgrades(t);
  2067. recruitCreatures(t);
  2068. moveCreaturesToHero(t);
  2069. }
  2070. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  2071. {
  2072. TimeCheck tc("looking for best exploration neighbour");
  2073. std::map<int3, int> dstToRevealedTiles;
  2074. BOOST_FOREACH(crint3 dir, dirs)
  2075. if(cb->isInTheMap(hpos+dir))
  2076. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir) * isSafeToVisit(h, hpos + dir);
  2077. auto best = dstToRevealedTiles.begin();
  2078. best->second *= cb->getPathInfo(best->first)->reachable();
  2079. best->second *= cb->getPathInfo(best->first)->accessible == CGPathNode::ACCESSIBLE;
  2080. for(auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  2081. {
  2082. const CGPathNode *pn = cb->getPathInfo(i->first);
  2083. //const TerrainTile *t = cb->getTile(i->first);
  2084. if(best->second < i->second && i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  2085. best = i;
  2086. }
  2087. if(best->second)
  2088. return best->first;
  2089. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  2090. }
  2091. int3 VCAI::explorationNewPoint(int radius, HeroPtr h, std::vector<std::vector<int3> > &tiles)
  2092. {
  2093. TimeCheck tc("looking for new exploration point");
  2094. PNLOG("Looking for an another place for exploration...");
  2095. tiles.resize(radius);
  2096. foreach_tile_pos([&](const int3 &pos)
  2097. {
  2098. if(!cb->isVisible(pos))
  2099. tiles[0].push_back(pos);
  2100. });
  2101. for (int i = 1; i < radius; i++)
  2102. {
  2103. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2104. removeDuplicates(tiles[i]);
  2105. BOOST_FOREACH(const int3 &tile, tiles[i])
  2106. {
  2107. if(cb->getPathInfo(tile)->reachable() && isSafeToVisit(h, tile) && howManyTilesWillBeDiscovered(tile, radius) && !isBlockedBorderGate(tile))
  2108. {
  2109. return tile;
  2110. }
  2111. }
  2112. }
  2113. throw cannotFulfillGoalException("No accessible tile will bring discoveries!");
  2114. }
  2115. TResources VCAI::estimateIncome() const
  2116. {
  2117. TResources ret;
  2118. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2119. {
  2120. ret[Res::GOLD] += t->dailyIncome();
  2121. //TODO duplikuje newturn
  2122. if(t->hasBuilt(EBuilding::RESOURCE_SILO)) //there is resource silo
  2123. {
  2124. if(t->town->primaryRes == 127) //we'll give wood and ore
  2125. {
  2126. ret[Res::WOOD] ++;
  2127. ret[Res::ORE] ++;
  2128. }
  2129. else
  2130. {
  2131. ret[t->town->primaryRes] ++;
  2132. }
  2133. }
  2134. }
  2135. BOOST_FOREACH(const CGObjectInstance *obj, getFlaggedObjects())
  2136. {
  2137. if(obj->ID == Obj::MINE)
  2138. {
  2139. switch(obj->subID)
  2140. {
  2141. case Res::WOOD:
  2142. case Res::ORE:
  2143. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2144. break;
  2145. case Res::GOLD:
  2146. case 7: //abandoned mine -> also gold
  2147. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2148. break;
  2149. default:
  2150. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2151. break;
  2152. }
  2153. }
  2154. }
  2155. return ret;
  2156. }
  2157. bool VCAI::containsSavedRes(const TResources &cost) const
  2158. {
  2159. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2160. {
  2161. if(saving[i] && cost[i])
  2162. return true;
  2163. }
  2164. return false;
  2165. }
  2166. void VCAI::checkHeroArmy (HeroPtr h)
  2167. {
  2168. auto it = lockedHeroes.find(h);
  2169. if (it != lockedHeroes.end())
  2170. {
  2171. if (it->second.goalType == GATHER_ARMY && it->second.value <= h->getArmyStrength())
  2172. completeGoal(CGoal (GATHER_ARMY).sethero(h));
  2173. }
  2174. }
  2175. void VCAI::recruitHero(const CGTownInstance * t)
  2176. {
  2177. BNLOG("Trying to recruit a hero in %s at %s", t->name % t->visitablePos())
  2178. cb->recruitHero(t, cb->getAvailableHeroes(t).front());
  2179. }
  2180. void VCAI::finish()
  2181. {
  2182. if(makingTurn)
  2183. makingTurn->interrupt();
  2184. }
  2185. void VCAI::requestActionASAP(boost::function<void()> whatToDo)
  2186. {
  2187. // static boost::mutex m;
  2188. // boost::unique_lock<boost::mutex> mylock(m);
  2189. boost::barrier b(2);
  2190. boost::thread newThread([&b,this,whatToDo]()
  2191. {
  2192. setThreadName("VCAI::requestActionASAP::helper");
  2193. SET_GLOBAL_STATE(this);
  2194. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2195. b.wait();
  2196. whatToDo();
  2197. });
  2198. b.wait();
  2199. }
  2200. void VCAI::lostHero(HeroPtr h)
  2201. {
  2202. BNLOG("I lost my hero %s. It's best to forget and move on.\n", h.name);
  2203. remove_if_present(lockedHeroes, h);
  2204. BOOST_FOREACH(auto obj, reservedHeroesMap[h])
  2205. {
  2206. remove_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2207. }
  2208. remove_if_present(reservedHeroesMap, h);
  2209. }
  2210. void VCAI::answerQuery(int queryID, int selection)
  2211. {
  2212. BNLOG("I'll answer the query %d giving the choice %d", queryID % selection);
  2213. if(queryID != -1)
  2214. {
  2215. cb->selectionMade(selection, queryID);
  2216. }
  2217. else
  2218. {
  2219. BNLOG("Since the query ID is %d, the answer won't be sent. This is not a real query!", queryID);
  2220. //do nothing
  2221. }
  2222. }
  2223. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2224. {
  2225. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2226. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2227. {
  2228. status.attemptedAnsweringQuery(reply->qid, requestID);
  2229. }
  2230. }
  2231. std::string VCAI::getBattleAIName() const
  2232. {
  2233. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2234. return settings["server"]["neutralAI"].String();
  2235. else
  2236. return "StupidAI";
  2237. }
  2238. AIStatus::AIStatus()
  2239. {
  2240. battle = NO_BATTLE;
  2241. havingTurn = false;
  2242. }
  2243. AIStatus::~AIStatus()
  2244. {
  2245. }
  2246. void AIStatus::setBattle(BattleState BS)
  2247. {
  2248. boost::unique_lock<boost::mutex> lock(mx);
  2249. battle = BS;
  2250. cv.notify_all();
  2251. }
  2252. BattleState AIStatus::getBattle()
  2253. {
  2254. boost::unique_lock<boost::mutex> lock(mx);
  2255. return battle;
  2256. }
  2257. void AIStatus::addQuery(int ID, std::string description)
  2258. {
  2259. boost::unique_lock<boost::mutex> lock(mx);
  2260. if(ID == -1)
  2261. {
  2262. BNLOG("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s", ID % description);
  2263. return;
  2264. }
  2265. assert(!vstd::contains(remainingQueries, ID));
  2266. assert(ID >= 0);
  2267. remainingQueries[ID] = description;
  2268. cv.notify_all();
  2269. BNLOG("Adding query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2270. }
  2271. void AIStatus::removeQuery(int ID)
  2272. {
  2273. boost::unique_lock<boost::mutex> lock(mx);
  2274. assert(vstd::contains(remainingQueries, ID));
  2275. std::string description = remainingQueries[ID];
  2276. remainingQueries.erase(ID);
  2277. cv.notify_all();
  2278. BNLOG("Removing query %d - %s. Total queries count: %d", ID % description % remainingQueries.size());
  2279. }
  2280. int AIStatus::getQueriesCount()
  2281. {
  2282. boost::unique_lock<boost::mutex> lock(mx);
  2283. return remainingQueries.size();
  2284. }
  2285. void AIStatus::startedTurn()
  2286. {
  2287. boost::unique_lock<boost::mutex> lock(mx);
  2288. havingTurn = true;
  2289. cv.notify_all();
  2290. }
  2291. void AIStatus::madeTurn()
  2292. {
  2293. boost::unique_lock<boost::mutex> lock(mx);
  2294. havingTurn = false;
  2295. cv.notify_all();
  2296. }
  2297. void AIStatus::waitTillFree()
  2298. {
  2299. boost::unique_lock<boost::mutex> lock(mx);
  2300. while(battle != NO_BATTLE || remainingQueries.size())
  2301. cv.wait(lock);
  2302. }
  2303. bool AIStatus::haveTurn()
  2304. {
  2305. boost::unique_lock<boost::mutex> lock(mx);
  2306. return havingTurn;
  2307. }
  2308. void AIStatus::attemptedAnsweringQuery(int queryID, int answerRequestID)
  2309. {
  2310. boost::unique_lock<boost::mutex> lock(mx);
  2311. assert(vstd::contains(remainingQueries, queryID));
  2312. std::string description = remainingQueries[queryID];
  2313. BNLOG("Attempted answering query %d - %s. Request id=%d. Waiting for results...", queryID % description % answerRequestID);
  2314. requestToQueryID[answerRequestID] = queryID;
  2315. }
  2316. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2317. {
  2318. assert(vstd::contains(requestToQueryID, answerRequestID));
  2319. int query = requestToQueryID[answerRequestID];
  2320. assert(vstd::contains(remainingQueries, query));
  2321. requestToQueryID.erase(answerRequestID);
  2322. if(result)
  2323. {
  2324. removeQuery(query);
  2325. }
  2326. else
  2327. {
  2328. tlog1 << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2329. //TODO safely retry
  2330. }
  2331. }
  2332. int3 whereToExplore(HeroPtr h)
  2333. {
  2334. //TODO it's stupid and ineffective, write sth better
  2335. cb->setSelection(*h);
  2336. int radius = h->getSightRadious();
  2337. int3 hpos = h->visitablePos();
  2338. //look for nearby objs -> visit them if they're close enouh
  2339. const int DIST_LIMIT = 3;
  2340. std::vector<const CGObjectInstance *> nearbyVisitableObjs;
  2341. BOOST_FOREACH(const CGObjectInstance *obj, ai->getPossibleDestinations(h))
  2342. {
  2343. int3 op = obj->visitablePos();
  2344. CGPath p;
  2345. cb->getPath2(op, p);
  2346. if(p.nodes.size() && p.endPos() == op && p.nodes.size() <= DIST_LIMIT)
  2347. nearbyVisitableObjs.push_back(obj);
  2348. }
  2349. boost::sort(nearbyVisitableObjs, isCloser);
  2350. if(nearbyVisitableObjs.size())
  2351. return nearbyVisitableObjs.back()->visitablePos();
  2352. try
  2353. {
  2354. return ai->explorationBestNeighbour(hpos, radius, h);
  2355. }
  2356. catch(cannotFulfillGoalException &e)
  2357. {
  2358. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2359. try
  2360. {
  2361. return ai->explorationNewPoint(radius, h, tiles);
  2362. }
  2363. catch(cannotFulfillGoalException &e)
  2364. {
  2365. std::map<int, std::vector<int3> > profits;
  2366. {
  2367. TimeCheck tc("Evaluating exploration possibilities");
  2368. tiles[0].clear(); //we can't reach FoW anyway
  2369. BOOST_FOREACH(auto &vt, tiles)
  2370. BOOST_FOREACH(auto &tile, vt)
  2371. profits[howManyTilesWillBeDiscovered(tile, radius)].push_back(tile);
  2372. }
  2373. if(profits.empty())
  2374. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  2375. auto bestDest = profits.end();
  2376. bestDest--;
  2377. return bestDest->second.front(); //TODO which is the real best tile?
  2378. }
  2379. }
  2380. }
  2381. TSubgoal CGoal::whatToDoToAchieve()
  2382. {
  2383. BNLOG("Decomposing goal of type %s", goalName(goalType));
  2384. INDENT;
  2385. switch(goalType)
  2386. {
  2387. case WIN:
  2388. {
  2389. const CVictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  2390. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  2391. if(!vc.appliesToAI)
  2392. {
  2393. //TODO deduce victory from human loss condition
  2394. cond = EVictoryConditionType::WINSTANDARD;
  2395. }
  2396. switch(cond)
  2397. {
  2398. case EVictoryConditionType::ARTIFACT:
  2399. return CGoal(GET_ART_TYPE).setaid(vc.ID);
  2400. case EVictoryConditionType::BEATHERO:
  2401. return CGoal(GET_OBJ).setobjid(vc.ID);
  2402. case EVictoryConditionType::BEATMONSTER:
  2403. return CGoal(GET_OBJ).setobjid(vc.ID);
  2404. case EVictoryConditionType::BUILDCITY:
  2405. //TODO build castle/capitol
  2406. break;
  2407. case EVictoryConditionType::BUILDGRAIL:
  2408. {
  2409. if(auto h = ai->getHeroWithGrail())
  2410. {
  2411. //hero is in a town that can host Grail
  2412. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, EBuilding::GRAIL))
  2413. {
  2414. const CGTownInstance *t = h->visitedTown;
  2415. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::GRAIL).settown(t);
  2416. }
  2417. else
  2418. {
  2419. auto towns = cb->getTownsInfo();
  2420. towns.erase(boost::remove_if(towns,
  2421. [](const CGTownInstance *t) -> bool
  2422. {
  2423. return vstd::contains(t->forbiddenBuildings, EBuilding::GRAIL);
  2424. }),
  2425. towns.end());
  2426. boost::sort(towns, isCloser);
  2427. if(towns.size())
  2428. {
  2429. return CGoal(VISIT_TILE).sethero(h).settile(towns.front()->visitablePos());
  2430. }
  2431. }
  2432. }
  2433. double ratio = 0;
  2434. int3 grailPos = cb->getGrailPos(ratio);
  2435. if(ratio > 0.99)
  2436. {
  2437. return CGoal(DIG_AT_TILE).settile(grailPos);
  2438. } //TODO: use FIND_OBJ
  2439. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  2440. {
  2441. return CGoal(GET_OBJ).setobjid(obj->id);
  2442. }
  2443. else
  2444. return CGoal(EXPLORE);
  2445. }
  2446. break;
  2447. case EVictoryConditionType::CAPTURECITY:
  2448. return CGoal(GET_OBJ).setobjid(vc.ID);
  2449. case EVictoryConditionType::GATHERRESOURCE:
  2450. return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
  2451. //TODO mines? piles? marketplace?
  2452. //save?
  2453. break;
  2454. case EVictoryConditionType::GATHERTROOP:
  2455. return CGoal(GATHER_TROOPS).setobjid(vc.ID).setvalue(vc.count);
  2456. break;
  2457. case EVictoryConditionType::TAKEDWELLINGS:
  2458. break;
  2459. case EVictoryConditionType::TAKEMINES:
  2460. break;
  2461. case EVictoryConditionType::TRANSPORTITEM:
  2462. break;
  2463. case EVictoryConditionType::WINSTANDARD:
  2464. return CGoal(CONQUER);
  2465. default:
  2466. assert(0);
  2467. }
  2468. }
  2469. break;
  2470. case FIND_OBJ:
  2471. {
  2472. const CGObjectInstance * o = NULL;
  2473. if (resID > -1) //specified
  2474. {
  2475. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2476. {
  2477. if(obj->ID == objid && obj->subID == resID)
  2478. {
  2479. o = obj;
  2480. break; //TODO: consider multiple objects and choose best
  2481. }
  2482. }
  2483. }
  2484. else
  2485. {
  2486. BOOST_FOREACH(const CGObjectInstance *obj, ai->visitableObjs)
  2487. {
  2488. if(obj->ID == objid)
  2489. {
  2490. o = obj;
  2491. break; //TODO: consider multiple objects and choose best
  2492. }
  2493. }
  2494. }
  2495. if (o)
  2496. return CGoal(GET_OBJ).setobjid(o->id);
  2497. else
  2498. return CGoal(EXPLORE);
  2499. }
  2500. break;
  2501. case GET_OBJ:
  2502. {
  2503. const CGObjectInstance * obj = cb->getObj(objid);
  2504. if(!obj)
  2505. return CGoal(EXPLORE);
  2506. int3 pos = obj->visitablePos();
  2507. return CGoal(VISIT_TILE).settile(pos);
  2508. }
  2509. break;
  2510. case VISIT_HERO:
  2511. {
  2512. const CGObjectInstance * obj = cb->getObj(objid);
  2513. if(!obj)
  2514. return CGoal(EXPLORE);
  2515. int3 pos = obj->visitablePos();
  2516. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  2517. return CGoal(*this).settile(pos).setisElementar(true);
  2518. }
  2519. break;
  2520. case GET_ART_TYPE:
  2521. {
  2522. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  2523. if(alternativeWay.invalid())
  2524. return CGoal(FIND_OBJ).setobjid(Obj::ARTIFACT).setresID(aid);
  2525. }
  2526. break;
  2527. case CLEAR_WAY_TO:
  2528. {
  2529. assert(tile.x >= 0); //set tile
  2530. if(!cb->isVisible(tile))
  2531. {
  2532. tlog1 << "Clear way should be used with visible tiles!\n";
  2533. return CGoal(EXPLORE);
  2534. }
  2535. HeroPtr h = hero ? hero : ai->primaryHero();
  2536. if(!h)
  2537. return CGoal(RECRUIT_HERO);
  2538. cb->setSelection(*h);
  2539. SectorMap sm;
  2540. bool dropToFile = false;
  2541. if(dropToFile) //for debug purposes
  2542. sm.write("test.txt");
  2543. int3 tileToHit = sm.firstTileToGet(h, tile);
  2544. //if(isSafeToVisit(h, tileToHit))
  2545. if(isBlockedBorderGate(tileToHit))
  2546. { //FIXME: this way we'll not visit gate and activate quest :?
  2547. return CGoal(FIND_OBJ).setobjid(Obj::KEYMASTER).setresID(cb->getTile(tileToHit)->visitableObjects.back()->subID);
  2548. }
  2549. //FIXME: this code shouldn't be necessary
  2550. if(tileToHit == tile)
  2551. {
  2552. tlog1 << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  2553. % tileToHit % tile % h->name % h->visitablePos();
  2554. throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  2555. }
  2556. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  2557. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != 0)
  2558. {
  2559. std::string problem = boost::str(boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText());
  2560. throw cannotFulfillGoalException(problem);
  2561. }
  2562. return CGoal(VISIT_TILE).settile(tileToHit).sethero(h); //FIXME:: attempts to visit completely unreachable tile with hero results in stall
  2563. //TODO czy istnieje lepsza droga?
  2564. }
  2565. throw cannotFulfillGoalException("Cannot reach given tile!");
  2566. //return CGoal(EXPLORE); // TODO improve
  2567. case EXPLORE:
  2568. {
  2569. if (hero)
  2570. {
  2571. return CGoal(VISIT_TILE).settile(whereToExplore(hero)).sethero(hero);
  2572. }
  2573. auto hs = cb->getHeroesInfo();
  2574. int howManyHeroes = hs.size();
  2575. erase(hs, [](const CGHeroInstance *h)
  2576. {
  2577. return contains(ai->lockedHeroes, h);
  2578. });
  2579. if(hs.empty()) //all heroes are busy. buy new one
  2580. {
  2581. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2582. return CGoal(RECRUIT_HERO);
  2583. else //find mobile hero with weakest army
  2584. {
  2585. hs = cb->getHeroesInfo();
  2586. erase_if(hs, [](const CGHeroInstance *h)
  2587. {
  2588. return !h->movement; //only hero with movement are of interest for us
  2589. });
  2590. if (hs.empty())
  2591. {
  2592. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2593. return CGoal(RECRUIT_HERO);
  2594. else
  2595. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2596. }
  2597. boost::sort(hs, compareMovement); //closer to what?
  2598. }
  2599. }
  2600. const CGHeroInstance *h = hs.front();
  2601. return (*this).sethero(h).setisAbstract(true);
  2602. }
  2603. I_AM_ELEMENTAR;
  2604. case RECRUIT_HERO:
  2605. {
  2606. const CGTownInstance *t = ai->findTownWithTavern();
  2607. if(!t)
  2608. return CGoal(BUILD_STRUCTURE).setbid(EBuilding::TAVERN);
  2609. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  2610. return CGoal(COLLECT_RES).setresID(Res::GOLD).setvalue(HERO_GOLD_COST);
  2611. I_AM_ELEMENTAR;
  2612. }
  2613. break;
  2614. case VISIT_TILE:
  2615. {
  2616. if(!cb->isVisible(tile))
  2617. return CGoal(EXPLORE);
  2618. if(hero && !ai->isAccessibleForHero(tile, hero))
  2619. hero = NULL;
  2620. if(!hero)
  2621. {
  2622. if(cb->getHeroesInfo().empty())
  2623. {
  2624. return CGoal(RECRUIT_HERO);
  2625. }
  2626. BOOST_FOREACH(const CGHeroInstance *h, cb->getHeroesInfo())
  2627. {
  2628. if(ai->isAccessibleForHero(tile, h))
  2629. {
  2630. hero = h;
  2631. break;
  2632. }
  2633. }
  2634. }
  2635. if(hero)
  2636. {
  2637. if(isSafeToVisit(hero, tile))
  2638. return CGoal(*this).setisElementar(true);
  2639. else
  2640. {
  2641. return CGoal(GATHER_ARMY).sethero(hero).setvalue(evaluateDanger(tile, *hero) * SAFE_ATTACK_CONSTANT); //TODO: should it be abstract?
  2642. }
  2643. }
  2644. else //inaccessible for all heroes
  2645. {
  2646. return CGoal(CLEAR_WAY_TO).settile(tile);
  2647. }
  2648. }
  2649. break;
  2650. case DIG_AT_TILE:
  2651. {
  2652. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  2653. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  2654. {
  2655. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  2656. return CGoal(*this).sethero(h).setisElementar(true);
  2657. }
  2658. return CGoal(VISIT_TILE).settile(tile);
  2659. }
  2660. break;
  2661. case BUILD_STRUCTURE:
  2662. //TODO check res
  2663. //look for town
  2664. //prerequisites?
  2665. I_AM_ELEMENTAR;
  2666. case COLLECT_RES:
  2667. {
  2668. std::vector<const IMarket*> markets;
  2669. std::vector<const CGObjectInstance*> visObjs;
  2670. ai->retreiveVisitableObjs(visObjs, true);
  2671. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  2672. {
  2673. if(const IMarket *m = IMarket::castFrom(obj, false))
  2674. {
  2675. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  2676. markets.push_back(m);
  2677. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  2678. markets.push_back(m);
  2679. }
  2680. }
  2681. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  2682. {
  2683. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  2684. });
  2685. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  2686. {
  2687. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  2688. && !ai->isAccessible(market->o->visitablePos());
  2689. }),markets.end());
  2690. if(!markets.size())
  2691. {
  2692. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2693. {
  2694. if(cb->canBuildStructure(t, EBuilding::MARKETPLACE) == EBuildingState::ALLOWED)
  2695. return CGoal(BUILD_STRUCTURE).settown(t).setbid(EBuilding::MARKETPLACE);
  2696. }
  2697. }
  2698. else
  2699. {
  2700. const IMarket *m = markets.back();
  2701. //attempt trade at back (best prices)
  2702. int howManyCanWeBuy = 0;
  2703. for(int i = 0; i < ACTUAL_RESOURCE_COUNT; i++)
  2704. {
  2705. if(i == resID) continue;
  2706. int toGive = -1, toReceive = -1;
  2707. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  2708. assert(toGive > 0 && toReceive > 0);
  2709. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  2710. }
  2711. if(howManyCanWeBuy + cb->getResourceAmount(resID) >= value)
  2712. {
  2713. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  2714. assert(backObj);
  2715. if(backObj->tempOwner != ai->playerID)
  2716. return CGoal(GET_OBJ).setobjid(m->o->id);
  2717. return setobjid(m->o->id).setisElementar(true);
  2718. }
  2719. }
  2720. }
  2721. return CGoal(INVALID);
  2722. case GATHER_TROOPS:
  2723. {
  2724. std::vector<const CGDwelling *> dwellings;
  2725. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2726. {
  2727. auto creature = VLC->creh->creatures[objid];
  2728. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  2729. {
  2730. auto creatures = t->town->creatures[creature->level];
  2731. int upgradeNumber = std::find(creatures.begin(), creatures.end(), creature->idNumber) - creatures.begin();
  2732. int bid = EBuilding::DWELL_FIRST + creature->level + upgradeNumber * GameConstants::CREATURES_PER_TOWN;
  2733. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  2734. {
  2735. dwellings.push_back(t);
  2736. }
  2737. else
  2738. {
  2739. return CGoal (BUILD_STRUCTURE).settown(t).setbid(bid);
  2740. }
  2741. }
  2742. }
  2743. BOOST_FOREACH (auto obj, ai->visitableObjs)
  2744. {
  2745. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  2746. continue;
  2747. auto d = dynamic_cast<const CGDwelling *>(obj);
  2748. BOOST_FOREACH (auto creature, d->creatures)
  2749. {
  2750. if (creature.first) //there are more than 0 creatures avaliabe
  2751. {
  2752. BOOST_FOREACH (auto type, creature.second)
  2753. {
  2754. if (type == objid)
  2755. dwellings.push_back(d);
  2756. }
  2757. }
  2758. }
  2759. }
  2760. if (dwellings.size())
  2761. {
  2762. boost::sort(dwellings, isCloser);
  2763. return CGoal(GET_OBJ).setobjid (dwellings.front()->id); //TODO: consider needed resources
  2764. }
  2765. else
  2766. return CGoal(EXPLORE);
  2767. //TODO: exchange troops between heroes
  2768. }
  2769. break;
  2770. case CONQUER: //TODO: put it into a function?
  2771. {
  2772. auto hs = cb->getHeroesInfo();
  2773. int howManyHeroes = hs.size();
  2774. erase(hs, [](const CGHeroInstance *h)
  2775. {
  2776. return contains(ai->lockedHeroes, h);
  2777. });
  2778. if(hs.empty()) //all heroes are busy. buy new one
  2779. {
  2780. if (howManyHeroes < 3 && ai->findTownWithTavern()) //we may want to recruit second hero. TODO: make it smart finally
  2781. return CGoal(RECRUIT_HERO);
  2782. else //find mobile hero with weakest army
  2783. {
  2784. hs = cb->getHeroesInfo();
  2785. erase_if(hs, [](const CGHeroInstance *h)
  2786. {
  2787. return !h->movement; //only hero with movement are of interest for us
  2788. });
  2789. if (hs.empty())
  2790. {
  2791. if (howManyHeroes < GameConstants::MAX_HEROES_PER_PLAYER)
  2792. return CGoal(RECRUIT_HERO);
  2793. else
  2794. throw cannotFulfillGoalException("No heroes with remaining MPs for exploring!\n");
  2795. }
  2796. boost::sort(hs, compareHeroStrength);
  2797. }
  2798. }
  2799. const CGHeroInstance *h = hs.back();
  2800. cb->setSelection(h);
  2801. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  2802. ai->retreiveVisitableObjs(objs);
  2803. erase_if(objs, [&](const CGObjectInstance *obj)
  2804. {
  2805. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO) //not town/hero
  2806. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != 0; //not enemy
  2807. });
  2808. if(objs.empty())
  2809. return CGoal(EXPLORE); //we need to find an enemy
  2810. erase_if(objs, [&](const CGObjectInstance *obj)
  2811. {
  2812. return !isSafeToVisit(h, obj->visitablePos());
  2813. });
  2814. if(objs.empty())
  2815. I_AM_ELEMENTAR;
  2816. boost::sort(objs, isCloser);
  2817. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2818. {
  2819. if(ai->isAccessibleForHero(obj->visitablePos(), h))
  2820. {
  2821. if (obj->ID == Obj::HERO)
  2822. return CGoal(VISIT_HERO).sethero(h).setobjid(obj->id).setisAbstract(true); //track enemy hero
  2823. else
  2824. return CGoal(VISIT_TILE).sethero(h).settile(obj->visitablePos());
  2825. }
  2826. }
  2827. return CGoal(EXPLORE); //enemy is inaccessible
  2828. }
  2829. break;
  2830. case BUILD:
  2831. I_AM_ELEMENTAR;
  2832. case INVALID:
  2833. I_AM_ELEMENTAR;
  2834. case GATHER_ARMY:
  2835. {
  2836. //TODO: find hero if none set
  2837. assert(hero);
  2838. cb->setSelection(*hero);
  2839. auto compareReinforcements = [this](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  2840. {
  2841. return howManyReinforcementsCanGet(hero, lhs) < howManyReinforcementsCanGet(hero, rhs);
  2842. };
  2843. std::vector<const CGTownInstance *> townsReachable;
  2844. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  2845. {
  2846. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  2847. {
  2848. if(isReachable(t) && !vstd::contains (ai->townVisitsThisWeek[hero], t))
  2849. townsReachable.push_back(t);
  2850. }
  2851. }
  2852. if(townsReachable.size()) //try towns first
  2853. {
  2854. boost::sort(townsReachable, compareReinforcements);
  2855. return CGoal(VISIT_TILE).sethero(hero).settile(townsReachable.back()->visitablePos());
  2856. }
  2857. else
  2858. {
  2859. if (hero == ai->primaryHero()) //we can get army from other heroes
  2860. {
  2861. auto otherHeroes = cb->getHeroesInfo();
  2862. auto heroDummy = hero;
  2863. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  2864. {
  2865. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->pos, h, true) || !ai->canGetArmy(heroDummy.h, h));
  2866. });
  2867. if (otherHeroes.size())
  2868. {
  2869. boost::sort(otherHeroes, compareArmyStrength); //TODO: check if hero has at least one stack more powerful than ours? not likely to fail
  2870. int primaryPath, secondaryPath;
  2871. auto h = otherHeroes.back();
  2872. cb->setSelection(hero.h);
  2873. primaryPath = cb->getPathInfo(h->pos)->turns; //FIXME: investigate crash at this line
  2874. cb->setSelection(h);
  2875. secondaryPath = cb->getPathInfo(hero->pos)->turns;
  2876. if (primaryPath < secondaryPath)
  2877. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(h->id).sethero(hero); //go to the other hero if we are faster
  2878. else
  2879. return CGoal(VISIT_HERO).setisAbstract(true).setobjid(hero->id).sethero(h); //let the other hero come to us
  2880. }
  2881. }
  2882. std::vector<const CGObjectInstance *> objs; //here we'll gather all dwellings
  2883. ai->retreiveVisitableObjs(objs);
  2884. erase_if(objs, [&](const CGObjectInstance *obj)
  2885. {
  2886. return (obj->ID != Obj::CREATURE_GENERATOR1);
  2887. });
  2888. if(objs.empty()) //no possible objects, we did eveyrthing already
  2889. return CGoal(EXPLORE).sethero(hero);
  2890. //TODO: check if we can recruit any creatures there, evaluate army
  2891. else
  2892. {
  2893. boost::sort(objs, isCloser);
  2894. HeroPtr h = NULL;
  2895. BOOST_FOREACH(const CGObjectInstance *obj, objs)
  2896. { //find safe dwelling
  2897. auto pos = obj->visitablePos();
  2898. if (shouldVisit (hero, obj)) //creatures fit in army
  2899. h = hero;
  2900. else
  2901. {
  2902. BOOST_FOREACH(auto ourHero, cb->getHeroesInfo()) //make use of multiple heroes
  2903. {
  2904. if (shouldVisit(ourHero, obj))
  2905. h = ourHero;
  2906. }
  2907. }
  2908. if (h && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  2909. return CGoal(VISIT_TILE).sethero(h).settile(pos);
  2910. }
  2911. }
  2912. }
  2913. return CGoal(EXPLORE).sethero(hero); //find dwelling. use current hero to prevent him from doing nothing.
  2914. }
  2915. break;
  2916. default:
  2917. assert(0);
  2918. }
  2919. return CGoal(EXPLORE);
  2920. }
  2921. TSubgoal CGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  2922. {
  2923. if(obj)
  2924. return CGoal(GET_OBJ).setobjid(obj->id);
  2925. else
  2926. return CGoal(EXPLORE);
  2927. }
  2928. TSubgoal CGoal::lookForArtSmart(int aid)
  2929. {
  2930. return CGoal(INVALID);
  2931. }
  2932. bool CGoal::invalid() const
  2933. {
  2934. return goalType == INVALID;
  2935. }
  2936. bool isBlockedBorderGate(int3 tileToHit)
  2937. {
  2938. return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
  2939. && cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
  2940. }
  2941. SectorMap::SectorMap()
  2942. {
  2943. // int3 sizes = cb->getMapSize();
  2944. // sector.resize(sizes.x);
  2945. // BOOST_FOREACH(auto &i, sector)
  2946. // i.resize(sizes.y);
  2947. //
  2948. // BOOST_FOREACH(auto &i, sector)
  2949. // BOOST_FOREACH(auto &j, i)
  2950. // j.resize(sizes.z, 0);
  2951. update();
  2952. }
  2953. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2954. {
  2955. if(t->blocked && !t->visitable)
  2956. {
  2957. sec = NOT_AVAILABLE;
  2958. return true;
  2959. }
  2960. return false;
  2961. }
  2962. bool markIfBlocked(ui8 &sec, crint3 pos)
  2963. {
  2964. return markIfBlocked(sec, pos, cb->getTile(pos));
  2965. }
  2966. void SectorMap::update()
  2967. {
  2968. clear();
  2969. int curSector = 3; //0 is invisible, 1 is not explored
  2970. foreach_tile_pos([&](crint3 pos)
  2971. {
  2972. if(retreiveTile(pos) == NOT_CHECKED)
  2973. {
  2974. if(!markIfBlocked(retreiveTile(pos), pos))
  2975. exploreNewSector(pos, curSector++);
  2976. }
  2977. });
  2978. valid = true;
  2979. }
  2980. void SectorMap::clear()
  2981. {
  2982. sector = cb->getVisibilityMap();
  2983. valid = false;
  2984. }
  2985. bool canBeEmbarkmentPoint(const TerrainTile *t)
  2986. {
  2987. //tile must be free of with unoccupied boat
  2988. return !t->blocked
  2989. || (t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT);
  2990. }
  2991. void SectorMap::exploreNewSector(crint3 pos, int num)
  2992. {
  2993. Sector &s = infoOnSectors[num];
  2994. s.id = num;
  2995. s.water = cb->getTile(pos)->isWater();
  2996. std::queue<int3> toVisit;
  2997. toVisit.push(pos);
  2998. while(toVisit.size())
  2999. {
  3000. int3 curPos = toVisit.front();
  3001. toVisit.pop();
  3002. ui8 &sec = retreiveTile(curPos);
  3003. if(sec == NOT_CHECKED)
  3004. {
  3005. const TerrainTile *t = cb->getTile(curPos);
  3006. if(!markIfBlocked(sec, curPos, t))
  3007. {
  3008. if(t->isWater() == s.water) //sector is only-water or only-land
  3009. {
  3010. sec = num;
  3011. s.tiles.push_back(curPos);
  3012. foreach_neighbour(curPos, [&](crint3 neighPos)
  3013. {
  3014. if(retreiveTile(neighPos) == NOT_CHECKED)
  3015. {
  3016. toVisit.push(neighPos);
  3017. //parent[neighPos] = curPos;
  3018. }
  3019. const TerrainTile *nt = cb->getTile(neighPos, false);
  3020. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt))
  3021. {
  3022. s.embarkmentPoints.push_back(neighPos);
  3023. }
  3024. });
  3025. if(t->visitable && vstd::contains(ai->knownSubterraneanGates, t->visitableObjects.front()))
  3026. toVisit.push(ai->knownSubterraneanGates[t->visitableObjects.front()]->pos);
  3027. }
  3028. }
  3029. }
  3030. }
  3031. removeDuplicates(s.embarkmentPoints);
  3032. }
  3033. void SectorMap::write(crstring fname)
  3034. {
  3035. std::ofstream out(fname);
  3036. for(int k = 0; k < cb->getMapSize().z; k++)
  3037. {
  3038. for(int j = 0; j < cb->getMapSize().y; j++)
  3039. {
  3040. for(int i = 0; i < cb->getMapSize().x; i++)
  3041. {
  3042. out << (int)sector[i][j][k] << '\t';
  3043. }
  3044. out << std::endl;
  3045. }
  3046. out << std::endl;
  3047. }
  3048. }
  3049. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  3050. { //TODO: allow polling of remaining creatures in dwelling
  3051. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  3052. dynamic_cast<const CGDwelling *>(obj) ||
  3053. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  3054. return true;
  3055. switch (obj->ID)
  3056. {
  3057. case Obj::STABLES:
  3058. case Obj::MAGIC_WELL:
  3059. case Obj::HILL_FORT:
  3060. return true;
  3061. break;
  3062. case Obj::BORDER_GATE:
  3063. case Obj::BORDERGUARD:
  3064. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  3065. break;
  3066. }
  3067. return false;
  3068. }
  3069. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  3070. {
  3071. switch (obj->ID)
  3072. {
  3073. case Obj::BORDERGUARD:
  3074. case Obj::BORDER_GATE:
  3075. case Obj::SEER_HUT:
  3076. case Obj::QUEST_GUARD:
  3077. {
  3078. //return false; //fixme: avoid crash
  3079. BOOST_FOREACH (auto q, ai->myCb->getMyQuests())
  3080. {
  3081. if (q.obj == obj)
  3082. {
  3083. if (q.quest.checkQuest(*h))
  3084. return true; //we completed the quest
  3085. else
  3086. return false; //we can't complete this quest
  3087. }
  3088. }
  3089. return true; //we don't have this quest yet
  3090. break;
  3091. }
  3092. case Obj::CREATURE_GENERATOR1:
  3093. {
  3094. if (obj->tempOwner != h->tempOwner)
  3095. return true; //flag just in case
  3096. bool canRecruitCreatures = false;
  3097. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  3098. BOOST_FOREACH(auto level, d->creatures)
  3099. {
  3100. BOOST_FOREACH(auto c, level.second)
  3101. {
  3102. if (h->getSlotFor(c) != -1)
  3103. canRecruitCreatures = true;
  3104. }
  3105. }
  3106. return canRecruitCreatures;
  3107. break;
  3108. }
  3109. case Obj::HILL_FORT:
  3110. {
  3111. BOOST_FOREACH (auto slot, h->Slots())
  3112. {
  3113. if (slot.second->type->upgrades.size())
  3114. return true; //TODO: check price?
  3115. }
  3116. return false;
  3117. break;
  3118. }
  3119. case Obj::MONOLITH1:
  3120. case Obj::MONOLITH2:
  3121. case Obj::MONOLITH3:
  3122. case Obj::WHIRLPOOL:
  3123. //TODO: mechanism for handling monoliths
  3124. return false;
  3125. break;
  3126. case Obj::SCHOOL_OF_MAGIC:
  3127. case Obj::SCHOOL_OF_WAR:
  3128. {
  3129. TResources myRes = ai->myCb->getResourceAmount();
  3130. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  3131. return false;
  3132. }
  3133. break;
  3134. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  3135. if (h->level < 12)
  3136. return false;
  3137. break;
  3138. case Obj::TREE_OF_KNOWLEDGE:
  3139. {
  3140. TResources myRes = ai->myCb->getResourceAmount();
  3141. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  3142. return false;
  3143. }
  3144. break;
  3145. case Obj::MAGIC_WELL:
  3146. return h->mana < h->manaLimit();
  3147. break;
  3148. case Obj::BOAT:
  3149. return false;
  3150. //Boats are handled by pathfinder
  3151. }
  3152. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  3153. return false;
  3154. return true;
  3155. }
  3156. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  3157. {
  3158. int sourceSector = retreiveTile(h->visitablePos()),
  3159. destinationSector = retreiveTile(dst);
  3160. if(sourceSector != destinationSector)
  3161. {
  3162. const Sector *src = &infoOnSectors[sourceSector],
  3163. *dst = &infoOnSectors[destinationSector];
  3164. std::map<const Sector*, const Sector*> preds;
  3165. std::queue<const Sector *> sq;
  3166. sq.push(src);
  3167. while(!sq.empty())
  3168. {
  3169. const Sector *s = sq.front();
  3170. sq.pop();
  3171. BOOST_FOREACH(int3 ep, s->embarkmentPoints)
  3172. {
  3173. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  3174. //preds[s].push_back(neigh);
  3175. if(!preds[neigh])
  3176. {
  3177. preds[neigh] = s;
  3178. sq.push(neigh);
  3179. }
  3180. }
  3181. //TODO consider other types of connections between sectors?
  3182. }
  3183. if(!preds[dst])
  3184. {
  3185. write("test.txt");
  3186. ai->completeGoal (CGoal(EXPLORE).sethero(h)); //if we can't find the way, seemingly all tiles were explored
  3187. //TODO: more organized way?
  3188. throw cannotFulfillGoalException(str(format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  3189. }
  3190. std::vector<const Sector*> toTraverse;
  3191. toTraverse.push_back(dst);
  3192. while(toTraverse.back() != src)
  3193. {
  3194. toTraverse.push_back(preds[toTraverse.back()]);
  3195. }
  3196. if(preds[dst])
  3197. {
  3198. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  3199. if(!src->water && sectorToReach->water) //embark
  3200. {
  3201. //embark on ship -> look for an EP with a boat
  3202. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  3203. {
  3204. const TerrainTile *t = cb->getTile(pos);
  3205. return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
  3206. && retreiveTile(pos) == sectorToReach->id;
  3207. });
  3208. if(firstEP != src->embarkmentPoints.end())
  3209. {
  3210. return *firstEP;
  3211. }
  3212. else
  3213. {
  3214. //we need to find a shipyard with an access to the desired sector's EP
  3215. //TODO what about Summon Boat spell?
  3216. std::vector<const IShipyard *> shipyards;
  3217. BOOST_FOREACH(const CGTownInstance *t, cb->getTownsInfo())
  3218. {
  3219. if(t->hasBuilt(EBuilding::SHIPYARD))
  3220. shipyards.push_back(t);
  3221. }
  3222. std::vector<const CGObjectInstance*> visObjs;
  3223. ai->retreiveVisitableObjs(visObjs, true);
  3224. BOOST_FOREACH(const CGObjectInstance *obj, visObjs)
  3225. {
  3226. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  3227. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  3228. shipyards.push_back(shipyard);
  3229. }
  3230. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  3231. {
  3232. return shipyard->state() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  3233. }),shipyards.end());
  3234. if(!shipyards.size())
  3235. {
  3236. //TODO consider possibility of building shipyard in a town
  3237. throw cannotFulfillGoalException("There is no known shipyard!");
  3238. }
  3239. //we have only shipyards that possibly can build ships onto the appropriate EP
  3240. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  3241. {
  3242. return s->o->tempOwner == ai->playerID;
  3243. });
  3244. if(ownedGoodShipyard != shipyards.end())
  3245. {
  3246. const IShipyard *s = *ownedGoodShipyard;
  3247. TResources shipCost;
  3248. s->getBoatCost(shipCost);
  3249. if(cb->getResourceAmount().canAfford(shipCost))
  3250. {
  3251. int3 ret = s->bestLocation();
  3252. cb->buildBoat(s);
  3253. return ret;
  3254. }
  3255. else
  3256. {
  3257. //TODO gather res
  3258. throw cannotFulfillGoalException("Not enough resources to build a boat");
  3259. }
  3260. }
  3261. else
  3262. {
  3263. //TODO pick best shipyard to take over
  3264. return shipyards.front()->o->pos;
  3265. }
  3266. }
  3267. }
  3268. else if(src->water && !sectorToReach->water)
  3269. {
  3270. //TODO
  3271. //disembark
  3272. }
  3273. else
  3274. {
  3275. //TODO
  3276. //transition between two land/water sectors. Monolith? Whirlpool? ...
  3277. throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  3278. }
  3279. }
  3280. else
  3281. {
  3282. throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  3283. }
  3284. }
  3285. else
  3286. {
  3287. makeParentBFS(h->visitablePos());
  3288. int3 curtile = dst;
  3289. while(curtile != h->visitablePos())
  3290. {
  3291. if(cb->getPathInfo(curtile)->reachable())
  3292. {
  3293. return curtile;
  3294. }
  3295. else
  3296. {
  3297. auto i = parent.find(curtile);
  3298. if(i != parent.end())
  3299. {
  3300. assert(curtile != i->second);
  3301. curtile = i->second;
  3302. }
  3303. else
  3304. throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  3305. }
  3306. }
  3307. }
  3308. throw cannotFulfillGoalException("Impossible happened.");
  3309. }
  3310. void SectorMap::makeParentBFS(crint3 source)
  3311. {
  3312. parent.clear();
  3313. int mySector = retreiveTile(source);
  3314. std::queue<int3> toVisit;
  3315. toVisit.push(source);
  3316. while(toVisit.size())
  3317. {
  3318. int3 curPos = toVisit.front();
  3319. toVisit.pop();
  3320. ui8 &sec = retreiveTile(curPos);
  3321. assert(sec == mySector); //consider only tiles from the same sector
  3322. //const TerrainTile *t = cb->getTile(curPos);
  3323. foreach_neighbour(curPos, [&](crint3 neighPos)
  3324. {
  3325. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  3326. {
  3327. toVisit.push(neighPos);
  3328. parent[neighPos] = curPos;
  3329. }
  3330. });
  3331. }
  3332. }
  3333. unsigned char & SectorMap::retreiveTile(crint3 pos)
  3334. {
  3335. return retreiveTileN(sector, pos);
  3336. }
  3337. const CGObjectInstance * ObjectIdRef::operator->() const
  3338. {
  3339. return cb->getObj(id, false);
  3340. }
  3341. ObjectIdRef::operator const CGObjectInstance*() const
  3342. {
  3343. return cb->getObj(id, false);
  3344. }
  3345. ObjectIdRef::ObjectIdRef(int _id) : id(_id)
  3346. {
  3347. }
  3348. ObjectIdRef::ObjectIdRef(const CGObjectInstance *obj) : id(obj->id)
  3349. {
  3350. }
  3351. bool ObjectIdRef::operator<(const ObjectIdRef &rhs) const
  3352. {
  3353. return id < rhs.id;
  3354. }
  3355. HeroPtr::HeroPtr(const CGHeroInstance *H)
  3356. {
  3357. if(!H)
  3358. {
  3359. //init from nullptr should equal to default init
  3360. *this = HeroPtr();
  3361. return;
  3362. }
  3363. h = H;
  3364. name = h->name;
  3365. hid = H->id;
  3366. // infosCount[ai->playerID][hid]++;
  3367. }
  3368. HeroPtr::HeroPtr()
  3369. {
  3370. h = nullptr;
  3371. hid = -1;
  3372. }
  3373. HeroPtr::~HeroPtr()
  3374. {
  3375. // if(hid >= 0)
  3376. // infosCount[ai->playerID][hid]--;
  3377. }
  3378. bool HeroPtr::operator<(const HeroPtr &rhs) const
  3379. {
  3380. return hid < rhs.hid;
  3381. }
  3382. const CGHeroInstance * HeroPtr::get(bool doWeExpectNull /*= false*/) const
  3383. {
  3384. //TODO? check if these all assertions every time we get info about hero affect efficiency
  3385. //
  3386. //behave terribly when attempting unauthorized access to hero that is not ours (or was lost)
  3387. assert(doWeExpectNull || h);
  3388. if(h)
  3389. {
  3390. auto obj = cb->getObj(hid);
  3391. const bool owned = obj && obj->tempOwner == ai->playerID;
  3392. if(doWeExpectNull && !owned)
  3393. {
  3394. return nullptr;
  3395. }
  3396. else
  3397. {
  3398. assert(obj);
  3399. assert(owned);
  3400. }
  3401. }
  3402. return h;
  3403. }
  3404. const CGHeroInstance * HeroPtr::operator->() const
  3405. {
  3406. return get();
  3407. }
  3408. bool HeroPtr::validAndSet() const
  3409. {
  3410. return get(true);
  3411. }
  3412. const CGHeroInstance * HeroPtr::operator*() const
  3413. {
  3414. return get();
  3415. }