Goals.cpp 35 KB

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