Goals.cpp 43 KB

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