VCAI.cpp 115 KB

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