VCAI.cpp 96 KB

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