Goals.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. /*
  2. * Goals.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "Goals.h"
  12. #include "VCAI.h"
  13. #include "Fuzzy.h"
  14. #include "ResourceManager.h"
  15. #include "../../lib/mapping/CMap.h" //for victory conditions
  16. #include "../../lib/CPathfinder.h"
  17. #include "StringConstants.h"
  18. #include "AIhelper.h"
  19. extern boost::thread_specific_ptr<CCallback> cb;
  20. extern boost::thread_specific_ptr<VCAI> ai;
  21. extern boost::thread_specific_ptr<AIhelper> ah;
  22. extern FuzzyHelper * fh;
  23. using namespace Goals;
  24. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  25. {
  26. TSubgoal ptr;
  27. ptr.reset(tmp.clone());
  28. return ptr;
  29. }
  30. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  31. {
  32. std::string desc;
  33. switch(goalType)
  34. {
  35. case INVALID:
  36. return "INVALID";
  37. case WIN:
  38. return "WIN";
  39. case DO_NOT_LOSE:
  40. return "DO NOT LOOSE";
  41. case CONQUER:
  42. return "CONQUER";
  43. case BUILD:
  44. return "BUILD";
  45. case EXPLORE:
  46. desc = "EXPLORE";
  47. break;
  48. case GATHER_ARMY:
  49. desc = "GATHER ARMY";
  50. break;
  51. case BUY_ARMY:
  52. return "BUY ARMY";
  53. break;
  54. case BOOST_HERO:
  55. desc = "BOOST_HERO (unsupported)";
  56. break;
  57. case RECRUIT_HERO:
  58. return "RECRUIT HERO";
  59. case BUILD_STRUCTURE:
  60. return "BUILD STRUCTURE";
  61. case COLLECT_RES:
  62. desc = "COLLECT RESOURCE " + GameConstants::RESOURCE_NAMES[resID] + " (" + boost::lexical_cast<std::string>(value) + ")";
  63. break;
  64. case GATHER_TROOPS:
  65. desc = "GATHER TROOPS";
  66. break;
  67. case GET_OBJ:
  68. {
  69. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  70. if(obj)
  71. desc = "GET OBJ " + obj->getObjectName();
  72. }
  73. break;
  74. case FIND_OBJ:
  75. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  76. break;
  77. case VISIT_HERO:
  78. {
  79. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  80. if(obj)
  81. desc = "VISIT HERO " + obj->getObjectName();
  82. }
  83. break;
  84. case GET_ART_TYPE:
  85. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  86. break;
  87. case ISSUE_COMMAND:
  88. return "ISSUE COMMAND (unsupported)";
  89. case VISIT_TILE:
  90. desc = "VISIT TILE " + tile.toString();
  91. break;
  92. case CLEAR_WAY_TO:
  93. desc = "CLEAR WAY TO " + tile.toString();
  94. break;
  95. case DIG_AT_TILE:
  96. desc = "DIG AT TILE " + tile.toString();
  97. break;
  98. default:
  99. return boost::lexical_cast<std::string>(goalType);
  100. }
  101. if(hero.get(true)) //FIXME: used to crash when we lost hero and failed goal
  102. desc += " (" + hero->name + ")";
  103. return desc;
  104. }
  105. //TODO: virtualize if code gets complex?
  106. bool Goals::AbstractGoal::operator==(AbstractGoal & g)
  107. {
  108. if(g.goalType != goalType)
  109. return false;
  110. if(g.isElementar != isElementar) //elementar goals fulfill long term non-elementar goals (VisitTile)
  111. return false;
  112. switch(goalType)
  113. {
  114. //no parameters
  115. case INVALID:
  116. case WIN:
  117. case DO_NOT_LOSE:
  118. case RECRUIT_HERO: //overloaded
  119. return true;
  120. break;
  121. //assigned to hero, no parameters
  122. case CONQUER:
  123. case EXPLORE:
  124. case BOOST_HERO:
  125. return g.hero.h == hero.h; //how comes HeroPtrs are equal for different heroes?
  126. break;
  127. case GATHER_ARMY: //actual value is indifferent
  128. return (g.hero.h == hero.h || town == g.town); //TODO: gather army for town maybe?
  129. break;
  130. //assigned hero and tile
  131. case VISIT_TILE:
  132. case CLEAR_WAY_TO:
  133. case DIG_AT_TILE:
  134. return (g.hero.h == hero.h && g.tile == tile);
  135. break;
  136. //assigned hero and object
  137. case GET_OBJ:
  138. case FIND_OBJ: //TODO: use subtype?
  139. case VISIT_HERO:
  140. case GET_ART_TYPE:
  141. return (g.hero.h == hero.h && g.objid == objid);
  142. break;
  143. case BUILD_STRUCTURE:
  144. return (town == g.town && bid == g.bid); //build specific structure in specific town
  145. break;
  146. //no check atm
  147. case COLLECT_RES:
  148. return (resID == g.resID); //every hero may collect resources
  149. break;
  150. case GATHER_TROOPS:
  151. case ISSUE_COMMAND:
  152. case BUILD: //TODO: should be decomposed to build specific structures
  153. default:
  154. return false;
  155. }
  156. }
  157. //TODO: find out why the following are not generated automatically on MVS?
  158. namespace Goals
  159. {
  160. template<>
  161. void CGoal<Win>::accept(VCAI * ai)
  162. {
  163. ai->tryRealize(static_cast<Win &>(*this));
  164. }
  165. template<>
  166. void CGoal<Build>::accept(VCAI * ai)
  167. {
  168. ai->tryRealize(static_cast<Build &>(*this));
  169. }
  170. template<>
  171. float CGoal<Win>::accept(FuzzyHelper * f)
  172. {
  173. return f->evaluate(static_cast<Win &>(*this));
  174. }
  175. template<>
  176. float CGoal<Build>::accept(FuzzyHelper * f)
  177. {
  178. return f->evaluate(static_cast<Build &>(*this));
  179. }
  180. bool TSubgoal::operator==(const TSubgoal & rhs) const
  181. {
  182. return *get() == *rhs.get(); //comparison for Goals is overloaded, so they don't need to be identical to match
  183. }
  184. bool BuyArmy::operator==(BuyArmy & g)
  185. {
  186. //if (hero && hero != g.hero)
  187. // return false;
  188. return town == g.town;
  189. }
  190. bool BuyArmy::fulfillsMe(TSubgoal goal)
  191. {
  192. //if (hero && hero != goal->hero)
  193. // return false;
  194. return town == goal->town && goal->value >= value; //can always buy more army
  195. }
  196. TSubgoal BuyArmy::whatToDoToAchieve()
  197. {
  198. //TODO: calculate the actual cost of units instead
  199. TResources price;
  200. price[Res::GOLD] = value * 0.4f; //some approximate value
  201. return ah->whatToDo(price, iAmElementar()); //buy right now or gather resources
  202. }
  203. std::string BuyArmy::completeMessage() const
  204. {
  205. return boost::format("Bought army of value %d in town of %s") % boost::lexical_cast<std::string>(value), town->name;
  206. }
  207. }
  208. //TSubgoal AbstractGoal::whatToDoToAchieve()
  209. //{
  210. // logAi->debug("Decomposing goal of type %s",name());
  211. // return sptr (Goals::Explore());
  212. //}
  213. TSubgoal Win::whatToDoToAchieve()
  214. {
  215. auto toBool = [=](const EventCondition &)
  216. {
  217. // TODO: proper implementation
  218. // Right now even already fulfilled goals will be included into generated list
  219. // Proper check should test if event condition is already fulfilled
  220. // Easiest way to do this is to call CGameState::checkForVictory but this function should not be
  221. // used on client side or in AI code
  222. return false;
  223. };
  224. std::vector<EventCondition> goals;
  225. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  226. {
  227. //TODO: try to eliminate human player(s) using loss conditions that have isHuman element
  228. if(event.effect.type == EventEffect::VICTORY)
  229. {
  230. boost::range::copy(event.trigger.getFulfillmentCandidates(toBool), std::back_inserter(goals));
  231. }
  232. }
  233. //TODO: instead of returning first encountered goal AI should generate list of possible subgoals
  234. for(const EventCondition & goal : goals)
  235. {
  236. switch(goal.condition)
  237. {
  238. case EventCondition::HAVE_ARTIFACT:
  239. return sptr(Goals::GetArtOfType(goal.objectType));
  240. case EventCondition::DESTROY:
  241. {
  242. if(goal.object)
  243. {
  244. auto obj = cb->getObj(goal.object->id);
  245. if(obj)
  246. if(obj->getOwner() == ai->playerID) //we can't capture our own object
  247. return sptr(Goals::Conquer());
  248. return sptr(Goals::GetObj(goal.object->id.getNum()));
  249. }
  250. else
  251. {
  252. // TODO: destroy all objects of type goal.objectType
  253. // This situation represents "kill all creatures" condition from H3
  254. break;
  255. }
  256. }
  257. case EventCondition::HAVE_BUILDING:
  258. {
  259. // TODO build other buildings apart from Grail
  260. // goal.objectType = buidingID to build
  261. // goal.object = optional, town in which building should be built
  262. // Represents "Improve town" condition from H3 (but unlike H3 it consists from 2 separate conditions)
  263. if(goal.objectType == BuildingID::GRAIL)
  264. {
  265. if(auto h = ai->getHeroWithGrail())
  266. {
  267. //hero is in a town that can host Grail
  268. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  269. {
  270. const CGTownInstance * t = h->visitedTown;
  271. return sptr(Goals::BuildThis(BuildingID::GRAIL, t).setpriority(10));
  272. }
  273. else
  274. {
  275. auto towns = cb->getTownsInfo();
  276. towns.erase(boost::remove_if(towns,
  277. [](const CGTownInstance * t) -> bool
  278. {
  279. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  280. }),
  281. towns.end());
  282. boost::sort(towns, CDistanceSorter(h.get()));
  283. if(towns.size())
  284. {
  285. return sptr(Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  286. }
  287. }
  288. }
  289. double ratio = 0;
  290. // maybe make this check a bit more complex? For example:
  291. // 0.75 -> dig randomly within 3 tiles radius
  292. // 0.85 -> radius now 2 tiles
  293. // 0.95 -> 1 tile radius, position is fully known
  294. // AFAIK H3 AI does something like this
  295. int3 grailPos = cb->getGrailPos(&ratio);
  296. if(ratio > 0.99)
  297. {
  298. return sptr(Goals::DigAtTile(grailPos));
  299. } //TODO: use FIND_OBJ
  300. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  301. return sptr(Goals::GetObj(obj->id.getNum()));
  302. else
  303. return sptr(Goals::Explore());
  304. }
  305. break;
  306. }
  307. case EventCondition::CONTROL:
  308. {
  309. if(goal.object)
  310. {
  311. return sptr(Goals::GetObj(goal.object->id.getNum()));
  312. }
  313. else
  314. {
  315. //TODO: control all objects of type "goal.objectType"
  316. // Represents H3 condition "Flag all mines"
  317. break;
  318. }
  319. }
  320. case EventCondition::HAVE_RESOURCES:
  321. //TODO mines? piles? marketplace?
  322. //save?
  323. return sptr(Goals::CollectRes(static_cast<Res::ERes>(goal.objectType), goal.value));
  324. case EventCondition::HAVE_CREATURES:
  325. return sptr(Goals::GatherTroops(goal.objectType, goal.value));
  326. case EventCondition::TRANSPORT:
  327. {
  328. //TODO. merge with bring Grail to town? So AI will first dig grail, then transport it using this goal and builds it
  329. // Represents "transport artifact" condition:
  330. // goal.objectType = type of artifact
  331. // goal.object = destination-town where artifact should be transported
  332. break;
  333. }
  334. case EventCondition::STANDARD_WIN:
  335. return sptr(Goals::Conquer());
  336. // Conditions that likely don't need any implementation
  337. case EventCondition::DAYS_PASSED:
  338. break; // goal.value = number of days for condition to trigger
  339. case EventCondition::DAYS_WITHOUT_TOWN:
  340. break; // goal.value = number of days to trigger this
  341. case EventCondition::IS_HUMAN:
  342. break; // Should be only used in calculation of candidates (see toBool lambda)
  343. case EventCondition::CONST_VALUE:
  344. break;
  345. case EventCondition::HAVE_0:
  346. case EventCondition::HAVE_BUILDING_0:
  347. case EventCondition::DESTROY_0:
  348. //TODO: support new condition format
  349. return sptr(Goals::Conquer());
  350. default:
  351. assert(0);
  352. }
  353. }
  354. return sptr(Goals::Invalid());
  355. }
  356. TSubgoal FindObj::whatToDoToAchieve()
  357. {
  358. const CGObjectInstance * o = nullptr;
  359. if(resID > -1) //specified
  360. {
  361. for(const CGObjectInstance * obj : ai->visitableObjs)
  362. {
  363. if(obj->ID == objid && obj->subID == resID)
  364. {
  365. o = obj;
  366. break; //TODO: consider multiple objects and choose best
  367. }
  368. }
  369. }
  370. else
  371. {
  372. for(const CGObjectInstance * obj : ai->visitableObjs)
  373. {
  374. if(obj->ID == objid)
  375. {
  376. o = obj;
  377. break; //TODO: consider multiple objects and choose best
  378. }
  379. }
  380. }
  381. if(o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  382. return sptr(Goals::GetObj(o->id.getNum()));
  383. else
  384. return sptr(Goals::Explore());
  385. }
  386. bool Goals::FindObj::fulfillsMe(TSubgoal goal)
  387. {
  388. if (goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  389. {
  390. if (!hero || hero == goal->hero)
  391. for (auto obj : cb->getVisitableObjs(goal->tile)) //check if any object on that tile matches criteria
  392. if (obj->visitablePos() == goal->tile) //object could be removed
  393. if (obj->ID == objid && obj->subID == resID) //same type and subtype
  394. return true;
  395. }
  396. return false;
  397. }
  398. std::string GetObj::completeMessage() const
  399. {
  400. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  401. }
  402. TSubgoal GetObj::whatToDoToAchieve()
  403. {
  404. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  405. if(!obj)
  406. return sptr(Goals::Explore());
  407. if(obj->tempOwner == ai->playerID) //we can't capture our own object -> move to Win codition
  408. throw cannotFulfillGoalException("Cannot capture my own object " + obj->getObjectName());
  409. int3 pos = obj->visitablePos();
  410. if(hero)
  411. {
  412. if(ai->isAccessibleForHero(pos, hero))
  413. return sptr(Goals::VisitTile(pos).sethero(hero));
  414. }
  415. else
  416. {
  417. for(auto h : cb->getHeroesInfo())
  418. {
  419. if(ai->isAccessibleForHero(pos, h))
  420. return sptr(Goals::VisitTile(pos).sethero(h)); //we must visit object with same hero, if any
  421. }
  422. }
  423. return sptr(Goals::ClearWayTo(pos).sethero(hero));
  424. }
  425. bool GetObj::fulfillsMe(TSubgoal goal)
  426. {
  427. if(goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  428. {
  429. if (!hero || hero == goal->hero)
  430. {
  431. auto obj = cb->getObj(ObjectInstanceID(objid));
  432. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  433. return true;
  434. }
  435. }
  436. return false;
  437. }
  438. std::string VisitHero::completeMessage() const
  439. {
  440. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  441. }
  442. TSubgoal VisitHero::whatToDoToAchieve()
  443. {
  444. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  445. if(!obj)
  446. return sptr(Goals::Explore());
  447. int3 pos = obj->visitablePos();
  448. if(hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  449. {
  450. if(hero->pos == pos)
  451. logAi->error("Hero %s tries to visit himself.", hero.name);
  452. else
  453. {
  454. //can't use VISIT_TILE here as tile appears blocked by target hero
  455. //FIXME: elementar goal should not be abstract
  456. return sptr(Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  457. }
  458. }
  459. return sptr(Goals::Invalid());
  460. }
  461. bool VisitHero::fulfillsMe(TSubgoal goal)
  462. {
  463. //TODO: VisitObj shoudl not be used for heroes, but...
  464. if(goal->goalType == Goals::VISIT_TILE)
  465. {
  466. auto obj = cb->getObj(ObjectInstanceID(objid));
  467. if (!obj)
  468. {
  469. logAi->error("Hero %s: VisitHero::fulfillsMe at %s: object %d not found", hero.name, goal->tile.toString(), objid);
  470. return false;
  471. }
  472. return obj->visitablePos() == goal->tile;
  473. }
  474. return false;
  475. }
  476. TSubgoal GetArtOfType::whatToDoToAchieve()
  477. {
  478. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  479. if(alternativeWay->invalid())
  480. return sptr(Goals::FindObj(Obj::ARTIFACT, aid));
  481. return sptr(Goals::Invalid());
  482. }
  483. TSubgoal ClearWayTo::whatToDoToAchieve()
  484. {
  485. assert(cb->isInTheMap(tile)); //set tile
  486. if(!cb->isVisible(tile))
  487. {
  488. logAi->error("Clear way should be used with visible tiles!");
  489. return sptr(Goals::Explore());
  490. }
  491. return (fh->chooseSolution(getAllPossibleSubgoals()));
  492. }
  493. bool Goals::ClearWayTo::fulfillsMe(TSubgoal goal)
  494. {
  495. if (goal->goalType == Goals::VISIT_TILE)
  496. if (!hero || hero == goal->hero)
  497. return tile == goal->tile;
  498. return false;
  499. }
  500. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  501. {
  502. TGoalVec ret;
  503. std::vector<const CGHeroInstance *> heroes;
  504. if(hero)
  505. heroes.push_back(hero.h);
  506. else
  507. heroes = cb->getHeroesInfo();
  508. for(auto h : heroes)
  509. {
  510. //TODO: handle clearing way to allied heroes that are blocked
  511. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  512. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  513. // continue;
  514. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  515. auto sm = ai->getCachedSectorMap(h);
  516. int3 tileToHit = sm->firstTileToGet(h, tile);
  517. if(!tileToHit.valid())
  518. continue;
  519. if(isBlockedBorderGate(tileToHit))
  520. {
  521. //FIXME: this way we'll not visit gate and activate quest :?
  522. ret.push_back(sptr(Goals::FindObj(Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  523. }
  524. auto topObj = cb->getTopObj(tileToHit);
  525. if(topObj)
  526. {
  527. if(vstd::contains(ai->reservedObjs, topObj) && !vstd::contains(ai->reservedHeroesMap[h], topObj))
  528. {
  529. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile, h)));
  530. continue; //do not capure object reserved by other hero
  531. }
  532. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  533. {
  534. if(topObj != hero.get(true)) //the hero we want to free
  535. logAi->error("%s stands in the way of %s", topObj->getObjectName(), h->getObjectName());
  536. }
  537. if(topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  538. {
  539. if(shouldVisit(h, topObj))
  540. {
  541. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  542. ret.push_back(sptr(Goals::GetObj(topObj->id.getNum()).sethero(h)));
  543. continue; //do not try to visit tile or gather army
  544. }
  545. else
  546. {
  547. //TODO: we should be able to return apriopriate quest here (VCAI::striveToQuest)
  548. logAi->debug("Quest guard blocks the way to %s", tile.toString());
  549. continue; //do not access quets guard if we can't complete the quest
  550. }
  551. }
  552. }
  553. if(isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there i no quest object
  554. {
  555. ret.push_back(sptr(Goals::VisitTile(tileToHit).sethero(h)));
  556. }
  557. else
  558. {
  559. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(tileToHit, h) * SAFE_ATTACK_CONSTANT).
  560. sethero(h).setisAbstract(true)));
  561. }
  562. }
  563. if(ai->canRecruitAnyHero())
  564. ret.push_back(sptr(Goals::RecruitHero()));
  565. if(ret.empty())
  566. {
  567. logAi->warn("There is no known way to clear the way to tile %s", tile.toString());
  568. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  569. }
  570. return ret;
  571. }
  572. std::string Explore::completeMessage() const
  573. {
  574. return "Hero " + hero.get()->name + " completed exploration";
  575. }
  576. TSubgoal Explore::whatToDoToAchieve()
  577. {
  578. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  579. if(hero) //use best step for this hero
  580. {
  581. return ret;
  582. }
  583. else
  584. {
  585. if(ret->hero.get(true))
  586. return sptr(sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  587. else
  588. return ret; //other solutions, like buying hero from tavern
  589. }
  590. }
  591. TGoalVec Explore::getAllPossibleSubgoals()
  592. {
  593. TGoalVec ret;
  594. std::vector<const CGHeroInstance *> heroes;
  595. if(hero)
  596. {
  597. heroes.push_back(hero.h);
  598. }
  599. else
  600. {
  601. //heroes = ai->getUnblockedHeroes();
  602. heroes = cb->getHeroesInfo();
  603. vstd::erase_if(heroes, [](const HeroPtr h)
  604. {
  605. if(ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  606. return true;
  607. if(!ai->isAbleToExplore(h))
  608. return true;
  609. return !h->movement; //saves time, immobile heroes are useless anyway
  610. });
  611. }
  612. //try to use buildings that uncover map
  613. std::vector<const CGObjectInstance *> objs;
  614. for(auto obj : ai->visitableObjs)
  615. {
  616. if(!vstd::contains(ai->alreadyVisited, obj))
  617. {
  618. switch(obj->ID.num)
  619. {
  620. case Obj::REDWOOD_OBSERVATORY:
  621. case Obj::PILLAR_OF_FIRE:
  622. case Obj::CARTOGRAPHER:
  623. objs.push_back(obj);
  624. break;
  625. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  626. case Obj::MONOLITH_TWO_WAY:
  627. case Obj::SUBTERRANEAN_GATE:
  628. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  629. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  630. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  631. objs.push_back(obj);
  632. break;
  633. }
  634. }
  635. else
  636. {
  637. switch(obj->ID.num)
  638. {
  639. case Obj::MONOLITH_TWO_WAY:
  640. case Obj::SUBTERRANEAN_GATE:
  641. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  642. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  643. break;
  644. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  645. {
  646. if(!cb->getObj(exit))
  647. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  648. objs.push_back(obj);
  649. break;
  650. }
  651. }
  652. break;
  653. }
  654. }
  655. }
  656. for(auto h : heroes)
  657. {
  658. auto sm = ai->getCachedSectorMap(h);
  659. for(auto obj : objs) //double loop, performance risk?
  660. {
  661. auto t = sm->firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  662. if(ai->isTileNotReserved(h, t))
  663. ret.push_back(sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  664. }
  665. int3 t = whereToExplore(h);
  666. if(t.valid())
  667. {
  668. ret.push_back(sptr(Goals::VisitTile(t).sethero(h)));
  669. }
  670. else
  671. {
  672. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  673. //possible issues when gathering army to break
  674. if(hero.h == h || (!hero && h == ai->primaryHero().h)) //check this only ONCE, high cost
  675. {
  676. t = ai->explorationDesperate(h);
  677. if(t.valid()) //don't waste time if we are completely blocked
  678. ret.push_back(sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  679. }
  680. }
  681. }
  682. //we either don't have hero yet or none of heroes can explore
  683. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  684. ret.push_back(sptr(Goals::RecruitHero()));
  685. if(ret.empty())
  686. {
  687. throw goalFulfilledException(sptr(Goals::Explore().sethero(hero)));
  688. }
  689. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  690. return ret;
  691. }
  692. bool Explore::fulfillsMe(TSubgoal goal)
  693. {
  694. if(goal->goalType == Goals::EXPLORE)
  695. {
  696. if(goal->hero)
  697. return hero == goal->hero;
  698. else
  699. return true; //cancel ALL exploration
  700. }
  701. return false;
  702. }
  703. TSubgoal RecruitHero::whatToDoToAchieve()
  704. {
  705. const CGTownInstance * t = ai->findTownWithTavern();
  706. if(!t)
  707. return sptr(Goals::BuildThis(BuildingID::TAVERN).setpriority(2));
  708. TResources res;
  709. res[Res::GOLD] = GameConstants::HERO_GOLD_COST;
  710. return ah->whatToDo(res, iAmElementar()); //either buy immediately, or collect res
  711. }
  712. bool Goals::RecruitHero::operator==(RecruitHero & g)
  713. {
  714. //TODO: check town and hero
  715. return true; //for now, recruiting any hero will do
  716. }
  717. std::string VisitTile::completeMessage() const
  718. {
  719. return "Hero " + hero.get()->name + " visited tile " + tile.toString();
  720. }
  721. TSubgoal VisitTile::whatToDoToAchieve()
  722. {
  723. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  724. if(ret->hero)
  725. {
  726. if(isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  727. {
  728. if(cb->getTile(tile)->topVisitableId().num == Obj::TOWN) //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  729. ret->objid = Obj::TOWN; //TODO: move to getObj eventually and add appropiate logic there
  730. ret->setisElementar(true);
  731. return ret;
  732. }
  733. else
  734. {
  735. return sptr(Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  736. .sethero(ret->hero).setisAbstract(true));
  737. }
  738. }
  739. return ret;
  740. }
  741. TGoalVec VisitTile::getAllPossibleSubgoals()
  742. {
  743. assert(cb->isInTheMap(tile));
  744. TGoalVec ret;
  745. if(!cb->isVisible(tile))
  746. ret.push_back(sptr(Goals::Explore())); //what sense does it make?
  747. else
  748. {
  749. std::vector<const CGHeroInstance *> heroes;
  750. if(hero)
  751. heroes.push_back(hero.h); //use assigned hero if any
  752. else
  753. heroes = cb->getHeroesInfo(); //use most convenient hero
  754. for(auto h : heroes)
  755. {
  756. if(ai->isAccessibleForHero(tile, h))
  757. ret.push_back(sptr(Goals::VisitTile(tile).sethero(h)));
  758. }
  759. if(ai->canRecruitAnyHero())
  760. ret.push_back(sptr(Goals::RecruitHero()));
  761. }
  762. if(ret.empty())
  763. {
  764. auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  765. if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  766. {
  767. if(hero.get(true) && hero->id == obj->id) //if it's assigned hero, visit tile. If it's different hero, we can't visit tile now
  768. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  769. else
  770. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  771. }
  772. else
  773. ret.push_back(sptr(Goals::ClearWayTo(tile)));
  774. }
  775. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  776. return ret;
  777. }
  778. TSubgoal DigAtTile::whatToDoToAchieve()
  779. {
  780. const CGObjectInstance * firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  781. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  782. {
  783. const CGHeroInstance * h = dynamic_cast<const CGHeroInstance *>(firstObj);
  784. sethero(h).setisElementar(true);
  785. return sptr(*this);
  786. }
  787. return sptr(Goals::VisitTile(tile));
  788. }
  789. TSubgoal BuildThis::whatToDoToAchieve()
  790. {
  791. auto b = BuildingID(bid);
  792. // find town if not set
  793. if (!town && hero)
  794. town = hero->visitedTown;
  795. if (!town)
  796. {
  797. for (const CGTownInstance * t : cb->getTownsInfo())
  798. {
  799. switch (cb->canBuildStructure(town, b))
  800. {
  801. case EBuildingState::ALLOWED:
  802. town = t;
  803. break; //TODO: look for prerequisites? this is not our reponsibility
  804. default:
  805. continue;
  806. }
  807. }
  808. }
  809. if (town) //we have specific town to build this
  810. {
  811. auto res = town->town->buildings.at(BuildingID(bid))->resources;
  812. return ah->whatToDo(res, iAmElementar()); //realize immediately or gather resources
  813. }
  814. else
  815. throw cannotFulfillGoalException("Cannot find town to build this");
  816. }
  817. TGoalVec Goals::CollectRes::getAllPossibleSubgoals()
  818. {
  819. TGoalVec ret;
  820. auto givesResource = [this](const CGObjectInstance * obj) -> bool
  821. {
  822. //TODO: move this logic to object side
  823. //TODO: remember mithril exists
  824. //TODO: water objects
  825. //TODO: Creature banks
  826. //return false first from once-visitable, before checking if they were even visited
  827. switch (obj->ID.num)
  828. {
  829. case Obj::TREASURE_CHEST:
  830. return resID == Res::GOLD;
  831. break;
  832. case Obj::RESOURCE:
  833. return obj->subID == resID;
  834. break;
  835. case Obj::MINE:
  836. return (obj->subID == resID &&
  837. (cb->getPlayerRelations(obj->tempOwner, ai->playerID) == PlayerRelations::ENEMIES)); //don't capture our mines
  838. break;
  839. case Obj::CAMPFIRE:
  840. return true; //contains all resources
  841. break;
  842. case Obj::WINDMILL:
  843. switch (resID)
  844. {
  845. case Res::GOLD:
  846. case Res::WOOD:
  847. return false;
  848. }
  849. break;
  850. case Obj::WATER_WHEEL:
  851. if (resID != Res::GOLD)
  852. return false;
  853. break;
  854. case Obj::MYSTICAL_GARDEN:
  855. if ((resID != Res::GOLD) && (resID != Res::GEMS))
  856. return false;
  857. break;
  858. case Obj::LEAN_TO:
  859. case Obj::WAGON:
  860. if (resID != Res::GOLD)
  861. return false;
  862. break;
  863. default:
  864. return false;
  865. break;
  866. }
  867. return !vstd::contains(ai->alreadyVisited, obj); //for weekly / once visitable
  868. };
  869. std::vector<const CGObjectInstance *> objs;
  870. for (auto obj : ai->visitableObjs)
  871. {
  872. if (givesResource(obj))
  873. objs.push_back(obj);
  874. }
  875. for (auto h : cb->getHeroesInfo())
  876. {
  877. auto sm = ai->getCachedSectorMap(h);
  878. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  879. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  880. {
  881. if (givesResource(obj))
  882. ourObjs.push_back(obj);
  883. }
  884. for (auto obj : ourObjs)
  885. {
  886. int3 dest = obj->visitablePos();
  887. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  888. if (t.valid()) //we know any path at all
  889. {
  890. if (ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  891. {
  892. if (isSafeToVisit(h, dest))
  893. {
  894. if (dest != t) //there is something blocking our way
  895. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  896. else
  897. {
  898. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  899. }
  900. }
  901. else //we need to get army in order to pick that object
  902. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  903. }
  904. }
  905. }
  906. }
  907. return ret;
  908. }
  909. TSubgoal CollectRes::whatToDoToAchieve()
  910. {
  911. auto goals = getAllPossibleSubgoals();
  912. auto trade = whatToDoToTrade();
  913. if (!trade->invalid())
  914. goals.push_back(trade);
  915. if (goals.empty())
  916. return sptr(Goals::Explore()); //we can always do that
  917. else
  918. return fh->chooseSolution(goals); //TODO: evaluate trading
  919. }
  920. TSubgoal Goals::CollectRes::whatToDoToTrade()
  921. {
  922. std::vector<const IMarket *> markets;
  923. std::vector<const CGObjectInstance *> visObjs;
  924. ai->retrieveVisitableObjs(visObjs, true);
  925. for (const CGObjectInstance * obj : visObjs)
  926. {
  927. if (const IMarket * m = IMarket::castFrom(obj, false))
  928. {
  929. if (obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  930. markets.push_back(m);
  931. else if (obj->ID == Obj::TRADING_POST)
  932. markets.push_back(m);
  933. }
  934. }
  935. boost::sort(markets, [](const IMarket * m1, const IMarket * m2) -> bool
  936. {
  937. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  938. });
  939. markets.erase(boost::remove_if(markets, [](const IMarket * market) -> bool
  940. {
  941. if (!(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID))
  942. {
  943. if (!ai->isAccessible(market->o->visitablePos()))
  944. return true;
  945. }
  946. return false;
  947. }), markets.end());
  948. if (!markets.size())
  949. {
  950. for (const CGTownInstance * t : cb->getTownsInfo())
  951. {
  952. if (cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  953. return sptr(Goals::BuildThis(BuildingID::MARKETPLACE, t).setpriority(2));
  954. }
  955. }
  956. else
  957. {
  958. const IMarket * m = markets.back();
  959. //attempt trade at back (best prices)
  960. int howManyCanWeBuy = 0;
  961. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  962. {
  963. if (i == resID)
  964. continue;
  965. int toGive = -1, toReceive = -1;
  966. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  967. assert(toGive > 0 && toReceive > 0);
  968. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  969. }
  970. if (howManyCanWeBuy >= value)
  971. {
  972. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  973. assert(backObj);
  974. auto objid = m->o->id.getNum();
  975. if (backObj->tempOwner != ai->playerID)
  976. {
  977. return sptr(Goals::GetObj(objid));
  978. }
  979. else
  980. {
  981. if (m->o->ID == Obj::TOWN) //just trade remotely using town objid
  982. return sptr(setobjid(objid).setisElementar(true));
  983. else //just go there
  984. return sptr(Goals::GetObj(objid).setisElementar(true));
  985. }
  986. }
  987. }
  988. return sptr(Goals::Invalid()); //cannot trade
  989. //TODO: separate goal to execute trade?
  990. //return sptr(setisElementar(true)); //not sure why we are here
  991. }
  992. bool CollectRes::fulfillsMe(TSubgoal goal)
  993. {
  994. if (goal->resID == resID)
  995. if (goal->value >= value)
  996. return true;
  997. return false;
  998. }
  999. TSubgoal GatherTroops::whatToDoToAchieve()
  1000. {
  1001. std::vector<const CGDwelling *> dwellings;
  1002. for(const CGTownInstance * t : cb->getTownsInfo())
  1003. {
  1004. auto creature = VLC->creh->creatures[objid];
  1005. if(t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  1006. {
  1007. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  1008. if(!creatures)
  1009. continue;
  1010. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  1011. if(upgradeNumber < 0)
  1012. continue;
  1013. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  1014. if(t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  1015. {
  1016. dwellings.push_back(t);
  1017. }
  1018. else
  1019. {
  1020. return sptr(Goals::BuildThis(bid, t).setpriority(priority));
  1021. }
  1022. }
  1023. }
  1024. for(auto obj : ai->visitableObjs)
  1025. {
  1026. if(obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  1027. continue;
  1028. auto d = dynamic_cast<const CGDwelling *>(obj);
  1029. for(auto creature : d->creatures)
  1030. {
  1031. if(creature.first) //there are more than 0 creatures avaliabe
  1032. {
  1033. for(auto type : creature.second)
  1034. {
  1035. if(type == objid && ah->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  1036. dwellings.push_back(d);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. if(dwellings.size())
  1042. {
  1043. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  1044. // sorted helper
  1045. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  1046. {
  1047. const CGPathNode * ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos());
  1048. const CGPathNode * rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  1049. if(ln->turns != rn->turns)
  1050. return ln->turns < rn->turns;
  1051. return (ln->moveRemains > rn->moveRemains);
  1052. };
  1053. // for all owned heroes generate map <hero -> nearest dwelling>
  1054. TDwellMap nearestDwellings;
  1055. for(const CGHeroInstance * hero : cb->getHeroesInfo(true))
  1056. {
  1057. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  1058. }
  1059. if(nearestDwellings.size())
  1060. {
  1061. // find hero who is nearest to a dwelling
  1062. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  1063. if(!nearest)
  1064. throw cannotFulfillGoalException("Cannot find nearest dwelling!");
  1065. return sptr(Goals::GetObj(nearest->id.getNum()));
  1066. }
  1067. else
  1068. return sptr(Goals::Explore());
  1069. }
  1070. else
  1071. {
  1072. return sptr(Goals::Explore());
  1073. }
  1074. //TODO: exchange troops between heroes
  1075. }
  1076. bool Goals::GatherTroops::fulfillsMe(TSubgoal goal)
  1077. {
  1078. if (!hero || hero == goal->hero) //we got army for desired hero or any hero
  1079. if (goal->objid == objid) //same creature type //TODO: consider upgrades?
  1080. if (goal->value >= value) //notify every time we get resources?
  1081. return true;
  1082. return false;
  1083. }
  1084. TSubgoal Conquer::whatToDoToAchieve()
  1085. {
  1086. return fh->chooseSolution(getAllPossibleSubgoals());
  1087. }
  1088. TGoalVec Conquer::getAllPossibleSubgoals()
  1089. {
  1090. TGoalVec ret;
  1091. auto conquerable = [](const CGObjectInstance * obj) -> bool
  1092. {
  1093. if(cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  1094. {
  1095. switch(obj->ID.num)
  1096. {
  1097. case Obj::TOWN:
  1098. case Obj::HERO:
  1099. case Obj::CREATURE_GENERATOR1:
  1100. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  1101. return true;
  1102. }
  1103. }
  1104. return false;
  1105. };
  1106. std::vector<const CGObjectInstance *> objs;
  1107. for(auto obj : ai->visitableObjs)
  1108. {
  1109. if(conquerable(obj))
  1110. objs.push_back(obj);
  1111. }
  1112. for(auto h : cb->getHeroesInfo())
  1113. {
  1114. auto sm = ai->getCachedSectorMap(h);
  1115. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  1116. for(auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  1117. {
  1118. if(conquerable(obj))
  1119. ourObjs.push_back(obj);
  1120. }
  1121. for(auto obj : ourObjs)
  1122. {
  1123. int3 dest = obj->visitablePos();
  1124. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  1125. if(t.valid()) //we know any path at all
  1126. {
  1127. if(ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  1128. {
  1129. if(isSafeToVisit(h, dest))
  1130. {
  1131. if(dest != t) //there is something blocking our way
  1132. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  1133. else
  1134. {
  1135. if(obj->ID.num == Obj::HERO) //enemy hero may move to other position
  1136. {
  1137. ret.push_back(sptr(Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  1138. }
  1139. else //just visit that tile
  1140. {
  1141. if(obj->ID.num == Obj::TOWN)
  1142. //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  1143. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setobjid(obj->ID.num).setisAbstract(true))); //TODO: change to getObj eventually and and move appropiate logic there
  1144. else
  1145. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  1146. }
  1147. }
  1148. }
  1149. else //we need to get army in order to conquer that place
  1150. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  1151. }
  1152. }
  1153. }
  1154. }
  1155. if(!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  1156. ret.push_back(sptr(Goals::RecruitHero()));
  1157. if(ret.empty())
  1158. ret.push_back(sptr(Goals::Explore())); //we need to find an enemy
  1159. return ret;
  1160. }
  1161. TSubgoal Build::whatToDoToAchieve()
  1162. {
  1163. return iAmElementar();
  1164. }
  1165. bool Goals::Build::fulfillsMe(TSubgoal goal)
  1166. {
  1167. if (goal->goalType == Goals::BUILD || goal->goalType == Goals::BUILD_STRUCTURE)
  1168. return (!town || town == goal->town); //building anything will do, in this town if set
  1169. else
  1170. return false;
  1171. }
  1172. TSubgoal Invalid::whatToDoToAchieve()
  1173. {
  1174. return iAmElementar();
  1175. }
  1176. std::string GatherArmy::completeMessage() const
  1177. {
  1178. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  1179. }
  1180. TSubgoal GatherArmy::whatToDoToAchieve()
  1181. {
  1182. //TODO: find hero if none set
  1183. assert(hero.h);
  1184. return fh->chooseSolution(getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  1185. }
  1186. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1187. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1188. TGoalVec GatherArmy::getAllPossibleSubgoals()
  1189. {
  1190. //get all possible towns, heroes and dwellings we may use
  1191. TGoalVec ret;
  1192. //TODO: include evaluation of monsters gather in calculation
  1193. for(auto t : cb->getTownsInfo())
  1194. {
  1195. auto pos = t->visitablePos();
  1196. if(ai->isAccessibleForHero(pos, hero))
  1197. {
  1198. //grab army from town
  1199. if(!t->visitingHero && howManyReinforcementsCanGet(hero, t))
  1200. {
  1201. if(!vstd::contains(ai->townVisitsThisWeek[hero], t))
  1202. ret.push_back(sptr(Goals::VisitTile(pos).sethero(hero)));
  1203. }
  1204. //buy army in town
  1205. if (!t->visitingHero || t->visitingHero != hero.get(true))
  1206. {
  1207. ui32 val = std::min<ui32>(value, howManyReinforcementsCanBuy(hero, t));
  1208. if (val)
  1209. {
  1210. auto goal = sptr(Goals::BuyArmy(t, val).sethero(hero));
  1211. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1212. ret.push_back(goal);
  1213. }
  1214. }
  1215. //build dwelling
  1216. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  1217. if (bid != BuildingID::NONE)
  1218. {
  1219. auto goal = sptr(BuildThis(bid, t).setpriority(priority));
  1220. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1221. ret.push_back(goal);
  1222. }
  1223. }
  1224. }
  1225. auto otherHeroes = cb->getHeroesInfo();
  1226. auto heroDummy = hero;
  1227. vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  1228. {
  1229. if(h == heroDummy.h)
  1230. return true;
  1231. else if(!ai->isAccessibleForHero(heroDummy->visitablePos(), h, true))
  1232. return true;
  1233. else if(!ai->canGetArmy(heroDummy.h, h))
  1234. return true;
  1235. else if(ai->getGoal(h)->goalType == Goals::GATHER_ARMY)
  1236. return true;
  1237. else
  1238. return false;
  1239. });
  1240. for(auto h : otherHeroes)
  1241. {
  1242. // Go to the other hero if we are faster
  1243. ret.push_back(sptr(Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  1244. // Let the other hero come to us
  1245. ret.push_back(sptr(Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  1246. }
  1247. std::vector<const CGObjectInstance *> objs;
  1248. for(auto obj : ai->visitableObjs)
  1249. {
  1250. if(obj->ID == Obj::CREATURE_GENERATOR1)
  1251. {
  1252. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  1253. //Use flagged dwellings only when there are available creatures that we can afford
  1254. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  1255. {
  1256. auto dwelling = dynamic_cast<const CGDwelling *>(obj);
  1257. for(auto & creLevel : dwelling->creatures)
  1258. {
  1259. if(creLevel.first)
  1260. {
  1261. for(auto & creatureID : creLevel.second)
  1262. {
  1263. auto creature = VLC->creh->creatures[creatureID];
  1264. if(ah->freeResources().canAfford(creature->cost))
  1265. objs.push_back(obj);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. for(auto h : cb->getHeroesInfo())
  1273. {
  1274. auto sm = ai->getCachedSectorMap(h);
  1275. for(auto obj : objs)
  1276. {
  1277. //find safe dwelling
  1278. auto pos = obj->visitablePos();
  1279. if(ai->isGoodForVisit(obj, h, *sm))
  1280. ret.push_back(sptr(Goals::VisitTile(pos).sethero(h)));
  1281. }
  1282. }
  1283. if(ai->canRecruitAnyHero() && ah->freeGold() > GameConstants::HERO_GOLD_COST) //this is not stupid in early phase of game
  1284. {
  1285. if(auto t = ai->findTownWithTavern())
  1286. {
  1287. for(auto h : cb->getAvailableHeroes(t)) //we assume that all towns have same set of heroes
  1288. {
  1289. if(h && h->getTotalStrength() > 500) //do not buy heroes with single creatures for GatherArmy
  1290. {
  1291. ret.push_back(sptr(Goals::RecruitHero()));
  1292. break;
  1293. }
  1294. }
  1295. }
  1296. }
  1297. if(ret.empty())
  1298. {
  1299. if(hero == ai->primaryHero() || value >= 1.1f) // FIXME: check PR388
  1300. ret.push_back(sptr(Goals::Explore()));
  1301. else //workaround to break loop - seemingly there are no ways to explore left
  1302. throw goalFulfilledException(sptr(Goals::GatherArmy(0).sethero(hero)));
  1303. }
  1304. return ret;
  1305. }
  1306. //TSubgoal AbstractGoal::whatToDoToAchieve()
  1307. //{
  1308. // logAi->debug("Decomposing goal of type %s",name());
  1309. // return sptr (Goals::Explore());
  1310. //}
  1311. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance * obj)
  1312. {
  1313. if(obj)
  1314. return sptr(Goals::GetObj(obj->id.getNum()));
  1315. else
  1316. return sptr(Goals::Explore());
  1317. }
  1318. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  1319. {
  1320. return sptr(Goals::Invalid());
  1321. }
  1322. bool AbstractGoal::invalid() const
  1323. {
  1324. return goalType == INVALID;
  1325. }
  1326. void AbstractGoal::accept(VCAI * ai)
  1327. {
  1328. ai->tryRealize(*this);
  1329. }
  1330. template<typename T>
  1331. void CGoal<T>::accept(VCAI * ai)
  1332. {
  1333. ai->tryRealize(static_cast<T &>(*this)); //casting enforces template instantiation
  1334. }
  1335. float AbstractGoal::accept(FuzzyHelper * f)
  1336. {
  1337. return f->evaluate(*this);
  1338. }
  1339. template<typename T>
  1340. float CGoal<T>::accept(FuzzyHelper * f)
  1341. {
  1342. return f->evaluate(static_cast<T &>(*this)); //casting enforces template instantiation
  1343. }