Goals.cpp 33 KB

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