VCAI.cpp 88 KB

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