VCAI.cpp 112 KB

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