CGCreature.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. /*
  2. * CGCreature.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 "CGCreature.h"
  12. #include "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CConfigHandler.h"
  15. #include "../GameSettings.h"
  16. #include "../IGameCallback.h"
  17. #include "../serializer/JsonSerializeFormat.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. std::string CGCreature::getHoverText(PlayerColor player) const
  20. {
  21. if(stacks.empty())
  22. {
  23. //should not happen...
  24. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", pos.toString(), subID, id.getNum());
  25. return "INVALID_STACK";
  26. }
  27. std::string hoverName;
  28. MetaString ms;
  29. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  30. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  31. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  32. ms.appendRawString(CCreature::getQuantityRangeStringForId(monsterQuantityId));
  33. else
  34. ms.appendLocalString(EMetaText::ARRAY_TXT, quantityTextIndex);
  35. ms.appendRawString(" ");
  36. ms.appendLocalString(EMetaText::CRE_PL_NAMES,subID);
  37. hoverName = ms.toString();
  38. return hoverName;
  39. }
  40. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  41. {
  42. std::string hoverName;
  43. if(hero->hasVisions(this, 0))
  44. {
  45. MetaString ms;
  46. ms.appendNumber(stacks.begin()->second->count);
  47. ms.appendRawString(" ");
  48. ms.appendLocalString(EMetaText::CRE_PL_NAMES,subID);
  49. ms.appendRawString("\n\n");
  50. int decision = takenAction(hero, true);
  51. switch (decision)
  52. {
  53. case FIGHT:
  54. ms.appendLocalString(EMetaText::GENERAL_TXT,246);
  55. break;
  56. case FLEE:
  57. ms.appendLocalString(EMetaText::GENERAL_TXT,245);
  58. break;
  59. case JOIN_FOR_FREE:
  60. ms.appendLocalString(EMetaText::GENERAL_TXT,243);
  61. break;
  62. default: //decision = cost in gold
  63. ms.appendRawString(boost::str(boost::format(VLC->generaltexth->allTexts[244]) % decision));
  64. break;
  65. }
  66. hoverName = ms.toString();
  67. }
  68. else
  69. {
  70. hoverName = getHoverText(hero->tempOwner);
  71. }
  72. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  73. int choice;
  74. double ratio = (static_cast<double>(getArmyStrength()) / hero->getTotalStrength());
  75. if (ratio < 0.1) choice = 0;
  76. else if (ratio < 0.25) choice = 1;
  77. else if (ratio < 0.6) choice = 2;
  78. else if (ratio < 0.9) choice = 3;
  79. else if (ratio < 1.1) choice = 4;
  80. else if (ratio < 1.3) choice = 5;
  81. else if (ratio < 1.8) choice = 6;
  82. else if (ratio < 2.5) choice = 7;
  83. else if (ratio < 4) choice = 8;
  84. else if (ratio < 8) choice = 9;
  85. else if (ratio < 20) choice = 10;
  86. else choice = 11;
  87. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  88. return hoverName;
  89. }
  90. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  91. {
  92. //show message
  93. if(!message.empty())
  94. {
  95. InfoWindow iw;
  96. iw.player = h->tempOwner;
  97. iw.text = message;
  98. iw.type = EInfoWindowMode::MODAL;
  99. cb->showInfoDialog(&iw);
  100. }
  101. int action = takenAction(h);
  102. switch( action ) //decide what we do...
  103. {
  104. case FIGHT:
  105. fight(h);
  106. break;
  107. case FLEE:
  108. {
  109. flee(h);
  110. break;
  111. }
  112. case JOIN_FOR_FREE: //join for free
  113. {
  114. BlockingDialog ynd(true,false);
  115. ynd.player = h->tempOwner;
  116. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, 86);
  117. ynd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, subID);
  118. cb->showBlockingDialog(&ynd);
  119. break;
  120. }
  121. default: //join for gold
  122. {
  123. assert(action > 0);
  124. //ask if player agrees to pay gold
  125. BlockingDialog ynd(true,false);
  126. ynd.player = h->tempOwner;
  127. std::string tmp = VLC->generaltexth->advobtxt[90];
  128. boost::algorithm::replace_first(tmp, "%d", std::to_string(getStackCount(SlotID(0))));
  129. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  130. boost::algorithm::replace_first(tmp,"%s",VLC->creh->objects[subID]->getNamePluralTranslated());
  131. ynd.text.appendRawString(tmp);
  132. cb->showBlockingDialog(&ynd);
  133. break;
  134. }
  135. }
  136. }
  137. void CGCreature::initObj(CRandomGenerator & rand)
  138. {
  139. blockVisit = true;
  140. switch(character)
  141. {
  142. case 0:
  143. character = -4;
  144. break;
  145. case 1:
  146. character = rand.nextInt(1, 7);
  147. break;
  148. case 2:
  149. character = rand.nextInt(1, 10);
  150. break;
  151. case 3:
  152. character = rand.nextInt(4, 10);
  153. break;
  154. case 4:
  155. character = 10;
  156. break;
  157. }
  158. stacks[SlotID(0)]->setType(CreatureID(subID));
  159. TQuantity &amount = stacks[SlotID(0)]->count;
  160. CCreature &c = *VLC->creh->objects[subID];
  161. if(amount == 0)
  162. {
  163. amount = rand.nextInt(c.ammMin, c.ammMax);
  164. if(amount == 0) //armies with 0 creatures are illegal
  165. {
  166. logGlobal->warn("Stack %s cannot have 0 creatures. Check properties of %s", nodeName(), c.nodeName());
  167. amount = 1;
  168. }
  169. }
  170. temppower = stacks[SlotID(0)]->count * static_cast<ui64>(1000);
  171. refusedJoining = false;
  172. }
  173. void CGCreature::newTurn(CRandomGenerator & rand) const
  174. {//Works only for stacks of single type of size up to 2 millions
  175. if (!notGrowingTeam)
  176. {
  177. if (stacks.begin()->second->count < VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  178. {
  179. ui32 power = static_cast<ui32>(temppower * (100 + VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  180. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  181. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  182. }
  183. }
  184. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  185. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->settings()->getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  186. }
  187. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  188. {
  189. switch (what)
  190. {
  191. case ObjProperty::MONSTER_COUNT:
  192. stacks[SlotID(0)]->count = val;
  193. break;
  194. case ObjProperty::MONSTER_POWER:
  195. temppower = val;
  196. break;
  197. case ObjProperty::MONSTER_EXP:
  198. giveStackExp(val);
  199. break;
  200. case ObjProperty::MONSTER_RESTORE_TYPE:
  201. formation.basicType = val;
  202. break;
  203. case ObjProperty::MONSTER_REFUSED_JOIN:
  204. refusedJoining = val;
  205. break;
  206. }
  207. }
  208. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  209. {
  210. //calculate relative strength of hero and creatures armies
  211. double relStrength = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  212. int powerFactor;
  213. if(relStrength >= 7)
  214. powerFactor = 11;
  215. else if(relStrength >= 1)
  216. powerFactor = static_cast<int>(2 * (relStrength - 1));
  217. else if(relStrength >= 0.5)
  218. powerFactor = -1;
  219. else if(relStrength >= 0.333)
  220. powerFactor = -2;
  221. else
  222. powerFactor = -3;
  223. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  224. const CCreature * myCreature = VLC->creh->objects[subID];
  225. myKindCres.insert(myCreature->getId()); //we
  226. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  227. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->objects)
  228. {
  229. if(vstd::contains(crea->upgrades, myCreature->getId())) //it's our base creatures
  230. myKindCres.insert(crea->getId());
  231. }
  232. int count = 0; //how many creatures of similar kind has hero
  233. int totalCount = 0;
  234. for(const auto & elem : h->Slots())
  235. {
  236. if(vstd::contains(myKindCres,elem.second->type->getId()))
  237. count += elem.second->count;
  238. totalCount += elem.second->count;
  239. }
  240. int sympathy = 0; // 0 if hero have no similar creatures
  241. if(count)
  242. sympathy++; // 1 - if hero have at least 1 similar creature
  243. if(count*2 > totalCount)
  244. sympathy++; // 2 - hero have similar creatures more that 50%
  245. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  246. int charisma = powerFactor + diplomacy + sympathy;
  247. if(charisma < character)
  248. return FIGHT;
  249. if (allowJoin)
  250. {
  251. if(diplomacy + sympathy + 1 >= character)
  252. return JOIN_FOR_FREE;
  253. else if(diplomacy * 2 + sympathy + 1 >= character)
  254. return VLC->creatures()->getByIndex(subID)->getRecruitCost(EGameResID::GOLD) * getStackCount(SlotID(0)); //join for gold
  255. }
  256. //we are still here - creatures have not joined hero, flee or fight
  257. if (charisma > character && !neverFlees)
  258. return FLEE;
  259. else
  260. return FIGHT;
  261. }
  262. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  263. {
  264. if(refusedJoining)
  265. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  266. if(pursue)
  267. {
  268. fight(h);
  269. }
  270. else
  271. {
  272. cb->removeObject(this, h->getOwner());
  273. }
  274. }
  275. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  276. {
  277. if(!accept)
  278. {
  279. if(takenAction(h,false) == FLEE)
  280. {
  281. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  282. flee(h);
  283. }
  284. else //they fight
  285. {
  286. h->showInfoDialog(87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  287. fight(h);
  288. }
  289. }
  290. else //accepted
  291. {
  292. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  293. {
  294. InfoWindow iw;
  295. iw.player = h->tempOwner;
  296. iw.text.appendLocalString(EMetaText::GENERAL_TXT,29); //You don't have enough gold
  297. cb->showInfoDialog(&iw);
  298. //act as if player refused
  299. joinDecision(h,cost,false);
  300. return;
  301. }
  302. //take gold
  303. if(cost)
  304. cb->giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  305. giveReward(h);
  306. cb->tryJoiningArmy(this, h, true, true);
  307. }
  308. }
  309. void CGCreature::fight( const CGHeroInstance *h ) const
  310. {
  311. //split stacks
  312. //TODO: multiple creature types in a stack?
  313. int basicType = stacks.begin()->second->type->getId();
  314. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  315. int stacksCount = getNumberOfStacks(h);
  316. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  317. int amount = getStackCount(SlotID(0));
  318. int m = amount / stacksCount;
  319. int b = stacksCount * (m + 1) - amount;
  320. int a = stacksCount - b;
  321. SlotID sourceSlot = stacks.begin()->first;
  322. for (int slotID = 1; slotID < a; ++slotID)
  323. {
  324. int stackSize = m + 1;
  325. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  326. }
  327. for (int slotID = a; slotID < stacksCount; ++slotID)
  328. {
  329. int stackSize = m;
  330. if (slotID) //don't do this when a = 0 -> stack is single
  331. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  332. }
  333. if (stacksCount > 1)
  334. {
  335. if (containsUpgradedStack()) //upgrade
  336. {
  337. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  338. const auto & upgrades = getStack(slotID).type->upgrades;
  339. if(!upgrades.empty())
  340. {
  341. auto it = RandomGeneratorUtil::nextItem(upgrades, CRandomGenerator::getDefault());
  342. cb->changeStackType(StackLocation(this, slotID), VLC->creh->objects[*it]);
  343. }
  344. }
  345. }
  346. cb->startBattleI(h, this);
  347. }
  348. void CGCreature::flee( const CGHeroInstance * h ) const
  349. {
  350. BlockingDialog ynd(true,false);
  351. ynd.player = h->tempOwner;
  352. ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
  353. ynd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, subID);
  354. cb->showBlockingDialog(&ynd);
  355. }
  356. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  357. {
  358. if(result.winner == 0)
  359. {
  360. giveReward(hero);
  361. cb->removeObject(this, hero->getOwner());
  362. }
  363. else if(result.winner > 1) // draw
  364. {
  365. // guarded reward is lost forever on draw
  366. cb->removeObject(this, hero->getOwner());
  367. }
  368. else
  369. {
  370. //merge stacks into one
  371. TSlots::const_iterator i;
  372. CCreature * cre = VLC->creh->objects[formation.basicType];
  373. for(i = stacks.begin(); i != stacks.end(); i++)
  374. {
  375. if(cre->isMyUpgrade(i->second->type))
  376. {
  377. cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures
  378. }
  379. }
  380. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  381. if(!hasStackAtSlot(SlotID(0)))
  382. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  383. while(stacks.size() > 1) //hopefully that's enough
  384. {
  385. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  386. i = stacks.end();
  387. i--;
  388. SlotID slot = getSlotFor(i->second->type);
  389. if(slot == i->first) //no reason to move stack to its own slot
  390. break;
  391. else
  392. cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  393. }
  394. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  395. }
  396. }
  397. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  398. {
  399. auto action = takenAction(hero);
  400. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  401. joinDecision(hero, action, answer);
  402. else if(action != FIGHT)
  403. fleeDecision(hero, answer);
  404. else
  405. assert(0);
  406. }
  407. bool CGCreature::containsUpgradedStack() const
  408. {
  409. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  410. float a = 2992.911117f;
  411. float b = 14174.264968f;
  412. float c = 5325.181015f;
  413. float d = 32788.727920f;
  414. int val = static_cast<int>(std::floor(a * pos.x + b * pos.y + c * pos.z + d));
  415. return ((val % 32768) % 100) < 50;
  416. }
  417. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  418. {
  419. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  420. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  421. int split = 1;
  422. if (strengthRatio < 0.5f)
  423. split = 7;
  424. else if (strengthRatio < 0.67f)
  425. split = 6;
  426. else if (strengthRatio < 1)
  427. split = 5;
  428. else if (strengthRatio < 1.5f)
  429. split = 4;
  430. else if (strengthRatio < 2)
  431. split = 3;
  432. else
  433. split = 2;
  434. ui32 a = 1550811371u;
  435. ui32 b = 3359066809u;
  436. ui32 c = 1943276003u;
  437. ui32 d = 3174620878u;
  438. ui32 R1 = a * static_cast<ui32>(pos.x) + b * static_cast<ui32>(pos.y) + c * static_cast<ui32>(pos.z) + d;
  439. ui32 R2 = (R1 >> 16) & 0x7fff;
  440. int R4 = R2 % 100 + 1;
  441. if (R4 <= 20)
  442. split -= 1;
  443. else if (R4 >= 80)
  444. split += 1;
  445. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  446. vstd::amin(split, 7); //can't have more than 7 stacks
  447. return split;
  448. }
  449. void CGCreature::giveReward(const CGHeroInstance * h) const
  450. {
  451. InfoWindow iw;
  452. iw.player = h->tempOwner;
  453. if(!resources.empty())
  454. {
  455. cb->giveResources(h->tempOwner, resources);
  456. for(int i = 0; i < resources.size(); i++)
  457. {
  458. if(resources[i] > 0)
  459. iw.components.emplace_back(Component::EComponentType::RESOURCE, i, resources[i], 0);
  460. }
  461. }
  462. if(gainedArtifact != ArtifactID::NONE)
  463. {
  464. cb->giveHeroNewArtifact(h, VLC->arth->objects[gainedArtifact], ArtifactPosition::FIRST_AVAILABLE);
  465. iw.components.emplace_back(Component::EComponentType::ARTIFACT, gainedArtifact, 0, 0);
  466. }
  467. if(!iw.components.empty())
  468. {
  469. iw.type = EInfoWindowMode::AUTO;
  470. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 183); // % has found treasure
  471. iw.text.replaceRawString(h->getNameTranslated());
  472. cb->showInfoDialog(&iw);
  473. }
  474. }
  475. static const std::vector<std::string> CHARACTER_JSON =
  476. {
  477. "compliant", "friendly", "aggressive", "hostile", "savage"
  478. };
  479. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  480. {
  481. handler.serializeEnum("character", character, CHARACTER_JSON);
  482. if(handler.saving)
  483. {
  484. if(hasStackAtSlot(SlotID(0)))
  485. {
  486. si32 amount = getStack(SlotID(0)).count;
  487. handler.serializeInt("amount", amount, 0);
  488. }
  489. }
  490. else
  491. {
  492. si32 amount = 0;
  493. handler.serializeInt("amount", amount);
  494. auto * hlp = new CStackInstance();
  495. hlp->count = amount;
  496. //type will be set during initialization
  497. putStack(SlotID(0), hlp);
  498. }
  499. resources.serializeJson(handler, "rewardResources");
  500. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  501. handler.serializeBool("noGrowing", notGrowingTeam);
  502. handler.serializeBool("neverFlees", neverFlees);
  503. handler.serializeStruct("rewardMessage", message);
  504. }
  505. VCMI_LIB_NAMESPACE_END