Goals.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  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 "ResourceManager.h"
  15. #include "BuildingManager.h"
  16. #include "../../lib/mapping/CMap.h" //for victory conditions
  17. #include "../../lib/CPathfinder.h"
  18. #include "../../lib/StringConstants.h"
  19. #include "AIhelper.h"
  20. extern boost::thread_specific_ptr<CCallback> cb;
  21. extern boost::thread_specific_ptr<VCAI> ai;
  22. extern boost::thread_specific_ptr<AIhelper> ah;
  23. extern FuzzyHelper * fh;
  24. using namespace Goals;
  25. TSubgoal Goals::sptr(const AbstractGoal & tmp)
  26. {
  27. TSubgoal ptr;
  28. ptr.reset(tmp.clone());
  29. return ptr;
  30. }
  31. std::string Goals::AbstractGoal::name() const //TODO: virtualize
  32. {
  33. std::string desc;
  34. switch(goalType)
  35. {
  36. case INVALID:
  37. return "INVALID";
  38. case WIN:
  39. return "WIN";
  40. case DO_NOT_LOSE:
  41. return "DO NOT LOOSE";
  42. case CONQUER:
  43. return "CONQUER";
  44. case BUILD:
  45. return "BUILD";
  46. case EXPLORE:
  47. desc = "EXPLORE";
  48. break;
  49. case GATHER_ARMY:
  50. desc = "GATHER ARMY";
  51. break;
  52. case BUY_ARMY:
  53. return "BUY ARMY";
  54. break;
  55. case BOOST_HERO:
  56. desc = "BOOST_HERO (unsupported)";
  57. break;
  58. case RECRUIT_HERO:
  59. return "RECRUIT HERO";
  60. case BUILD_STRUCTURE:
  61. return "BUILD STRUCTURE";
  62. case COLLECT_RES:
  63. desc = "COLLECT RESOURCE " + GameConstants::RESOURCE_NAMES[resID] + " (" + boost::lexical_cast<std::string>(value) + ")";
  64. break;
  65. case TRADE:
  66. {
  67. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  68. if (obj)
  69. desc = (boost::format("TRADE %d of %s at %s") % value % GameConstants::RESOURCE_NAMES[resID] % obj->getObjectName()).str();
  70. }
  71. break;
  72. case GATHER_TROOPS:
  73. desc = "GATHER TROOPS";
  74. break;
  75. case GET_OBJ:
  76. {
  77. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  78. if(obj)
  79. desc = "GET OBJ " + obj->getObjectName();
  80. }
  81. break;
  82. case FIND_OBJ:
  83. desc = "FIND OBJ " + boost::lexical_cast<std::string>(objid);
  84. break;
  85. case VISIT_HERO:
  86. {
  87. auto obj = cb->getObjInstance(ObjectInstanceID(objid));
  88. if(obj)
  89. desc = "VISIT HERO " + obj->getObjectName();
  90. }
  91. break;
  92. case GET_ART_TYPE:
  93. desc = "GET ARTIFACT OF TYPE " + VLC->arth->artifacts[aid]->Name();
  94. break;
  95. case ISSUE_COMMAND:
  96. return "ISSUE COMMAND (unsupported)";
  97. case VISIT_TILE:
  98. desc = "VISIT TILE " + tile.toString();
  99. break;
  100. case CLEAR_WAY_TO:
  101. desc = "CLEAR WAY TO " + tile.toString();
  102. break;
  103. case DIG_AT_TILE:
  104. desc = "DIG AT TILE " + tile.toString();
  105. break;
  106. default:
  107. return boost::lexical_cast<std::string>(goalType);
  108. }
  109. if(hero.get(true)) //FIXME: used to crash when we lost hero and failed goal
  110. desc += " (" + hero->name + ")";
  111. return desc;
  112. }
  113. bool Goals::AbstractGoal::operator==(AbstractGoal & g)
  114. {
  115. /*this operator checks if goals are EQUIVALENT, ie. if they represent same objective
  116. it does not not check isAbstract or isElementar, as this is up to VCAI decomposition logic
  117. */
  118. if(g.goalType != goalType)
  119. return false;
  120. switch(goalType)
  121. {
  122. //no parameters
  123. case INVALID:
  124. case WIN:
  125. case DO_NOT_LOSE:
  126. case RECRUIT_HERO: //overloaded
  127. return true;
  128. break;
  129. //assigned to hero, no parameters
  130. case CONQUER:
  131. case EXPLORE:
  132. case BOOST_HERO:
  133. return g.hero.h == hero.h; //how comes HeroPtrs are equal for different heroes?
  134. break;
  135. case GATHER_ARMY: //actual value is indifferent
  136. return (g.hero.h == hero.h || town == g.town); //TODO: gather army for town maybe?
  137. break;
  138. //assigned hero and tile
  139. case VISIT_TILE:
  140. case CLEAR_WAY_TO:
  141. case DIG_AT_TILE:
  142. return (g.hero.h == hero.h && g.tile == tile);
  143. break;
  144. //assigned hero and object
  145. case GET_OBJ:
  146. case FIND_OBJ: //TODO: use subtype?
  147. case VISIT_HERO:
  148. case GET_ART_TYPE:
  149. return (g.hero.h == hero.h && g.objid == objid);
  150. break;
  151. case BUILD_STRUCTURE:
  152. return (town == g.town && bid == g.bid); //build specific structure in specific town
  153. break;
  154. //no check atm
  155. case COLLECT_RES:
  156. case TRADE: //TODO
  157. return (resID == g.resID); //every hero may collect resources
  158. break;
  159. case BUILD: //abstract build is indentical, TODO: consider building anything in town
  160. return true;
  161. break;
  162. case GATHER_TROOPS:
  163. case ISSUE_COMMAND:
  164. default:
  165. return false;
  166. }
  167. }
  168. bool Goals::AbstractGoal::operator<(AbstractGoal & g) //for std::unique
  169. {
  170. //TODO: make sure it gets goals consistent with == operator
  171. if (goalType < g.goalType)
  172. return true;
  173. if (goalType > g.goalType)
  174. return false;
  175. if (hero < g.hero)
  176. return true;
  177. if (hero > g.hero)
  178. return false;
  179. if (tile < g.tile)
  180. return true;
  181. if (g.tile < tile)
  182. return false;
  183. if (objid < g.objid)
  184. return true;
  185. if (objid > g.objid)
  186. return false;
  187. if (town < g.town)
  188. return true;
  189. if (town > g.town)
  190. return false;
  191. if (value < g.value)
  192. return true;
  193. if (value > g.value)
  194. return false;
  195. if (priority < g.priority)
  196. return true;
  197. if (priority > g.priority)
  198. return false;
  199. if (resID < g.resID)
  200. return true;
  201. if (resID > g.resID)
  202. return false;
  203. if (bid < g.bid)
  204. return true;
  205. if (bid > g.bid)
  206. return false;
  207. if (aid < g.aid)
  208. return true;
  209. if (aid > g.aid)
  210. return false;
  211. return false;
  212. }
  213. //TODO: find out why the following are not generated automatically on MVS?
  214. namespace Goals
  215. {
  216. template<>
  217. void CGoal<Win>::accept(VCAI * ai)
  218. {
  219. ai->tryRealize(static_cast<Win &>(*this));
  220. }
  221. template<>
  222. void CGoal<Build>::accept(VCAI * ai)
  223. {
  224. ai->tryRealize(static_cast<Build &>(*this));
  225. }
  226. template<>
  227. float CGoal<Win>::accept(FuzzyHelper * f)
  228. {
  229. return f->evaluate(static_cast<Win &>(*this));
  230. }
  231. template<>
  232. float CGoal<Build>::accept(FuzzyHelper * f)
  233. {
  234. return f->evaluate(static_cast<Build &>(*this));
  235. }
  236. bool TSubgoal::operator==(const TSubgoal & rhs) const
  237. {
  238. return *get() == *rhs.get(); //comparison for Goals is overloaded, so they don't need to be identical to match
  239. }
  240. bool TSubgoal::operator<(const TSubgoal & rhs) const
  241. {
  242. return get() < rhs.get(); //compae by value
  243. }
  244. bool BuyArmy::operator==(AbstractGoal & g)
  245. {
  246. if (g.goalType != goalType)
  247. return false;
  248. //if (hero && hero != g.hero)
  249. // return false;
  250. return town == g.town;
  251. }
  252. bool BuyArmy::fulfillsMe(TSubgoal goal)
  253. {
  254. //if (hero && hero != goal->hero)
  255. // return false;
  256. return town == goal->town && goal->value >= value; //can always buy more army
  257. }
  258. TSubgoal BuyArmy::whatToDoToAchieve()
  259. {
  260. //TODO: calculate the actual cost of units instead
  261. TResources price;
  262. price[Res::GOLD] = value * 0.4f; //some approximate value
  263. return ah->whatToDo(price, iAmElementar()); //buy right now or gather resources
  264. }
  265. std::string BuyArmy::completeMessage() const
  266. {
  267. return boost::format("Bought army of value %d in town of %s") % value, town->name;
  268. }
  269. }
  270. TSubgoal Trade::whatToDoToAchieve()
  271. {
  272. return iAmElementar();
  273. }
  274. bool Trade::operator==(AbstractGoal & g)
  275. {
  276. if (g.goalType != goalType)
  277. return false;
  278. if (g.resID == resID)
  279. if (g.value == value) //TODO: not sure if that logic is consitent
  280. return true;
  281. return false;
  282. }
  283. //TSubgoal AbstractGoal::whatToDoToAchieve()
  284. //{
  285. // logAi->debug("Decomposing goal of type %s",name());
  286. // return sptr (Goals::Explore());
  287. //}
  288. TSubgoal Win::whatToDoToAchieve()
  289. {
  290. auto toBool = [=](const EventCondition &)
  291. {
  292. // TODO: proper implementation
  293. // Right now even already fulfilled goals will be included into generated list
  294. // Proper check should test if event condition is already fulfilled
  295. // Easiest way to do this is to call CGameState::checkForVictory but this function should not be
  296. // used on client side or in AI code
  297. return false;
  298. };
  299. std::vector<EventCondition> goals;
  300. for(const TriggeredEvent & event : cb->getMapHeader()->triggeredEvents)
  301. {
  302. //TODO: try to eliminate human player(s) using loss conditions that have isHuman element
  303. if(event.effect.type == EventEffect::VICTORY)
  304. {
  305. boost::range::copy(event.trigger.getFulfillmentCandidates(toBool), std::back_inserter(goals));
  306. }
  307. }
  308. //TODO: instead of returning first encountered goal AI should generate list of possible subgoals
  309. for(const EventCondition & goal : goals)
  310. {
  311. switch(goal.condition)
  312. {
  313. case EventCondition::HAVE_ARTIFACT:
  314. return sptr(Goals::GetArtOfType(goal.objectType));
  315. case EventCondition::DESTROY:
  316. {
  317. if(goal.object)
  318. {
  319. auto obj = cb->getObj(goal.object->id);
  320. if(obj)
  321. if(obj->getOwner() == ai->playerID) //we can't capture our own object
  322. return sptr(Goals::Conquer());
  323. return sptr(Goals::GetObj(goal.object->id.getNum()));
  324. }
  325. else
  326. {
  327. // TODO: destroy all objects of type goal.objectType
  328. // This situation represents "kill all creatures" condition from H3
  329. break;
  330. }
  331. }
  332. case EventCondition::HAVE_BUILDING:
  333. {
  334. // TODO build other buildings apart from Grail
  335. // goal.objectType = buidingID to build
  336. // goal.object = optional, town in which building should be built
  337. // Represents "Improve town" condition from H3 (but unlike H3 it consists from 2 separate conditions)
  338. if(goal.objectType == BuildingID::GRAIL)
  339. {
  340. if(auto h = ai->getHeroWithGrail())
  341. {
  342. //hero is in a town that can host Grail
  343. if(h->visitedTown && !vstd::contains(h->visitedTown->forbiddenBuildings, BuildingID::GRAIL))
  344. {
  345. const CGTownInstance * t = h->visitedTown;
  346. return sptr(Goals::BuildThis(BuildingID::GRAIL, t).setpriority(10));
  347. }
  348. else
  349. {
  350. auto towns = cb->getTownsInfo();
  351. towns.erase(boost::remove_if(towns,
  352. [](const CGTownInstance * t) -> bool
  353. {
  354. return vstd::contains(t->forbiddenBuildings, BuildingID::GRAIL);
  355. }),
  356. towns.end());
  357. boost::sort(towns, CDistanceSorter(h.get()));
  358. if(towns.size())
  359. {
  360. return sptr(Goals::VisitTile(towns.front()->visitablePos()).sethero(h));
  361. }
  362. }
  363. }
  364. double ratio = 0;
  365. // maybe make this check a bit more complex? For example:
  366. // 0.75 -> dig randomly within 3 tiles radius
  367. // 0.85 -> radius now 2 tiles
  368. // 0.95 -> 1 tile radius, position is fully known
  369. // AFAIK H3 AI does something like this
  370. int3 grailPos = cb->getGrailPos(&ratio);
  371. if(ratio > 0.99)
  372. {
  373. return sptr(Goals::DigAtTile(grailPos));
  374. } //TODO: use FIND_OBJ
  375. else if(const CGObjectInstance * obj = ai->getUnvisitedObj(objWithID<Obj::OBELISK>)) //there are unvisited Obelisks
  376. return sptr(Goals::GetObj(obj->id.getNum()));
  377. else
  378. return sptr(Goals::Explore());
  379. }
  380. break;
  381. }
  382. case EventCondition::CONTROL:
  383. {
  384. if(goal.object)
  385. {
  386. return sptr(Goals::GetObj(goal.object->id.getNum()));
  387. }
  388. else
  389. {
  390. //TODO: control all objects of type "goal.objectType"
  391. // Represents H3 condition "Flag all mines"
  392. break;
  393. }
  394. }
  395. case EventCondition::HAVE_RESOURCES:
  396. //TODO mines? piles? marketplace?
  397. //save?
  398. return sptr(Goals::CollectRes(static_cast<Res::ERes>(goal.objectType), goal.value));
  399. case EventCondition::HAVE_CREATURES:
  400. return sptr(Goals::GatherTroops(goal.objectType, goal.value));
  401. case EventCondition::TRANSPORT:
  402. {
  403. //TODO. merge with bring Grail to town? So AI will first dig grail, then transport it using this goal and builds it
  404. // Represents "transport artifact" condition:
  405. // goal.objectType = type of artifact
  406. // goal.object = destination-town where artifact should be transported
  407. break;
  408. }
  409. case EventCondition::STANDARD_WIN:
  410. return sptr(Goals::Conquer());
  411. // Conditions that likely don't need any implementation
  412. case EventCondition::DAYS_PASSED:
  413. break; // goal.value = number of days for condition to trigger
  414. case EventCondition::DAYS_WITHOUT_TOWN:
  415. break; // goal.value = number of days to trigger this
  416. case EventCondition::IS_HUMAN:
  417. break; // Should be only used in calculation of candidates (see toBool lambda)
  418. case EventCondition::CONST_VALUE:
  419. break;
  420. case EventCondition::HAVE_0:
  421. case EventCondition::HAVE_BUILDING_0:
  422. case EventCondition::DESTROY_0:
  423. //TODO: support new condition format
  424. return sptr(Goals::Conquer());
  425. default:
  426. assert(0);
  427. }
  428. }
  429. return sptr(Goals::Invalid());
  430. }
  431. TSubgoal FindObj::whatToDoToAchieve()
  432. {
  433. const CGObjectInstance * o = nullptr;
  434. if(resID > -1) //specified
  435. {
  436. for(const CGObjectInstance * obj : ai->visitableObjs)
  437. {
  438. if(obj->ID == objid && obj->subID == resID)
  439. {
  440. o = obj;
  441. break; //TODO: consider multiple objects and choose best
  442. }
  443. }
  444. }
  445. else
  446. {
  447. for(const CGObjectInstance * obj : ai->visitableObjs)
  448. {
  449. if(obj->ID == objid)
  450. {
  451. o = obj;
  452. break; //TODO: consider multiple objects and choose best
  453. }
  454. }
  455. }
  456. if(o && ai->isAccessible(o->pos)) //we don't use isAccessibleForHero as we don't know which hero it is
  457. return sptr(Goals::GetObj(o->id.getNum()));
  458. else
  459. return sptr(Goals::Explore());
  460. }
  461. bool Goals::FindObj::fulfillsMe(TSubgoal goal)
  462. {
  463. if (goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  464. {
  465. if (!hero || hero == goal->hero)
  466. for (auto obj : cb->getVisitableObjs(goal->tile)) //check if any object on that tile matches criteria
  467. if (obj->visitablePos() == goal->tile) //object could be removed
  468. if (obj->ID == objid && obj->subID == resID) //same type and subtype
  469. return true;
  470. }
  471. return false;
  472. }
  473. std::string GetObj::completeMessage() const
  474. {
  475. return "hero " + hero.get()->name + " captured Object ID = " + boost::lexical_cast<std::string>(objid);
  476. }
  477. TSubgoal GetObj::whatToDoToAchieve()
  478. {
  479. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  480. if(!obj)
  481. return sptr(Goals::Explore());
  482. if(obj->tempOwner == ai->playerID) //we can't capture our own object -> move to Win codition
  483. throw cannotFulfillGoalException("Cannot capture my own object " + obj->getObjectName());
  484. int3 pos = obj->visitablePos();
  485. if(hero)
  486. {
  487. if(ai->isAccessibleForHero(pos, hero))
  488. return sptr(Goals::VisitTile(pos).sethero(hero));
  489. }
  490. else
  491. {
  492. for(auto h : cb->getHeroesInfo())
  493. {
  494. if(ai->isAccessibleForHero(pos, h))
  495. return sptr(Goals::VisitTile(pos).sethero(h)); //we must visit object with same hero, if any
  496. }
  497. }
  498. return sptr(Goals::ClearWayTo(pos).sethero(hero));
  499. }
  500. bool Goals::GetObj::operator==(AbstractGoal & g)
  501. {
  502. if (g.goalType != goalType)
  503. return false;
  504. return g.objid == objid;
  505. }
  506. bool GetObj::fulfillsMe(TSubgoal goal)
  507. {
  508. if(goal->goalType == Goals::VISIT_TILE) //visiting tile visits object at same time
  509. {
  510. if (!hero || hero == goal->hero)
  511. {
  512. auto obj = cb->getObj(ObjectInstanceID(objid));
  513. if (obj && obj->visitablePos() == goal->tile) //object could be removed
  514. return true;
  515. }
  516. }
  517. return false;
  518. }
  519. std::string VisitHero::completeMessage() const
  520. {
  521. return "hero " + hero.get()->name + " visited hero " + boost::lexical_cast<std::string>(objid);
  522. }
  523. TSubgoal VisitHero::whatToDoToAchieve()
  524. {
  525. const CGObjectInstance * obj = cb->getObj(ObjectInstanceID(objid));
  526. if(!obj)
  527. return sptr(Goals::Explore());
  528. int3 pos = obj->visitablePos();
  529. if(hero && ai->isAccessibleForHero(pos, hero, true) && isSafeToVisit(hero, pos)) //enemy heroes can get reinforcements
  530. {
  531. if(hero->pos == pos)
  532. logAi->error("Hero %s tries to visit himself.", hero.name);
  533. else
  534. {
  535. //can't use VISIT_TILE here as tile appears blocked by target hero
  536. //FIXME: elementar goal should not be abstract
  537. return sptr(Goals::VisitHero(objid).sethero(hero).settile(pos).setisElementar(true));
  538. }
  539. }
  540. return sptr(Goals::Invalid());
  541. }
  542. bool Goals::VisitHero::operator==(AbstractGoal & g)
  543. {
  544. if (g.goalType != goalType)
  545. return false;
  546. return g.hero == hero && g.objid == objid;
  547. }
  548. bool VisitHero::fulfillsMe(TSubgoal goal)
  549. {
  550. //TODO: VisitObj shoudl not be used for heroes, but...
  551. if(goal->goalType == Goals::VISIT_TILE)
  552. {
  553. auto obj = cb->getObj(ObjectInstanceID(objid));
  554. if (!obj)
  555. {
  556. logAi->error("Hero %s: VisitHero::fulfillsMe at %s: object %d not found", hero.name, goal->tile.toString(), objid);
  557. return false;
  558. }
  559. return obj->visitablePos() == goal->tile;
  560. }
  561. return false;
  562. }
  563. TSubgoal GetArtOfType::whatToDoToAchieve()
  564. {
  565. TSubgoal alternativeWay = CGoal::lookForArtSmart(aid); //TODO: use
  566. if(alternativeWay->invalid())
  567. return sptr(Goals::FindObj(Obj::ARTIFACT, aid));
  568. return sptr(Goals::Invalid());
  569. }
  570. TSubgoal ClearWayTo::whatToDoToAchieve()
  571. {
  572. assert(cb->isInTheMap(tile)); //set tile
  573. if(!cb->isVisible(tile))
  574. {
  575. logAi->error("Clear way should be used with visible tiles!");
  576. return sptr(Goals::Explore());
  577. }
  578. return (fh->chooseSolution(getAllPossibleSubgoals()));
  579. }
  580. bool Goals::ClearWayTo::operator==(AbstractGoal & g)
  581. {
  582. if (g.goalType != goalType)
  583. return false;
  584. return g.goalType == goalType && g.tile == tile;
  585. }
  586. bool Goals::ClearWayTo::fulfillsMe(TSubgoal goal)
  587. {
  588. if (goal->goalType == Goals::VISIT_TILE)
  589. {
  590. if (!hero || hero == goal->hero)
  591. return tile == goal->tile;
  592. }
  593. return false;
  594. }
  595. TGoalVec ClearWayTo::getAllPossibleSubgoals()
  596. {
  597. TGoalVec ret;
  598. std::vector<const CGHeroInstance *> heroes;
  599. if(hero)
  600. heroes.push_back(hero.h);
  601. else
  602. heroes = cb->getHeroesInfo();
  603. for(auto h : heroes)
  604. {
  605. //TODO: handle clearing way to allied heroes that are blocked
  606. //if ((hero && hero->visitablePos() == tile && hero == *h) || //we can't free the way ourselves
  607. // h->visitablePos() == tile) //we are already on that tile! what does it mean?
  608. // continue;
  609. //if our hero is trapped, make sure we request clearing the way from OUR perspective
  610. auto sm = ai->getCachedSectorMap(h);
  611. int3 tileToHit = sm->firstTileToGet(h, tile);
  612. if(!tileToHit.valid())
  613. continue;
  614. if(isBlockedBorderGate(tileToHit))
  615. {
  616. //FIXME: this way we'll not visit gate and activate quest :?
  617. ret.push_back(sptr(Goals::FindObj(Obj::KEYMASTER, cb->getTile(tileToHit)->visitableObjects.back()->subID)));
  618. return ret; //only option
  619. }
  620. auto topObj = cb->getTopObj(tileToHit);
  621. if(topObj)
  622. {
  623. if(vstd::contains(ai->reservedObjs, topObj) && !vstd::contains(ai->reservedHeroesMap[h], topObj))
  624. {
  625. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile, h)));
  626. continue; //do not capure object reserved by other hero
  627. }
  628. if(topObj->ID == Obj::HERO && cb->getPlayerRelations(h->tempOwner, topObj->tempOwner) != PlayerRelations::ENEMIES)
  629. {
  630. if(topObj != hero.get(true)) //the hero we want to free
  631. logAi->error("%s stands in the way of %s", topObj->getObjectName(), h->getObjectName());
  632. }
  633. if(topObj->ID == Obj::QUEST_GUARD || topObj->ID == Obj::BORDERGUARD)
  634. {
  635. if(shouldVisit(h, topObj))
  636. {
  637. //do NOT use VISIT_TILE, as tile with quets guard can't be visited
  638. ret.push_back(sptr(Goals::GetObj(topObj->id.getNum()).sethero(h)));
  639. continue; //do not try to visit tile or gather army
  640. }
  641. else
  642. {
  643. //TODO: we should be able to return apriopriate quest here
  644. //ret.push_back(ai->questToGoal());
  645. //however, visiting obj for firts time will give us quest
  646. logAi->debug("Quest guard blocks the way to %s", tile.toString());
  647. continue; //do not access quets guard if we can't complete the quest
  648. }
  649. return ret; //try complete quest as the only option
  650. }
  651. }
  652. if(isSafeToVisit(h, tileToHit)) //this makes sense only if tile is guarded, but there is no quest object
  653. {
  654. ret.push_back(sptr(Goals::VisitTile(tileToHit).sethero(h)));
  655. }
  656. else
  657. {
  658. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(tileToHit, h) * SAFE_ATTACK_CONSTANT).
  659. sethero(h).setisAbstract(true)));
  660. }
  661. }
  662. if(ai->canRecruitAnyHero())
  663. ret.push_back(sptr(Goals::RecruitHero()));
  664. if(ret.empty())
  665. {
  666. logAi->warn("There is no known way to clear the way to tile %s", tile.toString());
  667. throw goalFulfilledException(sptr(Goals::ClearWayTo(tile))); //make sure asigned hero gets unlocked
  668. }
  669. return ret;
  670. }
  671. std::string Explore::completeMessage() const
  672. {
  673. return "Hero " + hero.get()->name + " completed exploration";
  674. }
  675. TSubgoal Explore::whatToDoToAchieve()
  676. {
  677. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  678. if(hero) //use best step for this hero
  679. {
  680. return ret;
  681. }
  682. else
  683. {
  684. if(ret->hero.get(true))
  685. return sptr(sethero(ret->hero.h).setisAbstract(true)); //choose this hero and then continue with him
  686. else
  687. return ret; //other solutions, like buying hero from tavern
  688. }
  689. }
  690. TGoalVec Explore::getAllPossibleSubgoals()
  691. {
  692. TGoalVec ret;
  693. std::vector<const CGHeroInstance *> heroes;
  694. if(hero)
  695. {
  696. heroes.push_back(hero.h);
  697. }
  698. else
  699. {
  700. //heroes = ai->getUnblockedHeroes();
  701. heroes = cb->getHeroesInfo();
  702. vstd::erase_if(heroes, [](const HeroPtr h)
  703. {
  704. if(ai->getGoal(h)->goalType == Goals::EXPLORE) //do not reassign hero who is already explorer
  705. return true;
  706. if(!ai->isAbleToExplore(h))
  707. return true;
  708. return !h->movement; //saves time, immobile heroes are useless anyway
  709. });
  710. }
  711. //try to use buildings that uncover map
  712. std::vector<const CGObjectInstance *> objs;
  713. for(auto obj : ai->visitableObjs)
  714. {
  715. if(!vstd::contains(ai->alreadyVisited, obj))
  716. {
  717. switch(obj->ID.num)
  718. {
  719. case Obj::REDWOOD_OBSERVATORY:
  720. case Obj::PILLAR_OF_FIRE:
  721. case Obj::CARTOGRAPHER:
  722. objs.push_back(obj);
  723. break;
  724. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  725. case Obj::MONOLITH_TWO_WAY:
  726. case Obj::SUBTERRANEAN_GATE:
  727. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  728. assert(ai->knownTeleportChannels.find(tObj->channel) != ai->knownTeleportChannels.end());
  729. if(TeleportChannel::IMPASSABLE != ai->knownTeleportChannels[tObj->channel]->passability)
  730. objs.push_back(obj);
  731. break;
  732. }
  733. }
  734. else
  735. {
  736. switch(obj->ID.num)
  737. {
  738. case Obj::MONOLITH_TWO_WAY:
  739. case Obj::SUBTERRANEAN_GATE:
  740. auto tObj = dynamic_cast<const CGTeleport *>(obj);
  741. if(TeleportChannel::IMPASSABLE == ai->knownTeleportChannels[tObj->channel]->passability)
  742. break;
  743. for(auto exit : ai->knownTeleportChannels[tObj->channel]->exits)
  744. {
  745. if(!cb->getObj(exit))
  746. { // Always attempt to visit two-way teleports if one of channel exits is not visible
  747. objs.push_back(obj);
  748. break;
  749. }
  750. }
  751. break;
  752. }
  753. }
  754. }
  755. auto primaryHero = ai->primaryHero().h;
  756. for(auto h : heroes)
  757. {
  758. auto sm = ai->getCachedSectorMap(h);
  759. for(auto obj : objs) //double loop, performance risk?
  760. {
  761. auto t = sm->firstTileToGet(h, obj->visitablePos()); //we assume that no more than one tile on the way is guarded
  762. if(ai->isTileNotReserved(h, t))
  763. ret.push_back(sptr(Goals::ClearWayTo(obj->visitablePos(), h).setisAbstract(true)));
  764. }
  765. int3 t = whereToExplore(h);
  766. if(t.valid())
  767. {
  768. ret.push_back(sptr(Goals::VisitTile(t).sethero(h)));
  769. }
  770. else
  771. {
  772. //FIXME: possible issues when gathering army to break
  773. if(hero.h == h || //exporation is assigned to this hero
  774. (!hero && h == primaryHero)) //not assigned to specific hero, let our main hero do the job
  775. {
  776. t = ai->explorationDesperate(h); //check this only ONCE, high cost
  777. if (t.valid()) //don't waste time if we are completely blocked
  778. {
  779. ret.push_back(sptr(Goals::ClearWayTo(t, h).setisAbstract(true)));
  780. continue;
  781. }
  782. }
  783. ai->markHeroUnableToExplore(h); //there is no freely accessible tile, do not poll this hero anymore
  784. }
  785. }
  786. //we either don't have hero yet or none of heroes can explore
  787. if((!hero || ret.empty()) && ai->canRecruitAnyHero())
  788. ret.push_back(sptr(Goals::RecruitHero()));
  789. if(ret.empty())
  790. {
  791. throw goalFulfilledException(sptr(Goals::Explore().sethero(hero)));
  792. }
  793. //throw cannotFulfillGoalException("Cannot explore - no possible ways found!");
  794. return ret;
  795. }
  796. bool Explore::fulfillsMe(TSubgoal goal)
  797. {
  798. if(goal->goalType == Goals::EXPLORE)
  799. {
  800. if(goal->hero)
  801. return hero == goal->hero;
  802. else
  803. return true; //cancel ALL exploration
  804. }
  805. return false;
  806. }
  807. TSubgoal RecruitHero::whatToDoToAchieve()
  808. {
  809. const CGTownInstance * t = ai->findTownWithTavern();
  810. if(!t)
  811. return sptr(Goals::BuildThis(BuildingID::TAVERN).setpriority(2));
  812. TResources res;
  813. res[Res::GOLD] = GameConstants::HERO_GOLD_COST;
  814. return ah->whatToDo(res, iAmElementar()); //either buy immediately, or collect res
  815. }
  816. bool Goals::RecruitHero::operator==(AbstractGoal & g)
  817. {
  818. if (g.goalType != goalType)
  819. return false;
  820. //TODO: check town and hero
  821. return true; //for now, recruiting any hero will do
  822. }
  823. std::string VisitTile::completeMessage() const
  824. {
  825. return "Hero " + hero.get()->name + " visited tile " + tile.toString();
  826. }
  827. TSubgoal VisitTile::whatToDoToAchieve()
  828. {
  829. auto ret = fh->chooseSolution(getAllPossibleSubgoals());
  830. if(ret->hero)
  831. {
  832. if(isSafeToVisit(ret->hero, tile) && ai->isAccessibleForHero(tile, ret->hero))
  833. {
  834. if(cb->getTile(tile)->topVisitableId().num == Obj::TOWN) //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  835. ret->objid = Obj::TOWN; //TODO: move to getObj eventually and add appropiate logic there
  836. ret->setisElementar(true);
  837. return ret;
  838. }
  839. else
  840. {
  841. return sptr(Goals::GatherArmy(evaluateDanger(tile, *ret->hero) * SAFE_ATTACK_CONSTANT)
  842. .sethero(ret->hero).setisAbstract(true));
  843. }
  844. }
  845. return ret;
  846. }
  847. bool Goals::VisitTile::operator==(AbstractGoal & g)
  848. {
  849. if (g.goalType != goalType)
  850. return false;
  851. return g.goalType == goalType && g.tile == tile;
  852. }
  853. TGoalVec VisitTile::getAllPossibleSubgoals()
  854. {
  855. assert(cb->isInTheMap(tile));
  856. TGoalVec ret;
  857. if(!cb->isVisible(tile))
  858. ret.push_back(sptr(Goals::Explore())); //what sense does it make?
  859. else
  860. {
  861. std::vector<const CGHeroInstance *> heroes;
  862. if(hero)
  863. heroes.push_back(hero.h); //use assigned hero if any
  864. else
  865. heroes = cb->getHeroesInfo(); //use most convenient hero
  866. for(auto h : heroes)
  867. {
  868. if(ai->isAccessibleForHero(tile, h))
  869. ret.push_back(sptr(Goals::VisitTile(tile).sethero(h)));
  870. }
  871. if(ai->canRecruitAnyHero())
  872. ret.push_back(sptr(Goals::RecruitHero()));
  873. }
  874. if(ret.empty())
  875. {
  876. auto obj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  877. if(obj && obj->ID == Obj::HERO && obj->tempOwner == ai->playerID) //our own hero stands on that tile
  878. {
  879. 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
  880. ret.push_back(sptr(Goals::VisitTile(tile).sethero(dynamic_cast<const CGHeroInstance *>(obj)).setisElementar(true)));
  881. else
  882. throw cannotFulfillGoalException("Tile is already occupied by another hero "); //FIXME: we should give up this tile earlier
  883. }
  884. else
  885. ret.push_back(sptr(Goals::ClearWayTo(tile)));
  886. }
  887. //important - at least one sub-goal must handle case which is impossible to fulfill (unreachable tile)
  888. return ret;
  889. }
  890. TSubgoal DigAtTile::whatToDoToAchieve()
  891. {
  892. const CGObjectInstance * firstObj = vstd::frontOrNull(cb->getVisitableObjs(tile));
  893. if(firstObj && firstObj->ID == Obj::HERO && firstObj->tempOwner == ai->playerID) //we have hero at dest
  894. {
  895. const CGHeroInstance * h = dynamic_cast<const CGHeroInstance *>(firstObj);
  896. sethero(h).setisElementar(true);
  897. return sptr(*this);
  898. }
  899. return sptr(Goals::VisitTile(tile));
  900. }
  901. bool Goals::DigAtTile::operator==(AbstractGoal & g)
  902. {
  903. if (g.goalType != goalType)
  904. return false;
  905. return g.goalType == goalType && g.tile == tile;
  906. }
  907. TSubgoal BuildThis::whatToDoToAchieve()
  908. {
  909. auto b = BuildingID(bid);
  910. // find town if not set
  911. if (!town && hero)
  912. town = hero->visitedTown;
  913. if (!town)
  914. {
  915. for (const CGTownInstance * t : cb->getTownsInfo())
  916. {
  917. switch (cb->canBuildStructure(town, b))
  918. {
  919. case EBuildingState::ALLOWED:
  920. town = t;
  921. break; //TODO: look for prerequisites? this is not our reponsibility
  922. default:
  923. continue;
  924. }
  925. }
  926. }
  927. if (town) //we have specific town to build this
  928. {
  929. if (cb->canBuildStructure(town, b) != EBuildingState::ALLOWED) //FIXME: decompose further? kind of mess if we're here
  930. throw cannotFulfillGoalException("Not possible to build");
  931. else
  932. {
  933. auto res = town->town->buildings.at(BuildingID(bid))->resources;
  934. return ah->whatToDo(res, iAmElementar()); //realize immediately or gather resources
  935. }
  936. }
  937. else
  938. throw cannotFulfillGoalException("Cannot find town to build this");
  939. }
  940. TGoalVec Goals::CollectRes::getAllPossibleSubgoals()
  941. {
  942. TGoalVec ret;
  943. auto givesResource = [this](const CGObjectInstance * obj) -> bool
  944. {
  945. //TODO: move this logic to object side
  946. //TODO: remember mithril exists
  947. //TODO: water objects
  948. //TODO: Creature banks
  949. //return false first from once-visitable, before checking if they were even visited
  950. switch (obj->ID.num)
  951. {
  952. case Obj::TREASURE_CHEST:
  953. return resID == Res::GOLD;
  954. break;
  955. case Obj::RESOURCE:
  956. return obj->subID == resID;
  957. break;
  958. case Obj::MINE:
  959. return (obj->subID == resID &&
  960. (cb->getPlayerRelations(obj->tempOwner, ai->playerID) == PlayerRelations::ENEMIES)); //don't capture our mines
  961. break;
  962. case Obj::CAMPFIRE:
  963. return true; //contains all resources
  964. break;
  965. case Obj::WINDMILL:
  966. switch (resID)
  967. {
  968. case Res::GOLD:
  969. case Res::WOOD:
  970. return false;
  971. }
  972. break;
  973. case Obj::WATER_WHEEL:
  974. if (resID != Res::GOLD)
  975. return false;
  976. break;
  977. case Obj::MYSTICAL_GARDEN:
  978. if ((resID != Res::GOLD) && (resID != Res::GEMS))
  979. return false;
  980. break;
  981. case Obj::LEAN_TO:
  982. case Obj::WAGON:
  983. if (resID != Res::GOLD)
  984. return false;
  985. break;
  986. default:
  987. return false;
  988. break;
  989. }
  990. return !vstd::contains(ai->alreadyVisited, obj); //for weekly / once visitable
  991. };
  992. std::vector<const CGObjectInstance *> objs;
  993. for (auto obj : ai->visitableObjs)
  994. {
  995. if (givesResource(obj))
  996. objs.push_back(obj);
  997. }
  998. for (auto h : cb->getHeroesInfo())
  999. {
  1000. auto sm = ai->getCachedSectorMap(h);
  1001. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  1002. for (auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  1003. {
  1004. if (givesResource(obj))
  1005. ourObjs.push_back(obj);
  1006. }
  1007. for (auto obj : ourObjs)
  1008. {
  1009. int3 dest = obj->visitablePos();
  1010. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  1011. if (t.valid()) //we know any path at all
  1012. {
  1013. if (ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  1014. {
  1015. if (isSafeToVisit(h, dest))
  1016. {
  1017. if (dest != t) //there is something blocking our way
  1018. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  1019. else
  1020. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  1021. }
  1022. else //we need to get army in order to pick that object
  1023. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  1024. }
  1025. }
  1026. }
  1027. }
  1028. return ret;
  1029. }
  1030. TSubgoal CollectRes::whatToDoToAchieve()
  1031. {
  1032. auto goals = getAllPossibleSubgoals();
  1033. auto trade = whatToDoToTrade();
  1034. if (!trade->invalid())
  1035. goals.push_back(trade);
  1036. if (goals.empty())
  1037. return sptr(Goals::Explore()); //we can always do that
  1038. else
  1039. return fh->chooseSolution(goals); //TODO: evaluate trading
  1040. }
  1041. TSubgoal Goals::CollectRes::whatToDoToTrade()
  1042. {
  1043. std::vector<const IMarket *> markets;
  1044. std::vector<const CGObjectInstance *> visObjs;
  1045. ai->retrieveVisitableObjs(visObjs, true);
  1046. for (const CGObjectInstance * obj : visObjs)
  1047. {
  1048. if (const IMarket * m = IMarket::castFrom(obj, false))
  1049. {
  1050. if (obj->ID == Obj::TOWN && obj->tempOwner == ai->playerID && m->allowsTrade(EMarketMode::RESOURCE_RESOURCE))
  1051. markets.push_back(m);
  1052. else if (obj->ID == Obj::TRADING_POST)
  1053. markets.push_back(m);
  1054. }
  1055. }
  1056. boost::sort(markets, [](const IMarket * m1, const IMarket * m2) -> bool
  1057. {
  1058. return m1->getMarketEfficiency() < m2->getMarketEfficiency();
  1059. });
  1060. markets.erase(boost::remove_if(markets, [](const IMarket * market) -> bool
  1061. {
  1062. if (!(market->o->ID == Obj::TOWN && market->o->tempOwner == ai->playerID))
  1063. {
  1064. if (!ai->isAccessible(market->o->visitablePos()))
  1065. return true;
  1066. }
  1067. return false;
  1068. }), markets.end());
  1069. if (!markets.size())
  1070. {
  1071. for (const CGTownInstance * t : cb->getTownsInfo())
  1072. {
  1073. if (cb->canBuildStructure(t, BuildingID::MARKETPLACE) == EBuildingState::ALLOWED)
  1074. return sptr(Goals::BuildThis(BuildingID::MARKETPLACE, t).setpriority(2));
  1075. }
  1076. }
  1077. else
  1078. {
  1079. const IMarket * m = markets.back();
  1080. //attempt trade at back (best prices)
  1081. int howManyCanWeBuy = 0;
  1082. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, 1))
  1083. {
  1084. if (i == resID)
  1085. continue;
  1086. int toGive = -1, toReceive = -1;
  1087. m->getOffer(i, resID, toGive, toReceive, EMarketMode::RESOURCE_RESOURCE);
  1088. assert(toGive > 0 && toReceive > 0);
  1089. howManyCanWeBuy += toReceive * (ah->freeResources()[i] / toGive);
  1090. }
  1091. if (howManyCanWeBuy >= value)
  1092. {
  1093. auto backObj = cb->getTopObj(m->o->visitablePos()); //it'll be a hero if we have one there; otherwise marketplace
  1094. assert(backObj);
  1095. auto objid = m->o->id.getNum();
  1096. if (backObj->tempOwner != ai->playerID) //top object not owned
  1097. {
  1098. return sptr(Goals::GetObj(objid)); //just go there
  1099. }
  1100. else //either it's our town, or we have hero there
  1101. {
  1102. Goals::Trade trade(resID, value, objid);
  1103. return sptr(trade.setisElementar(true)); //we can do this immediately - highest priority
  1104. }
  1105. }
  1106. }
  1107. return sptr(Goals::Invalid()); //cannot trade
  1108. }
  1109. bool CollectRes::fulfillsMe(TSubgoal goal)
  1110. {
  1111. if (goal->resID == resID)
  1112. if (goal->value >= value)
  1113. return true;
  1114. return false;
  1115. }
  1116. bool Goals::CollectRes::operator==(AbstractGoal & g)
  1117. {
  1118. if (g.goalType != goalType)
  1119. return false;
  1120. if (g.resID == resID)
  1121. if (g.value == value) //TODO: not sure if that logic is consitent
  1122. return true;
  1123. return false;
  1124. }
  1125. TSubgoal GatherTroops::whatToDoToAchieve()
  1126. {
  1127. std::vector<const CGDwelling *> dwellings;
  1128. for(const CGTownInstance * t : cb->getTownsInfo())
  1129. {
  1130. auto creature = VLC->creh->creatures[objid];
  1131. if(t->subID == creature->faction) //TODO: how to force AI to build unupgraded creatures? :O
  1132. {
  1133. auto creatures = vstd::tryAt(t->town->creatures, creature->level - 1);
  1134. if(!creatures)
  1135. continue;
  1136. int upgradeNumber = vstd::find_pos(*creatures, creature->idNumber);
  1137. if(upgradeNumber < 0)
  1138. continue;
  1139. BuildingID bid(BuildingID::DWELL_FIRST + creature->level - 1 + upgradeNumber * GameConstants::CREATURES_PER_TOWN);
  1140. if(t->hasBuilt(bid)) //this assumes only creatures with dwellings are assigned to faction
  1141. {
  1142. dwellings.push_back(t);
  1143. }
  1144. else
  1145. {
  1146. return sptr(Goals::BuildThis(bid, t).setpriority(priority));
  1147. }
  1148. }
  1149. }
  1150. for(auto obj : ai->visitableObjs)
  1151. {
  1152. if(obj->ID != Obj::CREATURE_GENERATOR1) //TODO: what with other creature generators?
  1153. continue;
  1154. auto d = dynamic_cast<const CGDwelling *>(obj);
  1155. for(auto creature : d->creatures)
  1156. {
  1157. if(creature.first) //there are more than 0 creatures avaliabe
  1158. {
  1159. for(auto type : creature.second)
  1160. {
  1161. if(type == objid && ah->freeResources().canAfford(VLC->creh->creatures[type]->cost))
  1162. dwellings.push_back(d);
  1163. }
  1164. }
  1165. }
  1166. }
  1167. if(dwellings.size())
  1168. {
  1169. typedef std::map<const CGHeroInstance *, const CGDwelling *> TDwellMap;
  1170. // sorted helper
  1171. auto comparator = [](const TDwellMap::value_type & a, const TDwellMap::value_type & b) -> bool
  1172. {
  1173. const CGPathNode * ln = ai->myCb->getPathsInfo(a.first)->getPathInfo(a.second->visitablePos());
  1174. const CGPathNode * rn = ai->myCb->getPathsInfo(b.first)->getPathInfo(b.second->visitablePos());
  1175. if(ln->turns != rn->turns)
  1176. return ln->turns < rn->turns;
  1177. return (ln->moveRemains > rn->moveRemains);
  1178. };
  1179. // for all owned heroes generate map <hero -> nearest dwelling>
  1180. TDwellMap nearestDwellings;
  1181. for(const CGHeroInstance * hero : cb->getHeroesInfo(true))
  1182. {
  1183. nearestDwellings[hero] = *boost::range::min_element(dwellings, CDistanceSorter(hero));
  1184. }
  1185. if(nearestDwellings.size())
  1186. {
  1187. // find hero who is nearest to a dwelling
  1188. const CGDwelling * nearest = boost::range::min_element(nearestDwellings, comparator)->second;
  1189. if(!nearest)
  1190. throw cannotFulfillGoalException("Cannot find nearest dwelling!");
  1191. return sptr(Goals::GetObj(nearest->id.getNum()));
  1192. }
  1193. else
  1194. return sptr(Goals::Explore());
  1195. }
  1196. else
  1197. {
  1198. return sptr(Goals::Explore());
  1199. }
  1200. //TODO: exchange troops between heroes
  1201. }
  1202. bool Goals::GatherTroops::fulfillsMe(TSubgoal goal)
  1203. {
  1204. if (!hero || hero == goal->hero) //we got army for desired hero or any hero
  1205. if (goal->objid == objid) //same creature type //TODO: consider upgrades?
  1206. if (goal->value >= value) //notify every time we get resources?
  1207. return true;
  1208. return false;
  1209. }
  1210. TSubgoal Conquer::whatToDoToAchieve()
  1211. {
  1212. return fh->chooseSolution(getAllPossibleSubgoals());
  1213. }
  1214. TGoalVec Conquer::getAllPossibleSubgoals()
  1215. {
  1216. TGoalVec ret;
  1217. auto conquerable = [](const CGObjectInstance * obj) -> bool
  1218. {
  1219. if(cb->getPlayerRelations(ai->playerID, obj->tempOwner) == PlayerRelations::ENEMIES)
  1220. {
  1221. switch(obj->ID.num)
  1222. {
  1223. case Obj::TOWN:
  1224. case Obj::HERO:
  1225. case Obj::CREATURE_GENERATOR1:
  1226. case Obj::MINE: //TODO: check ai->knownSubterraneanGates
  1227. return true;
  1228. }
  1229. }
  1230. return false;
  1231. };
  1232. std::vector<const CGObjectInstance *> objs;
  1233. for(auto obj : ai->visitableObjs)
  1234. {
  1235. if(conquerable(obj))
  1236. objs.push_back(obj);
  1237. }
  1238. for(auto h : cb->getHeroesInfo())
  1239. {
  1240. auto sm = ai->getCachedSectorMap(h);
  1241. std::vector<const CGObjectInstance *> ourObjs(objs); //copy common objects
  1242. for(auto obj : ai->reservedHeroesMap[h]) //add objects reserved by this hero
  1243. {
  1244. if(conquerable(obj))
  1245. ourObjs.push_back(obj);
  1246. }
  1247. for(auto obj : ourObjs)
  1248. {
  1249. int3 dest = obj->visitablePos();
  1250. auto t = sm->firstTileToGet(h, dest); //we assume that no more than one tile on the way is guarded
  1251. if(t.valid()) //we know any path at all
  1252. {
  1253. if(ai->isTileNotReserved(h, t)) //no other hero wants to conquer that tile
  1254. {
  1255. if(isSafeToVisit(h, dest))
  1256. {
  1257. if(dest != t) //there is something blocking our way
  1258. ret.push_back(sptr(Goals::ClearWayTo(dest, h).setisAbstract(true)));
  1259. else
  1260. {
  1261. if(obj->ID.num == Obj::HERO) //enemy hero may move to other position
  1262. {
  1263. ret.push_back(sptr(Goals::VisitHero(obj->id.getNum()).sethero(h).setisAbstract(true)));
  1264. }
  1265. else //just visit that tile
  1266. {
  1267. if(obj->ID.num == Obj::TOWN)
  1268. //if target is town, fuzzy system will use additional "estimatedReward" variable to increase priority a bit
  1269. 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
  1270. else
  1271. ret.push_back(sptr(Goals::VisitTile(dest).sethero(h).setisAbstract(true)));
  1272. }
  1273. }
  1274. }
  1275. else //we need to get army in order to conquer that place
  1276. ret.push_back(sptr(Goals::GatherArmy(evaluateDanger(dest, h) * SAFE_ATTACK_CONSTANT).sethero(h).setisAbstract(true)));
  1277. }
  1278. }
  1279. }
  1280. }
  1281. if(!objs.empty() && ai->canRecruitAnyHero()) //probably no point to recruit hero if we see no objects to capture
  1282. ret.push_back(sptr(Goals::RecruitHero()));
  1283. if(ret.empty())
  1284. ret.push_back(sptr(Goals::Explore())); //we need to find an enemy
  1285. return ret;
  1286. }
  1287. TGoalVec Goals::Build::getAllPossibleSubgoals()
  1288. {
  1289. TGoalVec ret;
  1290. for (const CGTownInstance * t : cb->getTownsInfo())
  1291. {
  1292. //start fresh with every town
  1293. ah->getBuildingOptions(t);
  1294. auto ib = ah->immediateBuilding();
  1295. if (ib.is_initialized())
  1296. {
  1297. ret.push_back(sptr(Goals::BuildThis(ib.get().bid, t).setpriority(2))); //prioritize buildings we can build quick
  1298. }
  1299. else //try build later
  1300. {
  1301. auto eb = ah->expensiveBuilding();
  1302. if (eb.is_initialized())
  1303. {
  1304. auto pb = eb.get(); //gather resources for any we can't afford
  1305. auto goal = ah->whatToDo(pb.price, sptr(Goals::BuildThis(pb.bid, t).setpriority(0.5)));
  1306. ret.push_back(goal);
  1307. }
  1308. }
  1309. }
  1310. if (ret.empty())
  1311. throw cannotFulfillGoalException("BUILD has been realized as much as possible."); //who catches it and what for?
  1312. else
  1313. return ret;
  1314. }
  1315. TSubgoal Build::whatToDoToAchieve()
  1316. {
  1317. return fh->chooseSolution(getAllPossibleSubgoals());
  1318. }
  1319. bool Goals::Build::fulfillsMe(TSubgoal goal)
  1320. {
  1321. if (goal->goalType == Goals::BUILD || goal->goalType == Goals::BUILD_STRUCTURE)
  1322. return (!town || town == goal->town); //building anything will do, in this town if set
  1323. else
  1324. return false;
  1325. }
  1326. TSubgoal Invalid::whatToDoToAchieve()
  1327. {
  1328. return iAmElementar();
  1329. }
  1330. std::string GatherArmy::completeMessage() const
  1331. {
  1332. return "Hero " + hero.get()->name + " gathered army of value " + boost::lexical_cast<std::string>(value);
  1333. }
  1334. TSubgoal GatherArmy::whatToDoToAchieve()
  1335. {
  1336. //TODO: find hero if none set
  1337. assert(hero.h);
  1338. return fh->chooseSolution(getAllPossibleSubgoals()); //find dwelling. use current hero to prevent him from doing nothing.
  1339. }
  1340. static const BuildingID unitsSource[] = { BuildingID::DWELL_LVL_1, BuildingID::DWELL_LVL_2, BuildingID::DWELL_LVL_3,
  1341. BuildingID::DWELL_LVL_4, BuildingID::DWELL_LVL_5, BuildingID::DWELL_LVL_6, BuildingID::DWELL_LVL_7};
  1342. TGoalVec GatherArmy::getAllPossibleSubgoals()
  1343. {
  1344. //get all possible towns, heroes and dwellings we may use
  1345. TGoalVec ret;
  1346. //TODO: include evaluation of monsters gather in calculation
  1347. for(auto t : cb->getTownsInfo())
  1348. {
  1349. auto pos = t->visitablePos();
  1350. if(ai->isAccessibleForHero(pos, hero))
  1351. {
  1352. //grab army from town
  1353. if(!t->visitingHero && howManyReinforcementsCanGet(hero, t))
  1354. {
  1355. if(!vstd::contains(ai->townVisitsThisWeek[hero], t))
  1356. ret.push_back(sptr(Goals::VisitTile(pos).sethero(hero)));
  1357. }
  1358. //buy army in town
  1359. if (!t->visitingHero || t->visitingHero != hero.get(true))
  1360. {
  1361. ui32 val = std::min<ui32>(value, howManyReinforcementsCanBuy(hero, t));
  1362. if (val)
  1363. {
  1364. auto goal = sptr(Goals::BuyArmy(t, val).sethero(hero));
  1365. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1366. ret.push_back(goal);
  1367. }
  1368. }
  1369. //build dwelling
  1370. auto bid = ah->canBuildAnyStructure(t, std::vector<BuildingID>(unitsSource, unitsSource + ARRAY_COUNT(unitsSource)), 8 - cb->getDate(Date::DAY_OF_WEEK));
  1371. if (bid.is_initialized())
  1372. {
  1373. auto goal = sptr(BuildThis(bid.get(), t).setpriority(priority));
  1374. if (!ah->containsObjective(goal)) //avoid loops caused by reserving same objective twice
  1375. ret.push_back(goal);
  1376. }
  1377. }
  1378. }
  1379. auto otherHeroes = cb->getHeroesInfo();
  1380. auto heroDummy = hero;
  1381. vstd::erase_if(otherHeroes, [heroDummy](const CGHeroInstance * h)
  1382. {
  1383. if(h == heroDummy.h)
  1384. return true;
  1385. else if(!ai->isAccessibleForHero(heroDummy->visitablePos(), h, true))
  1386. return true;
  1387. else if(!ai->canGetArmy(heroDummy.h, h)) //TODO: return actual aiValue
  1388. return true;
  1389. else if(ai->getGoal(h)->goalType == Goals::GATHER_ARMY)
  1390. return true;
  1391. else
  1392. return false;
  1393. });
  1394. for(auto h : otherHeroes)
  1395. {
  1396. // Go to the other hero if we are faster
  1397. if (!vstd::contains(ai->visitedHeroes[hero], h)) //visit only once each turn //FIXME: this is only bug workaround
  1398. ret.push_back(sptr(Goals::VisitHero(h->id.getNum()).setisAbstract(true).sethero(hero)));
  1399. // Let the other hero come to us
  1400. if (!vstd::contains(ai->visitedHeroes[h], hero))
  1401. ret.push_back(sptr(Goals::VisitHero(hero->id.getNum()).setisAbstract(true).sethero(h)));
  1402. }
  1403. std::vector<const CGObjectInstance *> objs;
  1404. for(auto obj : ai->visitableObjs)
  1405. {
  1406. if(obj->ID == Obj::CREATURE_GENERATOR1)
  1407. {
  1408. auto relationToOwner = cb->getPlayerRelations(obj->getOwner(), ai->playerID);
  1409. //Use flagged dwellings only when there are available creatures that we can afford
  1410. if(relationToOwner == PlayerRelations::SAME_PLAYER)
  1411. {
  1412. auto dwelling = dynamic_cast<const CGDwelling *>(obj);
  1413. for(auto & creLevel : dwelling->creatures)
  1414. {
  1415. if(creLevel.first)
  1416. {
  1417. for(auto & creatureID : creLevel.second)
  1418. {
  1419. auto creature = VLC->creh->creatures[creatureID];
  1420. if(ah->freeResources().canAfford(creature->cost))
  1421. objs.push_back(obj); //TODO: reserve resources?
  1422. }
  1423. }
  1424. }
  1425. }
  1426. }
  1427. }
  1428. for(auto h : cb->getHeroesInfo())
  1429. {
  1430. auto sm = ai->getCachedSectorMap(h);
  1431. for(auto obj : objs)
  1432. {
  1433. //find safe dwelling
  1434. auto pos = obj->visitablePos();
  1435. if(ai->isGoodForVisit(obj, h, *sm))
  1436. ret.push_back(sptr(Goals::VisitTile(pos).sethero(h)));
  1437. }
  1438. }
  1439. if(ai->canRecruitAnyHero() && ah->freeGold() > GameConstants::HERO_GOLD_COST) //this is not stupid in early phase of game
  1440. {
  1441. if(auto t = ai->findTownWithTavern())
  1442. {
  1443. for(auto h : cb->getAvailableHeroes(t)) //we assume that all towns have same set of heroes
  1444. {
  1445. if(h && h->getTotalStrength() > 500) //do not buy heroes with single creatures for GatherArmy
  1446. {
  1447. ret.push_back(sptr(Goals::RecruitHero()));
  1448. break;
  1449. }
  1450. }
  1451. }
  1452. }
  1453. if(ret.empty())
  1454. {
  1455. if(hero == ai->primaryHero())
  1456. ret.push_back(sptr(Goals::Explore()));
  1457. else
  1458. throw cannotFulfillGoalException("No ways to gather army");
  1459. }
  1460. return ret;
  1461. }
  1462. //TSubgoal AbstractGoal::whatToDoToAchieve()
  1463. //{
  1464. // logAi->debug("Decomposing goal of type %s",name());
  1465. // return sptr (Goals::Explore());
  1466. //}
  1467. TSubgoal AbstractGoal::goVisitOrLookFor(const CGObjectInstance * obj)
  1468. {
  1469. if(obj)
  1470. return sptr(Goals::GetObj(obj->id.getNum()));
  1471. else
  1472. return sptr(Goals::Explore());
  1473. }
  1474. TSubgoal AbstractGoal::lookForArtSmart(int aid)
  1475. {
  1476. return sptr(Goals::Invalid());
  1477. }
  1478. bool AbstractGoal::invalid() const
  1479. {
  1480. return goalType == INVALID;
  1481. }
  1482. void AbstractGoal::accept(VCAI * ai)
  1483. {
  1484. ai->tryRealize(*this);
  1485. }
  1486. template<typename T>
  1487. void CGoal<T>::accept(VCAI * ai)
  1488. {
  1489. ai->tryRealize(static_cast<T &>(*this)); //casting enforces template instantiation
  1490. }
  1491. float AbstractGoal::accept(FuzzyHelper * f)
  1492. {
  1493. return f->evaluate(*this);
  1494. }
  1495. template<typename T>
  1496. float CGoal<T>::accept(FuzzyHelper * f)
  1497. {
  1498. return f->evaluate(static_cast<T &>(*this)); //casting enforces template instantiation
  1499. }