VCAI.cpp 99 KB

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