VCAI.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159
  1. #include "StdInc.h"
  2. #include "VCAI.h"
  3. #include "Goals.h"
  4. #include "../../lib/UnlockGuard.h"
  5. #include "../../lib/mapObjects/MapObjects.h"
  6. #include "../../lib/CConfigHandler.h"
  7. #include "../../lib/CHeroHandler.h"
  8. /*
  9. * CCreatureHandler.h, part of VCMI engine
  10. *
  11. * Authors: listed in file AUTHORS in main folder
  12. *
  13. * License: GNU General Public License v2.0 or later
  14. * Full text of license available in license.txt file, in main folder
  15. *
  16. */
  17. extern FuzzyHelper *fh;
  18. class CGVisitableOPW;
  19. const double SAFE_ATTACK_CONSTANT = 1.5;
  20. 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)
  21. using namespace vstd;
  22. //one thread may be turn of AI and another will be handling a side effect for AI2
  23. boost::thread_specific_ptr<CCallback> cb;
  24. boost::thread_specific_ptr<VCAI> ai;
  25. //std::map<int, std::map<int, int> > HeroView::infosCount;
  26. //helper RAII to manage global ai/cb ptrs
  27. struct SetGlobalState
  28. {
  29. SetGlobalState(VCAI * AI)
  30. {
  31. assert(!ai.get());
  32. assert(!cb.get());
  33. ai.reset(AI);
  34. cb.reset(AI->myCb.get());
  35. }
  36. ~SetGlobalState()
  37. {
  38. ai.release();
  39. cb.release();
  40. }
  41. };
  42. #define SET_GLOBAL_STATE(ai) SetGlobalState _hlpSetState(ai);
  43. #define NET_EVENT_HANDLER SET_GLOBAL_STATE(this)
  44. #define MAKING_TURN SET_GLOBAL_STATE(this)
  45. unsigned char &retreiveTileN(std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  46. {
  47. return vectors[pos.x][pos.y][pos.z];
  48. }
  49. const unsigned char &retreiveTileN(const std::vector< std::vector< std::vector<unsigned char> > > &vectors, const int3 &pos)
  50. {
  51. return vectors[pos.x][pos.y][pos.z];
  52. }
  53. void foreach_tile(std::vector< std::vector< std::vector<unsigned char> > > &vectors, std::function<void(unsigned char &in)> foo)
  54. {
  55. for(auto & vector : vectors)
  56. for(auto j = vector.begin(); j != vector.end(); j++)
  57. for(auto & elem : *j)
  58. foo(elem);
  59. }
  60. struct ObjInfo
  61. {
  62. int3 pos;
  63. std::string name;
  64. ObjInfo(){}
  65. ObjInfo(const CGObjectInstance *obj):
  66. pos(obj->pos),
  67. name(obj->getHoverText())
  68. {
  69. }
  70. };
  71. std::map<const CGObjectInstance *, ObjInfo> helperObjInfo;
  72. VCAI::VCAI(void)
  73. {
  74. LOG_TRACE(logAi);
  75. makingTurn = nullptr;
  76. }
  77. VCAI::~VCAI(void)
  78. {
  79. LOG_TRACE(logAi);
  80. }
  81. void VCAI::availableCreaturesChanged(const CGDwelling *town)
  82. {
  83. LOG_TRACE(logAi);
  84. NET_EVENT_HANDLER;
  85. }
  86. void VCAI::heroMoved(const TryMoveHero & details)
  87. {
  88. LOG_TRACE(logAi);
  89. NET_EVENT_HANDLER;
  90. validateObject(details.id); //enemy hero may have left visible area
  91. if(details.result == TryMoveHero::TELEPORTATION)
  92. {
  93. const int3 from = CGHeroInstance::convertPosition(details.start, false),
  94. to = CGHeroInstance::convertPosition(details.end, false);
  95. const CGObjectInstance *o1 = frontOrNull(cb->getVisitableObjs(from)),
  96. *o2 = frontOrNull(cb->getVisitableObjs(to));
  97. if(o1 && o2 && o1->ID == Obj::SUBTERRANEAN_GATE && o2->ID == Obj::SUBTERRANEAN_GATE)
  98. {
  99. knownSubterraneanGates[o1] = o2;
  100. knownSubterraneanGates[o2] = o1;
  101. logAi->debugStream() << boost::format("Found a pair of subterranean gates between %s and %s!") % from % to;
  102. }
  103. }
  104. }
  105. void VCAI::stackChagedCount(const StackLocation &location, const TQuantity &change, bool isAbsolute)
  106. {
  107. LOG_TRACE_PARAMS(logAi, "isAbsolute '%i'", isAbsolute);
  108. NET_EVENT_HANDLER;
  109. }
  110. void VCAI::heroInGarrisonChange(const CGTownInstance *town)
  111. {
  112. LOG_TRACE(logAi);
  113. NET_EVENT_HANDLER;
  114. }
  115. void VCAI::centerView(int3 pos, int focusTime)
  116. {
  117. LOG_TRACE_PARAMS(logAi, "focusTime '%i'", focusTime);
  118. NET_EVENT_HANDLER;
  119. }
  120. void VCAI::artifactMoved(const ArtifactLocation &src, const ArtifactLocation &dst)
  121. {
  122. LOG_TRACE(logAi);
  123. NET_EVENT_HANDLER;
  124. }
  125. void VCAI::artifactAssembled(const ArtifactLocation &al)
  126. {
  127. LOG_TRACE(logAi);
  128. NET_EVENT_HANDLER;
  129. }
  130. void VCAI::showTavernWindow(const CGObjectInstance *townOrTavern)
  131. {
  132. LOG_TRACE(logAi);
  133. NET_EVENT_HANDLER;
  134. }
  135. void VCAI::showThievesGuildWindow (const CGObjectInstance * obj)
  136. {
  137. LOG_TRACE(logAi);
  138. NET_EVENT_HANDLER;
  139. }
  140. void VCAI::playerBlocked(int reason, bool start)
  141. {
  142. LOG_TRACE_PARAMS(logAi, "reason '%i', start '%i'", reason % start);
  143. NET_EVENT_HANDLER;
  144. if (start && reason == PlayerBlocked::UPCOMING_BATTLE)
  145. status.setBattle(UPCOMING_BATTLE);
  146. if(reason == PlayerBlocked::ONGOING_MOVEMENT)
  147. status.setMove(start);
  148. }
  149. void VCAI::showPuzzleMap()
  150. {
  151. LOG_TRACE(logAi);
  152. NET_EVENT_HANDLER;
  153. }
  154. void VCAI::showShipyardDialog(const IShipyard *obj)
  155. {
  156. LOG_TRACE(logAi);
  157. NET_EVENT_HANDLER;
  158. }
  159. void VCAI::gameOver(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult)
  160. {
  161. LOG_TRACE_PARAMS(logAi, "victoryLossCheckResult '%s'", victoryLossCheckResult);
  162. NET_EVENT_HANDLER;
  163. logAi->debugStream() << boost::format("Player %d: I heard that player %d %s.") % playerID % player.getNum() % (victoryLossCheckResult.victory() ? "won" : "lost");
  164. if(player == playerID)
  165. {
  166. if(victoryLossCheckResult.victory())
  167. {
  168. logAi->debugStream() << "VCAI: I won! Incredible!";
  169. logAi->debugStream() << "Turn nr " << myCb->getDate();
  170. }
  171. else
  172. {
  173. logAi->debugStream() << "VCAI: Player " << player << " lost. It's me. What a disappointment! :(";
  174. }
  175. finish();
  176. }
  177. }
  178. void VCAI::artifactPut(const ArtifactLocation &al)
  179. {
  180. LOG_TRACE(logAi);
  181. NET_EVENT_HANDLER;
  182. }
  183. void VCAI::artifactRemoved(const ArtifactLocation &al)
  184. {
  185. LOG_TRACE(logAi);
  186. NET_EVENT_HANDLER;
  187. }
  188. void VCAI::stacksErased(const StackLocation &location)
  189. {
  190. LOG_TRACE(logAi);
  191. NET_EVENT_HANDLER;
  192. }
  193. void VCAI::artifactDisassembled(const ArtifactLocation &al)
  194. {
  195. LOG_TRACE(logAi);
  196. NET_EVENT_HANDLER;
  197. }
  198. void VCAI::heroVisit(const CGHeroInstance *visitor, const CGObjectInstance *visitedObj, bool start)
  199. {
  200. LOG_TRACE_PARAMS(logAi, "start '%i'; obj '%s'", start % (visitedObj ? visitedObj->hoverName : std::string("n/a")));
  201. NET_EVENT_HANDLER;
  202. if(start)
  203. {
  204. markObjectVisited (visitedObj);
  205. unreserveObject(visitor, visitedObj);
  206. completeGoal (sptr(Goals::GetObj(visitedObj->id.getNum()).sethero(visitor))); //we don't need to visit it anymore
  207. //TODO: what if we visited one-time visitable object that was reserved by another hero (shouldn't, but..)
  208. }
  209. status.heroVisit(visitedObj, start);
  210. }
  211. void VCAI::availableArtifactsChanged(const CGBlackMarket *bm /*= nullptr*/)
  212. {
  213. LOG_TRACE(logAi);
  214. NET_EVENT_HANDLER;
  215. }
  216. void VCAI::heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town)
  217. {
  218. LOG_TRACE(logAi);
  219. NET_EVENT_HANDLER;
  220. //buildArmyIn(town);
  221. //moveCreaturesToHero(town);
  222. }
  223. void VCAI::tileHidden(const std::unordered_set<int3, ShashInt3> &pos)
  224. {
  225. LOG_TRACE(logAi);
  226. NET_EVENT_HANDLER;
  227. validateVisitableObjs();
  228. }
  229. void VCAI::tileRevealed(const std::unordered_set<int3, ShashInt3> &pos)
  230. {
  231. LOG_TRACE(logAi);
  232. NET_EVENT_HANDLER;
  233. for(int3 tile : pos)
  234. for(const CGObjectInstance *obj : myCb->getVisitableObjs(tile))
  235. addVisitableObj(obj);
  236. clearHeroesUnableToExplore();
  237. }
  238. void VCAI::heroExchangeStarted(ObjectInstanceID hero1, ObjectInstanceID hero2, QueryID query)
  239. {
  240. LOG_TRACE(logAi);
  241. NET_EVENT_HANDLER;
  242. auto firstHero = cb->getHero(hero1);
  243. auto secondHero = cb->getHero(hero2);
  244. status.addQuery(query, boost::str(boost::format("Exchange between heroes %s and %s") % firstHero->name % secondHero->name));
  245. requestActionASAP([=]()
  246. {
  247. float goalpriority1 = 0, goalpriority2 = 0;
  248. auto firstGoal = getGoal(firstHero);
  249. if (firstGoal->goalType == Goals::GATHER_ARMY)
  250. goalpriority1 = firstGoal->priority;
  251. auto secondGoal = getGoal(secondHero);
  252. if (secondGoal->goalType == Goals::GATHER_ARMY)
  253. goalpriority2 = secondGoal->priority;
  254. if (goalpriority1 > goalpriority2)
  255. pickBestCreatures (firstHero, secondHero);
  256. else if (goalpriority1 < goalpriority2)
  257. pickBestCreatures (secondHero, firstHero);
  258. else //regular criteria
  259. {
  260. if (firstHero->getFightingStrength() > secondHero->getFightingStrength() && canGetArmy (firstHero, secondHero))
  261. pickBestCreatures (firstHero, secondHero);
  262. else if (canGetArmy (secondHero, firstHero))
  263. pickBestCreatures (secondHero, firstHero);
  264. completeGoal(sptr(Goals::VisitHero(firstHero->id.getNum()))); //TODO: what if we were visited by other hero in the meantime?
  265. completeGoal(sptr(Goals::VisitHero(secondHero->id.getNum())));
  266. //TODO: exchange artifacts
  267. }
  268. answerQuery(query, 0);
  269. });
  270. }
  271. void VCAI::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, si64 val)
  272. {
  273. LOG_TRACE_PARAMS(logAi, "which '%i', val '%i'", which % val);
  274. NET_EVENT_HANDLER;
  275. }
  276. void VCAI::showRecruitmentDialog(const CGDwelling *dwelling, const CArmedInstance *dst, int level)
  277. {
  278. LOG_TRACE_PARAMS(logAi, "level '%i'", level);
  279. NET_EVENT_HANDLER;
  280. }
  281. void VCAI::heroMovePointsChanged(const CGHeroInstance * hero)
  282. {
  283. LOG_TRACE(logAi);
  284. NET_EVENT_HANDLER;
  285. }
  286. void VCAI::stackChangedType(const StackLocation &location, const CCreature &newType)
  287. {
  288. LOG_TRACE(logAi);
  289. NET_EVENT_HANDLER;
  290. }
  291. void VCAI::stacksRebalanced(const StackLocation &src, const StackLocation &dst, TQuantity count)
  292. {
  293. LOG_TRACE(logAi);
  294. NET_EVENT_HANDLER;
  295. }
  296. void VCAI::newObject(const CGObjectInstance * obj)
  297. {
  298. LOG_TRACE(logAi);
  299. NET_EVENT_HANDLER;
  300. if(obj->isVisitable())
  301. addVisitableObj(obj);
  302. clearHeroesUnableToExplore();
  303. }
  304. void VCAI::objectRemoved(const CGObjectInstance *obj)
  305. {
  306. LOG_TRACE(logAi);
  307. NET_EVENT_HANDLER;
  308. erase_if_present(visitableObjs, obj);
  309. erase_if_present(alreadyVisited, obj);
  310. for (auto h : cb->getHeroesInfo())
  311. unreserveObject(h, obj);
  312. //TODO
  313. //there are other places where CGObjectinstance ptrs are stored...
  314. //
  315. if(obj->ID == Obj::HERO && obj->tempOwner == playerID)
  316. {
  317. lostHero(cb->getHero(obj->id)); //we can promote, since objectRemoved is called just before actual deletion
  318. }
  319. }
  320. void VCAI::showHillFortWindow(const CGObjectInstance *object, const CGHeroInstance *visitor)
  321. {
  322. LOG_TRACE(logAi);
  323. NET_EVENT_HANDLER;
  324. requestActionASAP([=]()
  325. {
  326. makePossibleUpgrades(visitor);
  327. });
  328. }
  329. void VCAI::playerBonusChanged(const Bonus &bonus, bool gain)
  330. {
  331. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  332. NET_EVENT_HANDLER;
  333. }
  334. void VCAI::newStackInserted(const StackLocation &location, const CStackInstance &stack)
  335. {
  336. LOG_TRACE(logAi);
  337. NET_EVENT_HANDLER;
  338. }
  339. void VCAI::heroCreated(const CGHeroInstance* h)
  340. {
  341. LOG_TRACE(logAi);
  342. if (h->visitedTown)
  343. townVisitsThisWeek[HeroPtr(h)].insert(h->visitedTown);
  344. NET_EVENT_HANDLER;
  345. }
  346. void VCAI::advmapSpellCast(const CGHeroInstance * caster, int spellID)
  347. {
  348. LOG_TRACE_PARAMS(logAi, "spellID '%i", spellID);
  349. NET_EVENT_HANDLER;
  350. }
  351. void VCAI::showInfoDialog(const std::string &text, const std::vector<Component*> &components, int soundID)
  352. {
  353. LOG_TRACE_PARAMS(logAi, "soundID '%i'", soundID);
  354. NET_EVENT_HANDLER;
  355. }
  356. void VCAI::requestRealized(PackageApplied *pa)
  357. {
  358. LOG_TRACE(logAi);
  359. NET_EVENT_HANDLER;
  360. if(status.haveTurn())
  361. {
  362. if(pa->packType == typeList.getTypeID<EndTurn>())
  363. if(pa->result)
  364. status.madeTurn();
  365. }
  366. if(pa->packType == typeList.getTypeID<QueryReply>())
  367. {
  368. status.receivedAnswerConfirmation(pa->requestID, pa->result);
  369. }
  370. }
  371. void VCAI::receivedResource(int type, int val)
  372. {
  373. LOG_TRACE_PARAMS(logAi, "type '%i', val '%i'", type % val);
  374. NET_EVENT_HANDLER;
  375. }
  376. void VCAI::stacksSwapped(const StackLocation &loc1, const StackLocation &loc2)
  377. {
  378. LOG_TRACE(logAi);
  379. NET_EVENT_HANDLER;
  380. }
  381. void VCAI::showUniversityWindow(const IMarket *market, const CGHeroInstance *visitor)
  382. {
  383. LOG_TRACE(logAi);
  384. NET_EVENT_HANDLER;
  385. }
  386. void VCAI::heroManaPointsChanged(const CGHeroInstance * hero)
  387. {
  388. LOG_TRACE(logAi);
  389. NET_EVENT_HANDLER;
  390. }
  391. void VCAI::heroSecondarySkillChanged(const CGHeroInstance * hero, int which, int val)
  392. {
  393. LOG_TRACE_PARAMS(logAi, "which '%d', val '%d'", which % val);
  394. NET_EVENT_HANDLER;
  395. }
  396. void VCAI::battleResultsApplied()
  397. {
  398. LOG_TRACE(logAi);
  399. NET_EVENT_HANDLER;
  400. assert(status.getBattle() == ENDING_BATTLE);
  401. status.setBattle(NO_BATTLE);
  402. }
  403. void VCAI::objectPropertyChanged(const SetObjectProperty * sop)
  404. {
  405. LOG_TRACE(logAi);
  406. NET_EVENT_HANDLER;
  407. if(sop->what == ObjProperty::OWNER)
  408. {
  409. if(sop->val == playerID.getNum())
  410. erase_if_present(visitableObjs, myCb->getObj(sop->id));
  411. //TODO restore lost obj
  412. }
  413. }
  414. void VCAI::buildChanged(const CGTownInstance *town, BuildingID buildingID, int what)
  415. {
  416. LOG_TRACE_PARAMS(logAi, "what '%i'", what);
  417. NET_EVENT_HANDLER;
  418. }
  419. void VCAI::heroBonusChanged(const CGHeroInstance *hero, const Bonus &bonus, bool gain)
  420. {
  421. LOG_TRACE_PARAMS(logAi, "gain '%i'", gain);
  422. NET_EVENT_HANDLER;
  423. }
  424. void VCAI::showMarketWindow(const IMarket *market, const CGHeroInstance *visitor)
  425. {
  426. LOG_TRACE(logAi);
  427. NET_EVENT_HANDLER;
  428. }
  429. void VCAI::init(shared_ptr<CCallback> CB)
  430. {
  431. LOG_TRACE(logAi);
  432. myCb = CB;
  433. cbc = CB;
  434. NET_EVENT_HANDLER;
  435. playerID = *myCb->getMyColor();
  436. myCb->waitTillRealize = true;
  437. myCb->unlockGsWhenWaiting = true;
  438. if(!fh)
  439. fh = new FuzzyHelper();
  440. retreiveVisitableObjs(visitableObjs);
  441. }
  442. void VCAI::yourTurn()
  443. {
  444. LOG_TRACE(logAi);
  445. NET_EVENT_HANDLER;
  446. status.startedTurn();
  447. makingTurn = make_unique<boost::thread>(&VCAI::makeTurn, this);
  448. }
  449. void VCAI::heroGotLevel(const CGHeroInstance *hero, PrimarySkill::PrimarySkill pskill, std::vector<SecondarySkill> &skills, QueryID queryID)
  450. {
  451. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  452. NET_EVENT_HANDLER;
  453. status.addQuery(queryID, boost::str(boost::format("Hero %s got level %d") % hero->name % hero->level));
  454. requestActionASAP([=]{ answerQuery(queryID, 0); });
  455. }
  456. void VCAI::commanderGotLevel (const CCommanderInstance * commander, std::vector<ui32> skills, QueryID queryID)
  457. {
  458. LOG_TRACE_PARAMS(logAi, "queryID '%i'", queryID);
  459. NET_EVENT_HANDLER;
  460. status.addQuery(queryID, boost::str(boost::format("Commander %s of %s got level %d") % commander->name % commander->armyObj->nodeName() % (int)commander->level));
  461. requestActionASAP([=]{ answerQuery(queryID, 0); });
  462. }
  463. void VCAI::showBlockingDialog(const std::string &text, const std::vector<Component> &components, QueryID askID, const int soundID, bool selection, bool cancel)
  464. {
  465. LOG_TRACE_PARAMS(logAi, "text '%s', askID '%i', soundID '%i', selection '%i', cancel '%i'", text % askID % soundID % selection % cancel);
  466. NET_EVENT_HANDLER;
  467. int sel = 0;
  468. status.addQuery(askID, boost::str(boost::format("Blocking dialog query with %d components - %s")
  469. % components.size() % text));
  470. if(selection) //select from multiple components -> take the last one (they're indexed [1-size])
  471. sel = components.size();
  472. if(!selection && cancel) //yes&no -> always answer yes, we are a brave AI :)
  473. sel = 1;
  474. requestActionASAP([=]()
  475. {
  476. answerQuery(askID, sel);
  477. });
  478. }
  479. void VCAI::showGarrisonDialog(const CArmedInstance *up, const CGHeroInstance *down, bool removableUnits, QueryID queryID)
  480. {
  481. LOG_TRACE_PARAMS(logAi, "removableUnits '%i', queryID '%i'", removableUnits % queryID);
  482. NET_EVENT_HANDLER;
  483. std::string s1 = up ? up->nodeName() : "NONE";
  484. std::string s2 = down ? down->nodeName() : "NONE";
  485. status.addQuery(queryID, boost::str(boost::format("Garrison dialog with %s and %s") % s1 % s2));
  486. //you can't request action from action-response thread
  487. requestActionASAP([=]()
  488. {
  489. pickBestCreatures (down, up);
  490. answerQuery(queryID, 0);
  491. });
  492. }
  493. void VCAI::saveGame(COSer<CSaveFile> &h, const int version)
  494. {
  495. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  496. NET_EVENT_HANDLER;
  497. validateVisitableObjs();
  498. registerGoals(h);
  499. CAdventureAI::saveGame(h, version);
  500. serializeInternal(h, version);
  501. }
  502. void VCAI::loadGame(CISer<CLoadFile> &h, const int version)
  503. {
  504. LOG_TRACE_PARAMS(logAi, "version '%i'", version);
  505. NET_EVENT_HANDLER;
  506. registerGoals(h);
  507. CAdventureAI::loadGame(h, version);
  508. serializeInternal(h, version);
  509. }
  510. void makePossibleUpgrades(const CArmedInstance *obj)
  511. {
  512. if(!obj)
  513. return;
  514. for(int i = 0; i < GameConstants::ARMY_SIZE; i++)
  515. {
  516. if(const CStackInstance *s = obj->getStackPtr(SlotID(i)))
  517. {
  518. UpgradeInfo ui;
  519. cb->getUpgradeInfo(obj, SlotID(i), ui);
  520. if(ui.oldID >= 0 && cb->getResourceAmount().canAfford(ui.cost[0] * s->count))
  521. {
  522. cb->upgradeCreature(obj, SlotID(i), ui.newID[0]);
  523. }
  524. }
  525. }
  526. }
  527. void VCAI::makeTurn()
  528. {
  529. MAKING_TURN;
  530. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  531. setThreadName("VCAI::makeTurn");
  532. logGlobal->infoStream() << boost::format("Player %d starting turn") % static_cast<int>(playerID.getNum());
  533. switch(cb->getDate(Date::DAY_OF_WEEK))
  534. {
  535. case 1:
  536. {
  537. townVisitsThisWeek.clear();
  538. std::vector<const CGObjectInstance *> objs;
  539. retreiveVisitableObjs(objs, true);
  540. for(const CGObjectInstance *obj : objs)
  541. {
  542. if (isWeeklyRevisitable(obj))
  543. {
  544. visitableObjs.insert(obj); //set doesn't need duplicate check
  545. erase_if_present (alreadyVisited, obj);
  546. }
  547. }
  548. }
  549. break;
  550. }
  551. if(cb->getSelectedHero())
  552. cb->recalculatePaths();
  553. markHeroAbleToExplore (primaryHero());
  554. makeTurnInternal();
  555. makingTurn.reset();
  556. return;
  557. }
  558. void VCAI::makeTurnInternal()
  559. {
  560. saving = 0;
  561. //it looks messy here, but it's better to have armed heroes before attempting realizing goals
  562. for(const CGTownInstance *t : cb->getTownsInfo())
  563. moveCreaturesToHero(t);
  564. try
  565. {
  566. //Pick objects reserved in previous turn - we expect only nerby objects there
  567. auto reservedHeroesCopy = reservedHeroesMap; //work on copy => the map may be changed while iterating (eg because hero died when attempting a goal)
  568. for (auto hero : reservedHeroesCopy)
  569. {
  570. if(reservedHeroesMap.count(hero.first))
  571. continue; //hero might have been removed while we were in this loop
  572. if(!hero.first.validAndSet())
  573. {
  574. logAi->errorStream() << "Hero " << hero.first.name << " present on reserved map. Shouldn't be. ";
  575. continue;
  576. }
  577. cb->setSelection(hero.first.get());
  578. std::vector<const CGObjectInstance *> vec(hero.second.begin(), hero.second.end());
  579. boost::sort (vec, isCloser);
  580. for (auto obj : vec)
  581. {
  582. if(!obj || !cb->getObj(obj->id))
  583. {
  584. logAi->errorStream() << "Error: there is wrong object on list for hero " << hero.first->name;
  585. continue;
  586. }
  587. striveToGoal (sptr(Goals::VisitTile(obj->visitablePos()).sethero(hero.first)));
  588. }
  589. }
  590. //now try to win
  591. striveToGoal(sptr(Goals::Win()));
  592. //finally, continue our abstract long-term goals
  593. int oldMovement = 0;
  594. int newMovement = 0;
  595. while (true)
  596. {
  597. oldMovement = newMovement; //remember old value
  598. newMovement = 0;
  599. std::vector<std::pair<HeroPtr, Goals::TSubgoal> > safeCopy;
  600. for (auto mission : lockedHeroes)
  601. {
  602. fh->setPriority (mission.second); //re-evaluate
  603. if (canAct(mission.first))
  604. {
  605. newMovement += mission.first->movement;
  606. safeCopy.push_back (mission);
  607. }
  608. }
  609. if (newMovement == oldMovement) //means our heroes didn't move or didn't re-assign their goals
  610. {
  611. logAi->warnStream() << "Our heroes don't move anymore, exhaustive decomposition failed";
  612. break;
  613. }
  614. if (safeCopy.empty())
  615. break; //all heroes exhausted their locked goals
  616. else
  617. {
  618. typedef std::pair<HeroPtr, Goals::TSubgoal> TItrType;
  619. auto lockedHeroesSorter = [](TItrType m1, TItrType m2) -> bool
  620. {
  621. return m1.second->priority < m2.second->priority;
  622. };
  623. boost::sort(safeCopy, lockedHeroesSorter);
  624. striveToGoal (safeCopy.back().second);
  625. }
  626. }
  627. auto quests = myCb->getMyQuests();
  628. for (auto quest : quests)
  629. {
  630. striveToQuest (quest);
  631. }
  632. striveToGoal(sptr(Goals::Build())); //TODO: smarter building management
  633. performTypicalActions();
  634. //for debug purpose
  635. for (auto h : cb->getHeroesInfo())
  636. {
  637. if (h->movement)
  638. logAi->warnStream() << boost::format("hero %s has %d MP left") % h->name % h->movement;
  639. }
  640. }
  641. catch(boost::thread_interrupted &e)
  642. {
  643. logAi->debugStream() << "Making turn thread has been interrupted. We'll end without calling endTurn.";
  644. return;
  645. }
  646. catch(std::exception &e)
  647. {
  648. logAi->debugStream() << "Making turn thread has caught an exception: " << e.what();
  649. }
  650. endTurn();
  651. }
  652. bool VCAI::goVisitObj(const CGObjectInstance * obj, HeroPtr h)
  653. {
  654. int3 dst = obj->visitablePos();
  655. logAi->debugStream() << boost::format("%s will try to visit %s at (%s)") % h->name % obj->getHoverText() % strFromInt3(dst);
  656. return moveHeroToTile(dst, h);
  657. }
  658. void VCAI::performObjectInteraction(const CGObjectInstance * obj, HeroPtr h)
  659. {
  660. LOG_TRACE_PARAMS(logAi, "Hero %s and object %s at %s", h->name % obj->getHoverText() % obj->pos);
  661. switch (obj->ID)
  662. {
  663. case Obj::CREATURE_GENERATOR1:
  664. recruitCreatures (dynamic_cast<const CGDwelling *>(obj));
  665. checkHeroArmy (h);
  666. break;
  667. case Obj::TOWN:
  668. moveCreaturesToHero (dynamic_cast<const CGTownInstance *>(obj));
  669. if (h->visitedTown) //we are inside, not just attacking
  670. {
  671. townVisitsThisWeek[h].insert(h->visitedTown);
  672. if (!h->hasSpellbook() && cb->getResourceAmount(Res::GOLD) >= GameConstants::SPELLBOOK_GOLD_COST + saving[Res::GOLD] &&
  673. h->visitedTown->hasBuilt (BuildingID::MAGES_GUILD_1))
  674. cb->buyArtifact(h.get(), ArtifactID::SPELLBOOK);
  675. }
  676. break;
  677. }
  678. completeGoal (sptr(Goals::GetObj(obj->id.getNum()).sethero(h)));
  679. }
  680. void VCAI::moveCreaturesToHero(const CGTownInstance * t)
  681. {
  682. if(t->visitingHero && t->armedGarrison() && t->visitingHero->tempOwner == t->tempOwner)
  683. {
  684. pickBestCreatures (t->visitingHero, t);
  685. }
  686. }
  687. bool VCAI::canGetArmy (const CGHeroInstance * army, const CGHeroInstance * source)
  688. { //TODO: merge with pickBestCreatures
  689. //if (ai->primaryHero().h == source)
  690. if(army->tempOwner != source->tempOwner)
  691. {
  692. logAi->errorStream() << "Why are we even considering exchange between heroes from different players?";
  693. return false;
  694. }
  695. const CArmedInstance *armies[] = {army, source};
  696. //we calculate total strength for each creature type available in armies
  697. std::map<const CCreature*, int> creToPower;
  698. for(auto armyPtr : armies)
  699. for(auto &i : armyPtr->Slots())
  700. {
  701. //TODO: allow splitting stacks?
  702. creToPower[i.second->type] += i.second->getPower();
  703. }
  704. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  705. int armySize = creToPower.size();
  706. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  707. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  708. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  709. {
  710. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  711. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  712. {
  713. return lhs.second < rhs.second;
  714. });
  715. bestArmy.push_back(creIt->first);
  716. creToPower.erase(creIt);
  717. if(creToPower.empty())
  718. break;
  719. }
  720. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  721. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  722. {
  723. for(auto armyPtr : armies)
  724. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  725. {
  726. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && armyPtr != army) //it's a searched creature not in dst ARMY
  727. {
  728. //FIXME: line below is useless when simulating exchange between two non-singular armies
  729. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature
  730. return true; //at least one exchange will be performed
  731. else
  732. return false; //no further exchange possible
  733. }
  734. }
  735. }
  736. return false;
  737. }
  738. void VCAI::pickBestCreatures(const CArmedInstance * army, const CArmedInstance * source)
  739. {
  740. //TODO - what if source is a hero (the last stack problem) -> it'd good to create a single stack of weakest cre
  741. const CArmedInstance *armies[] = {army, source};
  742. //we calculate total strength for each creature type available in armies
  743. std::map<const CCreature*, int> creToPower;
  744. for(auto armyPtr : armies)
  745. for(auto &i : armyPtr->Slots())
  746. {//TODO: allow splitting stacks?
  747. creToPower[i.second->type] += i.second->getPower();
  748. }
  749. //TODO - consider more than just power (ie morale penalty, hero specialty in certain stacks, etc)
  750. int armySize = creToPower.size();
  751. armySize = std::min ((source->needsLastStack() ? armySize - 1 : armySize), GameConstants::ARMY_SIZE); //can't move away last stack
  752. std::vector<const CCreature *> bestArmy; //types that'll be in final dst army
  753. for (int i = 0; i < armySize; i++) //pick the creatures from which we can get most power, as many as dest can fit
  754. {
  755. typedef const std::pair<const CCreature*, int> &CrePowerPair;
  756. auto creIt = boost::max_element(creToPower, [](CrePowerPair lhs, CrePowerPair rhs)
  757. {
  758. return lhs.second < rhs.second;
  759. });
  760. bestArmy.push_back(creIt->first);
  761. creToPower.erase(creIt);
  762. if(creToPower.empty())
  763. break;
  764. }
  765. //foreach best type -> iterate over slots in both armies and if it's the appropriate type, send it to the slot where it belongs
  766. for (int i = 0; i < bestArmy.size(); i++) //i-th strongest creature type will go to i-th slot
  767. {
  768. for(auto armyPtr : armies)
  769. for (int j = 0; j < GameConstants::ARMY_SIZE; j++)
  770. {
  771. if(armyPtr->getCreature(SlotID(j)) == bestArmy[i] && (i != j || armyPtr != army)) //it's a searched creature not in dst SLOT
  772. if (!(armyPtr->needsLastStack() && armyPtr->Slots().size() == 1)) //can't take away last creature
  773. cb->mergeOrSwapStacks(armyPtr, army, SlotID(j), SlotID(i));
  774. }
  775. }
  776. //TODO - having now strongest possible army, we may want to think about arranging stacks
  777. auto hero = dynamic_cast<const CGHeroInstance *>(army);
  778. if (hero)
  779. {
  780. checkHeroArmy (hero);
  781. }
  782. }
  783. void VCAI::recruitCreatures(const CGDwelling * d)
  784. {
  785. for(int i = 0; i < d->creatures.size(); i++)
  786. {
  787. if(!d->creatures[i].second.size())
  788. continue;
  789. int count = d->creatures[i].first;
  790. CreatureID creID = d->creatures[i].second.back();
  791. // const CCreature *c = VLC->creh->creatures[creID];
  792. // if(containsSavedRes(c->cost))
  793. // continue;
  794. amin(count, freeResources() / VLC->creh->creatures[creID]->cost);
  795. if(count > 0)
  796. cb->recruitCreatures(d, creID, count, i);
  797. }
  798. }
  799. bool VCAI::tryBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays)
  800. {
  801. if (maxDays == 0)
  802. {
  803. logAi->warnStream() << "Request to build building " << building << " in 0 days!";
  804. return false;
  805. }
  806. if (!vstd::contains(t->town->buildings, building))
  807. return false; // no such building in town
  808. if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  809. return true;
  810. const CBuilding * buildPtr = t->town->buildings.at(building);
  811. auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  812. {
  813. return t->hasBuilt(buildID);
  814. });
  815. toBuild.push_back(building);
  816. for(BuildingID buildID : toBuild)
  817. {
  818. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  819. if (canBuild == EBuildingState::HAVE_CAPITAL
  820. || canBuild == EBuildingState::FORBIDDEN
  821. || canBuild == EBuildingState::NO_WATER)
  822. return false; //we won't be able to build this
  823. }
  824. if (maxDays && toBuild.size() > maxDays)
  825. return false;
  826. TResources currentRes = cb->getResourceAmount();
  827. //TODO: calculate if we have enough resources to build it in maxDays
  828. for(const auto & buildID : toBuild)
  829. {
  830. const CBuilding *b = t->town->buildings.at(buildID);
  831. EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  832. if(canBuild == EBuildingState::ALLOWED)
  833. {
  834. if(!containsSavedRes(b->resources))
  835. {
  836. logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  837. cb->buildBuilding(t, buildID);
  838. return true;
  839. }
  840. continue;
  841. }
  842. else if(canBuild == EBuildingState::NO_RESOURCES)
  843. {
  844. //TResources income = estimateIncome();
  845. TResources cost = t->town->buildings.at(buildID)->resources;
  846. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  847. {
  848. //int diff = currentRes[i] - cost[i] + income[i];
  849. int diff = currentRes[i] - cost[i];
  850. if(diff < 0)
  851. saving[i] = 1;
  852. }
  853. continue;
  854. }
  855. else if (canBuild == EBuildingState::PREREQUIRES)
  856. {
  857. // can happen when dependencies have their own missing dependencies
  858. if (tryBuildStructure(t, buildID, maxDays - 1))
  859. return true;
  860. }
  861. else if (canBuild == EBuildingState::MISSING_BASE)
  862. {
  863. if (tryBuildStructure(t, b->upgrade, maxDays - 1))
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. //bool VCAI::canBuildStructure(const CGTownInstance * t, BuildingID building, unsigned int maxDays=7)
  870. //{
  871. // if (maxDays == 0)
  872. // {
  873. // logAi->warnStream() << "Request to build building " << building << " in 0 days!";
  874. // return false;
  875. // }
  876. //
  877. // if (!vstd::contains(t->town->buildings, building))
  878. // return false; // no such building in town
  879. //
  880. // if (t->hasBuilt(building)) //Already built? Shouldn't happen in general
  881. // return true;
  882. //
  883. // const CBuilding * buildPtr = t->town->buildings.at(building);
  884. //
  885. // auto toBuild = buildPtr->requirements.getFulfillmentCandidates([&](const BuildingID & buildID)
  886. // {
  887. // return t->hasBuilt(buildID);
  888. // });
  889. // toBuild.push_back(building);
  890. //
  891. // for(BuildingID buildID : toBuild)
  892. // {
  893. // EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  894. // if (canBuild == EBuildingState::HAVE_CAPITAL
  895. // || canBuild == EBuildingState::FORBIDDEN
  896. // || canBuild == EBuildingState::NO_WATER)
  897. // return false; //we won't be able to build this
  898. // }
  899. //
  900. // if (maxDays && toBuild.size() > maxDays)
  901. // return false;
  902. //
  903. // TResources currentRes = cb->getResourceAmount();
  904. // TResources income = estimateIncome();
  905. // //TODO: calculate if we have enough resources to build it in maxDays
  906. //
  907. // for(const auto & buildID : toBuild)
  908. // {
  909. // const CBuilding *b = t->town->buildings.at(buildID);
  910. //
  911. // EBuildingState::EBuildingState canBuild = cb->canBuildStructure(t, buildID);
  912. // if(canBuild == EBuildingState::ALLOWED)
  913. // {
  914. // if(!containsSavedRes(b->resources))
  915. // {
  916. // logAi->debugStream() << boost::format("Player %d will build %s in town of %s at %s") % playerID % b->Name() % t->name % t->pos;
  917. // return true;
  918. // }
  919. // continue;
  920. // }
  921. // else if(canBuild == EBuildingState::NO_RESOURCES)
  922. // {
  923. // TResources cost = t->town->buildings.at(buildID)->resources;
  924. // for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  925. // {
  926. // int diff = currentRes[i] - cost[i] + income[i];
  927. // if(diff < 0)
  928. // saving[i] = 1;
  929. // }
  930. // continue;
  931. // }
  932. // else if (canBuild == EBuildingState::PREREQUIRES)
  933. // {
  934. // // can happen when dependencies have their own missing dependencies
  935. // if (canBuildStructure(t, buildID, maxDays - 1))
  936. // return true;
  937. // }
  938. // else if (canBuild == EBuildingState::MISSING_BASE)
  939. // {
  940. // if (canBuildStructure(t, b->upgrade, maxDays - 1))
  941. // return true;
  942. // }
  943. // }
  944. // return false;
  945. //}
  946. bool VCAI::tryBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  947. {
  948. for(const auto & building : buildList)
  949. {
  950. if(t->hasBuilt(building))
  951. continue;
  952. if (tryBuildStructure(t, building, maxDays))
  953. return true;
  954. }
  955. return false; //Can't build anything
  956. }
  957. BuildingID VCAI::canBuildAnyStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  958. {
  959. for(const auto & building : buildList)
  960. {
  961. if(t->hasBuilt(building))
  962. continue;
  963. if (cb->canBuildStructure(t, building))
  964. return building;
  965. }
  966. return BuildingID::NONE; //Can't build anything
  967. }
  968. bool VCAI::tryBuildNextStructure(const CGTownInstance * t, std::vector<BuildingID> buildList, unsigned int maxDays)
  969. {
  970. for(const auto & building : buildList)
  971. {
  972. if(t->hasBuilt(building))
  973. continue;
  974. return tryBuildStructure(t, building, maxDays);
  975. }
  976. return false;//Nothing to build
  977. }
  978. void VCAI::buildStructure(const CGTownInstance * t)
  979. {
  980. //TODO make *real* town development system
  981. //TODO: faction-specific development: use special buildings, build dwellings in better order, etc
  982. //TODO: build resource silo, defences when needed
  983. //Possible - allow "locking" on specific building (build prerequisites and then building itself)
  984. TResources currentRes = cb->getResourceAmount();
  985. TResources currentIncome = t->dailyIncome();
  986. int townIncome = currentIncome[Res::GOLD];
  987. if (tryBuildAnyStructure(t, std::vector<BuildingID>(essential, essential + ARRAY_COUNT(essential))))
  988. return;
  989. //we're running out of gold - try to build something gold-producing. Multiplier can be tweaked, 6 is minimum due to buildings costs
  990. if (currentRes[Res::GOLD] < townIncome * 6)
  991. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  992. return;
  993. if (cb->getDate(Date::DAY_OF_WEEK) > 6)// last 2 days of week - try to focus on growth
  994. {
  995. if (tryBuildNextStructure(t, std::vector<BuildingID>(unitGrowth, unitGrowth + ARRAY_COUNT(unitGrowth)), 2))
  996. return;
  997. }
  998. // first in-game week or second half of any week: try build dwellings
  999. if (cb->getDate(Date::DAY) < 7 || cb->getDate(Date::DAY_OF_WEEK) > 3)
  1000. if (tryBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK)))
  1001. return;
  1002. //try to upgrade dwelling
  1003. for(int i = 0; i < ARRAY_COUNT(unitsUpgrade); i++)
  1004. {
  1005. if (t->hasBuilt(unitsSource[i]) && !t->hasBuilt(unitsUpgrade[i]))
  1006. {
  1007. if (tryBuildStructure(t, unitsUpgrade[i]))
  1008. return;
  1009. }
  1010. }
  1011. //remaining tasks
  1012. if (tryBuildNextStructure(t, std::vector<BuildingID>(goldSource, goldSource + ARRAY_COUNT(goldSource))))
  1013. return;
  1014. if (tryBuildNextStructure(t, std::vector<BuildingID>(spells, spells + ARRAY_COUNT(spells))))
  1015. return;
  1016. if (tryBuildAnyStructure(t, std::vector<BuildingID>(extra, extra + ARRAY_COUNT(extra))))
  1017. return;
  1018. }
  1019. bool VCAI::isGoodForVisit(const CGObjectInstance *obj, HeroPtr h)
  1020. {
  1021. const int3 pos = obj->visitablePos();
  1022. if (isAccessibleForHero(obj->visitablePos(), h) &&
  1023. !obj->wasVisited(playerID) &&
  1024. (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES || isWeeklyRevisitable(obj)) && //flag or get weekly resources / creatures
  1025. isSafeToVisit(h, pos) &&
  1026. shouldVisit(h, obj) &&
  1027. !vstd::contains(alreadyVisited, obj) &&
  1028. !vstd::contains(reservedObjs, obj))
  1029. {
  1030. const CGObjectInstance *topObj = cb->getVisitableObjs(obj->visitablePos()).back(); //it may be hero visiting this obj
  1031. //we don't try visiting object on which allied or owned hero stands
  1032. // -> it will just trigger exchange windows and AI will be confused that obj behind doesn't get visited
  1033. if (topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  1034. return false;
  1035. else
  1036. return true; //all of the following is met
  1037. }
  1038. return false;
  1039. }
  1040. std::vector<const CGObjectInstance *> VCAI::getPossibleDestinations(HeroPtr h)
  1041. {
  1042. validateVisitableObjs();
  1043. std::vector<const CGObjectInstance *> possibleDestinations;
  1044. for(const CGObjectInstance *obj : visitableObjs)
  1045. {
  1046. if (isGoodForVisit(obj, h))
  1047. {
  1048. possibleDestinations.push_back(obj);
  1049. }
  1050. }
  1051. boost::sort(possibleDestinations, isCloser);
  1052. return possibleDestinations;
  1053. }
  1054. bool VCAI::canReachTile (const CGHeroInstance * h, int3 t)
  1055. {
  1056. if (t.valid())
  1057. {
  1058. auto obj = cb->getTopObj(t);
  1059. if (obj && vstd::contains(ai->reservedObjs, obj) && !vstd::contains(reservedHeroesMap[h], obj))
  1060. return false; //do not capture object reserved by another hero
  1061. else
  1062. return true;
  1063. }
  1064. else
  1065. return false;
  1066. }
  1067. bool VCAI::canRecruitAnyHero (const CGTownInstance * t) const
  1068. {
  1069. //TODO: make gathering gold, building tavern or conquering town (?) possible subgoals
  1070. if (!t)
  1071. t = findTownWithTavern();
  1072. if (t)
  1073. return cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST &&
  1074. cb->getHeroesInfo().size() < ALLOWED_ROAMING_HEROES &&
  1075. cb->getAvailableHeroes(t).size();
  1076. else
  1077. return false;
  1078. }
  1079. void VCAI::wander(HeroPtr h)
  1080. {
  1081. cb->setSelection(*h);
  1082. //unclaim objects that are now dangerous for us
  1083. auto reservedObjsSetCopy = reservedHeroesMap[h];
  1084. for (auto obj : reservedObjsSetCopy)
  1085. {
  1086. if (!isSafeToVisit(h, obj->visitablePos()))
  1087. unreserveObject(h, obj);
  1088. }
  1089. TimeCheck tc("looking for wander destination");
  1090. while (h->movement)
  1091. {
  1092. validateVisitableObjs();
  1093. std::vector <ObjectIdRef> dests, tmp;
  1094. range::copy(reservedHeroesMap[h], std::back_inserter(tmp)); //visit our reserved objects first
  1095. for (auto obj : tmp)
  1096. {
  1097. if (isAccessibleForHero (obj->visitablePos(), h)) //even nearby objects could be blocked by other heroes :(
  1098. dests.push_back(obj); //can't use lambda for member function :(
  1099. }
  1100. if (!dests.size())
  1101. range::copy(getPossibleDestinations(h), std::back_inserter(dests));
  1102. if(!dests.size())
  1103. {
  1104. if (cb->getVisitableObjs(h->visitablePos()).size() > 1)
  1105. moveHeroToTile(h->visitablePos(), h); //just in case we're standing on blocked subterranean gate
  1106. auto compareReinforcements = [h](const CGTownInstance *lhs, const CGTownInstance *rhs) -> bool
  1107. {
  1108. return howManyReinforcementsCanGet(h, lhs) < howManyReinforcementsCanGet(h, rhs);
  1109. };
  1110. std::vector<const CGTownInstance *> townsReachable;
  1111. std::vector<const CGTownInstance *> townsNotReachable;
  1112. for(const CGTownInstance *t : cb->getTownsInfo())
  1113. {
  1114. if(!t->visitingHero && howManyReinforcementsCanGet(h,t) && !vstd::contains(townVisitsThisWeek[h], t))
  1115. {
  1116. if (isAccessibleForHero (t->visitablePos(), h))
  1117. townsReachable.push_back(t);
  1118. else
  1119. townsNotReachable.push_back(t);
  1120. }
  1121. }
  1122. if(townsReachable.size())
  1123. {
  1124. boost::sort(townsReachable, compareReinforcements);
  1125. dests.push_back(townsReachable.back());
  1126. }
  1127. else if(townsNotReachable.size())
  1128. {
  1129. boost::sort(townsNotReachable, compareReinforcements);
  1130. //TODO pick the truly best
  1131. const CGTownInstance *t = townsNotReachable.back();
  1132. 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();
  1133. int3 pos1 = h->pos;
  1134. striveToGoal(sptr(Goals::ClearWayTo(t->visitablePos()).sethero(h)));
  1135. //if out hero is stuck, we may need to request another hero to clear the way we see
  1136. if (pos1 == h->pos && h == primaryHero()) //hero can't move
  1137. {
  1138. if (canRecruitAnyHero(t))
  1139. recruitHero(t);
  1140. }
  1141. break;
  1142. }
  1143. else if(cb->getResourceAmount(Res::GOLD) >= HERO_GOLD_COST)
  1144. {
  1145. std::vector<const CGTownInstance *> towns = cb->getTownsInfo();
  1146. erase_if(towns, [](const CGTownInstance *t) -> bool
  1147. {
  1148. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1149. if(!t->getArmyStrength() || howManyReinforcementsCanGet(h, t))
  1150. return true;
  1151. return false;
  1152. });
  1153. boost::sort(towns, compareArmyStrength);
  1154. if(towns.size())
  1155. recruitHero(towns.back());
  1156. break;
  1157. }
  1158. else
  1159. {
  1160. logAi->debugStream() << "Nowhere more to go...";
  1161. break;
  1162. }
  1163. }
  1164. //end of objs empty
  1165. while (dests.size()) //performance improvement
  1166. {
  1167. //wander should not cause heroes to be reserved - they are always considered free
  1168. const ObjectIdRef&dest = dests.front();
  1169. logAi->debugStream() << boost::format("Of all %d destinations, object oid=%d seems nice") % dests.size() % dest.id.getNum();
  1170. if(!goVisitObj(dest, h))
  1171. {
  1172. if(!dest)
  1173. {
  1174. logAi->debugStream() << boost::format("Visit attempt made the object (id=%d) gone...") % dest.id.getNum();
  1175. }
  1176. else
  1177. {
  1178. logAi->debugStream() << boost::format("Hero %s apparently used all MPs (%d left)") % h->name % h->movement;
  1179. return;
  1180. }
  1181. }
  1182. //TODO: refactor removing deleted objects from the list
  1183. std::vector<const CGObjectInstance *> hlp;
  1184. retreiveVisitableObjs(hlp, true);
  1185. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1186. {
  1187. if(!vstd::contains(hlp, obj))
  1188. {
  1189. return true;
  1190. }
  1191. return false;
  1192. };
  1193. erase_if(dests, shouldBeErased);
  1194. erase_if_present(dests, dest); //why that fails sometimes when removing monsters?
  1195. boost::sort(dests, isCloser); //find next closest one
  1196. }
  1197. if (h->visitedTown)
  1198. {
  1199. townVisitsThisWeek[h].insert(h->visitedTown);
  1200. buildArmyIn(h->visitedTown);
  1201. }
  1202. }
  1203. }
  1204. void VCAI::setGoal(HeroPtr h, Goals::TSubgoal goal)
  1205. { //TODO: check for presence?
  1206. if (goal->invalid())
  1207. erase_if_present(lockedHeroes, h);
  1208. else
  1209. {
  1210. lockedHeroes[h] = goal;
  1211. goal->setisElementar(false); //always evaluate goals before realizing
  1212. }
  1213. }
  1214. void VCAI::completeGoal (Goals::TSubgoal goal)
  1215. {
  1216. logAi->traceStream() << boost::format("Completing goal: %s") % goal->name();
  1217. if (const CGHeroInstance * h = goal->hero.get(true))
  1218. {
  1219. auto it = lockedHeroes.find(h);
  1220. if (it != lockedHeroes.end())
  1221. if (it->second == goal)
  1222. {
  1223. logAi->debugStream() << boost::format("%s") % goal->completeMessage();
  1224. lockedHeroes.erase(it); //goal fulfilled, free hero
  1225. }
  1226. }
  1227. else //complete goal for all heroes maybe?
  1228. {
  1229. vstd::erase_if(lockedHeroes, [goal](std::pair<HeroPtr, Goals::TSubgoal> p)
  1230. {
  1231. if (*(p.second) == *goal || p.second->fulfillsMe(goal)) //we could have fulfilled goals of other heroes by chance
  1232. {
  1233. logAi->debugStream() << boost::format("%s") % p.second->completeMessage();
  1234. return true;
  1235. }
  1236. return false;
  1237. });
  1238. }
  1239. }
  1240. void VCAI::battleStart(const CCreatureSet *army1, const CCreatureSet *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool side)
  1241. {
  1242. NET_EVENT_HANDLER;
  1243. assert(playerID > PlayerColor::PLAYER_LIMIT || status.getBattle() == UPCOMING_BATTLE);
  1244. status.setBattle(ONGOING_BATTLE);
  1245. 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
  1246. battlename = boost::str(boost::format("Starting battle of %s attacking %s at %s") % (hero1 ? hero1->name : "a army") % (presumedEnemy ? presumedEnemy->hoverName : "unknown enemy") % tile);
  1247. CAdventureAI::battleStart(army1, army2, tile, hero1, hero2, side);
  1248. }
  1249. void VCAI::battleEnd(const BattleResult *br)
  1250. {
  1251. NET_EVENT_HANDLER;
  1252. assert(status.getBattle() == ONGOING_BATTLE);
  1253. status.setBattle(ENDING_BATTLE);
  1254. bool won = br->winner == myCb->battleGetMySide();
  1255. logAi->debugStream() << boost::format("Player %d: I %s the %s!") % playerID % (won ? "won" : "lost") % battlename;
  1256. battlename.clear();
  1257. CAdventureAI::battleEnd(br);
  1258. }
  1259. void VCAI::waitTillFree()
  1260. {
  1261. auto unlock = vstd::makeUnlockSharedGuard(cb->getGsMutex());
  1262. status.waitTillFree();
  1263. }
  1264. void VCAI::markObjectVisited (const CGObjectInstance *obj)
  1265. {
  1266. if(dynamic_cast<const CGVisitableOPH *>(obj) || //we may want to wisit it with another hero
  1267. dynamic_cast<const CGBonusingObject *>(obj) || //or another time
  1268. (obj->ID == Obj::MONSTER))
  1269. return;
  1270. alreadyVisited.insert(obj);
  1271. }
  1272. void VCAI::reserveObject(HeroPtr h, const CGObjectInstance *obj)
  1273. {
  1274. reservedObjs.insert(obj);
  1275. reservedHeroesMap[h].insert(obj);
  1276. logAi->debugStream() << "reserved object id=" << obj->id << "; address=" << (intptr_t)obj << "; name=" << obj->getHoverText();
  1277. }
  1278. void VCAI::unreserveObject(HeroPtr h, const CGObjectInstance *obj)
  1279. {
  1280. erase_if_present(reservedObjs, obj); //unreserve objects
  1281. erase_if_present(reservedHeroesMap[h], obj);
  1282. }
  1283. void VCAI::markHeroUnableToExplore (HeroPtr h)
  1284. {
  1285. heroesUnableToExplore.insert(h);
  1286. }
  1287. void VCAI::markHeroAbleToExplore (HeroPtr h)
  1288. {
  1289. erase_if_present(heroesUnableToExplore, h);
  1290. }
  1291. bool VCAI::isAbleToExplore (HeroPtr h)
  1292. {
  1293. return !vstd::contains (heroesUnableToExplore, h);
  1294. }
  1295. void VCAI::clearHeroesUnableToExplore()
  1296. {
  1297. heroesUnableToExplore.clear();
  1298. }
  1299. void VCAI::validateVisitableObjs()
  1300. {
  1301. std::vector<const CGObjectInstance *> hlp;
  1302. retreiveVisitableObjs(hlp, true);
  1303. std::string errorMsg;
  1304. auto shouldBeErased = [&](const CGObjectInstance *obj) -> bool
  1305. {
  1306. if(!vstd::contains(hlp, obj))
  1307. {
  1308. logAi->errorStream() << helperObjInfo[obj].name << " at " << helperObjInfo[obj].pos << errorMsg;
  1309. return true;
  1310. }
  1311. return false;
  1312. };
  1313. //errorMsg is captured by ref so lambda will take the new text
  1314. errorMsg = " shouldn't be on the visitable objects list!";
  1315. erase_if(visitableObjs, shouldBeErased);
  1316. for(auto &p : reservedHeroesMap)
  1317. {
  1318. errorMsg = " shouldn't be on list for hero " + p.first->name + "!";
  1319. erase_if(p.second, shouldBeErased);
  1320. }
  1321. errorMsg = " shouldn't be on the reserved objs list!";
  1322. erase_if(reservedObjs, shouldBeErased);
  1323. //TODO overkill, hidden object should not be removed. However, we can't know if hidden object is erased from game.
  1324. errorMsg = " shouldn't be on the already visited objs list!";
  1325. erase_if(alreadyVisited, shouldBeErased);
  1326. }
  1327. void VCAI::retreiveVisitableObjs(std::vector<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1328. {
  1329. foreach_tile_pos([&](const int3 &pos)
  1330. {
  1331. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1332. {
  1333. if(includeOwned || obj->tempOwner != playerID)
  1334. out.push_back(obj);
  1335. }
  1336. });
  1337. }
  1338. void VCAI::retreiveVisitableObjs(std::set<const CGObjectInstance *> &out, bool includeOwned /*= false*/) const
  1339. {
  1340. foreach_tile_pos([&](const int3 &pos)
  1341. {
  1342. for(const CGObjectInstance *obj : myCb->getVisitableObjs(pos, false))
  1343. {
  1344. if(includeOwned || obj->tempOwner != playerID)
  1345. out.insert(obj);
  1346. }
  1347. });
  1348. }
  1349. std::vector<const CGObjectInstance *> VCAI::getFlaggedObjects() const
  1350. {
  1351. std::vector<const CGObjectInstance *> ret;
  1352. retreiveVisitableObjs(ret, true);
  1353. erase_if(ret, [](const CGObjectInstance *obj)
  1354. {
  1355. return obj->tempOwner != ai->playerID;
  1356. });
  1357. return ret;
  1358. }
  1359. void VCAI::addVisitableObj(const CGObjectInstance *obj)
  1360. {
  1361. visitableObjs.insert(obj);
  1362. helperObjInfo[obj] = ObjInfo(obj);
  1363. }
  1364. const CGObjectInstance * VCAI::lookForArt(int aid) const
  1365. {
  1366. for(const CGObjectInstance *obj : ai->visitableObjs)
  1367. {
  1368. if(obj->ID == 5 && obj->subID == aid)
  1369. return obj;
  1370. }
  1371. return nullptr;
  1372. //TODO what if more than one artifact is available? return them all or some slection criteria
  1373. }
  1374. bool VCAI::isAccessible(const int3 &pos)
  1375. {
  1376. //TODO precalculate for speed
  1377. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1378. {
  1379. if(isAccessibleForHero(pos, h))
  1380. return true;
  1381. }
  1382. return false;
  1383. }
  1384. HeroPtr VCAI::getHeroWithGrail() const
  1385. {
  1386. for(const CGHeroInstance *h : cb->getHeroesInfo())
  1387. if(h->hasArt(2)) //grail
  1388. return h;
  1389. return nullptr;
  1390. }
  1391. const CGObjectInstance * VCAI::getUnvisitedObj(const std::function<bool(const CGObjectInstance *)> &predicate)
  1392. {
  1393. //TODO smarter definition of unvisited
  1394. for(const CGObjectInstance *obj : visitableObjs)
  1395. if(predicate(obj) && !vstd::contains(alreadyVisited, obj))
  1396. return obj;
  1397. return nullptr;
  1398. }
  1399. bool VCAI::isAccessibleForHero(const int3 & pos, HeroPtr h, bool includeAllies /*= false*/) const
  1400. {
  1401. cb->setSelection(*h);
  1402. if (!includeAllies)
  1403. { //don't visit tile occupied by allied hero
  1404. for (auto obj : cb->getVisitableObjs(pos))
  1405. {
  1406. if (obj->ID == Obj::HERO &&
  1407. cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES &&
  1408. obj != h.get())
  1409. return false;
  1410. }
  1411. }
  1412. return cb->getPathInfo(pos)->reachable();
  1413. }
  1414. bool VCAI::moveHeroToTile(int3 dst, HeroPtr h)
  1415. {
  1416. cb->setSelection(h.h); //make sure we are using the RIGHT pathfinder
  1417. logAi->debugStream() << boost::format("Moving hero %s to tile %s") % h->name % dst;
  1418. int3 startHpos = h->visitablePos();
  1419. bool ret = false;
  1420. if(startHpos == dst)
  1421. {
  1422. //FIXME: this assertion fails also if AI moves onto defeated guarded object
  1423. assert(cb->getVisitableObjs(dst).size() > 1); //there's no point in revisiting tile where there is no visitable object
  1424. cb->moveHero(*h, CGHeroInstance::convertPosition(dst, true));
  1425. waitTillFree(); //movement may cause battle or blocking dialog
  1426. ret = true;
  1427. }
  1428. else
  1429. {
  1430. CGPath path;
  1431. cb->getPath2(dst, path);
  1432. if(path.nodes.empty())
  1433. {
  1434. logAi->errorStream() << "Hero " << h->name << " cannot reach " << dst;
  1435. cb->recalculatePaths();
  1436. throw goalFulfilledException (sptr(Goals::VisitTile(dst).sethero(h)));
  1437. }
  1438. int i=path.nodes.size()-1;
  1439. for(; i>0; i--)
  1440. {
  1441. //stop sending move requests if the next node can't be reached at the current turn (hero exhausted his move points)
  1442. if(path.nodes[i-1].turns)
  1443. {
  1444. //blockedHeroes.insert(h); //to avoid attempts of moving heroes with very little MPs
  1445. break;
  1446. }
  1447. int3 endpos = path.nodes[i-1].coord;
  1448. if(endpos == h->visitablePos())
  1449. continue;
  1450. cb->moveHero(*h, CGHeroInstance::convertPosition(endpos, true));
  1451. waitTillFree(); //movement may cause battle or blocking dialog
  1452. boost::this_thread::interruption_point();
  1453. if(!h) //we lost hero - remove all tasks assigned to him/her
  1454. {
  1455. lostHero(h);
  1456. //we need to throw, otherwise hero will be assigned to sth again
  1457. throw std::runtime_error("Hero was lost!");
  1458. }
  1459. }
  1460. ret = !i;
  1461. }
  1462. if (h)
  1463. {
  1464. if (auto visitedObject = frontOrNull(cb->getVisitableObjs(h->visitablePos()))) //we stand on something interesting
  1465. {
  1466. if (visitedObject != *h)
  1467. performObjectInteraction (visitedObject, h);
  1468. }
  1469. }
  1470. if(h) //we could have lost hero after last move
  1471. {
  1472. completeGoal (sptr(Goals::VisitTile(dst).sethero(h))); //we stepped on some tile, anyway
  1473. if (!ret) //reserve object we are heading towards
  1474. {
  1475. auto obj = frontOrNull(cb->getVisitableObjs(dst));
  1476. if (obj && obj != *h)
  1477. reserveObject(h, obj);
  1478. }
  1479. cb->recalculatePaths();
  1480. if (startHpos == h->visitablePos() && !ret) //we didn't move and didn't reach the target
  1481. {
  1482. erase_if_present (lockedHeroes, h); //hero seemingly is confused
  1483. throw cannotFulfillGoalException("Invalid path found!"); //FIXME: should never happen
  1484. }
  1485. logAi->debugStream() << boost::format("Hero %s moved from %s to %s. Returning %d.") % h->name % startHpos % h->visitablePos() % ret;
  1486. }
  1487. return ret;
  1488. }
  1489. void VCAI::tryRealize(Goals::Explore & g)
  1490. {
  1491. throw cannotFulfillGoalException("EXPLORE is not a elementar goal!");
  1492. }
  1493. void VCAI::tryRealize(Goals::RecruitHero & g)
  1494. {
  1495. if(const CGTownInstance *t = findTownWithTavern())
  1496. {
  1497. recruitHero(t, true);
  1498. //TODO try to free way to blocked town
  1499. //TODO: adventure map tavern or prison?
  1500. }
  1501. }
  1502. void VCAI::tryRealize(Goals::VisitTile & g)
  1503. {
  1504. if(!g.hero->movement)
  1505. throw cannotFulfillGoalException("Cannot visit tile: hero is out of MPs!");
  1506. if(g.tile == g.hero->visitablePos() && cb->getVisitableObjs(g.hero->visitablePos()).size() < 2)
  1507. {
  1508. logAi->warnStream() << boost::format("Why do I want to move hero %s to tile %s? Already standing on that tile! ")
  1509. % g.hero->name % g.tile;
  1510. throw goalFulfilledException (sptr(g));
  1511. }
  1512. if (ai->moveHeroToTile(g.tile, g.hero.get()))
  1513. {
  1514. throw goalFulfilledException (sptr(g));
  1515. }
  1516. }
  1517. void VCAI::tryRealize(Goals::VisitHero & g)
  1518. {
  1519. if(!g.hero->movement)
  1520. throw cannotFulfillGoalException("Cannot visit target hero: hero is out of MPs!");
  1521. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(g.objid));
  1522. if (obj)
  1523. {
  1524. if (ai->moveHeroToTile(obj->visitablePos(), g.hero.get()))
  1525. {
  1526. throw goalFulfilledException (sptr(g));
  1527. }
  1528. }
  1529. else
  1530. throw cannotFulfillGoalException("Cannot visit hero: object not found!");
  1531. }
  1532. void VCAI::tryRealize(Goals::BuildThis & g)
  1533. {
  1534. const CGTownInstance *t = g.town;
  1535. if(!t && g.hero)
  1536. t = g.hero->visitedTown;
  1537. if(!t)
  1538. {
  1539. for(const CGTownInstance *t : cb->getTownsInfo())
  1540. {
  1541. switch(cb->canBuildStructure(t, BuildingID(g.bid)))
  1542. {
  1543. case EBuildingState::ALLOWED:
  1544. cb->buildBuilding(t, BuildingID(g.bid));
  1545. return;
  1546. default:
  1547. break;
  1548. }
  1549. }
  1550. }
  1551. else if(cb->canBuildStructure(t, BuildingID(g.bid)) == EBuildingState::ALLOWED)
  1552. {
  1553. cb->buildBuilding(t, BuildingID(g.bid));
  1554. return;
  1555. }
  1556. throw cannotFulfillGoalException("Cannot build a given structure!");
  1557. }
  1558. void VCAI::tryRealize(Goals::DigAtTile & g)
  1559. {
  1560. assert(g.hero->visitablePos() == g.tile); //surely we want to crash here?
  1561. if (g.hero->diggingStatus() == CGHeroInstance::CAN_DIG)
  1562. {
  1563. cb->dig(g.hero.get());
  1564. completeGoal(sptr(g)); // finished digging
  1565. }
  1566. else
  1567. {
  1568. ai->lockedHeroes[g.hero] = sptr(g); //hero who tries to dig shouldn't do anything else
  1569. throw cannotFulfillGoalException("A hero can't dig!\n");
  1570. }
  1571. }
  1572. void VCAI::tryRealize(Goals::CollectRes & g)
  1573. {
  1574. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1575. throw cannotFulfillGoalException("Goal is already fulfilled!");
  1576. if(const CGObjectInstance *obj = cb->getObj(ObjectInstanceID(g.objid), false))
  1577. {
  1578. if(const IMarket *m = IMarket::castFrom(obj, false))
  1579. {
  1580. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1581. {
  1582. if(i == g.resID) continue;
  1583. int toGive, toGet;
  1584. m->getOffer(i, g.resID, toGive, toGet, EMarketMode::RESOURCE_RESOURCE);
  1585. toGive = toGive * (cb->getResourceAmount(i) / toGive);
  1586. //TODO trade only as much as needed
  1587. cb->trade(obj, EMarketMode::RESOURCE_RESOURCE, i, g.resID, toGive);
  1588. if(cb->getResourceAmount(static_cast<Res::ERes>(g.resID)) >= g.value)
  1589. return;
  1590. }
  1591. throw cannotFulfillGoalException("I cannot get needed resources by trade!");
  1592. }
  1593. else
  1594. {
  1595. throw cannotFulfillGoalException("I don't know how to use this object to raise resources!");
  1596. }
  1597. }
  1598. else
  1599. {
  1600. saving[g.resID] = 1;
  1601. throw cannotFulfillGoalException("No object that could be used to raise resources!");
  1602. }
  1603. }
  1604. void VCAI::tryRealize(Goals::Build & g)
  1605. {
  1606. for(const CGTownInstance *t : cb->getTownsInfo())
  1607. {
  1608. logAi->debugStream() << boost::format("Looking into %s") % t->name;
  1609. buildStructure(t);
  1610. buildArmyIn(t);
  1611. if(!ai->primaryHero() ||
  1612. (t->getArmyStrength() > ai->primaryHero()->getArmyStrength() * 2 && !isAccessibleForHero(t->visitablePos(), ai->primaryHero())))
  1613. {
  1614. recruitHero(t);
  1615. buildArmyIn(t);
  1616. }
  1617. }
  1618. throw cannotFulfillGoalException("BUILD has been realized as much as possible.");
  1619. }
  1620. void VCAI::tryRealize(Goals::Invalid & g)
  1621. {
  1622. throw cannotFulfillGoalException("I don't know how to fulfill this!");
  1623. }
  1624. void VCAI::tryRealize(Goals::AbstractGoal & g)
  1625. {
  1626. logAi->debugStream() << boost::format("Attempting realizing goal with code %s") % g.name();
  1627. throw cannotFulfillGoalException("Unknown type of goal !");
  1628. }
  1629. const CGTownInstance * VCAI::findTownWithTavern() const
  1630. {
  1631. for(const CGTownInstance *t : cb->getTownsInfo())
  1632. if(t->hasBuilt(BuildingID::TAVERN) && !t->visitingHero)
  1633. return t;
  1634. return nullptr;
  1635. }
  1636. Goals::TSubgoal VCAI::getGoal (HeroPtr h) const
  1637. {
  1638. auto it = lockedHeroes.find(h);
  1639. if (it != lockedHeroes.end())
  1640. return it->second;
  1641. else
  1642. return sptr(Goals::Invalid());
  1643. }
  1644. std::vector<HeroPtr> VCAI::getUnblockedHeroes() const
  1645. {
  1646. std::vector<HeroPtr> ret;
  1647. for (auto h : cb->getHeroesInfo())
  1648. {
  1649. //&& !vstd::contains(lockedHeroes, h)
  1650. //at this point we assume heroes exhausted their locked goals
  1651. if (canAct(h))
  1652. ret.push_back(h);
  1653. }
  1654. return ret;
  1655. }
  1656. bool VCAI::canAct (HeroPtr h) const
  1657. {
  1658. auto mission = lockedHeroes.find(h);
  1659. if (mission != lockedHeroes.end())
  1660. {
  1661. //FIXME: I'm afraid there can be other conditions when heroes can act but not move :?
  1662. if (mission->second->goalType == Goals::DIG_AT_TILE && !mission->second->isElementar)
  1663. return false;
  1664. }
  1665. return h->movement;
  1666. }
  1667. HeroPtr VCAI::primaryHero() const
  1668. {
  1669. auto hs = cb->getHeroesInfo();
  1670. boost::sort(hs, compareHeroStrength);
  1671. if(hs.empty())
  1672. return nullptr;
  1673. return hs.back();
  1674. }
  1675. void VCAI::endTurn()
  1676. {
  1677. logAi->infoStream() << "Player " << static_cast<int>(playerID.getNum()) << " ends turn";
  1678. if(!status.haveTurn())
  1679. {
  1680. logAi->errorStream() << "Not having turn at the end of turn???";
  1681. }
  1682. logAi->debugStream() << "Resources at the end of turn: " << cb->getResourceAmount();
  1683. do
  1684. {
  1685. cb->endTurn();
  1686. } 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
  1687. logGlobal->infoStream() << "Player " << static_cast<int>(playerID.getNum()) << " ended turn";
  1688. }
  1689. void VCAI::striveToGoal(Goals::TSubgoal ultimateGoal)
  1690. {
  1691. if (ultimateGoal->invalid())
  1692. return;
  1693. //we are looking for abstract goals
  1694. auto abstractGoal = striveToGoalInternal (ultimateGoal, false);
  1695. if (abstractGoal->invalid())
  1696. return;
  1697. //we received abstract goal, need to find concrete goals
  1698. striveToGoalInternal (abstractGoal, true);
  1699. //TODO: save abstract goals not related to hero
  1700. }
  1701. Goals::TSubgoal VCAI::striveToGoalInternal(Goals::TSubgoal ultimateGoal, bool onlyAbstract)
  1702. {
  1703. const int searchDepth = 30;
  1704. const int searchDepth2 = searchDepth-2;
  1705. Goals::TSubgoal abstractGoal = sptr(Goals::Invalid());
  1706. while(1)
  1707. {
  1708. Goals::TSubgoal goal = ultimateGoal;
  1709. logAi->debugStream() << boost::format("Striving to goal of type %s") % ultimateGoal->name();
  1710. int maxGoals = searchDepth; //preventing deadlock for mutually dependent goals
  1711. while(!goal->isElementar && maxGoals && (onlyAbstract || !goal->isAbstract))
  1712. {
  1713. logAi->debugStream() << boost::format("Considering goal %s") % goal->name();
  1714. try
  1715. {
  1716. boost::this_thread::interruption_point();
  1717. goal = goal->whatToDoToAchieve();
  1718. --maxGoals;
  1719. if (*goal == *ultimateGoal) //compare objects by value
  1720. throw cannotFulfillGoalException("Goal dependency loop detected!");
  1721. }
  1722. catch(goalFulfilledException &e)
  1723. {
  1724. //it is impossible to continue some goals (like exploration, for example)
  1725. completeGoal (goal);
  1726. logAi->debugStream() << boost::format("Goal %s decomposition failed: goal was completed as much as possible") % goal->name();
  1727. return sptr(Goals::Invalid());
  1728. }
  1729. catch(std::exception &e)
  1730. {
  1731. logAi->debugStream() << boost::format("Goal %s decomposition failed: %s") % goal->name() % e.what();
  1732. return sptr(Goals::Invalid());
  1733. }
  1734. }
  1735. try
  1736. {
  1737. boost::this_thread::interruption_point();
  1738. if (!maxGoals)
  1739. {
  1740. std::runtime_error e("Too many subgoals, don't know what to do");
  1741. throw (e);
  1742. }
  1743. if (goal->hero) //lock this hero to fulfill ultimate goal
  1744. {
  1745. if (maxGoals)
  1746. {
  1747. setGoal(goal->hero, goal);
  1748. }
  1749. else
  1750. {
  1751. erase_if_present (lockedHeroes, goal->hero); // we seemingly don't know what to do with hero
  1752. }
  1753. }
  1754. if (goal->isAbstract)
  1755. {
  1756. abstractGoal = goal; //allow only one abstract goal per call
  1757. logAi->debugStream() << boost::format("Choosing abstract goal %s") % goal->name();
  1758. break;
  1759. }
  1760. else
  1761. {
  1762. logAi->debugStream() << boost::format("Trying to realize %s (value %2.3f)") % goal->name() % goal->priority;
  1763. goal->accept(this);
  1764. }
  1765. boost::this_thread::interruption_point();
  1766. }
  1767. catch(boost::thread_interrupted &e)
  1768. {
  1769. logAi->debugStream() << boost::format("Player %d: Making turn thread received an interruption!") % playerID;
  1770. throw; //rethrow, we want to truly end this thread
  1771. }
  1772. catch(goalFulfilledException &e)
  1773. {
  1774. //the goal was completed successfully
  1775. completeGoal (goal);
  1776. //completed goal was main goal //TODO: find better condition
  1777. if (ultimateGoal->fulfillsMe(goal) || maxGoals > searchDepth2)
  1778. return sptr(Goals::Invalid());
  1779. }
  1780. catch(std::exception &e)
  1781. {
  1782. logAi->debugStream() << boost::format("Failed to realize subgoal of type %s (greater goal type was %s), I will stop.") % goal->name() % ultimateGoal->name();
  1783. logAi->debugStream() << boost::format("The error message was: %s") % e.what();
  1784. break;
  1785. }
  1786. }
  1787. return abstractGoal;
  1788. }
  1789. void VCAI::striveToQuest (const QuestInfo &q)
  1790. {
  1791. if (q.quest->missionType && q.quest->progress != CQuest::COMPLETE)
  1792. {
  1793. MetaString ms;
  1794. q.quest->getRolloverText(ms, false);
  1795. logAi->debugStream() << boost::format("Trying to realize quest: %s") % ms.toString();
  1796. auto heroes = cb->getHeroesInfo();
  1797. switch (q.quest->missionType)
  1798. {
  1799. case CQuest::MISSION_ART:
  1800. {
  1801. for (auto hero : heroes) //TODO: remove duplicated code?
  1802. {
  1803. if (q.quest->checkQuest(hero))
  1804. {
  1805. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1806. return;
  1807. }
  1808. }
  1809. for (auto art : q.quest->m5arts)
  1810. {
  1811. striveToGoal (sptr(Goals::GetArtOfType(art))); //TODO: transport?
  1812. }
  1813. break;
  1814. }
  1815. case CQuest::MISSION_HERO:
  1816. {
  1817. //striveToGoal (CGoal(RECRUIT_HERO));
  1818. for (auto hero : heroes)
  1819. {
  1820. if (q.quest->checkQuest(hero))
  1821. {
  1822. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1823. return;
  1824. }
  1825. }
  1826. striveToGoal (sptr(Goals::FindObj(Obj::PRISON))); //rule of a thumb - quest heroes usually are locked in prisons
  1827. //BNLOG ("Don't know how to recruit hero with id %d\n", q.quest->m13489val);
  1828. break;
  1829. }
  1830. case CQuest::MISSION_ARMY:
  1831. {
  1832. for (auto hero : heroes)
  1833. {
  1834. if (q.quest->checkQuest(hero)) //very bad info - stacks can be split between multiple heroes :(
  1835. {
  1836. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1837. return;
  1838. }
  1839. }
  1840. for (auto creature : q.quest->m6creatures)
  1841. {
  1842. striveToGoal (sptr(Goals::GatherTroops(creature.type->idNumber, creature.count)));
  1843. }
  1844. //TODO: exchange armies... oh my
  1845. //BNLOG ("Don't know how to recruit %d of %s\n", (int)(creature.count) % creature.type->namePl);
  1846. break;
  1847. }
  1848. case CQuest::MISSION_RESOURCES:
  1849. {
  1850. if (heroes.size())
  1851. {
  1852. if (q.quest->checkQuest(heroes.front())) //it doesn't matter which hero it is
  1853. {
  1854. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum())));
  1855. }
  1856. else
  1857. {
  1858. for (int i = 0; i < q.quest->m7resources.size(); ++i)
  1859. {
  1860. if (q.quest->m7resources[i])
  1861. striveToGoal (sptr(Goals::CollectRes(i, q.quest->m7resources[i])));
  1862. }
  1863. }
  1864. }
  1865. else
  1866. striveToGoal (sptr(Goals::RecruitHero())); //FIXME: checkQuest requires any hero belonging to player :(
  1867. break;
  1868. }
  1869. case CQuest::MISSION_KILL_HERO:
  1870. case CQuest::MISSION_KILL_CREATURE:
  1871. {
  1872. auto obj = cb->getObjByQuestIdentifier(q.quest->m13489val);
  1873. if (obj)
  1874. striveToGoal (sptr(Goals::GetObj(obj->id.getNum())));
  1875. else
  1876. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()))); //visit seer hut
  1877. break;
  1878. }
  1879. case CQuest::MISSION_PRIMARY_STAT:
  1880. {
  1881. auto heroes = cb->getHeroesInfo();
  1882. for (auto hero : heroes)
  1883. {
  1884. if (q.quest->checkQuest(hero))
  1885. {
  1886. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero)));
  1887. return;
  1888. }
  1889. }
  1890. for (int i = 0; i < q.quest->m2stats.size(); ++i)
  1891. {
  1892. logAi->debugStream() << boost::format("Don't know how to increase primary stat %d") % i;
  1893. }
  1894. break;
  1895. }
  1896. case CQuest::MISSION_LEVEL:
  1897. {
  1898. auto heroes = cb->getHeroesInfo();
  1899. for (auto hero : heroes)
  1900. {
  1901. if (q.quest->checkQuest(hero))
  1902. {
  1903. striveToGoal (sptr(Goals::GetObj(q.obj->id.getNum()).sethero(hero))); //TODO: causes infinite loop :/
  1904. return;
  1905. }
  1906. }
  1907. logAi->debugStream() << boost::format("Don't know how to reach hero level %d") % q.quest->m13489val;
  1908. break;
  1909. }
  1910. case CQuest::MISSION_PLAYER:
  1911. {
  1912. if (playerID.getNum() != q.quest->m13489val)
  1913. logAi->debugStream() << boost::format("Can't be player of color %d") % q.quest->m13489val;
  1914. break;
  1915. }
  1916. case CQuest::MISSION_KEYMASTER:
  1917. {
  1918. striveToGoal (sptr(Goals::FindObj(Obj::KEYMASTER, q.obj->subID)));
  1919. break;
  1920. }
  1921. }
  1922. }
  1923. }
  1924. void VCAI::performTypicalActions()
  1925. {
  1926. for(auto h : getUnblockedHeroes())
  1927. {
  1928. logAi->debugStream() << boost::format("Looking into %s, MP=%d") % h->name.c_str() % h->movement;
  1929. makePossibleUpgrades(*h);
  1930. try
  1931. {
  1932. wander(h);
  1933. }
  1934. catch(std::exception &e)
  1935. {
  1936. logAi->debugStream() << boost::format("Cannot use this hero anymore, received exception: %s") % e.what();
  1937. continue;
  1938. }
  1939. }
  1940. }
  1941. void VCAI::buildArmyIn(const CGTownInstance * t)
  1942. {
  1943. makePossibleUpgrades(t->visitingHero);
  1944. makePossibleUpgrades(t);
  1945. recruitCreatures(t);
  1946. moveCreaturesToHero(t);
  1947. }
  1948. int3 VCAI::explorationBestNeighbour(int3 hpos, int radius, HeroPtr h)
  1949. {
  1950. std::map<int3, int> dstToRevealedTiles;
  1951. for(crint3 dir : dirs)
  1952. if(cb->isInTheMap(hpos+dir))
  1953. if (isSafeToVisit(h, hpos + dir) && isAccessibleForHero (hpos + dir, h))
  1954. dstToRevealedTiles[hpos + dir] = howManyTilesWillBeDiscovered(radius, hpos, dir);
  1955. if (dstToRevealedTiles.empty()) //yes, it DID happen!
  1956. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1957. auto best = dstToRevealedTiles.begin();
  1958. for (auto i = dstToRevealedTiles.begin(); i != dstToRevealedTiles.end(); i++)
  1959. {
  1960. const CGPathNode *pn = cb->getPathInfo(i->first);
  1961. //const TerrainTile *t = cb->getTile(i->first);
  1962. if(best->second < i->second && pn->reachable() && pn->accessible == CGPathNode::ACCESSIBLE)
  1963. best = i;
  1964. }
  1965. if(best->second)
  1966. return best->first;
  1967. throw cannotFulfillGoalException("No neighbour will bring new discoveries!");
  1968. }
  1969. int3 VCAI::explorationNewPoint(HeroPtr h)
  1970. {
  1971. //logAi->debugStream() << "Looking for an another place for exploration...";
  1972. cb->setSelection(h.h);
  1973. int radius = h->getSightRadious();
  1974. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  1975. tiles.resize(radius);
  1976. CCallback * cbp = cb.get();
  1977. foreach_tile_pos([&](const int3 &pos)
  1978. {
  1979. if(!cbp->isVisible(pos))
  1980. tiles[0].push_back(pos);
  1981. });
  1982. float bestValue = 0; //discovered tile to node distance ratio
  1983. int3 bestTile(-1,-1,-1);
  1984. for (int i = 1; i < radius; i++)
  1985. {
  1986. getVisibleNeighbours(tiles[i-1], tiles[i]);
  1987. removeDuplicates(tiles[i]);
  1988. for(const int3 &tile : tiles[i])
  1989. {
  1990. if (cbp->getTile(tile)->blocked) //does it shorten the time?
  1991. continue;
  1992. if (!cbp->getPathInfo(tile)->reachable()) //this will remove tiles that are guarded by monsters (or removable objects)
  1993. continue;
  1994. CGPath path;
  1995. cbp->getPath2(tile, path);
  1996. float ourValue = (float)howManyTilesWillBeDiscovered(tile, radius, cbp) / (path.nodes.size() + 1); //+1 prevents erratic jumps
  1997. if (ourValue > bestValue) //avoid costly checks of tiles that don't reveal much
  1998. {
  1999. if(isSafeToVisit(h, tile) && !isBlockedBorderGate(tile))
  2000. {
  2001. bestTile = tile;
  2002. bestValue = ourValue;
  2003. }
  2004. }
  2005. }
  2006. }
  2007. return bestTile;
  2008. }
  2009. int3 VCAI::explorationDesperate(HeroPtr h)
  2010. {
  2011. //logAi->debugStream() << "Looking for an another place for exploration...";
  2012. SectorMap sm(h);
  2013. int radius = h->getSightRadious();
  2014. std::vector<std::vector<int3> > tiles; //tiles[distance_to_fow]
  2015. tiles.resize(radius);
  2016. CCallback * cbp = cb.get();
  2017. foreach_tile_pos([&](const int3 &pos)
  2018. {
  2019. if(!cbp->isVisible(pos))
  2020. tiles[0].push_back(pos);
  2021. });
  2022. ui64 lowestDanger = -1;
  2023. int3 bestTile(-1,-1,-1);
  2024. for (int i = 1; i < radius; i++)
  2025. {
  2026. getVisibleNeighbours(tiles[i-1], tiles[i]);
  2027. removeDuplicates(tiles[i]);
  2028. for(const int3 &tile : tiles[i])
  2029. {
  2030. if (cbp->getTile(tile)->blocked) //does it shorten the time?
  2031. continue;
  2032. if (!howManyTilesWillBeDiscovered(tile, radius, cbp)) //avoid costly checks of tiles that don't reveal much
  2033. continue;
  2034. auto t = sm.firstTileToGet(h, tile);
  2035. if (t.valid())
  2036. {
  2037. ui64 ourDanger = evaluateDanger(t, h.h);
  2038. if (ourDanger < lowestDanger)
  2039. {
  2040. if(!isBlockedBorderGate(t))
  2041. {
  2042. if (!ourDanger) //at least one safe place found
  2043. return t;
  2044. bestTile = t;
  2045. lowestDanger = ourDanger;
  2046. }
  2047. }
  2048. }
  2049. }
  2050. }
  2051. return bestTile;
  2052. }
  2053. TResources VCAI::estimateIncome() const
  2054. {
  2055. TResources ret;
  2056. for(const CGTownInstance *t : cb->getTownsInfo())
  2057. {
  2058. ret += t->dailyIncome();
  2059. }
  2060. for(const CGObjectInstance *obj : getFlaggedObjects())
  2061. {
  2062. if(obj->ID == Obj::MINE)
  2063. {
  2064. switch(obj->subID)
  2065. {
  2066. case Res::WOOD:
  2067. case Res::ORE:
  2068. ret[obj->subID] += WOOD_ORE_MINE_PRODUCTION;
  2069. break;
  2070. case Res::GOLD:
  2071. case 7: //abandoned mine -> also gold
  2072. ret[Res::GOLD] += GOLD_MINE_PRODUCTION;
  2073. break;
  2074. default:
  2075. ret[obj->subID] += RESOURCE_MINE_PRODUCTION;
  2076. break;
  2077. }
  2078. }
  2079. }
  2080. return ret;
  2081. }
  2082. bool VCAI::containsSavedRes(const TResources &cost) const
  2083. {
  2084. for (int i = 0; i < GameConstants::RESOURCE_QUANTITY; i++)
  2085. {
  2086. if(saving[i] && cost[i])
  2087. return true;
  2088. }
  2089. return false;
  2090. }
  2091. void VCAI::checkHeroArmy (HeroPtr h)
  2092. {
  2093. auto it = lockedHeroes.find(h);
  2094. if (it != lockedHeroes.end())
  2095. {
  2096. if (it->second->goalType == Goals::GATHER_ARMY && it->second->value <= h->getArmyStrength())
  2097. completeGoal(sptr(Goals::GatherArmy(it->second->value).sethero(h)));
  2098. }
  2099. }
  2100. void VCAI::recruitHero(const CGTownInstance * t, bool throwing)
  2101. {
  2102. logAi->debugStream() << boost::format("Trying to recruit a hero in %s at %s") % t->name % t->visitablePos();
  2103. auto heroes = cb->getAvailableHeroes(t);
  2104. if(heroes.size())
  2105. {
  2106. auto hero = heroes[0];
  2107. if (heroes.size() >= 2) //makes sense to recruit two heroes with starting amries in first week
  2108. {
  2109. if (heroes[1]->getTotalStrength() > hero->getTotalStrength())
  2110. hero = heroes[1];
  2111. }
  2112. cb->recruitHero(t, hero);
  2113. }
  2114. else if(throwing)
  2115. throw cannotFulfillGoalException("No available heroes in tavern in " + t->nodeName());
  2116. }
  2117. void VCAI::finish()
  2118. {
  2119. if(makingTurn)
  2120. makingTurn->interrupt();
  2121. }
  2122. void VCAI::requestActionASAP(std::function<void()> whatToDo)
  2123. {
  2124. // static boost::mutex m;
  2125. // boost::unique_lock<boost::mutex> mylock(m);
  2126. boost::barrier b(2);
  2127. boost::thread newThread([&b,this,whatToDo]()
  2128. {
  2129. setThreadName("VCAI::requestActionASAP::helper");
  2130. SET_GLOBAL_STATE(this);
  2131. boost::shared_lock<boost::shared_mutex> gsLock(cb->getGsMutex());
  2132. b.wait();
  2133. whatToDo();
  2134. });
  2135. b.wait();
  2136. }
  2137. void VCAI::lostHero(HeroPtr h)
  2138. {
  2139. logAi->debugStream() << boost::format("I lost my hero %s. It's best to forget and move on.") % h.name;
  2140. erase_if_present(lockedHeroes, h);
  2141. for(auto obj : reservedHeroesMap[h])
  2142. {
  2143. erase_if_present(reservedObjs, obj); //unreserve all objects for that hero
  2144. }
  2145. erase_if_present(reservedHeroesMap, h);
  2146. }
  2147. void VCAI::answerQuery(QueryID queryID, int selection)
  2148. {
  2149. logAi->debugStream() << boost::format("I'll answer the query %d giving the choice %d") % queryID % selection;
  2150. if(queryID != QueryID(-1))
  2151. {
  2152. cb->selectionMade(selection, queryID);
  2153. }
  2154. else
  2155. {
  2156. logAi->debugStream() << boost::format("Since the query ID is %d, the answer won't be sent. This is not a real query!") % queryID;
  2157. //do nothing
  2158. }
  2159. }
  2160. void VCAI::requestSent(const CPackForServer *pack, int requestID)
  2161. {
  2162. //BNLOG("I have sent request of type %s", typeid(*pack).name());
  2163. if(auto reply = dynamic_cast<const QueryReply*>(pack))
  2164. {
  2165. status.attemptedAnsweringQuery(reply->qid, requestID);
  2166. }
  2167. }
  2168. std::string VCAI::getBattleAIName() const
  2169. {
  2170. if(settings["server"]["neutralAI"].getType() == JsonNode::DATA_STRING)
  2171. return settings["server"]["neutralAI"].String();
  2172. else
  2173. return "StupidAI";
  2174. }
  2175. void VCAI::validateObject(const CGObjectInstance *obj)
  2176. {
  2177. validateObject(obj->id);
  2178. }
  2179. void VCAI::validateObject(ObjectIdRef obj)
  2180. {
  2181. auto matchesId = [&] (const CGObjectInstance *hlpObj) -> bool { return hlpObj->id == obj.id; };
  2182. if(!obj)
  2183. {
  2184. erase_if(visitableObjs, matchesId);
  2185. for(auto &p : reservedHeroesMap)
  2186. erase_if(p.second, matchesId);
  2187. erase_if(reservedObjs, matchesId);
  2188. }
  2189. }
  2190. TResources VCAI::freeResources() const
  2191. {
  2192. TResources myRes = cb->getResourceAmount();
  2193. myRes[Res::GOLD] -= GOLD_RESERVE;
  2194. vstd::amax(myRes[Res::GOLD], 0);
  2195. return myRes;
  2196. }
  2197. AIStatus::AIStatus()
  2198. {
  2199. battle = NO_BATTLE;
  2200. havingTurn = false;
  2201. ongoingHeroMovement = false;
  2202. }
  2203. AIStatus::~AIStatus()
  2204. {
  2205. }
  2206. void AIStatus::setBattle(BattleState BS)
  2207. {
  2208. boost::unique_lock<boost::mutex> lock(mx);
  2209. LOG_TRACE_PARAMS(logAi, "battle state=%d", (int)BS);
  2210. battle = BS;
  2211. cv.notify_all();
  2212. }
  2213. BattleState AIStatus::getBattle()
  2214. {
  2215. boost::unique_lock<boost::mutex> lock(mx);
  2216. return battle;
  2217. }
  2218. void AIStatus::addQuery(QueryID ID, std::string description)
  2219. {
  2220. boost::unique_lock<boost::mutex> lock(mx);
  2221. if(ID == QueryID(-1))
  2222. {
  2223. logAi->debugStream() << boost::format("The \"query\" has an id %d, it'll be ignored as non-query. Description: %s") % ID % description;
  2224. return;
  2225. }
  2226. assert(!vstd::contains(remainingQueries, ID));
  2227. assert(ID.getNum() >= 0);
  2228. remainingQueries[ID] = description;
  2229. cv.notify_all();
  2230. logAi->debugStream() << boost::format("Adding query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2231. }
  2232. void AIStatus::removeQuery(QueryID ID)
  2233. {
  2234. boost::unique_lock<boost::mutex> lock(mx);
  2235. assert(vstd::contains(remainingQueries, ID));
  2236. std::string description = remainingQueries[ID];
  2237. remainingQueries.erase(ID);
  2238. cv.notify_all();
  2239. logAi->debugStream() << boost::format("Removing query %d - %s. Total queries count: %d") % ID % description % remainingQueries.size();
  2240. }
  2241. int AIStatus::getQueriesCount()
  2242. {
  2243. boost::unique_lock<boost::mutex> lock(mx);
  2244. return remainingQueries.size();
  2245. }
  2246. void AIStatus::startedTurn()
  2247. {
  2248. boost::unique_lock<boost::mutex> lock(mx);
  2249. havingTurn = true;
  2250. cv.notify_all();
  2251. }
  2252. void AIStatus::madeTurn()
  2253. {
  2254. boost::unique_lock<boost::mutex> lock(mx);
  2255. havingTurn = false;
  2256. cv.notify_all();
  2257. }
  2258. void AIStatus::waitTillFree()
  2259. {
  2260. boost::unique_lock<boost::mutex> lock(mx);
  2261. while(battle != NO_BATTLE || !remainingQueries.empty() || !objectsBeingVisited.empty() || ongoingHeroMovement)
  2262. cv.timed_wait(lock, boost::posix_time::milliseconds(100));
  2263. }
  2264. bool AIStatus::haveTurn()
  2265. {
  2266. boost::unique_lock<boost::mutex> lock(mx);
  2267. return havingTurn;
  2268. }
  2269. void AIStatus::attemptedAnsweringQuery(QueryID queryID, int answerRequestID)
  2270. {
  2271. boost::unique_lock<boost::mutex> lock(mx);
  2272. assert(vstd::contains(remainingQueries, queryID));
  2273. std::string description = remainingQueries[queryID];
  2274. logAi->debugStream() << boost::format("Attempted answering query %d - %s. Request id=%d. Waiting for results...") % queryID % description % answerRequestID;
  2275. requestToQueryID[answerRequestID] = queryID;
  2276. }
  2277. void AIStatus::receivedAnswerConfirmation(int answerRequestID, int result)
  2278. {
  2279. assert(vstd::contains(requestToQueryID, answerRequestID));
  2280. QueryID query = requestToQueryID[answerRequestID];
  2281. assert(vstd::contains(remainingQueries, query));
  2282. requestToQueryID.erase(answerRequestID);
  2283. if(result)
  2284. {
  2285. removeQuery(query);
  2286. }
  2287. else
  2288. {
  2289. logAi->errorStream() << "Something went really wrong, failed to answer query " << query << ": " << remainingQueries[query];
  2290. //TODO safely retry
  2291. }
  2292. }
  2293. void AIStatus::heroVisit(const CGObjectInstance *obj, bool started)
  2294. {
  2295. boost::unique_lock<boost::mutex> lock(mx);
  2296. if(started)
  2297. objectsBeingVisited.push_back(obj);
  2298. else
  2299. {
  2300. // There can be more than one object visited at the time (eg. hero visits Subterranean Gate
  2301. // causing visit to hero on the other side.
  2302. // However, we are guaranteed that start/end visit notification maintain stack order.
  2303. assert(!objectsBeingVisited.empty());
  2304. objectsBeingVisited.pop_back();
  2305. }
  2306. cv.notify_all();
  2307. }
  2308. void AIStatus::setMove(bool ongoing)
  2309. {
  2310. boost::unique_lock<boost::mutex> lock(mx);
  2311. ongoingHeroMovement = ongoing;
  2312. cv.notify_all();
  2313. }
  2314. SectorMap::SectorMap()
  2315. {
  2316. update();
  2317. }
  2318. SectorMap::SectorMap(HeroPtr h)
  2319. {
  2320. cb->setSelection(h.h);
  2321. update();
  2322. makeParentBFS(h->visitablePos());
  2323. }
  2324. bool markIfBlocked(ui8 &sec, crint3 pos, const TerrainTile *t)
  2325. {
  2326. if(t->blocked && !t->visitable)
  2327. {
  2328. sec = NOT_AVAILABLE;
  2329. return true;
  2330. }
  2331. return false;
  2332. }
  2333. bool markIfBlocked(ui8 &sec, crint3 pos)
  2334. {
  2335. return markIfBlocked(sec, pos, cb->getTile(pos));
  2336. }
  2337. void SectorMap::update()
  2338. {
  2339. clear();
  2340. int curSector = 3; //0 is invisible, 1 is not explored
  2341. CCallback * cbp = cb.get(); //optimization
  2342. foreach_tile_pos([&](crint3 pos)
  2343. {
  2344. if(retreiveTile(pos) == NOT_CHECKED)
  2345. {
  2346. if(!markIfBlocked(retreiveTile(pos), pos))
  2347. exploreNewSector(pos, curSector++, cbp);
  2348. }
  2349. });
  2350. valid = true;
  2351. }
  2352. void SectorMap::clear()
  2353. {
  2354. sector = cb->getVisibilityMap();
  2355. valid = false;
  2356. }
  2357. void SectorMap::exploreNewSector(crint3 pos, int num, CCallback * cbp)
  2358. {
  2359. Sector &s = infoOnSectors[num];
  2360. s.id = num;
  2361. s.water = cbp->getTile(pos)->isWater();
  2362. std::queue<int3> toVisit;
  2363. toVisit.push(pos);
  2364. while(!toVisit.empty())
  2365. {
  2366. int3 curPos = toVisit.front();
  2367. toVisit.pop();
  2368. ui8 &sec = retreiveTile(curPos);
  2369. if(sec == NOT_CHECKED)
  2370. {
  2371. const TerrainTile *t = cbp->getTile(curPos);
  2372. if(!markIfBlocked(sec, curPos, t))
  2373. {
  2374. if(t->isWater() == s.water) //sector is only-water or only-land
  2375. {
  2376. sec = num;
  2377. s.tiles.push_back(curPos);
  2378. foreach_neighbour(cbp, curPos, [&](CCallback * cbp, crint3 neighPos)
  2379. {
  2380. if(retreiveTile(neighPos) == NOT_CHECKED)
  2381. {
  2382. toVisit.push(neighPos);
  2383. //parent[neighPos] = curPos;
  2384. }
  2385. const TerrainTile *nt = cbp->getTile(neighPos, false);
  2386. if(nt && nt->isWater() != s.water && canBeEmbarkmentPoint(nt, s.water))
  2387. {
  2388. s.embarkmentPoints.push_back(neighPos);
  2389. }
  2390. });
  2391. if(t->visitable)
  2392. {
  2393. auto obj = t->visitableObjects.front();
  2394. if (vstd::contains(ai->knownSubterraneanGates, obj))
  2395. {
  2396. s.subterraneanGates.push_back (obj);
  2397. }
  2398. }
  2399. }
  2400. }
  2401. }
  2402. }
  2403. removeDuplicates(s.embarkmentPoints);
  2404. }
  2405. void SectorMap::write(crstring fname)
  2406. {
  2407. std::ofstream out(fname);
  2408. for(int k = 0; k < cb->getMapSize().z; k++)
  2409. {
  2410. for(int j = 0; j < cb->getMapSize().y; j++)
  2411. {
  2412. for(int i = 0; i < cb->getMapSize().x; i++)
  2413. {
  2414. out << (int)sector[i][j][k] << '\t';
  2415. }
  2416. out << std::endl;
  2417. }
  2418. out << std::endl;
  2419. }
  2420. }
  2421. bool isWeeklyRevisitable (const CGObjectInstance * obj)
  2422. { //TODO: allow polling of remaining creatures in dwelling
  2423. if (dynamic_cast<const CGVisitableOPW *>(obj) || //ensures future compatibility, unlike IDs
  2424. dynamic_cast<const CGDwelling *>(obj) ||
  2425. dynamic_cast<const CBank *>(obj)) //banks tend to respawn often in mods
  2426. return true;
  2427. switch (obj->ID)
  2428. {
  2429. case Obj::STABLES:
  2430. case Obj::MAGIC_WELL:
  2431. case Obj::HILL_FORT:
  2432. return true;
  2433. case Obj::BORDER_GATE:
  2434. case Obj::BORDERGUARD:
  2435. return (dynamic_cast <const CGKeys *>(obj))->wasMyColorVisited (ai->playerID); //FIXME: they could be revisited sooner than in a week
  2436. }
  2437. return false;
  2438. }
  2439. bool shouldVisit(HeroPtr h, const CGObjectInstance * obj)
  2440. {
  2441. switch (obj->ID)
  2442. {
  2443. case Obj::TOWN:
  2444. case Obj::HERO: //never visit our heroes at random
  2445. return obj->tempOwner != h->tempOwner; //do not visit our towns at random
  2446. break;
  2447. case Obj::BORDER_GATE:
  2448. {
  2449. for (auto q : ai->myCb->getMyQuests())
  2450. {
  2451. if (q.obj == obj)
  2452. {
  2453. return false; // do not visit guards or gates when wandering
  2454. }
  2455. }
  2456. return true; //we don't have this quest yet
  2457. }
  2458. break;
  2459. case Obj::BORDERGUARD: //open borderguard if possible
  2460. case Obj::SEER_HUT:
  2461. case Obj::QUEST_GUARD:
  2462. {
  2463. for (auto q : ai->myCb->getMyQuests())
  2464. {
  2465. if (q.obj == obj)
  2466. {
  2467. if (q.quest->checkQuest(h.h))
  2468. return true; //we completed the quest
  2469. else
  2470. return false; //we can't complete this quest
  2471. }
  2472. }
  2473. return true; //we don't have this quest yet
  2474. }
  2475. break;
  2476. case Obj::CREATURE_GENERATOR1:
  2477. {
  2478. if (obj->tempOwner != h->tempOwner)
  2479. return true; //flag just in case
  2480. bool canRecruitCreatures = false;
  2481. const CGDwelling * d = dynamic_cast<const CGDwelling *>(obj);
  2482. for(auto level : d->creatures)
  2483. {
  2484. for(auto c : level.second)
  2485. {
  2486. if (h->getSlotFor(CreatureID(c)) != SlotID())
  2487. canRecruitCreatures = true;
  2488. }
  2489. }
  2490. return canRecruitCreatures;
  2491. }
  2492. case Obj::HILL_FORT:
  2493. {
  2494. for (auto slot : h->Slots())
  2495. {
  2496. if (slot.second->type->upgrades.size())
  2497. return true; //TODO: check price?
  2498. }
  2499. return false;
  2500. }
  2501. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  2502. case Obj::MONOLITH_ONE_WAY_EXIT:
  2503. case Obj::MONOLITH_TWO_WAY:
  2504. case Obj::WHIRLPOOL:
  2505. //TODO: mechanism for handling monoliths
  2506. return false;
  2507. case Obj::SCHOOL_OF_MAGIC:
  2508. case Obj::SCHOOL_OF_WAR:
  2509. {
  2510. TResources myRes = ai->myCb->getResourceAmount();
  2511. if (myRes[Res::GOLD] - GOLD_RESERVE < 1000)
  2512. return false;
  2513. }
  2514. break;
  2515. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2516. if (h->level < 12)
  2517. return false;
  2518. break;
  2519. case Obj::TREE_OF_KNOWLEDGE:
  2520. {
  2521. TResources myRes = ai->myCb->getResourceAmount();
  2522. if (myRes[Res::GOLD] - GOLD_RESERVE < 2000 || myRes[Res::GEMS] < 10)
  2523. return false;
  2524. }
  2525. break;
  2526. case Obj::MAGIC_WELL:
  2527. return h->mana < h->manaLimit();
  2528. case Obj::PRISON:
  2529. return ai->myCb->getHeroesInfo().size() < VLC->modh->settings.MAX_HEROES_ON_MAP_PER_PLAYER;// GameConstants::MAX_HEROES_PER_PLAYER;
  2530. case Obj::BOAT:
  2531. return false;
  2532. //Boats are handled by pathfinder
  2533. }
  2534. if (obj->wasVisited(*h)) //it must pointer to hero instance, heroPtr calls function wasVisited(ui8 player);
  2535. return false;
  2536. return true;
  2537. }
  2538. int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
  2539. /*
  2540. this functions returns one target tile or invalid tile. We will use it to poll possible destinations
  2541. For ship construction etc, another function (goal?) is needed
  2542. */
  2543. {
  2544. int3 ret(-1,-1,-1);
  2545. int sourceSector = retreiveTile(h->visitablePos()),
  2546. destinationSector = retreiveTile(dst);
  2547. const Sector *src = &infoOnSectors[sourceSector],
  2548. *dest = &infoOnSectors[destinationSector];
  2549. if(sourceSector != destinationSector) //use ships, shipyards etc..
  2550. {
  2551. if (ai->isAccessibleForHero(dst, h)) //pathfinder can find a way using ships and gates if tile is not blocked by objects
  2552. return dst;
  2553. std::map<const Sector*, const Sector*> preds;
  2554. std::queue<const Sector *> sectorQueue;
  2555. sectorQueue.push(src);
  2556. while(!sectorQueue.empty())
  2557. {
  2558. const Sector *s = sectorQueue.front();
  2559. sectorQueue.pop();
  2560. for(int3 ep : s->embarkmentPoints)
  2561. {
  2562. Sector *neigh = &infoOnSectors[retreiveTile(ep)];
  2563. //preds[s].push_back(neigh);
  2564. if(!preds[neigh])
  2565. {
  2566. preds[neigh] = s;
  2567. sectorQueue.push(neigh);
  2568. }
  2569. }
  2570. for (auto gate : s->subterraneanGates)
  2571. {
  2572. auto gatePair = ai->knownSubterraneanGates.find(gate);
  2573. if (gatePair != ai->knownSubterraneanGates.end())
  2574. {
  2575. //check the other side of gate
  2576. Sector *neigh = &infoOnSectors[retreiveTile(gatePair->second->visitablePos())];
  2577. if(!preds[neigh]) //if we didn't come into this sector yet
  2578. {
  2579. preds[neigh] = s; //it becomes our new target sector
  2580. sectorQueue.push(neigh);
  2581. }
  2582. }
  2583. }
  2584. }
  2585. if(!preds[dest])
  2586. {
  2587. //write("test.txt");
  2588. return ret;
  2589. //throw cannotFulfillGoalException(boost::str(boost::format("Cannot find connection between sectors %d and %d") % src->id % dst->id));
  2590. }
  2591. std::vector<const Sector*> toTraverse;
  2592. toTraverse.push_back(dest);
  2593. while(toTraverse.back() != src)
  2594. {
  2595. toTraverse.push_back(preds[toTraverse.back()]);
  2596. }
  2597. if(preds[dest])
  2598. {
  2599. //TODO: would be nice to find sectors in loop
  2600. const Sector *sectorToReach = toTraverse.at(toTraverse.size() - 2);
  2601. if(!src->water && sectorToReach->water) //embark
  2602. {
  2603. //embark on ship -> look for an EP with a boat
  2604. auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
  2605. {
  2606. const TerrainTile *t = cb->getTile(pos);
  2607. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
  2608. && retreiveTile(pos) == sectorToReach->id;
  2609. });
  2610. if(firstEP != src->embarkmentPoints.end())
  2611. {
  2612. return *firstEP;
  2613. }
  2614. else
  2615. {
  2616. //we need to find a shipyard with an access to the desired sector's EP
  2617. //TODO what about Summon Boat spell?
  2618. std::vector<const IShipyard *> shipyards;
  2619. for(const CGTownInstance *t : cb->getTownsInfo())
  2620. {
  2621. if(t->hasBuilt(BuildingID::SHIPYARD))
  2622. shipyards.push_back(t);
  2623. }
  2624. for(const CGObjectInstance *obj : ai->visitableObjs)
  2625. {
  2626. if(obj->ID != Obj::TOWN) //towns were handled in the previous loop
  2627. if(const IShipyard *shipyard = IShipyard::castFrom(obj))
  2628. shipyards.push_back(shipyard);
  2629. }
  2630. shipyards.erase(boost::remove_if(shipyards, [=](const IShipyard *shipyard) -> bool
  2631. {
  2632. return shipyard->shipyardStatus() != 0 || retreiveTile(shipyard->bestLocation()) != sectorToReach->id;
  2633. }),shipyards.end());
  2634. if(!shipyards.size())
  2635. {
  2636. //TODO consider possibility of building shipyard in a town
  2637. return ret;
  2638. //throw cannotFulfillGoalException("There is no known shipyard!");
  2639. }
  2640. //we have only shipyards that possibly can build ships onto the appropriate EP
  2641. auto ownedGoodShipyard = boost::find_if(shipyards, [](const IShipyard *s) -> bool
  2642. {
  2643. return s->o->tempOwner == ai->playerID;
  2644. });
  2645. if(ownedGoodShipyard != shipyards.end())
  2646. {
  2647. const IShipyard *s = *ownedGoodShipyard;
  2648. TResources shipCost;
  2649. s->getBoatCost(shipCost);
  2650. if(cb->getResourceAmount().canAfford(shipCost))
  2651. {
  2652. int3 ret = s->bestLocation();
  2653. cb->buildBoat(s); //TODO: move actions elsewhere
  2654. return ret;
  2655. }
  2656. else
  2657. {
  2658. //TODO gather res
  2659. return ret;
  2660. //throw cannotFulfillGoalException("Not enough resources to build a boat");
  2661. }
  2662. }
  2663. else
  2664. {
  2665. //TODO pick best shipyard to take over
  2666. return shipyards.front()->o->visitablePos();
  2667. }
  2668. }
  2669. }
  2670. else if(src->water && !sectorToReach->water)
  2671. {
  2672. //TODO
  2673. //disembark
  2674. return ret;
  2675. }
  2676. else //use subterranean gates
  2677. {
  2678. //auto t = findFirstVisitableTile (h, dst);
  2679. //if (t.valid())
  2680. // return t;
  2681. //TODO: pop sectors linked by Subterranean Gate in loop
  2682. auto firstGate = boost::find_if(src->subterraneanGates, [=](const CGObjectInstance * gate) -> bool
  2683. {
  2684. //make sure no hero block the way
  2685. auto pos = ai->knownSubterraneanGates[gate]->visitablePos();
  2686. const TerrainTile *t = cb->getTile(pos);
  2687. return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::SUBTERRANEAN_GATE
  2688. && retreiveTile(pos) == sectorToReach->id;
  2689. });
  2690. if(firstGate != src->subterraneanGates.end())
  2691. {
  2692. //TODO: pahtfinder can find path through subterranean gates, but this function only reaches closest gate
  2693. return (*firstGate)->visitablePos();
  2694. }
  2695. //TODO
  2696. //Monolith? Whirlpool? ...
  2697. return ret;
  2698. //throw cannotFulfillGoalException("Land-land and water-water inter-sector transitions are not implemented!");
  2699. }
  2700. }
  2701. else
  2702. {
  2703. return ret;
  2704. //throw cannotFulfillGoalException("Inter-sector route detection failed: not connected sectors?");
  2705. }
  2706. }
  2707. else
  2708. {
  2709. return findFirstVisitableTile(h, dst);
  2710. }
  2711. //FIXME: find out why this line is reached
  2712. logAi->errorStream() << ("Impossible happened at SectorMap::firstTileToGet");
  2713. return ret;
  2714. }
  2715. int3 SectorMap::findFirstVisitableTile (HeroPtr h, crint3 dst)
  2716. {
  2717. int3 ret(-1,-1,-1);
  2718. int3 curtile = dst;
  2719. while(curtile != h->visitablePos())
  2720. {
  2721. auto topObj = cb->getTopObj(curtile);
  2722. if (topObj && topObj->ID == Obj::HERO && topObj != h.h)
  2723. {
  2724. logAi->warnStream() << ("Another allied hero stands in our way");
  2725. return ret;
  2726. }
  2727. if(cb->getPathInfo(curtile)->reachable())
  2728. {
  2729. return curtile;
  2730. }
  2731. else
  2732. {
  2733. auto i = parent.find(curtile);
  2734. if(i != parent.end())
  2735. {
  2736. assert(curtile != i->second);
  2737. curtile = i->second;
  2738. }
  2739. else
  2740. {
  2741. return ret;
  2742. //throw cannotFulfillGoalException("Unreachable tile in sector? Should not happen!");
  2743. }
  2744. }
  2745. }
  2746. return ret;
  2747. }
  2748. void SectorMap::makeParentBFS(crint3 source)
  2749. {
  2750. parent.clear();
  2751. int mySector = retreiveTile(source);
  2752. std::queue<int3> toVisit;
  2753. toVisit.push(source);
  2754. while(!toVisit.empty())
  2755. {
  2756. int3 curPos = toVisit.front();
  2757. toVisit.pop();
  2758. ui8 &sec = retreiveTile(curPos);
  2759. assert(sec == mySector); //consider only tiles from the same sector
  2760. UNUSED(sec);
  2761. foreach_neighbour(curPos, [&](crint3 neighPos)
  2762. {
  2763. if(retreiveTile(neighPos) == mySector && !vstd::contains(parent, neighPos))
  2764. {
  2765. if (cb->canMoveBetween(curPos, neighPos))
  2766. {
  2767. toVisit.push(neighPos);
  2768. parent[neighPos] = curPos;
  2769. }
  2770. }
  2771. });
  2772. }
  2773. }
  2774. unsigned char & SectorMap::retreiveTile(crint3 pos)
  2775. {
  2776. return retreiveTileN(sector, pos);
  2777. }