VCAI.cpp 107 KB

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