Goals.cpp 33 KB

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