Fuzzy.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #include "StdInc.h"
  2. #include "Fuzzy.h"
  3. #include <limits>
  4. #include "../../lib/mapObjects/MapObjects.h"
  5. #include "../../lib/mapObjects/CommonConstructors.h"
  6. #include "../../lib/CCreatureHandler.h"
  7. #include "../../lib/VCMI_Lib.h"
  8. #include "../../CCallback.h"
  9. #include "VCAI.h"
  10. /*
  11. * Fuzzy.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. #define MIN_AI_STRENGHT (0.5f) //lower when combat AI gets smarter
  20. #define UNGUARDED_OBJECT (100.0f) //we consider unguarded objects 100 times weaker than us
  21. struct BankConfig;
  22. class IObjectInfo;
  23. class CBankInfo;
  24. class Engine;
  25. class InputVariable;
  26. class CGTownInstance;
  27. using namespace vstd;
  28. //using namespace Goals;
  29. FuzzyHelper *fh;
  30. extern boost::thread_specific_ptr<CCallback> cb;
  31. extern boost::thread_specific_ptr<VCAI> ai;
  32. struct armyStructure
  33. {
  34. float walkers, shooters, flyers;
  35. ui32 maxSpeed;
  36. };
  37. armyStructure evaluateArmyStructure (const CArmedInstance * army)
  38. {
  39. ui64 totalStrenght = army->getArmyStrength();
  40. double walkersStrenght = 0;
  41. double flyersStrenght = 0;
  42. double shootersStrenght = 0;
  43. ui32 maxSpeed = 0;
  44. for(auto s : army->Slots())
  45. {
  46. bool walker = true;
  47. if (s.second->type->hasBonusOfType(Bonus::SHOOTER))
  48. {
  49. shootersStrenght += s.second->getPower();
  50. walker = false;
  51. }
  52. if (s.second->type->hasBonusOfType(Bonus::FLYING))
  53. {
  54. flyersStrenght += s.second->getPower();
  55. walker = false;
  56. }
  57. if (walker)
  58. walkersStrenght += s.second->getPower();
  59. amax (maxSpeed, s.second->type->valOfBonuses(Bonus::STACKS_SPEED));
  60. }
  61. armyStructure as;
  62. as.walkers = walkersStrenght / totalStrenght;
  63. as.shooters = shootersStrenght / totalStrenght;
  64. as.flyers = flyersStrenght / totalStrenght;
  65. as.maxSpeed = maxSpeed;
  66. return as;
  67. }
  68. FuzzyHelper::FuzzyHelper()
  69. {
  70. initTacticalAdvantage();
  71. initVisitTile();
  72. engine.configure("Minimum", "Maximum", "Minimum", "AlgebraicSum", "Centroid");
  73. logAi->infoStream() << engine.toString();
  74. }
  75. void FuzzyHelper::initTacticalAdvantage()
  76. {
  77. try
  78. {
  79. ta.ourShooters = new fl::InputVariable("OurShooters");
  80. ta.ourWalkers = new fl::InputVariable("OurWalkers");
  81. ta.ourFlyers = new fl::InputVariable("OurFlyers");
  82. ta.enemyShooters = new fl::InputVariable("EnemyShooters");
  83. ta.enemyWalkers = new fl::InputVariable("EnemyWalkers");
  84. ta.enemyFlyers = new fl::InputVariable("EnemyFlyers");
  85. //Tactical advantage calculation
  86. std::vector<fl::InputVariable*> helper =
  87. {
  88. ta.ourShooters, ta.ourWalkers, ta.ourFlyers, ta.enemyShooters, ta.enemyWalkers, ta.enemyFlyers
  89. };
  90. for (auto val : helper)
  91. {
  92. engine.addInputVariable(val);
  93. val->addTerm(new fl::Ramp("FEW", 0.6, 0.0));
  94. val->addTerm(new fl::Ramp("MANY", 0.4, 1));
  95. val->setRange(0.0, 1.0);
  96. }
  97. ta.ourSpeed = new fl::InputVariable("OurSpeed");
  98. ta.enemySpeed = new fl::InputVariable("EnemySpeed");
  99. helper = {ta.ourSpeed, ta.enemySpeed};
  100. for (auto val : helper)
  101. {
  102. engine.addInputVariable(val);
  103. val->addTerm(new fl::Ramp("LOW", 6.5, 3));
  104. val->addTerm(new fl::Triangle("MEDIUM", 5.5, 10.5));
  105. val->addTerm(new fl::Ramp("HIGH", 8.5, 16));
  106. val->setRange(0, 25);
  107. }
  108. ta.castleWalls = new fl::InputVariable("CastleWalls");
  109. engine.addInputVariable(ta.castleWalls);
  110. {
  111. fl::Rectangle* none = new fl::Rectangle("NONE", CGTownInstance::NONE, CGTownInstance::NONE + (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f);
  112. ta.castleWalls->addTerm(none);
  113. fl::Trapezoid* medium = new fl::Trapezoid("MEDIUM", (CGTownInstance::FORT - CGTownInstance::NONE) * 0.5f, CGTownInstance::FORT,
  114. CGTownInstance::CITADEL, CGTownInstance::CITADEL + (CGTownInstance::CASTLE - CGTownInstance::CITADEL) * 0.5f);
  115. ta.castleWalls->addTerm(medium);
  116. fl::Ramp* high = new fl::Ramp("HIGH", CGTownInstance::CITADEL - 0.1, CGTownInstance::CASTLE);
  117. ta.castleWalls->addTerm(high);
  118. ta.castleWalls->setRange(CGTownInstance::NONE, CGTownInstance::CASTLE);
  119. }
  120. ta.bankPresent = new fl::InputVariable("Bank");
  121. engine.addInputVariable(ta.bankPresent);
  122. {
  123. fl::Rectangle* termFalse = new fl::Rectangle("FALSE", 0.0, 0.5f);
  124. ta.bankPresent->addTerm(termFalse);
  125. fl::Rectangle* termTrue = new fl::Rectangle("TRUE", 0.5f, 1);
  126. ta.bankPresent->addTerm(termTrue);
  127. ta.bankPresent->setRange(0, 1);
  128. }
  129. ta.threat = new fl::OutputVariable("Threat");
  130. engine.addOutputVariable(ta.threat);
  131. ta.threat->addTerm(new fl::Ramp("LOW", 1, MIN_AI_STRENGHT));
  132. ta.threat->addTerm(new fl::Triangle("MEDIUM", 0.8, 1.2));
  133. ta.threat->addTerm(new fl::Ramp("HIGH", 1, 1.5));
  134. ta.threat->setRange(MIN_AI_STRENGHT, 1.5);
  135. engine.addRuleBlock(&ta.tacticalAdvantage);
  136. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurShooters is MANY and EnemySpeed is LOW then Threat is LOW", &engine));
  137. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurShooters is MANY and EnemyShooters is FEW then Threat is LOW", &engine));
  138. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurSpeed is LOW and EnemyShooters is MANY then Threat is HIGH", &engine));
  139. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurSpeed is HIGH and EnemyShooters is MANY then Threat is LOW", &engine));
  140. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurWalkers is FEW and EnemyShooters is MANY then Threat is somewhat LOW", &engine));
  141. ta.tacticalAdvantage.addRule(fl::Rule::parse("if OurShooters is MANY and EnemySpeed is HIGH then Threat is somewhat HIGH", &engine));
  142. //just to cover all cases
  143. ta.tacticalAdvantage.addRule(fl::Rule::parse("if EnemySpeed is MEDIUM then Threat is MEDIUM", &engine));
  144. ta.tacticalAdvantage.addRule(fl::Rule::parse("if EnemySpeed is LOW and OurShooters is FEW then Threat is MEDIUM", &engine));
  145. ta.tacticalAdvantage.addRule(fl::Rule::parse("if Bank is TRUE and OurShooters is MANY then Threat is somewhat HIGH", &engine));
  146. ta.tacticalAdvantage.addRule(fl::Rule::parse("if Bank is TRUE and EnemyShooters is MANY then Threat is LOW", &engine));
  147. ta.tacticalAdvantage.addRule(fl::Rule::parse("if CastleWalls is HIGH and OurWalkers is MANY then Threat is very HIGH", &engine));
  148. ta.tacticalAdvantage.addRule(fl::Rule::parse("if CastleWalls is HIGH and OurFlyers is MANY and OurShooters is MANY then Threat is MEDIUM", &engine));
  149. ta.tacticalAdvantage.addRule(fl::Rule::parse("if CastleWalls is MEDIUM and OurShooters is MANY and EnemyWalkers is MANY then Threat is LOW", &engine));
  150. }
  151. catch (fl::Exception & pe)
  152. {
  153. logAi->errorStream() << "initTacticalAdvantage " << ": " << pe.getWhat();
  154. }
  155. }
  156. ui64 FuzzyHelper::estimateBankDanger (const CBank * bank)
  157. {
  158. //this one is not fuzzy anymore, just calculate weighted average
  159. auto objectInfo = VLC->objtypeh->getHandlerFor(bank->ID, bank->subID)->getObjectInfo(bank->appearance);
  160. CBankInfo * bankInfo = dynamic_cast<CBankInfo *> (objectInfo.get());
  161. ui64 totalStrength = 0;
  162. ui8 totalChance = 0;
  163. for (auto config : bankInfo->getPossibleGuards())
  164. {
  165. totalStrength += config.second.totalStrength * config.first;
  166. totalChance += config.first;
  167. }
  168. return totalStrength / totalChance;
  169. }
  170. float FuzzyHelper::getTacticalAdvantage (const CArmedInstance *we, const CArmedInstance *enemy)
  171. {
  172. float output = 1;
  173. try
  174. {
  175. armyStructure ourStructure = evaluateArmyStructure(we);
  176. armyStructure enemyStructure = evaluateArmyStructure(enemy);
  177. ta.ourWalkers->setInputValue(ourStructure.walkers);
  178. ta.ourShooters->setInputValue(ourStructure.shooters);
  179. ta.ourFlyers->setInputValue(ourStructure.flyers);
  180. ta.ourSpeed->setInputValue(ourStructure.maxSpeed);
  181. ta.enemyWalkers->setInputValue(enemyStructure.walkers);
  182. ta.enemyShooters->setInputValue(enemyStructure.shooters);
  183. ta.enemyFlyers->setInputValue(enemyStructure.flyers);
  184. ta.enemySpeed->setInputValue(enemyStructure.maxSpeed);
  185. bool bank = dynamic_cast<const CBank*> (enemy);
  186. if (bank)
  187. ta.bankPresent->setInputValue(1);
  188. else
  189. ta.bankPresent->setInputValue(0);
  190. const CGTownInstance * fort = dynamic_cast<const CGTownInstance*> (enemy);
  191. if (fort)
  192. {
  193. ta.castleWalls->setInputValue(fort->fortLevel());
  194. }
  195. else
  196. ta.castleWalls->setInputValue(0);
  197. //engine.process(TACTICAL_ADVANTAGE);//TODO: Process only Tactical_Advantage
  198. engine.process();
  199. output = ta.threat->getOutputValue();
  200. }
  201. catch (fl::Exception & fe)
  202. {
  203. logAi->errorStream() << "getTacticalAdvantage " << ": " << fe.getWhat();
  204. }
  205. assert (output >= 0);
  206. return output;
  207. }
  208. FuzzyHelper::TacticalAdvantage::~TacticalAdvantage()
  209. {
  210. //TODO: smart pointers?
  211. delete ourWalkers;
  212. delete ourShooters;
  213. delete ourFlyers;
  214. delete enemyWalkers;
  215. delete enemyShooters;
  216. delete enemyFlyers;
  217. delete ourSpeed;
  218. delete enemySpeed;
  219. delete bankPresent;
  220. delete castleWalls;
  221. delete threat;
  222. }
  223. //shared_ptr<AbstractGoal> chooseSolution (std::vector<shared_ptr<AbstractGoal>> & vec)
  224. Goals::TSubgoal FuzzyHelper::chooseSolution (Goals::TGoalVec vec)
  225. {
  226. if (vec.empty()) //no possibilities found
  227. return sptr(Goals::Invalid());
  228. //a trick to switch between heroes less often - calculatePaths is costly
  229. auto sortByHeroes = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  230. {
  231. return lhs->hero.h < rhs->hero.h;
  232. };
  233. boost::sort (vec, sortByHeroes);
  234. for (auto g : vec)
  235. {
  236. setPriority(g);
  237. }
  238. auto compareGoals = [](const Goals::TSubgoal & lhs, const Goals::TSubgoal & rhs) -> bool
  239. {
  240. return lhs->priority < rhs->priority;
  241. };
  242. boost::sort (vec, compareGoals);
  243. return vec.back();
  244. }
  245. float FuzzyHelper::evaluate (Goals::Explore & g)
  246. {
  247. return 1;
  248. }
  249. float FuzzyHelper::evaluate (Goals::RecruitHero & g)
  250. {
  251. return 1; //just try to recruit hero as one of options
  252. }
  253. FuzzyHelper::EvalVisitTile::~EvalVisitTile()
  254. {
  255. delete strengthRatio;
  256. delete heroStrength;
  257. delete turnDistance;
  258. delete missionImportance;
  259. }
  260. void FuzzyHelper::initVisitTile()
  261. {
  262. try
  263. {
  264. vt.strengthRatio = new fl::InputVariable("strengthRatio"); //hero must be strong enough to defeat guards
  265. vt.heroStrength = new fl::InputVariable("heroStrength"); //we want to use weakest possible hero
  266. vt.turnDistance = new fl::InputVariable("turnDistance"); //we want to use hero who is near
  267. vt.missionImportance = new fl::InputVariable("lockedMissionImportance"); //we may want to preempt hero with low-priority mission
  268. vt.value = new fl::OutputVariable("Value");
  269. vt.value->setMinimum(0);
  270. vt.value->setMaximum(5);
  271. std::vector<fl::InputVariable*> helper = {vt.strengthRatio, vt.heroStrength, vt.turnDistance, vt.missionImportance};
  272. for (auto val : helper)
  273. {
  274. engine.addInputVariable(val);
  275. }
  276. engine.addOutputVariable(vt.value);
  277. vt.strengthRatio->addTerm(new fl::Ramp("LOW", SAFE_ATTACK_CONSTANT, 0));
  278. vt.strengthRatio->addTerm(new fl::Ramp("HIGH", SAFE_ATTACK_CONSTANT, SAFE_ATTACK_CONSTANT * 3));
  279. vt.strengthRatio->setRange(0, SAFE_ATTACK_CONSTANT * 3 );
  280. //strength compared to our main hero
  281. vt.heroStrength->addTerm(new fl::Ramp("LOW", 0.2, 0));
  282. vt.heroStrength->addTerm(new fl::Triangle("MEDIUM", 0.2, 0.8));
  283. vt.heroStrength->addTerm(new fl::Ramp("HIGH", 0.5, 1));
  284. vt.heroStrength->setRange(0.0, 1.0);
  285. vt.turnDistance->addTerm(new fl::Ramp("SMALL", 0.5, 0));
  286. vt.turnDistance->addTerm(new fl::Triangle("MEDIUM", 0.1, 0.8));
  287. vt.turnDistance->addTerm(new fl::Ramp("LONG", 0.5, 3));
  288. vt.turnDistance->setRange(0.0, 3.0);
  289. vt.missionImportance->addTerm(new fl::Ramp("LOW", 2.5, 0));
  290. vt.missionImportance->addTerm(new fl::Triangle("MEDIUM", 2, 3));
  291. vt.missionImportance->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  292. vt.missionImportance->setRange(0.0, 5.0);
  293. //an issue: in 99% cases this outputs center of mass (2.5) regardless of actual input :/
  294. //should be same as "mission Importance" to keep consistency
  295. vt.value->addTerm(new fl::Ramp("LOW", 2.5, 0));
  296. vt.value->addTerm(new fl::Triangle("MEDIUM", 2, 3)); //can't be center of mass :/
  297. vt.value->addTerm(new fl::Ramp("HIGH", 2.5, 5));
  298. vt.value->setRange(0.0,5.0);
  299. engine.addRuleBlock (&vt.rules);
  300. //use unarmed scouts if possible
  301. vt.rules.addRule(fl::Rule::parse("if strengthRatio is HIGH and heroStrength is LOW then Value is very HIGH", &engine));
  302. //we may want to use secondary hero(es) rather than main hero
  303. vt.rules.addRule(fl::Rule::parse("if strengthRatio is HIGH and heroStrength is MEDIUM then Value is somewhat HIGH", &engine));
  304. vt.rules.addRule(fl::Rule::parse("if strengthRatio is HIGH and heroStrength is HIGH then Value is somewhat LOW", &engine));
  305. //don't assign targets to heroes who are too weak, but prefer targets of our main hero (in case we need to gather army)
  306. vt.rules.addRule(fl::Rule::parse("if strengthRatio is LOW and heroStrength is LOW then Value is very LOW", &engine));
  307. //attempt to arm secondary heroes is not stupid
  308. vt.rules.addRule(fl::Rule::parse("if strengthRatio is LOW and heroStrength is MEDIUM then Value is somewhat HIGH", &engine));
  309. vt.rules.addRule(fl::Rule::parse("if strengthRatio is LOW and heroStrength is HIGH then Value is LOW", &engine));
  310. //do not cancel important goals
  311. vt.rules.addRule(fl::Rule::parse("if lockedMissionImportance is HIGH then Value is very LOW", &engine));
  312. vt.rules.addRule(fl::Rule::parse("if lockedMissionImportance is MEDIUM then Value is somewhat LOW", &engine));
  313. vt.rules.addRule(fl::Rule::parse("if lockedMissionImportance is LOW then Value is HIGH", &engine));
  314. //pick nearby objects if it's easy, avoid long walks
  315. vt.rules.addRule(fl::Rule::parse("if turnDistance is SMALL then Value is HIGH", &engine));
  316. vt.rules.addRule(fl::Rule::parse("if turnDistance is MEDIUM then Value is MEDIUM", &engine));
  317. vt.rules.addRule(fl::Rule::parse("if turnDistance is LONG then Value is LOW", &engine));
  318. }
  319. catch (fl::Exception & fe)
  320. {
  321. logAi->errorStream() << "visitTile " << ": " << fe.getWhat();
  322. }
  323. }
  324. float FuzzyHelper::evaluate (Goals::VisitTile & g)
  325. {
  326. //we assume that hero is already set and we want to choose most suitable one for the mission
  327. if (!g.hero)
  328. return 0;
  329. //assert(cb->isInTheMap(g.tile));
  330. float turns = 0;
  331. float distance = cb->getMovementCost(g.hero.h, g.tile);
  332. if (!distance) //we stand on that tile
  333. turns = 0;
  334. else
  335. {
  336. if (distance < g.hero->movement) //we can move there within one turn
  337. turns = (fl::scalar)distance / g.hero->movement;
  338. else
  339. turns = 1 + (fl::scalar)(distance - g.hero->movement) / g.hero->maxMovePoints(true); //bool on land?
  340. }
  341. float missionImportance = 0;
  342. if (vstd::contains(ai->lockedHeroes, g.hero))
  343. missionImportance = ai->lockedHeroes[g.hero]->priority;
  344. float strengthRatio = 10.0f; //we are much stronger than enemy
  345. ui64 danger = evaluateDanger (g.tile, g.hero.h);
  346. if (danger)
  347. strengthRatio = (fl::scalar)g.hero.h->getTotalStrength() / danger;
  348. try
  349. {
  350. vt.strengthRatio->setInputValue(strengthRatio);
  351. vt.heroStrength->setInputValue((fl::scalar)g.hero->getTotalStrength() / ai->primaryHero()->getTotalStrength());
  352. vt.turnDistance->setInputValue(turns);
  353. vt.missionImportance->setInputValue(missionImportance);
  354. engine.process();
  355. //engine.process(VISIT_TILE); //TODO: Process only Visit_Tile
  356. g.priority = vt.value->getOutputValue();
  357. }
  358. catch (fl::Exception & fe)
  359. {
  360. logAi->errorStream() << "evaluate VisitTile " << ": " << fe.getWhat();
  361. }
  362. assert (g.priority >= 0);
  363. return g.priority;
  364. }
  365. float FuzzyHelper::evaluate (Goals::VisitHero & g)
  366. {
  367. auto obj = cb->getObj(ObjectInstanceID(g.objid)); //we assume for now that these goals are similar
  368. if (!obj)
  369. return -100; //hero died in the meantime
  370. //TODO: consider direct copy (constructor?)
  371. g.setpriority(Goals::VisitTile(obj->visitablePos()).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  372. return g.priority;
  373. }
  374. float FuzzyHelper::evaluate (Goals::GatherArmy & g)
  375. {
  376. //the more army we need, the more important goal
  377. //the more army we lack, the less important goal
  378. float army = g.hero->getArmyStrength();
  379. return g.value / std::max(g.value - army, 1000.0f);
  380. }
  381. float FuzzyHelper::evaluate (Goals::ClearWayTo & g)
  382. {
  383. if (!g.hero.h)
  384. throw cannotFulfillGoalException("ClearWayTo called without hero!");
  385. SectorMap sm(g.hero);
  386. int3 t = sm.firstTileToGet(g.hero, g.tile);
  387. if (t.valid())
  388. {
  389. if (isSafeToVisit(g.hero, t))
  390. {
  391. g.setpriority(Goals::VisitTile(g.tile).sethero(g.hero).setisAbstract(g.isAbstract).accept(this));
  392. }
  393. else
  394. {
  395. g.setpriority (Goals::GatherArmy(evaluateDanger(t, g.hero.h)*SAFE_ATTACK_CONSTANT).
  396. sethero(g.hero).setisAbstract(true).accept(this));
  397. }
  398. return g.priority;
  399. }
  400. else
  401. return -1;
  402. }
  403. float FuzzyHelper::evaluate (Goals::BuildThis & g)
  404. {
  405. return 1;
  406. }
  407. float FuzzyHelper::evaluate (Goals::DigAtTile & g)
  408. {
  409. return 0;
  410. }
  411. float FuzzyHelper::evaluate (Goals::CollectRes & g)
  412. {
  413. return 0;
  414. }
  415. float FuzzyHelper::evaluate (Goals::Build & g)
  416. {
  417. return 0;
  418. }
  419. float FuzzyHelper::evaluate (Goals::Invalid & g)
  420. {
  421. return -1e10;
  422. }
  423. float FuzzyHelper::evaluate (Goals::AbstractGoal & g)
  424. {
  425. logAi->warnStream() << boost::format("Cannot evaluate goal %s") % g.name();
  426. return g.priority;
  427. }
  428. void FuzzyHelper::setPriority (Goals::TSubgoal & g)
  429. {
  430. g->setpriority(g->accept(this)); //this enforces returned value is set
  431. }