Goals.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. #include "StdInc.h"
  2. #include "Goals.h"
  3. #include "VCAI.h"
  4. #include "Fuzzy.h"
  5. /*
  6. * Goals.cpp, part of VCMI engine
  7. *
  8. * Authors: listed in file AUTHORS in main folder
  9. *
  10. * License: GNU General Public License v2.0 or later
  11. * Full text of license available in license.txt file, in main folder
  12. *
  13. */
  14. extern boost::thread_specific_ptr<CCallback> cb;
  15. extern boost::thread_specific_ptr<VCAI> ai;
  16. extern FuzzyHelper * fh; //TODO: this logic should be moved inside VCAI
  17. using namespace vstd;
  18. using namespace Goals;
  19. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  20. {
  21. shared_ptr<AbstractGoal> ptr;
  22. ptr.reset(tmp.clone());
  23. return ptr;
  24. }
  25. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  26. {
  27. std::string desc;
  28. switch (goalType)
  29. {
  30. case INVALID:
  31. return "INVALID";
  32. case WIN:
  33. return "WIN";
  34. case DO_NOT_LOSE:
  35. return "DO NOT LOOSE";
  36. case CONQUER:
  37. return "CONQUER";
  38. case BUILD:
  39. return "BUILD";
  40. case EXPLORE:
  41. desc = "EXPLORE";
  42. break;
  43. case GATHER_ARMY:
  44. desc = "GATHER ARMY";
  45. break;
  46. case BOOST_HERO:
  47. desc = "BOOST_HERO (unsupported)";
  48. break;
  49. case RECRUIT_HERO:
  50. return "RECRUIT HERO";
  51. case BUILD_STRUCTURE:
  52. return "BUILD STRUCTURE";
  53. case COLLECT_RES:
  54. desc = "COLLECT RESOURCE";
  55. break;
  56. case GATHER_TROOPS:
  57. desc = "GATHER TROOPS";
  58. break;
  59. case GET_OBJ:
  60. desc = "GET OBJ " + cb->getObjInstance(ObjectInstanceID(objid))->getHoverText();
  61. break;
  62. case FIND_OBJ:
  63. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  64. break;
  65. case VISIT_HERO:
  66. desc = "VISIT HERO " + cb->getObjInstance(ObjectInstanceID(objid))->getHoverText();
  67. break;
  68. case GET_ART_TYPE:
  69. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  70. break;
  71. case ISSUE_COMMAND:
  72. return "ISSUE COMMAND (unsupported)";
  73. case VISIT_TILE:
  74. desc = "VISIT TILE " + tile();
  75. break;
  76. case CLEAR_WAY_TO:
  77. desc = "CLEAR WAY TO " + tile();
  78. break;
  79. case DIG_AT_TILE:
  80. desc = "DIG AT TILE " + tile();
  81. break;
  82. default:
  83. return boost::lexical_cast<std::string>(goalType);
  84. }
  85. if (hero.h)
  86. desc += " (" + hero->name + ")";
  87. return desc;
  88. }
  89. //TODO: find out why the following are not generated automatically on MVS?
  90. namespace Goals
  91. {
  92. template <>
  93. void CGoal<Win>::accept (VCAI * ai)
  94. {
  95. ai->tryRealize(static_cast<Win&>(*this));
  96. }
  97. template <>
  98. void CGoal<Build>::accept (VCAI * ai)
  99. {
  100. ai->tryRealize(static_cast<Build&>(*this));
  101. }
  102. template <>
  103. float CGoal<Win>::accept (FuzzyHelper * f)
  104. {
  105. return f->evaluate(static_cast<Win&>(*this));
  106. }
  107. template <>
  108. float CGoal<Build>::accept (FuzzyHelper * f)
  109. {
  110. return f->evaluate(static_cast<Build&>(*this));
  111. }
  112. }
  113. //TSubgoal AbstractGoal::whatToDoToAchieve()
  114. //{
  115. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  116. // return sptr (Goals::Explore());
  117. //}
  118. TSubgoal Win::whatToDoToAchieve()
  119. {
  120. const VictoryCondition &vc = cb->getMapHeader()->victoryCondition;
  121. EVictoryConditionType::EVictoryConditionType cond = vc.condition;
  122. if(!vc.appliesToAI)
  123. {
  124. //TODO deduce victory from human loss condition
  125. cond = EVictoryConditionType::WINSTANDARD;
  126. }
  127. switch(cond)
  128. {
  129. case EVictoryConditionType::ARTIFACT:
  130. return sptr (Goals::GetArtOfType(vc.objectId));
  131. case EVictoryConditionType::BEATHERO:
  132. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  133. case EVictoryConditionType::BEATMONSTER:
  134. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  135. case EVictoryConditionType::BUILDCITY:
  136. //TODO build castle/capitol
  137. break;
  138. case EVictoryConditionType::BUILDGRAIL:
  139. {
  140. if(auto h = ai->getHeroWithGrail())
  141. {
  142. //hero is in a town that can host Grail
  143. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  144. {
  145. const CGTownInstance *t = h->visitedTown;
  146. return sptr (Goals::BuildThis(BuildingID::GRAIL, t));
  147. }
  148. else
  149. {
  150. auto towns = cb->getTownsInfo();
  151. towns.erase(boost::remove_if(towns,
  152. [](const CGTownInstance *t) -> bool
  153. {
  154. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  155. }),
  156. towns.end());
  157. boost::sort(towns, isCloser);
  158. if(towns.size())
  159. {
  160. return sptr (Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  161. }
  162. }
  163. }
  164. double ratio = 0;
  165. int3 grailPos = cb->getGrailPos(ratio);
  166. if(ratio > 0.99)
  167. {
  168. return sptr (Goals::DigAtTile(grailPos));
  169. } //TODO: use FIND_OBJ
  170. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  171. {
  172. return sptr (Goals::GetObj(obj->id.getNum()));
  173. }
  174. else
  175. return sptr (Goals::Explore());
  176. }
  177. break;
  178. case EVictoryConditionType::CAPTURECITY:
  179. return sptr (Goals::GetObj(vc.obj->id.getNum()));
  180. case EVictoryConditionType::GATHERRESOURCE:
  181. return sptr (Goals::CollectRes(static_cast<Res::ERes>(vc.objectId), vc.count));
  182. //TODO mines? piles? marketplace?
  183. //save?
  184. break;
  185. case EVictoryConditionType::GATHERTROOP:
  186. return sptr (Goals::GatherTroops(vc.objectId, vc.count));
  187. break;
  188. case EVictoryConditionType::TAKEDWELLINGS:
  189. break;
  190. case EVictoryConditionType::TAKEMINES:
  191. break;
  192. case EVictoryConditionType::TRANSPORTITEM:
  193. break;
  194. case EVictoryConditionType::WINSTANDARD:
  195. return sptr (Goals::Conquer());
  196. default:
  197. assert(0);
  198. }
  199. return sptr (Goals::Invalid());
  200. }
  201. TSubgoal FindObj::whatToDoToAchieve()
  202. {
  203. const CGObjectInstance * o = nullptr;
  204. if (resID > -1) //specified
  205. {
  206. for(const CGObjectInstance *obj : ai->visitableObjs)
  207. {
  208. if(obj->ID == objid && obj->subID == resID)
  209. {
  210. o = obj;
  211. break; //TODO: consider multiple objects and choose best
  212. }
  213. }
  214. }
  215. else
  216. {
  217. for(const CGObjectInstance *obj : ai->visitableObjs)
  218. {
  219. if(obj->ID == objid)
  220. {
  221. o = obj;
  222. break; //TODO: consider multiple objects and choose best
  223. }
  224. }
  225. }
  226. if (o && isReachable(o)) //we don't use isAccessibleForHero as we don't know which hero it is
  227. return sptr (Goals::GetObj(o->id.getNum()));
  228. else
  229. return sptr (Goals::Explore());
  230. }
  231. float FindObj::importanceWhenLocked() const
  232. {
  233. return 1; //we will probably fins it anyway, someday
  234. }
  235. std::string GetObj::completeMessage() const
  236. {
  237. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  238. }
  239. TSubgoal GetObj::whatToDoToAchieve()
  240. {
  241. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  242. if(!obj)
  243. return sptr (Goals::Explore());
  244. int3 pos = obj->visitablePos();
  245. return sptr (Goals::VisitTile(pos).sethero(hero)); //we must visit object with same hero, if any
  246. }
  247. float GetObj::importanceWhenLocked() const
  248. {
  249. return 3;
  250. }
  251. bool GetObj::fulfillsMe (shared_ptr<VisitTile> goal)
  252. {
  253. if (cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  254. return true;
  255. else
  256. return false;
  257. }
  258. std::string VisitHero::completeMessage() const
  259. {
  260. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  261. }
  262. TSubgoal VisitHero::whatToDoToAchieve()
  263. {
  264. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  265. if(!obj)
  266. return sptr (Goals::Explore());
  267. int3 pos = obj->visitablePos();
  268. if (hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  269. {
  270. if (hero->pos == pos)
  271. logAi->errorStream() << "Hero " << hero.name << " tries to visit himself.";
  272. else
  273. {
  274. settile(pos).setisElementar(true);
  275. return sptr (*this);
  276. }
  277. }
  278. return sptr (Goals::Invalid());
  279. }
  280. float VisitHero::importanceWhenLocked() const
  281. {
  282. return 4;
  283. }
  284. bool VisitHero::fulfillsMe (shared_ptr<VisitTile> goal)
  285. {
  286. if (cb->getObj(ObjectInstanceID(objid))->visitablePos() == goal->tile)
  287. return true;
  288. else
  289. return false;
  290. }
  291. TSubgoal GetArtOfType::whatToDoToAchieve()
  292. {
  293. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  294. if(alternativeWay->invalid())
  295. return sptr (Goals::FindObj(Obj::ARTIFACT, aid));
  296. return sptr (Goals::Invalid());
  297. }
  298. float GetArtOfType::importanceWhenLocked() const
  299. {
  300. return 2;
  301. }
  302. TSubgoal ClearWayTo::whatToDoToAchieve()
  303. {
  304. assert(cb->isInTheMap(tile)); //set tile
  305. if(!cb->isVisible(tile))
  306. {
  307. logAi->errorStream() << "Clear way should be used with visible tiles!";
  308. return sptr (Goals::Explore());
  309. }
  310. return (fh->chooseSolution(getAllPossibleSubgoals()));
  311. }
  312. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  313. {
  314. TGoalVec ret;
  315. for (auto h : cb->getHeroesInfo())
  316. {
  317. cb->setSelection(h);
  318. SectorMap sm;
  319. int3 tileToHit = sm.firstTileToGet(hero ? hero : h, tile);
  320. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  321. if (isBlockedBorderGate(tileToHit))
  322. { //FIXME: this way we'll not visit gate and activate quest :?
  323. ret.push_back (sptr (Goals::FindObj (Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  324. }
  325. ////FIXME: this code shouldn't be necessary
  326. //if(tileToHit == tile)
  327. //{
  328. // logAi->errorStream() << boost::format("Very strange, tile to hit is %s and tile is also %s, while hero %s is at %s\n")
  329. // % tileToHit % tile % h->name % h->visitablePos();
  330. // throw cannotFulfillGoalException("Retrieving first tile to hit failed (probably)!");
  331. //}
  332. auto topObj = backOrNull(cb->getVisitableObjs(tileToHit));
  333. if(topObj && topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  334. {
  335. logAi->errorStream() << boost::format("%s stands in the way of %s.\n") % topObj->getHoverText() % h->getHoverText();
  336. }
  337. else
  338. ret.push_back (sptr (Goals::VisitTile(tileToHit).sethero(h)));
  339. }
  340. if (ai->canRecruitAnyHero())
  341. ret.push_back (sptr (Goals::RecruitHero()));
  342. if (ret.empty())
  343. throw cannotFulfillGoalException("There is no known way to clear the way to tile " + tile());
  344. return ret;
  345. }
  346. float ClearWayTo::importanceWhenLocked() const
  347. {
  348. return 5;
  349. }
  350. std::string Explore::completeMessage() const
  351. {
  352. return "Hero " + hero.get()->name + " completed exploration";
  353. };
  354. TSubgoal Explore::whatToDoToAchieve()
  355. {
  356. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  357. if (hero) //use best step for this hero
  358. return ret;
  359. else
  360. {
  361. if (ret->hero.get(true))
  362. return sptr (sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  363. else
  364. return ret; //other solutions, like buying hero from tavern
  365. }
  366. };
  367. TGoalVec Explore::getAllPossibleSubgoals()
  368. {
  369. TGoalVec ret;
  370. std::vector<const CGHeroInstance *> heroes;
  371. //std::vector<HeroPtr> heroes;
  372. if (hero)
  373. //heroes.push_back(hero);
  374. heroes.push_back(hero.h);
  375. else
  376. {
  377. //heroes = ai->getUnblockedHeroes();
  378. heroes = cb->getHeroesInfo();
  379. erase_if (heroes, [](const HeroPtr h)
  380. {
  381. return !h->movement; //saves time, immobile heroes are useless anyway
  382. });
  383. }
  384. //try to use buildings that uncover map
  385. std::vector<const CGObjectInstance *> objs;
  386. for (auto obj : ai->visitableObjs)
  387. {
  388. if (!vstd::contains(ai->alreadyVisited, obj))
  389. {
  390. switch (obj->ID.num)
  391. {
  392. case Obj::REDWOOD_OBSERVATORY:
  393. case Obj::PILLAR_OF_FIRE:
  394. case Obj::CARTOGRAPHER:
  395. case Obj::SUBTERRANEAN_GATE: //TODO: check ai->knownSubterraneanGates
  396. objs.push_back (obj);
  397. }
  398. }
  399. }
  400. for (auto h : heroes)
  401. {
  402. for (auto obj : objs) //double loop, performance risk?
  403. {
  404. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  405. {
  406. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  407. }
  408. }
  409. int3 t = whereToExplore(h);
  410. if (cb->isInTheMap(t)) //valid tile was found - could be invalid (none)
  411. ret.push_back (sptr (Goals::VisitTile(t).sethero(h)));
  412. }
  413. //we either don't have hero yet or none of heroes can explore
  414. if ((!hero || ret.empty()) && ai->canRecruitAnyHero())
  415. ret.push_back (sptr(Goals::RecruitHero()));
  416. if (ret.empty())
  417. {
  418. auto h = ai->primaryHero(); //we may need to gather big army to break!
  419. if (h.h)
  420. {
  421. int3 t = ai->explorationNewPoint(h->getSightRadious(), h, true);
  422. if (cb->isInTheMap(t))
  423. ret.push_back (sptr(ClearWayTo(t).setisAbstract(true).sethero(ai->primaryHero())));
  424. }
  425. }
  426. if (ret.empty())
  427. throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  428. return ret;
  429. };
  430. float Explore::importanceWhenLocked() const
  431. {
  432. return 1; //exploration is natural and lowpriority process
  433. }
  434. TSubgoal RecruitHero::whatToDoToAchieve()
  435. {
  436. const CGTownInstance *t = ai->findTownWithTavern();
  437. if(!t)
  438. return sptr (Goals::BuildThis(BuildingID::TAVERN));
  439. if(cb->getResourceAmount(Res::GOLD) < HERO_GOLD_COST)
  440. return sptr (Goals::CollectRes(Res::GOLD, HERO_GOLD_COST));
  441. return iAmElementar();
  442. }
  443. std::string VisitTile::completeMessage() const
  444. {
  445. return "Hero " + hero.get()->name + " visited tile " + tile();
  446. }
  447. TSubgoal VisitTile::whatToDoToAchieve()
  448. {
  449. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  450. if (ret->hero)
  451. {
  452. if (isSafeToVisit(ret->hero, tile))
  453. {
  454. ret->setisElementar(true);
  455. return ret;
  456. }
  457. else
  458. {
  459. return sptr (Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  460. .sethero(ret->hero).setisAbstract(true));
  461. }
  462. }
  463. return ret;
  464. }
  465. float VisitTile::importanceWhenLocked() const
  466. {
  467. return 5; //depends on a distance, but we should really reach the tile once it was selected
  468. }
  469. TGoalVec VisitTile::getAllPossibleSubgoals()
  470. {
  471. TGoalVec ret;
  472. if (!cb->isVisible(tile))
  473. ret.push_back (sptr(Goals::Explore())); //what sense does it make?
  474. else
  475. {
  476. std::vector<const CGHeroInstance *> heroes;
  477. if (hero)
  478. heroes.push_back(hero.h); //use assigned hero if any
  479. else
  480. heroes = cb->getHeroesInfo(); //use most convenient hero
  481. for (auto h : heroes)
  482. {
  483. if (ai->isAccessibleForHero(tile, h))
  484. ret.push_back (sptr(Goals::VisitTile(tile).sethero(h)));
  485. }
  486. if (ai->canRecruitAnyHero())
  487. ret.push_back (sptr(Goals::RecruitHero()));
  488. }
  489. if (ret.empty())
  490. ret.push_back (sptr(Goals::ClearWayTo(tile)));
  491. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  492. return ret;
  493. }
  494. TSubgoal DigAtTile::whatToDoToAchieve()
  495. {
  496. const CGObjectInstance *firstObj = frontOrNull(cb->getVisitableObjs(tile));
  497. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  498. {
  499. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(firstObj);
  500. sethero(h).setisElementar(true);
  501. return sptr (*this);
  502. }
  503. return sptr (Goals::VisitTile(tile));
  504. }
  505. float DigAtTile::importanceWhenLocked() const
  506. {
  507. return 20; //do not! interrupt tile digging
  508. }
  509. TSubgoal BuildThis::whatToDoToAchieve()
  510. {
  511. //TODO check res
  512. //look for town
  513. //prerequisites?
  514. return iAmElementar();
  515. }
  516. float BuildThis::importanceWhenLocked() const
  517. {
  518. return 5;
  519. }
  520. TSubgoal CollectRes::whatToDoToAchieve()
  521. {
  522. std::vector<const IMarket*> markets;
  523. std::vector<const CGObjectInstance*> visObjs;
  524. ai->retreiveVisitableObjs(visObjs, true);
  525. for(const CGObjectInstance *obj : visObjs)
  526. {
  527. if(const IMarket *m = IMarket::castFrom(obj, false))
  528. {
  529. if(obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  530. markets.push_back(m);
  531. else if(obj->ID == Obj::TRADING_POST) //TODO a moze po prostu test na pozwalanie handlu?
  532. markets.push_back(m);
  533. }
  534. }
  535. boost::sort(markets, [](const IMarket *m1, const IMarket *m2) -> bool
  536. {
  537. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  538. });
  539. markets.erase(boost::remove_if(markets, [](const IMarket *market) -> bool
  540. {
  541. return !(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID)
  542. && !ai->isAccessible(market->o->visitablePos());
  543. }),markets.end());
  544. if(!markets.size())
  545. {
  546. for(const CGTownInstance *t : cb->getTownsInfo())
  547. {
  548. if(cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  549. return sptr (Goals::BuildThis(BuildingID::MARKETPLACE, t));
  550. }
  551. }
  552. else
  553. {
  554. const IMarket *m = markets.back();
  555. //attempt trade at back (best prices)
  556. int howManyCanWeBuy = 0;
  557. for(Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  558. {
  559. if(i == resID) continue;
  560. int toGive = -1, toReceive = -1;
  561. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  562. assert(toGive > 0 && toReceive > 0);
  563. howManyCanWeBuy += toReceive * (cb->getResourceAmount(i) / toGive);
  564. }
  565. if(howManyCanWeBuy + cb->getResourceAmount(static_cast<Res::ERes>(resID)) >= value)
  566. {
  567. auto backObj = backOrNull(cb->getVisitableObjs(m->o->visitablePos())); //it'll be a hero if we have one there; otherwise marketplace
  568. assert(backObj);
  569. if (backObj->tempOwner != ai->playerID)
  570. {
  571. return sptr (Goals::GetObj(m->o->id.getNum()));
  572. }
  573. else
  574. {
  575. return sptr (Goals::GetObj(m->o->id.getNum()).setisElementar(true));
  576. }
  577. }
  578. }
  579. return sptr (Goals::Invalid()); //FIXME: unused?
  580. }
  581. float CollectRes::importanceWhenLocked() const
  582. {
  583. return 2;
  584. }
  585. TSubgoal GatherTroops::whatToDoToAchieve()
  586. {
  587. std::vector<const CGDwelling *> dwellings;
  588. for(const CGTownInstance *t : cb->getTownsInfo())
  589. {
  590. auto creature = VLC->creh->creatures[objid];
  591. if (t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  592. {
  593. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  594. if(!creatures)
  595. continue;
  596. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  597. if(upgradeNumber < 0)
  598. continue;
  599. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  600. if (t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  601. {
  602. dwellings.push_back(t);
  603. }
  604. else
  605. {
  606. return sptr (Goals::BuildThis(bid, t));
  607. }
  608. }
  609. }
  610. for (auto obj : ai->visitableObjs)
  611. {
  612. if (obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  613. continue;
  614. auto d = dynamic_cast<const CGDwelling *>(obj);
  615. for (auto creature : d->creatures)
  616. {
  617. if (creature.first) //there are more than 0 creatures avaliabe
  618. {
  619. for (auto type : creature.second)
  620. {
  621. if (type == objid && ai->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  622. dwellings.push_back(d);
  623. }
  624. }
  625. }
  626. }
  627. if (dwellings.size())
  628. {
  629. boost::sort(dwellings, isCloser);
  630. return sptr (Goals::GetObj(dwellings.front()->id.getNum()));
  631. }
  632. else
  633. return sptr (Goals::Explore());
  634. //TODO: exchange troops between heroes
  635. }
  636. float GatherTroops::importanceWhenLocked() const
  637. {
  638. return 2;
  639. }
  640. TSubgoal Conquer::whatToDoToAchieve()
  641. {
  642. return fh->chooseSolution (getAllPossibleSubgoals());
  643. }
  644. TGoalVec Conquer::getAllPossibleSubgoals()
  645. {
  646. TGoalVec ret;
  647. std::vector<const CGObjectInstance *> objs; //here we'll gather enemy towns and heroes
  648. ai->retreiveVisitableObjs(objs);
  649. erase_if(objs, [&](const CGObjectInstance *obj)
  650. {
  651. return (obj->ID != Obj::TOWN && obj->ID != Obj::HERO && //not town/hero
  652. obj->ID != Obj::CREATURE_GENERATOR1 && obj->ID != Obj::MINE) //not dwelling or mine
  653. || cb->getPlayerRelations(ai->playerID, obj->tempOwner) != PlayerRelations::ENEMIES; //only enemy objects are interesting
  654. });
  655. erase_if(objs, [&](const CGObjectInstance *obj)
  656. {
  657. return vstd::contains (ai->reservedObjs, obj);
  658. //no need to capture same object twice
  659. });
  660. for (auto h : cb->getHeroesInfo())
  661. {
  662. for (auto obj : objs) //double loop, performance risk?
  663. {
  664. if (ai->isAccessibleForHero(obj->visitablePos(), h) && isSafeToVisit(h, obj->visitablePos()))
  665. {
  666. if (obj->ID == Obj::HERO)
  667. ret.push_back (sptr (Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  668. //track enemy hero
  669. else
  670. ret.push_back (sptr (Goals::VisitTile(obj->visitablePos()).sethero(h)));
  671. }
  672. }
  673. }
  674. if (!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  675. ret.push_back (sptr(Goals::RecruitHero()));
  676. if (ret.empty())
  677. ret.push_back (sptr(Goals::Explore())); //we need to find an enemy
  678. return ret;
  679. }
  680. float Conquer::importanceWhenLocked() const
  681. {
  682. return 10; //defeating opponent is hig priority, always
  683. }
  684. TSubgoal Build::whatToDoToAchieve()
  685. {
  686. return iAmElementar();
  687. }
  688. float Build::importanceWhenLocked() const
  689. {
  690. return 1;
  691. }
  692. TSubgoal Invalid::whatToDoToAchieve()
  693. {
  694. return iAmElementar();
  695. }
  696. std::string GatherArmy::completeMessage() const
  697. {
  698. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  699. };
  700. TSubgoal GatherArmy::whatToDoToAchieve()
  701. {
  702. //TODO: find hero if none set
  703. assert(hero.h);
  704. return fh->chooseSolution (getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  705. }
  706. TGoalVec GatherArmy::getAllPossibleSubgoals()
  707. {
  708. //get all possible towns, heroes and dwellings we may use
  709. TGoalVec ret;
  710. //TODO: include evaluation of monsters gather in calculation
  711. for (auto t : cb->getTownsInfo())
  712. {
  713. auto pos = t->visitablePos();
  714. if (ai->isAccessibleForHero(pos, hero))
  715. {
  716. if(!t->visitingHero && howManyReinforcementsCanGet(hero,t))
  717. {
  718. if (!vstd::contains (ai->townVisitsThisWeek[hero], t))
  719. ret.push_back (sptr (Goals::VisitTile(pos).sethero(hero)));
  720. }
  721. auto bid = ai->canBuildAnyStructure(t, std::vector<BuildingID>
  722. (unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  723. if (bid != BuildingID::NONE)
  724. ret.push_back (sptr(BuildThis(bid, t)));
  725. }
  726. }
  727. auto otherHeroes = cb->getHeroesInfo();
  728. auto heroDummy = hero;
  729. erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  730. {
  731. return (h == heroDummy.h || !ai->isAccessibleForHero(heroDummy->visitablePos(), h, true) || !ai->canGetArmy(heroDummy.h, h));
  732. });
  733. for (auto h : otherHeroes)
  734. {
  735. ret.push_back (sptr (Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  736. //go to the other hero if we are faster
  737. ret.push_back (sptr (Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  738. //let the other hero come to us
  739. }
  740. std::vector <const CGObjectInstance *> objs;
  741. for (auto obj : ai->visitableObjs)
  742. {
  743. if(obj->ID == Obj::CREATURE_GENERATOR1)
  744. {
  745. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  746. //Use flagged dwellings only when there are available creatures that we can afford
  747. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  748. {
  749. auto dwelling = dynamic_cast<const CGDwelling*>(obj);
  750. for(auto & creLevel : dwelling->creatures)
  751. {
  752. if(creLevel.first)
  753. {
  754. for(auto & creatureID : creLevel.second)
  755. {
  756. auto creature = VLC->creh->creatures[creatureID];
  757. if (ai->freeResources().canAfford(creature->cost))
  758. objs.push_back(obj);
  759. }
  760. }
  761. }
  762. }
  763. }
  764. }
  765. for(auto h : cb->getHeroesInfo())
  766. {
  767. for (auto obj : objs)
  768. { //find safe dwelling
  769. auto pos = obj->visitablePos();
  770. if (shouldVisit (h, obj) && isSafeToVisit(h, pos) && ai->isAccessibleForHero(pos, h))
  771. ret.push_back (sptr (Goals::VisitTile(pos).sethero(h)));
  772. }
  773. }
  774. if (ret.empty())
  775. ret.push_back (sptr(Goals::Explore()));
  776. return ret;
  777. }
  778. float GatherArmy::importanceWhenLocked() const
  779. {
  780. return 2.5;
  781. }
  782. //TSubgoal AbstractGoal::whatToDoToAchieve()
  783. //{
  784. // logAi->debugStream() << boost::format("Decomposing goal of type %s") % name();
  785. // return sptr (Goals::Explore());
  786. //}
  787. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance *obj)
  788. {
  789. if(obj)
  790. return sptr (Goals::GetObj(obj->id.getNum()));
  791. else
  792. return sptr (Goals::Explore());
  793. }
  794. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  795. {
  796. return sptr (Goals::Invalid());
  797. }
  798. bool AbstractGoal::invalid() const
  799. {
  800. return goalType == INVALID;
  801. }
  802. void AbstractGoal::accept (VCAI * ai)
  803. {
  804. ai->tryRealize(*this);
  805. }
  806. template<typename T>
  807. void CGoal<T>::accept (VCAI * ai)
  808. {
  809. ai->tryRealize(static_cast<T&>(*this)); //casting enforces template instantiation
  810. }
  811. float AbstractGoal::accept (FuzzyHelper * f)
  812. {
  813. return f->evaluate(*this);
  814. }
  815. template<typename T>
  816. float CGoal<T>::accept (FuzzyHelper * f)
  817. {
  818. return f->evaluate(static_cast<T&>(*this)); //casting enforces template instantiation
  819. }