Goals.cpp 35 KB

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