Goals.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. /*
  7. * Goals.cpp, part of VCMI engine
  8. *
  9. * Authors: listed in file AUTHORS in main folder
  10. *
  11. * License: GNU General Public License v2.0 or later
  12. * Full text of license available in license.txt file, in main folder
  13. *
  14. */
  15. extern boost::thread_specific_ptr<CCallback> cb;
  16. extern boost::thread_specific_ptr<VCAI> ai;
  17. extern FuzzyHelper * fh; //TODO: this logic should be moved inside VCAI
  18. using namespace vstd;
  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. SectorMap sm(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. }
  473. }
  474. }
  475. if (isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there i no quest object
  476. {
  477. ret.push_back (sptr (Goals::VisitTile(tileToHit).sethero(h)));
  478. }
  479. else
  480. {
  481. ret.push_back (sptr (Goals::GatherArmy(evaluateDanger(tileToHit, h)*SAFE_ATTACK_CONSTANT).
  482. sethero(h).setisAbstract(true)));
  483. }
  484. }
  485. if (ai->canRecruitAnyHero())
  486. ret.push_back (sptr (Goals::RecruitHero()));
  487. if (ret.empty())
  488. {
  489. logAi->warnStream() << "There is no known way to clear the way to tile " + tile();
  490. throw goalFulfilledException (sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  491. }
  492. return ret;
  493. }
  494. std::string Explore::completeMessage() const
  495. {
  496. return "Hero " + hero.get()->name + " completed exploration";
  497. }
  498. TSubgoal Explore::whatToDoToAchieve()
  499. {
  500. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  501. if (hero) //use best step for this hero
  502. return ret;
  503. else
  504. {
  505. if (ret->hero.get(true))
  506. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  507. else
  508. return ret; //other solutions, like buying hero from tavern
  509. }
  510. }
  511. TGoalVec Explore::getAllPossibleSubgoals()
  512. {
  513. TGoalVec ret;
  514. std::vector<const CGHeroInstance *> heroes;
  515. if (hero)
  516. heroes.push_back(hero.h);
  517. else
  518. {
  519. //heroes = ai->getUnblockedHeroes();
  520. heroes = cb->getHeroesInfo();
  521. erase_if (heroes, [](const HeroPtr h)
  522. {
  523. if (ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  524. return true;
  525. if (!ai->isAbleToExplore(h))
  526. return true;
  527. return !h->movement; //saves time, immobile heroes are useless anyway
  528. });
  529. }
  530. //try to use buildings that uncover map
  531. std::vector<const CGObjectInstance *> objs;
  532. for (auto obj : ai->visitableObjs)
  533. {
  534. if (!vstd::contains(ai->alreadyVisited, obj))
  535. {
  536. switch (obj->ID.num)
  537. {
  538. case Obj::REDWOOD_OBSERVATORY:
  539. case Obj::PILLAR_OF_FIRE:
  540. case Obj::CARTOGRAPHER:
  541. objs.push_back (obj);
  542. break;
  543. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  544. case Obj::MONOLITH_TWO_WAY:
  545. case Obj::SUBTERRANEAN_GATE:
  546. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  547. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  548. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  549. objs.push_back (obj);
  550. break;
  551. }
  552. }
  553. else
  554. {
  555. switch (obj->ID.num)
  556. {
  557. case Obj::MONOLITH_TWO_WAY:
  558. case Obj::SUBTERRANEAN_GATE:
  559. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  560. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  561. break;
  562. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  563. {
  564. if(!cb->getObj(exit))
  565. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  566. objs.push_back(obj);
  567. break;
  568. }
  569. }
  570. break;
  571. }
  572. }
  573. }
  574. for (auto h : heroes)
  575. {
  576. SectorMap sm(h);
  577. for (auto obj : objs) //double loop, performance risk?
  578. {
  579. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  580. if (ai->isTileNotReserved(h, t))
  581. ret.push_back (sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  582. }
  583. int3 t = whereToExplore(h);
  584. if (t.valid())
  585. {
  586. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  587. }
  588. else
  589. {
  590. ai->markHeroUnableToExplore (h); //there is no freely accessible tile, do not poll this hero anymore
  591. //possible issues when gathering army to break
  592. if (hero.h == h || (!hero && h == ai->primaryHero().h)) //check this only ONCE, high cost
  593. {
  594. t = ai->explorationDesperate(h);
  595. if (t.valid()) //don't waste time if we are completely blocked
  596. ret.push_back (sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  597. }
  598. }
  599. }
  600. //we either don't have hero yet or none of heroes can explore
  601. if ((!hero || ret.empty()) && ai->canRecruitAnyHero())
  602. ret.push_back (sptr(Goals::RecruitHero()));
  603. if (ret.empty())
  604. {
  605. throw goalFulfilledException (sptr(Goals::Explore().sethero(hero)));
  606. }
  607. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  608. return ret;
  609. }
  610. bool Explore::fulfillsMe (TSubgoal goal)
  611. {
  612. if (goal->goalType == Goals::EXPLORE)
  613. {
  614. if (goal->hero)
  615. return hero == goal->hero;
  616. else
  617. return true; //cancel ALL exploration
  618. }
  619. return false;
  620. }
  621. TSubgoal RecruitHero::whatToDoToAchieve()
  622. {
  623. const CGTownInstance *t = ai->findTownWithTavern();
  624. if(!t)
  625. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  626. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  627. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  628. return iAmElementar();
  629. }
  630. std::string VisitTile::completeMessage() const
  631. {
  632. return "Hero " + hero.get()->name + " visited tile " + tile();
  633. }
  634. TSubgoal VisitTile::whatToDoToAchieve()
  635. {
  636. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  637. if (ret->hero)
  638. {
  639. if (isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  640. {
  641. ret->setisElementar(true);
  642. return ret;
  643. }
  644. else
  645. {
  646. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  647. .sethero(ret->hero).setisAbstract(true));
  648. }
  649. }
  650. return ret;
  651. }
  652. TGoalVec VisitTile::getAllPossibleSubgoals()
  653. {
  654. assert(cb->isInTheMap(tile));
  655. TGoalVec ret;
  656. if (!cb->isVisible(tile))
  657. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  658. else
  659. {
  660. std::vector<const CGHeroInstance *> heroes;
  661. if (hero)
  662. heroes.push_back(hero.h); //use assigned hero if any
  663. else
  664. heroes = cb->getHeroesInfo(); //use most convenient hero
  665. for (auto h : heroes)
  666. {
  667. if (ai->isAccessibleForHero(tile, h))
  668. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  669. }
  670. if (ai->canRecruitAnyHero())
  671. ret.push_back (sptr(Goals::RecruitHero()));
  672. }
  673. if (ret.empty())
  674. {
  675. auto obj = frontOrNull(cb->getVisitableObjs(tile));
  676. if (obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  677. {
  678. 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
  679. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  680. else
  681. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  682. }
  683. else
  684. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  685. }
  686. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  687. return ret;
  688. }
  689. TSubgoal DigAtTile::whatToDoToAchieve()
  690. {
  691. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  692. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  693. {
  694. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  695. sethero(h).setisElementar(true);
  696. return sptr (*this);
  697. }
  698. return sptr (Goals::VisitTile(tile));
  699. }
  700. TSubgoal BuildThis::whatToDoToAchieve()
  701. {
  702. //TODO check res
  703. //look for town
  704. //prerequisites?
  705. return iAmElementar();
  706. }
  707. TSubgoal CollectRes::whatToDoToAchieve()
  708. {
  709. std::vector<const IMarket*> markets;
  710. std::vector<const CGObjectInstance*> visObjs;
  711. ai->retreiveVisitableObjs(visObjs, true);
  712. for(const CGObjectInstance *obj : visObjs)
  713. {
  714. if(const IMarket *m = IMarket::castFrom(obj, false))
  715. {
  716. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  717. markets.push_back(m);
  718. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  719. markets.push_back(m);
  720. }
  721. }
  722. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  723. {
  724. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  725. });
  726. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  727. {
  728. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  729. && !ai->isAccessible(market->o->visitablePos());
  730. }),markets.end());
  731. if(!markets.size())
  732. {
  733. for(const CGTownInstance *t : cb->getTownsInfo())
  734. {
  735. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  736. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  737. }
  738. }
  739. else
  740. {
  741. const IMarket *m = markets.back();
  742. //attempt trade at back (best prices)
  743. int howManyCanWeBuy = 0;
  744. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  745. {
  746. if(i == resID) continue;
  747. int toGive = -1, toReceive = -1;
  748. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  749. assert(toGive > 0 && toReceive > 0);
  750. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  751. }
  752. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  753. {
  754. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  755. assert(backObj);
  756. if (backObj->tempOwner != ai->playerID)
  757. {
  758. return sptr (Goals::GetObj(m->o->id.getNum()));
  759. }
  760. else
  761. {
  762. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  763. }
  764. }
  765. }
  766. return sptr (setisElementar(true)); //all the conditions for trade are met
  767. }
  768. TSubgoal GatherTroops::whatToDoToAchieve()
  769. {
  770. std::vector<const CGDwelling *> dwellings;
  771. for(const CGTownInstance *t : cb->getTownsInfo())
  772. {
  773. auto creature = VLC->creh->creatures[objid];
  774. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  775. {
  776. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  777. if(!creatures)
  778. continue;
  779. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  780. if(upgradeNumber < 0)
  781. continue;
  782. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  783. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  784. {
  785. dwellings.push_back(t);
  786. }
  787. else
  788. {
  789. return sptr (Goals::BuildThis(bid, t));
  790. }
  791. }
  792. }
  793. for (auto obj : ai->visitableObjs)
  794. {
  795. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  796. continue;
  797. auto d = dynamic_cast<const CGDwelling *>(obj);
  798. for (auto creature : d->creatures)
  799. {
  800. if (creature.first) //there are more than 0 creatures avaliabe
  801. {
  802. for (auto type : creature.second)
  803. {
  804. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  805. dwellings.push_back(d);
  806. }
  807. }
  808. }
  809. }
  810. if (dwellings.size())
  811. {
  812. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  813. // sorted helper
  814. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  815. {
  816. const CGPathNode *ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos()),
  817. *rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  818. if(ln->turns != rn->turns)
  819. return ln->turns < rn->turns;
  820. return (ln->moveRemains > rn->moveRemains);
  821. };
  822. // for all owned heroes generate map <hero -> nearest dwelling>
  823. TDwellMap nearestDwellings;
  824. for (const CGHeroInstance * hero : cb->getHeroesInfo(true))
  825. {
  826. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  827. }
  828. // find hero who is nearest to a dwelling
  829. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  830. return sptr (Goals::GetObj(nearest->id.getNum()));
  831. }
  832. else
  833. return sptr (Goals::Explore());
  834. //TODO: exchange troops between heroes
  835. }
  836. TSubgoal Conquer::whatToDoToAchieve()
  837. {
  838. return fh->chooseSolution (getAllPossibleSubgoals());
  839. }
  840. TGoalVec Conquer::getAllPossibleSubgoals()
  841. {
  842. TGoalVec ret;
  843. auto conquerable = [](const CGObjectInstance * obj) -> bool
  844. {
  845. if (cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  846. {
  847. switch (obj->ID.num)
  848. {
  849. case Obj::TOWN:
  850. case Obj::HERO:
  851. case Obj::CREATURE_GENERATOR1:
  852. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  853. return true;
  854. }
  855. }
  856. return false;
  857. };
  858. std::vector<const CGObjectInstance *> objs;
  859. for (auto obj : ai->visitableObjs)
  860. {
  861. if (conquerable(obj))
  862. objs.push_back (obj);
  863. }
  864. for (auto h : cb->getHeroesInfo())
  865. {
  866. SectorMap sm(h);
  867. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  868. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  869. {
  870. if (conquerable(obj))
  871. ourObjs.push_back(obj);
  872. }
  873. for (auto obj : ourObjs) //double loop, performance risk?
  874. {
  875. auto t = sm.firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  876. if (ai->isTileNotReserved(h, t))
  877. ret.push_back (sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  878. }
  879. }
  880. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  881. ret.push_back (sptr(Goals::RecruitHero()));
  882. if (ret.empty())
  883. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  884. return ret;
  885. }
  886. TSubgoal Build::whatToDoToAchieve()
  887. {
  888. return iAmElementar();
  889. }
  890. TSubgoal Invalid::whatToDoToAchieve()
  891. {
  892. return iAmElementar();
  893. }
  894. std::string GatherArmy::completeMessage() const
  895. {
  896. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  897. }
  898. TSubgoal GatherArmy::whatToDoToAchieve()
  899. {
  900. //TODO: find hero if none set
  901. assert(hero.h);
  902. return fh->chooseSolution (getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  903. }
  904. TGoalVec GatherArmy::getAllPossibleSubgoals()
  905. {
  906. //get all possible towns, heroes and dwellings we may use
  907. TGoalVec ret;
  908. //TODO: include evaluation of monsters gather in calculation
  909. for (auto t : cb->getTownsInfo())
  910. {
  911. auto pos = t->visitablePos();
  912. if (ai->isAccessibleForHero(pos, hero))
  913. {
  914. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  915. {
  916. if (!vstd::contains (ai->townVisitsThisWeek[hero], t))
  917. ret.push_back (sptr (Goals::VisitTile(pos).sethero(hero)));
  918. }
  919. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>
  920. (unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  921. if (bid != BuildingID::NONE)
  922. ret.push_back (sptr(BuildThis(bid, t)));
  923. }
  924. }
  925. auto otherHeroes = cb->getHeroesInfo();
  926. auto heroDummy = hero;
  927. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  928. {
  929. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true)
  930. || !ai->canGetArmy(heroDummy.h, h) || ai->getGoal(h)->goalType == Goals::GATHER_ARMY);
  931. });
  932. for (auto h : otherHeroes)
  933. {
  934. ret.push_back (sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  935. //go to the other hero if we are faster
  936. ret.push_back (sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  937. //let the other hero come to us
  938. }
  939. std::vector <const CGObjectInstance *> objs;
  940. for (auto obj : ai->visitableObjs)
  941. {
  942. if(obj->ID == Obj::CREATURE_GENERATOR1)
  943. {
  944. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  945. //Use flagged dwellings only when there are available creatures that we can afford
  946. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  947. {
  948. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  949. for(auto & creLevel : dwelling->creatures)
  950. {
  951. if(creLevel.first)
  952. {
  953. for(auto & creatureID : creLevel.second)
  954. {
  955. auto creature = VLC->creh->creatures[creatureID];
  956. if (ai->freeResources().canAfford(creature->cost))
  957. objs.push_back(obj);
  958. }
  959. }
  960. }
  961. }
  962. }
  963. }
  964. for(auto h : cb->getHeroesInfo())
  965. {
  966. SectorMap sm(h);
  967. for (auto obj : objs)
  968. { //find safe dwelling
  969. auto pos = obj->visitablePos();
  970. if (ai->isGoodForVisit(obj, h, sm))
  971. ret.push_back (sptr (Goals::VisitTile(pos).sethero(h)));
  972. }
  973. }
  974. if (ai->canRecruitAnyHero()) //this is not stupid in early phase of game
  975. ret.push_back (sptr(Goals::RecruitHero()));
  976. if (ret.empty())
  977. {
  978. if (hero == ai->primaryHero() || value >= 1.1f)
  979. ret.push_back (sptr(Goals::Explore()));
  980. else //workaround to break loop - seemingly there are no ways to explore left
  981. throw goalFulfilledException (sptr(Goals::GatherArmy(0).sethero(hero)));
  982. }
  983. return ret;
  984. }
  985. //TSubgoal AbstractGoal::whatToDoToAchieve()
  986. //{
  987. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  988. // return sptr (Goals::Explore());
  989. //}
  990. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  991. {
  992. if(obj)
  993. return sptr (Goals::GetObj(obj->id.getNum()));
  994. else
  995. return sptr (Goals::Explore());
  996. }
  997. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  998. {
  999. return sptr (Goals::Invalid());
  1000. }
  1001. bool AbstractGoal::invalid() const
  1002. {
  1003. return goalType == INVALID;
  1004. }
  1005. void AbstractGoal::accept (VCAI * ai)
  1006. {
  1007. ai->tryRealize(*this);
  1008. }
  1009. template<typename T>
  1010. void CGoal<T>::accept (VCAI * ai)
  1011. {
  1012. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  1013. }
  1014. float AbstractGoal::accept (FuzzyHelper * f)
  1015. {
  1016. return f->evaluate(*this);
  1017. }
  1018. template<typename T>
  1019. float CGoal<T>::accept (FuzzyHelper * f)
  1020. {
  1021. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  1022. }