Goals.cpp 44 KB

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