Goals.cpp 33 KB

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