CGCreature.cpp 16 KB

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